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