e68dc718d9d352527e558a5c9383cf30ef3b1772
[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                 } else {
160                         jack_deactivate (_jack);
161                 }
162                 Stopped(); /* EMIT SIGNAL */
163         }
164
165         return _running ? -1 : 0;
166 }
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         }
383         m_meter_thread->join ();
384         m_meter_thread = 0;
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 (g_atomic_int_get(&m_meter_exit) != true) {
399                 Glib::usleep (10000); /* 1/100th sec interval */
400                 IO::update_meters ();
401         }
402 }
403
404 void 
405 AudioEngine::set_session (Session *s)
406 {
407         if (!session) {
408                 session = s;
409         }
410 }
411
412 void 
413 AudioEngine::remove_session ()
414 {
415         Glib::Mutex::Lock lm (_process_lock);
416
417         if (_running) {
418
419                 if (session) {
420                         session_remove_pending = true;
421                         session_removed.wait(_process_lock);
422                 } 
423
424         } else {
425
426                 session = 0;
427
428         }
429         
430         remove_all_ports ();
431 }
432
433 Port *
434 AudioEngine::register_input_port (DataType type, const string& portname)
435 {
436         if (!_running) {
437                 if (!_has_run) {
438                         fatal << _("register input port called before engine was started") << endmsg;
439                         /*NOTREACHED*/
440                 } else {
441                         return 0;
442                 }
443         }
444
445         jack_port_t *p = jack_port_register (_jack, portname.c_str(), type.to_jack_type(), JackPortIsInput, 0);
446
447         if (p) {
448
449                 Port *newport;
450
451                 if ((newport = new Port (p)) != 0) {
452                         RCUWriter<Ports> writer (ports);
453                         boost::shared_ptr<Ports> ps = writer.get_copy ();
454                         ps->insert (ps->begin(), newport);
455                         /* writer goes out of scope, forces update */
456                 }
457
458                 return newport;
459
460         } else {
461
462                 _process_lock.unlock();
463                 throw PortRegistrationFailure();
464         }
465
466         return 0;
467 }
468
469 Port *
470 AudioEngine::register_output_port (DataType type, const string& portname)
471 {
472         if (!_running) {
473                 if (!_has_run) {
474                         fatal << _("register output port called before engine was started") << endmsg;
475                         /*NOTREACHED*/
476                 } else {
477                         return 0;
478                 }
479         }
480
481         jack_port_t *p;
482
483         if ((p = jack_port_register (_jack, portname.c_str(),
484                 type.to_jack_type(), JackPortIsOutput, 0)) != 0) {
485
486                 Port *newport = 0;
487
488                 {
489                         RCUWriter<Ports> writer (ports);
490                         boost::shared_ptr<Ports> ps = writer.get_copy ();
491                         
492                         newport = new Port (p);
493                         ps->insert (ps->begin(), newport);
494
495                         /* writer goes out of scope, forces update */
496                 }
497
498                 return newport;
499
500         } else {
501
502                 _process_lock.unlock();
503                 throw PortRegistrationFailure ();
504         }
505
506         return 0;
507 }
508
509
510 int          
511 AudioEngine::unregister_port (Port *port)
512 {
513         if (!_running) { 
514                 /* probably happening when the engine has been halted by JACK,
515                    in which case, there is nothing we can do here.
516                 */
517                 return 0;
518         }
519
520         if (port) {
521
522                 int ret = jack_port_unregister (_jack, port->_port);
523                 
524                 if (ret == 0) {
525                         
526                         {
527
528                                 RCUWriter<Ports> writer (ports);
529                                 boost::shared_ptr<Ports> ps = writer.get_copy ();
530                                 
531                                 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
532                                         if ((*i) == port) {
533                                                 ps->erase (i);
534                                                 break;
535                                         }
536                                 }
537
538                                 /* writer goes out of scope, forces update */
539                         }
540
541                         remove_connections_for (port);
542                 }
543
544                 return ret;
545
546         } else {
547                 return -1;
548         }
549 }
550
551 int 
552 AudioEngine::connect (const string& source, const string& destination)
553 {
554         if (!_running) {
555                 if (!_has_run) {
556                         fatal << _("connect called before engine was started") << endmsg;
557                         /*NOTREACHED*/
558                 } else {
559                         return -1;
560                 }
561         }
562         
563         string s = make_port_name_non_relative (source);
564         string d = make_port_name_non_relative (destination);
565
566         int ret = jack_connect (_jack, s.c_str(), d.c_str());
567
568         if (ret == 0) {
569                 pair<string,string> c (s, d);
570                 port_connections.push_back (c);
571         } else if (ret == EEXIST) {
572                 error << string_compose(_("AudioEngine: connection already exists: %1 (%2) to %3 (%4)"), 
573                                  source, s, destination, d) 
574                       << endmsg;
575         } else {
576                 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"), 
577                                  source, s, destination, d) 
578                       << endmsg;
579         }
580
581         return ret;
582 }
583
584 int 
585 AudioEngine::disconnect (const string& source, const string& destination)
586 {
587         if (!_running) {
588                 if (!_has_run) {
589                         fatal << _("disconnect called before engine was started") << endmsg;
590                         /*NOTREACHED*/
591                 } else {
592                         return -1;
593                 }
594         }
595         
596         string s = make_port_name_non_relative (source);
597         string d = make_port_name_non_relative (destination);
598
599         int ret = jack_disconnect (_jack, s.c_str(), d.c_str());
600
601         if (ret == 0) {
602                 pair<string,string> c (s, d);
603                 PortConnections::iterator i;
604                 
605                 if ((i = find (port_connections.begin(), port_connections.end(), c)) != port_connections.end()) {
606                         port_connections.erase (i);
607                 }
608         }
609          
610         return ret;
611 }
612
613 int
614 AudioEngine::disconnect (Port *port)
615 {
616         if (!_running) {
617                 if (!_has_run) {
618                         fatal << _("disconnect called before engine was started") << endmsg;
619                         /*NOTREACHED*/
620                 } else {
621                         return -1;
622                 }
623         }
624
625         int ret = jack_port_disconnect (_jack, port->_port);
626
627         if (ret == 0) {
628                 remove_connections_for (port);
629         }
630
631         return ret;
632
633 }
634
635 nframes_t
636 AudioEngine::frame_rate ()
637 {
638         if (_jack) {
639                 if (_frame_rate == 0) {
640                         return (_frame_rate = jack_get_sample_rate (_jack));
641                 } else {
642                         return _frame_rate;
643                 }
644         } else {
645                 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
646                       << endmsg;
647                 /*NOTREACHED*/
648                 return 0;
649         }
650 }
651
652 nframes_t
653 AudioEngine::frames_per_cycle ()
654 {
655         if (_jack) {
656                 if (_buffer_size == 0) {
657                         return (_buffer_size = jack_get_buffer_size (_jack));
658                 } else {
659                         return _buffer_size;
660                 }
661         } else {
662                 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
663                       << endmsg;
664                 /*NOTREACHED*/
665                 return 0;
666         }
667 }
668
669 Port *
670 AudioEngine::get_port_by_name (const string& portname, bool keep)
671 {
672         Glib::Mutex::Lock lm (_process_lock);
673
674         if (!_running) {
675                 if (!_has_run) {
676                         fatal << _("get_port_by_name() called before engine was started") << endmsg;
677                         /*NOTREACHED*/
678                 } else {
679                         return 0;
680                 }
681         }
682         
683         /* check to see if we have a Port for this name already */
684
685         boost::shared_ptr<Ports> pr = ports.reader();
686         
687         for (Ports::iterator i = pr->begin(); i != pr->end(); ++i) {
688                 if (portname == (*i)->name()) {
689                         return (*i);
690                 }
691         }
692
693         jack_port_t *p;
694
695         if ((p = jack_port_by_name (_jack, portname.c_str())) != 0) {
696                 Port *newport = new Port (p);
697
698                 {
699                         if (keep && newport->is_mine (_jack)) {
700                                 RCUWriter<Ports> writer (ports);
701                                 boost::shared_ptr<Ports> ps = writer.get_copy ();
702                                 ps->insert (newport);
703                                 /* writer goes out of scope, forces update */
704                         }
705                 }
706
707                 return newport;
708
709         } else {
710
711                 return 0;
712         }
713 }
714
715 const char **
716 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
717 {
718         if (!_running) {
719                 if (!_has_run) {
720                         fatal << _("get_ports called before engine was started") << endmsg;
721                         /*NOTREACHED*/
722                 } else {
723                         return 0;
724                 }
725         }
726         return jack_get_ports (_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
727 }
728
729 void
730 AudioEngine::halted (void *arg)
731 {
732         AudioEngine* ae = static_cast<AudioEngine *> (arg);
733
734         ae->_running = false;
735         ae->_jack = 0;
736
737         ae->_buffer_size = 0;
738         ae->_frame_rate = 0;
739
740         ae->Halted(); /* EMIT SIGNAL */
741 }
742
743 uint32_t
744 AudioEngine::n_physical_outputs () const
745 {
746         const char ** ports;
747         uint32_t i = 0;
748
749         if (!_jack) {
750                 return 0;
751         }
752
753         if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
754                 return 0;
755         }
756
757         if (ports) {
758                 for (i = 0; ports[i]; ++i);
759                 free (ports);
760         }
761         return i;
762 }
763
764 uint32_t
765 AudioEngine::n_physical_inputs () const
766 {
767         const char ** ports;
768         uint32_t i = 0;
769         
770         if (!_jack) {
771                 return 0;
772         }
773         
774         if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
775                 return 0;
776         }
777
778         if (ports) {
779                 for (i = 0; ports[i]; ++i);
780                 free (ports);
781         }
782         return i;
783 }
784
785 void
786 AudioEngine::get_physical_inputs (vector<string>& ins)
787 {
788         const char ** ports;
789         uint32_t i = 0;
790         
791         if (!_jack) {
792                 return;
793         }
794         
795         if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
796                 return;
797         }
798
799         if (ports) {
800                 for (i = 0; ports[i]; ++i) {
801                         ins.push_back (ports[i]);
802                 }
803                 free (ports);
804         }
805 }
806
807 void
808 AudioEngine::get_physical_outputs (vector<string>& outs)
809 {
810         const char ** ports;
811         uint32_t i = 0;
812         
813         if (!_jack) {
814                 return;
815         }
816         
817         if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
818                 return;
819         }
820
821         if (ports) {
822                 for (i = 0; ports[i]; ++i) {
823                         outs.push_back (ports[i]);
824                 }
825                 free (ports);
826         }
827 }
828
829 string
830 AudioEngine::get_nth_physical (uint32_t n, int flag)
831 {
832         const char ** ports;
833         uint32_t i;
834         string ret;
835
836         if (!_running || !_jack) {
837                 if (!_has_run) {
838                         fatal << _("get_nth_physical called before engine was started") << endmsg;
839                         /*NOTREACHED*/
840                 } else {
841                         return "";
842                 }
843         }
844
845         ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|flag);
846         
847         if (ports == 0) {
848                 return "";
849         }
850
851         for (i = 0; i < n && ports[i]; ++i);
852
853         if (ports[i]) {
854                 ret = ports[i];
855         }
856
857         free ((char *) ports);
858
859         return ret;
860 }
861
862 nframes_t
863 AudioEngine::get_port_total_latency (const Port& port)
864 {
865         if (!_jack) {
866                 fatal << _("get_port_total_latency() called with no JACK client connection") << endmsg;
867                 /*NOTREACHED*/
868         }
869
870         if (!_running) {
871                 if (!_has_run) {
872                         fatal << _("get_port_total_latency() called before engine was started") << endmsg;
873                         /*NOTREACHED*/
874                 } 
875         }
876
877         return jack_port_get_total_latency (_jack, port._port);
878 }
879
880 void
881 AudioEngine::transport_stop ()
882 {
883         // cerr << "tell JACK to stop\n";
884         if (_jack) {
885                 jack_transport_stop (_jack);
886         }
887 }
888
889 void
890 AudioEngine::transport_start ()
891 {
892         // cerr << "tell JACK to start\n";
893         if (_jack) {
894                 jack_transport_start (_jack);
895         }
896 }
897
898 void
899 AudioEngine::transport_locate (nframes_t where)
900 {
901         // cerr << "tell JACK to locate to " << where << endl;
902         if (_jack) {
903                 jack_transport_locate (_jack, where);
904         }
905 }
906
907 AudioEngine::TransportState
908 AudioEngine::transport_state ()
909 {
910         if (_jack) {
911                 jack_position_t pos;
912                 return (TransportState) jack_transport_query (_jack, &pos);
913         } else {
914                 return (TransportState) JackTransportStopped;
915         }
916 }
917
918 int
919 AudioEngine::reset_timebase ()
920 {
921         if (_jack) {
922                 if (Config->get_jack_time_master()) {
923                         return jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
924                 } else {
925                         return jack_release_timebase (_jack);
926                 }
927         } else {
928                 return -1;
929         }
930 }
931
932 int
933 AudioEngine::freewheel (bool onoff)
934 {
935         if (_jack) {
936
937                 if (onoff) {
938                         _freewheel_thread_registered = false;
939                 }
940
941                 return jack_set_freewheel (_jack, onoff);
942
943         } else {
944                 return -1;
945         }
946 }
947
948 void
949 AudioEngine::remove_all_ports ()
950 {
951         /* process lock MUST be held */
952
953         if (_jack) {
954                 boost::shared_ptr<Ports> p = ports.reader();
955
956                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
957                         jack_port_unregister (_jack, (*i)->_port);
958                 }
959         }
960
961         {
962                 RCUWriter<Ports> writer (ports);
963                 boost::shared_ptr<Ports> ps = writer.get_copy ();
964                 ps->clear ();
965         }
966
967         port_connections.clear ();
968 }
969
970 void
971 AudioEngine::remove_connections_for (Port* port)
972 {
973         for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ) {
974                 PortConnections::iterator tmp;
975                 
976                 tmp = i;
977                 ++tmp;
978                 
979                 if ((*i).first == port->name()) {
980                         port_connections.erase (i);
981                 }
982
983                 i = tmp;
984         }
985 }
986
987 #ifdef HAVE_JACK_CLIENT_OPEN
988
989 int
990 AudioEngine::connect_to_jack (string client_name)
991 {
992         jack_options_t options = JackNullOption;
993         jack_status_t status;
994         const char *server_name = NULL;
995
996         jack_client_name = client_name; /* might be reset below */
997
998         _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
999         
1000         if (_jack == NULL) {
1001
1002                 if (status & JackServerFailed) {
1003                         error << _("Unable to connect to JACK server") << endmsg;
1004                 }
1005                 
1006                 error << string_compose (_("Could not connect to JACK server as  \"%1\""), jack_client_name) <<  endmsg;
1007                 return -1;
1008         }
1009
1010         if (status & JackServerStarted) {
1011                 info << _("JACK server started") << endmsg;
1012         }
1013
1014         if (status & JackNameNotUnique) {
1015                 jack_client_name = jack_get_client_name (_jack);
1016         }
1017         
1018         return 0;
1019 }
1020
1021 #else
1022
1023 int
1024 AudioEngine::connect_to_jack (string client_name)
1025 {
1026         jack_client_name = client_name;
1027
1028         if ((_jack = jack_client_new (client_name.c_str())) == NULL) {
1029                 return -1;
1030         }
1031
1032         return 0;
1033 }
1034
1035 #endif /* HAVE_JACK_CLIENT_OPEN */
1036
1037 int 
1038 AudioEngine::disconnect_from_jack ()
1039 {
1040         if (_jack == 0) {
1041                 return 0;
1042         }
1043
1044         if (jack_client_close (_jack)) {
1045                 error << _("cannot shutdown connection to JACK") << endmsg;
1046         }
1047
1048         _buffer_size = 0;
1049         _frame_rate = 0;
1050
1051         if (_running) {
1052                 _running = false;
1053                 Stopped(); /* EMIT SIGNAL */
1054         }
1055
1056         _jack = 0;
1057         return 0;
1058 }
1059
1060 int
1061 AudioEngine::reconnect_to_jack ()
1062 {
1063         if (_jack) {
1064                 disconnect_from_jack ();
1065                 /* XXX give jackd a chance */
1066                 Glib::usleep (250000);
1067         }
1068
1069         if (connect_to_jack (jack_client_name)) {
1070                 error << _("failed to connect to JACK") << endmsg;
1071                 return -1;
1072         }
1073
1074         Ports::iterator i;
1075
1076         boost::shared_ptr<Ports> p = ports.reader ();
1077
1078         for (i = p->begin(); i != p->end(); ++i) {
1079
1080                 /* XXX hack hack hack */
1081
1082                 string long_name = (*i)->name();
1083                 string short_name;
1084                 
1085                 short_name = long_name.substr (long_name.find_last_of (':') + 1);
1086
1087                 if (((*i)->_port = jack_port_register (_jack, short_name.c_str(), (*i)->type(), (*i)->flags(), 0)) == 0) {
1088                         error << string_compose (_("could not reregister %1"), (*i)->name()) << endmsg;
1089                         break;
1090                 } else {
1091                 }
1092
1093                 (*i)->reset ();
1094
1095                 if ((*i)->flags() & JackPortIsOutput) {
1096                         (*i)->silence (jack_get_buffer_size (_jack), 0);
1097                 }
1098         }
1099
1100         if (i != p->end()) {
1101                 /* failed */
1102                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
1103                         jack_port_unregister (_jack, (*i)->_port);
1104                 }
1105                 return -1;
1106         } 
1107
1108
1109         if (session) {
1110                 nframes_t blocksize = jack_get_buffer_size (_jack);
1111                 session->set_block_size (blocksize);
1112                 session->set_frame_rate (jack_get_sample_rate (_jack));
1113         }
1114
1115         last_monitor_check = 0;
1116         
1117         jack_on_shutdown (_jack, halted, this);
1118         jack_set_graph_order_callback (_jack, _graph_order_callback, this);
1119         jack_set_thread_init_callback (_jack, _thread_init_callback, this);
1120         jack_set_process_callback (_jack, _process_callback, this);
1121         jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
1122         jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
1123         jack_set_xrun_callback (_jack, _xrun_callback, this);
1124         jack_set_sync_callback (_jack, _jack_sync_callback, this);
1125         jack_set_freewheel_callback (_jack, _freewheel_callback, this);
1126         
1127         if (Config->get_jack_time_master()) {
1128                 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1129         }
1130         
1131         if (jack_activate (_jack) == 0) {
1132                 _running = true;
1133                 _has_run = true;
1134         } else {
1135                 return -1;
1136         }
1137
1138         /* re-establish connections */
1139         
1140         for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ++i) {
1141                 
1142                 int err;
1143                 
1144                 if ((err = jack_connect (_jack, (*i).first.c_str(), (*i).second.c_str())) != 0) {
1145                         if (err != EEXIST) {
1146                                 error << string_compose (_("could not reconnect %1 and %2 (err = %3)"),
1147                                                   (*i).first, (*i).second, err)
1148                                       << endmsg;
1149                         }
1150                 }
1151         }
1152
1153         Running (); /* EMIT SIGNAL*/
1154
1155         return 0;
1156 }
1157
1158 int
1159 AudioEngine::request_buffer_size (nframes_t nframes)
1160 {
1161         if (_jack) {
1162                 int ret = jack_set_buffer_size (_jack, nframes);
1163                 return ret;
1164         } else {
1165                 return -1;
1166         }
1167 }
1168
1169 void
1170 AudioEngine::update_total_latencies ()
1171 {
1172 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1173         jack_recompute_total_latencies (_jack);
1174 #endif
1175 }
1176                 
1177 string
1178 AudioEngine::make_port_name_relative (string portname)
1179 {
1180         string::size_type len;
1181         string::size_type n;
1182         
1183         len = portname.length();
1184
1185         for (n = 0; n < len; ++n) {
1186                 if (portname[n] == ':') {
1187                         break;
1188                 }
1189         }
1190         
1191         if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1192                 return portname.substr (n+1);
1193         }
1194
1195         return portname;
1196 }
1197
1198 string
1199 AudioEngine::make_port_name_non_relative (string portname)
1200 {
1201         string str;
1202
1203         if (portname.find_first_of (':') != string::npos) {
1204                 return portname;
1205         }
1206
1207         str  = jack_client_name;
1208         str += ':';
1209         str += portname;
1210         
1211         return str;
1212 }
1213