1 /*
2  * Hydrogen
3  * Copyright(c) 2002-2008 by Alex >Comix< Cominu [comix@users.sourceforge.net]
4  *
5  * http://www.hydrogen-music.org
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY, without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  */
22 #include "hydrogen/config.h"
23 
24 #ifdef WIN32
25 #    include "hydrogen/timehelper.h"
26 #else
27 #    include <unistd.h>
28 #    include <sys/time.h>
29 #endif
30 
31 #include <pthread.h>
32 #include <cassert>
33 #include <cstdio>
34 #include <deque>
35 #include <queue>
36 #include <iostream>
37 #include <ctime>
38 #include <cmath>
39 #include <algorithm>
40 
41 #include <QtCore/QMutex>
42 #include <QtCore/QMutexLocker>
43 
44 #include <hydrogen/event_queue.h>
45 #include <hydrogen/basics/adsr.h>
46 #include <hydrogen/basics/drumkit.h>
47 #include <hydrogen/basics/drumkit_component.h>
48 #include <hydrogen/h2_exception.h>
49 #include <hydrogen/audio_engine.h>
50 #include <hydrogen/basics/instrument.h>
51 #include <hydrogen/basics/instrument_component.h>
52 #include <hydrogen/basics/instrument_list.h>
53 #include <hydrogen/basics/instrument_layer.h>
54 #include <hydrogen/basics/playlist.h>
55 #include <hydrogen/basics/sample.h>
56 #include <hydrogen/basics/automation_path.h>
57 #include <hydrogen/hydrogen.h>
58 #include <hydrogen/basics/pattern.h>
59 #include <hydrogen/basics/pattern_list.h>
60 #include <hydrogen/basics/note.h>
61 #include <hydrogen/helpers/filesystem.h>
62 #include <hydrogen/fx/LadspaFX.h>
63 #include <hydrogen/fx/Effects.h>
64 
65 #include <hydrogen/Preferences.h>
66 #include <hydrogen/sampler/Sampler.h>
67 #include <hydrogen/midi_map.h>
68 #include <hydrogen/timeline.h>
69 
70 #ifdef H2CORE_HAVE_OSC
71 #include <hydrogen/nsm_client.h>
72 #include <hydrogen/osc_server.h>
73 #endif
74 
75 #include <hydrogen/IO/AudioOutput.h>
76 #include <hydrogen/IO/jack_audio_driver.h>
77 #include <hydrogen/IO/NullDriver.h>
78 #include <hydrogen/IO/MidiInput.h>
79 #include <hydrogen/IO/MidiOutput.h>
80 #include <hydrogen/IO/CoreMidiDriver.h>
81 #include <hydrogen/IO/TransportInfo.h>
82 #include <hydrogen/IO/OssDriver.h>
83 #include <hydrogen/IO/FakeDriver.h>
84 #include <hydrogen/IO/AlsaAudioDriver.h>
85 #include <hydrogen/IO/PortAudioDriver.h>
86 #include <hydrogen/IO/DiskWriterDriver.h>
87 #include <hydrogen/IO/AlsaMidiDriver.h>
88 #include <hydrogen/IO/JackMidiDriver.h>
89 #include <hydrogen/IO/PortMidiDriver.h>
90 #include <hydrogen/IO/CoreAudioDriver.h>
91 #include <hydrogen/IO/PulseAudioDriver.h>
92 
93 namespace H2Core
94 {
95 
96 // GLOBALS
97 
98 // info
99 float				m_fMasterPeak_L = 0.0f;		///< Master peak (left channel)
100 float				m_fMasterPeak_R = 0.0f;		///< Master peak (right channel)
101 float				m_fProcessTime = 0.0f;		///< time used in process function
102 float				m_fMaxProcessTime = 0.0f;	///< max ms usable in process with no xrun
103 //~ info
104 
105 /**
106  * Fallback speed in beats per minute.
107  *
108  * It is set by Hydrogen::setNewBpmJTM() and accessed via
109  * Hydrogen::getNewBpmJTM().
110  */
111 float				m_fNewBpmJTM = 120;
112 
113 /**
114  * Pointer to the current instance of the audio driver.
115  *
116  * Initialized with NULL inside audioEngine_init(). Inside
117  * audioEngine_startAudioDrivers() either the audio driver specified
118  * in Preferences::m_sAudioDriver and created via createDriver() or
119  * the NullDriver, in case the former failed, will be assigned.
120  */
121 AudioOutput *			m_pAudioDriver = nullptr;
122 /**
123  * Mutex for locking the pointer to the audio output buffer, allowing
124  * multiple readers.
125  *
126  * When locking this __and__ the AudioEngine, always lock the
127  * AudioEngine first using AudioEngine::lock() or
128  * AudioEngine::try_lock(). Always use a QMutexLocker to lock this
129  * mutex.
130  */
131 QMutex				mutex_OutputPointer;
132 /**
133  * MIDI input
134  *
135  * In audioEngine_startAudioDrivers() it is assigned the midi driver
136  * specified in Preferences::m_sMidiDriver.
137  */
138 MidiInput *			m_pMidiDriver = nullptr;
139 /**
140  * MIDI output
141  *
142  * In audioEngine_startAudioDrivers() it is assigned the midi driver
143  * specified in Preferences::m_sMidiDriver.
144  */
145 MidiOutput *			m_pMidiDriverOut = nullptr;
146 
147 // overload the > operator of Note objects for priority_queue
148 struct compare_pNotes {
operator ()H2Core::compare_pNotes149 	bool operator() (Note* pNote1, Note* pNote2) {
150 		return (pNote1->get_humanize_delay()
151 				+ pNote1->get_position() * m_pAudioDriver->m_transport.m_fTickSize)
152 			    >
153 			    (pNote2->get_humanize_delay()
154 			    + pNote2->get_position() * m_pAudioDriver->m_transport.m_fTickSize);
155 	}
156 };
157 
158 /// Song Note FIFO
159 std::priority_queue<Note*, std::deque<Note*>, compare_pNotes > m_songNoteQueue;
160 std::deque<Note*>		m_midiNoteQueue;	///< Midi Note FIFO
161 
162 /**
163  * Patterns to be played next in Song::PATTERN_MODE.
164  *
165  * In audioEngine_updateNoteQueue() whenever the end of the current
166  * pattern is reached the content of #m_pNextPatterns will be added to
167  * #m_pPlayingPatterns.
168  *
169  * Queried with Hydrogen::getNextPatterns(), set by
170  * Hydrogen::sequencer_setNextPattern() and
171  * Hydrogen::sequencer_setOnlyNextPattern(), initialized with an empty
172  * PatternList in audioEngine_init(), destroyed and set to NULL in
173  * audioEngine_destroy(), cleared in audioEngine_remove_Song(), and
174  * updated in audioEngine_updateNoteQueue(). Please note that ALL of
175  * these functions do access the variable directly!
176  */
177 PatternList*		m_pNextPatterns;
178 bool				m_bAppendNextPattern;		///< Add the next pattern to the list instead of replace.
179 bool				m_bDeleteNextPattern;		///< Delete the next pattern from the list.
180 /**
181  * PatternList containing all Patterns currently played back.
182  *
183  * Queried using Hydrogen::getCurrentPatternList(), set using
184  * Hydrogen::setCurrentPatternList(), initialized with an empty
185  * PatternList in audioEngine_init(), destroyed and set to NULL in
186  * audioEngine_destroy(), set to the first pattern list of the new
187  * song in audioEngine_setSong(), cleared in
188  * audioEngine_removeSong(), reset in Hydrogen::togglePlaysSelected()
189  * and processed in audioEngine_updateNoteQueue(). Please note that
190  * ALL of these functions do access the variable directly!
191  */
192 PatternList*			m_pPlayingPatterns;
193 /**
194  * Index of the current PatternList in the
195  * Song::__pattern_group_sequence.
196  *
197  * A value of -1 corresponds to "pattern list could not be found".
198  *
199  * Assigned using findPatternInTick() in
200  * audioEngine_updateNoteQueue(), queried using
201  * Hydrogen::getPatternPos() and set using Hydrogen::setPatternPos()
202  * if it AudioEngine is playing.
203  *
204  * It is initialized with -1 value in audioEngine_init(), and reset to
205  * the same value in audioEngine_start(), and
206  * Hydrogen::stopExportSong(). In Hydrogen::startExportSong() it will
207  * be set to 0. Please note that ALL of these functions do access the
208  * variable directly!
209  */
210 int				m_nSongPos; // TODO: rename it to something more
211 							// accurate, like m_nPatternListNumber
212 
213 /**
214  * Index of the pattern selected in the GUI or by a MIDI event.
215  *
216  * If Preferences::m_bPatternModePlaysSelected is set to true and the
217  * playback is in Song::PATTERN_MODE, the corresponding pattern will
218  * be assigned to #m_pPlayingPatterns in
219  * audioEngine_updateNoteQueue(). This way the user can specify to
220  * play back the pattern she is currently viewing/editing.
221  *
222  * Queried using Hydrogen::getSelectedPatternNumber() and set by
223  * Hydrogen::setSelectedPatternNumber().
224  *
225  * Initialized to 0 in audioEngine_init().
226  */
227 int				m_nSelectedPatternNumber;
228 /**
229  *
230  *
231  * Initialized to 0 in audioEngine_init().
232  */
233 int				m_nSelectedInstrumentNumber;
234 /**
235  * Pointer to the metronome.
236  *
237  * Initialized in audioEngine_init().
238  */
239 Instrument *			m_pMetronomeInstrument = nullptr;
240 
241 // Buffers used in the process function
242 unsigned			m_nBufferSize = 0;
243 /**
244  * Pointer to the audio buffer of the left stereo output returned by
245  * AudioOutput::getOut_L().
246  *
247  * Initialized to NULL in audioEngine_init(), assigned in
248  * audioEngine_startAudioDrivers(), reset in
249  * audioEngine_process_clearAudioBuffers(), and populated with the
250  * actual audio in audioEngine_process().
251  */
252 float *				m_pMainBuffer_L = nullptr;
253 /**
254  * Pointer to the audio buffer of the right stereo output returned by
255  * AudioOutput::getOut_R().
256  *
257  * Initialized to NULL in audioEngine_init(), assigned in
258  * audioEngine_startAudioDrivers(), reset in
259  * audioEngine_process_clearAudioBuffers(), and populated with the
260  * actual audio in audioEngine_process().
261  */
262 float *				m_pMainBuffer_R = nullptr;
263 /**
264  * Current state of the H2Core::AudioEngine.
265  *
266  * It is supposed to take five different states:
267  *
268  * - #STATE_UNINITIALIZED:	1      Not even the constructors have been called.
269  * - #STATE_INITIALIZED:	2      Not ready, but most pointers are now valid or NULL
270  * - #STATE_PREPARED:		3      Drivers are set up, but not ready to process audio.
271  * - #STATE_READY:		4      Ready to process audio
272  * - #STATE_PLAYING:		5      Currently playing a sequence.
273  *
274  * It gets initialized with #STATE_UNINITIALIZED.
275  */
276 int				m_audioEngineState = STATE_UNINITIALIZED;
277 
278 #if defined(H2CORE_HAVE_LADSPA) || _DOXYGEN_
279 float				m_fFXPeak_L[MAX_FX];
280 float				m_fFXPeak_R[MAX_FX];
281 #endif
282 
283 /**
284  * Beginning of the current pattern in ticks.
285  *
286  * It is set using finPatternInTick() and reset to -1 in
287  * audioEngine_start(), audioEngine_stop(),
288  * Hydrogen::startExportSong(), and
289  * Hydrogen::triggerRelocateDuringPlay() (if the playback it in
290  * Song::PATTERN_MODE).
291  */
292 int				m_nPatternStartTick = -1;
293 /**
294  * Ticks passed since the beginning of the current pattern.
295  *
296  * Queried using Hydrogen::getTickPosition().
297  *
298  * Initialized to 0 in audioEngine_init() and reset to 0 in
299  * Hydrogen::setPatternPos(), if the AudioEngine is not playing, in
300  * audioEngine_start(), Hydrogen::startExportSong() and
301  * Hydrogen::stopExportSong(), which marks the beginning of a Song.
302  */
303 unsigned int	m_nPatternTickPosition = 0;
304 
305 /** Set to the total number of ticks in a Song in findPatternInTick()
306     if Song::SONG_MODE is chosen and playback is at least in the
307     second loop.*/
308 int				m_nSongSizeInTicks = 0;
309 
310 /** Updated in audioEngine_updateNoteQueue().*/
311 struct timeval			m_currentTickTime;
312 
313 /**
314  * Variable keeping track of the transport position in realtime.
315  *
316  * Even if the audio engine is stopped, the variable will be
317  * incremented by #m_nBufferSize (as audioEngine_process() would do at
318  * the end of each cycle) to support realtime keyboard and MIDI event
319  * timing. It is set using Hydrogen::setRealtimeFrames(), accessed via
320  * Hydrogen::getRealtimeFrames(), and updated in
321  * audioEngine_process_transport() using the current transport
322  * position TransportInfo::m_nFrames.
323  */
324 unsigned long			m_nRealtimeFrames = 0;
325 unsigned int			m_naddrealtimenotetickposition = 0;
326 
327 // PROTOTYPES
328 /**
329  * Initialization of the H2Core::AudioEngine called in Hydrogen::Hydrogen().
330  *
331  * -# It creates two new instances of the H2Core::PatternList and stores them
332       in #m_pPlayingPatterns and #m_pNextPatterns.
333  * -# It sets #m_nSongPos = -1.
334  * -# It sets #m_nSelectedPatternNumber, #m_nSelectedInstrumentNumber,
335       and #m_nPatternTickPosition to 0.
336  * -# It sets #m_pMetronomeInstrument, #m_pAudioDriver,
337       #m_pMainBuffer_L, #m_pMainBuffer_R to NULL.
338  * -# It uses the current time to a random seed via std::srand(). This
339       way the states of the pseudo-random number generator are not
340       cross-correlated between different runs of Hydrogen.
341  * -# It initializes the metronome with the sound stored in
342       H2Core::Filesystem::click_file_path() by creating a new
343       Instrument with #METRONOME_INSTR_ID as first argument.
344  * -# It sets the H2Core::AudioEngine state #m_audioEngineState to
345       #STATE_INITIALIZED.
346  * -# It calls H2Core::Effects::create_instance() (if the
347       #H2CORE_HAVE_LADSPA is set),
348       H2Core::AudioEngine::create_instance(), and
349       H2Core::Playlist::create_instance().
350  * -# Finally, it pushes the H2Core::EVENT_STATE, #STATE_INITIALIZED
351       on the H2Core::EventQueue using
352       H2Core::EventQueue::push_event().
353  *
354  * If the current state of the H2Core::AudioEngine #m_audioEngineState is not
355  * ::STATE_UNINITIALIZED, it will thrown an error and
356  * H2Core::AudioEngine::unlock() it.
357  */
358 void				audioEngine_init();
359 void				audioEngine_destroy();
360 /**
361  * If the audio engine is in state #m_audioEngineState #STATE_READY,
362  * this function will
363  * - sets #m_fMasterPeak_L and #m_fMasterPeak_R to 0.0f
364  * - sets TransportInfo::m_nFrames to @a nTotalFrames
365  * - sets m_nSongPos and m_nPatternStartTick to -1
366  * - m_nPatternTickPosition to 0
367  * - calls updateTickSize()
368  * - sets #m_audioEngineState to #STATE_PLAYING
369  * - pushes the #EVENT_STATE #STATE_PLAYING using EventQueue::push_event()
370  *
371  * \param bLockEngine Whether or not to lock the audio engine before
372  *   performing any actions. The audio engine __must__ be locked! This
373  *   option should only be used, if the process calling this function
374  *   did already locked it.
375  * \param nTotalFrames New value of the transport position.
376  * \return 0 regardless what happens inside the function.
377  */
378 int				audioEngine_start( bool bLockEngine = false, unsigned nTotalFrames = 0 );
379 /**
380  * If the audio engine is in state #m_audioEngineState #STATE_PLAYING,
381  * this function will
382  * - sets #m_fMasterPeak_L and #m_fMasterPeak_R to 0.0f
383  * - sets #m_audioEngineState to #STATE_READY
384  * - sets #m_nPatternStartTick to -1
385  * - deletes all copied Note in song notes queue #m_songNoteQueue and
386  *   MIDI notes queue #m_midiNoteQueue
387  * - calls the _clear()_ member of #m_midiNoteQueue
388  *
389  * \param bLockEngine Whether or not to lock the audio engine before
390  *   performing any actions. The audio engine __must__ be locked! This
391  *   option should only be used, if the process calling this function
392  *   did already locked it.
393  */
394 void				audioEngine_stop( bool bLockEngine = false );
395 /**
396  * Updates the global objects of the audioEngine according to new #Song.
397  *
398  * Calls audioEngine_setupLadspaFX() on
399  * m_pAudioDriver->getBufferSize(),
400  * audioEngine_process_checkBPMChanged(),
401  * audioEngine_renameJackPorts(), adds its first pattern to
402  * #m_pPlayingPatterns, relocates the audio driver to the beginning of
403  * the #Song, and updates the BPM.
404  *
405  * \param pNewSong #Song to load.
406  */
407 void				audioEngine_setSong(Song *pNewSong );
408 /**
409  * Does the necessary cleanup of the global objects in the audioEngine.
410  *
411  * Class the clear() member of #m_pPlayingPatterns and
412  * #m_pNextPatterns as well as audioEngine_clearNoteQueue();
413  */
414 void				audioEngine_removeSong();
415 static void			audioEngine_noteOn( Note *note );
416 
417 /**
418  * Main audio processing function called by the audio drivers whenever
419  * there is work to do.
420  *
421  * In short, it resets the audio buffers, checks the current transport
422  * position and configuration, updates the queue of notes, which are
423  * about to be played, plays those notes and writes their output to
424  * the audio buffers, and, finally, increment the transport position
425  * in order to move forward in time.
426  *
427  * In detail the function
428  * - calls audioEngine_process_clearAudioBuffers() to reset all audio
429  * buffers with zeros.
430  * - calls audioEngine_process_transport() to verify the current
431  * TransportInfo stored in AudioOutput::m_transport. If e.g. the
432  * JACK server is used, an external JACK client might have changed the
433  * speed of the transport (as JACK timebase master) or the transport
434  * position. In such cases, Hydrogen has to sync its internal transport
435  * state AudioOutput::m_transport to reflect these changes. Else our
436  * playback would be off.
437  * - calls audioEngine_process_checkBPMChanged() to check whether the
438  * tick size, the number of frames per bar (size of a pattern), has
439  * changed (see TransportInfo::m_nFrames in case you are unfamiliar
440  * with the term _frames_). This is necessary because the transport
441  * position is often given in ticks within Hydrogen and changing the
442  * speed of the Song, e.g. via Hydrogen::setBPM(), would thus result
443  * in a(n unintended) relocation of the transport location.
444  * - calls audioEngine_updateNoteQueue() and
445  * audioEngine_process_playNotes(), two functions which handle the
446  * selection and playback of notes and will documented at a later
447  * point in time
448  * - If audioEngine_updateNoteQueue() returns with 2, the
449  * EVENT_PATTERN_CHANGED event will be pushed to the EventQueue.
450  * - writes the audio output of the Sampler, Synth, and the LadspaFX
451  * (if #H2CORE_HAVE_LADSPA is defined) to #m_pMainBuffer_L and
452  * #m_pMainBuffer_R and sets we peak values for #m_fFXPeak_L,
453  * #m_fFXPeak_R, #m_fMasterPeak_L, and #m_fMasterPeak_R.
454  * - finally increments the transport position
455  * TransportInfo::m_nFrames with the buffersize @a nframes. So, if
456  * this function is called during the next cycle, the transport is
457  * already in the correct position.
458  *
459  * If the H2Core::m_audioEngineState is neither in #STATE_READY nor
460  * #STATE_PLAYING or the locking of the AudioEngine failed, the
461  * function will return 0 without performing any actions.
462  *
463  * \param nframes Buffersize. If it doesn't match #m_nBufferSize, the
464    latter will be set to @a nframes.
465  * \param arg Unused.
466  * \return
467  * - __2__ : Failed to aquire the audio engine lock, no processing took place.
468  * - __1__ : kill the audio driver thread. This will be used if either
469  * the DiskWriterDriver or FakeDriver are used and the end of the Song
470  * is reached (audioEngine_updateNoteQueue() returned -1 ).
471  * - __0__ : else
472  */
473 int				audioEngine_process( uint32_t nframes, void *arg );
474 inline void			audioEngine_clearNoteQueue();
475 /**
476  * Update the tick size based on the current tempo without affecting
477  * the current transport position.
478  *
479  * To access a change in the tick size, the value stored in
480  * TransportInfo::m_fTickSize will be compared to the one calculated
481  * from the AudioOutput::getSampleRate(), Song::__bpm, and
482  * Song::__resolution. Thus, if any of those quantities did change,
483  * the transport position will be recalculated.
484  *
485  * The new transport position gets calculated by
486  * \code{.cpp}
487  * ceil( m_pAudioDriver->m_transport.m_nFrames/
488  *       m_pAudioDriver->m_transport.m_fTickSize ) *
489  * m_pAudioDriver->getSampleRate() * 60.0 / Song::__bpm / Song::__resolution
490  * \endcode
491  *
492  * If the JackAudioDriver is used and the audio engine is playing, a
493  * potential mismatch in the transport position is determined by
494  * JackAudioDriver::calculateFrameOffset() and covered by
495  * JackAudioDriver::updateTransportInfo() in the next cycle.
496  *
497  * Finally, EventQueue::push_event() is called with
498  * #EVENT_RECALCULATERUBBERBAND and -1 as arguments.
499  *
500  * Called in audioEngine_process() and audioEngine_setSong(). The
501  * function will only perform actions if #m_audioEngineState is in
502  * either #STATE_READY or #STATE_PLAYING.
503  */
504 inline void			audioEngine_process_checkBPMChanged(Song *pSong);
505 inline void			audioEngine_process_playNotes( unsigned long nframes );
506 /**
507  * Updating the TransportInfo of the audio driver.
508  *
509  * Firstly, it calls AudioOutput::updateTransportInfo() and then
510  * updates the state of the audio engine #m_audioEngineState depending
511  * on the status of the audio driver.  E.g. if the JACK transport was
512  * started by another client, the audio engine has to be started as
513  * well. If TransportInfo::m_status is TransportInfo::ROLLING,
514  * audioEngine_start() is called with
515  * TransportInfo::m_nFrames as argument if the engine is in
516  * #STATE_READY. If #m_audioEngineState is then still not in
517  * #STATE_PLAYING, the function will return. Otherwise, the current
518  * speed is getting updated by calling Hydrogen::setBPM using
519  * TransportInfo::m_fBPM and #m_nRealtimeFrames is set to
520  * TransportInfo::m_nFrames.
521  *
522  * If the status is TransportInfo::STOPPED but the engine is still
523  * running, audioEngine_stop() will be called. In any case,
524  * #m_nRealtimeFrames will be incremented by #m_nBufferSize to support
525  * realtime keyboard and MIDI event timing.
526  *
527  * If the H2Core::m_audioEngineState is neither in #STATE_READY nor
528  * #STATE_PLAYING the function will immediately return.
529  */
530 inline void			audioEngine_process_transport();
531 
532 inline unsigned		audioEngine_renderNote( Note* pNote, const unsigned& nBufferSize );
533 // TODO: Add documentation of doErase, inPunchArea, and
534 // m_addMidiNoteVector
535 /**
536  * Takes all notes from the current patterns, from the MIDI queue
537  * #m_midiNoteQueue, and those triggered by the metronome and pushes
538  * them onto #m_songNoteQueue for playback.
539  *
540  * Apart from the MIDI queue, the extraction of all notes will be
541  * based on their position measured in ticks. Since Hydrogen does
542  * support humanization, which also involves triggering a Note
543  * earlier or later than its actual position, the loop over all ticks
544  * won't be done starting from the current position but at some
545  * position in the future. This value, also called @e lookahead, is
546  * set to the sum of the maximum offsets introduced by both the random
547  * humanization (2000 frames) and the deterministic lead-lag offset (5
548  * times TransportInfo::m_nFrames) plus 1 (note that it's not given in
549  * ticks but in frames!). Hydrogen thus loops over @a nFrames frames
550  * starting at the current position + the lookahead (or at 0 when at
551  * the beginning of the Song).
552  *
553  * Within this loop all MIDI notes in #m_midiNoteQueue with a
554  * Note::__position smaller or equal the current tick will be popped
555  * and added to #m_songNoteQueue and the #EVENT_METRONOME Event is
556  * pushed to the EventQueue at a periodic rate. If in addition
557  * Preferences::m_bUseMetronome is set to true,
558  * #m_pMetronomeInstrument will be used to push a 'click' to the
559  * #m_songNoteQueue too. All patterns enclosing the current tick will
560  * be added to #m_pPlayingPatterns and all their containing notes,
561  * which position enclose the current tick too, will be added to the
562  * #m_songNoteQueue. If the Song is in Song::PATTERN_MODE, the
563  * patterns used are not chosen by the actual position but by
564  * #m_nSelectedPatternNumber and #m_pNextPatterns.
565  *
566  * All notes obtained by the current patterns (and only those) are
567  * also subject to humanization in the onset position of the created
568  * Note. For now Hydrogen does support three options of altering
569  * these:
570  * - @b Swing - A deterministic offset determined by Song::__swing_factor
571  * will be added for some notes in a periodic way.
572  * - @b Humanize - A random offset drawn from Gaussian white noise
573  * with a variance proportional to Song::__humanize_time_value will be
574  * added to every Note.
575  * - @b Lead/Lag - A deterministic offset determined by
576  * Note::__lead_lag will be added for every note.
577  *
578  * If the AudioEngine it not in #STATE_PLAYING, the loop jumps right
579  * to the next tick.
580  *
581  * \return
582  * - -1 if in Song::SONG_MODE and no patterns left.
583  * - 2 if the current pattern changed with respect to the last
584  * cycle.
585  */
586 inline int			audioEngine_updateNoteQueue( unsigned nFrames );
587 inline void			audioEngine_prepNoteQueue();
588 
589 /**
590  * Find a PatternList corresponding to the supplied tick position @a
591  * nTick.
592  *
593  * Adds up the lengths of all pattern columns until @a nTick lies in
594  * between the bounds of a Pattern.
595  *
596  * \param nTick Position in ticks.
597  * \param bLoopMode Whether looping is enabled in the Song, see
598  *   Song::is_loop_enabled(). If true, @a nTick is allowed to be
599  *   larger than the total length of the Song.
600  * \param pPatternStartTick Pointer to an integer the beginning of the
601  *   found pattern list will be stored in (in ticks).
602  * \return
603  *   - -1 : pattern list couldn't be found.
604  *   - >=0 : PatternList index in Song::__pattern_group_sequence.
605  */
606 inline int			findPatternInTick( int nTick, bool bLoopMode, int* pPatternStartTick );
607 
608 void				audioEngine_seek( long long nFrames, bool bLoopMode = false );
609 
610 void				audioEngine_restartAudioDrivers();
611 /**
612  * Creation and initialization of all audio and MIDI drivers called in
613  * Hydrogen::Hydrogen().
614  *
615  * Which audio driver to use is specified in
616  * Preferences::m_sAudioDriver. If "Auto" is selected, it will try to
617  * initialize drivers using createDriver() in the following order:
618  * - Windows:  "PortAudio", "Alsa", "CoreAudio", "Jack", "Oss",
619  *   and "PulseAudio"
620  * - all other systems: "Jack", "Alsa", "CoreAudio", "PortAudio",
621  *   "Oss", and "PulseAudio".
622  * If all of them return NULL, #m_pAudioDriver will be initialized
623  * with the NullDriver instead. If a specific choice is contained in
624  * Preferences::m_sAudioDriver and createDriver() returns NULL, the
625  * NullDriver will be initialized too.
626  *
627  * It probes Preferences::m_sMidiDriver to create a midi driver using
628  * either AlsaMidiDriver::AlsaMidiDriver(),
629  * PortMidiDriver::PortMidiDriver(), CoreMidiDriver::CoreMidiDriver(),
630  * or JackMidiDriver::JackMidiDriver(). Afterwards, it sets
631  * #m_pMidiDriverOut and #m_pMidiDriver to the freshly created midi
632  * driver and calls their open() and setActive( true ) functions.
633  *
634  * If a Song is already present, the state of the AudioEngine
635  * #m_audioEngineState will be set to #STATE_READY, the bpm of the
636  * #m_pAudioDriver will be set to the tempo of the Song Song::__bpm
637  * using AudioOutput::setBpm(), and #STATE_READY is pushed on the
638  * EventQueue. If no Song is present, the state will be
639  * #STATE_PREPARED and no bpm will be set.
640  *
641  * All the actions mentioned so far will be performed after locking
642  * both the AudioEngine using AudioEngine::lock() and the mutex of the
643  * audio output buffer #mutex_OutputPointer. When they are completed
644  * both mutex are unlocked and the audio driver is connected via
645  * AudioOutput::connect(). If this is not successful, the audio driver
646  * will be overwritten with the NullDriver and this one is connected
647  * instead.
648  *
649  * Finally, audioEngine_renameJackPorts() (if #H2CORE_HAVE_JACK is set)
650  * and audioEngine_setupLadspaFX() are called.
651  *
652  * The state of the AudioEngine #m_audioEngineState must not be in
653  * #STATE_INITIALIZED or the function will just unlock both mutex and
654  * returns.
655  */
656 void				audioEngine_startAudioDrivers();
657 /**
658  * Stops all audio and MIDI drivers.
659  *
660  * Uses audioEngine_stop() if the AudioEngine is still in state
661  * #m_audioEngineState #STATE_PLAYING, sets its state to
662  * #STATE_INITIALIZED, locks the AudioEngine using
663  * AudioEngine::lock(), deletes #m_pMidiDriver and #m_pAudioDriver and
664  * reinitializes them to NULL.
665  *
666  * If #m_audioEngineState is neither in #STATE_PREPARED or
667  * #STATE_READY, the function returns before deleting anything.
668  */
669 void				audioEngine_stopAudioDrivers();
670 
671 /** Gets the current time.
672  * \return Current time obtained by gettimeofday()*/
currentTime2()673 inline timeval currentTime2()
674 {
675 	struct timeval now;
676 	gettimeofday( &now, nullptr );
677 	return now;
678 }
679 
randomValue(int max)680 inline int randomValue( int max )
681 {
682 	return rand() % max;
683 }
684 
getGaussian(float z)685 inline float getGaussian( float z )
686 {
687 	// gaussian distribution -- dimss
688 	float x1, x2, w;
689 	do {
690 		x1 = 2.0 * ( ( ( float ) rand() ) / RAND_MAX ) - 1.0;
691 		x2 = 2.0 * ( ( ( float ) rand() ) / RAND_MAX ) - 1.0;
692 		w = x1 * x1 + x2 * x2;
693 	} while ( w >= 1.0 );
694 
695 	w = sqrtf( ( -2.0 * logf( w ) ) / w );
696 	return x1 * w * z + 0.0; // tunable
697 }
698 
audioEngine_raiseError(unsigned nErrorCode)699 void audioEngine_raiseError( unsigned nErrorCode )
700 {
701 	EventQueue::get_instance()->push_event( EVENT_ERROR, nErrorCode );
702 }
703 /** Function calculating the tick size by
704  * \code{.cpp}
705  * m_pAudioDriver->getSampleRate() * 60.0 / Song::__bpm / Song::__resolution
706  * \endcode
707  * and storing it in TransportInfo::m_fTickSize
708  */
updateTickSize()709 void updateTickSize()
710 {
711 	Hydrogen* pHydrogen = Hydrogen::get_instance();
712 	Song* pSong = pHydrogen->getSong();
713 
714 	float sampleRate = ( float ) m_pAudioDriver->getSampleRate();
715 	m_pAudioDriver->m_transport.m_fTickSize =
716 		( sampleRate * 60.0 /  pSong->__bpm / pSong->__resolution );
717 }
718 
audioEngine_init()719 void audioEngine_init()
720 {
721 	___INFOLOG( "*** Hydrogen audio engine init ***" );
722 
723 	// check current state
724 	if ( m_audioEngineState != STATE_UNINITIALIZED ) {
725 		___ERRORLOG( "Error the audio engine is not in UNINITIALIZED state" );
726 		AudioEngine::get_instance()->unlock();
727 		return;
728 	}
729 
730 	m_pPlayingPatterns = new PatternList();
731 	m_pNextPatterns = new PatternList();
732 	m_nSongPos = -1;
733 	m_nSelectedPatternNumber = 0;
734 	m_nSelectedInstrumentNumber = 0;
735 	m_nPatternTickPosition = 0;
736 	m_pMetronomeInstrument = nullptr;
737 	m_pAudioDriver = nullptr;
738 
739 	m_pMainBuffer_L = nullptr;
740 	m_pMainBuffer_R = nullptr;
741 
742 	srand( time( nullptr ) );
743 
744 	// Create metronome instrument
745 	// Get the path to the file of the metronome sound.
746 	QString sMetronomeFilename = Filesystem::click_file_path();
747 	m_pMetronomeInstrument =
748 			new Instrument( METRONOME_INSTR_ID, "metronome" );
749 
750 	InstrumentLayer* pLayer =
751 		new InstrumentLayer( Sample::load( sMetronomeFilename ) );
752 	InstrumentComponent* pCompo = new InstrumentComponent( 0 );
753 	pCompo->set_layer(pLayer, 0);
754 	m_pMetronomeInstrument->get_components()->push_back( pCompo );
755 	m_pMetronomeInstrument->set_is_metronome_instrument(true);
756 
757 	// Change the current audio engine state
758 	m_audioEngineState = STATE_INITIALIZED;
759 
760 #ifdef H2CORE_HAVE_LADSPA
761 	Effects::create_instance();
762 #endif
763 	AudioEngine::create_instance();
764 	Playlist::create_instance();
765 
766 	EventQueue::get_instance()->push_event( EVENT_STATE, STATE_INITIALIZED );
767 
768 }
769 
audioEngine_destroy()770 void audioEngine_destroy()
771 {
772 	// check current state
773 	if ( m_audioEngineState != STATE_INITIALIZED ) {
774 		___ERRORLOG( "Error the audio engine is not in INITIALIZED state" );
775 		return;
776 	}
777 	AudioEngine::get_instance()->get_sampler()->stop_playing_notes();
778 
779 	AudioEngine::get_instance()->lock( RIGHT_HERE );
780 	___INFOLOG( "*** Hydrogen audio engine shutdown ***" );
781 
782 	// delete all copied notes in the song notes queue
783 	while ( !m_songNoteQueue.empty() ) {
784 		m_songNoteQueue.top()->get_instrument()->dequeue();
785 		delete m_songNoteQueue.top();
786 		m_songNoteQueue.pop();
787 	}
788 	// delete all copied notes in the midi notes queue
789 	for ( unsigned i = 0; i < m_midiNoteQueue.size(); ++i ) {
790 		delete m_midiNoteQueue[i];
791 	}
792 	m_midiNoteQueue.clear();
793 
794 	// change the current audio engine state
795 	m_audioEngineState = STATE_UNINITIALIZED;
796 
797 	EventQueue::get_instance()->push_event( EVENT_STATE, STATE_UNINITIALIZED );
798 
799 	delete m_pPlayingPatterns;
800 	m_pPlayingPatterns = nullptr;
801 
802 	delete m_pNextPatterns;
803 	m_pNextPatterns = nullptr;
804 
805 	delete m_pMetronomeInstrument;
806 	m_pMetronomeInstrument = nullptr;
807 
808 	AudioEngine::get_instance()->unlock();
809 }
810 
audioEngine_start(bool bLockEngine,unsigned nTotalFrames)811 int audioEngine_start( bool bLockEngine, unsigned nTotalFrames )
812 {
813 	if ( bLockEngine ) {
814 		AudioEngine::get_instance()->lock( RIGHT_HERE );
815 	}
816 
817 	___INFOLOG( "[audioEngine_start]" );
818 
819 	// check current state
820 	if ( m_audioEngineState != STATE_READY ) {
821 		___ERRORLOG( "Error the audio engine is not in READY state" );
822 		if ( bLockEngine ) {
823 			AudioEngine::get_instance()->unlock();
824 		}
825 		return 0;	// FIXME!!
826 	}
827 
828 	m_fMasterPeak_L = 0.0f;
829 	m_fMasterPeak_R = 0.0f;
830 	// Reset the current transport position.
831 	m_pAudioDriver->m_transport.m_nFrames = nTotalFrames;
832 	m_nSongPos = -1;
833 	m_nPatternStartTick = -1;
834 	m_nPatternTickPosition = 0;
835 
836 	// prepare the tick size for this song
837 	updateTickSize();
838 
839 	// change the current audio engine state
840 	m_audioEngineState = STATE_PLAYING;
841 	EventQueue::get_instance()->push_event( EVENT_STATE, STATE_PLAYING );
842 
843 	if ( bLockEngine ) {
844 		AudioEngine::get_instance()->unlock();
845 	}
846 	return 0;
847 }
848 
audioEngine_stop(bool bLockEngine)849 void audioEngine_stop( bool bLockEngine )
850 {
851 	if ( bLockEngine ) {
852 		AudioEngine::get_instance()->lock( RIGHT_HERE );
853 	}
854 	___INFOLOG( "[audioEngine_stop]" );
855 
856 	// check current state
857 	if ( m_audioEngineState != STATE_PLAYING ) {
858 		___ERRORLOG( "Error the audio engine is not in PLAYING state" );
859 		if ( bLockEngine ) {
860 			AudioEngine::get_instance()->unlock();
861 		}
862 		return;
863 	}
864 
865 	// change the current audio engine state
866 	m_audioEngineState = STATE_READY;
867 	EventQueue::get_instance()->push_event( EVENT_STATE, STATE_READY );
868 
869 	m_fMasterPeak_L = 0.0f;
870 	m_fMasterPeak_R = 0.0f;
871 	//	m_nPatternTickPosition = 0;
872 	m_nPatternStartTick = -1;
873 
874 	// delete all copied notes in the song notes queue
875 	while(!m_songNoteQueue.empty()){
876 		m_songNoteQueue.top()->get_instrument()->dequeue();
877 		delete m_songNoteQueue.top();
878 		m_songNoteQueue.pop();
879 	}
880 
881 	// delete all copied notes in the midi notes queue
882 	for ( unsigned i = 0; i < m_midiNoteQueue.size(); ++i ) {
883 		delete m_midiNoteQueue[i];
884 	}
885 	m_midiNoteQueue.clear();
886 
887 	if ( bLockEngine ) {
888 		AudioEngine::get_instance()->unlock();
889 	}
890 }
891 
audioEngine_process_checkBPMChanged(Song * pSong)892 inline void audioEngine_process_checkBPMChanged(Song* pSong)
893 {
894 	if ( m_audioEngineState != STATE_READY
895 		 && m_audioEngineState != STATE_PLAYING ) {
896 		return;
897 	}
898 
899 	long long oldFrame;
900 #ifdef H2CORE_HAVE_JACK
901 	if ( Hydrogen::get_instance()->haveJackTransport() &&
902 		 m_audioEngineState != STATE_PLAYING ) {
903 		oldFrame = static_cast< JackAudioDriver* >( m_pAudioDriver )->m_currentPos;
904 
905 	} else {
906 		oldFrame = m_pAudioDriver->m_transport.m_nFrames;
907 	}
908 #else
909 	oldFrame = m_pAudioDriver->m_transport.m_nFrames;
910 #endif
911 	float fOldTickSize = m_pAudioDriver->m_transport.m_fTickSize;
912 	float fNewTickSize = AudioEngine::compute_tick_size( m_pAudioDriver->getSampleRate(), pSong->__bpm, pSong->__resolution );
913 
914 	// Nothing changed - avoid recomputing
915 	if ( fNewTickSize == fOldTickSize ) {
916 		return;
917 	}
918 	m_pAudioDriver->m_transport.m_fTickSize = fNewTickSize;
919 
920 	if ( fNewTickSize == 0 || fOldTickSize == 0 ) {
921 		return;
922 	}
923 
924 	float fTickNumber = (float)oldFrame / fOldTickSize;
925 
926 	// update frame position in transport class
927 	m_pAudioDriver->m_transport.m_nFrames = ceil(fTickNumber) * fNewTickSize;
928 
929 	___WARNINGLOG( QString( "Tempo change: Recomputing ticksize and frame position. Old TS: %1, new TS: %2, new pos: %3" )
930 		.arg( fOldTickSize ).arg( fNewTickSize )
931 		.arg( m_pAudioDriver->m_transport.m_nFrames ) );
932 
933 #ifdef H2CORE_HAVE_JACK
934 	if ( Hydrogen::get_instance()->haveJackTransport() ) {
935 		static_cast< JackAudioDriver* >( m_pAudioDriver )->calculateFrameOffset(oldFrame);
936 	}
937 #endif
938 	EventQueue::get_instance()->push_event( EVENT_RECALCULATERUBBERBAND, -1);
939 }
940 
audioEngine_process_playNotes(unsigned long nframes)941 inline void audioEngine_process_playNotes( unsigned long nframes )
942 {
943 	Hydrogen* pHydrogen = Hydrogen::get_instance();
944 	Song* pSong = pHydrogen->getSong();
945 
946 	unsigned int framepos;
947 
948 	if (  m_audioEngineState == STATE_PLAYING ) {
949 		framepos = m_pAudioDriver->m_transport.m_nFrames;
950 	} else {
951 		// use this to support realtime events when not playing
952 		framepos = pHydrogen->getRealtimeFrames();
953 	}
954 
955 	AutomationPath *vp = pSong->get_velocity_automation_path();
956 
957 
958 	// reading from m_songNoteQueue
959 	while ( !m_songNoteQueue.empty() ) {
960 		Note *pNote = m_songNoteQueue.top();
961 
962 		float velocity_adjustment = 1.0f;
963 		if ( pSong->get_mode() == Song::SONG_MODE ) {
964 			float fPos = m_nSongPos + (pNote->get_position()%192) / 192.f;
965 			velocity_adjustment = vp->get_value(fPos);
966 		}
967 
968 		// verifico se la nota rientra in questo ciclo
969 		unsigned int noteStartInFrames =
970 				(int)( pNote->get_position() * m_pAudioDriver->m_transport.m_fTickSize );
971 
972 		// if there is a negative Humanize delay, take into account so
973 		// we don't miss the time slice.  ignore positive delay, or we
974 		// might end the queue processing prematurely based on NoteQueue
975 		// placement.  the sampler handles positive delay.
976 		if (pNote->get_humanize_delay() < 0) {
977 			noteStartInFrames += pNote->get_humanize_delay();
978 		}
979 
980 		// m_nTotalFrames <= NotePos < m_nTotalFrames + bufferSize
981 		bool isNoteStart = ( ( noteStartInFrames >= framepos )
982 							 && ( noteStartInFrames < ( framepos + nframes ) ) );
983 		bool isOldNote = noteStartInFrames < framepos;
984 
985 		if ( isNoteStart || isOldNote ) {
986 			// Humanize - Velocity parameter
987 			pNote->set_velocity( pNote->get_velocity() * velocity_adjustment );
988 
989 			float rnd = (float)rand()/(float)RAND_MAX;
990 			if (pNote->get_probability() < rnd) {
991 				m_songNoteQueue.pop();
992 				pNote->get_instrument()->dequeue();
993 				continue;
994 			}
995 
996 			if ( pSong->get_humanize_velocity_value() != 0 ) {
997 				float random = pSong->get_humanize_velocity_value() * getGaussian( 0.2 );
998 				pNote->set_velocity(
999 							pNote->get_velocity()
1000 							+ ( random
1001 								- ( pSong->get_humanize_velocity_value() / 2.0 ) )
1002 							);
1003 				if ( pNote->get_velocity() > 1.0 ) {
1004 					pNote->set_velocity( 1.0 );
1005 				} else if ( pNote->get_velocity() < 0.0 ) {
1006 					pNote->set_velocity( 0.0 );
1007 				}
1008 			}
1009 
1010 			// Random Pitch ;)
1011 			const float fMaxPitchDeviation = 2.0;
1012 			pNote->set_pitch( pNote->get_pitch()
1013 							  + ( fMaxPitchDeviation * getGaussian( 0.2 )
1014 								  - fMaxPitchDeviation / 2.0 )
1015 							  * pNote->get_instrument()->get_random_pitch_factor() );
1016 
1017 
1018 			/*
1019 			 * Check if the current instrument has the property "Stop-Note" set.
1020 			 * If yes, a NoteOff note is generated automatically after each note.
1021 			 */
1022 			Instrument * noteInstrument = pNote->get_instrument();
1023 			if ( noteInstrument->is_stop_notes() ){
1024 				Note *pOffNote = new Note( noteInstrument,
1025 										   0.0,
1026 										   0.0,
1027 										   0.0,
1028 										   0.0,
1029 										   -1,
1030 										   0 );
1031 				pOffNote->set_note_off( true );
1032 				AudioEngine::get_instance()->get_sampler()->note_on( pOffNote );
1033 				delete pOffNote;
1034 			}
1035 
1036 			AudioEngine::get_instance()->get_sampler()->note_on( pNote );
1037 			m_songNoteQueue.pop(); // rimuovo la nota dalla lista di note
1038 			pNote->get_instrument()->dequeue();
1039 			// raise noteOn event
1040 			int nInstrument = pSong->get_instrument_list()->index( pNote->get_instrument() );
1041 			if( pNote->get_note_off() ){
1042 				delete pNote;
1043 			}
1044 
1045 			EventQueue::get_instance()->push_event( EVENT_NOTEON, nInstrument );
1046 			continue;
1047 		} else {
1048 			// this note will not be played
1049 			break;
1050 		}
1051 	}
1052 }
1053 
1054 
audioEngine_seek(long long nFrames,bool bLoopMode)1055 void audioEngine_seek( long long nFrames, bool bLoopMode )
1056 {
1057 	Hydrogen* pHydrogen = Hydrogen::get_instance();
1058 	Song* pSong = pHydrogen->getSong();
1059 
1060 	if ( m_pAudioDriver->m_transport.m_nFrames == nFrames ) {
1061 		return;
1062 	}
1063 
1064 	if ( nFrames < 0 ) {
1065 		___ERRORLOG( "nFrames < 0" );
1066 	}
1067 
1068 	char tmp[200];
1069 	sprintf( tmp, "seek in %lld (old pos = %d)",
1070 			 nFrames,
1071 			 ( int )m_pAudioDriver->m_transport.m_nFrames );
1072 	___INFOLOG( tmp );
1073 
1074 	m_pAudioDriver->m_transport.m_nFrames = nFrames;
1075 
1076 	int tickNumber_start = ( unsigned )(
1077 				m_pAudioDriver->m_transport.m_nFrames
1078 				/ m_pAudioDriver->m_transport.m_fTickSize );
1079 	//	sprintf(tmp, "[audioEngine_seek()] tickNumber_start = %d", tickNumber_start);
1080 	//	__instance->infoLog(tmp);
1081 
1082 	bool loop = pSong->is_loop_enabled();
1083 
1084 	if ( bLoopMode ) {
1085 		loop = true;
1086 	}
1087 
1088 	m_nSongPos = findPatternInTick( tickNumber_start, loop, &m_nPatternStartTick );
1089 	//	sprintf(tmp, "[audioEngine_seek()] m_nSongPos = %d", m_nSongPos);
1090 	//	__instance->infoLog(tmp);
1091 
1092 	audioEngine_clearNoteQueue();
1093 }
1094 
audioEngine_process_transport()1095 inline void audioEngine_process_transport()
1096 {
1097 	if ( m_audioEngineState != STATE_READY
1098 	  && m_audioEngineState != STATE_PLAYING
1099 	) return;
1100 
1101 	// Considering JackAudioDriver:
1102 	// Compares the current transport state, speed in bpm, and
1103 	// transport position with a query request to the JACK
1104 	// server. It will only overwrite m_transport.m_nFrames, if
1105 	// the transport position was changed by the user by
1106 	// e.g. clicking on the timeline.
1107 	m_pAudioDriver->updateTransportInfo();
1108 
1109 	Hydrogen* pHydrogen = Hydrogen::get_instance();
1110 	Song* pSong = pHydrogen->getSong();
1111 
1112 	// Update the state of the audio engine depending on the
1113 	// status of the audio driver. E.g. if the JACK transport was
1114 	// started by another client, the audio engine has to be
1115 	// started as well.
1116 	switch ( m_pAudioDriver->m_transport.m_status ) {
1117 	case TransportInfo::ROLLING:
1118 		if ( m_audioEngineState == STATE_READY ) {
1119 			// false == no engine lock. Already locked
1120 			// this should set STATE_PLAYING
1121 			audioEngine_start( false, m_pAudioDriver->m_transport.m_nFrames );
1122 		}
1123 		// So, we are not playing even after attempt to start engine
1124 		if ( m_audioEngineState != STATE_PLAYING ) {
1125 			return;
1126 		}
1127 
1128 		/* Now we're playing | Update BPM */
1129 		if ( pSong->__bpm != m_pAudioDriver->m_transport.m_fBPM ) {
1130 			___INFOLOG( QString( "song bpm: (%1) gets transport bpm: (%2)" )
1131 				.arg( pSong->__bpm )
1132 				.arg( m_pAudioDriver->m_transport.m_fBPM )
1133 			);
1134 
1135 			pHydrogen->setBPM( m_pAudioDriver->m_transport.m_fBPM );
1136 		}
1137 
1138 		// Update the variable m_nRealtimeFrames keeping track
1139 		// of the current transport position.
1140 		pHydrogen->setRealtimeFrames( m_pAudioDriver->m_transport.m_nFrames );
1141 		break;
1142 	case TransportInfo::STOPPED:
1143 		// So, we are not playing even after attempt to start engine
1144 		if ( m_audioEngineState == STATE_PLAYING ) {
1145 			// false == no engine lock. Already locked
1146 			audioEngine_stop( false );
1147 		}
1148 
1149 		// go ahead and increment the realtimeframes by buffersize
1150 		// to support our realtime keyboard and midi event timing
1151 		// TODO: use method like setRealtimeFrames
1152 		m_nRealtimeFrames += m_nBufferSize;
1153 		break;
1154 	}
1155 }
1156 
audioEngine_clearNoteQueue()1157 void audioEngine_clearNoteQueue()
1158 {
1159 	//___INFOLOG( "clear notes...");
1160 
1161 	// delete all copied notes in the song notes queue
1162 	while (!m_songNoteQueue.empty()) {
1163 		m_songNoteQueue.top()->get_instrument()->dequeue();
1164 		delete m_songNoteQueue.top();
1165 		m_songNoteQueue.pop();
1166 	}
1167 
1168 	AudioEngine::get_instance()->get_sampler()->stop_playing_notes();
1169 
1170 	// delete all copied notes in the midi notes queue
1171 	for ( unsigned i = 0; i < m_midiNoteQueue.size(); ++i ) {
1172 		delete m_midiNoteQueue[i];
1173 	}
1174 	m_midiNoteQueue.clear();
1175 
1176 }
1177 
1178 /** Clear all audio buffers.
1179  *
1180  * It locks the audio output buffer using #mutex_OutputPointer, gets
1181  * fresh pointers to the output buffers #m_pMainBuffer_L and
1182  * #m_pMainBuffer_R using AudioOutput::getOut_L() and
1183  * AudioOutput::getOut_R() of the current instance of the audio driver
1184  * #m_pAudioDriver, and overwrites their memory with
1185  * \code{.cpp}
1186  * nFrames * sizeof( float )
1187  * \endcode
1188  * zeros.
1189  *
1190  * If the JACK driver is used and Preferences::m_bJackTrackOuts is set
1191  * to true, the stereo buffers for all tracks of the components of
1192  * each instrument will be reset as well.  If LadspaFX are used, the
1193  * output buffers of all effects LadspaFX::m_pBuffer_L and
1194  * LadspaFX::m_pBuffer_L have to be reset as well.
1195  *
1196  * If the audio driver #m_pAudioDriver isn't set yet, it will just
1197  * unlock and return.
1198  */
audioEngine_process_clearAudioBuffers(uint32_t nFrames)1199 inline void audioEngine_process_clearAudioBuffers( uint32_t nFrames )
1200 {
1201 	QMutexLocker mx( &mutex_OutputPointer );
1202 
1203 	// clear main out Left and Right
1204 	if ( m_pAudioDriver ) {
1205 		m_pMainBuffer_L = m_pAudioDriver->getOut_L();
1206 		m_pMainBuffer_R = m_pAudioDriver->getOut_R();
1207 	} else {
1208 		m_pMainBuffer_L = m_pMainBuffer_R = nullptr;
1209 	}
1210 	if ( m_pMainBuffer_L ) {
1211 		memset( m_pMainBuffer_L, 0, nFrames * sizeof( float ) );
1212 	}
1213 	if ( m_pMainBuffer_R ) {
1214 		memset( m_pMainBuffer_R, 0, nFrames * sizeof( float ) );
1215 	}
1216 
1217 #ifdef H2CORE_HAVE_JACK
1218 	JackAudioDriver * jo = dynamic_cast<JackAudioDriver*>(m_pAudioDriver);
1219 	// Check whether the Preferences::m_bJackTrackOuts option was
1220 	// set. It enables a per-track creation of the output
1221 	// ports. All of them have to be reset as well.
1222 	if( jo && jo->has_track_outs() ) {
1223 		float* buf;
1224 		int k;
1225 		for( k=0 ; k<jo->getNumTracks() ; ++k ) {
1226 			buf = jo->getTrackOut_L(k);
1227 			if( buf ) {
1228 				memset( buf, 0, nFrames * sizeof( float ) );
1229 			}
1230 			buf = jo->getTrackOut_R(k);
1231 			if( buf ) {
1232 				memset( buf, 0, nFrames * sizeof( float ) );
1233 			}
1234 		}
1235 	}
1236 #endif
1237 
1238 	mx.unlock();
1239 
1240 #ifdef H2CORE_HAVE_LADSPA
1241 	if ( m_audioEngineState >= STATE_READY ) {
1242 		Effects* pEffects = Effects::get_instance();
1243 		for ( unsigned i = 0; i < MAX_FX; ++i ) {	// clear FX buffers
1244 			LadspaFX* pFX = pEffects->getLadspaFX( i );
1245 			if ( pFX ) {
1246 				assert( pFX->m_pBuffer_L );
1247 				assert( pFX->m_pBuffer_R );
1248 				memset( pFX->m_pBuffer_L, 0, nFrames * sizeof( float ) );
1249 				memset( pFX->m_pBuffer_R, 0, nFrames * sizeof( float ) );
1250 			}
1251 		}
1252 	}
1253 #endif
1254 }
1255 
audioEngine_process(uint32_t nframes,void *)1256 int audioEngine_process( uint32_t nframes, void* /*arg*/ )
1257 {
1258 	// ___INFOLOG( QString( "[begin] status: %1, frame: %2, ticksize: %3, bpm: %4" )
1259 	// 	    .arg( m_pAudioDriver->m_transport.m_status )
1260 	// 	    .arg( m_pAudioDriver->m_transport.m_nFrames )
1261 	// 	    .arg( m_pAudioDriver->m_transport.m_fTickSize )
1262 	// 	    .arg( m_pAudioDriver->m_transport.m_fBPM ) );
1263 	timeval startTimeval = currentTime2();
1264 
1265 	// Resetting all audio output buffers with zeros.
1266 	audioEngine_process_clearAudioBuffers( nframes );
1267 
1268 	/*
1269 	 * The "try_lock" was introduced for Bug #164 (Deadlock after during
1270 	 * alsa driver shutdown). The try_lock *should* only fail in rare circumstances
1271 	 * (like shutting down drivers). In such cases, it seems to be ok to interrupt
1272 	 * audio processing. Returning the special return value "2" enables the disk
1273 	 * writer driver to repeat the processing of the current data.
1274 	 */
1275 	if(!AudioEngine::get_instance()->try_lock( RIGHT_HERE )) {
1276 		if ( m_pAudioDriver->class_name() == DiskWriterDriver::class_name() ) {
1277 			return 2;	// inform the caller that we could not aquire the lock
1278 		}
1279 
1280 		return 0;
1281 	}
1282 
1283 	if ( m_audioEngineState < STATE_READY) {
1284 		AudioEngine::get_instance()->unlock();
1285 		return 0;
1286 	}
1287 
1288 	if ( m_nBufferSize != nframes ) {
1289 		___INFOLOG(
1290 			   QString( "Buffer size changed. Old size = %1, new size = %2" )
1291 			   .arg( m_nBufferSize )
1292 			   .arg( nframes ) );
1293 		m_nBufferSize = nframes;
1294 	}
1295 
1296 	Hydrogen* pHydrogen = Hydrogen::get_instance();
1297 	Song* pSong = pHydrogen->getSong();
1298 
1299 	// In case of the JackAudioDriver:
1300 	// Query the JACK server for the current status of the
1301 	// transport, start or stop the audio engine depending the
1302 	// results, update the speed of the current song according to
1303 	// the one used by the JACK server, and adjust the current
1304 	// transport position if it was changed by an user interaction
1305 	// (e.g. clicking on the timeline).
1306 	audioEngine_process_transport();
1307 
1308 
1309 	// ___INFOLOG( QString( "[after process] status: %1, frame: %2, ticksize: %3, bpm: %4" )
1310 	// 	    .arg( m_pAudioDriver->m_transport.m_status )
1311 	// 	    .arg( m_pAudioDriver->m_transport.m_nFrames )
1312 	// 	    .arg( m_pAudioDriver->m_transport.m_fTickSize )
1313 	// 	    .arg( m_pAudioDriver->m_transport.m_fBPM ) );
1314 	// Check whether the tick size has changed.
1315 	audioEngine_process_checkBPMChanged(pSong);
1316 
1317 	bool bSendPatternChange = false;
1318 	// always update note queue.. could come from pattern or realtime input
1319 	// (midi, keyboard)
1320 	int nResNoteQueue = audioEngine_updateNoteQueue( nframes );
1321 	if ( nResNoteQueue == -1 ) {	// end of song
1322 		___INFOLOG( "End of song received, calling engine_stop()" );
1323 		AudioEngine::get_instance()->unlock();
1324 		m_pAudioDriver->stop();
1325 		m_pAudioDriver->locate( 0 ); // locate 0, reposition from start of the song
1326 
1327 		if ( ( m_pAudioDriver->class_name() == DiskWriterDriver::class_name() )
1328 			 || ( m_pAudioDriver->class_name() == FakeDriver::class_name() )
1329 			 ) {
1330 			___INFOLOG( "End of song." );
1331 
1332 			return 1;	// kill the audio AudioDriver thread
1333 		}
1334 
1335 		return 0;
1336 	} else if ( nResNoteQueue == 2 ) { // send pattern change
1337 		bSendPatternChange = true;
1338 	}
1339 
1340 	// play all notes
1341 	audioEngine_process_playNotes( nframes );
1342 
1343 	// SAMPLER
1344 	AudioEngine::get_instance()->get_sampler()->process( nframes, pSong );
1345 	float* out_L = AudioEngine::get_instance()->get_sampler()->__main_out_L;
1346 	float* out_R = AudioEngine::get_instance()->get_sampler()->__main_out_R;
1347 	for ( unsigned i = 0; i < nframes; ++i ) {
1348 		m_pMainBuffer_L[ i ] += out_L[ i ];
1349 		m_pMainBuffer_R[ i ] += out_R[ i ];
1350 	}
1351 
1352 	// SYNTH
1353 	AudioEngine::get_instance()->get_synth()->process( nframes );
1354 	out_L = AudioEngine::get_instance()->get_synth()->m_pOut_L;
1355 	out_R = AudioEngine::get_instance()->get_synth()->m_pOut_R;
1356 	for ( unsigned i = 0; i < nframes; ++i ) {
1357 		m_pMainBuffer_L[ i ] += out_L[ i ];
1358 		m_pMainBuffer_R[ i ] += out_R[ i ];
1359 	}
1360 
1361 	timeval renderTime_end = currentTime2();
1362 	timeval ladspaTime_start = renderTime_end;
1363 
1364 #ifdef H2CORE_HAVE_LADSPA
1365 	// Process LADSPA FX
1366 	if ( m_audioEngineState >= STATE_READY ) {
1367 		for ( unsigned nFX = 0; nFX < MAX_FX; ++nFX ) {
1368 			LadspaFX *pFX = Effects::get_instance()->getLadspaFX( nFX );
1369 			if ( ( pFX ) && ( pFX->isEnabled() ) ) {
1370 				pFX->processFX( nframes );
1371 
1372 				float *buf_L, *buf_R;
1373 				if ( pFX->getPluginType() == LadspaFX::STEREO_FX ) {
1374 					buf_L = pFX->m_pBuffer_L;
1375 					buf_R = pFX->m_pBuffer_R;
1376 				} else { // MONO FX
1377 					buf_L = pFX->m_pBuffer_L;
1378 					buf_R = buf_L;
1379 				}
1380 
1381 				for ( unsigned i = 0; i < nframes; ++i ) {
1382 					m_pMainBuffer_L[ i ] += buf_L[ i ];
1383 					m_pMainBuffer_R[ i ] += buf_R[ i ];
1384 					if ( buf_L[ i ] > m_fFXPeak_L[nFX] ) {
1385 						m_fFXPeak_L[nFX] = buf_L[ i ];
1386 					}
1387 
1388 					if ( buf_R[ i ] > m_fFXPeak_R[nFX] ) {
1389 						m_fFXPeak_R[nFX] = buf_R[ i ];
1390 					}
1391 				}
1392 			}
1393 		}
1394 	}
1395 #endif
1396 	timeval ladspaTime_end = currentTime2();
1397 
1398 	// update master peaks
1399 	float val_L, val_R;
1400 	if ( m_audioEngineState >= STATE_READY ) {
1401 		for ( unsigned i = 0; i < nframes; ++i ) {
1402 			val_L = m_pMainBuffer_L[i];
1403 			val_R = m_pMainBuffer_R[i];
1404 
1405 			if ( val_L > m_fMasterPeak_L ) {
1406 				m_fMasterPeak_L = val_L;
1407 			}
1408 
1409 			if ( val_R > m_fMasterPeak_R ) {
1410 				m_fMasterPeak_R = val_R;
1411 			}
1412 
1413 			for (std::vector<DrumkitComponent*>::iterator it = pSong->get_components()->begin() ; it != pSong->get_components()->end(); ++it) {
1414 				DrumkitComponent* drumkit_component = *it;
1415 
1416 				float compo_val_L = drumkit_component->get_out_L(i);
1417 				float compo_val_R = drumkit_component->get_out_R(i);
1418 
1419 				if( compo_val_L > drumkit_component->get_peak_l() ) {
1420 					drumkit_component->set_peak_l( compo_val_L );
1421 				}
1422 				if( compo_val_R > drumkit_component->get_peak_r() ) {
1423 					drumkit_component->set_peak_r( compo_val_R );
1424 				}
1425 			}
1426 		}
1427 	}
1428 
1429 	// update total frames number
1430 	if ( m_audioEngineState == STATE_PLAYING ) {
1431 		m_pAudioDriver->m_transport.m_nFrames += nframes;
1432 	}
1433 
1434 	timeval finishTimeval = currentTime2();
1435 	m_fProcessTime =
1436 			( finishTimeval.tv_sec - startTimeval.tv_sec ) * 1000.0
1437 			+ ( finishTimeval.tv_usec - startTimeval.tv_usec ) / 1000.0;
1438 
1439 	float sampleRate = ( float )m_pAudioDriver->getSampleRate();
1440 	m_fMaxProcessTime = 1000.0 / ( sampleRate / nframes );
1441 
1442 #ifdef CONFIG_DEBUG
1443 	if ( m_fProcessTime > m_fMaxProcessTime ) {
1444 		___WARNINGLOG( "" );
1445 		___WARNINGLOG( "----XRUN----" );
1446 		___WARNINGLOG( QString( "XRUN of %1 msec (%2 > %3)" )
1447 					   .arg( ( m_fProcessTime - m_fMaxProcessTime ) )
1448 					   .arg( m_fProcessTime ).arg( m_fMaxProcessTime ) );
1449 		___WARNINGLOG( QString( "Ladspa process time = %1" ).arg( fLadspaTime ) );
1450 		___WARNINGLOG( "------------" );
1451 		___WARNINGLOG( "" );
1452 		// raise xRun event
1453 		EventQueue::get_instance()->push_event( EVENT_XRUN, -1 );
1454 	}
1455 #endif
1456 	// ___INFOLOG( QString( "[end] status: %1, frame: %2, ticksize: %3, bpm: %4" )
1457 	// 	    .arg( m_pAudioDriver->m_transport.m_status )
1458 	// 	    .arg( m_pAudioDriver->m_transport.m_nFrames )
1459 	// 	    .arg( m_pAudioDriver->m_transport.m_fTickSize )
1460 	// 	    .arg( m_pAudioDriver->m_transport.m_fBPM ) );
1461 
1462 	AudioEngine::get_instance()->unlock();
1463 
1464 	if ( bSendPatternChange ) {
1465 		EventQueue::get_instance()->push_event( EVENT_PATTERN_CHANGED, -1 );
1466 	}
1467 	return 0;
1468 }
1469 
audioEngine_setupLadspaFX(unsigned nBufferSize)1470 void audioEngine_setupLadspaFX( unsigned nBufferSize )
1471 {
1472 	//___INFOLOG( "buffersize=" + to_string(nBufferSize) );
1473 
1474 	Hydrogen* pHydrogen = Hydrogen::get_instance();
1475 	Song* pSong = pHydrogen->getSong();
1476 	if ( ! pSong ) {
1477 		return;
1478 	}
1479 
1480 	if ( nBufferSize == 0 ) {
1481 		___ERRORLOG( "nBufferSize=0" );
1482 		return;
1483 	}
1484 
1485 #ifdef H2CORE_HAVE_LADSPA
1486 	for ( unsigned nFX = 0; nFX < MAX_FX; ++nFX ) {
1487 		LadspaFX *pFX = Effects::get_instance()->getLadspaFX( nFX );
1488 		if ( pFX == nullptr ) {
1489 			return;
1490 		}
1491 
1492 		pFX->deactivate();
1493 
1494 		Effects::get_instance()->getLadspaFX( nFX )->connectAudioPorts(
1495 					pFX->m_pBuffer_L,
1496 					pFX->m_pBuffer_R,
1497 					pFX->m_pBuffer_L,
1498 					pFX->m_pBuffer_R
1499 					);
1500 		pFX->activate();
1501 	}
1502 #endif
1503 }
1504 
1505 /**
1506  * Hands the provided Song to JackAudioDriver::makeTrackOutputs() if
1507  * @a pSong is not a null pointer and the audio driver #m_pAudioDriver
1508  * is an instance of the JackAudioDriver.
1509  * \param pSong Song for which per-track output ports should be generated.
1510  */
audioEngine_renameJackPorts(Song * pSong)1511 void audioEngine_renameJackPorts(Song * pSong)
1512 {
1513 #ifdef H2CORE_HAVE_JACK
1514 	// renames jack ports
1515 	if ( ! pSong ) return;
1516 
1517 	if ( Hydrogen::get_instance()->haveJackAudioDriver() ) {
1518 		static_cast< JackAudioDriver* >( m_pAudioDriver )->makeTrackOutputs( pSong );
1519 	}
1520 #endif
1521 }
1522 
audioEngine_setSong(Song * pNewSong)1523 void audioEngine_setSong( Song* pNewSong )
1524 {
1525 	___WARNINGLOG( QString( "Set song: %1" ).arg( pNewSong->__name ) );
1526 
1527 	AudioEngine::get_instance()->lock( RIGHT_HERE );
1528 
1529 	// check current state
1530 	// should be set by removeSong called earlier
1531 	if ( m_audioEngineState != STATE_PREPARED ) {
1532 		___ERRORLOG( "Error the audio engine is not in PREPARED state" );
1533 	}
1534 
1535 	// setup LADSPA FX
1536 	audioEngine_setupLadspaFX( m_pAudioDriver->getBufferSize() );
1537 
1538 	// update tick size
1539 	audioEngine_process_checkBPMChanged( pNewSong );
1540 
1541 	// find the first pattern and set as current
1542 	if ( pNewSong->get_pattern_list()->size() > 0 ) {
1543 		m_pPlayingPatterns->add( pNewSong->get_pattern_list()->get( 0 ) );
1544 	}
1545 
1546 	audioEngine_renameJackPorts( pNewSong );
1547 
1548 	m_pAudioDriver->setBpm( pNewSong->__bpm );
1549 
1550 	// change the current audio engine state
1551 	m_audioEngineState = STATE_READY;
1552 
1553 	m_pAudioDriver->locate( 0 );
1554 
1555 	AudioEngine::get_instance()->unlock();
1556 
1557 	EventQueue::get_instance()->push_event( EVENT_STATE, STATE_READY );
1558 }
1559 
audioEngine_removeSong()1560 void audioEngine_removeSong()
1561 {
1562 	AudioEngine::get_instance()->lock( RIGHT_HERE );
1563 
1564 	if ( m_audioEngineState == STATE_PLAYING ) {
1565 		m_pAudioDriver->stop();
1566 		audioEngine_stop( false );
1567 	}
1568 
1569 	// check current state
1570 	if ( m_audioEngineState != STATE_READY ) {
1571 		___ERRORLOG( "Error the audio engine is not in READY state" );
1572 		AudioEngine::get_instance()->unlock();
1573 		return;
1574 	}
1575 
1576 	m_pPlayingPatterns->clear();
1577 	m_pNextPatterns->clear();
1578 	audioEngine_clearNoteQueue();
1579 
1580 	// change the current audio engine state
1581 	m_audioEngineState = STATE_PREPARED;
1582 	AudioEngine::get_instance()->unlock();
1583 
1584 	EventQueue::get_instance()->push_event( EVENT_STATE, STATE_PREPARED );
1585 }
1586 
audioEngine_updateNoteQueue(unsigned nFrames)1587 inline int audioEngine_updateNoteQueue( unsigned nFrames )
1588 {
1589 	Hydrogen* pHydrogen = Hydrogen::get_instance();
1590 	Song* pSong = pHydrogen->getSong();
1591 
1592 	// Indicates whether the current pattern list changed with respect
1593 	// to the last cycle.
1594 	bool bSendPatternChange = false;
1595 	float fTickSize = m_pAudioDriver->m_transport.m_fTickSize;
1596 	int nLeadLagFactor = pHydrogen->calculateLeadLagFactor( fTickSize );
1597 
1598 	unsigned int framepos;
1599 	if (  m_audioEngineState == STATE_PLAYING ) {
1600 		// Current transport position.
1601 		framepos = m_pAudioDriver->m_transport.m_nFrames;
1602 	} else {
1603 		// Use this to support realtime events, like MIDI, when not
1604 		// playing.
1605 		framepos = pHydrogen->getRealtimeFrames();
1606 	}
1607 
1608 	int lookahead = pHydrogen->calculateLookahead( fTickSize );
1609 	int tickNumber_start = 0;
1610 	if ( framepos == 0
1611 		 || ( m_audioEngineState == STATE_PLAYING
1612 			  && pSong->get_mode() == Song::SONG_MODE
1613 			  && m_nSongPos == -1 )
1614 	) {
1615 		tickNumber_start = framepos / fTickSize;
1616 	} else {
1617 		tickNumber_start = ( framepos + lookahead) / fTickSize;
1618 	}
1619 	int tickNumber_end = ( framepos + nFrames + lookahead ) /fTickSize;
1620 
1621 	// Get initial timestamp for first tick
1622 	gettimeofday( &m_currentTickTime, nullptr );
1623 
1624 	// A tick is the most fine-grained time scale within Hydrogen.
1625 	for ( int tick = tickNumber_start; tick < tickNumber_end; tick++ ) {
1626 
1627 		// MIDI events now get put into the `m_songNoteQueue` as well,
1628 		// based on their timestamp (which is given in terms of its
1629 		// transport position and not in terms of the date-time as
1630 		// above).
1631 		while ( m_midiNoteQueue.size() > 0 ) {
1632 			Note *pNote = m_midiNoteQueue[0];
1633 			if ( pNote->get_position() > tick ) break;
1634 
1635 			m_midiNoteQueue.pop_front();
1636 			pNote->get_instrument()->enqueue();
1637 			m_songNoteQueue.push( pNote );
1638 		}
1639 
1640 		if (  m_audioEngineState != STATE_PLAYING ) {
1641 			// only keep going if we're playing
1642 			continue;
1643 		}
1644 
1645 		bool doErase = m_audioEngineState == STATE_PLAYING
1646 				&& Preferences::get_instance()->getRecordEvents()
1647 				&& Preferences::get_instance()->getDestructiveRecord()
1648 				&& Preferences::get_instance()->m_nRecPreDelete == 0;
1649 
1650 		//////////////////////////////////////////////////////////////
1651 		// SONG MODE
1652 		if ( pSong->get_mode() == Song::SONG_MODE ) {
1653 			if ( pSong->get_pattern_group_vector()->size() == 0 ) {
1654 				// there's no song!!
1655 				___ERRORLOG( "no patterns in song." );
1656 				m_pAudioDriver->stop();
1657 				return -1;
1658 			}
1659 
1660 			m_nSongPos = findPatternInTick( tick, pSong->is_loop_enabled(), &m_nPatternStartTick );
1661 
1662 			// The `m_nSongSizeInTicks` variable is only set to some
1663 			// value other than zero in `findPatternInTick()` if
1664 			// either the pattern list was not found of loop mode was
1665 			// enabled and will contain the total size of the song in
1666 			// ticks.
1667 			if ( m_nSongSizeInTicks != 0 ) {
1668 				// When using the JACK audio driver the overall
1669 				// transport position will be managed by an external
1670 				// server. Since it is agnostic of all the looping in
1671 				// its clients, it will only increment time and
1672 				// Hydrogen has to take care of the looping itself.
1673 				m_nPatternTickPosition = ( tick - m_nPatternStartTick )
1674 						% m_nSongSizeInTicks;
1675 			} else {
1676 				m_nPatternTickPosition = tick - m_nPatternStartTick;
1677 			}
1678 
1679 			// Since we are located at the very beginning of the
1680 			// pattern list, it had to change with respect to the last
1681 			// cycle.
1682 			if ( m_nPatternTickPosition == 0 ) {
1683 				bSendPatternChange = true;
1684 			}
1685 
1686 			// If no pattern list could not be found, either choose
1687 			// the first one if loop mode is activate or the
1688 			// function returns indicating that the end of the song is
1689 			// reached.
1690 			if ( m_nSongPos == -1 ) {
1691 				___INFOLOG( "song pos = -1" );
1692 				if ( pSong->is_loop_enabled() == true ) {
1693 					// TODO: This function call should be redundant
1694 					// since `findPatternInTick()` is deterministic
1695 					// and was already invoked with
1696 					// `pSong->is_loop_enabled()` as second argument.
1697 					m_nSongPos = findPatternInTick( 0, true, &m_nPatternStartTick );
1698 				} else {
1699 
1700 					___INFOLOG( "End of Song" );
1701 
1702 					if( Hydrogen::get_instance()->getMidiOutput() != nullptr ){
1703 						Hydrogen::get_instance()->getMidiOutput()->handleQueueAllNoteOff();
1704 					}
1705 
1706 					return -1;
1707 				}
1708 			}
1709 
1710 			// Obtain the current PatternList and use it to overwrite
1711 			// the on in `m_pPlayingPatterns.
1712 			// TODO: Why overwriting it for each and every tick
1713 			//       without check if it did changed? This is highly
1714 			//       inefficient.
1715 			PatternList *pPatternList = ( *( pSong->get_pattern_group_vector() ) )[m_nSongPos];
1716 			m_pPlayingPatterns->clear();
1717 			for ( int i=0; i< pPatternList->size(); ++i ) {
1718 				Pattern* pPattern = pPatternList->get(i);
1719 				m_pPlayingPatterns->add( pPattern );
1720 				pPattern->extand_with_flattened_virtual_patterns( m_pPlayingPatterns );
1721 			}
1722 			// Set destructive record depending on punch area
1723 			doErase = doErase && Preferences::get_instance()->inPunchArea(m_nSongPos);
1724 		}
1725 
1726 		//////////////////////////////////////////////////////////////
1727 		// PATTERN MODE
1728 		else if ( pSong->get_mode() == Song::PATTERN_MODE )	{
1729 
1730 			int nPatternSize = MAX_NOTES;
1731 
1732 			// If the user chose to playback the pattern she focuses,
1733 			// use it to overwrite `m_pPlayingPatterns`.
1734 			if ( Preferences::get_instance()->patternModePlaysSelected() )
1735 			{
1736 				// TODO: Again, a check whether the pattern did change
1737 				// would be more efficient.
1738 				m_pPlayingPatterns->clear();
1739 				Pattern * pattern = pSong->get_pattern_list()->get(m_nSelectedPatternNumber);
1740 				m_pPlayingPatterns->add( pattern );
1741 				pattern->extand_with_flattened_virtual_patterns( m_pPlayingPatterns );
1742 			}
1743 
1744 			if ( m_pPlayingPatterns->size() != 0 ) {
1745 				const Pattern *pFirstPattern = m_pPlayingPatterns->get( 0 );
1746 				nPatternSize = pFirstPattern->get_length();
1747 			}
1748 
1749 			if ( nPatternSize == 0 ) {
1750 				___ERRORLOG( "nPatternSize == 0" );
1751 			}
1752 
1753 			// If either the beginning of the current pattern was not
1754 			// specified yet or if its end is reached, write the
1755 			// content of `m_pNextPatterns` to `m_pPlayingPatterns`
1756 			// and clear the former one.
1757 			if ( ( tick == m_nPatternStartTick + nPatternSize )
1758 				 || ( m_nPatternStartTick == -1 ) ) {
1759 				if ( m_pNextPatterns->size() > 0 ) {
1760 					Pattern* pPattern;
1761 					for ( uint i = 0; i < m_pNextPatterns->size(); i++ ) {
1762 						pPattern = m_pNextPatterns->get( i );
1763 						// If `pPattern is already present in
1764 						// `m_pPlayingPatterns`, it will be removed
1765 						// from the latter and its `del()` method will
1766 						// return a pointer to the very pattern. The
1767 						// if clause is therefore only entered if the
1768 						// `pPattern` was not already present.
1769 						if ( ( m_pPlayingPatterns->del( pPattern ) ) == nullptr ) {
1770 							m_pPlayingPatterns->add( pPattern );
1771 						}
1772 					}
1773 					m_pNextPatterns->clear();
1774 					bSendPatternChange = true;
1775 				}
1776 				if ( m_nPatternStartTick == -1 && nPatternSize > 0 ) {
1777 					m_nPatternStartTick = tick - (tick % nPatternSize);
1778 				} else {
1779 					m_nPatternStartTick = tick;
1780 				}
1781 			}
1782 
1783 			// Since the starting position of the Pattern may have
1784 			// been updated, update the number of ticks passed since
1785 			// the beginning of the pattern too.
1786 			m_nPatternTickPosition = tick - m_nPatternStartTick;
1787 			if ( m_nPatternTickPosition > nPatternSize && nPatternSize > 0 ) {
1788 				m_nPatternTickPosition = tick % nPatternSize;
1789 			}
1790 		}
1791 
1792 		//////////////////////////////////////////////////////////////
1793 		// Metronome
1794 		// Only trigger the metronome at a predefined rate.
1795 		if ( m_nPatternTickPosition % 48 == 0 ) {
1796 			float fPitch;
1797 			float fVelocity;
1798 
1799 			// Depending on whether the metronome beat will be issued
1800 			// at the beginning or in the remainder of the pattern,
1801 			// two different sounds and events will be used.
1802 			if ( m_nPatternTickPosition == 0 ) {
1803 				fPitch = 3;
1804 				fVelocity = 1.0;
1805 				EventQueue::get_instance()->push_event( EVENT_METRONOME, 1 );
1806 			} else {
1807 				fPitch = 0;
1808 				fVelocity = 0.8;
1809 				EventQueue::get_instance()->push_event( EVENT_METRONOME, 0 );
1810 			}
1811 
1812 			// Only trigger the sounds if the user enabled the
1813 			// metronome.
1814 			if ( Preferences::get_instance()->m_bUseMetronome ) {
1815 				m_pMetronomeInstrument->set_volume(
1816 							Preferences::get_instance()->m_fMetronomeVolume
1817 							);
1818 				Note *pMetronomeNote = new Note( m_pMetronomeInstrument,
1819 												 tick,
1820 												 fVelocity,
1821 												 0.5,
1822 												 0.5,
1823 												 -1,
1824 												 fPitch
1825 												 );
1826 				m_pMetronomeInstrument->enqueue();
1827 				m_songNoteQueue.push( pMetronomeNote );
1828 			}
1829 		}
1830 
1831 		//////////////////////////////////////////////////////////////
1832 		// Update the notes queue.
1833 		//
1834 		if ( m_pPlayingPatterns->size() != 0 ) {
1835 			for ( unsigned nPat = 0 ;
1836 				  nPat < m_pPlayingPatterns->size() ;
1837 				  ++nPat ) {
1838 				Pattern *pPattern = m_pPlayingPatterns->get( nPat );
1839 				assert( pPattern != nullptr );
1840 				Pattern::notes_t* notes = (Pattern::notes_t*)pPattern->get_notes();
1841 				// Delete notes before attempting to play them
1842 				if ( doErase ) {
1843 					FOREACH_NOTE_IT_BOUND(notes,it,m_nPatternTickPosition) {
1844 						Note* pNote = it->second;
1845 						assert( pNote != nullptr );
1846 						if ( pNote->get_just_recorded() == false ) {
1847 							EventQueue::AddMidiNoteVector noteAction;
1848 							noteAction.m_column = pNote->get_position();
1849 							noteAction.m_row = pNote->get_instrument_id();
1850 							noteAction.m_pattern = nPat;
1851 							noteAction.f_velocity = pNote->get_velocity();
1852 							noteAction.f_pan_L = pNote->get_pan_l();
1853 							noteAction.f_pan_R = pNote->get_pan_r();
1854 							noteAction.m_length = -1;
1855 							noteAction.no_octaveKeyVal = pNote->get_octave();
1856 							noteAction.nk_noteKeyVal = pNote->get_key();
1857 							noteAction.b_isInstrumentMode = false;
1858 							noteAction.b_isMidi = false;
1859 							noteAction.b_noteExist = false;
1860 							EventQueue::get_instance()->m_addMidiNoteVector.push_back(noteAction);
1861 						}
1862 					}
1863 				}
1864 
1865 				// Perform a loop over all notes, which are enclose
1866 				// the position of the current tick, using a constant
1867 				// iterator (notes won't be altered!). After some
1868 				// humanization was applied to onset of each note, it
1869 				// will be added to `m_songNoteQueue` for playback.
1870 				FOREACH_NOTE_CST_IT_BOUND(notes,it,m_nPatternTickPosition) {
1871 					Note *pNote = it->second;
1872 					if ( pNote ) {
1873 						pNote->set_just_recorded( false );
1874 						int nOffset = 0;
1875 
1876 						// Swing //
1877 						// Add a constant and periodic offset at
1878 						// predefined positions to the note position.
1879 						// TODO: incorporate the factor of 6.0 either
1880 						// in Song::__swing_factor or make it a member
1881 						// variable.
1882 						float fSwingFactor = pSong->get_swing_factor();
1883 						if ( ( ( m_nPatternTickPosition % 12 ) == 0 )
1884 							 && ( ( m_nPatternTickPosition % 24 ) != 0 ) ) {
1885 							// da l'accento al tick 4, 12, 20, 36...
1886 							nOffset += (int)( 6.0 * fTickSize * fSwingFactor );
1887 						}
1888 
1889 						// Humanize - Time parameter //
1890 						// Add a random offset to each note. Due to
1891 						// the nature of the Gaussian distribution,
1892 						// the factor Song::__humanize_time_value will
1893 						// also scale the variance of the generated
1894 						// random variable.
1895 						if ( pSong->get_humanize_time_value() != 0 ) {
1896 							nOffset += ( int )(
1897 										getGaussian( 0.3 )
1898 										* pSong->get_humanize_time_value()
1899 										* pHydrogen->m_nMaxTimeHumanize
1900 										);
1901 						}
1902 
1903 						// Lead or Lag - timing parameter //
1904 						// Add a constant offset to all notes.
1905 						nOffset += (int) ( pNote->get_lead_lag()
1906 										   * nLeadLagFactor );
1907 
1908 						// No note is allowed to start prior to the
1909 						// beginning of the song.
1910 						if((tick == 0) && (nOffset < 0)) {
1911 							nOffset = 0;
1912 						}
1913 
1914 						// Generate a copy of the current note, assign
1915 						// it the new offset, and push it to the list
1916 						// of all notes, which are about to be played
1917 						// back.
1918 						// TODO: Why a copy?
1919 						Note *pCopiedNote = new Note( pNote );
1920 						pCopiedNote->set_position( tick );
1921 						pCopiedNote->set_humanize_delay( nOffset );
1922 						pNote->get_instrument()->enqueue();
1923 						m_songNoteQueue.push( pCopiedNote );
1924 					}
1925 				}
1926 			}
1927 		}
1928 	}
1929 
1930 	// audioEngine_process() must send the pattern change event after
1931 	// mutex unlock
1932 	if ( bSendPatternChange ) {
1933 		return 2;
1934 	}
1935 	return 0;
1936 }
1937 
findPatternInTick(int nTick,bool bLoopMode,int * pPatternStartTick)1938 inline int findPatternInTick( int nTick, bool bLoopMode, int* pPatternStartTick )
1939 {
1940 	Hydrogen* pHydrogen = Hydrogen::get_instance();
1941 	Song* pSong = pHydrogen->getSong();
1942 	assert( pSong );
1943 
1944 	int nTotalTick = 0;
1945 	m_nSongSizeInTicks = 0;
1946 
1947 	std::vector<PatternList*> *pPatternColumns = pSong->get_pattern_group_vector();
1948 	int nColumns = pPatternColumns->size();
1949 
1950 	// Sum the lengths of all pattern columns and use the macro
1951 	// MAX_NOTES in case some of them are of size zero. If the
1952 	// supplied value nTick is bigger than this and doesn't belong to
1953 	// the next pattern column, we just found the pattern list we were
1954 	// searching for.
1955 	int nPatternSize;
1956 	for ( int i = 0; i < nColumns; ++i ) {
1957 		PatternList *pColumn = ( *pPatternColumns )[ i ];
1958 		if ( pColumn->size() != 0 ) {
1959 			nPatternSize = pColumn->get( 0 )->get_length();
1960 		} else {
1961 			nPatternSize = MAX_NOTES;
1962 		}
1963 
1964 		if ( ( nTick >= nTotalTick ) && ( nTick < nTotalTick + nPatternSize ) ) {
1965 			( *pPatternStartTick ) = nTotalTick;
1966 			return i;
1967 		}
1968 		nTotalTick += nPatternSize;
1969 	}
1970 
1971 	// If the song is played in loop mode, the tick numbers of the
1972 	// second turn are added on top of maximum tick number of the
1973 	// song. Therefore, we will introduced periodic boundary
1974 	// conditions and start the search again.
1975 	if ( bLoopMode ) {
1976 		m_nSongSizeInTicks = nTotalTick;
1977 		int nLoopTick = 0;
1978 		if ( m_nSongSizeInTicks != 0 ) {
1979 			nLoopTick = nTick % m_nSongSizeInTicks;
1980 		}
1981 		nTotalTick = 0;
1982 		for ( int i = 0; i < nColumns; ++i ) {
1983 			PatternList *pColumn = ( *pPatternColumns )[ i ];
1984 			if ( pColumn->size() != 0 ) {
1985 				nPatternSize = pColumn->get( 0 )->get_length();
1986 			} else {
1987 				nPatternSize = MAX_NOTES;
1988 			}
1989 
1990 			if ( ( nLoopTick >= nTotalTick )
1991 				 && ( nLoopTick < nTotalTick + nPatternSize ) ) {
1992 				( *pPatternStartTick ) = nTotalTick;
1993 				return i;
1994 			}
1995 			nTotalTick += nPatternSize;
1996 		}
1997 	}
1998 
1999 	QString err = QString( "[findPatternInTick] tick = %1. No pattern list found" ).arg( QString::number(nTick) );
2000 	___ERRORLOG( err );
2001 	return -1;
2002 }
2003 
audioEngine_noteOn(Note * note)2004 void audioEngine_noteOn( Note *note )
2005 {
2006 	// check current state
2007 	if ( ( m_audioEngineState != STATE_READY )
2008 		 && ( m_audioEngineState != STATE_PLAYING ) ) {
2009 		___ERRORLOG( "Error the audio engine is not in READY state" );
2010 		delete note;
2011 		return;
2012 	}
2013 
2014 	m_midiNoteQueue.push_back( note );
2015 }
2016 
2017 /**
2018  * Create an audio driver using audioEngine_process() as its argument
2019  * based on the provided choice and calling their _init()_ function to
2020  * trigger their initialization.
2021  *
2022  * For a listing of all possible choices, please see
2023  * Preferences::m_sAudioDriver.
2024  *
2025  * \param sDriver String specifying which audio driver should be
2026  * created.
2027  * \return Pointer to the freshly created audio driver. If the
2028  * creation resulted in a NullDriver, the corresponding object will be
2029  * deleted and a null pointer returned instead.
2030  */
createDriver(const QString & sDriver)2031 AudioOutput* createDriver( const QString& sDriver )
2032 {
2033 	___INFOLOG( QString( "Driver: '%1'" ).arg( sDriver ) );
2034 	Preferences *pPref = Preferences::get_instance();
2035 	AudioOutput *pDriver = nullptr;
2036 
2037 	if ( sDriver == "Oss" ) {
2038 		pDriver = new OssDriver( audioEngine_process );
2039 		if ( pDriver->class_name() == NullDriver::class_name() ) {
2040 			delete pDriver;
2041 			pDriver = nullptr;
2042 		}
2043 	} else if ( sDriver == "Jack" ) {
2044 		pDriver = new JackAudioDriver( audioEngine_process );
2045 		if ( pDriver->class_name() == NullDriver::class_name() ) {
2046 			delete pDriver;
2047 			pDriver = nullptr;
2048 		} else {
2049 #ifdef H2CORE_HAVE_JACK
2050 			static_cast<JackAudioDriver*>(pDriver)->setConnectDefaults(
2051 						Preferences::get_instance()->m_bJackConnectDefaults
2052 						);
2053 #endif
2054 		}
2055 	} else if ( sDriver == "Alsa" ) {
2056 		pDriver = new AlsaAudioDriver( audioEngine_process );
2057 		if ( pDriver->class_name() == NullDriver::class_name() ) {
2058 			delete pDriver;
2059 			pDriver = nullptr;
2060 		}
2061 	} else if ( sDriver == "PortAudio" ) {
2062 		pDriver = new PortAudioDriver( audioEngine_process );
2063 		if ( pDriver->class_name() == NullDriver::class_name() ) {
2064 			delete pDriver;
2065 			pDriver = nullptr;
2066 		}
2067 	}
2068 	//#ifdef Q_OS_MACX
2069 	else if ( sDriver == "CoreAudio" ) {
2070 		___INFOLOG( "Creating CoreAudioDriver" );
2071 		pDriver = new CoreAudioDriver( audioEngine_process );
2072 		if ( pDriver->class_name() == NullDriver::class_name() ) {
2073 			delete pDriver;
2074 			pDriver = nullptr;
2075 		}
2076 	}
2077 	//#endif
2078 	else if ( sDriver == "PulseAudio" ) {
2079 		pDriver = new PulseAudioDriver( audioEngine_process );
2080 		if ( pDriver->class_name() == NullDriver::class_name() ) {
2081 			delete pDriver;
2082 			pDriver = nullptr;
2083 		}
2084 	}
2085 	else if ( sDriver == "Fake" ) {
2086 		___WARNINGLOG( "*** Using FAKE audio driver ***" );
2087 		pDriver = new FakeDriver( audioEngine_process );
2088 	} else {
2089 		___ERRORLOG( "Unknown driver " + sDriver );
2090 		audioEngine_raiseError( Hydrogen::UNKNOWN_DRIVER );
2091 	}
2092 
2093 	if ( pDriver  ) {
2094 		// initialize the audio driver
2095 		int res = pDriver->init( pPref->m_nBufferSize );
2096 		if ( res != 0 ) {
2097 			___ERRORLOG( "Error starting audio driver [audioDriver::init()]" );
2098 			delete pDriver;
2099 			pDriver = nullptr;
2100 		}
2101 	}
2102 
2103 	return pDriver;
2104 }
2105 
audioEngine_startAudioDrivers()2106 void audioEngine_startAudioDrivers()
2107 {
2108 	Preferences *preferencesMng = Preferences::get_instance();
2109 
2110 	// Lock both the AudioEngine and the audio output buffers.
2111 	AudioEngine::get_instance()->lock( RIGHT_HERE );
2112 	QMutexLocker mx(&mutex_OutputPointer);
2113 
2114 	___INFOLOG( "[audioEngine_startAudioDrivers]" );
2115 
2116 	// check current state
2117 	if ( m_audioEngineState != STATE_INITIALIZED ) {
2118 		___ERRORLOG( QString( "Error the audio engine is not in INITIALIZED"
2119 							  " state. state=%1" )
2120 					 .arg( m_audioEngineState ) );
2121 		AudioEngine::get_instance()->unlock();
2122 		return;
2123 	}
2124 
2125 	if ( m_pAudioDriver ) {	// check if the audio m_pAudioDriver is still alive
2126 		___ERRORLOG( "The audio driver is still alive" );
2127 	}
2128 	if ( m_pMidiDriver ) {	// check if midi driver is still alive
2129 		___ERRORLOG( "The MIDI driver is still active" );
2130 	}
2131 
2132 
2133 	QString sAudioDriver = preferencesMng->m_sAudioDriver;
2134 	if ( sAudioDriver == "Auto" ) {
2135 	#ifndef WIN32
2136 		if ( ( m_pAudioDriver = createDriver( "Jack" ) ) == nullptr ) {
2137 			if ( ( m_pAudioDriver = createDriver( "Alsa" ) ) == nullptr ) {
2138 				if ( ( m_pAudioDriver = createDriver( "CoreAudio" ) ) == nullptr ) {
2139 					if ( ( m_pAudioDriver = createDriver( "PortAudio" ) ) == nullptr ) {
2140 						if ( ( m_pAudioDriver = createDriver( "Oss" ) ) == nullptr ) {
2141 							if ( ( m_pAudioDriver = createDriver( "PulseAudio" ) ) == nullptr ) {
2142 								audioEngine_raiseError( Hydrogen::ERROR_STARTING_DRIVER );
2143 								___ERRORLOG( "Error starting audio driver" );
2144 								___ERRORLOG( "Using the NULL output audio driver" );
2145 
2146 								// use the NULL output driver
2147 								m_pAudioDriver = new NullDriver( audioEngine_process );
2148 								m_pAudioDriver->init( 0 );
2149 							}
2150 						}
2151 					}
2152 				}
2153 			}
2154 		}
2155 	#else
2156 		//On Windows systems, use PortAudio is the prioritized backend
2157 		if ( ( m_pAudioDriver = createDriver( "PortAudio" ) ) == nullptr ) {
2158 			if ( ( m_pAudioDriver = createDriver( "Alsa" ) ) == nullptr ) {
2159 				if ( ( m_pAudioDriver = createDriver( "CoreAudio" ) ) == nullptr ) {
2160 					if ( ( m_pAudioDriver = createDriver( "Jack" ) ) == nullptr ) {
2161 						if ( ( m_pAudioDriver = createDriver( "Oss" ) ) == nullptr ) {
2162 							if ( ( m_pAudioDriver = createDriver( "PulseAudio" ) ) == nullptr ) {
2163 								audioEngine_raiseError( Hydrogen::ERROR_STARTING_DRIVER );
2164 								___ERRORLOG( "Error starting audio driver" );
2165 								___ERRORLOG( "Using the NULL output audio driver" );
2166 
2167 								// use the NULL output driver
2168 								m_pAudioDriver = new NullDriver( audioEngine_process );
2169 								m_pAudioDriver->init( 0 );
2170 							}
2171 						}
2172 					}
2173 				}
2174 			}
2175 		}
2176 	#endif
2177 	} else {
2178 		m_pAudioDriver = createDriver( sAudioDriver );
2179 		if ( m_pAudioDriver == nullptr ) {
2180 			audioEngine_raiseError( Hydrogen::ERROR_STARTING_DRIVER );
2181 			___ERRORLOG( "Error starting audio driver" );
2182 			___ERRORLOG( "Using the NULL output audio driver" );
2183 
2184 			// use the NULL output driver
2185 			m_pAudioDriver = new NullDriver( audioEngine_process );
2186 			m_pAudioDriver->init( 0 );
2187 		}
2188 	}
2189 
2190 	if ( preferencesMng->m_sMidiDriver == "ALSA" ) {
2191 #ifdef H2CORE_HAVE_ALSA
2192 		// Create MIDI driver
2193 		AlsaMidiDriver *alsaMidiDriver = new AlsaMidiDriver();
2194 		m_pMidiDriverOut = alsaMidiDriver;
2195 		m_pMidiDriver = alsaMidiDriver;
2196 		m_pMidiDriver->open();
2197 		m_pMidiDriver->setActive( true );
2198 #endif
2199 	} else if ( preferencesMng->m_sMidiDriver == "PortMidi" ) {
2200 #ifdef H2CORE_HAVE_PORTMIDI
2201 		PortMidiDriver* pPortMidiDriver = new PortMidiDriver();
2202 		m_pMidiDriver = pPortMidiDriver;
2203 		m_pMidiDriverOut = pPortMidiDriver;
2204 		m_pMidiDriver->open();
2205 		m_pMidiDriver->setActive( true );
2206 #endif
2207 	} else if ( preferencesMng->m_sMidiDriver == "CoreMidi" ) {
2208 #ifdef H2CORE_HAVE_COREMIDI
2209 		CoreMidiDriver *coreMidiDriver = new CoreMidiDriver();
2210 		m_pMidiDriver = coreMidiDriver;
2211 		m_pMidiDriverOut = coreMidiDriver;
2212 		m_pMidiDriver->open();
2213 		m_pMidiDriver->setActive( true );
2214 #endif
2215 	} else if ( preferencesMng->m_sMidiDriver == "JackMidi" ) {
2216 #ifdef H2CORE_HAVE_JACK
2217 		JackMidiDriver *jackMidiDriver = new JackMidiDriver();
2218 		m_pMidiDriverOut = jackMidiDriver;
2219 		m_pMidiDriver = jackMidiDriver;
2220 		m_pMidiDriver->open();
2221 		m_pMidiDriver->setActive( true );
2222 #endif
2223 	}
2224 
2225 	// change the current audio engine state
2226 	Hydrogen* pHydrogen = Hydrogen::get_instance();
2227 	Song* pSong = pHydrogen->getSong();
2228 	if ( pSong ) {
2229 		m_audioEngineState = STATE_READY;
2230 		m_pAudioDriver->setBpm( pSong->__bpm );
2231 	} else {
2232 		m_audioEngineState = STATE_PREPARED;
2233 	}
2234 
2235 	if ( m_audioEngineState == STATE_PREPARED ) {
2236 		EventQueue::get_instance()->push_event( EVENT_STATE, STATE_PREPARED );
2237 	} else if ( m_audioEngineState == STATE_READY ) {
2238 		EventQueue::get_instance()->push_event( EVENT_STATE, STATE_READY );
2239 	}
2240 
2241 	// Unlocking earlier might execute the jack process() callback before we
2242 	// are fully initialized.
2243 	mx.unlock();
2244 	AudioEngine::get_instance()->unlock();
2245 
2246 	if ( m_pAudioDriver ) {
2247 		int res = m_pAudioDriver->connect();
2248 		if ( res != 0 ) {
2249 			audioEngine_raiseError( Hydrogen::ERROR_STARTING_DRIVER );
2250 			___ERRORLOG( "Error starting audio driver [audioDriver::connect()]" );
2251 			___ERRORLOG( "Using the NULL output audio driver" );
2252 
2253 			mx.relock();
2254 			delete m_pAudioDriver;
2255 			m_pAudioDriver = new NullDriver( audioEngine_process );
2256 			mx.unlock();
2257 			m_pAudioDriver->init( 0 );
2258 			m_pAudioDriver->connect();
2259 		}
2260 
2261 		if ( ( m_pMainBuffer_L = m_pAudioDriver->getOut_L() ) == nullptr ) {
2262 			___ERRORLOG( "m_pMainBuffer_L == NULL" );
2263 		}
2264 		if ( ( m_pMainBuffer_R = m_pAudioDriver->getOut_R() ) == nullptr ) {
2265 			___ERRORLOG( "m_pMainBuffer_R == NULL" );
2266 		}
2267 
2268 #ifdef H2CORE_HAVE_JACK
2269 		audioEngine_renameJackPorts( pSong );
2270 #endif
2271 
2272 		audioEngine_setupLadspaFX( m_pAudioDriver->getBufferSize() );
2273 	}
2274 
2275 
2276 }
2277 
audioEngine_stopAudioDrivers()2278 void audioEngine_stopAudioDrivers()
2279 {
2280 	___INFOLOG( "[audioEngine_stopAudioDrivers]" );
2281 
2282 	// check current state
2283 	if ( m_audioEngineState == STATE_PLAYING ) {
2284 		audioEngine_stop();
2285 	}
2286 
2287 	if ( ( m_audioEngineState != STATE_PREPARED )
2288 		 && ( m_audioEngineState != STATE_READY ) ) {
2289 		___ERRORLOG( QString( "Error: the audio engine is not in PREPARED"
2290 							  " or READY state. state=%1" )
2291 					 .arg( m_audioEngineState ) );
2292 		return;
2293 	}
2294 
2295 	// change the current audio engine state
2296 	m_audioEngineState = STATE_INITIALIZED;
2297 	EventQueue::get_instance()->push_event( EVENT_STATE, STATE_INITIALIZED );
2298 
2299 	AudioEngine::get_instance()->lock( RIGHT_HERE );
2300 
2301 	// delete MIDI driver
2302 	if ( m_pMidiDriver ) {
2303 		m_pMidiDriver->close();
2304 		delete m_pMidiDriver;
2305 		m_pMidiDriver = nullptr;
2306 		m_pMidiDriverOut = nullptr;
2307 	}
2308 
2309 	// delete audio driver
2310 	if ( m_pAudioDriver ) {
2311 		m_pAudioDriver->disconnect();
2312 		QMutexLocker mx( &mutex_OutputPointer );
2313 		delete m_pAudioDriver;
2314 		m_pAudioDriver = nullptr;
2315 		mx.unlock();
2316 	}
2317 
2318 	AudioEngine::get_instance()->unlock();
2319 }
2320 
2321 
2322 
2323 /// Restart all audio and midi drivers by calling first
2324 /// audioEngine_stopAudioDrivers() and then
2325 /// audioEngine_startAudioDrivers().
audioEngine_restartAudioDrivers()2326 void audioEngine_restartAudioDrivers()
2327 {
2328 	audioEngine_stopAudioDrivers();
2329 	audioEngine_startAudioDrivers();
2330 }
2331 
2332 //----------------------------------------------------------------------------
2333 //
2334 // Implementation of Hydrogen class
2335 //
2336 //----------------------------------------------------------------------------
2337 
2338 Hydrogen* Hydrogen::__instance = nullptr;
2339 const char* Hydrogen::__class_name = "Hydrogen";
2340 
Hydrogen()2341 Hydrogen::Hydrogen()
2342 	: Object( __class_name )
2343 {
2344 	if ( __instance ) {
2345 		ERRORLOG( "Hydrogen audio engine is already running" );
2346 		throw H2Exception( "Hydrogen audio engine is already running" );
2347 	}
2348 
2349 	INFOLOG( "[Hydrogen]" );
2350 
2351 	__song = nullptr;
2352 
2353 	m_bExportSessionIsActive = false;
2354 	m_pTimeline = new Timeline();
2355 	m_pCoreActionController = new CoreActionController();
2356 	m_bActiveGUI = false;
2357 	m_nMaxTimeHumanize = 2000;
2358 
2359 	initBeatcounter();
2360 	InstrumentComponent::setMaxLayers( Preferences::get_instance()->getMaxLayers() );
2361 	audioEngine_init();
2362 
2363 	// Prevent double creation caused by calls from MIDI thread
2364 	__instance = this;
2365 
2366 	audioEngine_startAudioDrivers();
2367 	for(int i = 0; i< MAX_INSTRUMENTS; i++){
2368 		m_nInstrumentLookupTable[i] = i;
2369 	}
2370 
2371 #ifdef H2CORE_HAVE_OSC
2372 	if( Preferences::get_instance()->getOscServerEnabled() )
2373 	{
2374 		OscServer* pOscServer = OscServer::get_instance();
2375 		pOscServer->start();
2376 	}
2377 #endif
2378 }
2379 
~Hydrogen()2380 Hydrogen::~Hydrogen()
2381 {
2382 	INFOLOG( "[~Hydrogen]" );
2383 
2384 #ifdef H2CORE_HAVE_OSC
2385 	NsmClient* pNsmClient = NsmClient::get_instance();
2386 	if( pNsmClient ) {
2387 		pNsmClient->shutdown();
2388 		delete pNsmClient;
2389 	}
2390 	OscServer* pOscServer = OscServer::get_instance();
2391 	if( pOscServer ) {
2392 		delete pOscServer;
2393 	}
2394 #endif
2395 
2396 	if ( m_audioEngineState == STATE_PLAYING ) {
2397 		audioEngine_stop();
2398 	}
2399 	removeSong();
2400 	audioEngine_stopAudioDrivers();
2401 	audioEngine_destroy();
2402 	__kill_instruments();
2403 
2404 	delete m_pCoreActionController;
2405 	delete m_pTimeline;
2406 
2407 	__instance = nullptr;
2408 }
2409 
create_instance()2410 void Hydrogen::create_instance()
2411 {
2412 	// Create all the other instances that we need
2413 	// ....and in the right order
2414 	Logger::create_instance();
2415 	MidiMap::create_instance();
2416 	Preferences::create_instance();
2417 	EventQueue::create_instance();
2418 	MidiActionManager::create_instance();
2419 
2420 #ifdef H2CORE_HAVE_OSC
2421 	NsmClient::create_instance();
2422 	OscServer::create_instance( Preferences::get_instance() );
2423 #endif
2424 
2425 	if ( __instance == nullptr ) {
2426 		__instance = new Hydrogen;
2427 	}
2428 
2429 	// See audioEngine_init() for:
2430 	// AudioEngine::create_instance();
2431 	// Effects::create_instance();
2432 	// Playlist::create_instance();
2433 }
2434 
initBeatcounter()2435 void Hydrogen::initBeatcounter()
2436 {
2437 	m_ntaktoMeterCompute = 1;
2438 	m_nbeatsToCount = 4;
2439 	m_nEventCount = 1;
2440 	m_nTempoChangeCounter = 0;
2441 	m_nBeatCount = 1;
2442 	m_nCoutOffset = 0;
2443 	m_nStartOffset = 0;
2444 }
2445 
2446 /// Start the internal sequencer
sequencer_play()2447 void Hydrogen::sequencer_play()
2448 {
2449 	Song* pSong = getSong();
2450 	pSong->get_pattern_list()->set_to_old();
2451 	m_pAudioDriver->play();
2452 }
2453 
2454 /// Stop the internal sequencer
sequencer_stop()2455 void Hydrogen::sequencer_stop()
2456 {
2457 	if( Hydrogen::get_instance()->getMidiOutput() != nullptr ){
2458 		Hydrogen::get_instance()->getMidiOutput()->handleQueueAllNoteOff();
2459 	}
2460 
2461 	m_pAudioDriver->stop();
2462 	Preferences::get_instance()->setRecordEvents(false);
2463 }
2464 
setPlaybackTrackState(const bool state)2465 bool Hydrogen::setPlaybackTrackState( const bool state )
2466 {
2467 	Song* pSong = getSong();
2468 	if ( pSong == nullptr ) {
2469 		return false;
2470 	}
2471 
2472 	return pSong->set_playback_track_enabled(state);
2473 }
2474 
loadPlaybackTrack(const QString filename)2475 void Hydrogen::loadPlaybackTrack( const QString filename )
2476 {
2477 	Song* pSong = getSong();
2478 	pSong->set_playback_track_filename(filename);
2479 
2480 	AudioEngine::get_instance()->get_sampler()->reinitialize_playback_track();
2481 }
2482 
setSong(Song * pSong)2483 void Hydrogen::setSong( Song *pSong )
2484 {
2485 	assert ( pSong );
2486 
2487 	// Move to the beginning.
2488 	setSelectedPatternNumber( 0 );
2489 
2490 	Song* pCurrentSong = getSong();
2491 	if ( pSong == pCurrentSong ) {
2492 		DEBUGLOG( "pSong == pCurrentSong" );
2493 		return;
2494 	}
2495 
2496 	if ( pCurrentSong ) {
2497 		/* NOTE:
2498 		 *       - this is actually some kind of cleanup
2499 		 *       - removeSong cares itself for acquiring a lock
2500 		 */
2501 		removeSong();
2502 
2503 		AudioEngine::get_instance()->lock( RIGHT_HERE );
2504 		delete pCurrentSong;
2505 		pCurrentSong = nullptr;
2506 
2507 		AudioEngine::get_instance()->unlock();
2508 
2509 	}
2510 
2511 	/* Reset GUI */
2512 	EventQueue::get_instance()->push_event( EVENT_SELECTED_PATTERN_CHANGED, -1 );
2513 	EventQueue::get_instance()->push_event( EVENT_PATTERN_CHANGED, -1 );
2514 	EventQueue::get_instance()->push_event( EVENT_SELECTED_INSTRUMENT_CHANGED, -1 );
2515 
2516 	// In order to allow functions like audioEngine_setupLadspaFX() to
2517 	// load the settings of the new song, like whether the LADSPA FX
2518 	// are activated, __song has to be set prior to the call of
2519 	// audioEngine_setSong().
2520 	__song = pSong;
2521 
2522 
2523 	// Update the audio engine to work with the new song.
2524 	audioEngine_setSong( pSong );
2525 
2526 	// load new playback track information
2527 	AudioEngine::get_instance()->get_sampler()->reinitialize_playback_track();
2528 
2529 	// Push current state of Hydrogen to attached control interfaces,
2530 	// like OSC clients.
2531 	m_pCoreActionController->initExternalControlInterfaces();
2532 }
2533 
2534 /* Mean: remove current song from memory */
removeSong()2535 void Hydrogen::removeSong()
2536 {
2537 	__song = nullptr;
2538 	audioEngine_removeSong();
2539 }
2540 
midi_noteOn(Note * note)2541 void Hydrogen::midi_noteOn( Note *note )
2542 {
2543 	audioEngine_noteOn( note );
2544 }
2545 
addRealtimeNote(int instrument,float velocity,float pan_L,float pan_R,float pitch,bool noteOff,bool forcePlay,int msg1)2546 void Hydrogen::addRealtimeNote(	int		instrument,
2547 								float	velocity,
2548 								float	pan_L,
2549 								float	pan_R,
2550 								float	pitch,
2551 								bool	noteOff,
2552 								bool	forcePlay,
2553 								int		msg1 )
2554 {
2555 	UNUSED( pitch );
2556 
2557 	Preferences *pPreferences = Preferences::get_instance();
2558 	unsigned int nRealColumn = 0;
2559 	unsigned res = pPreferences->getPatternEditorGridResolution();
2560 	int nBase = pPreferences->isPatternEditorUsingTriplets() ? 3 : 4;
2561 	int scalar = ( 4 * MAX_NOTES ) / ( res * nBase );
2562 	bool hearnote = forcePlay;
2563 	int currentPatternNumber;
2564 
2565 	AudioEngine::get_instance()->lock( RIGHT_HERE );
2566 
2567 	Song *pSong = getSong();
2568 	if ( !pPreferences->__playselectedinstrument ) {
2569 		if ( instrument >= ( int ) pSong->get_instrument_list()->size() ) {
2570 			// unused instrument
2571 			AudioEngine::get_instance()->unlock();
2572 			return;
2573 		}
2574 	}
2575 
2576 	// Get current partern and column, compensating for "lookahead" if required
2577 	const Pattern* currentPattern = nullptr;
2578 	unsigned int column = 0;
2579 	float fTickSize = m_pAudioDriver->m_transport.m_fTickSize;
2580 	unsigned int lookaheadTicks = calculateLookahead( fTickSize ) / fTickSize;
2581 	bool doRecord = pPreferences->getRecordEvents();
2582 	if ( pSong->get_mode() == Song::SONG_MODE && doRecord &&
2583 		 m_audioEngineState == STATE_PLAYING )
2584 	{
2585 
2586 		// Recording + song playback mode + actually playing
2587 		PatternList *pPatternList = pSong->get_pattern_list();
2588 		int ipattern = getPatternPos(); // playlist index
2589 		if ( ipattern < 0 || ipattern >= (int) pPatternList->size() ) {
2590 			AudioEngine::get_instance()->unlock(); // unlock the audio engine
2591 			return;
2592 		}
2593 		// Locate column -- may need to jump back in the pattern list
2594 		column = getTickPosition();
2595 		while ( column < lookaheadTicks ) {
2596 			ipattern -= 1;
2597 			if ( ipattern < 0 || ipattern >= (int) pPatternList->size() ) {
2598 				AudioEngine::get_instance()->unlock(); // unlock the audio engine
2599 				return;
2600 			}
2601 
2602 			// Convert from playlist index to actual pattern index
2603 			std::vector<PatternList*> *pColumns = pSong->get_pattern_group_vector();
2604 			for ( int i = 0; i <= ipattern; ++i ) {
2605 				PatternList *pColumn = ( *pColumns )[i];
2606 				currentPattern = pColumn->get( 0 );
2607 				currentPatternNumber = i;
2608 			}
2609 			column = column + currentPattern->get_length();
2610 			// WARNINGLOG( "Undoing lookahead: corrected (" + to_string( ipattern+1 ) +
2611 			// "," + to_string( (int) ( column - currentPattern->get_length() ) -
2612 			// (int) lookaheadTicks ) + ") -> (" + to_string(ipattern) +
2613 			// "," + to_string( (int) column - (int) lookaheadTicks ) + ")." );
2614 		}
2615 		column -= lookaheadTicks;
2616 		// Convert from playlist index to actual pattern index (if not already done above)
2617 		if ( currentPattern == nullptr ) {
2618 			std::vector<PatternList*> *pColumns = pSong->get_pattern_group_vector();
2619 			for ( int i = 0; i <= ipattern; ++i ) {
2620 				PatternList *pColumn = ( *pColumns )[i];
2621 				currentPattern = pColumn->get( 0 );
2622 				currentPatternNumber = i;
2623 			}
2624 		}
2625 
2626 		// Cancel recording if punch area disagrees
2627 		doRecord = pPreferences->inPunchArea( ipattern );
2628 
2629 	} else { // Not song-record mode
2630 		PatternList *pPatternList = pSong->get_pattern_list();
2631 
2632 		if ( ( m_nSelectedPatternNumber != -1 )
2633 			 && ( m_nSelectedPatternNumber < ( int )pPatternList->size() ) )
2634 		{
2635 			currentPattern = pPatternList->get( m_nSelectedPatternNumber );
2636 			currentPatternNumber = m_nSelectedPatternNumber;
2637 		}
2638 
2639 		if ( ! currentPattern ) {
2640 			AudioEngine::get_instance()->unlock(); // unlock the audio engine
2641 			return;
2642 		}
2643 
2644 		// Locate column -- may need to wrap around end of pattern
2645 		column = getTickPosition();
2646 		if ( column >= lookaheadTicks ) {
2647 			column -= lookaheadTicks;
2648 		} else {
2649 			lookaheadTicks %= currentPattern->get_length();
2650 			column = (column + currentPattern->get_length() - lookaheadTicks)
2651 					% currentPattern->get_length();
2652 		}
2653 	}
2654 
2655 	nRealColumn = getRealtimeTickPosition();
2656 
2657 	if ( pPreferences->getQuantizeEvents() ) {
2658 		// quantize it to scale
2659 		unsigned qcolumn = ( unsigned )::round( column / ( double )scalar ) * scalar;
2660 
2661 		//we have to make sure that no beat is added on the last displayed note in a bar
2662 		//for example: if the pattern has 4 beats, the editor displays 5 beats, so we should avoid adding beats an note 5.
2663 		if ( qcolumn == currentPattern->get_length() ) qcolumn = 0;
2664 		column = qcolumn;
2665 	}
2666 
2667 	unsigned position = column;
2668 	m_naddrealtimenotetickposition = column;
2669 
2670 	Instrument *instrRef = nullptr;
2671 	if ( pSong ) {
2672 		//getlookuptable index = instrument+36, ziel wert = der entprechende wert -36
2673 		instrRef = pSong->get_instrument_list()->get( m_nInstrumentLookupTable[ instrument ] );
2674 	}
2675 
2676 	if ( currentPattern && ( getState() == STATE_PLAYING ) ) {
2677 		if ( doRecord && pPreferences->getDestructiveRecord() && pPreferences->m_nRecPreDelete>0 ) {
2678 			// Delete notes around current note if option toggled
2679 			int postdelete = 0;
2680 			int predelete = 0;
2681 			int prefpredelete = pPreferences->m_nRecPreDelete-1;
2682 			int prefpostdelete = pPreferences->m_nRecPostDelete;
2683 			int length = currentPattern->get_length();
2684 			bool fp = false;
2685 			postdelete = column;
2686 
2687 			switch (prefpredelete) {
2688 			case 0: predelete = length ; postdelete = 0; fp = true; break;
2689 			case 1: predelete = length ; fp = true; break;
2690 			case 2: predelete = length / 2; fp = true; break;
2691 			case 3: predelete = length / 4; fp = true; break;
2692 			case 4: predelete = length / 8; fp = true; break;
2693 			case 5: predelete = length / 16; fp = true; break;
2694 			case 6: predelete = length / 32; fp = true; break;
2695 			case 7: predelete = length / 64; fp = true; break;
2696 			case 8: predelete = length / 64; break;
2697 			case 9: predelete = length / 32; break;
2698 			case 10: predelete = length / 16; break;
2699 			case 11: predelete = length / 8; break;
2700 			case 12: predelete = length / 4; break;
2701 			case 13: predelete = length / 2; break;
2702 			case 14: predelete = length; break;
2703 			case 15: break;
2704 			default : predelete = 1; break;
2705 			}
2706 
2707 			if (!fp ) {
2708 				switch (prefpostdelete) {
2709 				case 0: postdelete = column; break;
2710 				case 1: postdelete -= length / 64; break;
2711 				case 2: postdelete -= length / 32; break;
2712 				case 3: postdelete -= length / 16; break;
2713 				case 4: postdelete -= length / 8; break;
2714 				case 5: postdelete -= length / 4; break;
2715 				case 6: postdelete -= length / 2; break;
2716 				case 7: postdelete -= length ; break;
2717 				default : postdelete = column; break;
2718 				}
2719 
2720 				if (postdelete<0) postdelete = 0;
2721 			}
2722 
2723 			Pattern::notes_t* notes = (Pattern::notes_t*)currentPattern->get_notes();
2724 			FOREACH_NOTE_IT_BEGIN_END(notes,it) {
2725 				Note *pNote = it->second;
2726 				assert( pNote );
2727 
2728 				int currentPosition = pNote->get_position();
2729 				if ( pPreferences->__playselectedinstrument ) {//fix me
2730 					if ( pSong->get_instrument_list()->get( getSelectedInstrumentNumber()) == pNote->get_instrument() )
2731 					{
2732 						if (prefpredelete>=1 && prefpredelete <=14 ) pNote->set_just_recorded( false );
2733 
2734 						if ( (prefpredelete == 15) && (pNote->get_just_recorded() == false))
2735 						{
2736 							bool replaceExisting = false;
2737 							if (column == currentPosition) replaceExisting = true;
2738 							EventQueue::AddMidiNoteVector noteAction;
2739 							noteAction.m_column = currentPosition;
2740 							noteAction.m_row = pNote->get_instrument_id(); //getSelectedInstrumentNumber();
2741 							noteAction.m_pattern = currentPatternNumber;
2742 							noteAction.f_velocity = velocity;
2743 							noteAction.f_pan_L = pan_L;
2744 							noteAction.f_pan_R = pan_R;
2745 							noteAction.m_length = -1;
2746 							int divider = msg1 / 12;
2747 							noteAction.no_octaveKeyVal = (Note::Octave)(divider -3);
2748 							noteAction.nk_noteKeyVal = (Note::Key)(msg1 - (12 * divider));
2749 							noteAction.b_isInstrumentMode = replaceExisting;
2750 							noteAction.b_isMidi = true;
2751 							noteAction.b_noteExist = replaceExisting;
2752 							EventQueue::get_instance()->m_addMidiNoteVector.push_back(noteAction);
2753 							continue;
2754 						}
2755 						if ( ( pNote->get_just_recorded() == false )
2756 							 && (static_cast<int>( pNote->get_position() ) >= postdelete
2757 								 && pNote->get_position() < column + predelete +1 )
2758 							 ) {
2759 							bool replaceExisting = false;
2760 							if ( column == currentPosition ) {
2761 								replaceExisting = true;
2762 							}
2763 							EventQueue::AddMidiNoteVector noteAction;
2764 							noteAction.m_column = currentPosition;
2765 							noteAction.m_row = pNote->get_instrument_id(); //getSelectedInstrumentNumber();
2766 							noteAction.m_pattern = currentPatternNumber;
2767 							noteAction.f_velocity = velocity;
2768 							noteAction.f_pan_L = pan_L;
2769 							noteAction.f_pan_R = pan_R;
2770 							noteAction.m_length = -1;
2771 							int divider = msg1 / 12;
2772 							noteAction.no_octaveKeyVal = (Note::Octave)(divider -3);
2773 							noteAction.nk_noteKeyVal = (Note::Key)(msg1 - (12 * divider));
2774 							noteAction.b_isInstrumentMode = replaceExisting;
2775 							noteAction.b_isMidi = true;
2776 							noteAction.b_noteExist = replaceExisting;
2777 							EventQueue::get_instance()->m_addMidiNoteVector.push_back(noteAction);
2778 						}
2779 					}
2780 					continue;
2781 				}
2782 
2783 				if ( !fp && pNote->get_instrument() != instrRef ) {
2784 					continue;
2785 				}
2786 
2787 				if (prefpredelete>=1 && prefpredelete <=14 ) {
2788 					pNote->set_just_recorded( false );
2789 				}
2790 
2791 				if ( (prefpredelete == 15) && (pNote->get_just_recorded() == false)) {
2792 					bool replaceExisting = false;
2793 					if (column == currentPosition) replaceExisting = true;
2794 					EventQueue::AddMidiNoteVector noteAction;
2795 					noteAction.m_column = currentPosition;
2796 					noteAction.m_row =  pNote->get_instrument_id();//m_nInstrumentLookupTable[ instrument ];
2797 					noteAction.m_pattern = currentPatternNumber;
2798 					noteAction.f_velocity = velocity;
2799 					noteAction.f_pan_L = pan_L;
2800 					noteAction.f_pan_R = pan_R;
2801 					noteAction.m_length = -1;
2802 					noteAction.no_octaveKeyVal = (Note::Octave)0;
2803 					noteAction.nk_noteKeyVal = (Note::Key)0;
2804 					noteAction.b_isInstrumentMode = false;
2805 					noteAction.b_isMidi = false;
2806 					noteAction.b_noteExist = replaceExisting;
2807 					EventQueue::get_instance()->m_addMidiNoteVector.push_back(noteAction);
2808 					continue;
2809 				}
2810 
2811 				if ( ( pNote->get_just_recorded() == false )
2812 					 && ( static_cast<int>( pNote->get_position() ) >= postdelete
2813 						  && pNote->get_position() <column + predelete +1 )
2814 					 ) {
2815 					bool replaceExisting = false;
2816 					if (column == currentPosition) replaceExisting = true;
2817 					EventQueue::AddMidiNoteVector noteAction;
2818 					noteAction.m_column = currentPosition;
2819 					noteAction.m_row =  pNote->get_instrument_id();//m_nInstrumentLookupTable[ instrument ];
2820 					noteAction.m_pattern = currentPatternNumber;
2821 					noteAction.f_velocity = velocity;
2822 					noteAction.f_pan_L = pan_L;
2823 					noteAction.f_pan_R = pan_R;
2824 					noteAction.m_length = -1;
2825 					noteAction.no_octaveKeyVal = (Note::Octave)0;
2826 					noteAction.nk_noteKeyVal = (Note::Key)0;
2827 					noteAction.b_isInstrumentMode = false;
2828 					noteAction.b_isMidi = false;
2829 					noteAction.b_noteExist = replaceExisting;
2830 					EventQueue::get_instance()->m_addMidiNoteVector.push_back(noteAction);
2831 				}
2832 			} /* FOREACH */
2833 		} /* if dorecord ... */
2834 
2835 		assert( currentPattern );
2836 		if ( doRecord ) {
2837 			EventQueue::AddMidiNoteVector noteAction;
2838 			noteAction.m_column = column;
2839 			noteAction.m_pattern = currentPatternNumber;
2840 			noteAction.f_velocity = velocity;
2841 			noteAction.f_pan_L = pan_L;
2842 			noteAction.f_pan_R = pan_R;
2843 			noteAction.m_length = -1;
2844 			noteAction.b_isMidi = true;
2845 
2846 			if ( pPreferences->__playselectedinstrument ) {
2847 				instrRef = pSong->get_instrument_list()->get( getSelectedInstrumentNumber() );
2848 				int divider = msg1 / 12;
2849 				noteAction.m_row = getSelectedInstrumentNumber();
2850 				noteAction.no_octaveKeyVal = (Note::Octave)(divider -3);
2851 				noteAction.nk_noteKeyVal = (Note::Key)(msg1 - (12 * divider));
2852 				noteAction.b_isInstrumentMode = true;
2853 			} else {
2854 				instrRef = pSong->get_instrument_list()->get( m_nInstrumentLookupTable[ instrument ] );
2855 				noteAction.m_row =  m_nInstrumentLookupTable[ instrument ];
2856 				noteAction.no_octaveKeyVal = (Note::Octave)0;
2857 				noteAction.nk_noteKeyVal = (Note::Key)0;
2858 				noteAction.b_isInstrumentMode = false;
2859 			}
2860 
2861 			Note* pNoteold = currentPattern->find_note( noteAction.m_column, -1, instrRef, noteAction.nk_noteKeyVal, noteAction.no_octaveKeyVal );
2862 			noteAction.b_noteExist = ( pNoteold ) ? true : false;
2863 
2864 			EventQueue::get_instance()->m_addMidiNoteVector.push_back(noteAction);
2865 
2866 			// hear note if its not in the future
2867 			if ( pPreferences->getHearNewNotes() && position <= getTickPosition() ) {
2868 				hearnote = true;
2869 			}
2870 		} /* if doRecord */
2871 	} else if ( pPreferences->getHearNewNotes() ) {
2872 			hearnote = true;
2873 	} /* if .. STATE_PLAYING */
2874 
2875 	if ( !pPreferences->__playselectedinstrument ) {
2876 		if ( hearnote && instrRef ) {
2877 			Note *pNote2 = new Note( instrRef, nRealColumn, velocity, pan_L, pan_R, -1, 0 );
2878 			midi_noteOn( pNote2 );
2879 		}
2880 	} else if ( hearnote  ) {
2881 		Instrument* pInstr = pSong->get_instrument_list()->get( getSelectedInstrumentNumber() );
2882 		Note *pNote2 = new Note( pInstr, nRealColumn, velocity, pan_L, pan_R, -1, 0 );
2883 
2884 		int divider = msg1 / 12;
2885 		Note::Octave octave = (Note::Octave)(divider -3);
2886 		Note::Key notehigh = (Note::Key)(msg1 - (12 * divider));
2887 
2888 		//ERRORLOG( QString( "octave: %1, note: %2, instrument %3" ).arg( octave ).arg(notehigh).arg(instrument));
2889 		pNote2->set_midi_info( notehigh, octave, msg1 );
2890 		midi_noteOn( pNote2 );
2891 	}
2892 
2893 	AudioEngine::get_instance()->unlock(); // unlock the audio engine
2894 }
2895 
getMasterPeak_L()2896 float Hydrogen::getMasterPeak_L()
2897 {
2898 	return m_fMasterPeak_L;
2899 }
2900 
getMasterPeak_R()2901 float Hydrogen::getMasterPeak_R()
2902 {
2903 	return m_fMasterPeak_R;
2904 }
2905 
getTickPosition()2906 unsigned long Hydrogen::getTickPosition()
2907 {
2908 	return m_nPatternTickPosition;
2909 }
2910 
getRealtimeTickPosition()2911 unsigned long Hydrogen::getRealtimeTickPosition()
2912 {
2913 	// Get the realtime transport position in frames and convert
2914 	// it into ticks.
2915 	unsigned int initTick = ( unsigned int )( getRealtimeFrames() /
2916 						  m_pAudioDriver->m_transport.m_fTickSize );
2917 	unsigned long retTick;
2918 
2919 	struct timeval currtime;
2920 	struct timeval deltatime;
2921 
2922 	double sampleRate = ( double ) m_pAudioDriver->getSampleRate();
2923 	gettimeofday ( &currtime, nullptr );
2924 
2925 	// Definition macro from timehelper.h calculating the time
2926 	// difference between `currtime` and `m_currentTickTime`
2927 	// (`currtime`-`m_currentTickTime`) and storing the results in
2928 	// `deltatime`. It uses both the .tv_sec (seconds) and
2929 	// .tv_usec (microseconds) members of the timeval struct.
2930 	timersub( &currtime, &m_currentTickTime, &deltatime );
2931 
2932 	// add a buffers worth for jitter resistance
2933 	double deltaSec =
2934 			( double ) deltatime.tv_sec
2935 			+ ( deltatime.tv_usec / 1000000.0 )
2936 			+ ( m_pAudioDriver->getBufferSize() / ( double )sampleRate );
2937 
2938 	retTick = ( unsigned long ) ( ( sampleRate / ( double ) m_pAudioDriver->m_transport.m_fTickSize ) * deltaSec );
2939 
2940 	retTick += initTick;
2941 
2942 	return retTick;
2943 }
2944 
2945 // TODO: make this function inline in the header
getCurrentPatternList()2946 PatternList* Hydrogen::getCurrentPatternList()
2947 {
2948 	return m_pPlayingPatterns;
2949 }
2950 
2951 // TODO: make this function inline in the header
getNextPatterns()2952 PatternList * Hydrogen::getNextPatterns()
2953 {
2954 	return m_pNextPatterns;
2955 }
2956 
sequencer_setNextPattern(int pos)2957 void Hydrogen::sequencer_setNextPattern( int pos )
2958 {
2959 	AudioEngine::get_instance()->lock( RIGHT_HERE );
2960 
2961 	Song* pSong = getSong();
2962 	if ( pSong && pSong->get_mode() == Song::PATTERN_MODE ) {
2963 		PatternList* pPatternList = pSong->get_pattern_list();
2964 
2965 		// Check whether `pos` is in range of the pattern list.
2966 		if ( ( pos >= 0 ) && ( pos < ( int )pPatternList->size() ) ) {
2967 			Pattern* pPattern = pPatternList->get( pos );
2968 
2969 			// If the pattern is already in the `m_pNextPatterns`, it
2970 			// will be removed from the latter and its `del()` method
2971 			// will return a pointer to the very pattern. The if
2972 			// clause is therefore only entered if the `pPattern` was
2973 			// not already present.
2974 			if ( m_pNextPatterns->del( pPattern ) == nullptr ) {
2975 				m_pNextPatterns->add( pPattern );
2976 			}
2977 		} else {
2978 			ERRORLOG( QString( "pos not in patternList range. pos=%1 patternListSize=%2" )
2979 					  .arg( pos ).arg( pPatternList->size() ) );
2980 			m_pNextPatterns->clear();
2981 		}
2982 	} else {
2983 		ERRORLOG( "can't set next pattern in song mode" );
2984 		m_pNextPatterns->clear();
2985 	}
2986 
2987 	AudioEngine::get_instance()->unlock();
2988 }
2989 
sequencer_setOnlyNextPattern(int pos)2990 void Hydrogen::sequencer_setOnlyNextPattern( int pos )
2991 {
2992 	AudioEngine::get_instance()->lock( RIGHT_HERE );
2993 
2994 	Song* pSong = getSong();
2995 	if ( pSong && pSong->get_mode() == Song::PATTERN_MODE ) {
2996 		PatternList* pPatternList = pSong->get_pattern_list();
2997 
2998 		// Clear the list of all patterns scheduled to be processed
2999 		// next and fill them with those currently played.
3000 		m_pNextPatterns->clear( );
3001 		Pattern* pPattern;
3002 		for ( int nPattern = 0 ; nPattern < (int)m_pPlayingPatterns->size() ; ++nPattern ) {
3003 			pPattern = m_pPlayingPatterns->get( nPattern );
3004 			m_pNextPatterns->add( pPattern );
3005 		}
3006 
3007 		// Appending the requested pattern.
3008 		pPattern = pPatternList->get( pos );
3009 		m_pNextPatterns->add( pPattern );
3010 	} else {
3011 		ERRORLOG( "can't set next pattern in song mode" );
3012 		m_pNextPatterns->clear();
3013 	}
3014 
3015 	AudioEngine::get_instance()->unlock();
3016 }
3017 
3018 // TODO: make variable name and getter/setter consistent.
getPatternPos()3019 int Hydrogen::getPatternPos()
3020 {
3021 	return m_nSongPos;
3022 }
3023 
3024 /* Return pattern for selected song tick position */
getPosForTick(unsigned long TickPos,int * nPatternStartTick)3025 int Hydrogen::getPosForTick( unsigned long TickPos, int* nPatternStartTick )
3026 {
3027 	Song* pSong = getSong();
3028 	if ( pSong == nullptr ) {
3029 		return 0;
3030 	}
3031 
3032 	return findPatternInTick( TickPos, pSong->is_loop_enabled(), nPatternStartTick );
3033 }
3034 
calculateLeadLagFactor(float fTickSize)3035 int Hydrogen::calculateLeadLagFactor( float fTickSize ){
3036 	return fTickSize * 5;
3037 }
3038 
calculateLookahead(float fTickSize)3039 int Hydrogen::calculateLookahead( float fTickSize ){
3040 	// Introduce a lookahead of 5 ticks. Since the ticksize is
3041 	// depending of the current tempo of the song, this component does
3042 	// make the lookahead dynamic.
3043 	int nLeadLagFactor = calculateLeadLagFactor( fTickSize );
3044 
3045 	// We need to look ahead in the song for notes with negative offsets
3046 	// from LeadLag or Humanize.
3047 	return nLeadLagFactor + m_nMaxTimeHumanize + 1;
3048 }
3049 
restartDrivers()3050 void Hydrogen::restartDrivers()
3051 {
3052 	audioEngine_restartAudioDrivers();
3053 }
3054 
startExportSession(int sampleRate,int sampleDepth)3055 void Hydrogen::startExportSession(int sampleRate, int sampleDepth )
3056 {
3057 	if ( getState() == STATE_PLAYING ) {
3058 		sequencer_stop();
3059 	}
3060 
3061 	unsigned nSamplerate = (unsigned) sampleRate;
3062 
3063 	AudioEngine::get_instance()->get_sampler()->stop_playing_notes();
3064 
3065 	Song* pSong = getSong();
3066 
3067 	m_oldEngineMode = pSong->get_mode();
3068 	m_bOldLoopEnabled = pSong->is_loop_enabled();
3069 
3070 	pSong->set_mode( Song::SONG_MODE );
3071 	pSong->set_loop_enabled( true );
3072 
3073 	/*
3074 	 * Currently an audio driver is loaded
3075 	 * which is not the DiskWriter driver.
3076 	 * Stop the current driver and fire up the DiskWriter.
3077 	 */
3078 	audioEngine_stopAudioDrivers();
3079 
3080 	m_pAudioDriver = new DiskWriterDriver( audioEngine_process, nSamplerate, sampleDepth );
3081 
3082 	m_bExportSessionIsActive = true;
3083 }
3084 
stopExportSession()3085 void Hydrogen::stopExportSession()
3086 {
3087 	m_bExportSessionIsActive = false;
3088 
3089  	audioEngine_stopAudioDrivers();
3090 
3091 	delete m_pAudioDriver;
3092 	m_pAudioDriver = nullptr;
3093 
3094 	Song* pSong = getSong();
3095 	pSong->set_mode( m_oldEngineMode );
3096 	pSong->set_loop_enabled( m_bOldLoopEnabled );
3097 
3098 	audioEngine_startAudioDrivers();
3099 
3100 	if ( m_pAudioDriver ) {
3101 		m_pAudioDriver->setBpm( pSong->__bpm );
3102 	} else {
3103 		ERRORLOG( "m_pAudioDriver = NULL" );
3104 	}
3105 }
3106 
3107 /// Export a song to a wav file
startExportSong(const QString & filename)3108 void Hydrogen::startExportSong( const QString& filename)
3109 {
3110 	// reset
3111 	m_pAudioDriver->m_transport.m_nFrames = 0; // reset total frames
3112 	// TODO: not -1 instead?
3113 	m_nSongPos = 0;
3114 	m_nPatternTickPosition = 0;
3115 	m_audioEngineState = STATE_PLAYING;
3116 	m_nPatternStartTick = -1;
3117 
3118 	Preferences *pPref = Preferences::get_instance();
3119 
3120 	int res = m_pAudioDriver->init( pPref->m_nBufferSize );
3121 	if ( res != 0 ) {
3122 		ERRORLOG( "Error starting disk writer driver [DiskWriterDriver::init()]" );
3123 	}
3124 
3125 	m_pMainBuffer_L = m_pAudioDriver->getOut_L();
3126 	m_pMainBuffer_R = m_pAudioDriver->getOut_R();
3127 
3128 	audioEngine_setupLadspaFX( m_pAudioDriver->getBufferSize() );
3129 
3130 	audioEngine_seek( 0, false );
3131 
3132 	DiskWriterDriver* pDiskWriterDriver = (DiskWriterDriver*) m_pAudioDriver;
3133 	pDiskWriterDriver->setFileName( filename );
3134 
3135 	res = m_pAudioDriver->connect();
3136 	if ( res != 0 ) {
3137 		ERRORLOG( "Error starting disk writer driver [DiskWriterDriver::connect()]" );
3138 	}
3139 }
3140 
stopExportSong()3141 void Hydrogen::stopExportSong()
3142 {
3143 	if ( m_pAudioDriver->class_name() != DiskWriterDriver::class_name() ) {
3144 		return;
3145 	}
3146 
3147 	AudioEngine::get_instance()->get_sampler()->stop_playing_notes();
3148 
3149 	m_pAudioDriver->disconnect();
3150 
3151 	m_nSongPos = -1;
3152 	m_nPatternTickPosition = 0;
3153 }
3154 
3155 /// Used to display audio driver info
getAudioOutput()3156 AudioOutput* Hydrogen::getAudioOutput()
3157 {
3158 	return m_pAudioDriver;
3159 }
3160 
3161 /// Used to display midi driver info
getMidiInput()3162 MidiInput* Hydrogen::getMidiInput()
3163 {
3164 	return m_pMidiDriver;
3165 }
3166 
getMidiOutput()3167 MidiOutput* Hydrogen::getMidiOutput()
3168 {
3169 	return m_pMidiDriverOut;
3170 }
3171 
setMasterPeak_L(float value)3172 void Hydrogen::setMasterPeak_L( float value )
3173 {
3174 	m_fMasterPeak_L = value;
3175 }
3176 
setMasterPeak_R(float value)3177 void Hydrogen::setMasterPeak_R( float value )
3178 {
3179 	m_fMasterPeak_R = value;
3180 }
3181 
getState()3182 int Hydrogen::getState()
3183 {
3184 	return m_audioEngineState;
3185 }
3186 
setCurrentPatternList(PatternList * pPatternList)3187 void Hydrogen::setCurrentPatternList( PatternList *pPatternList )
3188 {
3189 	AudioEngine::get_instance()->lock( RIGHT_HERE );
3190 	m_pPlayingPatterns = pPatternList;
3191 	EventQueue::get_instance()->push_event( EVENT_PATTERN_CHANGED, -1 );
3192 	AudioEngine::get_instance()->unlock();
3193 }
3194 
getProcessTime()3195 float Hydrogen::getProcessTime()
3196 {
3197 	return m_fProcessTime;
3198 }
3199 
getMaxProcessTime()3200 float Hydrogen::getMaxProcessTime()
3201 {
3202 	return m_fMaxProcessTime;
3203 }
3204 
3205 
3206 // Setting conditional to true will keep instruments that have notes if new kit has less instruments than the old one
loadDrumkit(Drumkit * pDrumkitInfo)3207 int Hydrogen::loadDrumkit( Drumkit *pDrumkitInfo )
3208 {
3209 	return loadDrumkit( pDrumkitInfo, true );
3210 }
3211 
loadDrumkit(Drumkit * pDrumkitInfo,bool conditional)3212 int Hydrogen::loadDrumkit( Drumkit *pDrumkitInfo, bool conditional )
3213 {
3214 	assert ( pDrumkitInfo );
3215 
3216 	int old_ae_state = m_audioEngineState;
3217 	if( m_audioEngineState >= STATE_READY ) {
3218 		m_audioEngineState = STATE_PREPARED;
3219 	}
3220 
3221 	INFOLOG( pDrumkitInfo->get_name() );
3222 	m_currentDrumkit = pDrumkitInfo->get_name();
3223 
3224 	std::vector<DrumkitComponent*>* pSongCompoList= getSong()->get_components();
3225 	std::vector<DrumkitComponent*>* pDrumkitCompoList = pDrumkitInfo->get_components();
3226 
3227 	AudioEngine::get_instance()->lock( RIGHT_HERE );
3228 	for( auto &pComponent : *pSongCompoList ){
3229 		delete pComponent;
3230 	}
3231 	pSongCompoList->clear();
3232 	AudioEngine::get_instance()->unlock();
3233 
3234 	for (std::vector<DrumkitComponent*>::iterator it = pDrumkitCompoList->begin() ; it != pDrumkitCompoList->end(); ++it) {
3235 		DrumkitComponent* pSrcComponent = *it;
3236 		DrumkitComponent* pNewComponent = new DrumkitComponent( pSrcComponent->get_id(), pSrcComponent->get_name() );
3237 		pNewComponent->load_from( pSrcComponent );
3238 
3239 		pSongCompoList->push_back( pNewComponent );
3240 	}
3241 
3242 	//current instrument list
3243 	InstrumentList *pSongInstrList = getSong()->get_instrument_list();
3244 
3245 	//new instrument list
3246 	InstrumentList *pDrumkitInstrList = pDrumkitInfo->get_instruments();
3247 
3248 	/*
3249 	 * If the old drumkit is bigger then the new drumkit,
3250 	 * delete all instruments with a bigger pos then
3251 	 * pDrumkitInstrList->size(). Otherwise the instruments
3252 	 * from our old instrumentlist with
3253 	 * pos > pDrumkitInstrList->size() stay in the
3254 	 * new instrumentlist
3255 	 *
3256 	 * wolke: info!
3257 	 * this has moved to the end of this function
3258 	 * because we get lost objects in memory
3259 	 * now:
3260 	 * 1. the new drumkit will loaded
3261 	 * 2. all not used instruments will complete deleted
3262 	 * old function:
3263 	 * while ( pDrumkitInstrList->size() < songInstrList->size() )
3264 	 * {
3265 	 *  songInstrList->del(songInstrList->size() - 1);
3266 	 * }
3267 	 */
3268 
3269 	//needed for the new delete function
3270 	int instrumentDiff =  pSongInstrList->size() - pDrumkitInstrList->size();
3271 
3272 	for ( unsigned nInstr = 0; nInstr < pDrumkitInstrList->size(); ++nInstr ) {
3273 		Instrument *pInstr = nullptr;
3274 		if ( nInstr < pSongInstrList->size() ) {
3275 			//instrument exists already
3276 			pInstr = pSongInstrList->get( nInstr );
3277 			assert( pInstr );
3278 		} else {
3279 			pInstr = new Instrument();
3280 			// The instrument isn't playing yet; no need for locking
3281 			// :-) - Jakob Lund.  AudioEngine::get_instance()->lock(
3282 			// "Hydrogen::loadDrumkit" );
3283 			pSongInstrList->add( pInstr );
3284 			// AudioEngine::get_instance()->unlock();
3285 		}
3286 
3287 		Instrument *pNewInstr = pDrumkitInstrList->get( nInstr );
3288 		assert( pNewInstr );
3289 		INFOLOG( QString( "Loading instrument (%1 of %2) [%3]" )
3290 				 .arg( nInstr + 1 )
3291 				 .arg( pDrumkitInstrList->size() )
3292 				 .arg( pNewInstr->get_name() ) );
3293 
3294 		// Moved code from here right into the Instrument class - Jakob Lund.
3295 		pInstr->load_from( pDrumkitInfo, pNewInstr );
3296 	}
3297 
3298 	//wolke: new delete function
3299 	if ( instrumentDiff >= 0 ) {
3300 		for ( int i = 0; i < instrumentDiff ; i++ ){
3301 			removeInstrument(
3302 						getSong()->get_instrument_list()->size() - 1,
3303 						conditional
3304 						);
3305 		}
3306 	}
3307 
3308 #ifdef H2CORE_HAVE_JACK
3309 	AudioEngine::get_instance()->lock( RIGHT_HERE );
3310 	renameJackPorts( getSong() );
3311 	AudioEngine::get_instance()->unlock();
3312 #endif
3313 
3314 	m_audioEngineState = old_ae_state;
3315 
3316 	m_pCoreActionController->initExternalControlInterfaces();
3317 
3318 	return 0;	//ok
3319 }
3320 
3321 // This will check if an instrument has any notes
instrumentHasNotes(Instrument * pInst)3322 bool Hydrogen::instrumentHasNotes( Instrument *pInst )
3323 {
3324 	Song* pSong = getSong();
3325 	PatternList* pPatternList = pSong->get_pattern_list();
3326 
3327 	for ( int nPattern = 0 ; nPattern < (int)pPatternList->size() ; ++nPattern )
3328 	{
3329 		if( pPatternList->get( nPattern )->references( pInst ) )
3330 		{
3331 			DEBUGLOG("Instrument " + pInst->get_name() + " has notes" );
3332 			return true;
3333 		}
3334 	}
3335 
3336 	// no notes for this instrument
3337 	return false;
3338 }
3339 
3340 //this is also a new function and will used from the new delete function in
3341 //Hydrogen::loadDrumkit to delete the instruments by number
removeInstrument(int instrumentNumber,bool conditional)3342 void Hydrogen::removeInstrument( int instrumentNumber, bool conditional )
3343 {
3344 	Song* pSong = getSong();
3345 	Instrument *pInstr = pSong->get_instrument_list()->get( instrumentNumber );
3346 	PatternList* pPatternList = pSong->get_pattern_list();
3347 
3348 	if ( conditional ) {
3349 		// new! this check if a pattern has an active note if there is an note
3350 		//inside the pattern the instrument would not be deleted
3351 		for ( int nPattern = 0 ;
3352 			  nPattern < (int)pPatternList->size() ;
3353 			  ++nPattern ) {
3354 			if( pPatternList
3355 					->get( nPattern )
3356 					->references( pInstr ) ) {
3357 				DEBUGLOG("Keeping instrument #" + QString::number( instrumentNumber ) );
3358 				return;
3359 			}
3360 		}
3361 	} else {
3362 		getSong()->purge_instrument( pInstr );
3363 	}
3364 
3365 	InstrumentList* pList = pSong->get_instrument_list();
3366 	if ( pList->size()==1 ){
3367 		AudioEngine::get_instance()->lock( RIGHT_HERE );
3368 		Instrument* pInstr = pList->get( 0 );
3369 		pInstr->set_name( (QString( "Instrument 1" )) );
3370 		for (std::vector<InstrumentComponent*>::iterator it = pInstr->get_components()->begin() ; it != pInstr->get_components()->end(); ++it) {
3371 			InstrumentComponent* pCompo = *it;
3372 			// remove all layers
3373 			for ( int nLayer = 0; nLayer < InstrumentComponent::getMaxLayers(); nLayer++ ) {
3374 				pCompo->set_layer( nullptr, nLayer );
3375 			}
3376 		}
3377 		AudioEngine::get_instance()->unlock();
3378 		EventQueue::get_instance()->push_event( EVENT_SELECTED_INSTRUMENT_CHANGED, -1 );
3379 		INFOLOG("clear last instrument to empty instrument 1 instead delete the last instrument");
3380 		return;
3381 	}
3382 
3383 	// if the instrument was the last on the instruments list, select the
3384 	// next-last
3385 	if ( instrumentNumber >= (int)getSong()->get_instrument_list()->size() - 1 ) {
3386 		Hydrogen::get_instance()->setSelectedInstrumentNumber(
3387 					std::max(0, instrumentNumber - 1 )
3388 					);
3389 	}
3390 	//
3391 	// delete the instrument from the instruments list
3392 	AudioEngine::get_instance()->lock( RIGHT_HERE );
3393 	getSong()->get_instrument_list()->del( instrumentNumber );
3394 	// Ensure the selected instrument is not a deleted one
3395 	setSelectedInstrumentNumber( instrumentNumber - 1 );
3396 	getSong()->set_is_modified( true );
3397 	AudioEngine::get_instance()->unlock();
3398 
3399 	// At this point the instrument has been removed from both the
3400 	// instrument list and every pattern in the song.  Hence there's no way
3401 	// (NOTE) to play on that instrument, and once all notes have stopped
3402 	// playing it will be save to delete.
3403 	// the ugly name is just for debugging...
3404 	QString xxx_name = QString( "XXX_%1" ) . arg( pInstr->get_name() );
3405 	pInstr->set_name( xxx_name );
3406 	__instrument_death_row.push_back( pInstr );
3407 	__kill_instruments(); // checks if there are still notes.
3408 
3409 	// this will force a GUI update.
3410 	EventQueue::get_instance()->push_event( EVENT_SELECTED_INSTRUMENT_CHANGED, -1 );
3411 }
3412 
raiseError(unsigned nErrorCode)3413 void Hydrogen::raiseError( unsigned nErrorCode )
3414 {
3415 	audioEngine_raiseError( nErrorCode );
3416 }
3417 
getTotalFrames()3418 unsigned long Hydrogen::getTotalFrames()
3419 {
3420 	return m_pAudioDriver->m_transport.m_nFrames;
3421 }
3422 
setRealtimeFrames(unsigned long frames)3423 void Hydrogen::setRealtimeFrames( unsigned long frames )
3424 {
3425 	m_nRealtimeFrames = frames;
3426 }
3427 
getRealtimeFrames()3428 unsigned long Hydrogen::getRealtimeFrames()
3429 {
3430 	return m_nRealtimeFrames;
3431 }
3432 
3433 
getTickForPosition(int pos)3434 long Hydrogen::getTickForPosition( int pos )
3435 {
3436 	Song* pSong = getSong();
3437 
3438 	int nPatternGroups = pSong->get_pattern_group_vector()->size();
3439 	if ( nPatternGroups == 0 ) {
3440 		return -1;
3441 	}
3442 
3443 	if ( pos >= nPatternGroups ) {
3444 		// The position is beyond the end of the Song, we
3445 		// set periodic boundary conditions or return the
3446 		// beginning of the Song as a fallback.
3447 		if ( pSong->is_loop_enabled() ) {
3448 			pos = pos % nPatternGroups;
3449 		} else {
3450 			WARNINGLOG( QString( "patternPos > nPatternGroups. pos:"
3451 								 " %1, nPatternGroups: %2")
3452 						.arg( pos ) .arg(  nPatternGroups )
3453 						);
3454 			return -1;
3455 		}
3456 	}
3457 
3458 	std::vector<PatternList*> *pColumns = pSong->get_pattern_group_vector();
3459 	long totalTick = 0;
3460 	int nPatternSize;
3461 	Pattern *pPattern = nullptr;
3462 
3463 	for ( int i = 0; i < pos; ++i ) {
3464 		PatternList *pColumn = ( *pColumns )[ i ];
3465 
3466 		if( pColumn->size() > 0)
3467 		{
3468 			pPattern = pColumn->get( 0 );
3469 			if ( pPattern ) {
3470 				nPatternSize = pPattern->get_length();
3471 			} else {
3472 				nPatternSize = MAX_NOTES;
3473 			}
3474 		} else {
3475 			nPatternSize = MAX_NOTES;
3476 		}
3477 		totalTick += nPatternSize;
3478 	}
3479 
3480 	return totalTick;
3481 }
3482 
setPatternPos(int pos)3483 void Hydrogen::setPatternPos( int pos )
3484 {
3485 	if ( pos < -1 ) {
3486 		pos = -1;
3487 	}
3488 
3489 	AudioEngine::get_instance()->lock( RIGHT_HERE );
3490 	// TODO: why?
3491 	EventQueue::get_instance()->push_event( EVENT_METRONOME, 1 );
3492 	long totalTick = getTickForPosition( pos );
3493 	if ( totalTick < 0 ) {
3494 		AudioEngine::get_instance()->unlock();
3495 		return;
3496 	}
3497 
3498 	if ( getState() != STATE_PLAYING ) {
3499 		// find pattern immediately when not playing
3500 		//		int dummy;
3501 		// 		m_nSongPos = findPatternInTick( totalTick,
3502 		//					        pSong->is_loop_enabled(),
3503 		//					        &dummy );
3504 		m_nSongPos = pos;
3505 		m_nPatternTickPosition = 0;
3506 	}
3507 	m_pAudioDriver->locate(
3508 				( int ) ( totalTick * m_pAudioDriver->m_transport.m_fTickSize )
3509 				);
3510 
3511 	AudioEngine::get_instance()->unlock();
3512 }
3513 
getLadspaFXPeak(int nFX,float * fL,float * fR)3514 void Hydrogen::getLadspaFXPeak( int nFX, float *fL, float *fR )
3515 {
3516 #ifdef H2CORE_HAVE_LADSPA
3517 	( *fL ) = m_fFXPeak_L[nFX];
3518 	( *fR ) = m_fFXPeak_R[nFX];
3519 #else
3520 	( *fL ) = 0;
3521 	( *fR ) = 0;
3522 #endif
3523 }
3524 
setLadspaFXPeak(int nFX,float fL,float fR)3525 void Hydrogen::setLadspaFXPeak( int nFX, float fL, float fR )
3526 {
3527 #ifdef H2CORE_HAVE_LADSPA
3528 	m_fFXPeak_L[nFX] = fL;
3529 	m_fFXPeak_R[nFX] = fR;
3530 #endif
3531 }
3532 
onTapTempoAccelEvent()3533 void Hydrogen::onTapTempoAccelEvent()
3534 {
3535 #ifndef WIN32
3536 	INFOLOG( "tap tempo" );
3537 	static timeval oldTimeVal;
3538 
3539 	struct timeval now;
3540 	gettimeofday(&now, nullptr);
3541 
3542 	float fInterval =
3543 			(now.tv_sec - oldTimeVal.tv_sec) * 1000.0
3544 			+ (now.tv_usec - oldTimeVal.tv_usec) / 1000.0;
3545 
3546 	oldTimeVal = now;
3547 
3548 	if ( fInterval < 1000.0 ) {
3549 		setTapTempo( fInterval );
3550 	}
3551 #endif
3552 }
3553 
setTapTempo(float fInterval)3554 void Hydrogen::setTapTempo( float fInterval )
3555 {
3556 
3557 	//	infoLog( "set tap tempo" );
3558 	static float fOldBpm1 = -1;
3559 	static float fOldBpm2 = -1;
3560 	static float fOldBpm3 = -1;
3561 	static float fOldBpm4 = -1;
3562 	static float fOldBpm5 = -1;
3563 	static float fOldBpm6 = -1;
3564 	static float fOldBpm7 = -1;
3565 	static float fOldBpm8 = -1;
3566 
3567 	float fBPM = 60000.0 / fInterval;
3568 
3569 	if ( fabs( fOldBpm1 - fBPM ) > 20 ) {	// troppa differenza, niente media
3570 		fOldBpm1 = fBPM;
3571 		fOldBpm2 = fBPM;
3572 		fOldBpm3 = fBPM;
3573 		fOldBpm4 = fBPM;
3574 		fOldBpm5 = fBPM;
3575 		fOldBpm6 = fBPM;
3576 		fOldBpm7 = fBPM;
3577 		fOldBpm8 = fBPM;
3578 	}
3579 
3580 	if ( fOldBpm1 == -1 ) {
3581 		fOldBpm1 = fBPM;
3582 		fOldBpm2 = fBPM;
3583 		fOldBpm3 = fBPM;
3584 		fOldBpm4 = fBPM;
3585 		fOldBpm5 = fBPM;
3586 		fOldBpm6 = fBPM;
3587 		fOldBpm7 = fBPM;
3588 		fOldBpm8 = fBPM;
3589 	}
3590 
3591 	fBPM = ( fBPM + fOldBpm1 + fOldBpm2 + fOldBpm3 + fOldBpm4 + fOldBpm5
3592 			 + fOldBpm6 + fOldBpm7 + fOldBpm8 ) / 9.0;
3593 
3594 	INFOLOG( QString( "avg BPM = %1" ).arg( fBPM ) );
3595 	fOldBpm8 = fOldBpm7;
3596 	fOldBpm7 = fOldBpm6;
3597 	fOldBpm6 = fOldBpm5;
3598 	fOldBpm5 = fOldBpm4;
3599 	fOldBpm4 = fOldBpm3;
3600 	fOldBpm3 = fOldBpm2;
3601 	fOldBpm2 = fOldBpm1;
3602 	fOldBpm1 = fBPM;
3603 
3604 	AudioEngine::get_instance()->lock( RIGHT_HERE );
3605 
3606 	setBPM( fBPM );
3607 
3608 	AudioEngine::get_instance()->unlock();
3609 }
3610 
setBPM(float fBPM)3611 void Hydrogen::setBPM( float fBPM )
3612 {
3613 	Song* pSong = getSong();
3614 	if ( ! m_pAudioDriver || ! pSong ){
3615 		return;
3616 	}
3617 
3618 	if ( haveJackTimebaseClient() ) {
3619 		ERRORLOG( "Unable to change tempo directly in the presence of an external JACK timebase master. Press 'J.MASTER' get tempo control." );
3620 		return;
3621 	}
3622 
3623 	m_pAudioDriver->setBpm( fBPM );
3624 	pSong->__bpm = fBPM;
3625 	setNewBpmJTM ( fBPM );
3626 }
3627 
restartLadspaFX()3628 void Hydrogen::restartLadspaFX()
3629 {
3630 	if ( m_pAudioDriver ) {
3631 		AudioEngine::get_instance()->lock( RIGHT_HERE );
3632 		audioEngine_setupLadspaFX( m_pAudioDriver->getBufferSize() );
3633 		AudioEngine::get_instance()->unlock();
3634 	} else {
3635 		ERRORLOG( "m_pAudioDriver = NULL" );
3636 	}
3637 }
3638 
getSelectedPatternNumber()3639 int Hydrogen::getSelectedPatternNumber()
3640 {
3641 	return m_nSelectedPatternNumber;
3642 }
3643 
3644 
setSelectedPatternNumberWithoutGuiEvent(int nPat)3645 void Hydrogen::setSelectedPatternNumberWithoutGuiEvent( int nPat )
3646 {
3647 	Song* pSong = getSong();
3648 
3649 	if ( nPat == m_nSelectedPatternNumber
3650 		 || ( nPat + 1 > pSong->get_pattern_list()->size() )
3651 		 ) return;
3652 
3653 	if ( Preferences::get_instance()->patternModePlaysSelected() ) {
3654 		AudioEngine::get_instance()->lock( RIGHT_HERE );
3655 
3656 		m_nSelectedPatternNumber = nPat;
3657 		AudioEngine::get_instance()->unlock();
3658 	} else {
3659 		m_nSelectedPatternNumber = nPat;
3660 	}
3661 }
3662 
setSelectedPatternNumber(int nPat)3663 void Hydrogen::setSelectedPatternNumber( int nPat )
3664 {
3665 	if ( nPat == m_nSelectedPatternNumber )	return;
3666 
3667 
3668 	if ( Preferences::get_instance()->patternModePlaysSelected() ) {
3669 		AudioEngine::get_instance()->lock( RIGHT_HERE );
3670 
3671 		m_nSelectedPatternNumber = nPat;
3672 		AudioEngine::get_instance()->unlock();
3673 	} else {
3674 		m_nSelectedPatternNumber = nPat;
3675 	}
3676 
3677 	EventQueue::get_instance()->push_event( EVENT_SELECTED_PATTERN_CHANGED, -1 );
3678 }
3679 
getSelectedInstrumentNumber()3680 int Hydrogen::getSelectedInstrumentNumber()
3681 {
3682 	return m_nSelectedInstrumentNumber;
3683 }
3684 
setSelectedInstrumentNumber(int nInstrument)3685 void Hydrogen::setSelectedInstrumentNumber( int nInstrument )
3686 {
3687 	if ( m_nSelectedInstrumentNumber == nInstrument )	return;
3688 
3689 	m_nSelectedInstrumentNumber = nInstrument;
3690 	EventQueue::get_instance()->push_event( EVENT_SELECTED_INSTRUMENT_CHANGED, -1 );
3691 }
3692 
refreshInstrumentParameters(int nInstrument)3693 void Hydrogen::refreshInstrumentParameters( int nInstrument )
3694 {
3695 	EventQueue::get_instance()->push_event( EVENT_PARAMETERS_INSTRUMENT_CHANGED, -1 );
3696 }
3697 
3698 #ifdef H2CORE_HAVE_JACK
renameJackPorts(Song * pSong)3699 void Hydrogen::renameJackPorts( Song *pSong )
3700 {
3701 	if( Preferences::get_instance()->m_bJackTrackOuts == true ){
3702 		audioEngine_renameJackPorts(pSong);
3703 	}
3704 }
3705 #endif
3706 
3707 /** Updates #m_nbeatsToCount
3708  * \param beatstocount New value*/
setbeatsToCount(int beatstocount)3709 void Hydrogen::setbeatsToCount( int beatstocount)
3710 {
3711 	m_nbeatsToCount = beatstocount;
3712 }
3713 /** \return #m_nbeatsToCount*/
getbeatsToCount()3714 int Hydrogen::getbeatsToCount()
3715 {
3716 	return m_nbeatsToCount;
3717 }
3718 
setNoteLength(float notelength)3719 void Hydrogen::setNoteLength( float notelength)
3720 {
3721 	m_ntaktoMeterCompute = notelength;
3722 }
3723 
getNoteLength()3724 float Hydrogen::getNoteLength()
3725 {
3726 	return m_ntaktoMeterCompute;
3727 }
3728 
getBcStatus()3729 int Hydrogen::getBcStatus()
3730 {
3731 	return m_nEventCount;
3732 }
3733 
setBcOffsetAdjust()3734 void Hydrogen::setBcOffsetAdjust()
3735 {
3736 	//individual fine tuning for the m_nBeatCounter
3737 	//to adjust  ms_offset from different people and controller
3738 	Preferences *pPreferences = Preferences::get_instance();
3739 
3740 	m_nCoutOffset = pPreferences->m_countOffset;
3741 	m_nStartOffset = pPreferences->m_startOffset;
3742 }
3743 
handleBeatCounter()3744 void Hydrogen::handleBeatCounter()
3745 {
3746 	// Get first time value:
3747 	if (m_nBeatCount == 1) {
3748 		gettimeofday(&m_CurrentTime,nullptr);
3749 	}
3750 
3751 	m_nEventCount++;
3752 
3753 	// Set wm_LastTime to wm_CurrentTime to remind the time:
3754 	m_LastTime = m_CurrentTime;
3755 
3756 	// Get new time:
3757 	gettimeofday(&m_CurrentTime,nullptr);
3758 
3759 
3760 	// Build doubled time difference:
3761 	m_nLastBeatTime = (double)(
3762 				m_LastTime.tv_sec
3763 				+ (double)(m_LastTime.tv_usec * US_DIVIDER)
3764 				+ (int)m_nCoutOffset * .0001
3765 				);
3766 	m_nCurrentBeatTime = (double)(
3767 				m_CurrentTime.tv_sec
3768 				+ (double)(m_CurrentTime.tv_usec * US_DIVIDER)
3769 				);
3770 	m_nBeatDiff = m_nBeatCount == 1 ? 0 : m_nCurrentBeatTime - m_nLastBeatTime;
3771 
3772 	//if differences are to big reset the beatconter
3773 	if( m_nBeatDiff > 3.001 * 1/m_ntaktoMeterCompute ) {
3774 		m_nEventCount = 1;
3775 		m_nBeatCount = 1;
3776 		return;
3777 	}
3778 	// Only accept differences big enough
3779 	if (m_nBeatCount == 1 || m_nBeatDiff > .001) {
3780 		if (m_nBeatCount > 1) {
3781 			m_nBeatDiffs[m_nBeatCount - 2] = m_nBeatDiff ;
3782 		}
3783 		// Compute and reset:
3784 		if (m_nBeatCount == m_nbeatsToCount){
3785 			//				unsigned long currentframe = getRealtimeFrames();
3786 			double beatTotalDiffs = 0;
3787 			for(int i = 0; i < (m_nbeatsToCount - 1); i++) {
3788 				beatTotalDiffs += m_nBeatDiffs[i];
3789 			}
3790 			double m_nBeatDiffAverage =
3791 					beatTotalDiffs
3792 					/ (m_nBeatCount - 1)
3793 					* m_ntaktoMeterCompute ;
3794 			m_fBeatCountBpm	 =
3795 					(float) ((int) (60 / m_nBeatDiffAverage * 100))
3796 					/ 100;
3797 			AudioEngine::get_instance()->lock( RIGHT_HERE );
3798 			if ( m_fBeatCountBpm > MAX_BPM) {
3799 				m_fBeatCountBpm = MAX_BPM;
3800 			}
3801 
3802 			setBPM( m_fBeatCountBpm );
3803 			AudioEngine::get_instance()->unlock();
3804 			if (Preferences::get_instance()->m_mmcsetplay
3805 					== Preferences::SET_PLAY_OFF) {
3806 				m_nBeatCount = 1;
3807 				m_nEventCount = 1;
3808 			}else{
3809 				if ( m_audioEngineState != STATE_PLAYING ){
3810 					unsigned bcsamplerate =
3811 							m_pAudioDriver->getSampleRate();
3812 					unsigned long rtstartframe = 0;
3813 					if ( m_ntaktoMeterCompute <= 1){
3814 						rtstartframe =
3815 								bcsamplerate
3816 								* m_nBeatDiffAverage
3817 								* ( 1/ m_ntaktoMeterCompute );
3818 					}else
3819 					{
3820 						rtstartframe =
3821 								bcsamplerate
3822 								* m_nBeatDiffAverage
3823 								/ m_ntaktoMeterCompute ;
3824 					}
3825 
3826 					int sleeptime =
3827 							( (float) rtstartframe
3828 							  / (float) bcsamplerate
3829 							  * (int) 1000 )
3830 							+ (int)m_nCoutOffset
3831 							+ (int) m_nStartOffset;
3832 #ifdef WIN32
3833 					Sleep( sleeptime );
3834 #else
3835 					usleep( 1000 * sleeptime );
3836 #endif
3837 
3838 					sequencer_play();
3839 				}
3840 
3841 				m_nBeatCount = 1;
3842 				m_nEventCount = 1;
3843 				return;
3844 			}
3845 		}
3846 		else {
3847 			m_nBeatCount ++;
3848 		}
3849 	}
3850 	return;
3851 }
3852 //~ m_nBeatCounter
3853 
3854 #ifdef H2CORE_HAVE_JACK
offJackMaster()3855 void Hydrogen::offJackMaster()
3856 {
3857 	if ( haveJackTransport() ) {
3858 		static_cast< JackAudioDriver* >( m_pAudioDriver )->releaseTimebaseMaster();
3859 	}
3860 }
3861 
onJackMaster()3862 void Hydrogen::onJackMaster()
3863 {
3864 	if ( haveJackTransport() ) {
3865 		static_cast< JackAudioDriver* >( m_pAudioDriver )->initTimebaseMaster();
3866 	}
3867 }
3868 #endif
3869 
getPatternLength(int nPattern)3870 long Hydrogen::getPatternLength( int nPattern )
3871 {
3872 	Song* pSong = getSong();
3873 	if ( pSong == nullptr ){
3874 		return -1;
3875 	}
3876 
3877 	std::vector< PatternList* > *pColumns = pSong->get_pattern_group_vector();
3878 
3879 	int nPatternGroups = pColumns->size();
3880 	if ( nPattern >= nPatternGroups ) {
3881 		if ( pSong->is_loop_enabled() ) {
3882 			nPattern = nPattern % nPatternGroups;
3883 		} else {
3884 			return MAX_NOTES;
3885 		}
3886 	}
3887 
3888 	if ( nPattern < 1 ){
3889 		return MAX_NOTES;
3890 	}
3891 
3892 	PatternList* pPatternList = pColumns->at( nPattern - 1 );
3893 	Pattern* pPattern = pPatternList->get( 0 );
3894 	if ( pPattern ) {
3895 		return pPattern->get_length();
3896 	} else {
3897 		return MAX_NOTES;
3898 	}
3899 }
3900 
getNewBpmJTM()3901 float Hydrogen::getNewBpmJTM()
3902 {
3903 	return m_fNewBpmJTM;
3904 }
3905 
setNewBpmJTM(float bpmJTM)3906 void Hydrogen::setNewBpmJTM( float bpmJTM )
3907 {
3908 	m_fNewBpmJTM = bpmJTM;
3909 }
3910 
3911 //~ jack transport master
resetPatternStartTick()3912 void Hydrogen::resetPatternStartTick()
3913 {
3914 	// This forces the barline position
3915 	if ( getSong()->get_mode() == Song::PATTERN_MODE ) {
3916 		m_nPatternStartTick = -1;
3917 	}
3918 }
3919 
togglePlaysSelected()3920 void Hydrogen::togglePlaysSelected()
3921 {
3922 	Song* pSong = getSong();
3923 
3924 	if ( pSong->get_mode() != Song::PATTERN_MODE ) {
3925 		return;
3926 	}
3927 
3928 	AudioEngine::get_instance()->lock( RIGHT_HERE );
3929 
3930 	Preferences* pPref = Preferences::get_instance();
3931 	bool isPlaysSelected = pPref->patternModePlaysSelected();
3932 
3933 	if (isPlaysSelected) {
3934 		m_pPlayingPatterns->clear();
3935 		Pattern* pSelectedPattern =
3936 				pSong->get_pattern_list()->get(m_nSelectedPatternNumber);
3937 		m_pPlayingPatterns->add( pSelectedPattern );
3938 	}
3939 
3940 	pPref->setPatternModePlaysSelected( !isPlaysSelected );
3941 	AudioEngine::get_instance()->unlock();
3942 }
3943 
__kill_instruments()3944 void Hydrogen::__kill_instruments()
3945 {
3946 	int c = 0;
3947 	Instrument * pInstr = nullptr;
3948 	while ( __instrument_death_row.size()
3949 			&& __instrument_death_row.front()->is_queued() == 0 ) {
3950 		pInstr = __instrument_death_row.front();
3951 		__instrument_death_row.pop_front();
3952 		INFOLOG( QString( "Deleting unused instrument (%1). "
3953 						  "%2 unused remain." )
3954 				 . arg( pInstr->get_name() )
3955 				 . arg( __instrument_death_row.size() ) );
3956 		delete pInstr;
3957 		c++;
3958 	}
3959 	if ( __instrument_death_row.size() ) {
3960 		pInstr = __instrument_death_row.front();
3961 		INFOLOG( QString( "Instrument %1 still has %2 active notes. "
3962 						  "Delaying 'delete instrument' operation." )
3963 				 . arg( pInstr->get_name() )
3964 				 . arg( pInstr->is_queued() ) );
3965 	}
3966 }
3967 
3968 
3969 
__panic()3970 void Hydrogen::__panic()
3971 {
3972 	sequencer_stop();
3973 	AudioEngine::get_instance()->get_sampler()->stop_playing_notes();
3974 }
3975 
__getMidiRealtimeNoteTickPosition()3976 unsigned int Hydrogen::__getMidiRealtimeNoteTickPosition()
3977 {
3978 	return m_naddrealtimenotetickposition;
3979 }
3980 
getTimelineBpm(int nBar)3981 float Hydrogen::getTimelineBpm( int nBar )
3982 {
3983 	Song* pSong = getSong();
3984 
3985 	// We need return something
3986 	if ( pSong == nullptr ) {
3987 		return getNewBpmJTM();
3988 	}
3989 
3990 	float fBPM = pSong->__bpm;
3991 
3992 	// Pattern mode don't use timeline and will have a constant
3993 	// speed.
3994 	if ( pSong->get_mode() == Song::PATTERN_MODE ) {
3995 		return fBPM;
3996 	}
3997 
3998 	// Check whether the user wants Hydrogen to determine the
3999 	// speed by local setting along the timeline or whether she
4000 	// wants to use a global speed instead.
4001 	if ( ! Preferences::get_instance()->getUseTimelineBpm() ) {
4002 		return fBPM;
4003 	}
4004 
4005 	// Determine the speed at the supplied beat.
4006 	for ( int i = 0; i < static_cast<int>(m_pTimeline->m_timelinevector.size()); i++) {
4007 		if ( m_pTimeline->m_timelinevector[i].m_htimelinebeat > nBar ) {
4008 			break;
4009 		}
4010 
4011 		fBPM = m_pTimeline->m_timelinevector[i].m_htimelinebpm;
4012 	}
4013 
4014 	return fBPM;
4015 }
4016 
setTimelineBpm()4017 void Hydrogen::setTimelineBpm()
4018 {
4019 	if ( ! Preferences::get_instance()->getUseTimelineBpm() ||
4020 		 haveJackTimebaseClient() ) {
4021 		return;
4022 	}
4023 
4024 	Song* pSong = getSong();
4025 	// Obtain the local speed specified for the current Pattern.
4026 	float fBPM = getTimelineBpm( getPatternPos() );
4027 
4028 	if ( fBPM != pSong->__bpm ) {
4029 		setBPM( fBPM );
4030 	}
4031 
4032 	// Get the realtime pattern position. This also covers
4033 	// keyboard and MIDI input events in case the audio engine is
4034 	// not playing.
4035 	unsigned long PlayTick = getRealtimeTickPosition();
4036 	int nStartPos;
4037 	int nRealtimePatternPos = getPosForTick( PlayTick, &nStartPos );
4038 	float fRealtimeBPM = getTimelineBpm( nRealtimePatternPos );
4039 
4040 	// FIXME: this was already done in setBPM but for "engine" time
4041 	//        so this is actually forcibly overwritten here
4042 	setNewBpmJTM( fRealtimeBPM );
4043 }
4044 
haveJackAudioDriver() const4045 bool Hydrogen::haveJackAudioDriver() const {
4046 #ifdef H2CORE_HAVE_JACK
4047 	if ( m_pAudioDriver != nullptr ) {
4048 		if ( JackAudioDriver::class_name() == m_pAudioDriver->class_name() ){
4049 			return true;
4050 		}
4051 	}
4052 	return false;
4053 #else
4054 	return false;
4055 #endif
4056 }
4057 
haveJackTransport() const4058 bool Hydrogen::haveJackTransport() const {
4059 #ifdef H2CORE_HAVE_JACK
4060 	if ( m_pAudioDriver != nullptr ) {
4061 		if ( JackAudioDriver::class_name() == m_pAudioDriver->class_name() &&
4062 			 Preferences::get_instance()->m_bJackTransportMode ==
4063 			 Preferences::USE_JACK_TRANSPORT ){
4064 			return true;
4065 		}
4066 	}
4067 	return false;
4068 #else
4069 	return false;
4070 #endif
4071 }
4072 
haveJackTimebaseClient() const4073 bool Hydrogen::haveJackTimebaseClient() const {
4074 #ifdef H2CORE_HAVE_JACK
4075 	if ( haveJackTransport() ) {
4076 		if ( static_cast<JackAudioDriver*>(m_pAudioDriver)->getIsTimebaseMaster() == 0 ) {
4077 			return true;
4078 		}
4079 	}
4080 	return false;
4081 #else
4082 	return false;
4083 #endif
4084 }
4085 
4086 #ifdef H2CORE_HAVE_OSC
startOscServer()4087 void startOscServer()
4088 {
4089 	OscServer* pOscServer = OscServer::get_instance();
4090 
4091 	if( pOscServer ){
4092 		pOscServer->start();
4093 	}
4094 }
4095 
startNsmClient()4096 void Hydrogen::startNsmClient()
4097 {
4098 	//NSM has to be started before jack driver gets created
4099 	NsmClient* pNsmClient = NsmClient::get_instance();
4100 
4101 	if(pNsmClient){
4102 		pNsmClient->createInitialClient();
4103 	}
4104 }
4105 #endif
4106 
4107 }; /* Namespace */
4108