use JACK thread creation functions to create process-graph threads; provide GUI contr...
[ardour.git] / libs / ardour / audioengine.cc
1 /*
2     Copyright (C) 2002 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <unistd.h>
21 #include <cerrno>
22 #include <vector>
23 #include <exception>
24 #include <stdexcept>
25 #include <sstream>
26
27 #include <glibmm/timer.h>
28 #include <jack/jack.h>
29 #include <jack/thread.h>
30
31 #include "pbd/pthread_utils.h"
32 #include "pbd/stacktrace.h"
33 #include "pbd/unknown_type.h"
34
35 #include "midi++/jack.h"
36
37 #include "ardour/amp.h"
38 #include "ardour/audio_port.h"
39 #include "ardour/audioengine.h"
40 #include "ardour/buffer.h"
41 #include "ardour/buffer_set.h"
42 #include "ardour/cycle_timer.h"
43 #include "ardour/delivery.h"
44 #include "ardour/event_type_map.h"
45 #include "ardour/internal_return.h"
46 #include "ardour/io.h"
47 #include "ardour/meter.h"
48 #include "ardour/midi_port.h"
49 #include "ardour/process_thread.h"
50 #include "ardour/port.h"
51 #include "ardour/port_set.h"
52 #include "ardour/session.h"
53 #include "ardour/timestamps.h"
54 #include "ardour/utils.h"
55
56 #include "i18n.h"
57
58 using namespace std;
59 using namespace ARDOUR;
60 using namespace PBD;
61
62 gint AudioEngine::m_meter_exit;
63 AudioEngine* AudioEngine::_instance = 0;
64
65 #define GET_PRIVATE_JACK_POINTER(j)  jack_client_t* _priv_jack = (jack_client_t*) (j); if (!_priv_jack) { return; }
66 #define GET_PRIVATE_JACK_POINTER_RET(j,r) jack_client_t* _priv_jack = (jack_client_t*) (j); if (!_priv_jack) { return r; }
67
68 AudioEngine::AudioEngine (string client_name, string session_uuid)
69         : ports (new Ports)
70 {
71         _instance = this; /* singleton */
72
73         session_remove_pending = false;
74         _running = false;
75         _has_run = false;
76         last_monitor_check = 0;
77         monitor_check_interval = max_frames;
78         _processed_frames = 0;
79         _usecs_per_cycle = 0;
80         _jack = 0;
81         _frame_rate = 0;
82         _buffer_size = 0;
83         _freewheeling = false;
84         _main_thread = 0;
85
86         m_meter_thread = 0;
87         g_atomic_int_set (&m_meter_exit, 0);
88
89         if (connect_to_jack (client_name, session_uuid)) {
90                 throw NoBackendAvailable ();
91         }
92
93         Port::set_engine (this);
94
95         // Initialize parameter metadata (e.g. ranges)
96         Evoral::Parameter p(NullAutomation);
97         p = EventTypeMap::instance().new_parameter(NullAutomation);
98         p = EventTypeMap::instance().new_parameter(GainAutomation);
99         p = EventTypeMap::instance().new_parameter(PanAutomation);
100         p = EventTypeMap::instance().new_parameter(PluginAutomation);
101         p = EventTypeMap::instance().new_parameter(SoloAutomation);
102         p = EventTypeMap::instance().new_parameter(MuteAutomation);
103         p = EventTypeMap::instance().new_parameter(MidiCCAutomation);
104         p = EventTypeMap::instance().new_parameter(MidiPgmChangeAutomation);
105         p = EventTypeMap::instance().new_parameter(MidiPitchBenderAutomation);
106         p = EventTypeMap::instance().new_parameter(MidiChannelPressureAutomation);
107         p = EventTypeMap::instance().new_parameter(FadeInAutomation);
108         p = EventTypeMap::instance().new_parameter(FadeOutAutomation);
109         p = EventTypeMap::instance().new_parameter(EnvelopeAutomation);
110         p = EventTypeMap::instance().new_parameter(MidiCCAutomation);
111 }
112
113 AudioEngine::~AudioEngine ()
114 {
115         {
116                 Glib::Mutex::Lock tm (_process_lock);
117                 session_removed.signal ();
118
119                 if (_running) {
120                         jack_client_close (_jack);
121                         _jack = 0;
122                 }
123
124                 stop_metering_thread ();
125         }
126 }
127
128 jack_client_t*
129 AudioEngine::jack() const
130 {
131         return _jack;
132 }
133
134 void
135 _thread_init_callback (void * /*arg*/)
136 {
137         /* make sure that anybody who needs to know about this thread
138            knows about it.
139         */
140
141         pthread_set_name (X_("audioengine"));
142
143         PBD::notify_gui_about_thread_creation ("gui", pthread_self(), X_("Audioengine"), 4096);
144         PBD::notify_gui_about_thread_creation ("midiui", pthread_self(), X_("Audioengine"), 128);
145
146         SessionEvent::create_per_thread_pool (X_("Audioengine"), 512);
147
148         MIDI::JACK_MidiPort::set_process_thread (pthread_self());
149 }
150
151 typedef void (*_JackInfoShutdownCallback)(jack_status_t code, const char* reason, void *arg);
152
153 static void (*on_info_shutdown)(jack_client_t*, _JackInfoShutdownCallback, void *);
154 extern void jack_on_info_shutdown (jack_client_t*, _JackInfoShutdownCallback, void *) __attribute__((weak));
155
156 static void check_jack_symbols () __attribute__((constructor));
157
158 void check_jack_symbols ()
159 {
160        /* use weak linking to see if we really have various late-model JACK function */
161        on_info_shutdown = jack_on_info_shutdown;
162 }
163
164 static void
165 ardour_jack_error (const char* msg)
166 {
167         error << "JACK: " << msg << endmsg;
168 }
169
170 int
171 AudioEngine::start ()
172 {
173         GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
174
175         if (!_running) {
176
177                 nframes_t blocksize = jack_get_buffer_size (_priv_jack);
178
179                 if (_session) {
180                         BootMessage (_("Connect session to engine"));
181
182                         _session->set_block_size (blocksize);
183                         _session->set_frame_rate (jack_get_sample_rate (_priv_jack));
184
185                         /* page in as much of the session process code as we
186                            can before we really start running.
187                         */
188
189                         _session->process (blocksize);
190                         _session->process (blocksize);
191                         _session->process (blocksize);
192                         _session->process (blocksize);
193                         _session->process (blocksize);
194                         _session->process (blocksize);
195                         _session->process (blocksize);
196                         _session->process (blocksize);
197                 }
198
199                 _processed_frames = 0;
200                 last_monitor_check = 0;
201
202                 if (on_info_shutdown) {
203                         jack_on_info_shutdown (_priv_jack, halted_info, this);
204                 } else {
205                         jack_on_shutdown (_priv_jack, halted, this);
206                 }
207                 jack_set_graph_order_callback (_priv_jack, _graph_order_callback, this);
208                 jack_set_thread_init_callback (_priv_jack, _thread_init_callback, this);
209                 // jack_set_process_callback (_priv_jack, _process_callback, this);
210                 jack_set_process_thread (_priv_jack, _process_thread, this);
211                 jack_set_sample_rate_callback (_priv_jack, _sample_rate_callback, this);
212                 jack_set_buffer_size_callback (_priv_jack, _bufsize_callback, this);
213                 jack_set_xrun_callback (_priv_jack, _xrun_callback, this);
214 #ifdef HAVE_JACK_SESSION 
215                 if( jack_set_session_callback )
216                     jack_set_session_callback (_priv_jack, _session_callback, this);
217 #endif
218                 jack_set_sync_callback (_priv_jack, _jack_sync_callback, this);
219                 jack_set_freewheel_callback (_priv_jack, _freewheel_callback, this);
220                 jack_set_port_registration_callback (_priv_jack, _registration_callback, this);
221                 jack_set_port_connect_callback (_priv_jack, _connect_callback, this);
222
223                 if (_session && _session->config.get_jack_time_master()) {
224                         jack_set_timebase_callback (_priv_jack, 0, _jack_timebase_callback, this);
225                 }
226
227                 jack_set_error_function (ardour_jack_error);
228
229                 if (jack_activate (_priv_jack) == 0) {
230                         _running = true;
231                         _has_run = true;
232                         Running(); /* EMIT SIGNAL */
233                 } else {
234                         // error << _("cannot activate JACK client") << endmsg;
235                 }
236
237                 _raw_buffer_sizes[DataType::AUDIO] = blocksize * sizeof(float);
238
239                 jack_port_t* midi_port = jack_port_register (_priv_jack, "m", JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0);
240                 if (!midi_port) {
241                         error << _("Cannot create temporary MIDI port to determine MIDI buffer size") << endmsg;
242                 } else {
243                         _raw_buffer_sizes[DataType::MIDI] = jack_midi_max_event_size (jack_port_get_buffer(midi_port, blocksize));
244                         cerr << "MIDI port buffers = " << _raw_buffer_sizes[DataType::MIDI] << endl;
245                         jack_port_unregister (_priv_jack, midi_port);
246                 }
247         }
248
249         return _running ? 0 : -1;
250 }
251
252 int
253 AudioEngine::stop (bool forever)
254 {
255         GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
256
257         if (_priv_jack) {
258                 if (forever) {
259                         disconnect_from_jack ();
260                 } else {
261                         jack_deactivate (_priv_jack);
262                         Stopped(); /* EMIT SIGNAL */
263                         MIDI::JACK_MidiPort::JackHalted (); /* EMIT SIGNAL */
264                 }
265         }
266
267         return _running ? -1 : 0;
268 }
269
270
271 bool
272 AudioEngine::get_sync_offset (nframes_t& offset) const
273 {
274
275 #ifdef HAVE_JACK_VIDEO_SUPPORT
276
277         GET_PRIVATE_JACK_POINTER_RET (_jack, false);
278
279         jack_position_t pos;
280
281         if (_priv_jack) {
282                 (void) jack_transport_query (_priv_jack, &pos);
283
284                 if (pos.valid & JackVideoFrameOffset) {
285                         offset = pos.video_offset;
286                         return true;
287                 }
288         }
289 #else
290         /* keep gcc happy */
291         offset = 0;
292 #endif
293
294         return false;
295 }
296
297 void
298 AudioEngine::_jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
299                                       jack_position_t* pos, int new_position, void *arg)
300 {
301         static_cast<AudioEngine*> (arg)->jack_timebase_callback (state, nframes, pos, new_position);
302 }
303
304 void
305 AudioEngine::jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
306                                      jack_position_t* pos, int new_position)
307 {
308         if (_jack && _session && _session->synced_to_jack()) {
309                 _session->jack_timebase_callback (state, nframes, pos, new_position);
310         }
311 }
312
313 int
314 AudioEngine::_jack_sync_callback (jack_transport_state_t state, jack_position_t* pos, void* arg)
315 {
316         return static_cast<AudioEngine*> (arg)->jack_sync_callback (state, pos);
317 }
318
319 int
320 AudioEngine::jack_sync_callback (jack_transport_state_t state, jack_position_t* pos)
321 {
322         if (_jack && _session) {
323                 return _session->jack_sync_callback (state, pos);
324         }
325
326         return true;
327 }
328
329 int
330 AudioEngine::_xrun_callback (void *arg)
331 {
332         AudioEngine* ae = static_cast<AudioEngine*> (arg);
333         if (ae->connected()) {
334                 ae->Xrun (); /* EMIT SIGNAL */
335         }
336         return 0;
337 }
338
339 #ifdef HAVE_JACK_SESSION
340 void
341 AudioEngine::_session_callback (jack_session_event_t *event, void *arg)
342 {
343         printf( "helo.... " );
344         AudioEngine* ae = static_cast<AudioEngine*> (arg);
345         if (ae->connected()) {
346                 ae->JackSessionEvent ( event ); /* EMIT SIGNAL */
347         }
348 }
349 #endif
350 int
351 AudioEngine::_graph_order_callback (void *arg)
352 {
353         AudioEngine* ae = static_cast<AudioEngine*> (arg);
354         if (ae->connected()) {
355                 ae->GraphReordered (); /* EMIT SIGNAL */
356         }
357         return 0;
358 }
359
360 /** Wrapped which is called by JACK as its process callback.  It is just
361  * here to get us back into C++ land by calling AudioEngine::process_callback()
362  * @param nframes Number of frames passed by JACK.
363  * @param arg User argument passed by JACK, which will be the AudioEngine*.
364  */
365 int
366 AudioEngine::_process_callback (nframes_t nframes, void *arg)
367 {
368         return static_cast<AudioEngine *> (arg)->process_callback (nframes);
369 }
370
371 void*
372 AudioEngine::_process_thread (void *arg)
373 {
374         return static_cast<AudioEngine *> (arg)->process_thread ();
375 }
376
377 void
378 AudioEngine::_freewheel_callback (int onoff, void *arg)
379 {
380         static_cast<AudioEngine*>(arg)->_freewheeling = onoff;
381 }
382
383 void
384 AudioEngine::_registration_callback (jack_port_id_t /*id*/, int /*reg*/, void* arg)
385 {
386         AudioEngine* ae = static_cast<AudioEngine*> (arg);
387         ae->PortRegisteredOrUnregistered (); /* EMIT SIGNAL */
388 }
389
390 void
391 AudioEngine::_connect_callback (jack_port_id_t /*id_a*/, jack_port_id_t /*id_b*/, int /*conn*/, void* arg)
392 {
393         AudioEngine* ae = static_cast<AudioEngine*> (arg);
394         ae->PortConnectedOrDisconnected (); /* EMIT SIGNAL */
395 }
396
397 void
398 AudioEngine::split_cycle (nframes_t offset)
399 {
400         /* caller must hold process lock */
401
402         Port::increment_port_offset (offset);
403
404         /* tell all Ports that we're going to start a new (split) cycle */
405
406         boost::shared_ptr<Ports> p = ports.reader();
407
408         for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
409                 (*i)->cycle_split ();
410         }
411 }
412
413 void
414 AudioEngine::finish_process_cycle (int status)
415 {
416         GET_PRIVATE_JACK_POINTER(_jack);
417         jack_cycle_signal (_jack, 0);
418 }
419
420 void*
421 AudioEngine::process_thread ()
422 {
423         /* JACK doesn't do this for us when we use the wait API 
424          */
425
426         _thread_init_callback (0);
427
428         _main_thread = new ProcessThread;
429
430         while (1) {
431                 GET_PRIVATE_JACK_POINTER_RET(_jack,0);
432                 jack_nframes_t nframes = jack_cycle_wait (_jack);
433
434                 if (process_callback (nframes)) {
435                         cerr << "--- process\n";
436                         return 0;
437                 }
438
439                 finish_process_cycle (0);
440         }
441
442         return 0;
443 }
444
445 /** Method called by JACK (via _process_callback) which says that there
446  * is work to be done.
447  * @param nframes Number of frames to process.
448  */
449 int
450 AudioEngine::process_callback (nframes_t nframes)
451 {
452         GET_PRIVATE_JACK_POINTER_RET(_jack,0);
453         // CycleTimer ct ("AudioEngine::process");
454         Glib::Mutex::Lock tm (_process_lock, Glib::TRY_LOCK);
455
456         /// The number of frames that will have been processed when we've finished
457         nframes_t next_processed_frames;
458
459         /* handle wrap around of total frames counter */
460
461         if (max_frames - _processed_frames < nframes) {
462                 next_processed_frames = nframes - (max_frames - _processed_frames);
463         } else {
464                 next_processed_frames = _processed_frames + nframes;
465         }
466
467         if (!tm.locked() || _session == 0) {
468                 /* return having done nothing */
469                 _processed_frames = next_processed_frames;
470                 return 0;
471         }
472
473         if (session_remove_pending) {
474                 /* perform the actual session removal */
475                 _session = 0;
476                 session_remove_pending = false;
477                 session_removed.signal();
478                 _processed_frames = next_processed_frames;
479                 return 0;
480         }
481
482         /* tell all relevant objects that we're starting a new cycle */
483
484         Delivery::CycleStart (nframes);
485         Port::set_port_offset (0);
486         InternalReturn::CycleStart (nframes);
487
488         /* tell all Ports that we're starting a new cycle */
489
490         boost::shared_ptr<Ports> p = ports.reader();
491
492         for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
493                 (*i)->cycle_start (nframes);
494         }
495
496         if (_freewheeling) {
497                 /* emit the Freewheel signal and stop freewheeling in the event of trouble 
498                  */
499                 boost::optional<int> r = Freewheel (nframes);
500                 if (r.get_value_or (0)) {
501                         jack_set_freewheel (_priv_jack, false);
502                 }
503
504         } else {
505                 if (_session) {
506                         _session->process (nframes);
507
508                 }
509         }
510
511         if (_freewheeling) {
512                 return 0;
513         }
514
515         if (!_running) {
516                 _processed_frames = next_processed_frames;
517                 return 0;
518         }
519
520         if (last_monitor_check + monitor_check_interval < next_processed_frames) {
521
522                 boost::shared_ptr<Ports> p = ports.reader();
523
524                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
525
526                         Port *port = (*i);
527                         bool x;
528
529                         if (port->_last_monitor != (x = port->monitoring_input ())) {
530                                 port->_last_monitor = x;
531                                 /* XXX I think this is dangerous, due to
532                                    a likely mutex in the signal handlers ...
533                                 */
534                                  port->MonitorInputChanged (x); /* EMIT SIGNAL */
535                         }
536                 }
537                 last_monitor_check = next_processed_frames;
538         }
539
540         if (_session->silent()) {
541
542                 boost::shared_ptr<Ports> p = ports.reader();
543
544                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
545
546                         Port *port = (*i);
547
548                         if (port->sends_output()) {
549                                 port->get_buffer(nframes).silence(nframes);
550                         }
551                 }
552         }
553
554         // Finalize ports
555
556         for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
557                 (*i)->cycle_end (nframes);
558         }
559
560         _processed_frames = next_processed_frames;
561         return 0;
562 }
563
564 int
565 AudioEngine::_sample_rate_callback (nframes_t nframes, void *arg)
566 {
567         return static_cast<AudioEngine *> (arg)->jack_sample_rate_callback (nframes);
568 }
569
570 int
571 AudioEngine::jack_sample_rate_callback (nframes_t nframes)
572 {
573         _frame_rate = nframes;
574         _usecs_per_cycle = (int) floor ((((double) frames_per_cycle() / nframes)) * 1000000.0);
575
576         /* check for monitor input change every 1/10th of second */
577
578         monitor_check_interval = nframes / 10;
579         last_monitor_check = 0;
580
581         if (_session) {
582                 _session->set_frame_rate (nframes);
583         }
584
585         SampleRateChanged (nframes); /* EMIT SIGNAL */
586
587         return 0;
588 }
589
590 int
591 AudioEngine::_bufsize_callback (nframes_t nframes, void *arg)
592 {
593         return static_cast<AudioEngine *> (arg)->jack_bufsize_callback (nframes);
594 }
595
596 int
597 AudioEngine::jack_bufsize_callback (nframes_t nframes)
598 {
599         bool need_midi_size = true;
600         bool need_audio_size = true;
601
602         _buffer_size = nframes;
603         _usecs_per_cycle = (int) floor ((((double) nframes / frame_rate())) * 1000000.0);
604         last_monitor_check = 0;
605
606         boost::shared_ptr<Ports> p = ports.reader();
607
608         /* crude guesses, see below where we try to get the right answers.
609
610            Note that our guess for MIDI deliberatey tries to overestimate
611            by a little. It would be nicer if we could get the actual
612            size from a port, but we have to use this estimate in the 
613            event that there are no MIDI ports currently. If there are
614            the value will be adjusted below.
615          */
616
617         _raw_buffer_sizes[DataType::AUDIO] = nframes * sizeof (Sample);
618         _raw_buffer_sizes[DataType::MIDI] = nframes * 4 - (nframes/2);
619
620         for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
621
622                 if (need_audio_size && (*i)->type() == DataType::AUDIO) {
623                         _raw_buffer_sizes[DataType::AUDIO] = (*i)->raw_buffer_size (nframes);
624                         need_audio_size = false;
625                 }
626                 
627                         
628                 if (need_midi_size && (*i)->type() == DataType::MIDI) {
629                         _raw_buffer_sizes[DataType::MIDI] = (*i)->raw_buffer_size (nframes);
630                         need_midi_size = false;
631                 }
632                 
633                 (*i)->reset();
634         }
635
636         if (_session) {
637                 _session->set_block_size (_buffer_size);
638         }
639
640         return 0;
641 }
642
643 void
644 AudioEngine::stop_metering_thread ()
645 {
646         if (m_meter_thread) {
647                 g_atomic_int_set (&m_meter_exit, 1);
648                 m_meter_thread->join ();
649                 m_meter_thread = 0;
650         }
651 }
652
653 void
654 AudioEngine::start_metering_thread ()
655 {
656         if (m_meter_thread == 0) {
657                 g_atomic_int_set (&m_meter_exit, 0);
658                 m_meter_thread = Glib::Thread::create (boost::bind (&AudioEngine::meter_thread, this),
659                                                        500000, true, true, Glib::THREAD_PRIORITY_NORMAL);
660         }
661 }
662
663 void
664 AudioEngine::meter_thread ()
665 {
666         pthread_set_name (X_("meter"));
667
668         while (true) {
669                 Glib::usleep (10000); /* 1/100th sec interval */
670                 if (g_atomic_int_get(&m_meter_exit)) {
671                         break;
672                 }
673                 Metering::Meter ();
674         }
675 }
676
677 void
678 AudioEngine::set_session (Session *s)
679 {
680         Glib::Mutex::Lock pl (_process_lock);
681
682         SessionHandlePtr::set_session (s);
683
684         if (_session) {
685
686                 start_metering_thread ();
687                 
688                 nframes_t blocksize = jack_get_buffer_size (_jack);
689                 
690                 /* page in as much of the session process code as we
691                    can before we really start running.
692                 */
693                 
694                 boost::shared_ptr<Ports> p = ports.reader();
695                 
696                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
697                         (*i)->cycle_start (blocksize);
698                 }
699                 
700                 _session->process (blocksize);
701                 _session->process (blocksize);
702                 _session->process (blocksize);
703                 _session->process (blocksize);
704                 _session->process (blocksize);
705                 _session->process (blocksize);
706                 _session->process (blocksize);
707                 _session->process (blocksize);
708                 
709                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
710                         (*i)->cycle_end (blocksize);
711                 }
712         }
713 }
714
715 void
716 AudioEngine::remove_session ()
717 {
718         Glib::Mutex::Lock lm (_process_lock);
719
720         if (_running) {
721
722                 stop_metering_thread ();
723
724                 if (_session) {
725                         session_remove_pending = true;
726                         session_removed.wait(_process_lock);
727                 }
728
729         } else {
730                 SessionHandlePtr::set_session (0);
731         }
732
733         remove_all_ports ();
734 }
735
736 void
737 AudioEngine::port_registration_failure (const std::string& portname)
738 {
739         GET_PRIVATE_JACK_POINTER (_jack);
740         string full_portname = jack_client_name;
741         full_portname += ':';
742         full_portname += portname;
743
744
745         jack_port_t* p = jack_port_by_name (_priv_jack, full_portname.c_str());
746         string reason;
747
748         if (p) {
749                 reason = string_compose (_("a port with the name \"%1\" already exists: check for duplicated track/bus names"), portname);
750         } else {
751                 reason = string_compose (_("No more JACK ports are available. You will need to stop %1 and restart JACK with ports if you need this many tracks."), PROGRAM_NAME);
752         }
753
754         throw PortRegistrationFailure (string_compose (_("AudioEngine: cannot register port \"%1\": %2"), portname, reason).c_str());
755 }
756
757 Port *
758 AudioEngine::register_port (DataType dtype, const string& portname, bool input)
759 {
760         Port* newport = 0;
761
762         try {
763                 if (dtype == DataType::AUDIO) {
764                         newport = new AudioPort (portname, (input ? Port::IsInput : Port::IsOutput));
765                 } else if (dtype == DataType::MIDI) {
766                         newport = new MidiPort (portname, (input ? Port::IsInput : Port::IsOutput));
767                 } else {
768                         throw PortRegistrationFailure("unable to create port (unknown type)");
769                 }
770
771                 size_t& old_buffer_size  = _raw_buffer_sizes[newport->type()];
772                 size_t  port_buffer_size = newport->raw_buffer_size(0);
773                 if (port_buffer_size > old_buffer_size) {
774                         old_buffer_size = port_buffer_size;
775                 }
776
777                 RCUWriter<Ports> writer (ports);
778                 boost::shared_ptr<Ports> ps = writer.get_copy ();
779                 ps->insert (ps->begin(), newport);
780
781                 /* writer goes out of scope, forces update */
782
783                 return newport;
784         }
785
786         catch (PortRegistrationFailure& err) {
787                 throw err;
788         } catch (std::exception& e) {
789                 throw PortRegistrationFailure(string_compose(
790                                 _("unable to create port: %1"), e.what()).c_str());
791         } catch (...) {
792                 throw PortRegistrationFailure("unable to create port (unknown error)");
793         }
794 }
795
796 Port *
797 AudioEngine::register_input_port (DataType type, const string& portname)
798 {
799         return register_port (type, portname, true);
800 }
801
802 Port *
803 AudioEngine::register_output_port (DataType type, const string& portname)
804 {
805         return register_port (type, portname, false);
806 }
807
808 int
809 AudioEngine::unregister_port (Port& port)
810 {
811         /* caller must hold process lock */
812
813         if (!_running) {
814                 /* probably happening when the engine has been halted by JACK,
815                    in which case, there is nothing we can do here.
816                    */
817                 return 0;
818         }
819
820         {
821                 RCUWriter<Ports> writer (ports);
822                 boost::shared_ptr<Ports> ps = writer.get_copy ();
823
824                 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
825                         if ((*i) == &port) {
826                                 delete *i;
827                                 ps->erase (i);
828                                 break;
829                         }
830                 }
831
832                 /* writer goes out of scope, forces update */
833         }
834
835         return 0;
836 }
837
838 int
839 AudioEngine::connect (const string& source, const string& destination)
840 {
841         /* caller must hold process lock */
842
843         int ret;
844
845         if (!_running) {
846                 if (!_has_run) {
847                         fatal << _("connect called before engine was started") << endmsg;
848                         /*NOTREACHED*/
849                 } else {
850                         return -1;
851                 }
852         }
853
854         string s = make_port_name_non_relative (source);
855         string d = make_port_name_non_relative (destination);
856
857
858         Port* src = get_port_by_name_locked (s);
859         Port* dst = get_port_by_name_locked (d);
860
861         if (src) {
862                 ret = src->connect (d);
863         } else if (dst) {
864                 ret = dst->connect (s);
865         } else {
866                 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
867                 ret = -1;
868         }
869
870         if (ret > 0) {
871                 /* already exists - no error, no warning */
872         } else if (ret < 0) {
873                 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"),
874                                         source, s, destination, d)
875                       << endmsg;
876         }
877
878         return ret;
879 }
880
881 int
882 AudioEngine::disconnect (const string& source, const string& destination)
883 {
884         /* caller must hold process lock */
885
886         int ret;
887
888         if (!_running) {
889                 if (!_has_run) {
890                         fatal << _("disconnect called before engine was started") << endmsg;
891                         /*NOTREACHED*/
892                 } else {
893                         return -1;
894                 }
895         }
896
897         string s = make_port_name_non_relative (source);
898         string d = make_port_name_non_relative (destination);
899
900         Port* src = get_port_by_name_locked (s);
901         Port* dst = get_port_by_name_locked (d);
902
903         if (src) {
904                         ret = src->disconnect (d);
905         } else if (dst) {
906                         ret = dst->disconnect (s);
907         } else {
908                 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
909                 ret = -1;
910         }
911         return ret;
912 }
913
914 int
915 AudioEngine::disconnect (Port& port)
916 {
917         GET_PRIVATE_JACK_POINTER_RET (_jack,-1);
918
919         if (!_running) {
920                 if (!_has_run) {
921                         fatal << _("disconnect called before engine was started") << endmsg;
922                         /*NOTREACHED*/
923                 } else {
924                         return -1;
925                 }
926         }
927
928         return port.disconnect_all ();
929 }
930
931 ARDOUR::nframes_t
932 AudioEngine::frame_rate () const
933 {
934         GET_PRIVATE_JACK_POINTER_RET (_jack,0);
935         if (_frame_rate == 0) {
936           return (_frame_rate = jack_get_sample_rate (_priv_jack));
937         } else {
938           return _frame_rate;
939         }
940 }
941
942 size_t
943 AudioEngine::raw_buffer_size (DataType t)
944 {
945         std::map<DataType,size_t>::const_iterator s = _raw_buffer_sizes.find(t);
946         return (s != _raw_buffer_sizes.end()) ? s->second : 0;
947 }
948
949 ARDOUR::nframes_t
950 AudioEngine::frames_per_cycle () const
951 {
952         GET_PRIVATE_JACK_POINTER_RET (_jack,0);
953         if (_buffer_size == 0) {
954           return (_buffer_size = jack_get_buffer_size (_jack));
955         } else {
956           return _buffer_size;
957         }
958 }
959
960 /** @param name Full name of port (including prefix:)
961  *  @return Corresponding Port*, or 0.  This object remains the property of the AudioEngine
962  *  so must not be deleted.
963  */
964 Port *
965 AudioEngine::get_port_by_name (const string& portname)
966 {
967         string s;
968         if (portname.find_first_of (':') == string::npos) {
969                 s = make_port_name_non_relative (portname);
970         } else {
971                 s = portname;
972         }
973
974         Glib::Mutex::Lock lm (_process_lock);
975         return get_port_by_name_locked (s);
976 }
977
978 Port *
979 AudioEngine::get_port_by_name_locked (const string& portname)
980 {
981         /* caller must hold process lock */
982
983         if (!_running) {
984                 if (!_has_run) {
985                         fatal << _("get_port_by_name_locked() called before engine was started") << endmsg;
986                         /*NOTREACHED*/
987                 } else {
988                         return 0;
989                 }
990         }
991
992         if (portname.substr (0, jack_client_name.length ()) != jack_client_name) {
993                 /* not an ardour: port */
994                 return 0;
995         }
996
997         std::string const rel = make_port_name_relative (portname);
998
999         boost::shared_ptr<Ports> pr = ports.reader();
1000
1001         for (Ports::iterator i = pr->begin(); i != pr->end(); ++i) {
1002                 if (rel == (*i)->name()) {
1003                         return *i;
1004                 }
1005         }
1006
1007         return 0;
1008 }
1009
1010 const char **
1011 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
1012 {
1013         GET_PRIVATE_JACK_POINTER_RET (_jack,0);
1014         if (!_running) {
1015                 if (!_has_run) {
1016                         fatal << _("get_ports called before engine was started") << endmsg;
1017                         /*NOTREACHED*/
1018                 } else {
1019                         return 0;
1020                 }
1021         }
1022         return jack_get_ports (_priv_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
1023 }
1024
1025 void
1026 AudioEngine::halted_info (jack_status_t code, const char* reason, void *arg)
1027 {
1028         /* called from jack shutdown handler  */
1029         
1030         AudioEngine* ae = static_cast<AudioEngine *> (arg);
1031         bool was_running = ae->_running;
1032         
1033         ae->stop_metering_thread ();
1034         
1035         ae->_running = false;
1036         ae->_buffer_size = 0;
1037         ae->_frame_rate = 0;
1038         ae->_jack = 0;
1039         
1040         if (was_running) {
1041 #ifdef HAVE_JACK_ON_INFO_SHUTDOWN
1042                 switch (code) {
1043                 case JackBackendError:
1044                         ae->Halted(reason); /* EMIT SIGNAL */
1045                         break;
1046                 default:
1047                         ae->Halted(""); /* EMIT SIGNAL */
1048                 }
1049 #else
1050                 ae->Halted(""); /* EMIT SIGNAL */
1051 #endif
1052         }
1053 }
1054
1055 void
1056 AudioEngine::halted (void *arg)
1057 {
1058         cerr << "HALTED by JACK\n";
1059
1060         /* called from jack shutdown handler  */
1061
1062         AudioEngine* ae = static_cast<AudioEngine *> (arg);
1063         bool was_running = ae->_running;
1064
1065         ae->stop_metering_thread ();
1066
1067         ae->_running = false;
1068         ae->_buffer_size = 0;
1069         ae->_frame_rate = 0;
1070         ae->_jack = 0;
1071
1072         if (was_running) {
1073                 ae->Halted(""); /* EMIT SIGNAL */
1074                 MIDI::JACK_MidiPort::JackHalted (); /* EMIT SIGNAL */
1075         }
1076 }
1077
1078 void
1079 AudioEngine::died ()
1080 {
1081         /* called from a signal handler for SIGPIPE */
1082
1083         stop_metering_thread ();
1084
1085         _running = false;
1086         _buffer_size = 0;
1087         _frame_rate = 0;
1088         _jack = 0;
1089 }
1090
1091 bool
1092 AudioEngine::can_request_hardware_monitoring ()
1093 {
1094         GET_PRIVATE_JACK_POINTER_RET (_jack,false);
1095         const char ** ports;
1096
1097         if ((ports = jack_get_ports (_priv_jack, NULL, JACK_DEFAULT_AUDIO_TYPE, JackPortCanMonitor)) == 0) {
1098                 return false;
1099         }
1100
1101         free (ports);
1102
1103         return true;
1104 }
1105
1106
1107 uint32_t
1108 AudioEngine::n_physical_outputs (DataType type) const
1109 {
1110         GET_PRIVATE_JACK_POINTER_RET (_jack,0);
1111         const char ** ports;
1112         uint32_t i = 0;
1113
1114         if ((ports = jack_get_ports (_priv_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsInput)) == 0) {
1115                 return 0;
1116         }
1117
1118         for (i = 0; ports[i]; ++i) {}
1119         free (ports);
1120
1121         return i;
1122 }
1123
1124 uint32_t
1125 AudioEngine::n_physical_inputs (DataType type) const
1126 {
1127         GET_PRIVATE_JACK_POINTER_RET (_jack,0);
1128         const char ** ports;
1129         uint32_t i = 0;
1130
1131         if ((ports = jack_get_ports (_priv_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsOutput)) == 0) {
1132                 return 0;
1133         }
1134
1135         for (i = 0; ports[i]; ++i) {}
1136         free (ports);
1137
1138         return i;
1139 }
1140
1141 void
1142 AudioEngine::get_physical_inputs (DataType type, vector<string>& ins)
1143 {
1144         GET_PRIVATE_JACK_POINTER (_jack);
1145         const char ** ports;
1146
1147         if ((ports = jack_get_ports (_priv_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsOutput)) == 0) {
1148                 return;
1149         }
1150
1151         if (ports) {
1152                 for (uint32_t i = 0; ports[i]; ++i) {
1153                         ins.push_back (ports[i]);
1154                 }
1155                 free (ports);
1156         }
1157 }
1158
1159 void
1160 AudioEngine::get_physical_outputs (DataType type, vector<string>& outs)
1161 {
1162         GET_PRIVATE_JACK_POINTER (_jack);
1163         const char ** ports;
1164         uint32_t i = 0;
1165
1166         if ((ports = jack_get_ports (_priv_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsInput)) == 0) {
1167                 return;
1168         }
1169
1170         for (i = 0; ports[i]; ++i) {
1171                 outs.push_back (ports[i]);
1172         }
1173         free (ports);
1174 }
1175
1176 string
1177 AudioEngine::get_nth_physical (DataType type, uint32_t n, int flag)
1178 {
1179         GET_PRIVATE_JACK_POINTER_RET (_jack,"");
1180         const char ** ports;
1181         uint32_t i;
1182         string ret;
1183
1184         assert(type != DataType::NIL);
1185
1186         if ((ports = jack_get_ports (_priv_jack, NULL, type.to_jack_type(), JackPortIsPhysical|flag)) == 0) {
1187                 return ret;
1188         }
1189
1190         for (i = 0; i < n && ports[i]; ++i) {}
1191
1192         if (ports[i]) {
1193                 ret = ports[i];
1194         }
1195
1196         free ((const char **) ports);
1197
1198         return ret;
1199 }
1200
1201 void
1202 AudioEngine::update_total_latency (const Port& port)
1203 {
1204         port.recompute_total_latency ();
1205 }
1206
1207 void
1208 AudioEngine::transport_stop ()
1209 {
1210         GET_PRIVATE_JACK_POINTER (_jack);
1211         jack_transport_stop (_priv_jack);
1212 }
1213
1214 void
1215 AudioEngine::transport_start ()
1216 {
1217         GET_PRIVATE_JACK_POINTER (_jack);
1218         jack_transport_start (_priv_jack);
1219 }
1220
1221 void
1222 AudioEngine::transport_locate (nframes_t where)
1223 {
1224         GET_PRIVATE_JACK_POINTER (_jack);
1225         // cerr << "tell JACK to locate to " << where << endl;
1226         jack_transport_locate (_priv_jack, where);
1227 }
1228
1229 AudioEngine::TransportState
1230 AudioEngine::transport_state ()
1231 {
1232         GET_PRIVATE_JACK_POINTER_RET (_jack, ((TransportState) JackTransportStopped));
1233         jack_position_t pos;
1234         return (TransportState) jack_transport_query (_priv_jack, &pos);
1235 }
1236
1237 int
1238 AudioEngine::reset_timebase ()
1239 {
1240         GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
1241         if (_session) {
1242                 if (_session->config.get_jack_time_master()) {
1243                         return jack_set_timebase_callback (_priv_jack, 0, _jack_timebase_callback, this);
1244                 } else {
1245                         return jack_release_timebase (_jack);
1246                 }
1247         }
1248         return 0;
1249 }
1250
1251 int
1252 AudioEngine::freewheel (bool onoff)
1253 {
1254         GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
1255
1256         if (onoff != _freewheeling) {
1257                 return jack_set_freewheel (_priv_jack, onoff);
1258                 
1259         } else {
1260                 /* already doing what has been asked for */
1261                 return 0;
1262         }
1263 }
1264
1265 void
1266 AudioEngine::remove_all_ports ()
1267 {
1268         /* process lock MUST be held */
1269
1270         {
1271                 RCUWriter<Ports> writer (ports);
1272                 boost::shared_ptr<Ports> ps = writer.get_copy ();
1273
1274                 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
1275                         delete *i;
1276                 }
1277
1278                 ps->clear ();
1279         }
1280
1281         /* clear dead wood list too */
1282
1283         ports.flush ();
1284 }
1285
1286 int
1287 AudioEngine::connect_to_jack (string client_name, string session_uuid)
1288 {
1289         jack_options_t options = JackNullOption;
1290         jack_status_t status;
1291         const char *server_name = NULL;
1292
1293         jack_client_name = client_name; /* might be reset below */
1294 #ifdef HAVE_JACK_SESSION
1295         if (! session_uuid.empty())
1296             _jack = jack_client_open (jack_client_name.c_str(), JackSessionID, &status, session_uuid.c_str());
1297         else
1298 #endif
1299             _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
1300
1301         if (_jack == NULL) {
1302                 // error message is not useful here
1303                 return -1;
1304         }
1305
1306         GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
1307
1308         if (status & JackNameNotUnique) {
1309                 jack_client_name = jack_get_client_name (_priv_jack);
1310         }
1311
1312         return 0;
1313 }
1314
1315 int
1316 AudioEngine::disconnect_from_jack ()
1317 {
1318         GET_PRIVATE_JACK_POINTER_RET (_jack, 0);
1319
1320         if (_running) {
1321                 stop_metering_thread ();
1322         }
1323
1324         {
1325                 Glib::Mutex::Lock lm (_process_lock);
1326                 jack_client_close (_priv_jack);
1327                 _jack = 0;
1328         }
1329
1330         _buffer_size = 0;
1331         _frame_rate = 0;
1332         _raw_buffer_sizes.clear();
1333
1334         if (_running) {
1335                 _running = false;
1336                 Stopped(); /* EMIT SIGNAL */
1337                 MIDI::JACK_MidiPort::JackHalted (); /* EMIT SIGNAL */
1338         }
1339
1340         return 0;
1341 }
1342
1343 int
1344 AudioEngine::reconnect_to_jack ()
1345 {
1346         if (_running) {
1347                 disconnect_from_jack ();
1348                 /* XXX give jackd a chance */
1349                 Glib::usleep (250000);
1350         }
1351
1352         if (connect_to_jack (jack_client_name, "")) {
1353                 error << _("failed to connect to JACK") << endmsg;
1354                 return -1;
1355         }
1356
1357         Ports::iterator i;
1358
1359         boost::shared_ptr<Ports> p = ports.reader ();
1360
1361         for (i = p->begin(); i != p->end(); ++i) {
1362                 if ((*i)->reestablish ()) {
1363                         break;
1364                 }
1365         }
1366
1367         if (i != p->end()) {
1368                 /* failed */
1369                 remove_all_ports ();
1370                 return -1;
1371         }
1372
1373         GET_PRIVATE_JACK_POINTER_RET (_jack,-1);
1374
1375         if (_session) {
1376                 _session->reset_jack_connection (_priv_jack);
1377                 jack_bufsize_callback (jack_get_buffer_size (_priv_jack));
1378                 _session->set_frame_rate (jack_get_sample_rate (_priv_jack));
1379         }
1380
1381         last_monitor_check = 0;
1382
1383         jack_on_shutdown (_priv_jack, halted, this);
1384         jack_set_graph_order_callback (_priv_jack, _graph_order_callback, this);
1385         jack_set_thread_init_callback (_priv_jack, _thread_init_callback, this);
1386         // jack_set_process_callback (_priv_jack, _process_callback, this);
1387         jack_set_process_thread (_priv_jack, _process_thread, this);
1388         jack_set_sample_rate_callback (_priv_jack, _sample_rate_callback, this);
1389         jack_set_buffer_size_callback (_priv_jack, _bufsize_callback, this);
1390         jack_set_xrun_callback (_priv_jack, _xrun_callback, this);
1391 #ifdef HAVE_JACK_SESSION
1392         if( jack_set_session_callback )
1393             jack_set_session_callback (_priv_jack, _session_callback, this);
1394 #endif
1395         jack_set_sync_callback (_priv_jack, _jack_sync_callback, this);
1396         jack_set_freewheel_callback (_priv_jack, _freewheel_callback, this);
1397
1398         if (_session && _session->config.get_jack_time_master()) {
1399                 jack_set_timebase_callback (_priv_jack, 0, _jack_timebase_callback, this);
1400         }
1401
1402         if (jack_activate (_priv_jack) == 0) {
1403                 _running = true;
1404                 _has_run = true;
1405         } else {
1406                 return -1;
1407         }
1408
1409         /* re-establish connections */
1410
1411         for (i = p->begin(); i != p->end(); ++i) {
1412                 (*i)->reconnect ();
1413         }
1414
1415         Running (); /* EMIT SIGNAL*/
1416
1417         start_metering_thread ();
1418
1419         return 0;
1420 }
1421
1422 int
1423 AudioEngine::request_buffer_size (nframes_t nframes)
1424 {
1425         GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
1426
1427         if (nframes == jack_get_buffer_size (_priv_jack)) {
1428           return 0;
1429         }
1430         
1431         return jack_set_buffer_size (_priv_jack, nframes);
1432 }
1433
1434 void
1435 AudioEngine::update_total_latencies ()
1436 {
1437 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1438         GET_PRIVATE_JACK_POINTER (_jack);
1439         jack_recompute_total_latencies (_priv_jack);
1440 #endif
1441 }
1442
1443 string
1444 AudioEngine::make_port_name_relative (string portname)
1445 {
1446         string::size_type len;
1447         string::size_type n;
1448
1449         len = portname.length();
1450
1451         for (n = 0; n < len; ++n) {
1452                 if (portname[n] == ':') {
1453                         break;
1454                 }
1455         }
1456
1457         if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1458                 return portname.substr (n+1);
1459         }
1460
1461         return portname;
1462 }
1463
1464 string
1465 AudioEngine::make_port_name_non_relative (string portname)
1466 {
1467         string str;
1468
1469         if (portname.find_first_of (':') != string::npos) {
1470                 return portname;
1471         }
1472
1473         str  = jack_client_name;
1474         str += ':';
1475         str += portname;
1476
1477         return str;
1478 }
1479
1480 bool
1481 AudioEngine::is_realtime () const
1482 {
1483         GET_PRIVATE_JACK_POINTER_RET (_jack,false);
1484         return jack_is_realtime (_priv_jack);
1485 }
1486
1487 pthread_t
1488 AudioEngine::create_process_thread (boost::function<void()> f, size_t stacksize)
1489 {
1490         GET_PRIVATE_JACK_POINTER_RET (_jack, 0);
1491         pthread_t thread;
1492         ThreadData* td = new ThreadData (this, f, stacksize);
1493
1494         if (jack_client_create_thread (_priv_jack, &thread, jack_client_real_time_priority (_priv_jack), 
1495                                        jack_is_realtime (_priv_jack), _start_process_thread, td)) {
1496                 return -1;
1497         } 
1498
1499         return thread;
1500 }
1501
1502 void*
1503 AudioEngine::_start_process_thread (void* arg)
1504 {
1505         ThreadData* td = reinterpret_cast<ThreadData*> (arg);
1506         boost::function<void()> f = td->f;
1507         delete td;
1508
1509         f ();
1510
1511         return 0;
1512 }