switch to using boost::signals2 instead of sigc++, at least for libardour. not finish...
[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         PBD::notify_gui_about_thread_creation ("gui", pthread_self(), X_("Audioengine"), 4096);
138         PBD::notify_gui_about_thread_creation ("midiui", pthread_self(), X_("Audioengine"), 128);
139
140         SessionEvent::create_per_thread_pool (X_("Audioengine"), 512);
141
142         MIDI::JACK_MidiPort::set_process_thread (pthread_self());
143 }
144
145 static void
146 ardour_jack_error (const char* msg)
147 {
148         error << "JACK: " << msg << endmsg;
149 }
150
151 int
152 AudioEngine::start ()
153 {
154         GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
155
156         if (!_running) {
157
158                 nframes_t blocksize = jack_get_buffer_size (_priv_jack);
159
160                 if (_session) {
161                         BootMessage (_("Connect session to engine"));
162
163                         _session->set_block_size (blocksize);
164                         _session->set_frame_rate (jack_get_sample_rate (_priv_jack));
165
166                         /* page in as much of the session process code as we
167                            can before we really start running.
168                         */
169
170                         _session->process (blocksize);
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                 }
179
180                 _processed_frames = 0;
181                 last_monitor_check = 0;
182
183                 jack_on_shutdown (_priv_jack, halted, this);
184                 jack_set_graph_order_callback (_priv_jack, _graph_order_callback, this);
185                 jack_set_thread_init_callback (_priv_jack, _thread_init_callback, this);
186                 jack_set_process_callback (_priv_jack, _process_callback, this);
187                 jack_set_sample_rate_callback (_priv_jack, _sample_rate_callback, this);
188                 jack_set_buffer_size_callback (_priv_jack, _bufsize_callback, this);
189                 jack_set_xrun_callback (_priv_jack, _xrun_callback, this);
190                 jack_set_sync_callback (_priv_jack, _jack_sync_callback, this);
191                 jack_set_freewheel_callback (_priv_jack, _freewheel_callback, this);
192                 jack_set_port_registration_callback (_priv_jack, _registration_callback, this);
193
194                 if (_session && _session->config.get_jack_time_master()) {
195                         jack_set_timebase_callback (_priv_jack, 0, _jack_timebase_callback, this);
196                 }
197
198                 jack_set_error_function (ardour_jack_error);
199
200                 if (jack_activate (_priv_jack) == 0) {
201                         _running = true;
202                         _has_run = true;
203                         Running(); /* EMIT SIGNAL */
204                 } else {
205                         // error << _("cannot activate JACK client") << endmsg;
206                 }
207
208                 start_metering_thread();
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                 }
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         while (true) {
549                 Glib::usleep (10000); /* 1/100th sec interval */
550                 if (g_atomic_int_get(&m_meter_exit)) {
551                         break;
552                 }
553                 Metering::update_meters ();
554         }
555 }
556
557 void
558 AudioEngine::set_session (Session *s)
559 {
560         Glib::Mutex::Lock pl (_process_lock);
561
562         SessionHandlePtr::set_session (s);
563
564         if (_session) {
565                 
566                 nframes_t blocksize = jack_get_buffer_size (_jack);
567                 
568                 /* page in as much of the session process code as we
569                    can before we really start running.
570                 */
571                 
572                 boost::shared_ptr<Ports> p = ports.reader();
573                 
574                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
575                         (*i)->cycle_start (blocksize);
576                 }
577                 
578                 _session->process (blocksize);
579                 _session->process (blocksize);
580                 _session->process (blocksize);
581                 _session->process (blocksize);
582                 _session->process (blocksize);
583                 _session->process (blocksize);
584                 _session->process (blocksize);
585                 _session->process (blocksize);
586                 
587                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
588                         (*i)->cycle_end (blocksize);
589                 }
590         }
591 }
592
593 void
594 AudioEngine::remove_session ()
595 {
596         Glib::Mutex::Lock lm (_process_lock);
597
598         if (_running) {
599
600                 if (_session) {
601                         session_remove_pending = true;
602                         session_removed.wait(_process_lock);
603                 }
604
605         } else {
606                 SessionHandlePtr::set_session (0);
607         }
608
609         remove_all_ports ();
610 }
611
612 void
613 AudioEngine::port_registration_failure (const std::string& portname)
614 {
615         GET_PRIVATE_JACK_POINTER (_jack);
616         string full_portname = jack_client_name;
617         full_portname += ':';
618         full_portname += portname;
619
620
621         jack_port_t* p = jack_port_by_name (_priv_jack, full_portname.c_str());
622         string reason;
623
624         if (p) {
625                 reason = string_compose (_("a port with the name \"%1\" already exists: check for duplicated track/bus names"), portname);
626         } else {
627                 reason = _("No more JACK ports are available. You will need to stop Ardour and restart JACK with ports if you need this many tracks.");
628         }
629
630         throw PortRegistrationFailure (string_compose (_("AudioEngine: cannot register port \"%1\": %2"), portname, reason).c_str());
631 }
632
633 Port *
634 AudioEngine::register_port (DataType dtype, const string& portname, bool input)
635 {
636         Port* newport = 0;
637
638         try {
639                 if (dtype == DataType::AUDIO) {
640                         newport = new AudioPort (portname, (input ? Port::IsInput : Port::IsOutput));
641                 } else if (dtype == DataType::MIDI) {
642                         newport = new MidiPort (portname, (input ? Port::IsInput : Port::IsOutput));
643                 } else {
644                         throw PortRegistrationFailure("unable to create port (unknown type)");
645                 }
646
647                 size_t& old_buffer_size  = _raw_buffer_sizes[newport->type()];
648                 size_t  port_buffer_size = newport->raw_buffer_size(0);
649                 if (port_buffer_size > old_buffer_size) {
650                         old_buffer_size = port_buffer_size;
651                 }
652
653                 RCUWriter<Ports> writer (ports);
654                 boost::shared_ptr<Ports> ps = writer.get_copy ();
655                 ps->insert (ps->begin(), newport);
656
657                 /* writer goes out of scope, forces update */
658
659                 return newport;
660         }
661
662         catch (PortRegistrationFailure& err) {
663                 throw err;
664         } catch (std::exception& e) {
665                 throw PortRegistrationFailure(string_compose(
666                                 _("unable to create port: %1"), e.what()).c_str());
667         } catch (...) {
668                 throw PortRegistrationFailure("unable to create port (unknown error)");
669         }
670 }
671
672 Port *
673 AudioEngine::register_input_port (DataType type, const string& portname)
674 {
675         return register_port (type, portname, true);
676 }
677
678 Port *
679 AudioEngine::register_output_port (DataType type, const string& portname)
680 {
681         return register_port (type, portname, false);
682 }
683
684 int
685 AudioEngine::unregister_port (Port& port)
686 {
687         /* caller must hold process lock */
688
689         if (!_running) {
690                 /* probably happening when the engine has been halted by JACK,
691                    in which case, there is nothing we can do here.
692                    */
693                 return 0;
694         }
695
696         {
697                 RCUWriter<Ports> writer (ports);
698                 boost::shared_ptr<Ports> ps = writer.get_copy ();
699
700                 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
701                         if ((*i) == &port) {
702                                 delete *i;
703                                 ps->erase (i);
704                                 break;
705                         }
706                 }
707
708                 /* writer goes out of scope, forces update */
709         }
710
711         return 0;
712 }
713
714 int
715 AudioEngine::connect (const string& source, const string& destination)
716 {
717         /* caller must hold process lock */
718
719         int ret;
720
721         if (!_running) {
722                 if (!_has_run) {
723                         fatal << _("connect called before engine was started") << endmsg;
724                         /*NOTREACHED*/
725                 } else {
726                         return -1;
727                 }
728         }
729
730         string s = make_port_name_non_relative (source);
731         string d = make_port_name_non_relative (destination);
732
733
734         Port* src = get_port_by_name_locked (s);
735         Port* dst = get_port_by_name_locked (d);
736
737         if (src) {
738                         ret = src->connect (d);
739         } else if (dst) {
740                         ret = dst->connect (s);
741         } else {
742                 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
743                 ret = -1;
744         }
745
746         if (ret > 0) {
747                 /* already exists - no error, no warning */
748         } else if (ret < 0) {
749                 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"),
750                                         source, s, destination, d)
751                       << endmsg;
752         }
753
754         return ret;
755 }
756
757 int
758 AudioEngine::disconnect (const string& source, const string& destination)
759 {
760         /* caller must hold process lock */
761
762         int ret;
763
764         if (!_running) {
765                 if (!_has_run) {
766                         fatal << _("disconnect called before engine was started") << endmsg;
767                         /*NOTREACHED*/
768                 } else {
769                         return -1;
770                 }
771         }
772
773         string s = make_port_name_non_relative (source);
774         string d = make_port_name_non_relative (destination);
775
776         Port* src = get_port_by_name_locked (s);
777         Port* dst = get_port_by_name_locked (d);
778
779         if (src) {
780                         ret = src->disconnect (d);
781         } else if (dst) {
782                         ret = dst->disconnect (s);
783         } else {
784                 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
785                 ret = -1;
786         }
787         return ret;
788 }
789
790 int
791 AudioEngine::disconnect (Port& port)
792 {
793         GET_PRIVATE_JACK_POINTER_RET (_jack,-1);
794
795         if (!_running) {
796                 if (!_has_run) {
797                         fatal << _("disconnect called before engine was started") << endmsg;
798                         /*NOTREACHED*/
799                 } else {
800                         return -1;
801                 }
802         }
803
804         return port.disconnect_all ();
805 }
806
807 ARDOUR::nframes_t
808 AudioEngine::frame_rate ()
809 {
810         GET_PRIVATE_JACK_POINTER_RET (_jack,0);
811         if (_frame_rate == 0) {
812           return (_frame_rate = jack_get_sample_rate (_priv_jack));
813         } else {
814           return _frame_rate;
815         }
816 }
817
818 size_t
819 AudioEngine::raw_buffer_size (DataType t)
820 {
821         std::map<DataType,size_t>::const_iterator s = _raw_buffer_sizes.find(t);
822         return (s != _raw_buffer_sizes.end()) ? s->second : 0;
823 }
824
825 ARDOUR::nframes_t
826 AudioEngine::frames_per_cycle ()
827 {
828         GET_PRIVATE_JACK_POINTER_RET (_jack,0);
829         if (_buffer_size == 0) {
830           return (_buffer_size = jack_get_buffer_size (_jack));
831         } else {
832           return _buffer_size;
833         }
834 }
835
836 /** @param name Full name of port (including prefix:)
837  *  @return Corresponding Port*, or 0.  This object remains the property of the AudioEngine
838  *  so must not be deleted.
839  */
840 Port *
841 AudioEngine::get_port_by_name (const string& portname)
842 {
843         string s;
844         if (portname.find_first_of (':') == string::npos) {
845                 s = make_port_name_non_relative (portname);
846         } else {
847                 s = portname;
848         }
849
850         Glib::Mutex::Lock lm (_process_lock);
851         return get_port_by_name_locked (s);
852 }
853
854 Port *
855 AudioEngine::get_port_by_name_locked (const string& portname)
856 {
857         /* caller must hold process lock */
858
859         if (!_running) {
860                 if (!_has_run) {
861                         fatal << _("get_port_by_name_locked() called before engine was started") << endmsg;
862                         /*NOTREACHED*/
863                 } else {
864                         return 0;
865                 }
866         }
867
868         if (portname.substr (0, jack_client_name.length ()) != jack_client_name) {
869                 /* not an ardour: port */
870                 return 0;
871         }
872
873         std::string const rel = make_port_name_relative (portname);
874
875         boost::shared_ptr<Ports> pr = ports.reader();
876
877         for (Ports::iterator i = pr->begin(); i != pr->end(); ++i) {
878                 if (rel == (*i)->name()) {
879                         return *i;
880                 }
881         }
882
883         return 0;
884 }
885
886 const char **
887 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
888 {
889         GET_PRIVATE_JACK_POINTER_RET (_jack,0);
890         if (!_running) {
891                 if (!_has_run) {
892                         fatal << _("get_ports called before engine was started") << endmsg;
893                         /*NOTREACHED*/
894                 } else {
895                         return 0;
896                 }
897         }
898         return jack_get_ports (_priv_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
899 }
900
901 void
902 AudioEngine::halted (void *arg)
903 {
904         /* called from jack shutdown handler  */
905
906         AudioEngine* ae = static_cast<AudioEngine *> (arg);
907         bool was_running = ae->_running;
908
909         ae->stop_metering_thread ();
910
911         ae->_running = false;
912         ae->_buffer_size = 0;
913         ae->_frame_rate = 0;
914
915         if (was_running) {
916                 ae->Halted(); /* EMIT SIGNAL */
917         }
918 }
919
920 void
921 AudioEngine::died ()
922 {
923         /* called from a signal handler for SIGPIPE */
924
925         stop_metering_thread ();
926
927         _running = false;
928         _buffer_size = 0;
929         _frame_rate = 0;
930         _jack = 0;
931 }
932
933 bool
934 AudioEngine::can_request_hardware_monitoring ()
935 {
936         GET_PRIVATE_JACK_POINTER_RET (_jack,false);
937         const char ** ports;
938
939         if ((ports = jack_get_ports (_priv_jack, NULL, JACK_DEFAULT_AUDIO_TYPE, JackPortCanMonitor)) == 0) {
940                 return false;
941         }
942
943         free (ports);
944
945         return true;
946 }
947
948
949 uint32_t
950 AudioEngine::n_physical_outputs (DataType type) const
951 {
952         GET_PRIVATE_JACK_POINTER_RET (_jack,0);
953         const char ** ports;
954         uint32_t i = 0;
955
956         if ((ports = jack_get_ports (_priv_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsInput)) == 0) {
957                 return 0;
958         }
959
960         for (i = 0; ports[i]; ++i) {}
961         free (ports);
962
963         return i;
964 }
965
966 uint32_t
967 AudioEngine::n_physical_inputs (DataType type) const
968 {
969         GET_PRIVATE_JACK_POINTER_RET (_jack,0);
970         const char ** ports;
971         uint32_t i = 0;
972
973         if ((ports = jack_get_ports (_priv_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsOutput)) == 0) {
974                 return 0;
975         }
976
977         for (i = 0; ports[i]; ++i) {}
978         free (ports);
979
980         return i;
981 }
982
983 void
984 AudioEngine::get_physical_inputs (DataType type, vector<string>& ins)
985 {
986         GET_PRIVATE_JACK_POINTER (_jack);
987         const char ** ports;
988         uint32_t i = 0;
989
990
991         if ((ports = jack_get_ports (_priv_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsOutput)) == 0) {
992                 return;
993         }
994
995         if (ports) {
996                 for (i = 0; ports[i]; ++i) {
997                         ins.push_back (ports[i]);
998                 }
999                 free (ports);
1000         }
1001 }
1002
1003 void
1004 AudioEngine::get_physical_outputs (DataType type, vector<string>& outs)
1005 {
1006         GET_PRIVATE_JACK_POINTER (_jack);
1007         const char ** ports;
1008         uint32_t i = 0;
1009
1010         if ((ports = jack_get_ports (_priv_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsInput)) == 0) {
1011                 return;
1012         }
1013
1014         for (i = 0; ports[i]; ++i) {
1015                 outs.push_back (ports[i]);
1016         }
1017         free (ports);
1018 }
1019
1020 string
1021 AudioEngine::get_nth_physical (DataType type, uint32_t n, int flag)
1022 {
1023         GET_PRIVATE_JACK_POINTER_RET (_jack,"");
1024         const char ** ports;
1025         uint32_t i;
1026         string ret;
1027
1028         assert(type != DataType::NIL);
1029
1030         if ((ports = jack_get_ports (_priv_jack, NULL, type.to_jack_type(), JackPortIsPhysical|flag)) == 0) {
1031                 return ret;
1032         }
1033
1034         for (i = 0; i < n && ports[i]; ++i) {}
1035
1036         if (ports[i]) {
1037                 ret = ports[i];
1038         }
1039
1040         free ((char *) ports);
1041
1042         return ret;
1043 }
1044
1045 void
1046 AudioEngine::update_total_latency (const Port& port)
1047 {
1048         port.recompute_total_latency ();
1049 }
1050
1051 void
1052 AudioEngine::transport_stop ()
1053 {
1054         GET_PRIVATE_JACK_POINTER (_jack);
1055         jack_transport_stop (_priv_jack);
1056 }
1057
1058 void
1059 AudioEngine::transport_start ()
1060 {
1061         GET_PRIVATE_JACK_POINTER (_jack);
1062         jack_transport_start (_priv_jack);
1063 }
1064
1065 void
1066 AudioEngine::transport_locate (nframes_t where)
1067 {
1068         GET_PRIVATE_JACK_POINTER (_jack);
1069         // cerr << "tell JACK to locate to " << where << endl;
1070         jack_transport_locate (_priv_jack, where);
1071 }
1072
1073 AudioEngine::TransportState
1074 AudioEngine::transport_state ()
1075 {
1076         GET_PRIVATE_JACK_POINTER_RET (_jack, ((TransportState) JackTransportStopped));
1077         jack_position_t pos;
1078         return (TransportState) jack_transport_query (_priv_jack, &pos);
1079 }
1080
1081 int
1082 AudioEngine::reset_timebase ()
1083 {
1084         GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
1085         if (_session) {
1086                 if (_session->config.get_jack_time_master()) {
1087                         return jack_set_timebase_callback (_priv_jack, 0, _jack_timebase_callback, this);
1088                 } else {
1089                         return jack_release_timebase (_jack);
1090                 }
1091         }
1092         return 0;
1093 }
1094
1095 int
1096 AudioEngine::freewheel (bool onoff)
1097 {
1098         GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
1099
1100         if (onoff != _freewheeling) {
1101           
1102           if (onoff) {
1103             _freewheel_thread_registered = false;
1104           }
1105           
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         }
1182
1183         return 0;
1184 }
1185
1186 int
1187 AudioEngine::reconnect_to_jack ()
1188 {
1189         if (_running) {
1190                 disconnect_from_jack ();
1191                 /* XXX give jackd a chance */
1192                 Glib::usleep (250000);
1193         }
1194
1195         if (connect_to_jack (jack_client_name)) {
1196                 error << _("failed to connect to JACK") << endmsg;
1197                 return -1;
1198         }
1199
1200         Ports::iterator i;
1201
1202         boost::shared_ptr<Ports> p = ports.reader ();
1203
1204         for (i = p->begin(); i != p->end(); ++i) {
1205                 if ((*i)->reestablish ()) {
1206                         break;
1207                 }
1208         }
1209
1210         if (i != p->end()) {
1211                 /* failed */
1212                 remove_all_ports ();
1213                 return -1;
1214         }
1215
1216         GET_PRIVATE_JACK_POINTER_RET (_jack,-1);
1217
1218         if (_session) {
1219                 _session->reset_jack_connection (_priv_jack);
1220                 nframes_t blocksize = jack_get_buffer_size (_priv_jack);
1221                 _session->set_block_size (blocksize);
1222                 _session->set_frame_rate (jack_get_sample_rate (_priv_jack));
1223
1224                 _raw_buffer_sizes[DataType::AUDIO] = blocksize * sizeof(float);
1225                 cout << "FIXME: Assuming maximum MIDI buffer size " << blocksize * 4 << "bytes" << endl;
1226                 _raw_buffer_sizes[DataType::MIDI] = blocksize * 4;
1227         }
1228
1229         last_monitor_check = 0;
1230
1231         jack_on_shutdown (_priv_jack, halted, this);
1232         jack_set_graph_order_callback (_priv_jack, _graph_order_callback, this);
1233         jack_set_thread_init_callback (_priv_jack, _thread_init_callback, this);
1234         jack_set_process_callback (_priv_jack, _process_callback, this);
1235         jack_set_sample_rate_callback (_priv_jack, _sample_rate_callback, this);
1236         jack_set_buffer_size_callback (_priv_jack, _bufsize_callback, this);
1237         jack_set_xrun_callback (_priv_jack, _xrun_callback, this);
1238         jack_set_sync_callback (_priv_jack, _jack_sync_callback, this);
1239         jack_set_freewheel_callback (_priv_jack, _freewheel_callback, this);
1240
1241         if (_session && _session->config.get_jack_time_master()) {
1242                 jack_set_timebase_callback (_priv_jack, 0, _jack_timebase_callback, this);
1243         }
1244
1245         if (jack_activate (_priv_jack) == 0) {
1246                 _running = true;
1247                 _has_run = true;
1248         } else {
1249                 return -1;
1250         }
1251
1252         /* re-establish connections */
1253
1254         for (i = p->begin(); i != p->end(); ++i) {
1255                 (*i)->reconnect ();
1256         }
1257
1258         Running (); /* EMIT SIGNAL*/
1259
1260         start_metering_thread ();
1261
1262         return 0;
1263 }
1264
1265 int
1266 AudioEngine::request_buffer_size (nframes_t nframes)
1267 {
1268         GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
1269
1270         if (nframes == jack_get_buffer_size (_priv_jack)) {
1271           return 0;
1272         }
1273         
1274         return jack_set_buffer_size (_priv_jack, nframes);
1275 }
1276
1277 void
1278 AudioEngine::update_total_latencies ()
1279 {
1280 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1281         GET_PRIVATE_JACK_POINTER (_jack);
1282         jack_recompute_total_latencies (_priv_jack);
1283 #endif
1284 }
1285
1286 string
1287 AudioEngine::make_port_name_relative (string portname)
1288 {
1289         string::size_type len;
1290         string::size_type n;
1291
1292         len = portname.length();
1293
1294         for (n = 0; n < len; ++n) {
1295                 if (portname[n] == ':') {
1296                         break;
1297                 }
1298         }
1299
1300         if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1301                 return portname.substr (n+1);
1302         }
1303
1304         return portname;
1305 }
1306
1307 string
1308 AudioEngine::make_port_name_non_relative (string portname)
1309 {
1310         string str;
1311
1312         if (portname.find_first_of (':') != string::npos) {
1313                 return portname;
1314         }
1315
1316         str  = jack_client_name;
1317         str += ':';
1318         str += portname;
1319
1320         return str;
1321 }
1322
1323 bool
1324 AudioEngine::is_realtime () const
1325 {
1326         GET_PRIVATE_JACK_POINTER_RET (_jack,false);
1327         return jack_is_realtime (_priv_jack);
1328 }