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