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