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