NOOP, reindent & whitespace
[ardour.git] / libs / backends / coreaudio / coreaudio_backend.cc
1 /*
2  * Copyright (C) 2014 Robin Gareus <robin@gareus.org>
3  * Copyright (C) 2013 Paul Davis
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19
20 #include <regex.h>
21 #include <sys/mman.h>
22 #include <sys/time.h>
23
24 #include <glibmm.h>
25
26 #include "coreaudio_backend.h"
27 #include "rt_thread.h"
28
29 #include "pbd/compose.h"
30 #include "pbd/error.h"
31 #include "pbd/file_utils.h"
32 #include "ardour/filesystem_paths.h"
33 #include "ardour/port_manager.h"
34 #include "i18n.h"
35
36 using namespace ARDOUR;
37
38 static std::string s_instance_name;
39 size_t CoreAudioBackend::_max_buffer_size = 8192;
40 std::vector<std::string> CoreAudioBackend::_midi_options;
41 std::vector<AudioBackend::DeviceStatus> CoreAudioBackend::_duplex_audio_device_status;
42 std::vector<AudioBackend::DeviceStatus> CoreAudioBackend::_input_audio_device_status;
43 std::vector<AudioBackend::DeviceStatus> CoreAudioBackend::_output_audio_device_status;
44
45
46 /* static class instance access */
47 static void hw_changed_callback_ptr (void *arg)
48 {
49         CoreAudioBackend *d = static_cast<CoreAudioBackend*> (arg);
50         d->hw_changed_callback();
51 }
52
53 static void error_callback_ptr (void *arg)
54 {
55         CoreAudioBackend *d = static_cast<CoreAudioBackend*> (arg);
56         d->error_callback();
57 }
58
59 static void xrun_callback_ptr (void *arg)
60 {
61         CoreAudioBackend *d = static_cast<CoreAudioBackend*> (arg);
62         d->xrun_callback();
63 }
64
65 static void buffer_size_callback_ptr (void *arg)
66 {
67         CoreAudioBackend *d = static_cast<CoreAudioBackend*> (arg);
68         d->buffer_size_callback();
69 }
70
71 static void sample_rate_callback_ptr (void *arg)
72 {
73         CoreAudioBackend *d = static_cast<CoreAudioBackend*> (arg);
74         d->sample_rate_callback();
75 }
76
77 static void midi_port_change (void *arg)
78 {
79         CoreAudioBackend *d = static_cast<CoreAudioBackend *>(arg);
80         d->coremidi_rediscover ();
81 }
82
83
84 CoreAudioBackend::CoreAudioBackend (AudioEngine& e, AudioBackendInfo& info)
85         : AudioBackend (e, info)
86         , _run (false)
87         , _active_ca (false)
88         , _active_fw (false)
89         , _freewheeling (false)
90         , _freewheel (false)
91         , _freewheel_ack (false)
92         , _reinit_thread_callback (false)
93         , _measure_latency (false)
94         , _last_process_start (0)
95         , _input_audio_device("")
96         , _output_audio_device("")
97         , _midi_driver_option(_("None"))
98         , _samplerate (48000)
99         , _samples_per_period (1024)
100         , _n_inputs (0)
101         , _n_outputs (0)
102         , _systemic_audio_input_latency (0)
103         , _systemic_audio_output_latency (0)
104         , _dsp_load (0)
105         , _processed_samples (0)
106         , _port_change_flag (false)
107 #ifdef USE_MIDI_PARSER
108         , _event(0)
109         , _first_time(true)
110         , _unbuffered_bytes(0)
111         , _total_bytes(0)
112         , _expected_bytes(0)
113         , _status_byte(0)
114 #endif
115 {
116         _instance_name = s_instance_name;
117         pthread_mutex_init (&_port_callback_mutex, 0);
118         pthread_mutex_init (&_process_callback_mutex, 0);
119         pthread_mutex_init (&_freewheel_mutex, 0);
120         pthread_cond_init  (&_freewheel_signal, 0);
121
122         _pcmio = new CoreAudioPCM ();
123         _midiio = new CoreMidiIo ();
124
125         _pcmio->set_hw_changed_callback (hw_changed_callback_ptr, this);
126         _pcmio->discover();
127 }
128
129 CoreAudioBackend::~CoreAudioBackend ()
130 {
131         delete _pcmio; _pcmio = 0;
132         delete _midiio; _midiio = 0;
133         pthread_mutex_destroy (&_port_callback_mutex);
134         pthread_mutex_destroy (&_process_callback_mutex);
135         pthread_mutex_destroy (&_freewheel_mutex);
136         pthread_cond_destroy  (&_freewheel_signal);
137 }
138
139 /* AUDIOBACKEND API */
140
141 std::string
142 CoreAudioBackend::name () const
143 {
144         return X_("CoreAudio");
145 }
146
147 bool
148 CoreAudioBackend::is_realtime () const
149 {
150         return true;
151 }
152
153 std::vector<AudioBackend::DeviceStatus>
154 CoreAudioBackend::enumerate_devices () const
155 {
156         _duplex_audio_device_status.clear();
157         std::map<size_t, std::string> devices;
158         _pcmio->duplex_device_list(devices);
159
160         for (std::map<size_t, std::string>::const_iterator i = devices.begin (); i != devices.end(); ++i) {
161                 if (_input_audio_device == "") _input_audio_device = i->second;
162                 if (_output_audio_device == "") _output_audio_device = i->second;
163                 _duplex_audio_device_status.push_back (DeviceStatus (i->second, true));
164         }
165         return _duplex_audio_device_status;
166 }
167
168 std::vector<AudioBackend::DeviceStatus>
169 CoreAudioBackend::enumerate_input_devices () const
170 {
171         _input_audio_device_status.clear();
172         std::map<size_t, std::string> devices;
173         _pcmio->input_device_list(devices);
174
175         _input_audio_device_status.push_back (DeviceStatus (_("None"), true));
176         for (std::map<size_t, std::string>::const_iterator i = devices.begin (); i != devices.end(); ++i) {
177                 if (_input_audio_device == "") _input_audio_device = i->second;
178                 _input_audio_device_status.push_back (DeviceStatus (i->second, true));
179         }
180         return _input_audio_device_status;
181 }
182
183
184 std::vector<AudioBackend::DeviceStatus>
185 CoreAudioBackend::enumerate_output_devices () const
186 {
187         _output_audio_device_status.clear();
188         std::map<size_t, std::string> devices;
189         _pcmio->output_device_list(devices);
190
191         _output_audio_device_status.push_back (DeviceStatus (_("None"), true));
192         for (std::map<size_t, std::string>::const_iterator i = devices.begin (); i != devices.end(); ++i) {
193                 if (_output_audio_device == "") _output_audio_device = i->second;
194                 _output_audio_device_status.push_back (DeviceStatus (i->second, true));
195         }
196         return _output_audio_device_status;
197 }
198
199 std::vector<float>
200 CoreAudioBackend::available_sample_rates (const std::string&) const
201 {
202         std::vector<float> sr;
203         std::vector<float> sr_in;
204         std::vector<float> sr_out;
205
206         const uint32_t inp = name_to_id(_input_audio_device);
207         const uint32_t out = name_to_id(_output_audio_device);
208         if (inp == UINT32_MAX && out == UINT32_MAX) {
209                 return sr;
210         } else if (inp == UINT32_MAX) {
211                 _pcmio->available_sample_rates(out, sr_out);
212                 return sr_out;
213         } else if (out == UINT32_MAX) {
214                 _pcmio->available_sample_rates(inp, sr_in);
215                 return sr_in;
216         } else {
217                 _pcmio->available_sample_rates(inp, sr_in);
218                 _pcmio->available_sample_rates(out, sr_out);
219                 // TODO allow to use different SR per device, tweak aggregate
220                 std::set_intersection(sr_in.begin(), sr_in.end(), sr_out.begin(), sr_out.end(), std::back_inserter(sr));
221                 return sr;
222         }
223 }
224
225 std::vector<uint32_t>
226 CoreAudioBackend::available_buffer_sizes (const std::string& device) const
227 {
228         std::vector<uint32_t> bs;
229         _pcmio->available_buffer_sizes(name_to_id(device), bs);
230         return bs;
231 }
232
233 uint32_t
234 CoreAudioBackend::available_input_channel_count (const std::string&) const
235 {
236         return 128; // TODO query current device
237 }
238
239 uint32_t
240 CoreAudioBackend::available_output_channel_count (const std::string&) const
241 {
242         return 128; // TODO query current device
243 }
244
245 bool
246 CoreAudioBackend::can_change_sample_rate_when_running () const
247 {
248         return false;
249 }
250
251 bool
252 CoreAudioBackend::can_change_buffer_size_when_running () const
253 {
254         return true;
255 }
256
257 int
258 CoreAudioBackend::set_device_name (const std::string& d)
259 {
260         int rv = 0;
261         rv |= set_input_device_name (d);
262         rv |= set_output_device_name (d);
263         return rv;
264 }
265
266 int
267 CoreAudioBackend::set_input_device_name (const std::string& d)
268 {
269         _input_audio_device = d;
270         const float sr = _pcmio->current_sample_rate(name_to_id(_input_audio_device));
271         if (sr > 0) { set_sample_rate(sr); }
272         return 0;
273 }
274
275 int
276 CoreAudioBackend::set_output_device_name (const std::string& d)
277 {
278         _output_audio_device = d;
279         // TODO check SR.
280         const float sr = _pcmio->current_sample_rate(name_to_id(_output_audio_device));
281         if (sr > 0) { set_sample_rate(sr); }
282         return 0;
283 }
284
285 int
286 CoreAudioBackend::set_sample_rate (float sr)
287 {
288         std::vector<float> srs = available_sample_rates (/* really ignored */_input_audio_device);
289         if (std::find(srs.begin(), srs.end(), sr) == srs.end()) {
290                 return -1;
291         }
292         _samplerate = sr;
293         engine.sample_rate_change (sr);
294         return 0;
295 }
296
297 int
298 CoreAudioBackend::set_buffer_size (uint32_t bs)
299 {
300         if (bs <= 0 || bs >= _max_buffer_size) {
301                 return -1;
302         }
303         _samples_per_period = bs;
304         _pcmio->set_samples_per_period(bs);
305         engine.buffer_size_change (bs);
306         return 0;
307 }
308
309 int
310 CoreAudioBackend::set_interleaved (bool yn)
311 {
312         if (!yn) { return 0; }
313         return -1;
314 }
315
316 int
317 CoreAudioBackend::set_input_channels (uint32_t cc)
318 {
319         _n_inputs = cc;
320         return 0;
321 }
322
323 int
324 CoreAudioBackend::set_output_channels (uint32_t cc)
325 {
326         _n_outputs = cc;
327         return 0;
328 }
329
330 int
331 CoreAudioBackend::set_systemic_input_latency (uint32_t sl)
332 {
333         _systemic_audio_input_latency = sl;
334         return 0;
335 }
336
337 int
338 CoreAudioBackend::set_systemic_output_latency (uint32_t sl)
339 {
340         _systemic_audio_output_latency = sl;
341         return 0;
342 }
343
344 /* Retrieving parameters */
345 std::string
346 CoreAudioBackend::device_name () const
347 {
348         return "";
349 }
350
351 std::string
352 CoreAudioBackend::input_device_name () const
353 {
354         return _input_audio_device;
355 }
356
357 std::string
358 CoreAudioBackend::output_device_name () const
359 {
360         return _output_audio_device;
361 }
362
363 float
364 CoreAudioBackend::sample_rate () const
365 {
366         return _samplerate;
367 }
368
369 uint32_t
370 CoreAudioBackend::buffer_size () const
371 {
372         return _samples_per_period;
373 }
374
375 bool
376 CoreAudioBackend::interleaved () const
377 {
378         return false;
379 }
380
381 uint32_t
382 CoreAudioBackend::input_channels () const
383 {
384         return _n_inputs;
385 }
386
387 uint32_t
388 CoreAudioBackend::output_channels () const
389 {
390         return _n_outputs;
391 }
392
393 uint32_t
394 CoreAudioBackend::systemic_input_latency () const
395 {
396         return _systemic_audio_input_latency;
397 }
398
399 uint32_t
400 CoreAudioBackend::systemic_output_latency () const
401 {
402         return _systemic_audio_output_latency;
403 }
404
405 /* MIDI */
406
407 std::vector<std::string>
408 CoreAudioBackend::enumerate_midi_options () const
409 {
410         if (_midi_options.empty()) {
411                 _midi_options.push_back (_("CoreMidi"));
412                 _midi_options.push_back (_("None"));
413         }
414         return _midi_options;
415 }
416
417 int
418 CoreAudioBackend::set_midi_option (const std::string& opt)
419 {
420         if (opt != _("None") && opt != _("CoreMidi")) {
421                 return -1;
422         }
423         _midi_driver_option = opt;
424         return 0;
425 }
426
427 std::string
428 CoreAudioBackend::midi_option () const
429 {
430         return _midi_driver_option;
431 }
432
433 void
434 CoreAudioBackend::launch_control_app ()
435 {
436     _pcmio->launch_control_app(name_to_id(_input_audio_device));
437 }
438
439 /* State Control */
440
441 static void * pthread_freewheel (void *arg)
442 {
443         CoreAudioBackend *d = static_cast<CoreAudioBackend *>(arg);
444         d->freewheel_thread ();
445         pthread_exit (0);
446         return 0;
447 }
448
449 static int process_callback_ptr (void *arg, const uint32_t n_samples, const uint64_t host_time)
450 {
451         CoreAudioBackend *d = static_cast<CoreAudioBackend*> (arg);
452         return d->process_callback(n_samples, host_time);
453 }
454
455 int
456 CoreAudioBackend::_start (bool for_latency_measurement)
457 {
458         if ((!_active_ca || !_active_fw)  && _run) {
459                 // recover from 'halted', reap threads
460                 stop();
461         }
462
463         if (_active_ca || _active_fw || _run) {
464                 PBD::error << _("CoreAudioBackend: already active.") << endmsg;
465                 return -1;
466         }
467
468         if (_ports.size()) {
469                 PBD::warning << _("CoreAudioBackend: recovering from unclean shutdown, port registry is not empty.") << endmsg;
470                 _system_inputs.clear();
471                 _system_outputs.clear();
472                 _system_midi_in.clear();
473                 _system_midi_out.clear();
474                 _ports.clear();
475         }
476
477         uint32_t device1 = name_to_id(_input_audio_device);
478         uint32_t device2 = name_to_id(_output_audio_device);
479
480         assert(_active_ca == false);
481         assert(_active_fw == false);
482
483         _freewheel_ack = false;
484         _reinit_thread_callback = true;
485         _last_process_start = 0;
486
487         _pcmio->set_error_callback (error_callback_ptr, this);
488         _pcmio->set_buffer_size_callback (buffer_size_callback_ptr, this);
489         _pcmio->set_sample_rate_callback (sample_rate_callback_ptr, this);
490
491         _pcmio->pcm_start (device1, device2, _samplerate, _samples_per_period, process_callback_ptr, this);
492         printf("STATE: %d\n", _pcmio->state ());
493
494         switch (_pcmio->state ()) {
495                 case 0: /* OK */ break;
496                 case -1: PBD::error << _("CoreAudioBackend: failed to open device.") << endmsg; break;
497                 default: PBD::error << _("CoreAudioBackend: initialization failed.") << endmsg; break;
498         }
499         if (_pcmio->state ()) {
500                 return -1;
501         }
502
503         if (_n_outputs != _pcmio->n_playback_channels ()) {
504                 if (_n_outputs == 0) {
505                  _n_outputs = _pcmio->n_playback_channels ();
506                 } else {
507                  _n_outputs = std::min (_n_outputs, _pcmio->n_playback_channels ());
508                 }
509                 PBD::info << _("CoreAudioBackend: adjusted output channel count to match device.") << endmsg;
510         }
511
512         if (_n_inputs != _pcmio->n_capture_channels ()) {
513                 if (_n_inputs == 0) {
514                  _n_inputs = _pcmio->n_capture_channels ();
515                 } else {
516                  _n_inputs = std::min (_n_inputs, _pcmio->n_capture_channels ());
517                 }
518                 PBD::info << _("CoreAudioBackend: adjusted input channel count to match device.") << endmsg;
519         }
520
521         if (_pcmio->samples_per_period() != _samples_per_period) {
522                 _samples_per_period = _pcmio->samples_per_period();
523                 PBD::warning << _("CoreAudioBackend: samples per period does not match.") << endmsg;
524         }
525
526         if (_pcmio->sample_rate() != _samplerate) {
527                 _samplerate = _pcmio->sample_rate();
528                 engine.sample_rate_change (_samplerate);
529                 PBD::warning << _("CoreAudioBackend: sample rate does not match.") << endmsg;
530         }
531
532         _measure_latency = for_latency_measurement;
533
534         _preinit = true;
535         _run = true;
536         _port_change_flag = false;
537
538         if (_midi_driver_option == _("CoreMidi")) {
539                 _midiio->set_enabled(true);
540                 _midiio->set_port_changed_callback(midi_port_change, this);
541                 _midiio->start(); // triggers port discovery, callback coremidi_rediscover()
542         }
543
544         if (register_system_audio_ports()) {
545                 PBD::error << _("CoreAudioBackend: failed to register system ports.") << endmsg;
546                 _run = false;
547                 return -1;
548         }
549
550         engine.sample_rate_change (_samplerate);
551         engine.buffer_size_change (_samples_per_period);
552
553         if (engine.reestablish_ports ()) {
554                 PBD::error << _("CoreAudioBackend: Could not re-establish ports.") << endmsg;
555                 _run = false;
556                 return -1;
557         }
558
559         if (pthread_create (&_freeewheel_thread, NULL, pthread_freewheel, this))
560         {
561                 PBD::error << _("CoreAudioBackend: failed to create process thread.") << endmsg;
562                 delete _pcmio; _pcmio = 0;
563                 _run = false;
564                 return -1;
565         }
566
567         int timeout = 5000;
568         while ((!_active_ca || !_active_fw) && --timeout > 0) { Glib::usleep (1000); }
569
570         if (timeout == 0) {
571                 PBD::error << _("CoreAudioBackend: failed to start.") << endmsg;
572         }
573
574         if (!_active_fw) {
575                 PBD::error << _("CoreAudioBackend: failed to start freewheeling thread.") << endmsg;
576                 _run = false;
577                 _pcmio->pcm_stop();
578                 unregister_ports();
579                 _active_ca = false;
580                 _active_fw = false;
581                 return -1;
582         }
583
584         if (!_active_ca) {
585                 PBD::error << _("CoreAudioBackend: failed to start coreaudio.") << endmsg;
586                 stop();
587                 _run = false;
588                 return -1;
589         }
590
591         engine.reconnect_ports ();
592
593         // force  an initial registration_callback() & latency re-compute
594         _port_change_flag = true;
595         pre_process ();
596
597         // all systems go.
598         _pcmio->set_xrun_callback (xrun_callback_ptr, this);
599         _preinit = false;
600
601         return 0;
602 }
603
604 int
605 CoreAudioBackend::stop ()
606 {
607         void *status;
608         if (!_run) {
609                 return 0;
610         }
611
612         _run = false;
613         _pcmio->pcm_stop();
614         _midiio->set_port_changed_callback(NULL, NULL);
615         _midiio->stop();
616
617         pthread_mutex_lock (&_freewheel_mutex);
618         pthread_cond_signal (&_freewheel_signal);
619         pthread_mutex_unlock (&_freewheel_mutex);
620
621         if (pthread_join (_freeewheel_thread, &status)) {
622                 PBD::error << _("CoreAudioBackend: failed to terminate.") << endmsg;
623                 return -1;
624         }
625
626         unregister_ports();
627
628         _active_ca = false;
629         _active_fw = false; // ??
630
631         return 0;
632 }
633
634 int
635 CoreAudioBackend::freewheel (bool onoff)
636 {
637         if (onoff == _freewheeling) {
638                 return 0;
639         }
640         _freewheeling = onoff;
641         // wake up freewheeling thread
642         if (0 == pthread_mutex_trylock (&_freewheel_mutex)) {
643                 pthread_cond_signal (&_freewheel_signal);
644                 pthread_mutex_unlock (&_freewheel_mutex);
645         }
646         return 0;
647 }
648
649 float
650 CoreAudioBackend::dsp_load () const
651 {
652         return std::min(100.f, 100.f * _dsp_load);
653 }
654
655 size_t
656 CoreAudioBackend::raw_buffer_size (DataType t)
657 {
658         switch (t) {
659                 case DataType::AUDIO:
660                         return _samples_per_period * sizeof(Sample);
661                 case DataType::MIDI:
662                         return _max_buffer_size; // XXX not really limited
663         }
664         return 0;
665 }
666
667 /* Process time */
668 framepos_t
669 CoreAudioBackend::sample_time ()
670 {
671         return _processed_samples;
672 }
673
674 framepos_t
675 CoreAudioBackend::sample_time_at_cycle_start ()
676 {
677         return _processed_samples;
678 }
679
680 pframes_t
681 CoreAudioBackend::samples_since_cycle_start ()
682 {
683         if (!_active_ca || !_run || _freewheeling || _freewheel) {
684                 return 0;
685         }
686         if (_last_process_start == 0) {
687                 return 0;
688         }
689
690         const uint64_t now = AudioGetCurrentHostTime ();
691         const int64_t elapsed_time_ns = AudioConvertHostTimeToNanos(now - _last_process_start);
692         return std::max((pframes_t)0, (pframes_t)rint(1e-9 * elapsed_time_ns * _samplerate));
693 }
694
695 uint32_t
696 CoreAudioBackend::name_to_id(std::string device_name) const {
697         uint32_t device_id = UINT32_MAX;
698         std::map<size_t, std::string> devices;
699         _pcmio->device_list(devices);
700
701         for (std::map<size_t, std::string>::const_iterator i = devices.begin (); i != devices.end(); ++i) {
702                 if (i->second == device_name) {
703                         device_id = i->first;
704                         break;
705                 }
706         }
707         return device_id;
708 }
709
710 void *
711 CoreAudioBackend::coreaudio_process_thread (void *arg)
712 {
713         ThreadData* td = reinterpret_cast<ThreadData*> (arg);
714         boost::function<void ()> f = td->f;
715         delete td;
716         f ();
717         return 0;
718 }
719
720 int
721 CoreAudioBackend::create_process_thread (boost::function<void()> func)
722 {
723         pthread_t thread_id;
724         pthread_attr_t attr;
725         size_t stacksize = 100000;
726
727         ThreadData* td = new ThreadData (this, func, stacksize);
728
729         if (_realtime_pthread_create (SCHED_FIFO, -21, stacksize,
730                                 &thread_id, coreaudio_process_thread, td)) {
731                 pthread_attr_init (&attr);
732                 pthread_attr_setstacksize (&attr, stacksize);
733                 if (pthread_create (&thread_id, &attr, coreaudio_process_thread, td)) {
734                         PBD::error << _("AudioEngine: cannot create process thread.") << endmsg;
735                         pthread_attr_destroy (&attr);
736                         return -1;
737                 }
738                 pthread_attr_destroy (&attr);
739         }
740
741         _threads.push_back (thread_id);
742         return 0;
743 }
744
745 int
746 CoreAudioBackend::join_process_threads ()
747 {
748         int rv = 0;
749
750         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
751         {
752                 void *status;
753                 if (pthread_join (*i, &status)) {
754                         PBD::error << _("AudioEngine: cannot terminate process thread.") << endmsg;
755                         rv -= 1;
756                 }
757         }
758         _threads.clear ();
759         return rv;
760 }
761
762 bool
763 CoreAudioBackend::in_process_thread ()
764 {
765         if (pthread_equal (_main_thread, pthread_self()) != 0) {
766                 return true;
767         }
768
769         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
770         {
771                 if (pthread_equal (*i, pthread_self ()) != 0) {
772                         return true;
773                 }
774         }
775         return false;
776 }
777
778 uint32_t
779 CoreAudioBackend::process_thread_count ()
780 {
781         return _threads.size ();
782 }
783
784 void
785 CoreAudioBackend::update_latencies ()
786 {
787         // trigger latency callback in RT thread (locked graph)
788         port_connect_add_remove_callback();
789 }
790
791 /* PORTENGINE API */
792
793 void*
794 CoreAudioBackend::private_handle () const
795 {
796         return NULL;
797 }
798
799 const std::string&
800 CoreAudioBackend::my_name () const
801 {
802         return _instance_name;
803 }
804
805 bool
806 CoreAudioBackend::available () const
807 {
808         return _run && _active_fw && _active_ca;
809 }
810
811 uint32_t
812 CoreAudioBackend::port_name_size () const
813 {
814         return 256;
815 }
816
817 int
818 CoreAudioBackend::set_port_name (PortEngine::PortHandle port, const std::string& name)
819 {
820         if (!valid_port (port)) {
821                 PBD::error << _("CoreAudioBackend::set_port_name: Invalid Port(s)") << endmsg;
822                 return -1;
823         }
824         return static_cast<CoreBackendPort*>(port)->set_name (_instance_name + ":" + name);
825 }
826
827 std::string
828 CoreAudioBackend::get_port_name (PortEngine::PortHandle port) const
829 {
830         if (!valid_port (port)) {
831                 PBD::error << _("CoreAudioBackend::get_port_name: Invalid Port(s)") << endmsg;
832                 return std::string ();
833         }
834         return static_cast<CoreBackendPort*>(port)->name ();
835 }
836
837 int
838 CoreAudioBackend::get_port_property (PortHandle port, const std::string& key, std::string& value, std::string& type) const
839 {
840         if (!valid_port (port)) {
841                 PBD::error << _("CoreAudioBackend::get_port_name: Invalid Port(s)") << endmsg;
842                 return -1;
843         }
844         if (key == "http://jackaudio.org/metadata/pretty-name") {
845                 type = "";
846                 value = static_cast<CoreBackendPort*>(port)->pretty_name ();
847                 if (!value.empty()) {
848                         return 0;
849                 }
850         }
851         return -1;
852 }
853
854 PortEngine::PortHandle
855 CoreAudioBackend::get_port_by_name (const std::string& name) const
856 {
857         PortHandle port = (PortHandle) find_port (name);
858         return port;
859 }
860
861 int
862 CoreAudioBackend::get_ports (
863                 const std::string& port_name_pattern,
864                 DataType type, PortFlags flags,
865                 std::vector<std::string>& port_names) const
866 {
867         int rv = 0;
868         regex_t port_regex;
869         bool use_regexp = false;
870         if (port_name_pattern.size () > 0) {
871                 if (!regcomp (&port_regex, port_name_pattern.c_str (), REG_EXTENDED|REG_NOSUB)) {
872                         use_regexp = true;
873                 }
874         }
875         for (size_t i = 0; i < _ports.size (); ++i) {
876                 CoreBackendPort* port = _ports[i];
877                 if ((port->type () == type) && flags == (port->flags () & flags)) {
878                         if (!use_regexp || !regexec (&port_regex, port->name ().c_str (), 0, NULL, 0)) {
879                                 port_names.push_back (port->name ());
880                                 ++rv;
881                         }
882                 }
883         }
884         if (use_regexp) {
885                 regfree (&port_regex);
886         }
887         return rv;
888 }
889
890 DataType
891 CoreAudioBackend::port_data_type (PortEngine::PortHandle port) const
892 {
893         if (!valid_port (port)) {
894                 return DataType::NIL;
895         }
896         return static_cast<CoreBackendPort*>(port)->type ();
897 }
898
899 PortEngine::PortHandle
900 CoreAudioBackend::register_port (
901                 const std::string& name,
902                 ARDOUR::DataType type,
903                 ARDOUR::PortFlags flags)
904 {
905         if (name.size () == 0) { return 0; }
906         if (flags & IsPhysical) { return 0; }
907         return add_port (_instance_name + ":" + name, type, flags);
908 }
909
910 PortEngine::PortHandle
911 CoreAudioBackend::add_port (
912                 const std::string& name,
913                 ARDOUR::DataType type,
914                 ARDOUR::PortFlags flags)
915 {
916         assert(name.size ());
917         if (find_port (name)) {
918                 PBD::error << _("CoreAudioBackend::register_port: Port already exists:")
919                                 << " (" << name << ")" << endmsg;
920                 return 0;
921         }
922         CoreBackendPort* port = NULL;
923         switch (type) {
924                 case DataType::AUDIO:
925                         port = new CoreAudioPort (*this, name, flags);
926                         break;
927                 case DataType::MIDI:
928                         port = new CoreMidiPort (*this, name, flags);
929                         break;
930                 default:
931                         PBD::error << _("CoreAudioBackend::register_port: Invalid Data Type.") << endmsg;
932                         return 0;
933         }
934
935         _ports.push_back (port);
936
937         return port;
938 }
939
940 void
941 CoreAudioBackend::unregister_port (PortEngine::PortHandle port_handle)
942 {
943         if (!_run) {
944                 return;
945         }
946         CoreBackendPort* port = static_cast<CoreBackendPort*>(port_handle);
947         std::vector<CoreBackendPort*>::iterator i = std::find (_ports.begin (), _ports.end (), static_cast<CoreBackendPort*>(port_handle));
948         if (i == _ports.end ()) {
949                 PBD::error << _("CoreAudioBackend::unregister_port: Failed to find port") << endmsg;
950                 return;
951         }
952         disconnect_all(port_handle);
953         _ports.erase (i);
954         delete port;
955 }
956
957 int
958 CoreAudioBackend::register_system_audio_ports()
959 {
960         LatencyRange lr;
961
962         const uint32_t a_ins = _n_inputs;
963         const uint32_t a_out = _n_outputs;
964
965         const uint32_t coreaudio_reported_input_latency = _pcmio->get_latency(name_to_id(_input_audio_device), true);
966         const uint32_t coreaudio_reported_output_latency = _pcmio->get_latency(name_to_id(_output_audio_device), false);
967
968 #ifndef NDEBUG
969         printf("COREAUDIO LATENCY: i:%d, o:%d\n",
970                         coreaudio_reported_input_latency,
971                         coreaudio_reported_output_latency);
972 #endif
973
974         /* audio ports */
975         lr.min = lr.max = coreaudio_reported_input_latency + (_measure_latency ? 0 : _systemic_audio_input_latency);
976         for (uint32_t i = 0; i < a_ins; ++i) {
977                 char tmp[64];
978                 snprintf(tmp, sizeof(tmp), "system:capture_%d", i+1);
979                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
980                 if (!p) return -1;
981                 set_latency_range (p, false, lr);
982                 CoreBackendPort *cp = static_cast<CoreBackendPort*>(p);
983                 cp->set_pretty_name (_pcmio->cached_port_name(i, true));
984                 _system_inputs.push_back(cp);
985         }
986
987         lr.min = lr.max = coreaudio_reported_output_latency + (_measure_latency ? 0 : _systemic_audio_output_latency);
988         for (uint32_t i = 0; i < a_out; ++i) {
989                 char tmp[64];
990                 snprintf(tmp, sizeof(tmp), "system:playback_%d", i+1);
991                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
992                 if (!p) return -1;
993                 set_latency_range (p, true, lr);
994                 CoreBackendPort *cp = static_cast<CoreBackendPort*>(p);
995                 cp->set_pretty_name (_pcmio->cached_port_name(i, false));
996                 _system_outputs.push_back(cp);
997         }
998         return 0;
999 }
1000
1001 void
1002 CoreAudioBackend::coremidi_rediscover()
1003 {
1004         if (!_run) { return; }
1005         assert(_midi_driver_option == _("CoreMidi"));
1006
1007         pthread_mutex_lock (&_process_callback_mutex);
1008
1009         for (std::vector<CoreBackendPort*>::iterator it = _system_midi_out.begin (); it != _system_midi_out.end ();) {
1010                 bool found = false;
1011                 for (size_t i = 0; i < _midiio->n_midi_outputs(); ++i) {
1012                         if ((*it)->name() == _midiio->port_id(i, false)) {
1013                                 found = true;
1014                                 break;
1015                         }
1016                 }
1017                 if (found) {
1018                         ++it;
1019                 } else {
1020 #ifndef NDEBUG
1021                         printf("unregister MIDI Output: %s\n", (*it)->name().c_str());
1022 #endif
1023                         _port_change_flag = true;
1024                         unregister_port((*it));
1025                         it = _system_midi_out.erase(it);
1026                 }
1027         }
1028
1029         for (std::vector<CoreBackendPort*>::iterator it = _system_midi_in.begin (); it != _system_midi_in.end ();) {
1030                 bool found = false;
1031                 for (size_t i = 0; i < _midiio->n_midi_inputs(); ++i) {
1032                         if ((*it)->name() == _midiio->port_id(i, true)) {
1033                                 found = true;
1034                                 break;
1035                         }
1036                 }
1037                 if (found) {
1038                         ++it;
1039                 } else {
1040 #ifndef NDEBUG
1041                         printf("unregister MIDI Input: %s\n", (*it)->name().c_str());
1042 #endif
1043                         _port_change_flag = true;
1044                         unregister_port((*it));
1045                         it = _system_midi_in.erase(it);
1046                 }
1047         }
1048
1049         for (size_t i = 0; i < _midiio->n_midi_inputs(); ++i) {
1050                 std::string name = _midiio->port_id(i, true);
1051                 if (find_port_in(_system_midi_in, name)) {
1052                         continue;
1053                 }
1054
1055 #ifndef NDEBUG
1056                 printf("register MIDI Input: %s\n", name.c_str());
1057 #endif
1058                 PortHandle p = add_port(name, DataType::MIDI, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
1059                 if (!p) {
1060                         fprintf(stderr, "failed to register MIDI IN: %s\n", name.c_str());
1061                         continue;
1062                 }
1063                 LatencyRange lr;
1064                 lr.min = lr.max = _samples_per_period; // TODO add per-port midi-systemic latency
1065                 set_latency_range (p, false, lr);
1066                 CoreBackendPort *pp = static_cast<CoreBackendPort*>(p);
1067                 pp->set_pretty_name(_midiio->port_name(i, true));
1068                 _system_midi_in.push_back(pp);
1069                 _port_change_flag = true;
1070         }
1071
1072         for (size_t i = 0; i < _midiio->n_midi_outputs(); ++i) {
1073                 std::string name = _midiio->port_id(i, false);
1074                 if (find_port_in(_system_midi_out, name)) {
1075                         continue;
1076                 }
1077
1078 #ifndef NDEBUG
1079                 printf("register MIDI OUT: %s\n", name.c_str());
1080 #endif
1081                 PortHandle p = add_port(name, DataType::MIDI, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
1082                 if (!p) {
1083                         fprintf(stderr, "failed to register MIDI OUT: %s\n", name.c_str());
1084                         continue;
1085                 }
1086                 LatencyRange lr;
1087                 lr.min = lr.max = _samples_per_period; // TODO add per-port midi-systemic latency
1088                 set_latency_range (p, false, lr);
1089                 CoreBackendPort *pp = static_cast<CoreBackendPort*>(p);
1090                 pp->set_pretty_name(_midiio->port_name(i, false));
1091                 _system_midi_out.push_back(pp);
1092                 _port_change_flag = true;
1093         }
1094
1095
1096         assert(_system_midi_out.size() == _midiio->n_midi_outputs());
1097         assert(_system_midi_in.size() == _midiio->n_midi_inputs());
1098
1099         pthread_mutex_unlock (&_process_callback_mutex);
1100 }
1101
1102 void
1103 CoreAudioBackend::unregister_ports (bool system_only)
1104 {
1105         size_t i = 0;
1106         _system_inputs.clear();
1107         _system_outputs.clear();
1108         _system_midi_in.clear();
1109         _system_midi_out.clear();
1110         while (i <  _ports.size ()) {
1111                 CoreBackendPort* port = _ports[i];
1112                 if (! system_only || (port->is_physical () && port->is_terminal ())) {
1113                         port->disconnect_all ();
1114                         delete port;
1115                         _ports.erase (_ports.begin() + i);
1116                 } else {
1117                         ++i;
1118                 }
1119         }
1120 }
1121
1122 int
1123 CoreAudioBackend::connect (const std::string& src, const std::string& dst)
1124 {
1125         CoreBackendPort* src_port = find_port (src);
1126         CoreBackendPort* dst_port = find_port (dst);
1127
1128         if (!src_port) {
1129                 PBD::error << _("CoreAudioBackend::connect: Invalid Source port:")
1130                                 << " (" << src <<")" << endmsg;
1131                 return -1;
1132         }
1133         if (!dst_port) {
1134                 PBD::error << _("CoreAudioBackend::connect: Invalid Destination port:")
1135                         << " (" << dst <<")" << endmsg;
1136                 return -1;
1137         }
1138         return src_port->connect (dst_port);
1139 }
1140
1141 int
1142 CoreAudioBackend::disconnect (const std::string& src, const std::string& dst)
1143 {
1144         CoreBackendPort* src_port = find_port (src);
1145         CoreBackendPort* dst_port = find_port (dst);
1146
1147         if (!src_port || !dst_port) {
1148                 PBD::error << _("CoreAudioBackend::disconnect: Invalid Port(s)") << endmsg;
1149                 return -1;
1150         }
1151         return src_port->disconnect (dst_port);
1152 }
1153
1154 int
1155 CoreAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
1156 {
1157         CoreBackendPort* dst_port = find_port (dst);
1158         if (!valid_port (src)) {
1159                 PBD::error << _("CoreAudioBackend::connect: Invalid Source Port Handle") << endmsg;
1160                 return -1;
1161         }
1162         if (!dst_port) {
1163                 PBD::error << _("CoreAudioBackend::connect: Invalid Destination Port")
1164                         << " (" << dst << ")" << endmsg;
1165                 return -1;
1166         }
1167         return static_cast<CoreBackendPort*>(src)->connect (dst_port);
1168 }
1169
1170 int
1171 CoreAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
1172 {
1173         CoreBackendPort* dst_port = find_port (dst);
1174         if (!valid_port (src) || !dst_port) {
1175                 PBD::error << _("CoreAudioBackend::disconnect: Invalid Port(s)") << endmsg;
1176                 return -1;
1177         }
1178         return static_cast<CoreBackendPort*>(src)->disconnect (dst_port);
1179 }
1180
1181 int
1182 CoreAudioBackend::disconnect_all (PortEngine::PortHandle port)
1183 {
1184         if (!valid_port (port)) {
1185                 PBD::error << _("CoreAudioBackend::disconnect_all: Invalid Port") << endmsg;
1186                 return -1;
1187         }
1188         static_cast<CoreBackendPort*>(port)->disconnect_all ();
1189         return 0;
1190 }
1191
1192 bool
1193 CoreAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
1194 {
1195         if (!valid_port (port)) {
1196                 PBD::error << _("CoreAudioBackend::disconnect_all: Invalid Port") << endmsg;
1197                 return false;
1198         }
1199         return static_cast<CoreBackendPort*>(port)->is_connected ();
1200 }
1201
1202 bool
1203 CoreAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
1204 {
1205         CoreBackendPort* dst_port = find_port (dst);
1206         if (!valid_port (src) || !dst_port) {
1207                 PBD::error << _("CoreAudioBackend::connected_to: Invalid Port") << endmsg;
1208                 return false;
1209         }
1210         return static_cast<CoreBackendPort*>(src)->is_connected (dst_port);
1211 }
1212
1213 bool
1214 CoreAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
1215 {
1216         if (!valid_port (port)) {
1217                 PBD::error << _("CoreAudioBackend::physically_connected: Invalid Port") << endmsg;
1218                 return false;
1219         }
1220         return static_cast<CoreBackendPort*>(port)->is_physically_connected ();
1221 }
1222
1223 int
1224 CoreAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
1225 {
1226         if (!valid_port (port)) {
1227                 PBD::error << _("CoreAudioBackend::get_connections: Invalid Port") << endmsg;
1228                 return -1;
1229         }
1230
1231         assert (0 == names.size ());
1232
1233         const std::vector<CoreBackendPort*>& connected_ports = static_cast<CoreBackendPort*>(port)->get_connections ();
1234
1235         for (std::vector<CoreBackendPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
1236                 names.push_back ((*i)->name ());
1237         }
1238
1239         return (int)names.size ();
1240 }
1241
1242 /* MIDI */
1243 int
1244 CoreAudioBackend::midi_event_get (
1245                 pframes_t& timestamp,
1246                 size_t& size, uint8_t** buf, void* port_buffer,
1247                 uint32_t event_index)
1248 {
1249         if (!buf || !port_buffer) return -1;
1250         CoreMidiBuffer& source = * static_cast<CoreMidiBuffer*>(port_buffer);
1251         if (event_index >= source.size ()) {
1252                 return -1;
1253         }
1254         CoreMidiEvent * const event = source[event_index].get ();
1255
1256         timestamp = event->timestamp ();
1257         size = event->size ();
1258         *buf = event->data ();
1259         return 0;
1260 }
1261
1262 int
1263 CoreAudioBackend::midi_event_put (
1264                 void* port_buffer,
1265                 pframes_t timestamp,
1266                 const uint8_t* buffer, size_t size)
1267 {
1268         if (!buffer || !port_buffer) return -1;
1269         CoreMidiBuffer& dst = * static_cast<CoreMidiBuffer*>(port_buffer);
1270         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
1271 #ifndef NDEBUG
1272                 // nevermind, ::get_buffer() sorts events
1273                 fprintf (stderr, "CoreMidiBuffer: unordered event: %d > %d\n",
1274                                 (pframes_t)dst.back ()->timestamp (), timestamp);
1275 #endif
1276         }
1277         dst.push_back (boost::shared_ptr<CoreMidiEvent>(new CoreMidiEvent (timestamp, buffer, size)));
1278         return 0;
1279 }
1280
1281 uint32_t
1282 CoreAudioBackend::get_midi_event_count (void* port_buffer)
1283 {
1284         if (!port_buffer) return 0;
1285         return static_cast<CoreMidiBuffer*>(port_buffer)->size ();
1286 }
1287
1288 void
1289 CoreAudioBackend::midi_clear (void* port_buffer)
1290 {
1291         if (!port_buffer) return;
1292         CoreMidiBuffer * buf = static_cast<CoreMidiBuffer*>(port_buffer);
1293         assert (buf);
1294         buf->clear ();
1295 }
1296
1297 /* Monitoring */
1298
1299 bool
1300 CoreAudioBackend::can_monitor_input () const
1301 {
1302         return false;
1303 }
1304
1305 int
1306 CoreAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1307 {
1308         return -1;
1309 }
1310
1311 int
1312 CoreAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1313 {
1314         return -1;
1315 }
1316
1317 bool
1318 CoreAudioBackend::monitoring_input (PortEngine::PortHandle)
1319 {
1320         return false;
1321 }
1322
1323 /* Latency management */
1324
1325 void
1326 CoreAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1327 {
1328         if (!valid_port (port)) {
1329                 PBD::error << _("CoreBackendPort::set_latency_range (): invalid port.") << endmsg;
1330         }
1331         static_cast<CoreBackendPort*>(port)->set_latency_range (latency_range, for_playback);
1332 }
1333
1334 LatencyRange
1335 CoreAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1336 {
1337         LatencyRange r;
1338         if (!valid_port (port)) {
1339                 PBD::error << _("CoreBackendPort::get_latency_range (): invalid port.") << endmsg;
1340                 r.min = 0;
1341                 r.max = 0;
1342                 return r;
1343         }
1344         CoreBackendPort* p = static_cast<CoreBackendPort*>(port);
1345         assert(p);
1346
1347         r = p->latency_range (for_playback);
1348         if (p->is_physical() && p->is_terminal() && p->type() == DataType::AUDIO) {
1349                 if (p->is_input() && for_playback) {
1350                         r.min += _samples_per_period;
1351                         r.max += _samples_per_period;
1352                 }
1353                 if (p->is_output() && !for_playback) {
1354                         r.min += _samples_per_period;
1355                         r.max += _samples_per_period;
1356                 }
1357         }
1358         return r;
1359 }
1360
1361 /* Discovering physical ports */
1362
1363 bool
1364 CoreAudioBackend::port_is_physical (PortEngine::PortHandle port) const
1365 {
1366         if (!valid_port (port)) {
1367                 PBD::error << _("CoreBackendPort::port_is_physical (): invalid port.") << endmsg;
1368                 return false;
1369         }
1370         return static_cast<CoreBackendPort*>(port)->is_physical ();
1371 }
1372
1373 void
1374 CoreAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1375 {
1376         for (size_t i = 0; i < _ports.size (); ++i) {
1377                 CoreBackendPort* port = _ports[i];
1378                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1379                         port_names.push_back (port->name ());
1380                 }
1381         }
1382 }
1383
1384 void
1385 CoreAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1386 {
1387         for (size_t i = 0; i < _ports.size (); ++i) {
1388                 CoreBackendPort* port = _ports[i];
1389                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1390                         port_names.push_back (port->name ());
1391                 }
1392         }
1393 }
1394
1395 ChanCount
1396 CoreAudioBackend::n_physical_outputs () const
1397 {
1398         int n_midi = 0;
1399         int n_audio = 0;
1400         for (size_t i = 0; i < _ports.size (); ++i) {
1401                 CoreBackendPort* port = _ports[i];
1402                 if (port->is_output () && port->is_physical ()) {
1403                         switch (port->type ()) {
1404                                 case DataType::AUDIO: ++n_audio; break;
1405                                 case DataType::MIDI: ++n_midi; break;
1406                                 default: break;
1407                         }
1408                 }
1409         }
1410         ChanCount cc;
1411         cc.set (DataType::AUDIO, n_audio);
1412         cc.set (DataType::MIDI, n_midi);
1413         return cc;
1414 }
1415
1416 ChanCount
1417 CoreAudioBackend::n_physical_inputs () const
1418 {
1419         int n_midi = 0;
1420         int n_audio = 0;
1421         for (size_t i = 0; i < _ports.size (); ++i) {
1422                 CoreBackendPort* port = _ports[i];
1423                 if (port->is_input () && port->is_physical ()) {
1424                         switch (port->type ()) {
1425                                 case DataType::AUDIO: ++n_audio; break;
1426                                 case DataType::MIDI: ++n_midi; break;
1427                                 default: break;
1428                         }
1429                 }
1430         }
1431         ChanCount cc;
1432         cc.set (DataType::AUDIO, n_audio);
1433         cc.set (DataType::MIDI, n_midi);
1434         return cc;
1435 }
1436
1437 /* Getting access to the data buffer for a port */
1438
1439 void*
1440 CoreAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1441 {
1442         if (!port || !valid_port (port)) return NULL;
1443         return static_cast<CoreBackendPort*>(port)->get_buffer (nframes);
1444 }
1445
1446 void
1447 CoreAudioBackend::pre_process ()
1448 {
1449         bool connections_changed = false;
1450         bool ports_changed = false;
1451         if (!pthread_mutex_trylock (&_port_callback_mutex)) {
1452                 if (_port_change_flag) {
1453                         ports_changed = true;
1454                         _port_change_flag = false;
1455                 }
1456                 if (!_port_connection_queue.empty ()) {
1457                         connections_changed = true;
1458                 }
1459                 while (!_port_connection_queue.empty ()) {
1460                         PortConnectData *c = _port_connection_queue.back ();
1461                         manager.connect_callback (c->a, c->b, c->c);
1462                         _port_connection_queue.pop_back ();
1463                         delete c;
1464                 }
1465                 pthread_mutex_unlock (&_port_callback_mutex);
1466         }
1467         if (ports_changed) {
1468                 manager.registration_callback();
1469         }
1470         if (connections_changed) {
1471                 manager.graph_order_callback();
1472         }
1473         if (connections_changed || ports_changed) {
1474                 engine.latency_callback(false);
1475                 engine.latency_callback(true);
1476         }
1477 }
1478
1479 void *
1480 CoreAudioBackend::freewheel_thread ()
1481 {
1482         _active_fw = true;
1483         bool first_run = false;
1484         /* Freewheeling - use for export.   The first call to
1485          * engine.process_callback() after engine.freewheel_callback will
1486          * if the first export cycle.
1487          * For reliable precise export timing, the calls need to be in sync.
1488          *
1489          * Furthermore we need to make sure the registered process thread
1490          * is correct.
1491          *
1492          * _freewheeling = GUI thread state as set by ::freewheel()
1493          * _freewheel = in sync here (export thread)
1494          */
1495         pthread_mutex_lock (&_freewheel_mutex);
1496         while (_run) {
1497                 // check if we should run,
1498                 if (_freewheeling != _freewheel) {
1499                         if (!_freewheeling) {
1500                                 // prepare leaving freewheeling mode
1501                                 _freewheel = false; // first mark as disabled
1502                                 _reinit_thread_callback = true; // hand over _main_thread
1503                                 _freewheel_ack = false; // prepare next handshake
1504                                 _midiio->set_enabled(true);
1505                         } else {
1506                                 first_run = true;
1507                                 _freewheel = true;
1508                         }
1509                 }
1510
1511                 if (!_freewheel || !_freewheel_ack) {
1512                         // wait for a change, we use a timed wait to
1513                         // terminate early in case some error sets _run = 0
1514                         struct timeval tv;
1515                         struct timespec ts;
1516                         gettimeofday (&tv, NULL);
1517                         ts.tv_sec = tv.tv_sec + 3;
1518                         ts.tv_nsec = 0;
1519                         pthread_cond_timedwait (&_freewheel_signal, &_freewheel_mutex, &ts);
1520                         continue;
1521                 }
1522
1523                 if (first_run) {
1524                         // tell the engine we're ready to GO.
1525                         engine.freewheel_callback (_freewheeling);
1526                         first_run = false;
1527                         _main_thread = pthread_self();
1528                         AudioEngine::thread_init_callback (this);
1529                         _midiio->set_enabled(false);
1530                 }
1531
1532                 // process port updates first in every cycle.
1533                 pre_process();
1534
1535                 // prevent coreaudio device changes
1536                 pthread_mutex_lock (&_process_callback_mutex);
1537
1538                 /* Freewheelin' */
1539                 
1540                 // clear input buffers
1541                 for (std::vector<CoreBackendPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
1542                         memset ((*it)->get_buffer (_samples_per_period), 0, _samples_per_period * sizeof (Sample));
1543                 }
1544                 for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it) {
1545                         static_cast<CoreMidiBuffer*>((*it)->get_buffer(0))->clear ();
1546                 }
1547
1548                 _last_process_start = 0;
1549                 if (engine.process_callback (_samples_per_period)) {
1550                         pthread_mutex_unlock (&_process_callback_mutex);
1551                         break;
1552                 }
1553
1554                 pthread_mutex_unlock (&_process_callback_mutex);
1555                 _dsp_load = 1.0;
1556                 Glib::usleep (100); // don't hog cpu
1557         }
1558
1559         pthread_mutex_unlock (&_freewheel_mutex);
1560
1561         _active_fw = false;
1562
1563         if (_run) {
1564                 // engine.process_callback() returner error
1565                 engine.halted_callback("CoreAudio Freehweeling aborted.");
1566         }
1567         return 0;
1568 }
1569
1570 #ifdef USE_MIDI_PARSER
1571 bool
1572 CoreAudioBackend::midi_process_byte (const uint8_t byte)
1573 {
1574         if (byte >= 0xf8) {
1575                 // Realtime
1576                 if (byte == 0xfd) {
1577                         // undefined
1578                         return false;
1579                 }
1580                 midi_prepare_byte_event (byte);
1581                 return true;
1582         }
1583         if (byte == 0xf7) {
1584                 // Sysex end
1585                 if (_status_byte == 0xf0) {
1586                         midi_record_byte (byte);
1587                         return midi_prepare_buffered_event ();
1588                 }
1589                 _total_bytes = 0;
1590                 _unbuffered_bytes = 0;
1591                 _expected_bytes = 0;
1592                 _status_byte = 0;
1593                 return false;
1594         }
1595         if (byte >= 0x80) {
1596                 // Non-realtime status byte
1597                 if (_total_bytes) {
1598                         _total_bytes = 0;
1599                         _unbuffered_bytes = 0;
1600                 }
1601                 _status_byte = byte;
1602                 switch (byte & 0xf0) {
1603                         case 0x80:
1604                         case 0x90:
1605                         case 0xa0:
1606                         case 0xb0:
1607                         case 0xe0:
1608                                 // Note On, Note Off, Aftertouch, Control Change, Pitch Wheel
1609                                 _expected_bytes = 3;
1610                                 break;
1611                         case 0xc0:
1612                         case 0xd0:
1613                                 // Program Change, Channel Pressure
1614                                 _expected_bytes = 2;
1615                                 break;
1616                         case 0xf0:
1617                                 switch (byte) {
1618                                         case 0xf0:
1619                                                 // Sysex
1620                                                 _expected_bytes = 0;
1621                                                 break;
1622                                         case 0xf1:
1623                                         case 0xf3:
1624                                                 // MTC Quarter Frame, Song Select
1625                                                 _expected_bytes = 2;
1626                                                 break;
1627                                         case 0xf2:
1628                                                 // Song Position
1629                                                 _expected_bytes = 3;
1630                                                 break;
1631                                         case 0xf4:
1632                                         case 0xf5:
1633                                                 // Undefined
1634                                                 _expected_bytes = 0;
1635                                                 _status_byte = 0;
1636                                                 return false;
1637                                         case 0xf6:
1638                                                 // Tune Request
1639                                                 midi_prepare_byte_event (byte);
1640                                                 _expected_bytes = 0;
1641                                                 _status_byte = 0;
1642                                                 return true;
1643                                 }
1644                 }
1645                 midi_record_byte (byte);
1646                 return false;
1647         }
1648         // Data byte
1649         if (! _status_byte) {
1650                 // Data bytes without a status will be discarded.
1651                 _total_bytes++;
1652                 _unbuffered_bytes++;
1653                 return false;
1654         }
1655         if (! _total_bytes) {
1656                 midi_record_byte (_status_byte);
1657         }
1658         midi_record_byte(byte);
1659         return (_total_bytes == _expected_bytes) ? midi_prepare_buffered_event() : false;
1660 }
1661 #endif
1662
1663
1664 int
1665 CoreAudioBackend::process_callback (const uint32_t n_samples, const uint64_t host_time)
1666 {
1667         uint32_t i = 0;
1668         uint64_t clock1, clock2;
1669
1670         _active_ca = true;
1671
1672         if (_run && _freewheel && !_freewheel_ack) {
1673                 // acknowledge freewheeling; hand-over thread ID
1674                 pthread_mutex_lock (&_freewheel_mutex);
1675                 if (_freewheel) _freewheel_ack = true;
1676                 pthread_cond_signal (&_freewheel_signal);
1677                 pthread_mutex_unlock (&_freewheel_mutex);
1678         }
1679
1680         if (!_run || _freewheel || _preinit) {
1681                 // NB if we return 1, the output is
1682                 // zeroed by the coreaudio callback
1683                 return 1;
1684         }
1685
1686         if (_reinit_thread_callback || _main_thread != pthread_self()) {
1687                 _reinit_thread_callback = false;
1688                 _main_thread = pthread_self();
1689                 AudioEngine::thread_init_callback (this);
1690         }
1691
1692         if (pthread_mutex_trylock (&_process_callback_mutex)) {
1693                 // block while devices are added/removed
1694 #ifndef NDEBUG
1695                 printf("Xrun due to device change\n");
1696 #endif
1697                 engine.Xrun();
1698                 return 1;
1699         }
1700         /* port-connection change */
1701         pre_process();
1702
1703         // cycle-length in usec
1704         const double nominal_time = 1e6 * n_samples / _samplerate;
1705
1706         clock1 = g_get_monotonic_time();
1707
1708         /* get midi */
1709         i=0;
1710         for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++i) {
1711                 CoreMidiBuffer* mbuf = static_cast<CoreMidiBuffer*>((*it)->get_buffer(0));
1712                 mbuf->clear();
1713                 uint64_t time_ns;
1714                 uint8_t data[128]; // matches CoreMidi's MIDIPacket
1715                 size_t size = sizeof(data);
1716                 while (_midiio->recv_event (i, nominal_time, time_ns, data, size)) {
1717                         pframes_t time = floor((float) time_ns * _samplerate * 1e-9);
1718                         assert (time < n_samples);
1719 #ifndef USE_MIDI_PARSER
1720                         midi_event_put((void*)mbuf, time, data, size);
1721 #else
1722                         for (size_t mb = 0; mb < size; ++mb) {
1723                                 if (_first_time && !(data[mb] & 0x80)) {
1724                                         // expect a status byte at the beginning or every Packet
1725                                         assert (0);
1726                                         continue;
1727                                 }
1728                                 _first_time = false;
1729
1730                                 if (midi_process_byte (data[mb])) {
1731                                         midi_event_put ((void*)mbuf, time, _parser_buffer, _event._size);
1732                                 }
1733                         }
1734 #endif
1735                         size = sizeof(data);
1736                 }
1737         }
1738
1739         /* get audio */
1740         i = 0;
1741         for (std::vector<CoreBackendPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++i) {
1742                 _pcmio->get_capture_channel (i, (float*)((*it)->get_buffer(n_samples)), n_samples);
1743         }
1744
1745         /* clear output buffers */
1746         for (std::vector<CoreBackendPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it) {
1747                 memset ((*it)->get_buffer (n_samples), 0, n_samples * sizeof (Sample));
1748         }
1749
1750         _midiio->start_cycle();
1751         _last_process_start = host_time;
1752
1753         if (engine.process_callback (n_samples)) {
1754                 fprintf(stderr, "ENGINE PROCESS ERROR\n");
1755                 //_pcmio->pcm_stop ();
1756                 _active_ca = false;
1757                 pthread_mutex_unlock (&_process_callback_mutex);
1758                 return -1;
1759         }
1760
1761         /* mixdown midi */
1762         for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it) {
1763                 static_cast<CoreMidiPort*>(*it)->get_buffer(0);
1764         }
1765
1766         /* queue outgoing midi */
1767         i = 0;
1768         for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it, ++i) {
1769 #if 0 // something's still b0rked with CoreMidiIo::send_events()
1770                 const CoreMidiBuffer *src = static_cast<const CoreMidiPort*>(*it)->const_buffer();
1771                 _midiio->send_events (i, nominal_time, (void*)src);
1772 #else // works..
1773                 const CoreMidiBuffer *src = static_cast<const CoreMidiPort*>(*it)->const_buffer();
1774                 for (CoreMidiBuffer::const_iterator mit = src->begin (); mit != src->end (); ++mit) {
1775                         _midiio->send_event (i, (*mit)->timestamp() / nominal_time, (*mit)->data(), (*mit)->size());
1776                 }
1777 #endif
1778         }
1779
1780         /* write back audio */
1781         i = 0;
1782         for (std::vector<CoreBackendPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it, ++i) {
1783                 _pcmio->set_playback_channel (i, (float const*)(*it)->get_buffer (n_samples), n_samples);
1784         }
1785
1786         _processed_samples += n_samples;
1787
1788         /* calc DSP load. */
1789         clock2 = g_get_monotonic_time();
1790         const int64_t elapsed_time = clock2 - clock1;
1791         // low pass filter
1792         const float load = elapsed_time / (float) nominal_time;
1793         if (load > _dsp_load) {
1794                 _dsp_load = load;
1795         } else {
1796                 const float a = .2 * _samples_per_period / _samplerate;
1797                 _dsp_load = _dsp_load + a * (load - _dsp_load) + 1e-12;
1798         }
1799
1800         pthread_mutex_unlock (&_process_callback_mutex);
1801         return 0;
1802 }
1803
1804 void
1805 CoreAudioBackend::error_callback ()
1806 {
1807         _pcmio->set_error_callback (NULL, NULL);
1808         _pcmio->set_sample_rate_callback (NULL, NULL);
1809         _pcmio->set_xrun_callback (NULL, NULL);
1810         _midiio->set_port_changed_callback(NULL, NULL);
1811         engine.halted_callback("CoreAudio Process aborted.");
1812         _active_ca = false;
1813 }
1814
1815 void
1816 CoreAudioBackend::xrun_callback ()
1817 {
1818         engine.Xrun ();
1819 }
1820
1821 void
1822 CoreAudioBackend::buffer_size_callback ()
1823 {
1824         uint32_t bs = _pcmio->samples_per_period();
1825         if (bs == _samples_per_period) {
1826                 return;
1827         }
1828         _samples_per_period = bs;
1829         engine.buffer_size_change (_samples_per_period);
1830 }
1831
1832 void
1833 CoreAudioBackend::sample_rate_callback ()
1834 {
1835         if (_preinit) {
1836 #ifndef NDEBUG
1837                 printf("Samplerate change during initialization.\n");
1838 #endif
1839                 return;
1840         }
1841         _pcmio->set_error_callback (NULL, NULL);
1842         _pcmio->set_sample_rate_callback (NULL, NULL);
1843         _pcmio->set_xrun_callback (NULL, NULL);
1844         _midiio->set_port_changed_callback(NULL, NULL);
1845         engine.halted_callback("Sample Rate Changed.");
1846         stop();
1847 }
1848
1849 void
1850 CoreAudioBackend::hw_changed_callback ()
1851 {
1852         _reinit_thread_callback = true;
1853         engine.request_device_list_update();
1854 }
1855
1856 /******************************************************************************/
1857
1858 static boost::shared_ptr<CoreAudioBackend> _instance;
1859
1860 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
1861 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
1862 static int deinstantiate ();
1863 static bool already_configured ();
1864 static bool available ();
1865
1866 static ARDOUR::AudioBackendInfo _descriptor = {
1867         "CoreAudio",
1868         instantiate,
1869         deinstantiate,
1870         backend_factory,
1871         already_configured,
1872         available
1873 };
1874
1875 static boost::shared_ptr<AudioBackend>
1876 backend_factory (AudioEngine& e)
1877 {
1878         if (!_instance) {
1879                 _instance.reset (new CoreAudioBackend (e, _descriptor));
1880         }
1881         return _instance;
1882 }
1883
1884 static int
1885 instantiate (const std::string& arg1, const std::string& /* arg2 */)
1886 {
1887         s_instance_name = arg1;
1888         return 0;
1889 }
1890
1891 static int
1892 deinstantiate ()
1893 {
1894         _instance.reset ();
1895         return 0;
1896 }
1897
1898 static bool
1899 already_configured ()
1900 {
1901         return false;
1902 }
1903
1904 static bool
1905 available ()
1906 {
1907         return true;
1908 }
1909
1910 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
1911 {
1912         return &_descriptor;
1913 }
1914
1915
1916 /******************************************************************************/
1917 CoreBackendPort::CoreBackendPort (CoreAudioBackend &b, const std::string& name, PortFlags flags)
1918         : _osx_backend (b)
1919         , _name  (name)
1920         , _flags (flags)
1921 {
1922         _capture_latency_range.min = 0;
1923         _capture_latency_range.max = 0;
1924         _playback_latency_range.min = 0;
1925         _playback_latency_range.max = 0;
1926 }
1927
1928 CoreBackendPort::~CoreBackendPort () {
1929         disconnect_all ();
1930 }
1931
1932
1933 int CoreBackendPort::connect (CoreBackendPort *port)
1934 {
1935         if (!port) {
1936                 PBD::error << _("CoreBackendPort::connect (): invalid (null) port") << endmsg;
1937                 return -1;
1938         }
1939
1940         if (type () != port->type ()) {
1941                 PBD::error << _("CoreBackendPort::connect (): wrong port-type") << endmsg;
1942                 return -1;
1943         }
1944
1945         if (is_output () && port->is_output ()) {
1946                 PBD::error << _("CoreBackendPort::connect (): cannot inter-connect output ports.") << endmsg;
1947                 return -1;
1948         }
1949
1950         if (is_input () && port->is_input ()) {
1951                 PBD::error << _("CoreBackendPort::connect (): cannot inter-connect input ports.") << endmsg;
1952                 return -1;
1953         }
1954
1955         if (this == port) {
1956                 PBD::error << _("CoreBackendPort::connect (): cannot self-connect ports.") << endmsg;
1957                 return -1;
1958         }
1959
1960         if (is_connected (port)) {
1961 #if 0 // don't bother to warn about this for now. just ignore it
1962                 PBD::error << _("CoreBackendPort::connect (): ports are already connected:")
1963                         << " (" << name () << ") -> (" << port->name () << ")"
1964                         << endmsg;
1965 #endif
1966                 return -1;
1967         }
1968
1969         _connect (port, true);
1970         return 0;
1971 }
1972
1973
1974 void CoreBackendPort::_connect (CoreBackendPort *port, bool callback)
1975 {
1976         _connections.push_back (port);
1977         if (callback) {
1978                 port->_connect (this, false);
1979                 _osx_backend.port_connect_callback (name(),  port->name(), true);
1980         }
1981 }
1982
1983 int CoreBackendPort::disconnect (CoreBackendPort *port)
1984 {
1985         if (!port) {
1986                 PBD::error << _("CoreBackendPort::disconnect (): invalid (null) port") << endmsg;
1987                 return -1;
1988         }
1989
1990         if (!is_connected (port)) {
1991                 PBD::error << _("CoreBackendPort::disconnect (): ports are not connected:")
1992                         << " (" << name () << ") -> (" << port->name () << ")"
1993                         << endmsg;
1994                 return -1;
1995         }
1996         _disconnect (port, true);
1997         return 0;
1998 }
1999
2000 void CoreBackendPort::_disconnect (CoreBackendPort *port, bool callback)
2001 {
2002         std::vector<CoreBackendPort*>::iterator it = std::find (_connections.begin (), _connections.end (), port);
2003
2004         assert (it != _connections.end ());
2005
2006         _connections.erase (it);
2007
2008         if (callback) {
2009                 port->_disconnect (this, false);
2010                 _osx_backend.port_connect_callback (name(),  port->name(), false);
2011         }
2012 }
2013
2014
2015 void CoreBackendPort::disconnect_all ()
2016 {
2017         while (!_connections.empty ()) {
2018                 _connections.back ()->_disconnect (this, false);
2019                 _osx_backend.port_connect_callback (name(),  _connections.back ()->name(), false);
2020                 _connections.pop_back ();
2021         }
2022 }
2023
2024 bool
2025 CoreBackendPort::is_connected (const CoreBackendPort *port) const
2026 {
2027         return std::find (_connections.begin (), _connections.end (), port) != _connections.end ();
2028 }
2029
2030 bool CoreBackendPort::is_physically_connected () const
2031 {
2032         for (std::vector<CoreBackendPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
2033                 if ((*it)->is_physical ()) {
2034                         return true;
2035                 }
2036         }
2037         return false;
2038 }
2039
2040 /******************************************************************************/
2041
2042 CoreAudioPort::CoreAudioPort (CoreAudioBackend &b, const std::string& name, PortFlags flags)
2043         : CoreBackendPort (b, name, flags)
2044 {
2045         memset (_buffer, 0, sizeof (_buffer));
2046         mlock(_buffer, sizeof (_buffer));
2047 }
2048
2049 CoreAudioPort::~CoreAudioPort () { }
2050
2051 void* CoreAudioPort::get_buffer (pframes_t n_samples)
2052 {
2053         if (is_input ()) {
2054                 std::vector<CoreBackendPort*>::const_iterator it = get_connections ().begin ();
2055                 if (it == get_connections ().end ()) {
2056                         memset (_buffer, 0, n_samples * sizeof (Sample));
2057                 } else {
2058                         CoreAudioPort const * source = static_cast<const CoreAudioPort*>(*it);
2059                         assert (source && source->is_output ());
2060                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
2061                         while (++it != get_connections ().end ()) {
2062                                 source = static_cast<const CoreAudioPort*>(*it);
2063                                 assert (source && source->is_output ());
2064                                 Sample* dst = buffer ();
2065                                 const Sample* src = source->const_buffer ();
2066                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
2067                                         *dst += *src;
2068                                 }
2069                         }
2070                 }
2071         }
2072         return _buffer;
2073 }
2074
2075
2076 CoreMidiPort::CoreMidiPort (CoreAudioBackend &b, const std::string& name, PortFlags flags)
2077         : CoreBackendPort (b, name, flags)
2078         , _n_periods (1)
2079         , _bufperiod (0)
2080 {
2081         _buffer[0].clear ();
2082         _buffer[1].clear ();
2083 }
2084
2085 CoreMidiPort::~CoreMidiPort () { }
2086
2087 struct MidiEventSorter {
2088         bool operator() (const boost::shared_ptr<CoreMidiEvent>& a, const boost::shared_ptr<CoreMidiEvent>& b) {
2089                 return *a < *b;
2090         }
2091 };
2092
2093 void* CoreMidiPort::get_buffer (pframes_t /* nframes */)
2094 {
2095         if (is_input ()) {
2096                 (_buffer[_bufperiod]).clear ();
2097                 for (std::vector<CoreBackendPort*>::const_iterator i = get_connections ().begin ();
2098                                 i != get_connections ().end ();
2099                                 ++i) {
2100                         const CoreMidiBuffer * src = static_cast<const CoreMidiPort*>(*i)->const_buffer ();
2101                         for (CoreMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
2102                                 (_buffer[_bufperiod]).push_back (boost::shared_ptr<CoreMidiEvent>(new CoreMidiEvent (**it)));
2103                         }
2104                 }
2105                 std::sort ((_buffer[_bufperiod]).begin (), (_buffer[_bufperiod]).end (), MidiEventSorter());
2106         }
2107         return &(_buffer[_bufperiod]);
2108 }
2109
2110 CoreMidiEvent::CoreMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
2111         : _size (size)
2112         , _timestamp (timestamp)
2113         , _data (0)
2114 {
2115         if (size > 0) {
2116                 _data = (uint8_t*) malloc (size);
2117                 memcpy (_data, data, size);
2118         }
2119 }
2120
2121 CoreMidiEvent::CoreMidiEvent (const CoreMidiEvent& other)
2122         : _size (other.size ())
2123         , _timestamp (other.timestamp ())
2124         , _data (0)
2125 {
2126         if (other.size () && other.const_data ()) {
2127                 _data = (uint8_t*) malloc (other.size ());
2128                 memcpy (_data, other.const_data (), other.size ());
2129         }
2130 };
2131
2132 CoreMidiEvent::~CoreMidiEvent () {
2133         free (_data);
2134 };