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