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 
23 #ifndef H2_JACK_OUTPUT_H
24 #define H2_JACK_OUTPUT_H
25 
26 #include <hydrogen/IO/AudioOutput.h>
27 #include <hydrogen/IO/NullDriver.h>
28 
29 // check if jack support is disabled
30 #if defined(H2CORE_HAVE_JACK) || _DOXYGEN_
31 // JACK support es enabled.
32 
33 #include <map>
34 #include <pthread.h>
35 #include <jack/jack.h>
36 
37 #if defined(H2CORE_HAVE_JACKSESSION) || _DOXYGEN_
38 #include <jack/session.h>
39 #endif
40 
41 #include <jack/transport.h>
42 
43 #include <hydrogen/globals.h>
44 #include <hydrogen/hydrogen.h>
45 
46 
47 
48 namespace H2Core
49 {
50 
51 class Song;
52 class Instrument;
53 class InstrumentComponent;
54 /**
55  * JACK (Jack Audio Connection Kit) server driver.
56  *
57  * __Transport Control__:
58  *
59  * Each JACK client can start and stop the transport or relocate the
60  * current transport position. The request will take place in
61  * cycles. During the first the status of the transport changes to
62  * _JackTransportStarting_ to inform all clients a change is about to
63  * happen. During the second the status is again
64  * _JackTransportRolling_ and the transport position is updated
65  * according to the request. The current timebase master (see below),
66  * if present, needs another cycle to update the additional transport
67  * information.
68  *
69  * Such a relocation request is also triggered when clicking on the
70  * timeline or the player control buttons of Hydrogen. Internally,
71  * audioEngine_stop() is called during the cycle in which the JACK
72  * transport status is _JackTransportStarting_ and started again by
73  * audioEngine_start() when in _JackTransportRolling_ in the next
74  * cycle. Note that if there are slow synchronizing client in JACK's
75  * connection graph, it can take multiple cycles until the JACK
76  * transport is rolling again.
77  *
78  * Also note that Hydrogen overwrites its local TransportInfo stored
79  * in AudioOutput::m_transport only with the transport position of the
80  * JACK server if a relocation did happened or another timebase master
81  * did change the speed. During normal transport the current position
82  * TransportInfo::m_nFrames will be always the same as the one of JACK
83  * during a cycle and incremented by the buffer size in
84  * audioEngine_process() at the very end of the cycle. The same
85  * happens for the transport information of the JACK server but in
86  * parallel.
87  *
88  * __Timebase Master__:
89  *
90  * The timebase master is responsible to update additional information
91  * in the transport information of the JACK server apart from the
92  * transport position in frames (see TransportInfo::m_nFrames if you
93  * aren't familiar with frames), like the current beat, bar, tick,
94  * tick size, speed etc. Every client can be registered as timebase
95  * master by supplying a callback (for Hydrogen this would be
96  * JackTimebaseCallback()) but there can be at most one timebase
97  * master at a time. Having none at all is perfectly fine too. Apart
98  * from this additional responsibility, the registered client has no
99  * other rights compared to others.
100  *
101  * After the status of the JACK transport has changed from
102  * _JackTransportStarting_ to _JackTransportRolling_, the timebase
103  * master needs an additional cycle to update its information.
104  *
105  * Having an external timebase master present will change the general
106  * behavior of Hydrogen. All local tempo settings on the Timeline will
107  * be disregarded and the tempo broadcasted by the JACK server will be
108  * used instead.
109  *
110  * This object will only be accessible if #H2CORE_HAVE_JACK was defined
111  * during the configuration and the user enables the support of the
112  * JACK server.
113  */
114 class JackAudioDriver : public AudioOutput
115 {
116 	H2_OBJECT
117 public:
118 	/**
119 	 * Object holding the external client session with the JACK
120 	 * server.
121 	 *
122 	 * It is set via init().
123 	 */
124 	jack_client_t* m_pClient;
125 	/**
126 	 * Constructor of the JACK server driver.
127 	 *
128 	 * @param m_processCallback Prototype for the client supplied
129 			 function that is called by the engine anytime there is
130 			 work to be done. It gets two input arguments _nframes_ of
131 			 type jack_nframes_t, which specifies the number of frames
132 			 to process, and a void pointer called _arg_, which points
133 			 to a client supplied structure.  Two preconditions do act
134 			 on the _nframes_ argument: _nframes_ == getBufferSize()
135 			 and _nframes_ == pow(2,x) It returns zero on success and
136 			 non-zero on error.
137 	 */
138 	JackAudioDriver( JackProcessCallback m_processCallback );
139 	/**
140 	 * Destructor of the JACK server driver.
141 	 *
142 	 * Calling disconnect().
143 	 */
144 	~JackAudioDriver();
145 
146 	/**
147 	 * Connects to output ports via the JACK server.
148 	 *
149 	 * Starts by telling the JACK server that Hydrogen is ready to
150 	 * process audio using the jack_activate function (from the
151 	 * jack/jack.h header) and overwriting the memory allocated by
152 	 * #m_pTrackOutputPortsL and #m_pTrackOutputPortsR with zeros. If
153 	 * the #m_bConnectDefaults variable is true or LashClient is used
154 	 * and Hydrogen is not within a new Lash project, the function
155 	 * attempts to connect the #m_pOutputPort1 port with
156 	 * #m_sOutputPortName1 and the #m_pOutputPort2 port with
157 	 * #m_sOutputPortName2. To establish the connection,
158 	 * _jack_connect()_ (jack/jack.h) will be used. In case this was
159 	 * not successful, the function will look up all ports containing
160 	 * the _JackPortIsInput_ (jack/types.h) flag using
161 	 * _jack_get_ports()_ (jack/jack.h) and attempts to connect to the
162 	 * first two it found.
163 	 *
164 	 * @return
165 	 * - __0__ : if either the connection of the output ports did
166 	 *       work, two ports having the _JackPortIsInput_ flag where
167 	 *       found and the #m_pOutputPort1 and #m_pOutputPort2 ports
168 	 *       where successfully connected to them, or the user enabled
169 	 *       Lash during compilation and an established project was
170 	 *       used.
171 	 * - __1__ : The activation of the JACK client using
172 	 *       _jack_activate()_ (jack/jack.h) did fail.
173 	 * - __2__ : The connections to #m_sOutputPortName1 and
174 	 *       #m_sOutputPortName2 could not be established and the
175 	 *       there were either no JACK ports holding the
176 	 *       JackPortIsInput flag found or no connection to them could
177 	 *       be established.
178 	 */
179 	int connect();
180 	/**
181 	 * Disconnects the JACK client of the Hydrogen from the JACK
182 	 * server.
183 	 *
184 	 * Firstly, it calls deactivate(). Then, it closes the connection
185 	 * between the JACK server and the local client using
186 	 * jack_client_close (jack/jack.h), and sets the #m_pClient
187 	 * pointer to nullptr.
188 	 */
189 	void disconnect();
190 	/**
191 	 * Deactivates the JACK client of Hydrogen and disconnects all
192 	 * ports belonging to it.
193 	 *
194 	 * It calls the _jack_deactivate()_ (jack/jack.h) function on the
195 	 * current client #m_pClient and overwrites the memory allocated
196 	 * by #m_pTrackOutputPortsL and #m_pTrackOutputPortsR with zeros.
197 	 */
198 	void deactivate();
199 	/** \return Global variable #jackServerBufferSize. */
200 	unsigned getBufferSize();
201 	/** \return Global variable #jackServerSampleRate. */
202 	unsigned getSampleRate();
203 	/** Accesses the number of output ports currently in use.
204 	 * \return #m_nTrackPortCount */
205 	int getNumTracks();
206 
207 	/** \return #m_JackTransportState */
getTransportState()208 	jack_transport_state_t getTransportState() {
209 		return m_JackTransportState;
210 	}
211 	/** \return #m_JackTransportPos */
getTransportPos()212 	jack_position_t getTransportPos() {
213 		return m_JackTransportPos;
214 	}
215 
216 	/**
217 	 * Creates per component output ports for each instrument.
218 	 *
219 	 * Firstly, it resets #m_trackMap with zeros. Then, it loops
220 	 * through all the instruments and their components, creates a new
221 	 * output or resets an existing one for each of them using
222 	 * setTrackOutput(), and stores the corresponding track number in
223 	 * #m_trackMap. Finally, all ports in #m_pTrackOutputPortsL and
224 	 * #m_pTrackOutputPortsR, which haven't been used in the previous
225 	 * step, are unregistered using _jack_port_unregister()_
226 	 * (jack/jack.h) and overwritten with 0. #m_nTrackPortCount will
227 	 * be set to biggest track number encountered during the
228 	 * creation/reassignment step.
229 	 *
230 	 * The function will only perform its tasks if the
231 	 * Preferences::m_bJackTrackOuts is set to true.
232 	 */
233 	void makeTrackOutputs( Song* pSong );
234 	/**
235 	 * Renames the @a n 'th port of JACK client and creates it if
236 	 * it's not already present.
237 	 *
238 	 * If the track number @a n is bigger than the number of ports
239 	 * currently in usage #m_nTrackPortCount, @a n + 1 -
240 	 * #m_nTrackPortCount new stereo ports will be created using
241 	 * _jack_port_register()_ (jack/jack.h) and #m_nTrackPortCount
242 	 * updated to @a n + 1.
243 	 *
244 	 * Afterwards, the @a n 'th port is renamed to a concatenation of
245 	 * "Track_", DrumkitComponent::__name, "_", @a n + 1, "_",
246 	 * Instrument::__name, and "_L", or "_R" using either
247 	 * _jack_port_rename()_ (if HAVE_JACK_PORT_RENAME is defined) or
248 	 * _jack_port_set_name()_ (both jack/jack.h). The former renaming
249 	 * function triggers a _PortRename_ notifications to clients that
250 	 * have registered a port rename handler.
251 	 *
252 	 * \param n Track number for which a port should be renamed
253 	 *   (and created).
254 	 * \param instr Pointer to the corresponding Instrument.
255 	 * \param pCompo Pointer to the corresponding
256 	 *   InstrumentComponent.
257 	 * \param pSong Pointer to the corresponding Song.
258 	 */
259 	void setTrackOutput( int n, Instrument* instr, InstrumentComponent* pCompo, Song* pSong );
260 
261 	/** \param flag Sets #m_bConnectDefaults*/
setConnectDefaults(bool flag)262 	void setConnectDefaults( bool flag ) {
263 		m_bConnectDefaults = flag;
264 	}
265 	/** \return #m_bConnectDefaults */
getConnectDefaults()266 	bool getConnectDefaults() {
267 		return m_bConnectDefaults;
268 	}
269 
270 	/**
271 	 * Get content in the left stereo output port.
272 	 *
273 	 * It calls _jack_port_get_buffer()_ (jack/jack.h) with both the
274 	 * port name #m_pOutputPort1 and buffer size
275 	 * #jackServerBufferSize.
276 	 *
277 	 * \return Pointer to buffer content of type
278 	 * _jack_default_audio_sample_t*_ (jack/types.h)
279 	 */
280 	float* getOut_L();
281 	/**
282 	 * Get content in the right stereo output port.
283 	 *
284 	 * It calls _jack_port_get_buffer()_ (jack/jack.h) with both the
285 	 * port name #m_pOutputPort2 and buffer size
286 	 * #jackServerBufferSize.
287 	 *
288 	 * \return Pointer to buffer content of type
289 	 * _jack_default_audio_sample_t*_ (jack/types.h)
290 	 */
291 	float* getOut_R();
292 	/**
293 	 * Get content of left output port of a specific track.
294 	 *
295 	 * It calls _jack_port_get_buffer()_ (jack/jack.h) with the port
296 	 * in the @a nTrack element of #m_pTrackOutputPortsL and buffer
297 	 * size #jackServerBufferSize.
298 	 *
299 	 * \param nTrack Track number. Must not be bigger than
300 	 * #m_nTrackPortCount.
301 	 *
302 	 * \return Pointer to buffer content of type
303 	 * _jack_default_audio_sample_t*_ (jack/types.h)
304 	 */
305 	float* getTrackOut_L( unsigned nTrack );
306 	/**
307 	 * Get content of right output port of a specific track.
308 	 *
309 	 * It calls _jack_port_get_buffer()_ (jack/jack.h) with the port
310 	 * in the @a nTrack element of #m_pTrackOutputPortsR and buffer
311 	 * size #jackServerBufferSize.
312 	 *
313 	 * \param nTrack Track number. Must not be bigger than
314 	 * #m_nTrackPortCount.
315 	 *
316 	 * \return Pointer to buffer content of type
317 	 * _jack_default_audio_sample_t*_ (jack/types.h)
318 	 */
319 	float* getTrackOut_R( unsigned nTrack );
320 	/**
321 	 * Convenience function looking up the track number of a component
322 	 * of an instrument using in #m_trackMap using their IDs
323 	 * Instrument::__id and
324 	 * InstrumentComponent::__related_drumkit_componentID. Using the
325 	 * track number it then calls getTrackOut_L( unsigned ) and
326 	 * returns its result.
327 	 *
328 	 * \param instr Pointer to an Instrument
329 	 * \param pCompo Pointer to one of the instrument's components.
330 	 *
331 	 * \return Pointer to buffer content of type
332 	 * _jack_default_audio_sample_t*_ (jack/types.h)
333 	 */
334 	float* getTrackOut_L( Instrument* instr, InstrumentComponent* pCompo );
335 	/**
336 	 * Convenience function looking up the track number of a component
337 	 * of an instrument using in #m_trackMap using their IDs
338 	 * Instrument::__id and
339 	 * InstrumentComponent::__related_drumkit_componentID. Using the
340 	 * track number it then calls getTrackOut_R( unsigned ) and
341 	 * returns its result.
342 	 *
343 	 * \param instr Pointer to an Instrument
344 	 * \param pCompo Pointer to one of the instrument's components.
345 	 *
346 	 * \return Pointer to buffer content of type
347 	 * _jack_default_audio_sample_t*_ (jack/types.h)
348 	 */
349 	float* getTrackOut_R( Instrument* instr, InstrumentComponent* pCompo );
350 
351 	/**
352 	 * Initializes the JACK audio driver.
353 	 *
354 	 * Firstly, it determines the destination ports
355 	 * #m_sOutputPortName1 and #m_sOutputPortName2 the output ports of
356 	 * Hydrogen will be connected to in connect() from
357 	 * Preferences::m_sJackPortName1 and
358 	 * Preferences::m_sJackPortName2. The name of the JACK client is
359 	 * either set to "Hydrogen" or, if #H2CORE_HAVE_OSC was defined
360 	 * during compilation and OSC support is enabled, to
361 	 * Preferences::m_sNsmClientId via Preferences::getNsmClientId().
362 	 *
363 	 * Next, the function attempts to open an external client session
364 	 * with the JACK server using _jack_client_open()_ (jack/jack.h)
365 	 * and saves it to the pointer #m_pClient. In case this didn't
366 	 * work properly, it will start two more attempts. Sometime JACK
367 	 * doesn't stop and start fast enough. If the compiler flag
368 	 * #H2CORE_HAVE_JACKSESSION was set and the user enabled the usage
369 	 * of JACK session, the client will be opened using the
370 	 * corresponding option and the sessionID Token
371 	 * Preferences::jackSessionUUID, obtained via
372 	 * Preferences::getJackSessionUUID(), will be provided so the
373 	 * sessionmanager can identify the client again.
374 	 *
375 	 * If the client was opened properly, the function will get its
376 	 * sample rate using _jack_get_sample_rate()_ and buffer size
377 	 * using _jack_get_buffer_size()_ (both jack/jack.h) and stores
378 	 * them in #jackServerSampleRate, Preferences::m_nSampleRate,
379 	 * #jackServerBufferSize, and Preferences::m_nBufferSize. In
380 	 * addition, it also registers JackAudioDriver::m_processCallback,
381 	 * H2Core::jackDriverSampleRate, H2Core::jackDriverBufferSize, and
382 	 * H2Core::jackDriverShutdown using _jack_set_process_callback()_,
383 	 * _jack_set_sample_rate_callback()_,
384 	 * _jack_set_buffer_size_callback()_, and _jack_on_shutdown()_
385 	 * (all in jack/jack.h).
386 	 *
387 	 * Next, two output ports called "out_L" and "out_R" are
388 	 * registered for the client #m_pClient using
389 	 * _jack_port_register()_.
390 	 *
391 	 * If everything worked properly, LASH is used
392 	 * (Preferences::useLash()) by the user, and the LashClient is
393 	 * LashClient::isConnected() the name of the client will be stored
394 	 * in LashClient::jackClientName using
395 	 * LashClient::setJackClientName. If JACK session was enabled, the
396 	 * jack_session_callback() will be registered using
397 	 * _jack_set_session_callback()_ (jack/session.h).
398 	 *
399 	 * Finally, the function will check whether Hydrogen should be the
400 	 * JACK timebase master or not via Preferences::m_bJackMasterMode
401 	 * and calls initTimebaseMaster() if its indeed the case.
402 	 *
403 	 * \param bufferSize Unused and only present to assure
404 	 * compatibility with the JACK API.
405 	 *
406 	 * \return
407 	 * -  __0__ : on success.
408 	 * - __-1__ : if the pointer #m_pClient obtained via
409 	 * _jack_client_open()_ (jack/jack.h) is 0.
410 	 * - __4__ : unable to register the "out_L" and/or "out_R"
411 	 * output ports for the JACK client using
412 	 * _jack_port_register()_ (jack/jack.h).
413 	 */
414 	int init( unsigned bufferSize );
415 
416 	/**
417 	 * Starts the JACK transport.
418 	 *
419 	 * If the JACK transport was activated in the GUI by clicking
420 	 * either the "J.TRANS" or "J.MASTER" button, the
421 	 * _jack_transport_start()_ (jack/transport.h) function will be
422 	 * called to start the JACK transport. Else, the internal
423 	 * TransportInfo::m_status will be set to TransportInfo::ROLLING
424 	 * instead.
425 	 */
426 	virtual void play();
427 	/**
428 	 * Stops the JACK transport.
429 	 *
430 	 * If the JACK transport was activated in the GUI by clicking
431 	 * either the "J.TRANS" or "J.MASTER" button, the
432 	 * _jack_transport_stop()_ (jack/transport.h) function will be
433 	 * called to stop the JACK transport. Else, the internal
434 	 * TransportInfo::m_status will be set to TransportInfo::STOPPED
435 	 * instead.
436 	 */
437 	virtual void stop();
438 	/**
439 	 * Re-positions the transport position to @a nFrame.
440 	 *
441 	 * If the Preferences::USE_JACK_TRANSPORT mode is chosen in
442 	 * Preferences::m_bJackTransportMode, the
443 	 * _jack_transport_locate()_ (jack/transport.h) function will be
444 	 * used to request the new transport position. If not, @a nFrame
445 	 * will be assigned to TransportInfo::m_nFrames of the local
446 	 * instance of the TransportInfo AudioOutput::m_transport.
447 	 *
448 	 * The new position takes effect in two process cycles during
449 	 * which JACK's state will be in JackTransportStarting and the
450 	 * transport won't be rolling.
451 	 *
452 	 * \param nFrame Requested new transport position.
453 	 */
454 	virtual void locate( unsigned long nFrame );
455 	/**
456 	 * Updating the local instance of the TransportInfo
457 	 * AudioOutput::m_transport.
458 	 *
459 	 * The function queries the transport position and additional
460 	 * information from the JACK server, writes them to
461 	 * #m_JackTransportPos and in #m_JackTransportState, and updates
462 	 * the information stored in AudioOutput::m_transport in case of a
463 	 * mismatch.
464 	 *
465 	 * If #m_JackTransportState is either _JackTransportStopped_ or
466      * _JackTransportStarting_, transport will be (temporarily)
467      * stopped - TransportInfo::m_status will be set to
468      * TransportInfo::STOPPED. If it's _JackTransportRolling_,
469      * transport will be started - TransportInfo::m_status will be set
470      * to TransportInfo::ROLLING.
471 	 *
472      * The function will check whether a relocation took place by the
473 	 * JACK server and (afterwards) whether the current tempo did
474 	 * change with respect to the last transport cycle. In case of a
475 	 * relocation, #m_frameOffset will be reset to 0,
476 	 * TransportInfo::m_nFrames updated to the new value provided by
477 	 * JACK, and - if Hydrogen is in Song::PATTERN_MODE - the playback
478 	 * moved to the beginning of the pattern. A change in speed, on
479 	 * the other hand, depends on the local JACK setup. If there is a
480 	 * timebase master, which broadcasts tempo information via JACK,
481 	 * and it's not Hydrogen itself, all customizations in the
482 	 * Timeline will be disregarded and the tempo of the master will
483 	 * be used instead. If Hydrogen is the timebase master or there is
484 	 * none at all, Hydrogen::setTimelineBpm() will be used to keep
485 	 * the transport tempo aligned the settings in the Timeline.
486 	 *
487 	 * If Preferences::USE_JACK_TRANSPORT was not selected in
488 	 * Preferences::m_bJackTransportMode, the function will return
489 	 * without performing any action.
490 	 */
491 	virtual void updateTransportInfo();
492 	/** Set the tempo stored TransportInfo::m_fBPM of the local
493 	 * instance of the TransportInfo AudioOutput::m_transport.
494 	 *
495 	 * Only sets the tempo to @a fBPM if its value is at least
496 	 * 1. Sometime (especially during the first cycle after locating
497 	 * with transport stopped) the JACK server sends some artifacts
498 	 * (6.95334e-310) which should not be assigned.
499 	 *
500 	 * \param fBPM new tempo.
501 	 */
502 	virtual void setBpm( float fBPM );
503 	/**
504 	 * Calculates the difference between the true transport position
505 	 * and the internal one.
506 	 *
507 	 * The internal transport position used in most parts of Hydrogen
508 	 * is given in ticks. But since the size of a tick is
509 	 * tempo-dependent, passing a tempo marker in the Timeline will
510 	 * cause the corresponding internal transport position in frames
511 	 * to diverge from the external one by a constant offset. This
512 	 * function will calculate and store it in #m_frameOffset.
513 	 *
514 	 * \param oldFrame Provides the previous transport position in
515 	 * frames prior to the change in tick size. This is required if
516 	 * transport is not rolling during the relocation into a region of
517 	 * different speed since there is no up-to-date JACK query
518 	 * providing these information.
519 	 */
520 	void calculateFrameOffset(long long oldFrame);
521 
522 	/**
523 	 * Registers Hydrogen as JACK timebase master.
524 	 *
525 	 * If for some reason registering Hydrogen as timebase master does
526 	 * not work, the function sets Preferences::m_bJackMasterMode to
527 	 * Preferences::NO_JACK_TIME_MASTER.
528 	 *
529 	 * If the function is called with Preferences::m_bJackMasterMode
530 	 * set to Preferences::NO_JACK_TIME_MASTER,
531 	 * releaseTimebaseMaster() will be called instead.
532 	 */
533 	void initTimebaseMaster();
534 	/**
535 	 * Calls _jack_release_timebase()_ (jack/transport.h) to release
536 	 * Hydrogen from the JACK timebase master responsibilities. This
537 	 * causes the JackTimebaseCallback() callback function to not be
538 	 * called by the JACK server anymore.
539 	 */
540 	void releaseTimebaseMaster();
541 
542 	/**
543 	 * \return #m_nIsTimebaseMaster
544 	 */
545 	int getIsTimebaseMaster() const;
546 	/** Stores the latest transport position (for both rolling and
547 	 * stopped transport).
548 	 *
549 	 * In case the user is clicking on the
550 	 * SongEditor::mousePressEvent() will trigger both a relocation
551 	 * and a change in speed. The change in speed causes the
552 	 * audioEngine_checkBPMChange() function to update the ticksize in
553 	 * case transported got moved into a region of different tempo and
554 	 * triggers the calculateFrameOffset() function. But the latter
555 	 * can only work properly if transport is rolling since it has to
556 	 * know the frame position prior to the change in tick size and
557 	 * there is no up-to-date JACK query providing this information.
558 	 */
559 	int m_currentPos;
560 protected:
561 	/**
562 	 * Callback function registered to the JACK server in
563 	 * initTimebaseMaster() if Hydrogen is set as JACK timebase master.
564 	 *
565 	 * It will update the current position not just in frames till
566 	 * the beginning of the song, but also in terms of beat, bar,
567 	 * and tick values.
568 	 *
569 	 * The function it will be called after the
570 	 * audioEngine_process() function and only if the
571 	 * #m_JackTransportState is _JackTransportRolling_.
572 	 *
573 	 * \param state Current transport state. Not used within the
574 	 * function but to ensure compatibility.
575 	 * \param nFrames Buffer size. Not used within the function but
576 	 * to ensure compatibility.
577 	 * \param pJackPosition Current transport position.
578 	 * \param new_pos Updated transport position in frames. Not
579 	 * used within the function but to ensure compatibility.
580 	 * \param arg Pointer to a JackAudioDriver instance.
581 	 */
582 	static void JackTimebaseCallback( jack_transport_state_t state,
583 					    jack_nframes_t nFrames,
584 					    jack_position_t* pJackPosition,
585 					    int new_pos,
586 					    void* arg );
587 
588 #if defined(H2CORE_HAVE_JACKSESSION) || _DOXYGEN_
589 	/**
590 	 * Function to call by the JACK server when a session event is
591 	 * to be delivered.
592 	 *
593 	 * It is registered to the JACK client in init() using
594 	 * _jack_set_session_callback()_ (jack/session.h) if
595 	 * #H2CORE_HAVE_JACKSESSION was defined during compilation.
596 	 *
597 	 * Internally it hands the @a event to
598 	 * jack_session_callback_impl().
599 	 *
600 	 * \param event Jack session event (see jack/session.h)
601 	 * \param arg Pointer to an instance of the JackAudioDriver.
602 	 */
603 	static void jack_session_callback( jack_session_event_t* event,
604 					   void* arg );
605 
606 	void jack_session_callback_impl( jack_session_event_t* event );
607 #endif
608 
609 private:
610 	/**
611 	 * Constant offset between the internal transport position in
612 	 * TransportInfo::m_nFrames and the external one.
613 	 *
614 	 * Imagine the following setting: During the playback you decide
615 	 * to change the speed of the song. This would cause a lot of
616 	 * position information within Hydrogen, which are given in ticks,
617 	 * to be off since the tick size depends on the speed and just got
618 	 * changed too. Instead, TransportInfo::m_nFrames will scaled to
619 	 * reflect the changes and everything will be still in place with
620 	 * the user to not note a single thing. Unfortunately, now the
621 	 * transport position in frames of the audio engine and of the
622 	 * JACK server are off by a constant offset. To nevertheless be
623 	 * able to identify relocation in updateTransportInfo(), this
624 	 * constant offset is stored in this variable and used in
625 	 * updateTransportInfo() to determine whether a relocation did
626 	 * happen.
627 	 *
628 	 * Positive values correspond to a position ahead of the current
629 	 * transport information. The variable is initialized with 0 in
630 	 * JackAudioDriver() and updated in calculateFrameOffset().
631 	 */
632 	long long			m_frameOffset;
633 	/**
634 	 * Function the JACK server will call whenever there is work to
635 	 * do.
636 	 *
637 	 * The audioEngine_process() function will be used and registered
638 	 * using _jack_set_process_callback()_ (jack/jack.h) in init().
639 	 *
640 	 * The code must be suitable for real-time execution.  That means
641 	 * that it cannot call functions that might block for a long
642 	 * time. This includes _malloc()_, _free()_, _printf()_,
643 	 * _pthread_mutex_lock()_, _sleep()_, _wait()_, _poll()_,
644 	 * _select()_, _pthread_join()_, _pthread_cond_wait()_, etc, etc.
645 	 */
646 	JackProcessCallback		m_processCallback;
647 	/**
648 	 * Left source port for which a connection to #m_sOutputPortName1
649 	 * will be established in connect() via the JACK server.
650 	 */
651 	jack_port_t*			m_pOutputPort1;
652 	/**
653 	 * Right source port for which a connection to #m_sOutputPortName2
654 	 * will be established in connect() via the JACK server.
655 	 */
656 	jack_port_t*			m_pOutputPort2;
657 	/**
658 	 * Destination of the left source port #m_pOutputPort1, for which
659 	 * a connection will be established in connect(). It is set to
660 	 * Preferences::m_sJackPortName1 during the call of init().
661 	 */
662 	QString				m_sOutputPortName1;
663 	/**
664 	 * Destination of the right source port #m_pOutputPort2, for which
665 	 * a connection will be established in connect(). It is set to
666 	 * Preferences::m_sJackPortName2 during the call of init().
667 	 */
668 	QString				m_sOutputPortName2;
669 	/**
670 	 * Matrix containing the track number of each component of of all
671 	 * instruments. Its rows represent the instruments and its columns
672 	 * their components. _m_trackMap[2][1]=6_ thus therefore mean the
673 	 * output of the second component of the third instrument is
674 	 * assigned the seventh output port. Since its total size is
675 	 * defined by #MAX_INSTRUMENTS and #MAX_COMPONENTS, most of its
676 	 * entries will be zero.
677 	 *
678 	 * It gets updated by makeTrackOutputs().
679 	 */
680 	int				m_trackMap[MAX_INSTRUMENTS][MAX_COMPONENTS];
681 	/**
682 	 * Total number of output ports currently in use. It gets updated
683 	 * by makeTrackOutputs().
684 	 */
685 	int				m_nTrackPortCount;
686 	/**
687 	 * Vector of all left audio output ports currently used by the
688 	 * local JACK client.
689 	 *
690 	 * They will be initialized with all zeros in both
691 	 * JackAudioDriver(), deactivate(), and connect(). Individual
692 	 * components will be created, renamed, or reassigned in
693 	 * setTrackOutput(), deleted in makeTrackOutputs(), and accessed
694 	 * via getTrackOut_L().  It is set to a length of
695 	 * #MAX_INSTRUMENTS.
696 	 */
697 	jack_port_t*			m_pTrackOutputPortsL[MAX_INSTRUMENTS];
698 	/**
699 	 * Vector of all right audio output ports currently used by the
700 	 * local JACK client.
701 	 *
702 	 * They will be initialized with all zeros in both
703 	 * JackAudioDriver(), deactivate(), and connect(). Individual
704 	 * components will be created, renamed, or reassigned in
705 	 * setTrackOutput(), deleted in makeTrackOutputs(), and accessed
706 	 * via getTrackOut_R().  It is set to a length of
707 	 * #MAX_INSTRUMENTS.
708 	 */
709 	jack_port_t*		 	m_pTrackOutputPortsR[MAX_INSTRUMENTS];
710 
711 	/**
712 	 * Current transport state returned by
713 	 * _jack_transport_query()_ (jack/transport.h).
714 	 *
715 	 * It is valid for the entire cycle and can have five
716 	 * different values:
717 	 * - _JackTransportStopped_ = 0 : Transport is halted
718 	 * - _JackTransportRolling_ = 1 : Transport is playing
719 	 * - _JackTransportLooping_ = 2 : For OLD_TRANSPORT, now
720 	 *   ignored
721 	 * - _JackTransportStarting_ = 3 : Waiting for sync ready
722 	 * - _JackTransportNetStarting_ = 4 : Waiting for sync ready
723 	 *   on the network
724 	 *
725 	 * The actual number of states depends on your JACK
726 	 * version. The listing above was done for version 1.9.12.
727 	 */
728 	jack_transport_state_t		m_JackTransportState;
729 	/**
730 	 * Current transport position obtained using
731 	 * _jack_transport_query()_ (jack/transport.h).
732 	 *
733 	 * It corresponds to the first frame of the current cycle. If it
734 	 * is NULL, _jack_transport_query()_ won't return any position
735 	 * information.
736 	 *
737 	 * The __valid__ member of #m_JackTransportPos will show which
738 	 * fields contain valid data. Thus, if it is set to
739 	 * _JackPositionBBT_, bar, beat, and tick information are
740 	 * provided by the current timebase master in addition to the
741 	 * transport information in frames. It is of class
742 	 * _jack_position_bits_t_ (jack/types.h) and is an enumerator
743 	 * with five different options:
744 	 * - _JackPositionBBT_ = 0x10 : Bar, Beat, Tick
745 	 * - _JackPositionTimecode_ = 0x20 : External timecode
746 	 * - _JackBBTFrameOffset_ = 0x40 : Frame offset of BBT
747 	 *   information
748 	 * - _JackAudioVideoRatio_ = 0x80 : audio frames per video
749 	 *   frame
750 	 * - _JackVideoFrameOffset_ = 0x100 : frame offset of first
751 	 *   video frame
752 	 *
753 	 * The __frame__ member contains the current transport
754 	 * position.
755 	 *
756 	 * It is set in updateTransportInfo(). Please see the
757 	 * documentation of JackTimebaseCallback() for more information
758 	 * about its different members.
759 	 */
760 	jack_position_t			m_JackTransportPos;
761 
762 	/**
763 	 * Specifies whether the default left and right (master) audio
764 	 * JACK ports will be automatically connected to the system's sink
765 	 * when registering the JACK client in connect().
766 	 *
767 	 * After the JackAudioDriver has been created by createDriver(),
768 	 * the variable will be, again, set to
769 	 * Preferences::m_bJackConnectDefaults.
770 	 */
771 	bool				m_bConnectDefaults;
772 	/**
773 	 * Whether Hydrogen or another program is Jack timebase master.
774 	 *
775 	 * - #m_nIsTimebaseMaster > 0 - Hydrogen itself is timebase
776           master.
777 	 * - #m_nIsTimebaseMaster == 0 - an external program is timebase
778           master and Hydrogen will disregard all tempo marker on the
779           Timeline and, instead, only use the BPM provided by JACK.
780 	 * - #m_nIsTimebaseMaster < 0 - only normal clients registered.
781 	 *
782 	 * While Hydrogen can unregister as timebase master on its own, it
783 	 * can not be observed directly whether another application has
784 	 * taken over as timebase master. When the JACK server is
785 	 * releasing Hydrogen in the later case, it won't advertise this
786 	 * fact but simply won't call the JackTimebaseCallback()
787 	 * anymore. But since this will be called in every cycle after
788 	 * updateTransportInfo(), we can use this variable to determine if
789 	 * Hydrogen is still timebase master.
790 	 *
791 	 * As Hydrogen registered as timebase master using
792 	 * initTimebaseMaster() it will be initialized with 1, decremented
793 	 * in updateTransportInfo(), and reset to 1 in
794 	 * JackTimebaseCallback(). Whenever it is zero in
795 	 * updateTransportInfo(), #m_nIsTimebaseMaster will be updated
796 	 * accordingly.
797 	 */
798 	int				m_nIsTimebaseMaster;
799 
800 };
801 
getIsTimebaseMaster()802 inline int JackAudioDriver::getIsTimebaseMaster() const {
803 	return m_nIsTimebaseMaster;
804 }
getNumTracks()805 inline int JackAudioDriver::getNumTracks() {
806 	return m_nTrackPortCount;
807 }
808 
809 
810 
811 }; // H2Core namespace
812 
813 
814 #else // H2CORE_HAVE_JACK
815 // JACK is disabled
816 
817 namespace H2Core {
818 class JackAudioDriver : public NullDriver {
819 	H2_OBJECT
820 public:
821 	/**
822 	 * Fallback version of the JackAudioDriver in case
823 	 * #H2CORE_HAVE_JACK was not defined during the configuration
824 	 * and the usage of the JACK audio server is not intended by
825 	 * the user.
826 	 */
JackAudioDriver(audioProcessCallback m_processCallback)827 	JackAudioDriver( audioProcessCallback m_processCallback ) : NullDriver( m_processCallback ) {}
828 
829 };
830 
831 }; // H2Core namespace
832 
833 
834 #endif // H2CORE_HAVE_JACK
835 
836 #endif
837 
838