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