0047721d81f1613b5c556e9b676e6eb2b4ab3745
[ardour.git] / libs / backends / coreaudio / coreaudio_backend.cc
1 /*
2  * Copyright (C) 2014 Robin Gareus <robin@gareus.org>
3  * Copyright (C) 2013 Paul Davis
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19
20 #include <regex.h>
21 #include <sys/mman.h>
22 #include <sys/time.h>
23
24 #include <glibmm.h>
25
26 #include "coreaudio_backend.h"
27 #include "rt_thread.h"
28
29 #include "pbd/compose.h"
30 #include "pbd/error.h"
31 #include "pbd/file_utils.h"
32 #include "ardour/filesystem_paths.h"
33 #include "ardour/port_manager.h"
34 #include "i18n.h"
35
36 using namespace ARDOUR;
37
38 static std::string s_instance_name;
39 size_t CoreAudioBackend::_max_buffer_size = 8192;
40 std::vector<std::string> CoreAudioBackend::_midi_options;
41 std::vector<AudioBackend::DeviceStatus> CoreAudioBackend::_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                 pthread_attr_destroy (&attr);
824         }
825
826         _threads.push_back (thread_id);
827         return 0;
828 }
829
830 int
831 CoreAudioBackend::join_process_threads ()
832 {
833         int rv = 0;
834
835         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
836         {
837                 void *status;
838                 if (pthread_join (*i, &status)) {
839                         PBD::error << _("AudioEngine: cannot terminate process thread.") << endmsg;
840                         rv -= 1;
841                 }
842         }
843         _threads.clear ();
844         return rv;
845 }
846
847 bool
848 CoreAudioBackend::in_process_thread ()
849 {
850         if (pthread_equal (_main_thread, pthread_self()) != 0) {
851                 return true;
852         }
853
854         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
855         {
856                 if (pthread_equal (*i, pthread_self ()) != 0) {
857                         return true;
858                 }
859         }
860         return false;
861 }
862
863 uint32_t
864 CoreAudioBackend::process_thread_count ()
865 {
866         return _threads.size ();
867 }
868
869 void
870 CoreAudioBackend::update_latencies ()
871 {
872         // trigger latency callback in RT thread (locked graph)
873         port_connect_add_remove_callback();
874 }
875
876 /* PORTENGINE API */
877
878 void*
879 CoreAudioBackend::private_handle () const
880 {
881         return NULL;
882 }
883
884 const std::string&
885 CoreAudioBackend::my_name () const
886 {
887         return _instance_name;
888 }
889
890 bool
891 CoreAudioBackend::available () const
892 {
893         return _run && _active_fw && _active_ca;
894 }
895
896 uint32_t
897 CoreAudioBackend::port_name_size () const
898 {
899         return 256;
900 }
901
902 int
903 CoreAudioBackend::set_port_name (PortEngine::PortHandle port, const std::string& name)
904 {
905         if (!valid_port (port)) {
906                 PBD::warning << _("CoreAudioBackend::set_port_name: Invalid Port(s)") << endmsg;
907                 return -1;
908         }
909         return static_cast<CoreBackendPort*>(port)->set_name (_instance_name + ":" + name);
910 }
911
912 std::string
913 CoreAudioBackend::get_port_name (PortEngine::PortHandle port) const
914 {
915         if (!valid_port (port)) {
916                 PBD::warning << _("CoreAudioBackend::get_port_name: Invalid Port(s)") << endmsg;
917                 return std::string ();
918         }
919         return static_cast<CoreBackendPort*>(port)->name ();
920 }
921
922 int
923 CoreAudioBackend::get_port_property (PortHandle port, const std::string& key, std::string& value, std::string& type) const
924 {
925         if (!valid_port (port)) {
926                 PBD::warning << _("CoreAudioBackend::get_port_property: Invalid Port(s)") << endmsg;
927                 return -1;
928         }
929         if (key == "http://jackaudio.org/metadata/pretty-name") {
930                 type = "";
931                 value = static_cast<CoreBackendPort*>(port)->pretty_name ();
932                 if (!value.empty()) {
933                         return 0;
934                 }
935         }
936         return -1;
937 }
938
939 int
940 CoreAudioBackend::set_port_property (PortHandle port, const std::string& key, const std::string& value, const std::string& type)
941 {
942         if (!valid_port (port)) {
943                 PBD::warning << _("CoreAudioBackend::set_port_property: Invalid Port(s)") << endmsg;
944                 return -1;
945         }
946         if (key == "http://jackaudio.org/metadata/pretty-name" && type.empty ()) {
947                 static_cast<CoreBackendPort*>(port)->set_pretty_name (value);
948                 return 0;
949         }
950         return -1;
951 }
952
953 PortEngine::PortHandle
954 CoreAudioBackend::get_port_by_name (const std::string& name) const
955 {
956         PortHandle port = (PortHandle) find_port (name);
957         return port;
958 }
959
960 int
961 CoreAudioBackend::get_ports (
962         const std::string& port_name_pattern,
963         DataType type, PortFlags flags,
964         std::vector<std::string>& port_names) const
965 {
966         int rv = 0;
967         regex_t port_regex;
968         bool use_regexp = false;
969         if (port_name_pattern.size () > 0) {
970                 if (!regcomp (&port_regex, port_name_pattern.c_str (), REG_EXTENDED|REG_NOSUB)) {
971                         use_regexp = true;
972                 }
973         }
974
975         for (PortIndex::iterator i = _ports.begin (); i != _ports.end (); ++i) {
976                 CoreBackendPort* port = *i;
977                 if ((port->type () == type) && flags == (port->flags () & flags)) {
978                         if (!use_regexp || !regexec (&port_regex, port->name ().c_str (), 0, NULL, 0)) {
979                                 port_names.push_back (port->name ());
980                                 ++rv;
981                         }
982                 }
983         }
984         if (use_regexp) {
985                 regfree (&port_regex);
986         }
987         return rv;
988 }
989
990 DataType
991 CoreAudioBackend::port_data_type (PortEngine::PortHandle port) const
992 {
993         if (!valid_port (port)) {
994                 return DataType::NIL;
995         }
996         return static_cast<CoreBackendPort*>(port)->type ();
997 }
998
999 PortEngine::PortHandle
1000 CoreAudioBackend::register_port (
1001         const std::string& name,
1002         ARDOUR::DataType type,
1003         ARDOUR::PortFlags flags)
1004 {
1005         if (name.size () == 0) { return 0; }
1006         if (flags & IsPhysical) { return 0; }
1007         return add_port (_instance_name + ":" + name, type, flags);
1008 }
1009
1010 PortEngine::PortHandle
1011 CoreAudioBackend::add_port (
1012         const std::string& name,
1013         ARDOUR::DataType type,
1014         ARDOUR::PortFlags flags)
1015 {
1016         assert(name.size ());
1017         if (find_port (name)) {
1018                 PBD::warning << _("CoreAudioBackend::register_port: Port already exists:")
1019                              << " (" << name << ")" << endmsg;
1020                 return 0;
1021         }
1022         CoreBackendPort* port = NULL;
1023         switch (type) {
1024         case DataType::AUDIO:
1025                 port = new CoreAudioPort (*this, name, flags);
1026                 break;
1027         case DataType::MIDI:
1028                 port = new CoreMidiPort (*this, name, flags);
1029                 break;
1030         default:
1031                 PBD::error << _("CoreAudioBackend::register_port: Invalid Data Type.") << endmsg;
1032                 return 0;
1033         }
1034
1035         _ports.insert (port);
1036         _portmap.insert (make_pair (name, port));
1037
1038         return port;
1039 }
1040
1041 void
1042 CoreAudioBackend::unregister_port (PortEngine::PortHandle port_handle)
1043 {
1044         if (!_run) {
1045                 return;
1046         }
1047         CoreBackendPort* port = static_cast<CoreBackendPort*>(port_handle);
1048         PortIndex::iterator i = _ports.find (static_cast<CoreBackendPort*>(port_handle));
1049         if (i == _ports.end ()) {
1050                 PBD::warning << _("CoreAudioBackend::unregister_port: Failed to find port") << endmsg;
1051                 return;
1052         }
1053         disconnect_all(port_handle);
1054         _portmap.erase (port->name());
1055         _ports.erase (i);
1056         delete port;
1057 }
1058
1059 int
1060 CoreAudioBackend::register_system_audio_ports()
1061 {
1062         LatencyRange lr;
1063
1064         const uint32_t a_ins = _n_inputs;
1065         const uint32_t a_out = _n_outputs;
1066
1067         const uint32_t coreaudio_reported_input_latency = _pcmio->get_latency(name_to_id(_input_audio_device), true);
1068         const uint32_t coreaudio_reported_output_latency = _pcmio->get_latency(name_to_id(_output_audio_device), false);
1069
1070 #ifndef NDEBUG
1071         printf("COREAUDIO LATENCY: i:%d, o:%d\n",
1072                coreaudio_reported_input_latency,
1073                coreaudio_reported_output_latency);
1074 #endif
1075
1076         /* audio ports */
1077         lr.min = lr.max = coreaudio_reported_input_latency + (_measure_latency ? 0 : _systemic_audio_input_latency);
1078         for (uint32_t i = 0; i < a_ins; ++i) {
1079                 char tmp[64];
1080                 snprintf(tmp, sizeof(tmp), "system:capture_%d", i+1);
1081                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
1082                 if (!p) return -1;
1083                 set_latency_range (p, false, lr);
1084                 CoreBackendPort *cp = static_cast<CoreBackendPort*>(p);
1085                 cp->set_pretty_name (_pcmio->cached_port_name(i, true));
1086                 _system_inputs.push_back(cp);
1087         }
1088
1089         lr.min = lr.max = coreaudio_reported_output_latency + (_measure_latency ? 0 : _systemic_audio_output_latency);
1090         for (uint32_t i = 0; i < a_out; ++i) {
1091                 char tmp[64];
1092                 snprintf(tmp, sizeof(tmp), "system:playback_%d", i+1);
1093                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
1094                 if (!p) return -1;
1095                 set_latency_range (p, true, lr);
1096                 CoreBackendPort *cp = static_cast<CoreBackendPort*>(p);
1097                 cp->set_pretty_name (_pcmio->cached_port_name(i, false));
1098                 _system_outputs.push_back(cp);
1099         }
1100         return 0;
1101 }
1102
1103 void
1104 CoreAudioBackend::coremidi_rediscover()
1105 {
1106         if (!_run) { return; }
1107         assert(_midi_driver_option == _("CoreMidi"));
1108
1109         pthread_mutex_lock (&_process_callback_mutex);
1110
1111         for (std::vector<CoreBackendPort*>::iterator it = _system_midi_out.begin (); it != _system_midi_out.end ();) {
1112                 bool found = false;
1113                 for (size_t i = 0; i < _midiio->n_midi_outputs(); ++i) {
1114                         if ((*it)->name() == _midiio->port_id(i, false)) {
1115                                 found = true;
1116                                 break;
1117                         }
1118                 }
1119                 if (found) {
1120                         ++it;
1121                 } else {
1122 #ifndef NDEBUG
1123                         printf("unregister MIDI Output: %s\n", (*it)->name().c_str());
1124 #endif
1125                         _port_change_flag = true;
1126                         unregister_port((*it));
1127                         it = _system_midi_out.erase(it);
1128                 }
1129         }
1130
1131         for (std::vector<CoreBackendPort*>::iterator it = _system_midi_in.begin (); it != _system_midi_in.end ();) {
1132                 bool found = false;
1133                 for (size_t i = 0; i < _midiio->n_midi_inputs(); ++i) {
1134                         if ((*it)->name() == _midiio->port_id(i, true)) {
1135                                 found = true;
1136                                 break;
1137                         }
1138                 }
1139                 if (found) {
1140                         ++it;
1141                 } else {
1142 #ifndef NDEBUG
1143                         printf("unregister MIDI Input: %s\n", (*it)->name().c_str());
1144 #endif
1145                         _port_change_flag = true;
1146                         unregister_port((*it));
1147                         it = _system_midi_in.erase(it);
1148                 }
1149         }
1150
1151         for (size_t i = 0; i < _midiio->n_midi_inputs(); ++i) {
1152                 std::string name = _midiio->port_id(i, true);
1153                 if (find_port_in(_system_midi_in, name)) {
1154                         continue;
1155                 }
1156
1157 #ifndef NDEBUG
1158                 printf("register MIDI Input: %s\n", name.c_str());
1159 #endif
1160                 PortHandle p = add_port(name, DataType::MIDI, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
1161                 if (!p) {
1162                         fprintf(stderr, "failed to register MIDI IN: %s\n", name.c_str());
1163                         continue;
1164                 }
1165                 LatencyRange lr;
1166                 lr.min = lr.max = _samples_per_period; // TODO add per-port midi-systemic latency
1167                 set_latency_range (p, false, lr);
1168                 CoreBackendPort *pp = static_cast<CoreBackendPort*>(p);
1169                 pp->set_pretty_name(_midiio->port_name(i, true));
1170                 _system_midi_in.push_back(pp);
1171                 _port_change_flag = true;
1172         }
1173
1174         for (size_t i = 0; i < _midiio->n_midi_outputs(); ++i) {
1175                 std::string name = _midiio->port_id(i, false);
1176                 if (find_port_in(_system_midi_out, name)) {
1177                         continue;
1178                 }
1179
1180 #ifndef NDEBUG
1181                 printf("register MIDI OUT: %s\n", name.c_str());
1182 #endif
1183                 PortHandle p = add_port(name, DataType::MIDI, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
1184                 if (!p) {
1185                         fprintf(stderr, "failed to register MIDI OUT: %s\n", name.c_str());
1186                         continue;
1187                 }
1188                 LatencyRange lr;
1189                 lr.min = lr.max = _samples_per_period; // TODO add per-port midi-systemic latency
1190                 set_latency_range (p, false, lr);
1191                 CoreBackendPort *pp = static_cast<CoreBackendPort*>(p);
1192                 pp->set_pretty_name(_midiio->port_name(i, false));
1193                 _system_midi_out.push_back(pp);
1194                 _port_change_flag = true;
1195         }
1196
1197
1198         assert(_system_midi_out.size() == _midiio->n_midi_outputs());
1199         assert(_system_midi_in.size() == _midiio->n_midi_inputs());
1200
1201         pthread_mutex_unlock (&_process_callback_mutex);
1202 }
1203
1204 void
1205 CoreAudioBackend::unregister_ports (bool system_only)
1206 {
1207         _system_inputs.clear();
1208         _system_outputs.clear();
1209         _system_midi_in.clear();
1210         _system_midi_out.clear();
1211
1212         for (PortIndex::iterator i = _ports.begin (); i != _ports.end ();) {
1213                 PortIndex::iterator cur = i++;
1214                 CoreBackendPort* port = *cur;
1215                 if (! system_only || (port->is_physical () && port->is_terminal ())) {
1216                         port->disconnect_all ();
1217                         _portmap.erase (port->name());
1218                         delete port;
1219                         _ports.erase (cur);
1220                 }
1221         }
1222 }
1223
1224 int
1225 CoreAudioBackend::connect (const std::string& src, const std::string& dst)
1226 {
1227         CoreBackendPort* src_port = find_port (src);
1228         CoreBackendPort* dst_port = find_port (dst);
1229
1230         if (!src_port) {
1231                 PBD::warning << _("CoreAudioBackend::connect: Invalid Source port:")
1232                              << " (" << src <<")" << endmsg;
1233                 return -1;
1234         }
1235         if (!dst_port) {
1236                 PBD::warning << _("CoreAudioBackend::connect: Invalid Destination port:")
1237                              << " (" << dst <<")" << endmsg;
1238                 return -1;
1239         }
1240         return src_port->connect (dst_port);
1241 }
1242
1243 int
1244 CoreAudioBackend::disconnect (const std::string& src, const std::string& dst)
1245 {
1246         CoreBackendPort* src_port = find_port (src);
1247         CoreBackendPort* dst_port = find_port (dst);
1248
1249         if (!src_port || !dst_port) {
1250                 PBD::warning << _("CoreAudioBackend::disconnect: Invalid Port(s)") << endmsg;
1251                 return -1;
1252         }
1253         return src_port->disconnect (dst_port);
1254 }
1255
1256 int
1257 CoreAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
1258 {
1259         CoreBackendPort* dst_port = find_port (dst);
1260         if (!valid_port (src)) {
1261                 PBD::warning << _("CoreAudioBackend::connect: Invalid Source Port Handle") << endmsg;
1262                 return -1;
1263         }
1264         if (!dst_port) {
1265                 PBD::warning << _("CoreAudioBackend::connect: Invalid Destination Port")
1266                              << " (" << dst << ")" << endmsg;
1267                 return -1;
1268         }
1269         return static_cast<CoreBackendPort*>(src)->connect (dst_port);
1270 }
1271
1272 int
1273 CoreAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
1274 {
1275         CoreBackendPort* dst_port = find_port (dst);
1276         if (!valid_port (src) || !dst_port) {
1277                 PBD::warning << _("CoreAudioBackend::disconnect: Invalid Port(s)") << endmsg;
1278                 return -1;
1279         }
1280         return static_cast<CoreBackendPort*>(src)->disconnect (dst_port);
1281 }
1282
1283 int
1284 CoreAudioBackend::disconnect_all (PortEngine::PortHandle port)
1285 {
1286         if (!valid_port (port)) {
1287                 PBD::warning << _("CoreAudioBackend::disconnect_all: Invalid Port") << endmsg;
1288                 return -1;
1289         }
1290         static_cast<CoreBackendPort*>(port)->disconnect_all ();
1291         return 0;
1292 }
1293
1294 bool
1295 CoreAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
1296 {
1297         if (!valid_port (port)) {
1298                 PBD::warning << _("CoreAudioBackend::disconnect_all: Invalid Port") << endmsg;
1299                 return false;
1300         }
1301         return static_cast<CoreBackendPort*>(port)->is_connected ();
1302 }
1303
1304 bool
1305 CoreAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
1306 {
1307         CoreBackendPort* dst_port = find_port (dst);
1308 #ifndef NDEBUG
1309         if (!valid_port (src) || !dst_port) {
1310                 PBD::warning << _("CoreAudioBackend::connected_to: Invalid Port") << endmsg;
1311                 return false;
1312         }
1313 #endif
1314         return static_cast<CoreBackendPort*>(src)->is_connected (dst_port);
1315 }
1316
1317 bool
1318 CoreAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
1319 {
1320         if (!valid_port (port)) {
1321                 PBD::warning << _("CoreAudioBackend::physically_connected: Invalid Port") << endmsg;
1322                 return false;
1323         }
1324         return static_cast<CoreBackendPort*>(port)->is_physically_connected ();
1325 }
1326
1327 int
1328 CoreAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
1329 {
1330         if (!valid_port (port)) {
1331                 PBD::warning << _("CoreAudioBackend::get_connections: Invalid Port") << endmsg;
1332                 return -1;
1333         }
1334
1335         assert (0 == names.size ());
1336
1337         const std::set<CoreBackendPort*>& connected_ports = static_cast<CoreBackendPort*>(port)->get_connections ();
1338
1339         for (std::set<CoreBackendPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
1340                 names.push_back ((*i)->name ());
1341         }
1342
1343         return (int)names.size ();
1344 }
1345
1346 /* MIDI */
1347 int
1348 CoreAudioBackend::midi_event_get (
1349         pframes_t& timestamp,
1350         size_t& size, uint8_t** buf, void* port_buffer,
1351         uint32_t event_index)
1352 {
1353         if (!buf || !port_buffer) return -1;
1354         CoreMidiBuffer& source = * static_cast<CoreMidiBuffer*>(port_buffer);
1355         if (event_index >= source.size ()) {
1356                 return -1;
1357         }
1358         CoreMidiEvent * const event = source[event_index].get ();
1359
1360         timestamp = event->timestamp ();
1361         size = event->size ();
1362         *buf = event->data ();
1363         return 0;
1364 }
1365
1366 int
1367 CoreAudioBackend::_midi_event_put (
1368         void* port_buffer,
1369         pframes_t timestamp,
1370         const uint8_t* buffer, size_t size)
1371 {
1372         if (!buffer || !port_buffer) return -1;
1373         CoreMidiBuffer& dst = * static_cast<CoreMidiBuffer*>(port_buffer);
1374         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
1375 #ifndef NDEBUG
1376                 // nevermind, ::get_buffer() sorts events
1377                 fprintf (stderr, "CoreMidiBuffer: unordered event: %d > %d\n",
1378                          (pframes_t)dst.back ()->timestamp (), timestamp);
1379 #endif
1380         }
1381         dst.push_back (boost::shared_ptr<CoreMidiEvent>(new CoreMidiEvent (timestamp, buffer, size)));
1382         return 0;
1383 }
1384
1385
1386 uint32_t
1387 CoreAudioBackend::get_midi_event_count (void* port_buffer)
1388 {
1389         if (!port_buffer) return 0;
1390         return static_cast<CoreMidiBuffer*>(port_buffer)->size ();
1391 }
1392
1393 void
1394 CoreAudioBackend::midi_clear (void* port_buffer)
1395 {
1396         if (!port_buffer) return;
1397         CoreMidiBuffer * buf = static_cast<CoreMidiBuffer*>(port_buffer);
1398         assert (buf);
1399         buf->clear ();
1400 }
1401
1402 /* Monitoring */
1403
1404 bool
1405 CoreAudioBackend::can_monitor_input () const
1406 {
1407         return false;
1408 }
1409
1410 int
1411 CoreAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1412 {
1413         return -1;
1414 }
1415
1416 int
1417 CoreAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1418 {
1419         return -1;
1420 }
1421
1422 bool
1423 CoreAudioBackend::monitoring_input (PortEngine::PortHandle)
1424 {
1425         return false;
1426 }
1427
1428 /* Latency management */
1429
1430 void
1431 CoreAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1432 {
1433         if (!valid_port (port)) {
1434                 PBD::warning << _("CoreBackendPort::set_latency_range (): invalid port.") << endmsg;
1435                 return;
1436         }
1437         static_cast<CoreBackendPort*>(port)->set_latency_range (latency_range, for_playback);
1438 }
1439
1440 LatencyRange
1441 CoreAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1442 {
1443         LatencyRange r;
1444         if (!valid_port (port)) {
1445                 PBD::warning << _("CoreBackendPort::get_latency_range (): invalid port.") << endmsg;
1446                 r.min = 0;
1447                 r.max = 0;
1448                 return r;
1449         }
1450         CoreBackendPort* p = static_cast<CoreBackendPort*>(port);
1451         assert(p);
1452
1453         r = p->latency_range (for_playback);
1454         if (p->is_physical() && p->is_terminal() && p->type() == DataType::AUDIO) {
1455                 if (p->is_input() && for_playback) {
1456                         r.min += _samples_per_period;
1457                         r.max += _samples_per_period;
1458                 }
1459                 if (p->is_output() && !for_playback) {
1460                         r.min += _samples_per_period;
1461                         r.max += _samples_per_period;
1462                 }
1463         }
1464         return r;
1465 }
1466
1467 /* Discovering physical ports */
1468
1469 bool
1470 CoreAudioBackend::port_is_physical (PortEngine::PortHandle port) const
1471 {
1472         if (!valid_port (port)) {
1473                 PBD::warning << _("CoreBackendPort::port_is_physical (): invalid port.") << endmsg;
1474                 return false;
1475         }
1476         return static_cast<CoreBackendPort*>(port)->is_physical ();
1477 }
1478
1479 void
1480 CoreAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1481 {
1482         for (PortIndex::iterator i = _ports.begin (); i != _ports.end (); ++i) {
1483                 CoreBackendPort* port = *i;
1484                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1485                         port_names.push_back (port->name ());
1486                 }
1487         }
1488 }
1489
1490 void
1491 CoreAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1492 {
1493         for (PortIndex::iterator i = _ports.begin (); i != _ports.end (); ++i) {
1494                 CoreBackendPort* port = *i;
1495                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1496                         port_names.push_back (port->name ());
1497                 }
1498         }
1499 }
1500
1501 ChanCount
1502 CoreAudioBackend::n_physical_outputs () const
1503 {
1504         int n_midi = 0;
1505         int n_audio = 0;
1506         for (PortIndex::iterator i = _ports.begin (); i != _ports.end (); ++i) {
1507                 CoreBackendPort* port = *i;
1508                 if (port->is_output () && port->is_physical ()) {
1509                         switch (port->type ()) {
1510                         case DataType::AUDIO: ++n_audio; break;
1511                         case DataType::MIDI: ++n_midi; break;
1512                         default: break;
1513                         }
1514                 }
1515         }
1516         ChanCount cc;
1517         cc.set (DataType::AUDIO, n_audio);
1518         cc.set (DataType::MIDI, n_midi);
1519         return cc;
1520 }
1521
1522 ChanCount
1523 CoreAudioBackend::n_physical_inputs () const
1524 {
1525         int n_midi = 0;
1526         int n_audio = 0;
1527         for (PortIndex::iterator i = _ports.begin (); i != _ports.end (); ++i) {
1528                 CoreBackendPort* port = *i;
1529                 if (port->is_input () && port->is_physical ()) {
1530                         switch (port->type ()) {
1531                         case DataType::AUDIO: ++n_audio; break;
1532                         case DataType::MIDI: ++n_midi; break;
1533                         default: break;
1534                         }
1535                 }
1536         }
1537         ChanCount cc;
1538         cc.set (DataType::AUDIO, n_audio);
1539         cc.set (DataType::MIDI, n_midi);
1540         return cc;
1541 }
1542
1543 /* Getting access to the data buffer for a port */
1544
1545 void*
1546 CoreAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1547 {
1548         if (!port || !valid_port (port)) return NULL;
1549         return static_cast<CoreBackendPort*>(port)->get_buffer (nframes);
1550 }
1551
1552 void
1553 CoreAudioBackend::pre_process ()
1554 {
1555         bool connections_changed = false;
1556         bool ports_changed = false;
1557         if (!pthread_mutex_trylock (&_port_callback_mutex)) {
1558                 if (_port_change_flag) {
1559                         ports_changed = true;
1560                         _port_change_flag = false;
1561                 }
1562                 if (!_port_connection_queue.empty ()) {
1563                         connections_changed = true;
1564                 }
1565                 while (!_port_connection_queue.empty ()) {
1566                         PortConnectData *c = _port_connection_queue.back ();
1567                         manager.connect_callback (c->a, c->b, c->c);
1568                         _port_connection_queue.pop_back ();
1569                         delete c;
1570                 }
1571                 pthread_mutex_unlock (&_port_callback_mutex);
1572         }
1573         if (ports_changed) {
1574                 manager.registration_callback();
1575         }
1576         if (connections_changed) {
1577                 manager.graph_order_callback();
1578         }
1579         if (connections_changed || ports_changed) {
1580                 engine.latency_callback(false);
1581                 engine.latency_callback(true);
1582         }
1583 }
1584
1585 void
1586 CoreAudioBackend::reset_midi_parsers ()
1587 {
1588         for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it) {
1589                 CoreMidiPort* port = dynamic_cast<CoreMidiPort*>(*it);
1590                 if (port) {
1591                         port->reset_parser ();
1592                 }
1593         }
1594 }
1595
1596 void *
1597 CoreAudioBackend::freewheel_thread ()
1598 {
1599         _active_fw = true;
1600         bool first_run = false;
1601         /* Freewheeling - use for export.   The first call to
1602          * engine.process_callback() after engine.freewheel_callback will
1603          * if the first export cycle.
1604          * For reliable precise export timing, the calls need to be in sync.
1605          *
1606          * Furthermore we need to make sure the registered process thread
1607          * is correct.
1608          *
1609          * _freewheeling = GUI thread state as set by ::freewheel()
1610          * _freewheel = in sync here (export thread)
1611          */
1612         pthread_mutex_lock (&_freewheel_mutex);
1613         while (_run) {
1614                 // check if we should run,
1615                 if (_freewheeling != _freewheel) {
1616                         if (!_freewheeling) {
1617                                 // prepare leaving freewheeling mode
1618                                 _freewheel = false; // first mark as disabled
1619                                 _reinit_thread_callback = true; // hand over _main_thread
1620                                 _freewheel_ack = false; // prepare next handshake
1621                                 reset_midi_parsers ();
1622                                 _midiio->set_enabled(true);
1623                                 engine.freewheel_callback (_freewheeling);
1624                         } else {
1625                                 first_run = true;
1626                                 _freewheel = true;
1627                         }
1628                 }
1629
1630                 if (!_freewheel || !_freewheel_ack) {
1631                         // wait for a change, we use a timed wait to
1632                         // terminate early in case some error sets _run = 0
1633                         struct timeval tv;
1634                         struct timespec ts;
1635                         gettimeofday (&tv, NULL);
1636                         ts.tv_sec = tv.tv_sec + 3;
1637                         ts.tv_nsec = 0;
1638                         pthread_cond_timedwait (&_freewheel_signal, &_freewheel_mutex, &ts);
1639                         continue;
1640                 }
1641
1642                 if (first_run) {
1643                         // tell the engine we're ready to GO.
1644                         engine.freewheel_callback (_freewheeling);
1645                         first_run = false;
1646                         _main_thread = pthread_self();
1647                         AudioEngine::thread_init_callback (this);
1648                         _midiio->set_enabled(false);
1649                         reset_midi_parsers ();
1650                 }
1651
1652                 // process port updates first in every cycle.
1653                 pre_process();
1654
1655                 // prevent coreaudio device changes
1656                 pthread_mutex_lock (&_process_callback_mutex);
1657
1658                 /* Freewheelin' */
1659
1660                 // clear input buffers
1661                 for (std::vector<CoreBackendPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
1662                         memset ((*it)->get_buffer (_samples_per_period), 0, _samples_per_period * sizeof (Sample));
1663                 }
1664                 for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it) {
1665                         static_cast<CoreMidiBuffer*>((*it)->get_buffer(0))->clear ();
1666                 }
1667
1668                 _last_process_start = 0;
1669                 if (engine.process_callback (_samples_per_period)) {
1670                         pthread_mutex_unlock (&_process_callback_mutex);
1671                         break;
1672                 }
1673
1674                 pthread_mutex_unlock (&_process_callback_mutex);
1675                 _dsp_load = 1.0;
1676                 Glib::usleep (100); // don't hog cpu
1677         }
1678
1679         pthread_mutex_unlock (&_freewheel_mutex);
1680
1681         _active_fw = false;
1682
1683         if (_run) {
1684                 // engine.process_callback() returner error
1685                 engine.halted_callback("CoreAudio Freehweeling aborted.");
1686         }
1687         return 0;
1688 }
1689 int
1690 CoreAudioBackend::process_callback (const uint32_t n_samples, const uint64_t host_time)
1691 {
1692         uint32_t i = 0;
1693         uint64_t clock1;
1694
1695         _active_ca = true;
1696
1697         if (_run && _freewheel && !_freewheel_ack) {
1698                 // acknowledge freewheeling; hand-over thread ID
1699                 pthread_mutex_lock (&_freewheel_mutex);
1700                 if (_freewheel) _freewheel_ack = true;
1701                 pthread_cond_signal (&_freewheel_signal);
1702                 pthread_mutex_unlock (&_freewheel_mutex);
1703         }
1704
1705         if (!_run || _freewheel || _preinit) {
1706                 // NB if we return 1, the output is
1707                 // zeroed by the coreaudio callback
1708                 return 1;
1709         }
1710
1711         if (_reinit_thread_callback || _main_thread != pthread_self()) {
1712                 _reinit_thread_callback = false;
1713                 _main_thread = pthread_self();
1714                 AudioEngine::thread_init_callback (this);
1715         }
1716
1717         if (pthread_mutex_trylock (&_process_callback_mutex)) {
1718                 // block while devices are added/removed
1719 #ifndef NDEBUG
1720                 printf("Xrun due to device change\n");
1721 #endif
1722                 engine.Xrun();
1723                 return 1;
1724         }
1725         /* port-connection change */
1726         pre_process();
1727
1728         // cycle-length in usec
1729         const double nominal_time = 1e6 * n_samples / _samplerate;
1730
1731         clock1 = g_get_monotonic_time();
1732
1733         /* get midi */
1734         i=0;
1735         for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++i) {
1736                 CoreMidiPort* port = dynamic_cast<CoreMidiPort*> (*it);
1737                 if (!port) {
1738                         continue;
1739                 }
1740                 uint64_t time_ns;
1741                 uint8_t data[128]; // matches CoreMidi's MIDIPacket
1742                 size_t size = sizeof(data);
1743
1744                 port->clear_events ();
1745
1746                 while (_midiio->recv_event (i, nominal_time, time_ns, data, size)) {
1747                         pframes_t time = floor((float) time_ns * _samplerate * 1e-9);
1748                         assert (time < n_samples);
1749                         port->parse_events (time, data, size);
1750                         size = sizeof(data); /* prepare for next call to recv_event */
1751                 }
1752         }
1753
1754         /* get audio */
1755         i = 0;
1756         for (std::vector<CoreBackendPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++i) {
1757                 _pcmio->get_capture_channel (i, (float*)((*it)->get_buffer(n_samples)), n_samples);
1758         }
1759
1760         /* clear output buffers */
1761         for (std::vector<CoreBackendPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it) {
1762                 memset ((*it)->get_buffer (n_samples), 0, n_samples * sizeof (Sample));
1763         }
1764
1765         _midiio->start_cycle();
1766         _last_process_start = host_time;
1767
1768         if (engine.process_callback (n_samples)) {
1769                 fprintf(stderr, "ENGINE PROCESS ERROR\n");
1770                 //_pcmio->pcm_stop ();
1771                 _active_ca = false;
1772                 pthread_mutex_unlock (&_process_callback_mutex);
1773                 return -1;
1774         }
1775
1776         /* mixdown midi */
1777         for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it) {
1778                 static_cast<CoreMidiPort*>(*it)->get_buffer(0);
1779         }
1780
1781         /* queue outgoing midi */
1782         i = 0;
1783         for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it, ++i) {
1784 #if 0 // something's still b0rked with CoreMidiIo::send_events()
1785                 const CoreMidiBuffer *src = static_cast<const CoreMidiPort*>(*it)->const_buffer();
1786                 _midiio->send_events (i, nominal_time, (void*)src);
1787 #else // works..
1788                 const CoreMidiBuffer *src = static_cast<const CoreMidiPort*>(*it)->const_buffer();
1789                 for (CoreMidiBuffer::const_iterator mit = src->begin (); mit != src->end (); ++mit) {
1790                         _midiio->send_event (i, (*mit)->timestamp() / nominal_time, (*mit)->data(), (*mit)->size());
1791                 }
1792 #endif
1793         }
1794
1795         /* write back audio */
1796         i = 0;
1797         for (std::vector<CoreBackendPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it, ++i) {
1798                 _pcmio->set_playback_channel (i, (float const*)(*it)->get_buffer (n_samples), n_samples);
1799         }
1800
1801         _processed_samples += n_samples;
1802
1803         /* calc DSP load. */
1804         _dsp_load_calc.set_max_time (_samplerate, _samples_per_period);
1805         _dsp_load_calc.set_start_timestamp_us (clock1);
1806         _dsp_load_calc.set_stop_timestamp_us (g_get_monotonic_time());
1807         _dsp_load = _dsp_load_calc.get_dsp_load ();
1808
1809         pthread_mutex_unlock (&_process_callback_mutex);
1810         return 0;
1811 }
1812
1813 void
1814 CoreAudioBackend::error_callback ()
1815 {
1816         _pcmio->set_error_callback (NULL, NULL);
1817         _pcmio->set_sample_rate_callback (NULL, NULL);
1818         _pcmio->set_xrun_callback (NULL, NULL);
1819         _midiio->set_port_changed_callback(NULL, NULL);
1820         engine.halted_callback("CoreAudio Process aborted.");
1821         _active_ca = false;
1822 }
1823
1824 void
1825 CoreAudioBackend::xrun_callback ()
1826 {
1827         engine.Xrun ();
1828 }
1829
1830 void
1831 CoreAudioBackend::buffer_size_callback ()
1832 {
1833         uint32_t bs = _pcmio->samples_per_period();
1834         if (bs == _samples_per_period) {
1835                 return;
1836         }
1837         _samples_per_period = bs;
1838         engine.buffer_size_change (_samples_per_period);
1839 }
1840
1841 void
1842 CoreAudioBackend::sample_rate_callback ()
1843 {
1844         if (_preinit) {
1845 #ifndef NDEBUG
1846                 printf("Samplerate change during initialization.\n");
1847 #endif
1848                 return;
1849         }
1850         _pcmio->set_error_callback (NULL, NULL);
1851         _pcmio->set_sample_rate_callback (NULL, NULL);
1852         _pcmio->set_xrun_callback (NULL, NULL);
1853         _midiio->set_port_changed_callback(NULL, NULL);
1854         engine.halted_callback("Sample Rate Changed.");
1855         stop();
1856 }
1857
1858 void
1859 CoreAudioBackend::hw_changed_callback ()
1860 {
1861         _reinit_thread_callback = true;
1862         engine.request_device_list_update();
1863 }
1864
1865 /******************************************************************************/
1866
1867 static boost::shared_ptr<CoreAudioBackend> _instance;
1868
1869 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
1870 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
1871 static int deinstantiate ();
1872 static bool already_configured ();
1873 static bool available ();
1874
1875 static ARDOUR::AudioBackendInfo _descriptor = {
1876         "CoreAudio",
1877         instantiate,
1878         deinstantiate,
1879         backend_factory,
1880         already_configured,
1881         available
1882 };
1883
1884 static boost::shared_ptr<AudioBackend>
1885 backend_factory (AudioEngine& e)
1886 {
1887         if (!_instance) {
1888                 _instance.reset (new CoreAudioBackend (e, _descriptor));
1889         }
1890         return _instance;
1891 }
1892
1893 static int
1894 instantiate (const std::string& arg1, const std::string& /* arg2 */)
1895 {
1896         s_instance_name = arg1;
1897         return 0;
1898 }
1899
1900 static int
1901 deinstantiate ()
1902 {
1903         _instance.reset ();
1904         return 0;
1905 }
1906
1907 static bool
1908 already_configured ()
1909 {
1910         return false;
1911 }
1912
1913 static bool
1914 available ()
1915 {
1916         return true;
1917 }
1918
1919 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
1920 {
1921         return &_descriptor;
1922 }
1923
1924
1925 /******************************************************************************/
1926 CoreBackendPort::CoreBackendPort (CoreAudioBackend &b, const std::string& name, PortFlags flags)
1927         : _osx_backend (b)
1928         , _name  (name)
1929         , _flags (flags)
1930 {
1931         _capture_latency_range.min = 0;
1932         _capture_latency_range.max = 0;
1933         _playback_latency_range.min = 0;
1934         _playback_latency_range.max = 0;
1935 }
1936
1937 CoreBackendPort::~CoreBackendPort () {
1938         disconnect_all ();
1939 }
1940
1941
1942 int CoreBackendPort::connect (CoreBackendPort *port)
1943 {
1944         if (!port) {
1945                 PBD::warning << _("CoreBackendPort::connect (): invalid (null) port") << endmsg;
1946                 return -1;
1947         }
1948
1949         if (type () != port->type ()) {
1950                 PBD::warning << _("CoreBackendPort::connect (): wrong port-type") << endmsg;
1951                 return -1;
1952         }
1953
1954         if (is_output () && port->is_output ()) {
1955                 PBD::warning << _("CoreBackendPort::connect (): cannot inter-connect output ports.") << endmsg;
1956                 return -1;
1957         }
1958
1959         if (is_input () && port->is_input ()) {
1960                 PBD::warning << _("CoreBackendPort::connect (): cannot inter-connect input ports.") << endmsg;
1961                 return -1;
1962         }
1963
1964         if (this == port) {
1965                 PBD::warning << _("CoreBackendPort::connect (): cannot self-connect ports.") << endmsg;
1966                 return -1;
1967         }
1968
1969         if (is_connected (port)) {
1970 #if 0 // don't bother to warn about this for now. just ignore it
1971                 PBD::info << _("CoreBackendPort::connect (): ports are already connected:")
1972                           << " (" << name () << ") -> (" << port->name () << ")"
1973                           << endmsg;
1974 #endif
1975                 return -1;
1976         }
1977
1978         _connect (port, true);
1979         return 0;
1980 }
1981
1982
1983 void CoreBackendPort::_connect (CoreBackendPort *port, bool callback)
1984 {
1985         _connections.insert (port);
1986         if (callback) {
1987                 port->_connect (this, false);
1988                 _osx_backend.port_connect_callback (name(),  port->name(), true);
1989         }
1990 }
1991
1992 int CoreBackendPort::disconnect (CoreBackendPort *port)
1993 {
1994         if (!port) {
1995                 PBD::warning << _("CoreBackendPort::disconnect (): invalid (null) port") << endmsg;
1996                 return -1;
1997         }
1998
1999         if (!is_connected (port)) {
2000                 PBD::warning << _("CoreBackendPort::disconnect (): ports are not connected:")
2001                              << " (" << name () << ") -> (" << port->name () << ")"
2002                              << endmsg;
2003                 return -1;
2004         }
2005         _disconnect (port, true);
2006         return 0;
2007 }
2008
2009 void CoreBackendPort::_disconnect (CoreBackendPort *port, bool callback)
2010 {
2011         std::set<CoreBackendPort*>::iterator it = _connections.find (port);
2012         assert (it != _connections.end ());
2013         _connections.erase (it);
2014         if (callback) {
2015                 port->_disconnect (this, false);
2016                 _osx_backend.port_connect_callback (name(),  port->name(), false);
2017         }
2018 }
2019
2020
2021 void CoreBackendPort::disconnect_all ()
2022 {
2023         while (!_connections.empty ()) {
2024                 std::set<CoreBackendPort*>::iterator it = _connections.begin ();
2025                 (*it)->_disconnect (this, false);
2026                 _osx_backend.port_connect_callback (name(), (*it)->name(), false);
2027                 _connections.erase (it);
2028         }
2029 }
2030
2031 bool
2032 CoreBackendPort::is_connected (const CoreBackendPort *port) const
2033 {
2034         return _connections.find (const_cast<CoreBackendPort *>(port)) != _connections.end ();
2035 }
2036
2037 bool CoreBackendPort::is_physically_connected () const
2038 {
2039         for (std::set<CoreBackendPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
2040                 if ((*it)->is_physical ()) {
2041                         return true;
2042                 }
2043         }
2044         return false;
2045 }
2046
2047 /******************************************************************************/
2048
2049 CoreAudioPort::CoreAudioPort (CoreAudioBackend &b, const std::string& name, PortFlags flags)
2050         : CoreBackendPort (b, name, flags)
2051 {
2052         memset (_buffer, 0, sizeof (_buffer));
2053         mlock(_buffer, sizeof (_buffer));
2054 }
2055
2056 CoreAudioPort::~CoreAudioPort () { }
2057
2058 void* CoreAudioPort::get_buffer (pframes_t n_samples)
2059 {
2060         if (is_input ()) {
2061                 const std::set<CoreBackendPort *>& connections = get_connections ();
2062                 std::set<CoreBackendPort*>::const_iterator it = connections.begin ();
2063                 if (it == connections.end ()) {
2064                         memset (_buffer, 0, n_samples * sizeof (Sample));
2065                 } else {
2066                         CoreAudioPort const * source = static_cast<const CoreAudioPort*>(*it);
2067                         assert (source && source->is_output ());
2068                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
2069                         while (++it != connections.end ()) {
2070                                 source = static_cast<const CoreAudioPort*>(*it);
2071                                 assert (source && source->is_output ());
2072                                 Sample* dst = buffer ();
2073                                 const Sample* src = source->const_buffer ();
2074                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
2075                                         *dst += *src;
2076                                 }
2077                         }
2078                 }
2079         }
2080         return _buffer;
2081 }
2082
2083
2084 CoreMidiPort::CoreMidiPort (CoreAudioBackend &b, const std::string& name, PortFlags flags)
2085         : CoreBackendPort (b, name, flags)
2086         , _n_periods (1)
2087         , _bufperiod (0)
2088         , _event (0, 0)
2089         , _first_time(true)
2090         , _unbuffered_bytes(0)
2091         , _total_bytes(0)
2092         , _expected_bytes(0)
2093         , _status_byte(0)
2094
2095 {
2096         _buffer[0].clear ();
2097         _buffer[1].clear ();
2098 }
2099
2100 CoreMidiPort::~CoreMidiPort () { }
2101
2102 struct MidiEventSorter {
2103         bool operator() (const boost::shared_ptr<CoreMidiEvent>& a, const boost::shared_ptr<CoreMidiEvent>& b) {
2104                 return *a < *b;
2105         }
2106 };
2107
2108 void* CoreMidiPort::get_buffer (pframes_t /* nframes */)
2109 {
2110         if (is_input ()) {
2111                 (_buffer[_bufperiod]).clear ();
2112                 const std::set<CoreBackendPort*>& connections = get_connections ();
2113                 for (std::set<CoreBackendPort*>::const_iterator i = connections.begin ();
2114                      i != connections.end ();
2115                      ++i) {
2116                         const CoreMidiBuffer * src = static_cast<const CoreMidiPort*>(*i)->const_buffer ();
2117                         for (CoreMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
2118                                 (_buffer[_bufperiod]).push_back (boost::shared_ptr<CoreMidiEvent>(new CoreMidiEvent (**it)));
2119                         }
2120                 }
2121                 std::sort ((_buffer[_bufperiod]).begin (), (_buffer[_bufperiod]).end (), MidiEventSorter());
2122         }
2123
2124         return &(_buffer[_bufperiod]);
2125 }
2126
2127 int
2128 CoreMidiPort::queue_event (
2129         void* port_buffer,
2130         pframes_t timestamp,
2131         const uint8_t* buffer, size_t size)
2132 {
2133         const int ret = CoreAudioBackend::_midi_event_put (port_buffer, timestamp, buffer, size);
2134         if (!ret) { /* success */
2135                 _event._pending = false;
2136         }
2137         return ret;
2138 }
2139
2140 void
2141 CoreMidiPort::reset_parser ()
2142 {
2143         _event._pending = false;
2144         _first_time = true;
2145         _unbuffered_bytes = 0;
2146         _total_bytes = 0;
2147         _expected_bytes = 0;
2148         _status_byte = 0;
2149 }
2150
2151 void
2152 CoreMidiPort::clear_events ()
2153 {
2154         CoreMidiBuffer* mbuf = static_cast<CoreMidiBuffer*>(get_buffer(0));
2155         mbuf->clear();
2156 }
2157
2158 void
2159 CoreMidiPort::parse_events (const uint64_t time, const uint8_t *data, const size_t size)
2160 {
2161         CoreMidiBuffer* mbuf = static_cast<CoreMidiBuffer*>(get_buffer(0));
2162
2163         if (_event._pending) {
2164                 if (queue_event (mbuf, _event._time, _parser_buffer, _event._size)) {
2165                         return;
2166                 }
2167         }
2168
2169         for (size_t i = 0; i < size; ++i) {
2170                 if (_first_time && !(data[i] & 0x80)) {
2171                         continue;
2172                 }
2173
2174                 _first_time = false;
2175
2176                 if (process_byte(time, data[i])) {
2177                         if (queue_event (mbuf, _event._time, _parser_buffer, _event._size)) {
2178                                 return;
2179                         }
2180                 }
2181         }
2182 }
2183
2184 // based on JackMidiRawInputWriteQueue by Devin Anderson //
2185 bool
2186 CoreMidiPort::process_byte(const uint64_t time, const uint8_t byte)
2187 {
2188         if (byte >= 0xf8) {
2189                 // Realtime
2190                 if (byte == 0xfd) {
2191                         return false;
2192                 }
2193                 _parser_buffer[0] = byte;
2194                 prepare_byte_event(time, byte);
2195                 return true;
2196         }
2197         if (byte == 0xf7) {
2198                 // Sysex end
2199                 if (_status_byte == 0xf0) {
2200                         record_byte(byte);
2201                         return prepare_buffered_event(time);
2202                 }
2203                 _total_bytes = 0;
2204                 _unbuffered_bytes = 0;
2205                 _expected_bytes = 0;
2206                 _status_byte = 0;
2207                 return false;
2208         }
2209         if (byte >= 0x80) {
2210                 // Non-realtime status byte
2211                 if (_total_bytes) {
2212                         printf ("CoreMidiPort: discarded bogus midi message\n");
2213 #if 0
2214                         for (size_t i=0; i < _total_bytes; ++i) {
2215                                 printf("%02x ", _parser_buffer[i]);
2216                         }
2217                         printf("\n");
2218 #endif
2219                         _total_bytes = 0;
2220                         _unbuffered_bytes = 0;
2221                 }
2222                 _status_byte = byte;
2223                 switch (byte & 0xf0) {
2224                 case 0x80:
2225                 case 0x90:
2226                 case 0xa0:
2227                 case 0xb0:
2228                 case 0xe0:
2229                         // Note On, Note Off, Aftertouch, Control Change, Pitch Wheel
2230                         _expected_bytes = 3;
2231                         break;
2232                 case 0xc0:
2233                 case 0xd0:
2234                         // Program Change, Channel Pressure
2235                         _expected_bytes = 2;
2236                         break;
2237                 case 0xf0:
2238                         switch (byte) {
2239                         case 0xf0:
2240                                 // Sysex
2241                                 _expected_bytes = 0;
2242                                 break;
2243                         case 0xf1:
2244                         case 0xf3:
2245                                 // MTC Quarter Frame, Song Select
2246                                 _expected_bytes = 2;
2247                                 break;
2248                         case 0xf2:
2249                                 // Song Position
2250                                 _expected_bytes = 3;
2251                                 break;
2252                         case 0xf4:
2253                         case 0xf5:
2254                                 // Undefined
2255                                 _expected_bytes = 0;
2256                                 _status_byte = 0;
2257                                 return false;
2258                         case 0xf6:
2259                                 // Tune Request
2260                                 prepare_byte_event(time, byte);
2261                                 _expected_bytes = 0;
2262                                 _status_byte = 0;
2263                                 return true;
2264                         }
2265                 }
2266                 record_byte(byte);
2267                 return false;
2268         }
2269         // Data byte
2270         if (! _status_byte) {
2271                 // Data bytes without a status will be discarded.
2272                 _total_bytes++;
2273                 _unbuffered_bytes++;
2274                 return false;
2275         }
2276         if (! _total_bytes) {
2277                 record_byte(_status_byte);
2278         }
2279         record_byte(byte);
2280         return (_total_bytes == _expected_bytes) ? prepare_buffered_event(time) : false;
2281 }
2282
2283
2284 CoreMidiEvent::CoreMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
2285         : _size (size)
2286         , _timestamp (timestamp)
2287         , _data (0)
2288 {
2289         if (size > 0) {
2290                 _data = (uint8_t*) malloc (size);
2291                 memcpy (_data, data, size);
2292         }
2293 }
2294
2295 CoreMidiEvent::CoreMidiEvent (const CoreMidiEvent& other)
2296         : _size (other.size ())
2297         , _timestamp (other.timestamp ())
2298         , _data (0)
2299 {
2300         if (other.size () && other.const_data ()) {
2301                 _data = (uint8_t*) malloc (other.size ());
2302                 memcpy (_data, other.const_data (), other.size ());
2303         }
2304 };
2305
2306 CoreMidiEvent::~CoreMidiEvent () {
2307         free (_data);
2308 };