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