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