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