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