"Run plugins while recording" -> "Do not run plugins while recording"
[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                 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