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