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