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