Apply MIDI looping patch from torbenh, with minor changes.
[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                 (*i)->cycle_start (nframes, 0);
355         }
356
357         if (_freewheeling) {
358                 /* emit the Freewheel signal and stop freewheeling in the event of trouble */
359                 if (Freewheel (nframes)) {
360                         jack_set_freewheel (_jack, false);
361                 }
362
363         } else {
364                 if (session) {
365                         session->process (nframes);
366                 }
367         }
368         
369         if (_freewheeling) {
370                 return 0;
371         }
372
373         if (!_running) {
374                 _processed_frames = next_processed_frames;
375                 return 0;
376         }
377
378         if (last_monitor_check + monitor_check_interval < next_processed_frames) {
379
380                 boost::shared_ptr<Ports> p = ports.reader();
381
382                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
383                         
384                         Port *port = (*i);
385                         bool x;
386                         
387                         if (port->_last_monitor != (x = port->monitoring_input ())) {
388                                 port->_last_monitor = x;
389                                 /* XXX I think this is dangerous, due to 
390                                    a likely mutex in the signal handlers ...
391                                 */
392                                  port->MonitorInputChanged (x); /* EMIT SIGNAL */
393                         }
394                 }
395                 last_monitor_check = next_processed_frames;
396         }
397
398         if (session->silent()) {
399
400                 boost::shared_ptr<Ports> p = ports.reader();
401
402                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
403                         
404                         Port *port = (*i);
405                         
406                         if (port->sends_output()) {
407                                 port->get_buffer(nframes, 0 ).silence(nframes);
408                         }
409                 }
410         }
411
412         // Finalize ports (ie write data if necessary)
413
414         for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
415
416                 (*i)->cycle_end (nframes, 0);
417         }
418
419         _processed_frames = next_processed_frames;
420         return 0;
421 }
422
423 int
424 AudioEngine::_sample_rate_callback (nframes_t nframes, void *arg)
425 {
426         return static_cast<AudioEngine *> (arg)->jack_sample_rate_callback (nframes);
427 }
428
429 int
430 AudioEngine::jack_sample_rate_callback (nframes_t nframes)
431 {
432         _frame_rate = nframes;
433         _usecs_per_cycle = (int) floor ((((double) frames_per_cycle() / nframes)) * 1000000.0);
434         
435         /* check for monitor input change every 1/10th of second */
436
437         monitor_check_interval = nframes / 10;
438         last_monitor_check = 0;
439         
440         if (session) {
441                 session->set_frame_rate (nframes);
442         }
443
444         SampleRateChanged (nframes); /* EMIT SIGNAL */
445
446         return 0;
447 }
448
449 int
450 AudioEngine::_bufsize_callback (nframes_t nframes, void *arg)
451 {
452         return static_cast<AudioEngine *> (arg)->jack_bufsize_callback (nframes);
453 }
454
455 int
456 AudioEngine::jack_bufsize_callback (nframes_t nframes)
457 {
458         _buffer_size = nframes;
459         _usecs_per_cycle = (int) floor ((((double) nframes / frame_rate())) * 1000000.0);
460         last_monitor_check = 0;
461
462         boost::shared_ptr<Ports> p = ports.reader();
463
464         for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
465                 (*i)->reset();
466         }
467
468         if (session) {
469                 session->set_block_size (_buffer_size);
470         }
471
472         return 0;
473 }
474
475 void
476 AudioEngine::stop_metering_thread ()
477 {
478         if (m_meter_thread) {
479                 g_atomic_int_set (&m_meter_exit, 1);
480                 m_meter_thread->join ();
481                 m_meter_thread = 0;
482         }
483 }
484
485 void
486 AudioEngine::start_metering_thread ()
487 {
488         if (m_meter_thread == 0) {
489                 g_atomic_int_set (&m_meter_exit, 0);
490                 m_meter_thread = Glib::Thread::create (sigc::mem_fun(this, &AudioEngine::meter_thread),
491                                                        500000, true, true, Glib::THREAD_PRIORITY_NORMAL);
492         }
493 }
494
495 void
496 AudioEngine::meter_thread ()
497 {
498         while (true) {
499                 Glib::usleep (10000); /* 1/100th sec interval */
500                 if (g_atomic_int_get(&m_meter_exit)) {
501                         break;
502                 }
503                 IO::update_meters ();
504         }
505 }
506
507 void 
508 AudioEngine::set_session (Session *s)
509 {
510         Glib::Mutex::Lock pl (_process_lock);
511
512         if (!session) {
513
514                 session = s;
515
516                 nframes_t blocksize = jack_get_buffer_size (_jack);
517                 
518                 /* page in as much of the session process code as we
519                    can before we really start running.
520                 */
521                 
522                 boost::shared_ptr<Ports> p = ports.reader();
523
524                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
525                         (*i)->cycle_start (blocksize, 0);
526                 }
527
528                 s->process (blocksize);
529                 s->process (blocksize);
530                 s->process (blocksize);
531                 s->process (blocksize);
532                 s->process (blocksize);
533                 s->process (blocksize);
534                 s->process (blocksize);
535                 s->process (blocksize);
536
537                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
538                         (*i)->cycle_end (blocksize, 0);
539                 }
540         }
541 }
542
543 void 
544 AudioEngine::remove_session ()
545 {
546         Glib::Mutex::Lock lm (_process_lock);
547
548         if (_running) {
549
550                 if (session) {
551                         session_remove_pending = true;
552                         session_removed.wait(_process_lock);
553                 }
554
555         } else {
556                 session = 0;
557         }
558         
559         //FIXME: Preliminary bugfix for  http://tracker.ardour.org/view.php?id=1985
560         //remove_all_ports ();
561 }
562
563 void
564 AudioEngine::port_registration_failure (const std::string& portname)
565 {
566         string full_portname = jack_client_name;
567         full_portname += ':';
568         full_portname += portname;
569         
570         
571         jack_port_t* p = jack_port_by_name (_jack, full_portname.c_str());
572         string reason;
573         
574         if (p) {
575                 reason = _("a port with this name already exists: check for duplicated track/bus names");
576         } else {
577                 reason = _("unknown error");
578         }
579         
580         throw PortRegistrationFailure (string_compose (_("AudioEngine: cannot register port \"%1\": %2"), portname, reason).c_str());
581 }       
582
583 Port *
584 AudioEngine::register_port (DataType dtype, const string& portname, bool input, bool publish)
585 {
586         Port* newport = 0;
587
588         /*cerr << "trying to register port with name " << portname << endl;*/
589         try {
590                 if (dtype == DataType::AUDIO) {
591                         newport = new AudioPort (portname, (input ? Port::IsInput : Port::IsOutput), publish, frames_per_cycle());
592                 } else if (dtype == DataType::MIDI) {
593                         newport = new MidiPort (portname, (input ? Port::IsInput : Port::IsOutput), publish, frames_per_cycle());
594                 } else {
595                         throw unknown_type();
596                 }
597
598                 /*cerr << "successfully got port " << portname << " with address " << newport << endl;*/
599
600                 RCUWriter<Ports> writer (ports);
601                 boost::shared_ptr<Ports> ps = writer.get_copy ();
602                 /*cerr << "Address of ports list: " << ps << endl
603                      << "Ports set size before insert: " << ps->size() << endl;*/
604                 ps->insert (ps->begin(), newport);
605                 /*cerr << "Ports set size after insert: " << ps->size() << endl;*/
606
607                 /* writer goes out of scope, forces update */
608
609                 return newport;
610         }
611
612         catch (...) {
613                 throw PortRegistrationFailure("unable to create port (unknown type?)");
614         }
615 }
616
617 Port*
618 AudioEngine::get_port (const std::string& full_name)
619 {
620         boost::shared_ptr<Ports> p = ports.reader();
621         
622         for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
623                 //cerr << "comparing port name '" << (*i)->name() << "' with '" << full_name << "'" << endl;
624                 if ((*i)->name() == full_name) {
625                         return *i;
626                 }
627         }
628         return 0;
629 }
630
631
632 Port *
633 AudioEngine::register_input_port (DataType type, const string& portname, bool publish)
634 {
635         return register_port (type, portname, true, publish);
636 }
637
638 Port *
639 AudioEngine::register_output_port (DataType type, const string& portname, bool publish)
640 {
641         return register_port (type, portname, false, publish);
642 }
643
644 int
645 AudioEngine::unregister_port (Port& port)
646 {
647         /* caller must hold process lock */
648
649         cerr << "about to unregister Port xx  x" << &port << "\n";
650
651         if (!_running) { 
652                 /* probably happening when the engine has been halted by JACK,
653                    in which case, there is nothing we can do here.
654                    */
655                 cerr << "not running\n";
656                 return 0;
657         }
658
659         {
660                 cerr << "before getcopy\n";
661                 
662                 RCUWriter<Ports> writer (ports);
663                 boost::shared_ptr<Ports> ps = writer.get_copy ();
664                 
665                 cerr << "Ports set size: " << ps.get()->size() << endl;
666
667                 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
668                         cerr << "before delete" << endl;
669                         if ((*i) == &port) {
670                                 cerr << "About to delete " << &port << endl;
671                                 delete *i;
672                                 ps->erase (i);
673                                 cerr << "After erasing ports size: " << ps->size();
674                                 break;
675                         }
676                 }
677                 
678                 /* writer goes out of scope, forces update */
679         }
680                 
681         cerr << "before remove_connections\n";
682         remove_connections_for (port);
683
684         return 0;
685 }
686
687 int 
688 AudioEngine::connect (const string& source, const string& destination)
689 {
690         int ret;
691
692         if (!_running) {
693                 if (!_has_run) {
694                         fatal << _("connect called before engine was started") << endmsg;
695                         /*NOTREACHED*/
696                 } else {
697                         return -1;
698                 }
699         }
700
701         string s = make_port_name_non_relative (source);
702         string d = make_port_name_non_relative (destination);
703                 
704         //cerr << "Trying to connect source: " << s << " with destination " << d << endl;
705         
706         Port* src = get_port (s);
707         Port* dst = get_port (d);
708
709         if (src && dst) {
710
711                 /* both ports are known to us, so do the internal connect stuff */
712
713                 if ((ret = src->connect (*dst)) == 0) {
714                         ret = dst->connect (*src);
715                 }
716
717         } else if (src || dst) {
718
719                 /* one port is known to us, try to connect it to something external */
720
721                 PortConnectableByName* pcn;
722                 string other;
723
724                 if (src) {
725                         pcn = dynamic_cast<PortConnectableByName*>(src);
726                         other = d;
727                 } else {
728                         pcn = dynamic_cast<PortConnectableByName*>(dst);
729                         other = s;
730                 }
731
732                 if (pcn) {
733                         ret = pcn->connect (other);
734                 } else {
735                         ret = -1;
736                 }
737
738         } else {
739
740                 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
741
742                 ret = -1;
743                 
744         }
745         
746         if (ret > 0) {
747                 error << string_compose(_("AudioEngine: connection already exists: %1 (%2) to %3 (%4)"), 
748                                         source, s, destination, d) 
749                       << endmsg;
750         } else if (ret < 0) {
751                 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"), 
752                                         source, s, destination, d) 
753                       << endmsg;
754         }
755
756         return ret;
757 }
758
759 int 
760 AudioEngine::disconnect (const string& source, const string& destination)
761 {
762         int ret;
763
764         if (!_running) {
765                 if (!_has_run) {
766                         fatal << _("disconnect called before engine was started") << endmsg;
767                         /*NOTREACHED*/
768                 } else {
769                         return -1;
770                 }
771         }
772         
773         string s = make_port_name_non_relative (source);
774         string d = make_port_name_non_relative (destination);
775
776         //cerr << "trying to disconnect port '" << s << "' from port '" << d << endl;
777         
778         Port* src = get_port (s);
779         Port* dst = get_port (d);
780
781         if (src && dst) {
782
783                 /* both ports are known to us, so do the internal connect stuff */
784                 
785                 if ((ret = src->disconnect (*dst)) == 0) {
786                         ret = dst->disconnect (*src);
787                 }
788
789         } else if (src || dst) {
790
791                 /* one port is known to us, try to connect it to something external */
792
793
794                 PortConnectableByName* pcn;
795                 string other;
796
797                 if (src) {
798                         pcn = dynamic_cast<PortConnectableByName*>(src);
799                         other = d;
800                 } else {
801                         pcn = dynamic_cast<PortConnectableByName*>(dst);
802                         other = s;
803                 }
804
805                 if (pcn) {
806                         ret = pcn->disconnect (other);
807                 } else {
808                         ret = -1;
809                 }
810
811         } else {
812
813                 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
814                 
815                 ret = -1;
816                 
817         }
818         
819         return ret;
820 }
821
822 int
823 AudioEngine::disconnect (Port& port)
824 {
825         if (!_running) {
826                 if (!_has_run) {
827                         fatal << _("disconnect called before engine was started") << endmsg;
828                         /*NOTREACHED*/
829                 } else {
830                         return -1;
831                 }
832         }
833
834         return port.disconnect_all ();
835 }
836
837 ARDOUR::nframes_t
838 AudioEngine::frame_rate ()
839 {
840         if (_jack) {
841                 if (_frame_rate == 0) {
842                         return (_frame_rate = jack_get_sample_rate (_jack));
843                 } else {
844                         return _frame_rate;
845                 }
846         } else {
847                 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
848                       << endmsg;
849                 /*NOTREACHED*/
850                 return 0;
851         }
852 }
853
854 ARDOUR::nframes_t
855 AudioEngine::frames_per_cycle ()
856 {
857         if (_jack) {
858                 if (_buffer_size == 0) {
859                         return (_buffer_size = jack_get_buffer_size (_jack));
860                 } else {
861                         return _buffer_size;
862                 }
863         } else {
864                 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
865                       << endmsg;
866                 /*NOTREACHED*/
867                 return 0;
868         }
869 }
870
871 /** Get a port by name.
872  * Note this can return NULL, it will NOT create a port if it is not found (any more).
873  */
874 Port *
875 AudioEngine::get_port_by_name (const string& portname, bool keep)
876 {
877         Glib::Mutex::Lock lm (_process_lock);
878
879         if (!_running) {
880                 if (!_has_run) {
881                         fatal << _("get_port_by_name() called before engine was started") << endmsg;
882                         /*NOTREACHED*/
883                 } else {
884                         return 0;
885                 }
886         }
887         
888         boost::shared_ptr<Ports> pr = ports.reader();
889         
890         for (Ports::iterator i = pr->begin(); i != pr->end(); ++i) {
891                 if (portname == (*i)->name()) {
892                         return (*i);
893                 }
894         }
895
896         return 0;
897 }
898
899 const char **
900 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
901 {
902         if (!_running) {
903                 if (!_has_run) {
904                         fatal << _("get_ports called before engine was started") << endmsg;
905                         /*NOTREACHED*/
906                 } else {
907                         return 0;
908                 }
909         }
910         return jack_get_ports (_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
911 }
912
913 void
914 AudioEngine::halted (void *arg)
915 {
916         AudioEngine* ae = static_cast<AudioEngine *> (arg);
917         bool was_running = ae->_running;
918
919         ae->stop_metering_thread ();
920
921         ae->_running = false;
922         ae->_buffer_size = 0;
923         ae->_frame_rate = 0;
924
925         cerr << "!!! HALTED !!!\n";
926
927         if (was_running) {
928                 ae->Halted(); /* EMIT SIGNAL */
929         }
930 }
931
932 bool
933 AudioEngine::can_request_hardware_monitoring () 
934 {
935         const char ** ports;
936
937         if (!_jack) {
938                 return 0;
939         }
940
941         if ((ports = jack_get_ports (_jack, NULL, JACK_DEFAULT_AUDIO_TYPE, JackPortCanMonitor)) == 0) {
942                 return false;
943         }
944
945         free (ports);
946
947         return true;
948 }
949
950
951 uint32_t
952 AudioEngine::n_physical_outputs (DataType type) const
953 {
954         const char ** ports;
955         uint32_t i = 0;
956
957         if (!_jack) {
958                 return 0;
959         }
960
961         if ((ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsInput)) == 0) {
962                 return 0;
963         }
964
965         for (i = 0; ports[i]; ++i);
966         free (ports);
967
968         return i;
969 }
970
971 uint32_t
972 AudioEngine::n_physical_inputs (DataType type) const
973 {
974         const char ** ports;
975         uint32_t i = 0;
976         
977         if (!_jack) {
978                 return 0;
979         }
980         
981         if ((ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsOutput)) == 0) {
982                 return 0;
983         }
984
985         if (ports) {
986                 for (i = 0; ports[i]; ++i);
987                 free (ports);
988         }
989         return i;
990 }
991
992 void
993 AudioEngine::get_physical_inputs (DataType type, vector<string>& ins)
994 {
995         const char ** ports;
996         uint32_t i = 0;
997         
998         if (!_jack) {
999                 return;
1000         }
1001         
1002         if ((ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsOutput)) == 0) {
1003                 return;
1004         }
1005
1006         if (ports) {
1007                 for (i = 0; ports[i]; ++i) {
1008                         ins.push_back (ports[i]);
1009                 }
1010                 free (ports);
1011         }
1012 }
1013
1014 void
1015 AudioEngine::get_physical_outputs (DataType type, vector<string>& outs)
1016 {
1017         const char ** ports;
1018         uint32_t i = 0;
1019         
1020         if (!_jack) {
1021                 return;
1022         }
1023         
1024         if ((ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|JackPortIsInput)) == 0) {
1025                 return;
1026         }
1027
1028         if (ports) {
1029                 for (i = 0; ports[i]; ++i) {
1030                         outs.push_back (ports[i]);
1031                 }
1032                 free (ports);
1033         }
1034 }
1035
1036 string
1037 AudioEngine::get_nth_physical (DataType type, uint32_t n, int flag)
1038 {
1039         const char ** ports;
1040         uint32_t i;
1041         string ret;
1042
1043         assert(type != DataType::NIL);
1044
1045         if (!_running || !_jack) {
1046                 if (!_has_run) {
1047                         fatal << _("get_nth_physical called before engine was started") << endmsg;
1048                         /*NOTREACHED*/
1049                 } else {
1050                         return "";
1051                 }
1052         }
1053
1054         ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|flag);
1055         
1056         if (ports == 0) {
1057                 return "";
1058         }
1059
1060         for (i = 0; i < n && ports[i]; ++i);
1061
1062         if (ports[i]) {
1063                 ret = ports[i];
1064         }
1065
1066         free ((char *) ports);
1067
1068         return ret;
1069 }
1070
1071 ARDOUR::nframes_t
1072 AudioEngine::get_port_total_latency (const Port& port)
1073 {
1074         return port.total_latency ();
1075 }
1076
1077 void
1078 AudioEngine::update_total_latency (const Port& port)
1079 {
1080         if (!_jack) {
1081                 fatal << _("update_total_latency() called with no JACK client connection") << endmsg;
1082                 /*NOTREACHED*/
1083         }
1084
1085         if (!_running) {
1086                 if (!_has_run) {
1087                         fatal << _("update_total_latency() called before engine was started") << endmsg;
1088                         /*NOTREACHED*/
1089                 } 
1090         }
1091
1092         port.recompute_total_latency ();
1093 }
1094
1095 void
1096 AudioEngine::transport_stop ()
1097 {
1098         if (_jack) {
1099                 jack_transport_stop (_jack);
1100         }
1101 }
1102
1103 void
1104 AudioEngine::transport_start ()
1105 {
1106         // cerr << "tell JACK to start\n";
1107         if (_jack) {
1108                 jack_transport_start (_jack);
1109         }
1110 }
1111
1112 void
1113 AudioEngine::transport_locate (nframes_t where)
1114 {
1115         // cerr << "tell JACK to locate to " << where << endl;
1116         if (_jack) {
1117                 jack_transport_locate (_jack, where);
1118         }
1119 }
1120
1121 AudioEngine::TransportState
1122 AudioEngine::transport_state ()
1123 {
1124         if (_jack) {
1125                 jack_position_t pos;
1126                 return (TransportState) jack_transport_query (_jack, &pos);
1127         } else {
1128                 return (TransportState) JackTransportStopped;
1129         }
1130 }
1131
1132 int
1133 AudioEngine::reset_timebase ()
1134 {
1135         if (_jack) {
1136                 if (Config->get_jack_time_master()) {
1137                         return jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1138                 } else {
1139                         return jack_release_timebase (_jack);
1140                 }
1141         } else {
1142                 return -1;
1143         }
1144 }
1145
1146 int
1147 AudioEngine::freewheel (bool onoff)
1148 {
1149         if (_jack) {
1150
1151                 if (onoff != _freewheeling) {
1152
1153                         if (onoff) {
1154                                 _freewheel_thread_registered = false;
1155                         }
1156
1157                         return jack_set_freewheel (_jack, onoff);
1158
1159                 } else {
1160                         /* already doing what has been asked for */
1161                         return 0;
1162                 }
1163
1164         } else {
1165                 return -1;
1166         }
1167 }
1168
1169 void
1170 AudioEngine::remove_all_ports ()
1171 {
1172         /* process lock MUST be held */
1173
1174         {
1175                 RCUWriter<Ports> writer (ports);
1176                 boost::shared_ptr<Ports> ps = writer.get_copy ();
1177                 ps->clear ();
1178         }
1179 }
1180
1181 void
1182 AudioEngine::remove_connections_for (Port& port)
1183 {
1184         for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ) {
1185                 PortConnections::iterator tmp;
1186                 
1187                 tmp = i;
1188                 ++tmp;
1189                 
1190                 if ((*i).first == port.name()) {
1191                         port_connections.erase (i);
1192                 }
1193
1194                 i = tmp;
1195         }
1196 }
1197
1198
1199 #ifdef HAVE_JACK_CLIENT_OPEN
1200
1201 int
1202 AudioEngine::connect_to_jack (string client_name)
1203 {
1204         jack_options_t options = JackNullOption;
1205         jack_status_t status;
1206         const char *server_name = NULL;
1207
1208         jack_client_name = client_name; /* might be reset below */
1209         _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
1210
1211         if (_jack == NULL) {
1212                 // error message is not useful here
1213                 return -1;
1214         }
1215
1216         if (status & JackNameNotUnique) {
1217                 jack_client_name = jack_get_client_name (_jack);
1218         }
1219
1220         jack_set_error_function (ardour_jack_error);
1221         
1222         return 0;
1223 }
1224
1225 #else
1226
1227 int
1228 AudioEngine::connect_to_jack (string client_name)
1229 {
1230         jack_client_name = client_name;
1231
1232         if ((_jack = jack_client_new (client_name.c_str())) == 0) {
1233                 return -1;
1234         }
1235
1236         return 0;
1237 }
1238
1239 #endif /* HAVE_JACK_CLIENT_OPEN */
1240
1241 int 
1242 AudioEngine::disconnect_from_jack ()
1243 {
1244         if (!_jack) {
1245                 return 0;
1246         }
1247
1248
1249         if (_running) {
1250                 stop_metering_thread ();
1251         }
1252
1253         { 
1254                 Glib::Mutex::Lock lm (_process_lock);
1255                 jack_client_close (_jack);
1256                 _jack = 0;
1257         }
1258
1259         _buffer_size = 0;
1260         _frame_rate = 0;
1261
1262         if (_running) {
1263                 _running = false;
1264                 Stopped(); /* EMIT SIGNAL */
1265         }
1266
1267         return 0;
1268 }
1269
1270 int
1271 AudioEngine::reconnect_to_jack ()
1272 {
1273         if (_running) {
1274                 disconnect_from_jack ();
1275                 /* XXX give jackd a chance */
1276                 Glib::usleep (250000);
1277         }
1278
1279         if (connect_to_jack (jack_client_name)) {
1280                 error << _("failed to connect to JACK") << endmsg;
1281                 return -1;
1282         }
1283
1284         Ports::iterator i;
1285
1286         boost::shared_ptr<Ports> p = ports.reader ();
1287
1288         for (i = p->begin(); i != p->end(); ++i) {
1289                 if ((*i)->reestablish ()) {
1290                         break;
1291                 } 
1292         }
1293
1294         if (i != p->end()) {
1295                 /* failed */
1296                 remove_all_ports ();
1297                 return -1;
1298         } 
1299
1300
1301         if (session) {
1302                 session->reset_jack_connection (_jack);
1303                 nframes_t blocksize = jack_get_buffer_size (_jack);
1304                 session->set_block_size (blocksize);
1305                 session->set_frame_rate (jack_get_sample_rate (_jack));
1306         }
1307
1308         last_monitor_check = 0;
1309         
1310         jack_on_shutdown (_jack, halted, this);
1311         jack_set_graph_order_callback (_jack, _graph_order_callback, this);
1312         jack_set_thread_init_callback (_jack, _thread_init_callback, this);
1313         jack_set_process_callback (_jack, _process_callback, this);
1314         jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
1315         jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
1316         jack_set_xrun_callback (_jack, _xrun_callback, this);
1317         jack_set_sync_callback (_jack, _jack_sync_callback, this);
1318         jack_set_freewheel_callback (_jack, _freewheel_callback, this);
1319         
1320         if (Config->get_jack_time_master()) {
1321                 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1322         }
1323         
1324         if (jack_activate (_jack) == 0) {
1325                 _running = true;
1326                 _has_run = true;
1327         } else {
1328                 return -1;
1329         }
1330
1331         /* re-establish connections */
1332         
1333         for (i = p->begin(); i != p->end(); ++i) {
1334                 (*i)->reconnect ();
1335         }
1336
1337         Running (); /* EMIT SIGNAL*/
1338
1339         start_metering_thread ();
1340
1341         return 0;
1342 }
1343
1344 int
1345 AudioEngine::request_buffer_size (nframes_t nframes)
1346 {
1347         if (_jack) {
1348
1349                 if (nframes == jack_get_buffer_size (_jack)) {
1350                         return 0;
1351                 }
1352
1353                 return jack_set_buffer_size (_jack, nframes);
1354
1355         } else {
1356                 return -1;
1357         }
1358 }
1359
1360 void
1361 AudioEngine::update_total_latencies ()
1362 {
1363 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1364         if (_jack) {
1365                 jack_recompute_total_latencies (_jack);
1366         }
1367 #endif
1368 }
1369                 
1370 string
1371 AudioEngine::make_port_name_relative (string portname)
1372 {
1373         string::size_type len;
1374         string::size_type n;
1375         
1376         len = portname.length();
1377
1378         for (n = 0; n < len; ++n) {
1379                 if (portname[n] == ':') {
1380                         break;
1381                 }
1382         }
1383         
1384         if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1385                 return portname.substr (n+1);
1386         }
1387
1388         return portname;
1389 }
1390
1391 string
1392 AudioEngine::make_port_name_non_relative (string portname)
1393 {
1394         string str;
1395
1396         if (portname.find_first_of (':') != string::npos) {
1397                 return portname;
1398         }
1399
1400         str  = jack_client_name;
1401         str += ':';
1402         str += portname;
1403         
1404         return str;
1405 }
1406
1407 bool
1408 AudioEngine::is_realtime () const
1409 {
1410         if (_jack) {
1411                 return jack_is_realtime (_jack);
1412         } else {
1413                 return false;
1414         }
1415 }