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