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