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