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