Merged timbyr's win32 branch. -r 547:566.
[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         Glib::Mutex::Lock tm (_process_lock, Glib::TRY_LOCK);
233         jack_nframes_t next_processed_frames;
234
235         /* handle wrap around of total frames counter */
236
237         if (max_frames - _processed_frames < nframes) {
238                 next_processed_frames = nframes - (max_frames - _processed_frames);
239         } else {
240                 next_processed_frames = _processed_frames + nframes;
241         }
242         
243         if (!tm.locked() || session == 0) {
244                 _processed_frames = next_processed_frames;
245                 return 0;
246         }
247
248         if (session_remove_pending) {
249                 session = 0;
250                 session_remove_pending = false;
251                 session_removed.signal();
252                 _processed_frames = next_processed_frames;
253                 return 0;
254         }
255
256         if (_freewheeling) {
257                 if (Freewheel (nframes)) {
258                         _freewheeling = false;
259                         jack_set_freewheel (_jack, false);
260                 }
261                 return 0;
262         }
263
264         session->process (nframes);
265
266         if (!_running) {
267                 /* we were zombified, maybe because a ladspa plugin took
268                    too long, or jackd exited, or something like that.
269                 */
270                 
271                 _processed_frames = next_processed_frames;
272                 return 0;
273         }
274
275         if (last_monitor_check + monitor_check_interval < next_processed_frames) {
276                 for (Ports::iterator i = ports.begin(); i != ports.end(); ++i) {
277                         
278                         Port *port = (*i);
279                         bool x;
280                         
281                         if (port->last_monitor != (x = port->monitoring_input ())) {
282                                 port->last_monitor = x;
283                                 /* XXX I think this is dangerous, due to 
284                                    a likely mutex in the signal handlers ...
285                                 */
286                                  port->MonitorInputChanged (x); /* EMIT SIGNAL */
287                         }
288                 }
289                 last_monitor_check = next_processed_frames;
290         }
291
292         _processed_frames = next_processed_frames;
293         return 0;
294 }
295
296 int
297 AudioEngine::_sample_rate_callback (jack_nframes_t nframes, void *arg)
298 {
299         return static_cast<AudioEngine *> (arg)->jack_sample_rate_callback (nframes);
300 }
301
302 int
303 AudioEngine::jack_sample_rate_callback (jack_nframes_t nframes)
304 {
305         _frame_rate = nframes;
306         _usecs_per_cycle = (int) floor ((((double) frames_per_cycle() / nframes)) * 1000000.0);
307         
308         /* check for monitor input change every 1/10th of second */
309
310         monitor_check_interval = nframes / 10;
311         last_monitor_check = 0;
312         
313         if (session) {
314                 session->set_frame_rate (nframes);
315         }
316
317         SampleRateChanged (nframes); /* EMIT SIGNAL */
318
319         return 0;
320 }
321
322 int
323 AudioEngine::_bufsize_callback (jack_nframes_t nframes, void *arg)
324 {
325         return static_cast<AudioEngine *> (arg)->jack_bufsize_callback (nframes);
326 }
327
328 int
329 AudioEngine::jack_bufsize_callback (jack_nframes_t nframes)
330 {
331         _buffer_size = nframes;
332         _usecs_per_cycle = (int) floor ((((double) nframes / frame_rate())) * 1000000.0);
333         last_monitor_check = 0;
334
335         for (Ports::iterator i = ports.begin(); i != ports.end(); ++i) {
336                 (*i)->reset();
337         }
338
339         if (session) {
340                 session->set_block_size (_buffer_size);
341         }
342
343         return 0;
344 }
345
346 void
347 AudioEngine::start_metering_thread ()
348 {
349     if(m_meter_thread == 0) {
350         m_meter_thread = Glib::Thread::create (sigc::mem_fun(this, &AudioEngine::meter_thread), false);
351     }
352 }
353
354 void
355 AudioEngine::meter_thread ()
356 {
357         while (g_atomic_int_get(&m_meter_exit) != true) {
358         Glib::usleep (10000); /* 1/100th sec interval */
359         IO::update_meters ();
360         }
361         return;
362 }
363
364 void 
365 AudioEngine::set_session (Session *s)
366 {
367         if (!session) {
368                 session = s;
369         }
370 }
371
372 void 
373 AudioEngine::remove_session ()
374 {
375         Glib::Mutex::Lock lm (_process_lock);
376
377         if (_running) {
378
379                 if (session) {
380                         session_remove_pending = true;
381                         session_removed.wait(_process_lock);
382                 } 
383
384         } else {
385
386                 session = 0;
387
388         }
389         
390         remove_all_ports ();
391
392 }
393
394 Port *
395 AudioEngine::register_audio_input_port (const string& portname)
396 {
397         if (!_running) {
398                 if (!_has_run) {
399                         fatal << _("register audio input port called before engine was started") << endmsg;
400                         /*NOTREACHED*/
401                 } else {
402                         return 0;
403                 }
404         }
405
406         jack_port_t *p = jack_port_register (_jack, portname.c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
407
408         if (p) {
409
410                 Port *newport;
411                 if ((newport = new Port (p)) != 0) {
412                         ports.insert (ports.begin(), newport);
413                 }
414                 return newport;
415
416         } else {
417
418                 _process_lock.unlock();
419                 throw PortRegistrationFailure();
420         }
421
422         return 0;
423 }
424
425 Port *
426 AudioEngine::register_audio_output_port (const string& portname)
427 {
428         if (!_running) {
429                 if (!_has_run) {
430                         fatal << _("register audio output port called before engine was started") << endmsg;
431                         /*NOTREACHED*/
432                 } else {
433                         return 0;
434                 }
435         }
436
437         jack_port_t *p;
438
439         if ((p = jack_port_register (_jack, portname.c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0)) != 0) {
440                 Port *newport = new Port (p);
441                 ports.insert (ports.begin(), newport);
442                 return newport;
443
444         } else {
445
446                 _process_lock.unlock();
447                 throw PortRegistrationFailure ();
448         }
449
450         return 0;
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
707 AudioEngine::get_nth_physical (uint32_t n, int flag)
708 {
709         const char ** ports;
710         uint32_t i;
711         string ret;
712
713         if (!_running || !_jack) {
714                 if (!_has_run) {
715                         fatal << _("get_nth_physical called before engine was started") << endmsg;
716                         /*NOTREACHED*/
717                 } else {
718                         return "";
719                 }
720         }
721
722         ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|flag);
723         
724         if (ports == 0) {
725                 return "";
726         }
727
728         for (i = 0; i < n && ports[i]; ++i);
729
730         if (ports[i]) {
731                 ret = ports[i];
732         }
733
734         free ((char *) ports);
735
736         return ret;
737 }
738
739 jack_nframes_t
740 AudioEngine::get_port_total_latency (const Port& port)
741 {
742         if (!_jack) {
743                 fatal << _("get_port_total_latency() called with no JACK client connection") << endmsg;
744                 /*NOTREACHED*/
745         }
746
747         if (!_running) {
748                 if (!_has_run) {
749                         fatal << _("get_port_total_latency() called before engine was started") << endmsg;
750                         /*NOTREACHED*/
751                 } 
752         }
753
754         return jack_port_get_total_latency (_jack, port.port);
755 }
756
757 void
758 AudioEngine::transport_stop ()
759 {
760         // cerr << "tell JACK to stop\n";
761         if (_jack) {
762                 jack_transport_stop (_jack);
763         }
764 }
765
766 void
767 AudioEngine::transport_start ()
768 {
769         // cerr << "tell JACK to start\n";
770         if (_jack) {
771                 jack_transport_start (_jack);
772         }
773 }
774
775 void
776 AudioEngine::transport_locate (jack_nframes_t where)
777 {
778         // cerr << "tell JACK to locate to " << where << endl;
779         if (_jack) {
780                 jack_transport_locate (_jack, where);
781         }
782 }
783
784 AudioEngine::TransportState
785 AudioEngine::transport_state ()
786 {
787         if (_jack) {
788                 jack_position_t pos;
789                 return (TransportState) jack_transport_query (_jack, &pos);
790         } else {
791                 return (TransportState) JackTransportStopped;
792         }
793 }
794
795 int
796 AudioEngine::reset_timebase ()
797 {
798         if (_jack) {
799                 if (Config->get_jack_time_master()) {
800                         return jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
801                 } else {
802                         return jack_release_timebase (_jack);
803                 }
804         } else {
805                 return -1;
806         }
807 }
808
809 int
810 AudioEngine::freewheel (bool onoff)
811 {
812         if (_jack) {
813
814                 if (onoff) {
815                         _freewheel_thread_registered = false;
816                 }
817
818                 return jack_set_freewheel (_jack, onoff);
819
820         } else {
821                 return -1;
822         }
823 }
824
825 void
826 AudioEngine::remove_all_ports ()
827 {
828         /* process lock MUST be held */
829
830         if (_jack) {
831                 for (Ports::iterator i = ports.begin(); i != ports.end(); ++i) {
832                         jack_port_unregister (_jack, (*i)->port);
833                 }
834         }
835
836         ports.clear ();
837         port_connections.clear ();
838 }
839
840 void
841 AudioEngine::remove_connections_for (Port* port)
842 {
843         for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ) {
844                 PortConnections::iterator tmp;
845                 
846                 tmp = i;
847                 ++tmp;
848                 
849                 if ((*i).first == port->name()) {
850                         port_connections.erase (i);
851                 }
852
853                 i = tmp;
854         }
855 }
856
857 #ifdef HAVE_JACK_CLIENT_OPEN
858
859 int
860 AudioEngine::connect_to_jack (string client_name)
861 {
862         jack_options_t options = JackNullOption;
863         jack_status_t status;
864         const char *server_name = NULL;
865
866         jack_client_name = client_name; /* might be reset below */
867
868         _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
869         
870         if (_jack == NULL) {
871
872                 if (status & JackServerFailed) {
873                         error << _("Unable to connect to JACK server") << endmsg;
874                 }
875                 
876                 error << string_compose (_("Could not connect to JACK server as  \"%1\""), jack_client_name) <<  endmsg;
877                 return -1;
878         }
879
880         if (status & JackServerStarted) {
881                 info << _("JACK server started") << endmsg;
882         }
883
884         if (status & JackNameNotUnique) {
885                 jack_client_name = jack_get_client_name (_jack);
886         }
887         
888         return 0;
889 }
890
891 #else
892
893 int
894 AudioEngine::connect_to_jack (string client_name)
895 {
896         jack_client_name = client_name;
897
898         if ((_jack = jack_client_new (client_name.c_str())) == NULL) {
899                 return -1;
900         }
901
902         return 0;
903 }
904
905 #endif /* HAVE_JACK_CLIENT_OPEN */
906
907 int 
908 AudioEngine::disconnect_from_jack ()
909 {
910         if (_jack == 0) {
911                 return 0;
912         }
913
914         if (jack_client_close (_jack)) {
915                 error << _("cannot shutdown connection to JACK") << endmsg;
916         }
917
918         _buffer_size = 0;
919         _frame_rate = 0;
920
921         if (_running) {
922                 _running = false;
923                 Stopped(); /* EMIT SIGNAL */
924         }
925
926         _jack = 0;
927         return 0;
928 }
929
930 int
931 AudioEngine::reconnect_to_jack ()
932 {
933         if (_jack) {
934                 disconnect_from_jack ();
935                 /* XXX give jackd a chance */
936         Glib::usleep (250000);
937         }
938
939         if (connect_to_jack (jack_client_name)) {
940                 error << _("failed to connect to JACK") << endmsg;
941                 return -1;
942         }
943
944         Ports::iterator i;
945
946         for (i = ports.begin(); i != ports.end(); ++i) {
947
948                 /* XXX hack hack hack */
949
950                 string long_name = (*i)->name();
951                 string short_name;
952                 
953                 short_name = long_name.substr (long_name.find_last_of (':') + 1);
954
955                 if (((*i)->port = jack_port_register (_jack, short_name.c_str(), (*i)->type(), (*i)->flags(), 0)) == 0) {
956                         error << string_compose (_("could not reregister %1"), (*i)->name()) << endmsg;
957                         break;
958                 } else {
959                 }
960
961                 (*i)->reset ();
962
963                 if ((*i)->flags() & JackPortIsOutput) {
964                         (*i)->silence (jack_get_buffer_size (_jack), 0);
965                 }
966         }
967
968         if (i != ports.end()) {
969                 for (Ports::iterator i = ports.begin(); i != ports.end(); ++i) {
970                         jack_port_unregister (_jack, (*i)->port);
971                 }
972                 return -1;
973         } 
974
975
976         if (session) {
977                 jack_nframes_t blocksize = jack_get_buffer_size (_jack);
978                 session->set_block_size (blocksize);
979                 session->set_frame_rate (jack_get_sample_rate (_jack));
980         }
981
982         last_monitor_check = 0;
983         
984         jack_on_shutdown (_jack, halted, this);
985         jack_set_graph_order_callback (_jack, _graph_order_callback, this);
986         jack_set_thread_init_callback (_jack, _thread_init_callback, this);
987         jack_set_process_callback (_jack, _process_callback, this);
988         jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
989         jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
990         jack_set_xrun_callback (_jack, _xrun_callback, this);
991         jack_set_sync_callback (_jack, _jack_sync_callback, this);
992         jack_set_freewheel_callback (_jack, _freewheel_callback, this);
993         
994         if (Config->get_jack_time_master()) {
995                 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
996         }
997         
998         if (jack_activate (_jack) == 0) {
999                 _running = true;
1000                 _has_run = true;
1001         } else {
1002                 return -1;
1003         }
1004
1005         /* re-establish connections */
1006         
1007         for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ++i) {
1008                 
1009                 int err;
1010                 
1011                 if ((err = jack_connect (_jack, (*i).first.c_str(), (*i).second.c_str())) != 0) {
1012                         if (err != EEXIST) {
1013                                 error << string_compose (_("could not reconnect %1 and %2 (err = %3)"),
1014                                                   (*i).first, (*i).second, err)
1015                                       << endmsg;
1016                         }
1017                 }
1018         }
1019
1020         Running (); /* EMIT SIGNAL*/
1021
1022         return 0;
1023 }
1024
1025 int
1026 AudioEngine::request_buffer_size (jack_nframes_t nframes)
1027 {
1028         if (_jack) {
1029                 int ret = jack_set_buffer_size (_jack, nframes);
1030                 return ret;
1031         } else {
1032                 return -1;
1033         }
1034 }
1035
1036 void
1037 AudioEngine::update_total_latencies ()
1038 {
1039 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1040         jack_recompute_total_latencies (_jack);
1041 #endif
1042 }
1043                 
1044 string
1045 AudioEngine::make_port_name_relative (string portname)
1046 {
1047         string::size_type len;
1048         string::size_type n;
1049         
1050         len = portname.length();
1051
1052         for (n = 0; n < len; ++n) {
1053                 if (portname[n] == ':') {
1054                         break;
1055                 }
1056         }
1057         
1058         if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1059                 return portname.substr (n+1);
1060         }
1061
1062         return portname;
1063 }
1064
1065 string
1066 AudioEngine::make_port_name_non_relative (string portname)
1067 {
1068         string str;
1069
1070         if (portname.find_first_of (':') != string::npos) {
1071                 return portname;
1072         }
1073
1074         str  = jack_client_name;
1075         str += ':';
1076         str += portname;
1077         
1078         return str;
1079 }
1080