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