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 #ifndef HYDROGEN_H
23 #define HYDROGEN_H
24 
25 #include <stdint.h> // for uint32_t et al
26 #include "hydrogen/config.h"
27 #include <hydrogen/midi_action.h>
28 #include <hydrogen/basics/song.h>
29 #include <hydrogen/basics/sample.h>
30 #include <hydrogen/object.h>
31 #include <hydrogen/timeline.h>
32 #include <hydrogen/IO/AudioOutput.h>
33 #include <hydrogen/IO/MidiInput.h>
34 #include <hydrogen/IO/MidiOutput.h>
35 #include <hydrogen/basics/drumkit.h>
36 #include <hydrogen/core_action_controller.h>
37 #include <cassert>
38 #include <hydrogen/timehelper.h>
39 // Engine states  (It's ok to use ==, <, and > when testing)
40 /**
41  * State of the H2Core::AudioEngine H2Core::m_audioEngineState. Not even the
42  * constructors have been called.
43  */
44 #define STATE_UNINITIALIZED	1
45 /**
46  * State of the H2Core::AudioEngine H2Core::m_audioEngineState. Not ready,
47  * but most pointers are now valid or NULL.
48  */
49 #define STATE_INITIALIZED	2
50 /**
51  * State of the H2Core::AudioEngine H2Core::m_audioEngineState. Drivers are
52  * set up, but not ready to process audio.
53  */
54 #define STATE_PREPARED		3
55 /**
56  * State of the H2Core::AudioEngine H2Core::m_audioEngineState. Ready to
57  * process audio.
58  */
59 #define STATE_READY		4
60 /**
61  * State of the H2Core::AudioEngine H2Core::m_audioEngineState. Currently
62  * playing a sequence.
63  */
64 #define STATE_PLAYING		5
65 inline int randomValue( int max );
66 
67 namespace H2Core
68 {
69 ///
70 /// Hydrogen Audio Engine.
71 ///
72 class Hydrogen : public H2Core::Object
73 {
74 	H2_OBJECT
75 public:
76 	/**
77 	 * Creates all the instances used within Hydrogen in the right
78 	 * order.
79 	 *
80 	 * -# H2Core::Logger::create_instance()
81 	 * -# MidiMap::create_instance()
82 	 * -# Preferences::create_instance()
83 	 * -# EventQueue::create_instance()
84 	 * -# MidiActionManager::create_instance()
85 	 *
86 	 * If #H2CORE_HAVE_OSC was set during compilation, the
87 	 * following instances will be created as well.
88 	 *
89 	 * -# NsmClient::create_instance()
90 	 * -# OscServer::create_instance() using
91 	 *    Preferences::get_instance() as input
92 	 *
93 	 * If all instances are created and the actual Hydrogen
94 	 * instance #__instance is still 0, it will be properly
95 	 * constructed via Hydrogen().
96 	 *
97 	 * The AudioEngine::create_instance(),
98 	 * Effects::create_instance(), and Playlist::create_instance()
99 	 * functions will be called from within audioEngine_init().
100 	 */
101 	static void		create_instance();
102 	/**
103 	 * Returns the current Hydrogen instance #__instance.
104 	 */
get_instance()105 	static Hydrogen*	get_instance(){ assert(__instance); return __instance; };
106 
107 	/**
108 	 * Destructor taking care of most of the clean up.
109 	 *
110 	 * -# Shuts down the NsmClient using NsmClient::shutdown() and
111               deletes it.
112 	 * -# Deletes the OscServer object.
113 	 * -# Stops the AudioEngine if playing via audioEngine_stop().
114 	 * -# Calls removeSong(), audioEngine_stopAudioDrivers(),
115               audioEngine_destroy(), __kill_instruments()
116          * -# Deletes the #m_pCoreActionController and #m_pTimeline
117               object
118 	 * -# Sets #__instance to NULL.
119 	 */
120 	~Hydrogen();
121 
122 // ***** SEQUENCER ********
123 	/// Start the internal sequencer
124 	void			sequencer_play();
125 
126 	/// Stop the internal sequencer
127 	void			sequencer_stop();
128 
129 	void			midi_noteOn( Note *note );
130 
131 	///Last received midi message
132 	QString			lastMidiEvent;
133 	int				lastMidiEventParameter;
134 
135 	// TODO: more descriptive name since it is able to both delete and
136 	// add a pattern. Possibly without the sequencer_ prefix for
137 	// consistency.
138 	/**
139 	 * Adding and removing a Pattern from #m_pNextPatterns.
140 	 *
141 	 * After locking the AudioEngine the function retrieves the
142 	 * particular pattern @a pos from the Song::__pattern_list and
143 	 * either deletes it from #m_pNextPatterns if already present or
144 	 * add it to the same pattern list if not present yet.
145 	 *
146 	 * If the Song is not in Song::PATTERN_MODE or @a pos is not
147 	 * within the range of Song::__pattern_list, #m_pNextPatterns will
148 	 * be cleared instead.
149 	 *
150 	 * \param pos Index of a particular pattern in
151 	 * Song::__pattern_list, which should be added to
152 	 * #m_pNextPatterns.
153 	 */
154 	void			sequencer_setNextPattern( int pos );
155 	// TODO: Possibly without the sequencer_ prefix for consistency.
156 	/**
157 	 * Clear #m_pNextPatterns and add one Pattern.
158 	 *
159 	 * After locking the AudioEngine the function clears
160 	 * #m_pNextPatterns, fills it with all currently played one in
161 	 * #m_pPlayingPatterns, and appends the particular pattern @a pos
162 	 * from the Song::__pattern_list.
163 	 *
164 	 * If the Song is not in Song::PATTERN_MODE or @a pos is not
165 	 * within the range of Song::__pattern_list, #m_pNextPatterns will
166 	 * be just cleared.
167 	 *
168 	 * \param pos Index of a particular pattern in
169 	 * Song::__pattern_list, which should be added to
170 	 * #m_pNextPatterns.
171 	 */
172 	void			sequencer_setOnlyNextPattern( int pos );
173 	/**
174 	 * Switches playback to focused pattern.
175 	 *
176 	 * If the current Song is in Song::PATTERN_MODE, the AudioEngine
177 	 * will be locked and Preferences::m_bPatternModePlaysSelected
178 	 * negated. If the latter was true before calling this function,
179 	 * #m_pPlayingPatterns will be cleared and replaced by the
180 	 * Pattern indexed with #m_nSelectedPatternNumber.
181 	 *
182 	 * This function will be called either by MainForm::eventFilter()
183 	 * when pressing Qt::Key_L or by
184 	 * SongEditorPanel::modeActionBtnPressed().
185 	 */
186 	void			togglePlaysSelected();
187 
188 		/**
189 		 * Get the current song.
190 		 * \return #__song
191 		 */
getSong()192 		Song*			getSong(){ return __song; }
193 		/**
194 		 * Sets the current song #__song to @a newSong.
195 		 * \param newSong Pointer to the new Song object.
196 		 */
197 		void			setSong	( Song *newSong );
198 
199 		void			removeSong();
200 
201 		void			addRealtimeNote ( int instrument,
202 							  float velocity,
203 							  float pan_L=1.0,
204 							  float pan_R=1.0,
205 							  float pitch=0.0,
206 							  bool noteoff=false,
207 							  bool forcePlay=false,
208 							  int msg1=0 );
209 
210 		float			getMasterPeak_L();
211 		void			setMasterPeak_L( float value );
212 
213 		float			getMasterPeak_R();
214 		void			setMasterPeak_R( float value );
215 
216 		void			getLadspaFXPeak( int nFX, float *fL, float *fR );
217 		void			setLadspaFXPeak( int nFX, float fL, float fR );
218 	/** \return #m_nPatternTickPosition */
219 	unsigned long		getTickPosition();
220 	/** Keep track of the tick position in realtime.
221 	 *
222 	 * Firstly, it gets the current transport position in frames
223 	 * #m_nRealtimeFrames and converts it into ticks using
224 	 * TransportInfo::m_fTickSize. Afterwards, it accesses how
225 	 * much time passed since the last update of
226 	 * #m_currentTickTime, converts the time difference +
227 	 * AudioOutput::getBufferSize()/ AudioOutput::getSampleRate()
228 	 * in frames, and adds the result to the first value to
229 	 * support keyboard and MIDI events as well.
230 	 *
231 	 * \return Current position in ticks.
232 	 */
233 	unsigned long		getRealtimeTickPosition();
234 	unsigned long		getTotalFrames();
235 
236 	/** Sets #m_nRealtimeFrames
237 	 * \param frames Current transport realtime position*/
238 	void			setRealtimeFrames( unsigned long frames );
239 	/** Returns the current realtime transport position
240 	 * TransportInfo::m_nFrames.
241 	 * \return #m_nRealtimeFrames */
242 	unsigned long		getRealtimeFrames();
243 	/** \return #m_pPlayingPatterns*/
244 	PatternList *		getCurrentPatternList();
245 	/**
246 	 * Sets #m_pPlayingPatterns.
247 	 *
248 	 * Before setting the variable it first locks the AudioEngine. In
249 	 * addition, it also pushes the Event #EVENT_PATTERN_CHANGED with
250 	 * the value -1 to the EventQueue.
251 	 *
252 	 * \param pPatternList Sets #m_pPlayingPatterns.*/
253 	void			setCurrentPatternList( PatternList * pPatternList );
254 
255 	/** \return #m_pNextPatterns*/
256 	PatternList *		getNextPatterns();
257 
258 	/** Get the position of the current Pattern in the Song.
259 	 * \return #m_nSongPos */
260 	int			getPatternPos();
261 	/**
262 	 * Relocate the position to another Pattern in the Song.
263 	 *
264 	 * The position of a Pattern in frames (see
265 	 * TransportInfo::m_nFrames for details) will be determined by
266 	 * retrieving the tick number the Pattern is located at using
267 	 * getTickForPosition() and multiplying it with
268 	 * TransportInfo::m_fTickSize. The resulting value will be
269 	 * used by the AudioOutput::locate() function of your audio
270 	 * driver to relocate the playback position.
271 	 *
272 	 * If #m_audioEngineState is not #STATE_PLAYING, the variables
273 	 * #m_nSongPos and #m_nPatternTickPosition will be set to @a
274 	 * pos and 0 right away.
275 	 *
276 	 * \param pos Position of the Pattern to relocate at. All
277 	 *   values smaller than -1 will be set to -1, which marks the
278 	 *   beginning of the Song.
279 	 */
280 	void			setPatternPos( int pos );
281 	/** Returns the pattern number corresponding to the tick
282 	 * position @a TickPos.
283 	 *
284 	 * Wrapper around function findPatternInTick() (globally defined
285 	 * in hydrogen.cpp).
286 	 *
287 	 * \param TickPos Position in ticks.
288 	 * \param nPatternStartTick Pointer to an int the starting
289 	 * position (in ticks) of the corresponding pattern will be
290 	 * written to.
291 	 *
292 	 * \return
293 	 * - __0__ : if the Song isn't specified yet.
294 	 * - the output of the findPatternInTick() function called
295 	 *   with @a TickPos and Song::is_loop_enabled() as input
296 	 *   arguments.
297 	 */
298 	int			getPosForTick( unsigned long TickPos, int* nPatternStartTick );
299 	/** Move playback in Pattern mode to the beginning of the pattern.
300 	 *
301 	 * Resetting the global variable #m_nPatternStartTick to -1 if the
302 	 * current Song mode is Song::PATTERN_MODE.
303 	 */
304 	void			resetPatternStartTick();
305 
306 		/**
307 		 * Get the total number of ticks passed up to a Pattern at
308 		 * position @a pos.
309 		 *
310 		 * The function will loop over all and sums up their
311 		 * Pattern::__length. If one of the Pattern is NULL or no
312 		 * Pattern is present one of the PatternList, #MAX_NOTES will
313 		 * be added instead.
314 		 *
315 		 * The driver should be LOCKED when calling this!
316 		 *
317 		 * \param pos Position of the Pattern in the
318 		 *   Song::__pattern_group_sequence.
319 		 * \return
320 		 *  - -1 : if @a pos is bigger than the number of patterns in
321 		 *   the Song and Song::__is_loop_enabled is set to false or
322 		 *   no Patterns could be found at all.
323 		 *  - >= 0 : the total number of ticks passed.
324 		 */
325 		long			getTickForPosition( int pos );
326 
327 		void			restartDrivers();
328 
329 		AudioOutput*		getAudioOutput();
330 		MidiInput*		getMidiInput();
331 		MidiOutput*		getMidiOutput();
332 
333 		/** Returns the current state of the audio engine.
334 		 * \return #m_audioEngineState*/
335 		int			getState();
336 
337 		float			getProcessTime();
338 		float			getMaxProcessTime();
339 
340 		int			loadDrumkit( Drumkit *pDrumkitInfo );
341 		int			loadDrumkit( Drumkit *pDrumkitInfo, bool conditional );
342 
343 		/** Test if an Instrument has some Note in the Pattern (used to
344 		    test before deleting an Instrument)*/
345 		bool 			instrumentHasNotes( Instrument *pInst );
346 
347 		/** Delete an Instrument. If @a conditional is true, and there
348 		    are some Pattern that are using this Instrument, it's not
349 		    deleted anyway.*/
350 		void			removeInstrument( int instrumentnumber, bool conditional );
351 
352 		/** Return the name of the current Drumkit.*/
353 		QString			m_currentDrumkit;
354 
355 		const QString&		getCurrentDrumkitname();
356 		void			setCurrentDrumkitname( const QString& currentdrumkitname );
357 
358 		void			raiseError( unsigned nErrorCode );
359 
360 
361 void			previewSample( Sample *pSample );
362 	void			previewInstrument( Instrument *pInstr );
363 
364 	enum ErrorMessages {
365 		/**
366 		 * The provided input string in createDriver() does
367 		 * not match any of the choices for
368 		 * Preferences::m_sAudioDriver.
369 		 */
370 		UNKNOWN_DRIVER,
371 		/**
372 		 * Unable to connect the audio driver stored in
373 		 * #m_pAudioDriver in
374 		 * audioEngine_startAudioDrivers(). The NullDriver
375 		 * will be used as a fallback instead.
376 		 */
377 		ERROR_STARTING_DRIVER,
378 		JACK_SERVER_SHUTDOWN,
379 		JACK_CANNOT_ACTIVATE_CLIENT,
380 		/**
381 		 * Unable to connect either the
382 		 * JackAudioDriver::output_port_1 and the
383 		 * JackAudioDriver::output_port_name_1 as well as the
384 		 * JackAudioDriver::output_port_2 and the
385 		 * JackAudioDriver::output_port_name_2 port using
386 		 * _jack_connect()_ (jack/jack.h) or the fallback
387 		 * version using the first two input ports in
388 		 * JackAudioDriver::connect().
389 		 */
390 		JACK_CANNOT_CONNECT_OUTPUT_PORT,
391 		/**
392 		 * The client of Hydrogen can not be disconnected from
393 		 * the JACK server using _jack_client_close()_
394 		 * (jack/jack.h). Used within JackAudioDriver::disconnect().
395 		 */
396 		JACK_CANNOT_CLOSE_CLIENT,
397 		/**
398 		 * Unable to register output ports for the JACK client
399 		 * using _jack_port_register()_ (jack/jack.h) in
400 		 * JackAudioDriver::init() or
401 		 * JackAudioDriver::setTrackOutput().
402 		 */
403 		JACK_ERROR_IN_PORT_REGISTER,
404 		/**
405 		 * Unable to start the OSC server with the given
406 		 * port number.
407 		 */
408 		OSC_CANNOT_CONNECT_TO_PORT
409 	};
410 
411 	void			onTapTempoAccelEvent();
412 	void			setTapTempo( float fInterval );
413 	/**
414 	 * Updates the speed.
415 	 *
416 	 * It calls AudioOutput::setBpm() and setNewBpmJTM() with @a
417 	 * fBPM as input argument and sets Song::__bpm to @a fBPM.
418 	 *
419 	 * This function will be called with the AudioEngine in LOCKED
420 	 * state.
421 	 * \param fBPM New speed in beats per minute.
422 	 */
423 	void			setBPM( float fBPM );
424 
425 	void			restartLadspaFX();
426 	/**
427 	 * Same as getSelectedPatternNumber() without pushing an event.
428 	 * \param nPat Sets #m_nSelectedPatternNumber*/
429 	void			setSelectedPatternNumberWithoutGuiEvent( int nPat );
430 	/** \return #m_nSelectedPatternNumber*/
431 	int				getSelectedPatternNumber();
432 	/**
433 	 * Sets #m_nSelectedPatternNumber.
434 	 *
435 	 * If Preferences::m_pPatternModePlaysSelected is set to true, the
436 	 * AudioEngine is locked before @a nPat will be assigned. But in
437 	 * any case the function will push the
438 	 * #EVENT_SELECTED_PATTERN_CHANGED Event to the EventQueue.
439 	 *
440 	 * If @a nPat is equal to #m_nSelectedPatternNumber, the function
441 	 * will return right away.
442 	 *
443 	 *\param nPat Sets #m_nSelectedPatternNumber*/
444 	void			setSelectedPatternNumber( int nPat );
445 
446 	int				getSelectedInstrumentNumber();
447 	void			setSelectedInstrumentNumber( int nInstrument );
448 
449 
450 	void			refreshInstrumentParameters( int nInstrument );
451 
452 #if defined(H2CORE_HAVE_JACK) || _DOXYGEN_
453 	/**
454 	 * Calls audioEngine_renameJackPorts() if
455 	 * Preferences::m_bJackTrackOuts is set to true.
456 	 * \param pSong Handed to audioEngine_renameJackPorts().
457 	 */
458 	void			renameJackPorts(Song* pSong);
459 #endif
460 
461 #if defined(H2CORE_HAVE_OSC) || _DOXYGEN_
462 	void			startOscServer();
463 	void			startNsmClient();
464 #endif
465 
466 	// beatconter
467 	void			setbeatsToCount( int beatstocount);
468 	int			getbeatsToCount();
469 	void			setNoteLength( float notelength);
470 	float			getNoteLength();
471 	int			getBcStatus();
472 	void			handleBeatCounter();
473 	void			setBcOffsetAdjust();
474 
475 	/** Calling JackAudioDriver::releaseTimebaseMaster() directly from
476 	    the GUI*/
477 	void			offJackMaster();
478 	/** Calling JackAudioDriver::initTimebaseMaster() directly from
479 	    the GUI*/
480 	void			onJackMaster();
481 	/**
482 	 * Get the length (in ticks) of the @a nPattern th pattern.
483 	 *
484 	 * Access the length of the first Pattern found in the
485 	 * PatternList at @a nPattern - 1.
486 	 *
487 	 * This function should also work if the loop mode is enabled
488 	 * in Song::is_loop_enabled().
489 	 *
490 	 * \param nPattern Position + 1 of the desired PatternList.
491 	 * \return
492 	 * - __-1__ : if not Song was initialized yet.
493 	 * - #MAX_NOTES : if @a nPattern was smaller than 1, larger
494 	 * than the length of the vector of the PatternList in
495 	 * Song::__pattern_group_sequence or no Pattern could be found
496 	 * in the PatternList at @a nPattern - 1.
497 	 * - __else__ : length of first Pattern found at @a nPattern.
498 	 */
499 	long			getPatternLength( int nPattern );
500 	/** Returns the fallback speed.
501 	 * \return #m_fNewBpmJTM */
502 	float			getNewBpmJTM();
503 	/** Set the fallback speed #m_fNewBpmJTM.
504 	 * \param bpmJTM New default tempo. */
505 	void			setNewBpmJTM( float bpmJTM);
506 
507 	void			__panic();
508 	unsigned int	__getMidiRealtimeNoteTickPosition();
509 
510 	/**
511 	 * Updates Song::__bpm, TransportInfo::m_fBPM, and #m_fNewBpmJTM
512 	 * to the local speed.
513 	 *
514 	 * The local speed will be obtained by calling getTimelineBpm()
515 	 * with getPatternPos() as input argument and set for the current
516 	 * song and transport. For setting the
517 	 * fallback speed #m_fNewBpmJTM, getRealtimeTickPosition() will be
518 	 * used instead.
519 	 *
520 	 * If Preferences::__useTimelineBpm is set to false or Hydrogen
521 	 * uses JACK transport in the presence of an external timebase
522 	 * master, the function will return without performing any
523 	 * actions.
524 	 */
525 	void			setTimelineBpm();
526 	/**
527 	 * Returns the local speed at a specific @a nBar in the
528 	 * Timeline.
529 	 *
530 	 * Timeline::HTimelineVector::m_htimelinebpm of the first
531 	 * Timeline::HTimelineVector::m_htimelinebeat bigger than @a
532 	 * nBar will be returned.
533 	 *
534 	 * If Hydrogen is in Song::PATTERN_MODE or
535 	 * Preferences::__useTimelineBpm is set to false, the global
536 	 * speed of the current Song Song::__bpm or, if no Song is
537 	 * present yet, the result of getNewBpmJTM() will be
538 	 * returned.
539 	 *
540 	 * Its counterpart is setTimelineBpm().
541 	 *
542 	 * \param nBar Position (in whole patterns) along the Timeline to
543 	 *   access the tempo at.
544 	 *
545 	 * \return Speed in beats per minute.
546 	 */
547 	float			getTimelineBpm( int nBar );
548 	Timeline*		getTimeline() const;
549 
550 	//export management
551 	bool			getIsExportSessionActive() const;
552 	void			startExportSession( int rate, int depth );
553 	void			stopExportSession();
554 	void			startExportSong( const QString& filename );
555 	void			stopExportSong();
556 
557 	CoreActionController* 	getCoreActionController() const;
558 
559 	/************************************************************/
560 	/********************** Playback track **********************/
561 	/**
562 	 * Wrapper around Song::set_playback_track_enabled().
563 	 *
564 	 * \param state Whether the playback track is enabled. It will
565 	 * be replaced by false, if no Song was selected (getSong()
566 	 * return nullptr).
567 	 */
568 	bool			setPlaybackTrackState( const bool state );
569 	/**
570 	 * Wrapper around Song::get_playback_track_enabled().
571 	 *
572 	 * \return Whether the playback track is enabled or false, if
573 	 * no Song was selected (getSong() return nullptr).
574 	 */
575 	bool			getPlaybackTrackState();
576 	/**
577 	 * Wrapper function for loading the playback track.
578 	 *
579 	 * Calls Song::set_playback_track_filename() and
580 	 * Sampler::reinitialize_playback_track(). While the former
581 	 * one is responsible to store metadata about the playback
582 	 * track, the latter one does load it to a new
583 	 * InstrumentLayer. The function is called by
584 	 * SongEditorPanel::editPlaybackTrackBtnPressed()
585 	 *
586 	 * \param filename Name of the file to load as the playback
587 	 * track
588 	 */
589 	void			loadPlaybackTrack( const QString filename );
590 
591 	/**\return #m_bActiveGUI*/
592 	bool			getActiveGUI() const;
593 	/**\param bActiveGUI Specifies whether the Qt5 GUI is active. Sets
594 	   #m_bActiveGUI.*/
595 	void			setActiveGUI( const bool bActiveGUI );
596 
597 	/**\return #m_pNextSong*/
598 	Song*			getNextSong() const;
599 	/**\param pNextSong Sets #m_pNextSong. #Song which is about to be
600 	   loaded by the GUI.*/
601 	void			setNextSong( Song* pNextSong );
602 	/** Calculates the lookahead for a specific tick size.
603 	 *
604 	 * During the humanization the onset of a Note will be moved
605 	 * Note::__lead_lag times the value calculated by this function.
606 	 *
607 	 * Since the size of a tick is tempo dependent, @a fTickSize
608 	 * allows you to calculate the lead-lag factor for an arbitrary
609 	 * position on the Timeline.
610 	 *
611 	 * \param fTickSize Number of frames that make up one tick.
612 	 *
613 	 * \return Five times the current size of a tick
614 	 * (TransportInfo::m_fTickSize) (in frames)
615 	 */
616 	int 			calculateLeadLagFactor( float fTickSize );
617 	/** Calculates time offset (in frames) used to determine the notes
618 	 * process by the audio engine.
619 	 *
620 	 * Due to the humanization there might be negative offset in the
621 	 * position of a particular note. To be able to still render it
622 	 * appropriately, we have to look into and handle notes from the
623 	 * future.
624 	 *
625 	 * The Lookahead is the sum of the #m_nMaxTimeHumanize and
626 	 * calculateLeadLagFactor() plus one (since it has to be larger
627 	 * than that).
628 	 *
629 	 * \param fTickSize Number of frames that make up one tick. Passed
630 	 * to calculateLeadLagFactor().
631 	 *
632 	 * \return Frame offset*/
633 	int 			calculateLookahead( float fTickSize );
634 	/**
635 	 * \return Whether JackAudioDriver is used as current audio
636 	 * driver.
637 	 */
638 	bool			haveJackAudioDriver() const;
639 	/**
640 	 * \return Whether JackAudioDriver is used as current audio driver
641 	 * and JACK transport was activated via the GUI
642 	 * (#Preferences::m_bJackTransportMode).
643 	 */
644 	bool			haveJackTransport() const;
645 	/**
646 	 * \return Whether we haveJackTransport() and there is an external
647 	 * JACK timebase master broadcasting us tempo information and
648 	 * making use disregard Hydrogen's Timeline information (see
649 	 * #JackAudioDriver::m_nIsTimebaseMaster).
650 	 */
651 	bool			haveJackTimebaseClient() const;
652 
653 	///midi lookuptable
654 	int 			m_nInstrumentLookupTable[MAX_INSTRUMENTS];
655 	/**
656 	 * Maximum time (in frames) a note's position can be off due to
657 	 * the humanization (lead-lag).
658 	 *
659 	 * Required to calculateLookahead(). Set to 2000.
660 	 */
661 	int 			m_nMaxTimeHumanize;
662 
663 private:
664 	/**
665 	 * Static reference to the Hydrogen singleton.
666 	 *
667 	 * It is created using the Hydrogen::Hydrogen() constructor,
668 	 * initialized with NULL and assigned a new Hydrogen instance
669 	 * if still 0 in create_instance().
670 	 */
671 	static Hydrogen* 	__instance;
672 
673 	/**
674 	 * Pointer to the current song. It is initialized with NULL in
675 	 * the Hydrogen() constructor, set via setSong(), and accessed
676 	 * via getSong().
677 	 */
678 	Song*			__song;
679 
680 	/**
681 	 * Auxiliary function setting a bunch of global variables.
682 	 *
683 	 * - #m_ntaktoMeterCompute = 1;
684 	 * - #m_nbeatsToCount = 4;
685 	 * - #m_nEventCount = 1;
686 	 * - #m_nTempoChangeCounter = 0;
687 	 * - #m_nBeatCount = 1;
688 	 * - #m_nCoutOffset = 0;
689 	 * - #m_nStartOffset = 0;
690 	 */
691 	void initBeatcounter();
692 
693 	// beatcounter
694 	float			m_ntaktoMeterCompute;	///< beatcounter note length
695 	int			m_nbeatsToCount;	///< beatcounter beats to count
696 	int			m_nEventCount;		///< beatcounter event
697 	int			m_nTempoChangeCounter;	///< count tempochanges for timeArray
698 	int			m_nBeatCount;		///< beatcounter beat to count
699 	double			m_nBeatDiffs[16];	///< beat diff
700 	timeval 		m_CurrentTime;		///< timeval
701 	timeval			m_LastTime;		///< timeval
702 	double			m_nLastBeatTime;	///< timediff
703 	double			m_nCurrentBeatTime;	///< timediff
704 	double			m_nBeatDiff;		///< timediff
705 	float			m_fBeatCountBpm;	///< bpm
706 	int			m_nCoutOffset;		///ms default 0
707 	int			m_nStartOffset;		///ms default 0
708 	//~ beatcounter
709 
710 
711 	// used for song export
712 	Song::SongMode		m_oldEngineMode;
713 	bool			m_bOldLoopEnabled;
714 	bool			m_bExportSessionIsActive;
715 
716 	/**
717 	 * Specifies whether the Qt5 GUI is active.
718 	 *
719 	 * When a new #Song is set via the core part of Hydrogen, e.g. in
720 	 * the context of session management, the #Song *must* be set via
721 	 * the GUI if active. Else the GUI will freeze.
722 	 *
723 	 * Set by setActiveGUI() and accessed via getActiveGUI().
724 	 */
725 	bool			m_bActiveGUI;
726 
727 	/**
728 	 * Stores a new #Song which is about of the loaded by the GUI.
729 	 *
730 	 * If #m_bActiveGUI is true, the core part of must not load a new
731 	 * #Song itself. Instead, the new #Song is prepared and stored in
732 	 * this object to be loaded by HydrogenApp::updateSongEvent() if
733 	 * H2Core::EVENT_UPDATE_SONG is pushed with a '1'.
734 	 *
735 	 * Set by setNextSong() and accessed via getNextSong().
736 	 */
737 	Song*			m_pNextSong;
738 
739 	/**
740 	 * Local instance of the Timeline object.
741 	 */
742 	Timeline*		m_pTimeline;
743 	/**
744 	 * Local instance of the CoreActionController object.
745 	 */
746 	CoreActionController* 	m_pCoreActionController;
747 
748 	/// Deleting instruments too soon leads to potential crashes.
749 	std::list<Instrument*> 	__instrument_death_row;
750 
751 	/**
752 	 * Constructor, entry point, and initialization of the
753 	 * Hydrogen application.
754 	 *
755 	 * It is called by the main() function after setting up a
756 	 * bunch of Qt5 stuff and creating an instance of the Logger
757 	 * and Preferences.
758 	 *
759 	 * Only one Hydrogen object is allowed to exist. If the
760 	 * #__instance object is present, the constructor will throw
761 	 * an error.
762 	 *
763 	 * - Sets the current #__song to NULL
764 	 * - Sets #m_bExportSessionIsActive to false
765 	 * - Creates a new Timeline #m_pTimeline
766 	 * - Creates a new CoreActionController
767 	 *   #m_pCoreActionController,
768 	 * - Calls initBeatcounter(), audioEngine_init(), and
769 	 *   audioEngine_startAudioDrivers()
770 	 * - Sets InstrumentComponent::m_nMaxLayers to
771 	 *   Preferences::m_nMaxLayers via
772 	 *   InstrumentComponent::setMaxLayers() and
773 	 *   Preferences::getMaxLayers()
774 	 * - Starts the OscServer using OscServer::start() if
775 	 *   #H2CORE_HAVE_OSC was set during compilation.
776 	 * - Fills #m_nInstrumentLookupTable with the corresponding
777 	 *   index of each element.
778 	 */
779 	Hydrogen();
780 
781 	void __kill_instruments();
782 
783 };
784 
785 
786 /*
787  * inline methods
788  */
getTimeline()789 inline Timeline* Hydrogen::getTimeline() const
790 {
791 	return m_pTimeline;
792 }
793 
getCoreActionController()794 inline CoreActionController* Hydrogen::getCoreActionController() const
795 {
796 	return m_pCoreActionController;
797 }
798 
799 
getCurrentDrumkitname()800 inline const QString& Hydrogen::getCurrentDrumkitname()
801 {
802 	return m_currentDrumkit;
803 }
804 
getIsExportSessionActive()805 inline bool Hydrogen::getIsExportSessionActive() const
806 {
807 	return m_bExportSessionIsActive;
808 }
809 
setCurrentDrumkitname(const QString & currentdrumkitname)810 inline void Hydrogen::setCurrentDrumkitname( const QString& currentdrumkitname )
811 {
812 	this->m_currentDrumkit = currentdrumkitname;
813 }
814 
getPlaybackTrackState()815 inline bool Hydrogen::getPlaybackTrackState()
816 {
817 	Song* pSong = getSong();
818 	bool  bState;
819 
820 	if(!pSong){
821 		bState = false;
822 	} else {
823 		bState = pSong->get_playback_track_enabled();
824 	}
825 	return 	bState;
826 }
827 
getActiveGUI()828 inline bool Hydrogen::getActiveGUI() const {
829 	return m_bActiveGUI;
830 }
setActiveGUI(const bool bActiveGUI)831 inline void Hydrogen::setActiveGUI( const bool bActiveGUI ) {
832 	m_bActiveGUI = bActiveGUI;
833 }
getNextSong()834 inline Song* Hydrogen::getNextSong() const {
835 	return m_pNextSong;
836 }
setNextSong(Song * pNextSong)837 inline void Hydrogen::setNextSong( Song* pNextSong ) {
838 	m_pNextSong = pNextSong;
839 }
840 
841 };
842 
843 #endif
844 
845