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