a putatively better approach to cleaning up ports at session closing
[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
29 #include "pbd/pthread_utils.h"
30 #include "pbd/stacktrace.h"
31 #include "pbd/unknown_type.h"
32 #include "pbd/epa.h"
33
34 #include <jack/weakjack.h>
35
36 #include "midi++/port.h"
37 #include "midi++/jack_midi_port.h"
38 #include "midi++/mmc.h"
39 #include "midi++/manager.h"
40
41 #include "ardour/audio_port.h"
42 #include "ardour/audioengine.h"
43 #include "ardour/buffer.h"
44 #include "ardour/cycle_timer.h"
45 #include "ardour/internal_send.h"
46 #include "ardour/meter.h"
47 #include "ardour/midi_port.h"
48 #include "ardour/port.h"
49 #include "ardour/process_thread.h"
50 #include "ardour/session.h"
51
52 #include "i18n.h"
53
54 using namespace std;
55 using namespace ARDOUR;
56 using namespace PBD;
57
58 gint AudioEngine::m_meter_exit;
59 AudioEngine* AudioEngine::_instance = 0;
60
61 #define GET_PRIVATE_JACK_POINTER(j)  jack_client_t* _priv_jack = (jack_client_t*) (j); if (!_priv_jack) { return; }
62 #define GET_PRIVATE_JACK_POINTER_RET(j,r) jack_client_t* _priv_jack = (jack_client_t*) (j); if (!_priv_jack) { return r; }
63
64 AudioEngine::AudioEngine (string client_name, string session_uuid)
65         : ports (new Ports)
66 {
67         _instance = this; /* singleton */
68
69         session_remove_pending = false;
70         _running = false;
71         _has_run = false;
72         last_monitor_check = 0;
73         monitor_check_interval = INT32_MAX;
74         _processed_frames = 0;
75         _usecs_per_cycle = 0;
76         _jack = 0;
77         _frame_rate = 0;
78         _buffer_size = 0;
79         _freewheeling = false;
80         _pre_freewheel_mmc_enabled = false;
81         _main_thread = 0;
82         port_remove_in_progress = false;
83
84         m_meter_thread = 0;
85         g_atomic_int_set (&m_meter_exit, 0);
86
87         if (connect_to_jack (client_name, session_uuid)) {
88                 throw NoBackendAvailable ();
89         }
90
91         Port::set_engine (this);
92 }
93
94 AudioEngine::~AudioEngine ()
95 {
96         {
97                 Glib::Mutex::Lock tm (_process_lock);
98                 session_removed.signal ();
99
100                 if (_running) {
101                         jack_client_close (_jack);
102                         _jack = 0;
103                 }
104
105                 stop_metering_thread ();
106         }
107 }
108
109 jack_client_t*
110 AudioEngine::jack() const
111 {
112         return _jack;
113 }
114
115 void
116 _thread_init_callback (void * /*arg*/)
117 {
118         /* make sure that anybody who needs to know about this thread
119            knows about it.
120         */
121
122         pthread_set_name (X_("audioengine"));
123
124         PBD::notify_gui_about_thread_creation ("gui", pthread_self(), X_("Audioengine"), 4096);
125         PBD::notify_gui_about_thread_creation ("midiui", pthread_self(), X_("Audioengine"), 128);
126
127         SessionEvent::create_per_thread_pool (X_("Audioengine"), 512);
128
129         MIDI::JackMIDIPort::set_process_thread (pthread_self());
130 }
131
132 static void
133 ardour_jack_error (const char* msg)
134 {
135         error << "JACK: " << msg << endmsg;
136 }
137
138 void
139 AudioEngine::set_jack_callbacks ()
140 {
141         GET_PRIVATE_JACK_POINTER (_jack);
142
143         if (jack_on_info_shutdown) {
144                 jack_on_info_shutdown (_priv_jack, halted_info, this);
145         } else {
146                 jack_on_shutdown (_priv_jack, halted, this);
147         }
148
149         jack_set_thread_init_callback (_priv_jack, _thread_init_callback, this);
150         jack_set_process_thread (_priv_jack, _process_thread, this);
151         jack_set_sample_rate_callback (_priv_jack, _sample_rate_callback, this);
152         jack_set_buffer_size_callback (_priv_jack, _bufsize_callback, this);
153         jack_set_graph_order_callback (_priv_jack, _graph_order_callback, this);
154         jack_set_port_registration_callback (_priv_jack, _registration_callback, this);
155         jack_set_port_connect_callback (_priv_jack, _connect_callback, this);
156         jack_set_xrun_callback (_priv_jack, _xrun_callback, this);
157         jack_set_sync_callback (_priv_jack, _jack_sync_callback, this);
158         jack_set_freewheel_callback (_priv_jack, _freewheel_callback, this);
159
160         if (_session && _session->config.get_jack_time_master()) {
161                 jack_set_timebase_callback (_priv_jack, 0, _jack_timebase_callback, this);
162         }
163
164 #ifdef HAVE_JACK_SESSION
165         if( jack_set_session_callback)
166                 jack_set_session_callback (_priv_jack, _session_callback, this);
167 #endif
168
169         if (jack_set_latency_callback) {
170                 jack_set_latency_callback (_priv_jack, _latency_callback, this);
171         }
172
173         jack_set_error_function (ardour_jack_error);
174 }
175
176 int
177 AudioEngine::start ()
178 {
179         GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
180
181         if (!_running) {
182
183                 if (!jack_port_type_get_buffer_size) {
184                         warning << _("This version of JACK is old - you should upgrade to a newer version that supports jack_port_type_get_buffer_size()") << endmsg;
185                 }
186
187                 if (_session) {
188                         BootMessage (_("Connect session to engine"));
189                         _session->set_frame_rate (jack_get_sample_rate (_priv_jack));
190                 }
191
192                 /* a proxy for whether jack_activate() will definitely call the buffer size
193                  * callback. with older versions of JACK, this function symbol will be null.
194                  * this is reliable, but not clean.
195                  */
196
197                 if (!jack_port_type_get_buffer_size) {
198                         jack_bufsize_callback (jack_get_buffer_size (_priv_jack));
199                 }
200                 
201                 _processed_frames = 0;
202                 last_monitor_check = 0;
203
204                 set_jack_callbacks ();
205
206                 if (jack_activate (_priv_jack) == 0) {
207                         _running = true;
208                         _has_run = true;
209                         Running(); /* EMIT SIGNAL */
210                 } else {
211                         // error << _("cannot activate JACK client") << endmsg;
212                 }
213         }
214                 
215         return _running ? 0 : -1;
216 }
217
218 int
219 AudioEngine::stop (bool forever)
220 {
221         GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
222
223         if (_priv_jack) {
224                 if (forever) {
225                         disconnect_from_jack ();
226                 } else {
227                         jack_deactivate (_priv_jack);
228                         Stopped(); /* EMIT SIGNAL */
229                         MIDI::JackMIDIPort::JackHalted (); /* EMIT SIGNAL */
230                 }
231         }
232
233         if (forever) {
234                 stop_metering_thread ();
235         }
236
237         return _running ? -1 : 0;
238 }
239
240
241 bool
242 AudioEngine::get_sync_offset (pframes_t& offset) const
243 {
244
245 #ifdef HAVE_JACK_VIDEO_SUPPORT
246
247         GET_PRIVATE_JACK_POINTER_RET (_jack, false);
248
249         jack_position_t pos;
250
251         if (_priv_jack) {
252                 (void) jack_transport_query (_priv_jack, &pos);
253
254                 if (pos.valid & JackVideoFrameOffset) {
255                         offset = pos.video_offset;
256                         return true;
257                 }
258         }
259 #else
260         /* keep gcc happy */
261         offset = 0;
262 #endif
263
264         return false;
265 }
266
267 void
268 AudioEngine::_jack_timebase_callback (jack_transport_state_t state, pframes_t nframes,
269                                       jack_position_t* pos, int new_position, void *arg)
270 {
271         static_cast<AudioEngine*> (arg)->jack_timebase_callback (state, nframes, pos, new_position);
272 }
273
274 void
275 AudioEngine::jack_timebase_callback (jack_transport_state_t state, pframes_t nframes,
276                                      jack_position_t* pos, int new_position)
277 {
278         if (_jack && _session && _session->synced_to_jack()) {
279                 _session->jack_timebase_callback (state, nframes, pos, new_position);
280         }
281 }
282
283 int
284 AudioEngine::_jack_sync_callback (jack_transport_state_t state, jack_position_t* pos, void* arg)
285 {
286         return static_cast<AudioEngine*> (arg)->jack_sync_callback (state, pos);
287 }
288
289 int
290 AudioEngine::jack_sync_callback (jack_transport_state_t state, jack_position_t* pos)
291 {
292         if (_jack && _session) {
293                 return _session->jack_sync_callback (state, pos);
294         }
295
296         return true;
297 }
298
299 int
300 AudioEngine::_xrun_callback (void *arg)
301 {
302         AudioEngine* ae = static_cast<AudioEngine*> (arg);
303         if (ae->connected()) {
304                 ae->Xrun (); /* EMIT SIGNAL */
305         }
306         return 0;
307 }
308
309 #ifdef HAVE_JACK_SESSION
310 void
311 AudioEngine::_session_callback (jack_session_event_t *event, void *arg)
312 {
313         AudioEngine* ae = static_cast<AudioEngine*> (arg);
314         if (ae->connected()) {
315                 ae->JackSessionEvent ( event ); /* EMIT SIGNAL */
316         }
317 }
318 #endif
319
320 int
321 AudioEngine::_graph_order_callback (void *arg)
322 {
323         AudioEngine* ae = static_cast<AudioEngine*> (arg);
324
325         if (ae->connected() && !ae->port_remove_in_progress) {
326                 ae->GraphReordered (); /* EMIT SIGNAL */
327         }
328         
329         return 0;
330 }
331
332 void*
333 AudioEngine::_process_thread (void *arg)
334 {
335         return static_cast<AudioEngine *> (arg)->process_thread ();
336 }
337
338 void
339 AudioEngine::_freewheel_callback (int onoff, void *arg)
340 {
341         static_cast<AudioEngine*>(arg)->freewheel_callback (onoff);
342 }
343
344 void
345 AudioEngine::freewheel_callback (int onoff)
346 {
347         _freewheeling = onoff;
348
349         if (onoff) {
350                 _pre_freewheel_mmc_enabled = MIDI::Manager::instance()->mmc()->send_enabled ();
351                 MIDI::Manager::instance()->mmc()->enable_send (false);
352         } else {
353                 MIDI::Manager::instance()->mmc()->enable_send (_pre_freewheel_mmc_enabled);
354         }
355 }
356
357 void
358 AudioEngine::_registration_callback (jack_port_id_t /*id*/, int /*reg*/, void* arg)
359 {
360         AudioEngine* ae = static_cast<AudioEngine*> (arg);
361
362         if (!ae->port_remove_in_progress) {
363                 ae->PortRegisteredOrUnregistered (); /* EMIT SIGNAL */
364         }
365 }
366
367 void
368 AudioEngine::_latency_callback (jack_latency_callback_mode_t mode, void* arg)
369 {
370         return static_cast<AudioEngine *> (arg)->jack_latency_callback (mode);
371 }
372
373 void
374 AudioEngine::_connect_callback (jack_port_id_t id_a, jack_port_id_t id_b, int conn, void* arg)
375 {
376         AudioEngine* ae = static_cast<AudioEngine*> (arg);
377
378         if (ae->port_remove_in_progress) {
379                 return;
380         }
381
382         GET_PRIVATE_JACK_POINTER (ae->_jack);
383
384         jack_port_t* jack_port_a = jack_port_by_id (_priv_jack, id_a);
385         jack_port_t* jack_port_b = jack_port_by_id (_priv_jack, id_b);
386
387         boost::shared_ptr<Port> port_a;
388         boost::shared_ptr<Port> port_b;
389
390         boost::shared_ptr<Ports> pr = ae->ports.reader ();
391         Ports::iterator i = pr->begin ();
392         while (i != pr->end() && (port_a == 0 || port_b == 0)) {
393                 if (jack_port_a == i->second->jack_port()) {
394                         port_a = i->second;
395                 } else if (jack_port_b == i->second->jack_port()) {
396                         port_b = i->second;
397                 }
398                 ++i;
399         }
400
401         ae->PortConnectedOrDisconnected (
402                 port_a, jack_port_name (jack_port_a),
403                 port_b, jack_port_name (jack_port_b),
404                 conn == 0 ? false : true
405                 ); /* EMIT SIGNAL */
406 }
407
408 void
409 AudioEngine::split_cycle (pframes_t offset)
410 {
411         /* caller must hold process lock */
412
413         Port::increment_global_port_buffer_offset (offset);
414
415         /* tell all Ports that we're going to start a new (split) cycle */
416
417         boost::shared_ptr<Ports> p = ports.reader();
418
419         for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
420                 i->second->cycle_split ();
421         }
422 }
423
424 void*
425 AudioEngine::process_thread ()
426 {
427         /* JACK doesn't do this for us when we use the wait API
428          */
429
430         _thread_init_callback (0);
431
432         _main_thread = new ProcessThread;
433
434         while (1) {
435                 GET_PRIVATE_JACK_POINTER_RET(_jack,0);
436
437                 pframes_t nframes = jack_cycle_wait (_priv_jack);
438
439                 if (process_callback (nframes)) {
440                         return 0;
441                 }
442
443                 jack_cycle_signal (_priv_jack, 0);
444         }
445
446         return 0;
447 }
448
449 /** Method called by our ::process_thread when there is work to be done.
450  *  @param nframes Number of frames to process.
451  */
452 int
453 AudioEngine::process_callback (pframes_t nframes)
454 {
455         GET_PRIVATE_JACK_POINTER_RET(_jack,0);
456         Glib::Mutex::Lock tm (_process_lock, Glib::TRY_LOCK);
457
458         PT_TIMING_REF;
459         PT_TIMING_CHECK (1);
460
461         /// The number of frames that will have been processed when we've finished
462         pframes_t next_processed_frames;
463
464         /* handle wrap around of total frames counter */
465
466         if (max_framepos - _processed_frames < nframes) {
467                 next_processed_frames = nframes - (max_framepos - _processed_frames);
468         } else {
469                 next_processed_frames = _processed_frames + nframes;
470         }
471
472         if (!tm.locked()) {
473                 /* return having done nothing */
474                 _processed_frames = next_processed_frames;
475                 return 0;
476         }
477
478         if (session_remove_pending) {
479                 /* perform the actual session removal */
480                 _session = 0;
481                 session_remove_pending = false;
482
483                 /* pump one cycle of silence into the ports
484                    before the session tears them all down
485                    (asynchronously).
486                 */
487
488                 boost::shared_ptr<Ports> p = ports.reader();
489                 
490                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
491                         
492                         if (i->second->sends_output()) {
493                                 i->second->get_buffer (nframes).silence (nframes);
494                         }
495                 }
496
497                 session_removed.signal();
498         }
499
500         if (_session == 0) {
501                 if (!_freewheeling) {
502                         MIDI::Manager::instance()->cycle_start(nframes);
503                         MIDI::Manager::instance()->cycle_end();
504                 }
505
506                 _processed_frames = next_processed_frames;
507
508                 return 0;
509         }
510
511         /* tell all relevant objects that we're starting a new cycle */
512
513         InternalSend::CycleStart (nframes);
514         Port::set_global_port_buffer_offset (0);
515         Port::set_cycle_framecnt (nframes);
516
517         /* tell all Ports that we're starting a new cycle */
518
519         boost::shared_ptr<Ports> p = ports.reader();
520
521         for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
522                 i->second->cycle_start (nframes);
523         }
524
525         /* test if we are freewheeling and there are freewheel signals connected.
526            ardour should act normally even when freewheeling unless /it/ is exporting */
527
528
529         if (_freewheeling && !Freewheel.empty()) {
530                 /* emit the Freewheel signal and stop freewheeling in the event of trouble
531                  */
532                 boost::optional<int> r = Freewheel (nframes);
533                 if (r.get_value_or (0)) {
534                         jack_set_freewheel (_priv_jack, false);
535                 }
536
537         } else {
538                 MIDI::Manager::instance()->cycle_start(nframes);
539
540                 if (_session) {
541                         _session->process (nframes);
542                 }
543
544                 MIDI::Manager::instance()->cycle_end();
545         }
546
547         if (_freewheeling) {
548                 return 0;
549         }
550
551         if (!_running) {
552                 _processed_frames = next_processed_frames;
553                 return 0;
554         }
555
556         if (last_monitor_check + monitor_check_interval < next_processed_frames) {
557
558                 boost::shared_ptr<Ports> p = ports.reader();
559
560                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
561
562                         bool x;
563
564                         if (i->second->last_monitor() != (x = i->second->jack_monitoring_input ())) {
565                                 i->second->set_last_monitor (x);
566                                 /* XXX I think this is dangerous, due to
567                                    a likely mutex in the signal handlers ...
568                                 */
569                                 i->second->MonitorInputChanged (x); /* EMIT SIGNAL */
570                         }
571                 }
572                 last_monitor_check = next_processed_frames;
573         }
574
575         if (_session->silent()) {
576
577                 boost::shared_ptr<Ports> p = ports.reader();
578
579                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
580
581                         if (i->second->sends_output()) {
582                                 i->second->get_buffer(nframes).silence(nframes);
583                         }
584                 }
585         }
586
587         // Finalize ports
588
589         for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
590                 i->second->cycle_end (nframes);
591         }
592
593         _processed_frames = next_processed_frames;
594
595         PT_TIMING_CHECK (2);
596         
597         return 0;
598 }
599
600 int
601 AudioEngine::_sample_rate_callback (pframes_t nframes, void *arg)
602 {
603         return static_cast<AudioEngine *> (arg)->jack_sample_rate_callback (nframes);
604 }
605
606 int
607 AudioEngine::jack_sample_rate_callback (pframes_t nframes)
608 {
609         _frame_rate = nframes;
610         _usecs_per_cycle = (int) floor ((((double) frames_per_cycle() / nframes)) * 1000000.0);
611
612         /* check for monitor input change every 1/10th of second */
613
614         monitor_check_interval = nframes / 10;
615         last_monitor_check = 0;
616
617         if (_session) {
618                 _session->set_frame_rate (nframes);
619         }
620
621         SampleRateChanged (nframes); /* EMIT SIGNAL */
622
623         return 0;
624 }
625
626 void
627 AudioEngine::jack_latency_callback (jack_latency_callback_mode_t mode)
628 {
629         if (_session) {
630                 _session->update_latency (mode == JackPlaybackLatency);
631         }
632 }
633
634 int
635 AudioEngine::_bufsize_callback (pframes_t nframes, void *arg)
636 {
637         return static_cast<AudioEngine *> (arg)->jack_bufsize_callback (nframes);
638 }
639
640 int
641 AudioEngine::jack_bufsize_callback (pframes_t nframes)
642 {
643         /* if the size has not changed, this should be a no-op */
644
645         if (nframes == _buffer_size) {
646                 return 0;
647         }
648
649         GET_PRIVATE_JACK_POINTER_RET (_jack, 1);
650
651         _buffer_size = nframes;
652         _usecs_per_cycle = (int) floor ((((double) nframes / frame_rate())) * 1000000.0);
653         last_monitor_check = 0;
654
655         if (jack_port_type_get_buffer_size) {
656                 _raw_buffer_sizes[DataType::AUDIO] = jack_port_type_get_buffer_size (_priv_jack, JACK_DEFAULT_AUDIO_TYPE);
657                 _raw_buffer_sizes[DataType::MIDI] = jack_port_type_get_buffer_size (_priv_jack, JACK_DEFAULT_MIDI_TYPE);
658         } else {
659
660                 /* Old version of JACK.
661
662                    These crude guesses, see below where we try to get the right answers.
663
664                    Note that our guess for MIDI deliberatey tries to overestimate
665                    by a little. It would be nicer if we could get the actual
666                    size from a port, but we have to use this estimate in the
667                    event that there are no MIDI ports currently. If there are
668                    the value will be adjusted below.
669                 */
670
671                 _raw_buffer_sizes[DataType::AUDIO] = nframes * sizeof (Sample);
672                 _raw_buffer_sizes[DataType::MIDI] = nframes * 4 - (nframes/2);
673         }
674
675         {
676                 Glib::Mutex::Lock lm (_process_lock);
677
678                 boost::shared_ptr<Ports> p = ports.reader();
679
680                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
681                         i->second->reset();
682                 }
683         }
684
685         if (_session) {
686                 _session->set_block_size (_buffer_size);
687         }
688
689         return 0;
690 }
691
692 void
693 AudioEngine::stop_metering_thread ()
694 {
695         if (m_meter_thread) {
696                 g_atomic_int_set (&m_meter_exit, 1);
697                 m_meter_thread->join ();
698                 m_meter_thread = 0;
699         }
700 }
701
702 void
703 AudioEngine::start_metering_thread ()
704 {
705         if (m_meter_thread == 0) {
706                 g_atomic_int_set (&m_meter_exit, 0);
707                 m_meter_thread = Glib::Thread::create (boost::bind (&AudioEngine::meter_thread, this),
708                                                        500000, true, true, Glib::THREAD_PRIORITY_NORMAL);
709         }
710 }
711
712 void
713 AudioEngine::meter_thread ()
714 {
715         pthread_set_name (X_("meter"));
716
717         while (true) {
718                 Glib::usleep (10000); /* 1/100th sec interval */
719                 if (g_atomic_int_get(&m_meter_exit)) {
720                         break;
721                 }
722                 Metering::Meter ();
723         }
724 }
725
726 void
727 AudioEngine::set_session (Session *s)
728 {
729         Glib::Mutex::Lock pl (_process_lock);
730
731         SessionHandlePtr::set_session (s);
732
733         if (_session) {
734
735                 start_metering_thread ();
736
737                 pframes_t blocksize = jack_get_buffer_size (_jack);
738
739                 /* page in as much of the session process code as we
740                    can before we really start running.
741                 */
742
743                 boost::shared_ptr<Ports> p = ports.reader();
744
745                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
746                         i->second->cycle_start (blocksize);
747                 }
748
749                 _session->process (blocksize);
750                 _session->process (blocksize);
751                 _session->process (blocksize);
752                 _session->process (blocksize);
753                 _session->process (blocksize);
754                 _session->process (blocksize);
755                 _session->process (blocksize);
756                 _session->process (blocksize);
757
758                 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
759                         i->second->cycle_end (blocksize);
760                 }
761         }
762 }
763
764 void
765 AudioEngine::remove_session ()
766 {
767         Glib::Mutex::Lock lm (_process_lock);
768
769         if (_running) {
770
771                 stop_metering_thread ();
772
773                 if (_session) {
774                         session_remove_pending = true;
775                         session_removed.wait(_process_lock);
776                 }
777
778         } else {
779                 SessionHandlePtr::set_session (0);
780         }
781
782         remove_all_ports ();
783 }
784
785 void
786 AudioEngine::port_registration_failure (const std::string& portname)
787 {
788         GET_PRIVATE_JACK_POINTER (_jack);
789         string full_portname = jack_client_name;
790         full_portname += ':';
791         full_portname += portname;
792
793
794         jack_port_t* p = jack_port_by_name (_priv_jack, full_portname.c_str());
795         string reason;
796
797         if (p) {
798                 reason = string_compose (_("a port with the name \"%1\" already exists: check for duplicated track/bus names"), portname);
799         } else {
800                 reason = string_compose (_("No more JACK ports are available. You will need to stop %1 and restart JACK with more ports if you need this many tracks."), PROGRAM_NAME);
801         }
802
803         throw PortRegistrationFailure (string_compose (_("AudioEngine: cannot register port \"%1\": %2"), portname, reason).c_str());
804 }
805
806 boost::shared_ptr<Port>
807 AudioEngine::register_port (DataType dtype, const string& portname, bool input)
808 {
809         boost::shared_ptr<Port> newport;
810
811         try {
812                 if (dtype == DataType::AUDIO) {
813                         newport.reset (new AudioPort (portname, (input ? Port::IsInput : Port::IsOutput)));
814                 } else if (dtype == DataType::MIDI) {
815                         newport.reset (new MidiPort (portname, (input ? Port::IsInput : Port::IsOutput)));
816                 } else {
817                         throw PortRegistrationFailure("unable to create port (unknown type)");
818                 }
819
820                 RCUWriter<Ports> writer (ports);
821                 boost::shared_ptr<Ports> ps = writer.get_copy ();
822                 ps->insert (make_pair (make_port_name_relative (portname), newport));
823
824                 /* writer goes out of scope, forces update */
825
826                 return newport;
827         }
828
829         catch (PortRegistrationFailure& err) {
830                 throw err;
831         } catch (std::exception& e) {
832                 throw PortRegistrationFailure(string_compose(
833                                 _("unable to create port: %1"), e.what()).c_str());
834         } catch (...) {
835                 throw PortRegistrationFailure("unable to create port (unknown error)");
836         }
837 }
838
839 boost::shared_ptr<Port>
840 AudioEngine::register_input_port (DataType type, const string& portname)
841 {
842         return register_port (type, portname, true);
843 }
844
845 boost::shared_ptr<Port>
846 AudioEngine::register_output_port (DataType type, const string& portname)
847 {
848         return register_port (type, portname, false);
849 }
850
851 int
852 AudioEngine::unregister_port (boost::shared_ptr<Port> port)
853 {
854         /* caller must hold process lock */
855
856         if (!_running) {
857                 /* probably happening when the engine has been halted by JACK,
858                    in which case, there is nothing we can do here.
859                    */
860                 return 0;
861         }
862
863         {
864                 RCUWriter<Ports> writer (ports);
865                 boost::shared_ptr<Ports> ps = writer.get_copy ();
866                 Ports::iterator x = ps->find (make_port_name_relative (port->name()));
867
868                 if (x != ps->end()) {
869                         ps->erase (x);
870                 }
871
872                 /* writer goes out of scope, forces update */
873         }
874
875         ports.flush ();
876
877         return 0;
878 }
879
880 int
881 AudioEngine::connect (const string& source, const string& destination)
882 {
883         int ret;
884
885         if (!_running) {
886                 if (!_has_run) {
887                         fatal << _("connect called before engine was started") << endmsg;
888                         /*NOTREACHED*/
889                 } else {
890                         return -1;
891                 }
892         }
893
894         string s = make_port_name_non_relative (source);
895         string d = make_port_name_non_relative (destination);
896
897
898         boost::shared_ptr<Port> src = get_port_by_name (s);
899         boost::shared_ptr<Port> dst = get_port_by_name (d);
900
901         if (src) {
902                 ret = src->connect (d);
903         } else if (dst) {
904                 ret = dst->connect (s);
905         } else {
906                 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
907                 ret = -1;
908         }
909
910         if (ret > 0) {
911                 /* already exists - no error, no warning */
912         } else if (ret < 0) {
913                 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"),
914                                         source, s, destination, d)
915                       << endmsg;
916         }
917
918         return ret;
919 }
920
921 int
922 AudioEngine::disconnect (const string& source, const string& destination)
923 {
924         int ret;
925
926         if (!_running) {
927                 if (!_has_run) {
928                         fatal << _("disconnect called before engine was started") << endmsg;
929                         /*NOTREACHED*/
930                 } else {
931                         return -1;
932                 }
933         }
934
935         string s = make_port_name_non_relative (source);
936         string d = make_port_name_non_relative (destination);
937
938         boost::shared_ptr<Port> src = get_port_by_name (s);
939         boost::shared_ptr<Port> dst = get_port_by_name (d);
940
941         if (src) {
942                         ret = src->disconnect (d);
943         } else if (dst) {
944                         ret = dst->disconnect (s);
945         } else {
946                 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
947                 ret = -1;
948         }
949         return ret;
950 }
951
952 int
953 AudioEngine::disconnect (boost::shared_ptr<Port> port)
954 {
955         GET_PRIVATE_JACK_POINTER_RET (_jack,-1);
956
957         if (!_running) {
958                 if (!_has_run) {
959                         fatal << _("disconnect called before engine was started") << endmsg;
960                         /*NOTREACHED*/
961                 } else {
962                         return -1;
963                 }
964         }
965
966         return port->disconnect_all ();
967 }
968
969 ARDOUR::framecnt_t
970 AudioEngine::frame_rate () const
971 {
972         GET_PRIVATE_JACK_POINTER_RET (_jack, 0);
973         if (_frame_rate == 0) {
974                 return (_frame_rate = jack_get_sample_rate (_priv_jack));
975         } else {
976                 return _frame_rate;
977         }
978 }
979
980 size_t
981 AudioEngine::raw_buffer_size (DataType t)
982 {
983         std::map<DataType,size_t>::const_iterator s = _raw_buffer_sizes.find(t);
984         return (s != _raw_buffer_sizes.end()) ? s->second : 0;
985 }
986
987 ARDOUR::pframes_t
988 AudioEngine::frames_per_cycle () const
989 {
990         GET_PRIVATE_JACK_POINTER_RET (_jack,0);
991         if (_buffer_size == 0) {
992                 return jack_get_buffer_size (_jack);
993         } else {
994                 return _buffer_size;
995         }
996 }
997
998 /** @param name Full or short name of port
999  *  @return Corresponding Port or 0.
1000  */
1001
1002 boost::shared_ptr<Port>
1003 AudioEngine::get_port_by_name (const string& portname)
1004 {
1005         if (!_running) {
1006                 if (!_has_run) {
1007                         fatal << _("get_port_by_name() called before engine was started") << endmsg;
1008                         /*NOTREACHED*/
1009                 } else {
1010                         boost::shared_ptr<Port> ();
1011                 }
1012         }
1013
1014         if (!port_is_mine (portname)) {
1015                 /* not an ardour port */
1016                 return boost::shared_ptr<Port> ();
1017         }
1018
1019         boost::shared_ptr<Ports> pr = ports.reader();
1020         std::string rel = make_port_name_relative (portname);
1021         Ports::iterator x = pr->find (rel);
1022
1023         if (x != pr->end()) {
1024                 /* its possible that the port was renamed by some 3rd party and
1025                    we don't know about it. check for this (the check is quick
1026                    and cheap), and if so, rename the port (which will alter
1027                    the port map as a side effect).
1028                 */
1029                 const std::string check = make_port_name_relative (jack_port_name (x->second->jack_port()));
1030                 if (check != rel) {
1031                         x->second->set_name (check);
1032                 }
1033                 return x->second;
1034         }
1035
1036         return boost::shared_ptr<Port> ();
1037 }
1038
1039 void
1040 AudioEngine::port_renamed (const std::string& old_relative_name, const std::string& new_relative_name)
1041 {
1042         RCUWriter<Ports> writer (ports);
1043         boost::shared_ptr<Ports> p = writer.get_copy();
1044         Ports::iterator x = p->find (old_relative_name);
1045         
1046         if (x != p->end()) {
1047                 boost::shared_ptr<Port> port = x->second;
1048                 p->erase (x);
1049                 p->insert (make_pair (new_relative_name, port));
1050         }
1051 }
1052
1053 const char **
1054 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
1055 {
1056         GET_PRIVATE_JACK_POINTER_RET (_jack,0);
1057         if (!_running) {
1058                 if (!_has_run) {
1059                         fatal << _("get_ports called before engine was started") << endmsg;
1060                         /*NOTREACHED*/
1061                 } else {
1062                         return 0;
1063                 }
1064         }
1065         return jack_get_ports (_priv_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
1066 }
1067
1068 void
1069 AudioEngine::halted_info (jack_status_t code, const char* reason, void *arg)
1070 {
1071         /* called from jack shutdown handler  */
1072
1073         AudioEngine* ae = static_cast<AudioEngine *> (arg);
1074         bool was_running = ae->_running;
1075
1076         ae->stop_metering_thread ();
1077
1078         ae->_running = false;
1079         ae->_buffer_size = 0;
1080         ae->_frame_rate = 0;
1081         ae->_jack = 0;
1082
1083         if (was_running) {
1084 #ifdef HAVE_JACK_ON_INFO_SHUTDOWN
1085                 switch (code) {
1086                 case JackBackendError:
1087                         ae->Halted(reason); /* EMIT SIGNAL */
1088                         break;
1089                 default:
1090                         ae->Halted(""); /* EMIT SIGNAL */
1091                 }
1092 #else
1093                 ae->Halted(""); /* EMIT SIGNAL */
1094 #endif
1095         }
1096 }
1097
1098 void
1099 AudioEngine::halted (void *arg)
1100 {
1101         cerr << "HALTED by JACK\n";
1102
1103         /* called from jack shutdown handler  */
1104
1105         AudioEngine* ae = static_cast<AudioEngine *> (arg);
1106         bool was_running = ae->_running;
1107
1108         ae->stop_metering_thread ();
1109
1110         ae->_running = false;
1111         ae->_buffer_size = 0;
1112         ae->_frame_rate = 0;
1113         ae->_jack = 0;
1114
1115         if (was_running) {
1116                 ae->Halted(""); /* EMIT SIGNAL */
1117                 MIDI::JackMIDIPort::JackHalted (); /* EMIT SIGNAL */
1118         }
1119 }
1120
1121 void
1122 AudioEngine::died ()
1123 {
1124         /* called from a signal handler for SIGPIPE */
1125
1126         stop_metering_thread ();
1127
1128         _running = false;
1129         _buffer_size = 0;
1130         _frame_rate = 0;
1131         _jack = 0;
1132 }
1133
1134 bool
1135 AudioEngine::can_request_hardware_monitoring ()
1136 {
1137         GET_PRIVATE_JACK_POINTER_RET (_jack,false);
1138         const char ** ports;
1139
1140         if ((ports = jack_get_ports (_priv_jack, NULL, JACK_DEFAULT_AUDIO_TYPE, JackPortCanMonitor)) == 0) {
1141                 return false;
1142         }
1143
1144         free (ports);
1145
1146         return true;
1147 }
1148
1149 ChanCount
1150 AudioEngine::n_physical (unsigned long flags) const
1151 {
1152         ChanCount c;
1153
1154         GET_PRIVATE_JACK_POINTER_RET (_jack, c);
1155
1156         const char ** ports = jack_get_ports (_priv_jack, NULL, NULL, JackPortIsPhysical | flags);
1157         if (ports == 0) {
1158                 return c;
1159         }
1160
1161         for (uint32_t i = 0; ports[i]; ++i) {
1162                 if (!strstr (ports[i], "Midi-Through")) {
1163                         DataType t (jack_port_type (jack_port_by_name (_jack, ports[i])));
1164                         c.set (t, c.get (t) + 1);
1165                 }
1166         }
1167
1168         free (ports);
1169
1170         return c;
1171 }
1172
1173 ChanCount
1174 AudioEngine::n_physical_inputs () const
1175 {
1176         return n_physical (JackPortIsInput);
1177 }
1178
1179 ChanCount
1180 AudioEngine::n_physical_outputs () const
1181 {
1182         return n_physical (JackPortIsOutput);
1183 }
1184
1185 void
1186 AudioEngine::get_physical (DataType type, unsigned long flags, vector<string>& phy)
1187 {
1188         GET_PRIVATE_JACK_POINTER (_jack);
1189         const char ** ports;
1190
1191         if ((ports = jack_get_ports (_priv_jack, NULL, type.to_jack_type(), JackPortIsPhysical | flags)) == 0) {
1192                 return;
1193         }
1194
1195         if (ports) {
1196                 for (uint32_t i = 0; ports[i]; ++i) {
1197                         if (strstr (ports[i], "Midi-Through")) {
1198                                 continue;
1199                         }
1200                         phy.push_back (ports[i]);
1201                 }
1202                 free (ports);
1203         }
1204 }
1205
1206 /** Get physical ports for which JackPortIsOutput is set; ie those that correspond to
1207  *  a physical input connector.
1208  */
1209 void
1210 AudioEngine::get_physical_inputs (DataType type, vector<string>& ins)
1211 {
1212         get_physical (type, JackPortIsOutput, ins);
1213 }
1214
1215 /** Get physical ports for which JackPortIsInput is set; ie those that correspond to
1216  *  a physical output connector.
1217  */
1218 void
1219 AudioEngine::get_physical_outputs (DataType type, vector<string>& outs)
1220 {
1221         get_physical (type, JackPortIsInput, outs);
1222 }
1223
1224 void
1225 AudioEngine::transport_stop ()
1226 {
1227         GET_PRIVATE_JACK_POINTER (_jack);
1228         jack_transport_stop (_priv_jack);
1229 }
1230
1231 void
1232 AudioEngine::transport_start ()
1233 {
1234         GET_PRIVATE_JACK_POINTER (_jack);
1235         jack_transport_start (_priv_jack);
1236 }
1237
1238 void
1239 AudioEngine::transport_locate (framepos_t where)
1240 {
1241         GET_PRIVATE_JACK_POINTER (_jack);
1242         jack_transport_locate (_priv_jack, where);
1243 }
1244
1245 AudioEngine::TransportState
1246 AudioEngine::transport_state ()
1247 {
1248         GET_PRIVATE_JACK_POINTER_RET (_jack, ((TransportState) JackTransportStopped));
1249         jack_position_t pos;
1250         return (TransportState) jack_transport_query (_priv_jack, &pos);
1251 }
1252
1253 int
1254 AudioEngine::reset_timebase ()
1255 {
1256         GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
1257         if (_session) {
1258                 if (_session->config.get_jack_time_master()) {
1259                         return jack_set_timebase_callback (_priv_jack, 0, _jack_timebase_callback, this);
1260                 } else {
1261                         return jack_release_timebase (_jack);
1262                 }
1263         }
1264         return 0;
1265 }
1266
1267 int
1268 AudioEngine::freewheel (bool onoff)
1269 {
1270         GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
1271
1272         if (onoff != _freewheeling) {
1273                 return jack_set_freewheel (_priv_jack, onoff);
1274
1275         } else {
1276                 /* already doing what has been asked for */
1277                 return 0;
1278         }
1279 }
1280
1281 void
1282 AudioEngine::remove_all_ports ()
1283 {
1284         /* make sure that JACK callbacks that will be invoked as we cleanup
1285          * ports know that they have nothing to do.
1286          */
1287
1288         port_remove_in_progress = true;
1289
1290         /* process lock MUST be held by caller
1291         */
1292
1293         {
1294                 RCUWriter<Ports> writer (ports);
1295                 boost::shared_ptr<Ports> ps = writer.get_copy ();
1296                 ps->clear ();
1297         }
1298
1299         /* clear dead wood list in RCU */
1300
1301         ports.flush ();
1302
1303         port_remove_in_progress = false;
1304 }
1305
1306 int
1307 AudioEngine::connect_to_jack (string client_name, string session_uuid)
1308 {
1309         EnvironmentalProtectionAgency* global_epa = EnvironmentalProtectionAgency::get_global_epa ();
1310         boost::scoped_ptr<EnvironmentalProtectionAgency> current_epa;
1311         jack_status_t status;
1312
1313         /* revert all environment settings back to whatever they were when ardour started
1314          */
1315
1316         if (global_epa) {
1317                 current_epa.reset (new EnvironmentalProtectionAgency(true)); /* will restore settings when we leave scope */
1318                 global_epa->restore ();
1319         }
1320
1321         jack_client_name = client_name; /* might be reset below */
1322 #ifdef HAVE_JACK_SESSION
1323         if (! session_uuid.empty())
1324             _jack = jack_client_open (jack_client_name.c_str(), JackSessionID, &status, session_uuid.c_str());
1325         else
1326 #endif
1327         _jack = jack_client_open (jack_client_name.c_str(), JackNullOption, &status, 0);
1328
1329         if (_jack == NULL) {
1330                 // error message is not useful here
1331                 return -1;
1332         }
1333
1334         GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
1335
1336         if (status & JackNameNotUnique) {
1337                 jack_client_name = jack_get_client_name (_priv_jack);
1338         }
1339
1340         return 0;
1341 }
1342
1343 int
1344 AudioEngine::disconnect_from_jack ()
1345 {
1346         GET_PRIVATE_JACK_POINTER_RET (_jack, 0);
1347
1348         if (_running) {
1349                 stop_metering_thread ();
1350         }
1351
1352         {
1353                 Glib::Mutex::Lock lm (_process_lock);
1354                 jack_client_close (_priv_jack);
1355                 _jack = 0;
1356         }
1357
1358         _buffer_size = 0;
1359         _frame_rate = 0;
1360         _raw_buffer_sizes.clear();
1361
1362         if (_running) {
1363                 _running = false;
1364                 Stopped(); /* EMIT SIGNAL */
1365                 MIDI::JackMIDIPort::JackHalted (); /* EMIT SIGNAL */
1366         }
1367
1368         return 0;
1369 }
1370
1371 int
1372 AudioEngine::reconnect_to_jack ()
1373 {
1374         if (_running) {
1375                 disconnect_from_jack ();
1376                 /* XXX give jackd a chance */
1377                 Glib::usleep (250000);
1378         }
1379
1380         if (connect_to_jack (jack_client_name, "")) {
1381                 error << _("failed to connect to JACK") << endmsg;
1382                 return -1;
1383         }
1384
1385         Ports::iterator i;
1386
1387         boost::shared_ptr<Ports> p = ports.reader ();
1388
1389         for (i = p->begin(); i != p->end(); ++i) {
1390                 if (i->second->reestablish ()) {
1391                         break;
1392                 }
1393         }
1394
1395         if (i != p->end()) {
1396                 /* failed */
1397                 remove_all_ports ();
1398                 return -1;
1399         }
1400
1401         GET_PRIVATE_JACK_POINTER_RET (_jack,-1);
1402
1403         MIDI::Manager::instance()->reestablish (_priv_jack);
1404
1405         if (_session) {
1406                 _session->reset_jack_connection (_priv_jack);
1407                 jack_bufsize_callback (jack_get_buffer_size (_priv_jack));
1408                 _session->set_frame_rate (jack_get_sample_rate (_priv_jack));
1409         }
1410
1411         last_monitor_check = 0;
1412
1413         set_jack_callbacks ();
1414
1415         if (jack_activate (_priv_jack) == 0) {
1416                 _running = true;
1417                 _has_run = true;
1418         } else {
1419                 return -1;
1420         }
1421
1422         /* re-establish connections */
1423
1424         for (i = p->begin(); i != p->end(); ++i) {
1425                 i->second->reconnect ();
1426         }
1427
1428         MIDI::Manager::instance()->reconnect ();
1429
1430         Running (); /* EMIT SIGNAL*/
1431
1432         start_metering_thread ();
1433
1434         return 0;
1435 }
1436
1437 int
1438 AudioEngine::request_buffer_size (pframes_t nframes)
1439 {
1440         GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
1441
1442         if (nframes == jack_get_buffer_size (_priv_jack)) {
1443                 return 0;
1444         }
1445
1446         return jack_set_buffer_size (_priv_jack, nframes);
1447 }
1448
1449 string
1450 AudioEngine::make_port_name_relative (string portname) const
1451 {
1452         string::size_type len;
1453         string::size_type n;
1454
1455         len = portname.length();
1456
1457         for (n = 0; n < len; ++n) {
1458                 if (portname[n] == ':') {
1459                         break;
1460                 }
1461         }
1462
1463         if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1464                 return portname.substr (n+1);
1465         }
1466
1467         return portname;
1468 }
1469
1470 string
1471 AudioEngine::make_port_name_non_relative (string portname) const
1472 {
1473         string str;
1474
1475         if (portname.find_first_of (':') != string::npos) {
1476                 return portname;
1477         }
1478
1479         str  = jack_client_name;
1480         str += ':';
1481         str += portname;
1482
1483         return str;
1484 }
1485
1486 bool
1487 AudioEngine::port_is_mine (const string& portname) const
1488 {
1489         if (portname.find_first_of (':') != string::npos) {
1490                 if (portname.substr (0, jack_client_name.length ()) != jack_client_name) {
1491                         return false;
1492                 }
1493         }
1494         return true;
1495 }
1496
1497 bool
1498 AudioEngine::is_realtime () const
1499 {
1500         GET_PRIVATE_JACK_POINTER_RET (_jack,false);
1501         return jack_is_realtime (_priv_jack);
1502 }
1503
1504 int
1505 AudioEngine::create_process_thread (boost::function<void()> f, pthread_t* thread, size_t stacksize)
1506 {
1507         GET_PRIVATE_JACK_POINTER_RET (_jack, 0);
1508         ThreadData* td = new ThreadData (this, f, stacksize);
1509
1510         if (jack_client_create_thread (_priv_jack, thread, jack_client_real_time_priority (_priv_jack),
1511                                        jack_is_realtime (_priv_jack), _start_process_thread, td)) {
1512                 return -1;
1513         }
1514
1515         return 0;
1516 }
1517
1518 void*
1519 AudioEngine::_start_process_thread (void* arg)
1520 {
1521         ThreadData* td = reinterpret_cast<ThreadData*> (arg);
1522         boost::function<void()> f = td->f;
1523         delete td;
1524
1525         f ();
1526
1527         return 0;
1528 }
1529
1530 bool
1531 AudioEngine::port_is_physical (const std::string& portname) const
1532 {
1533         GET_PRIVATE_JACK_POINTER_RET(_jack, false);
1534
1535         jack_port_t *port = jack_port_by_name (_priv_jack, portname.c_str());
1536
1537         if (!port) {
1538                 return false;
1539         }
1540
1541         return jack_port_flags (port) & JackPortIsPhysical;
1542 }
1543
1544 void
1545 AudioEngine::request_jack_monitors_input (const std::string& portname, bool yn) const
1546 {
1547         GET_PRIVATE_JACK_POINTER(_jack);
1548
1549         jack_port_t *port = jack_port_by_name (_priv_jack, portname.c_str());
1550
1551         if (!port) {
1552                 return;
1553         }
1554
1555         jack_port_request_monitor (port, yn);
1556 }
1557
1558 void
1559 AudioEngine::update_latencies ()
1560 {
1561         if (jack_recompute_total_latencies) {
1562                 GET_PRIVATE_JACK_POINTER (_jack);
1563                 jack_recompute_total_latencies (_priv_jack);
1564         }
1565 }
1566
1567 void
1568 AudioEngine::destroy ()
1569 {
1570         delete _instance;
1571         _instance = 0;
1572 }