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