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