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