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