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