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