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