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