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