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