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