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