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