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