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