* Add SysEx Support to MidiModel / SMF
[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, bool publish)
580 {
581         Port* newport = 0;
582
583         /*cerr << "trying to register port with name " << portname << endl;*/
584         try {
585                 if (dtype == DataType::AUDIO) {
586                         newport = new AudioPort (portname, (input ? Port::IsInput : Port::IsOutput), publish, frames_per_cycle());
587                 } else if (dtype == DataType::MIDI) {
588                         newport = new MidiPort (portname, (input ? Port::IsInput : Port::IsOutput), publish, frames_per_cycle());
589                 } else {
590                         throw unknown_type();
591                 }
592
593                 /*cerr << "successfully got port " << portname << " with address " << newport << endl;*/
594
595                 RCUWriter<Ports> writer (ports);
596                 boost::shared_ptr<Ports> ps = writer.get_copy ();
597                 /*cerr << "Address of ports list: " << ps << endl
598                      << "Ports set size before insert: " << ps->size() << endl;*/
599                 ps->insert (ps->begin(), newport);
600                 /*cerr << "Ports set size after insert: " << ps->size() << endl;*/
601
602                 /* writer goes out of scope, forces update */
603
604                 return newport;
605         }
606
607         catch (...) {
608                 throw PortRegistrationFailure("unable to create port (unknown type?)");
609         }
610 }
611
612 Port *
613 AudioEngine::register_input_port (DataType type, const string& portname, bool publish)
614 {
615         return register_port (type, portname, true, publish);
616 }
617
618 Port *
619 AudioEngine::register_output_port (DataType type, const string& portname, bool publish)
620 {
621         return register_port (type, portname, false, publish);
622 }
623
624 int
625 AudioEngine::unregister_port (Port& port)
626 {
627         /* caller must hold process lock */
628
629         cerr << "about to unregister Port xx  x" << &port << "\n";
630
631         if (!_running) { 
632                 /* probably happening when the engine has been halted by JACK,
633                    in which case, there is nothing we can do here.
634                    */
635                 cerr << "not running\n";
636                 return 0;
637         }
638
639         {
640                 cerr << "before getcopy\n";
641                 
642                 RCUWriter<Ports> writer (ports);
643                 boost::shared_ptr<Ports> ps = writer.get_copy ();
644                 
645                 cerr << "Ports set size: " << ps.get()->size() << endl;
646
647                 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
648                         cerr << "before delete" << endl;
649                         if ((*i) == &port) {
650                                 cerr << "About to delete " << &port << endl;
651                                 delete *i;
652                                 ps->erase (i);
653                                 cerr << "After erasing ports size: " << ps->size();
654                                 break;
655                         }
656                 }
657                 
658                 /* writer goes out of scope, forces update */
659         }
660                 
661         cerr << "before remove_connections\n";
662         remove_connections_for (port);
663
664         return 0;
665 }
666
667 int 
668 AudioEngine::connect (const string& source, const string& destination)
669 {
670         /* caller must hold process lock */
671         
672         int ret;
673
674         if (!_running) {
675                 if (!_has_run) {
676                         fatal << _("connect called before engine was started") << endmsg;
677                         /*NOTREACHED*/
678                 } else {
679                         return -1;
680                 }
681         }
682
683         string s = make_port_name_non_relative (source);
684         string d = make_port_name_non_relative (destination);
685
686         Port* src = get_port_by_name_locked (s);
687         Port* dst = get_port_by_name_locked (d);
688
689                 if (src) {
690                         ret = src->connect (d);
691         } else if (dst) {
692                         ret = dst->connect (s);
693         } else {
694                 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
695                 ret = -1;
696         }
697         
698         if (ret > 0) {
699                 error << string_compose(_("AudioEngine: connection already exists: %1 (%2) to %3 (%4)"), 
700                                         source, s, destination, d) 
701                       << endmsg;
702         } else if (ret < 0) {
703                 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"), 
704                                         source, s, destination, d) 
705                       << endmsg;
706         }
707
708         return ret;
709 }
710
711 int 
712 AudioEngine::disconnect (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 << _("disconnect 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         Port* src = get_port_by_name_locked (s);
731         Port* dst = get_port_by_name_locked (d);
732
733                 if (src) {
734                         ret = src->disconnect (d);
735         } else if (dst) {
736                         ret = dst->disconnect (s);
737         } else {
738                 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
739                 ret = -1;
740         }
741         return ret;
742 }
743
744 int
745 AudioEngine::disconnect (Port& port)
746 {
747         if (!_running) {
748                 if (!_has_run) {
749                         fatal << _("disconnect called before engine was started") << endmsg;
750                         /*NOTREACHED*/
751                 } else {
752                         return -1;
753                 }
754         }
755
756         return port.disconnect_all ();
757 }
758
759 ARDOUR::nframes_t
760 AudioEngine::frame_rate ()
761 {
762         if (_jack) {
763                 if (_frame_rate == 0) {
764                         return (_frame_rate = jack_get_sample_rate (_jack));
765                 } else {
766                         return _frame_rate;
767                 }
768         } else {
769                 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
770                       << endmsg;
771                 /*NOTREACHED*/
772                 return 0;
773         }
774 }
775
776 ARDOUR::nframes_t
777 AudioEngine::frames_per_cycle ()
778 {
779         if (_jack) {
780                 if (_buffer_size == 0) {
781                         return (_buffer_size = jack_get_buffer_size (_jack));
782                 } else {
783                         return _buffer_size;
784                 }
785         } else {
786                 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
787                       << endmsg;
788                 /*NOTREACHED*/
789                 return 0;
790         }
791 }
792
793 /** @param name Full name of port (including prefix:)
794  *  @return Corresponding Port*, or 0.  This object remains the property of the AudioEngine
795  *  so must not be deleted.
796  */
797 Port *
798 AudioEngine::get_port_by_name (const string& portname)
799 {
800         assert (portname.find_first_of (':') != string::npos);
801         
802         Glib::Mutex::Lock lm (_process_lock);
803         return get_port_by_name_locked (portname);
804 }
805
806 Port *
807 AudioEngine::get_port_by_name_locked (const string& portname)
808 {
809         /* caller must hold process lock */
810
811         if (!_running) {
812                 if (!_has_run) {
813                         fatal << _("get_port_by_name_locked() called before engine was started") << endmsg;
814                         /*NOTREACHED*/
815                 } else {
816                         return 0;
817                 }
818         }
819
820         if (portname.substr (0, jack_client_name.length ()) != jack_client_name) {
821                 /* not an ardour: port */
822                 return 0;
823         }
824
825         std::string const rel = make_port_name_relative (portname);
826
827         boost::shared_ptr<Ports> pr = ports.reader();
828
829         for (Ports::iterator i = pr->begin(); i != pr->end(); ++i) {
830                 if (rel == (*i)->name()) {
831                         return *i;
832                 }
833         }
834
835         return 0;
836 }
837
838
839
840
841
842 const char **
843 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
844 {
845         if (!_running) {
846                 if (!_has_run) {
847                         fatal << _("get_ports called before engine was started") << endmsg;
848                         /*NOTREACHED*/
849                 } else {
850                         return 0;
851                 }
852         }
853         return jack_get_ports (_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
854 }
855
856 void
857 AudioEngine::halted (void *arg)
858 {
859         AudioEngine* ae = static_cast<AudioEngine *> (arg);
860         bool was_running = ae->_running;
861
862         ae->stop_metering_thread ();
863
864         ae->_running = false;
865         ae->_buffer_size = 0;
866         ae->_frame_rate = 0;
867
868         if (was_running) {
869                 ae->Halted(); /* EMIT SIGNAL */
870         }
871 }
872
873 bool
874 AudioEngine::can_request_hardware_monitoring () 
875 {
876         const char ** ports;
877
878         if (!_jack) {
879                 return 0;
880         }
881
882         if ((ports = jack_get_ports (_jack, NULL, JACK_DEFAULT_AUDIO_TYPE, JackPortCanMonitor)) == 0) {
883                 return false;
884         }
885
886         free (ports);
887
888         return true;
889 }
890
891
892 uint32_t
893 AudioEngine::n_physical_outputs (DataType type) const
894 {
895         const char ** ports;
896         uint32_t i = 0;
897
898         if (!_jack) {
899                 return 0;
900         }
901
902         if ((ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsInput)) == 0) {
903                 return 0;
904         }
905
906         for (i = 0; ports[i]; ++i);
907         free (ports);
908
909         return i;
910 }
911
912 uint32_t
913 AudioEngine::n_physical_inputs (DataType type) const
914 {
915         const char ** ports;
916         uint32_t i = 0;
917         
918         if (!_jack) {
919                 return 0;
920         }
921         
922         if ((ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsOutput)) == 0) {
923                 return 0;
924         }
925
926         if (ports) {
927                 for (i = 0; ports[i]; ++i);
928                 free (ports);
929         }
930         return i;
931 }
932
933 void
934 AudioEngine::get_physical_inputs (DataType type, vector<string>& ins)
935 {
936         const char ** ports;
937         uint32_t i = 0;
938         
939         if (!_jack) {
940                 return;
941         }
942         
943         if ((ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsOutput)) == 0) {
944                 return;
945         }
946
947         if (ports) {
948                 for (i = 0; ports[i]; ++i) {
949                         ins.push_back (ports[i]);
950                 }
951                 free (ports);
952         }
953 }
954
955 void
956 AudioEngine::get_physical_outputs (DataType type, vector<string>& outs)
957 {
958         const char ** ports;
959         uint32_t i = 0;
960         
961         if (!_jack) {
962                 return;
963         }
964         
965         if ((ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsInput)) == 0) {
966                 return;
967         }
968
969         if (ports) {
970                 for (i = 0; ports[i]; ++i) {
971                         outs.push_back (ports[i]);
972                 }
973                 free (ports);
974         }
975 }
976
977 string
978 AudioEngine::get_nth_physical (DataType type, uint32_t n, int flag)
979 {
980         const char ** ports;
981         uint32_t i;
982         string ret;
983
984         assert(type != DataType::NIL);
985
986         if (!_running || !_jack) {
987                 if (!_has_run) {
988                         fatal << _("get_nth_physical called before engine was started") << endmsg;
989                         /*NOTREACHED*/
990                 } else {
991                         return "";
992                 }
993         }
994
995         ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|flag);
996         
997         if (ports == 0) {
998                 return "";
999         }
1000
1001         for (i = 0; i < n && ports[i]; ++i);
1002
1003         if (ports[i]) {
1004                 ret = ports[i];
1005         }
1006
1007         free ((char *) ports);
1008
1009         return ret;
1010 }
1011
1012 void
1013 AudioEngine::update_total_latency (const Port& port)
1014 {
1015         if (!_jack) {
1016                 fatal << _("update_total_latency() called with no JACK client connection") << endmsg;
1017                 /*NOTREACHED*/
1018         }
1019
1020         if (!_running) {
1021                 if (!_has_run) {
1022                         fatal << _("update_total_latency() called before engine was started") << endmsg;
1023                         /*NOTREACHED*/
1024                 } 
1025         }
1026
1027         port.recompute_total_latency ();
1028 }
1029
1030 void
1031 AudioEngine::transport_stop ()
1032 {
1033         if (_jack) {
1034                 jack_transport_stop (_jack);
1035         }
1036 }
1037
1038 void
1039 AudioEngine::transport_start ()
1040 {
1041         if (_jack) {
1042                 jack_transport_start (_jack);
1043         }
1044 }
1045
1046 void
1047 AudioEngine::transport_locate (nframes_t where)
1048 {
1049         // cerr << "tell JACK to locate to " << where << endl;
1050         if (_jack) {
1051                 jack_transport_locate (_jack, where);
1052         }
1053 }
1054
1055 AudioEngine::TransportState
1056 AudioEngine::transport_state ()
1057 {
1058         if (_jack) {
1059                 jack_position_t pos;
1060                 return (TransportState) jack_transport_query (_jack, &pos);
1061         } else {
1062                 return (TransportState) JackTransportStopped;
1063         }
1064 }
1065
1066 int
1067 AudioEngine::reset_timebase ()
1068 {
1069         if (_jack) {
1070                 if (Config->get_jack_time_master()) {
1071                         return jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1072                 } else {
1073                         return jack_release_timebase (_jack);
1074                 }
1075         } else {
1076                 return -1;
1077         }
1078 }
1079
1080 int
1081 AudioEngine::freewheel (bool onoff)
1082 {
1083         if (_jack) {
1084
1085                 if (onoff != _freewheeling) {
1086
1087                         if (onoff) {
1088                                 _freewheel_thread_registered = false;
1089                         }
1090
1091                         return jack_set_freewheel (_jack, onoff);
1092
1093                 } else {
1094                         /* already doing what has been asked for */
1095                         return 0;
1096                 }
1097
1098         } else {
1099                 return -1;
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                 ps->clear ();
1112         }
1113 }
1114
1115 void
1116 AudioEngine::remove_connections_for (Port& port)
1117 {
1118         for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ) {
1119                 PortConnections::iterator tmp;
1120                 
1121                 tmp = i;
1122                 ++tmp;
1123                 
1124                 if ((*i).first == port.name()) {
1125                         port_connections.erase (i);
1126                 }
1127
1128                 i = tmp;
1129         }
1130 }
1131
1132
1133 #ifdef HAVE_JACK_CLIENT_OPEN
1134
1135 int
1136 AudioEngine::connect_to_jack (string client_name)
1137 {
1138         jack_options_t options = JackNullOption;
1139         jack_status_t status;
1140         const char *server_name = NULL;
1141
1142         jack_client_name = client_name; /* might be reset below */
1143         _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
1144
1145         if (_jack == NULL) {
1146                 // error message is not useful here
1147                 return -1;
1148         }
1149
1150         if (status & JackNameNotUnique) {
1151                 jack_client_name = jack_get_client_name (_jack);
1152         }
1153
1154         jack_set_error_function (ardour_jack_error);
1155         
1156         return 0;
1157 }
1158
1159 #else
1160
1161 int
1162 AudioEngine::connect_to_jack (string client_name)
1163 {
1164         jack_client_name = client_name;
1165
1166         if ((_jack = jack_client_new (client_name.c_str())) == 0) {
1167                 return -1;
1168         }
1169
1170         return 0;
1171 }
1172
1173 #endif /* HAVE_JACK_CLIENT_OPEN */
1174
1175 int 
1176 AudioEngine::disconnect_from_jack ()
1177 {
1178         if (!_jack) {
1179                 return 0;
1180         }
1181
1182
1183         if (_running) {
1184                 stop_metering_thread ();
1185         }
1186
1187         { 
1188                 Glib::Mutex::Lock lm (_process_lock);
1189                 jack_client_close (_jack);
1190                 _jack = 0;
1191         }
1192
1193         _buffer_size = 0;
1194         _frame_rate = 0;
1195
1196         if (_running) {
1197                 _running = false;
1198                 Stopped(); /* EMIT SIGNAL */
1199         }
1200
1201         return 0;
1202 }
1203
1204 int
1205 AudioEngine::reconnect_to_jack ()
1206 {
1207         if (_running) {
1208                 disconnect_from_jack ();
1209                 /* XXX give jackd a chance */
1210                 Glib::usleep (250000);
1211         }
1212
1213         if (connect_to_jack (jack_client_name)) {
1214                 error << _("failed to connect to JACK") << endmsg;
1215                 return -1;
1216         }
1217
1218         Ports::iterator i;
1219
1220         boost::shared_ptr<Ports> p = ports.reader ();
1221
1222         for (i = p->begin(); i != p->end(); ++i) {
1223                 if ((*i)->reestablish ()) {
1224                         break;
1225                 } 
1226         }
1227
1228         if (i != p->end()) {
1229                 /* failed */
1230                 remove_all_ports ();
1231                 return -1;
1232         } 
1233
1234
1235         if (session) {
1236                 session->reset_jack_connection (_jack);
1237                 nframes_t blocksize = jack_get_buffer_size (_jack);
1238                 session->set_block_size (blocksize);
1239                 session->set_frame_rate (jack_get_sample_rate (_jack));
1240         }
1241
1242         last_monitor_check = 0;
1243         
1244         jack_on_shutdown (_jack, halted, this);
1245         jack_set_graph_order_callback (_jack, _graph_order_callback, this);
1246         jack_set_thread_init_callback (_jack, _thread_init_callback, this);
1247         jack_set_process_callback (_jack, _process_callback, this);
1248         jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
1249         jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
1250         jack_set_xrun_callback (_jack, _xrun_callback, this);
1251         jack_set_sync_callback (_jack, _jack_sync_callback, this);
1252         jack_set_freewheel_callback (_jack, _freewheel_callback, this);
1253         
1254         if (Config->get_jack_time_master()) {
1255                 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1256         } 
1257         
1258         if (jack_activate (_jack) == 0) {
1259                 _running = true;
1260                 _has_run = true;
1261         } else {
1262                 return -1;
1263         }
1264
1265         /* re-establish connections */
1266         
1267         for (i = p->begin(); i != p->end(); ++i) {
1268                 (*i)->reconnect ();
1269         }
1270
1271         Running (); /* EMIT SIGNAL*/
1272
1273         start_metering_thread ();
1274
1275         return 0;
1276 }
1277
1278 int
1279 AudioEngine::request_buffer_size (nframes_t nframes)
1280 {
1281         if (_jack) {
1282
1283                 if (nframes == jack_get_buffer_size (_jack)) {
1284                         return 0;
1285                 }
1286
1287                 return jack_set_buffer_size (_jack, nframes);
1288
1289         } else {
1290                 return -1;
1291         }
1292 }
1293
1294 void
1295 AudioEngine::update_total_latencies ()
1296 {
1297 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1298         if (_jack) {
1299                 jack_recompute_total_latencies (_jack);
1300         }
1301 #endif
1302 }
1303                 
1304 string
1305 AudioEngine::make_port_name_relative (string portname)
1306 {
1307         string::size_type len;
1308         string::size_type n;
1309         
1310         len = portname.length();
1311
1312         for (n = 0; n < len; ++n) {
1313                 if (portname[n] == ':') {
1314                         break;
1315                 }
1316         }
1317         
1318         if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1319                 return portname.substr (n+1);
1320         }
1321
1322         return portname;
1323 }
1324
1325 string
1326 AudioEngine::make_port_name_non_relative (string portname)
1327 {
1328         string str;
1329
1330         if (portname.find_first_of (':') != string::npos) {
1331                 return portname;
1332         }
1333
1334         str  = jack_client_name;
1335         str += ':';
1336         str += portname;
1337         
1338         return str;
1339 }
1340
1341 bool
1342 AudioEngine::is_realtime () const
1343 {
1344         if (_jack) {
1345                 return jack_is_realtime (_jack);
1346         } else {
1347                 return false;
1348         }
1349 }