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