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