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