coremidi: do not clear port buffer for every call to parse_events()
[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()) {
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         }
508
509         uint32_t device1 = name_to_id(_input_audio_device);
510         uint32_t device2 = name_to_id(_output_audio_device);
511
512         assert(_active_ca == false);
513         assert(_active_fw == false);
514
515         _freewheel_ack = false;
516         _reinit_thread_callback = true;
517         _last_process_start = 0;
518
519         _pcmio->set_error_callback (error_callback_ptr, this);
520         _pcmio->set_buffer_size_callback (buffer_size_callback_ptr, this);
521         _pcmio->set_sample_rate_callback (sample_rate_callback_ptr, this);
522
523         _pcmio->pcm_start (device1, device2, _samplerate, _samples_per_period, process_callback_ptr, this);
524 #ifndef NDEBUG
525         printf("STATE: %d\n", _pcmio->state ());
526 #endif
527         switch (_pcmio->state ()) {
528         case 0: /* OK */
529                 break;
530         case -1:
531                 PBD::error << _("CoreAudioBackend: Invalid Device ID.") << endmsg;
532                 error_code = AudioDeviceInvalidError;
533                 break;
534         case -2:
535                 PBD::error << _("CoreAudioBackend: Failed to resolve Device-Component by ID.") << endmsg;
536                 error_code = AudioDeviceNotAvailableError;
537                 break;
538         case -3:
539                 PBD::error << _("CoreAudioBackend: failed to open device.") << endmsg;
540                 error_code = AudioDeviceOpenError;
541                 break;
542         case -4:
543                 PBD::error << _("CoreAudioBackend: cannot set requested sample rate.") << endmsg;
544                 error_code = SampleRateNotSupportedError;
545                 break;
546         case -5:
547                 PBD::error << _("CoreAudioBackend: cannot configure requested buffer size.") << endmsg;
548                 error_code = PeriodSizeNotSupportedError;
549                 break;
550         case -6:
551                 PBD::error << _("CoreAudioBackend: unsupported sample format.") << endmsg;
552                 error_code = SampleFormatNotSupportedError;
553                 break;
554         case -7:
555                 PBD::error << _("CoreAudioBackend: Failed to enable Device.") << endmsg;
556                 error_code = BackendInitializationError; // XXX
557                 break;
558         case -8:
559                 PBD::error << _("CoreAudioBackend: Cannot allocate buffers, out-of-memory.") << endmsg;
560                 error_code = OutOfMemoryError;
561                 break;
562         case -9:
563                 PBD::error << _("CoreAudioBackend: Failed to set device-property listeners.") << endmsg;
564                 error_code = BackendInitializationError; // XXX
565                 break;
566         case -10:
567                 PBD::error << _("CoreAudioBackend: Setting Process Callback failed.") << endmsg;
568                 error_code = AudioDeviceIOError;
569                 break;
570         case -11:
571                 PBD::error << _("CoreAudioBackend: cannot use requested period size.") << endmsg;
572                 error_code = PeriodSizeNotSupportedError;
573                 break;
574         case -12:
575                 PBD::error << _("CoreAudioBackend: cannot create aggregate device.") << endmsg;
576                 error_code = DeviceConfigurationNotSupportedError;
577                 break;
578         default:
579                 PBD::error << _("CoreAudioBackend: initialization failure.") << endmsg;
580                 error_code = BackendInitializationError;
581                 break;
582         }
583         if (_pcmio->state ()) {
584                 return error_code;
585         }
586
587         if (_n_outputs != _pcmio->n_playback_channels ()) {
588                 if (_n_outputs == 0) {
589                         _n_outputs = _pcmio->n_playback_channels ();
590                 } else {
591                         _n_outputs = std::min (_n_outputs, _pcmio->n_playback_channels ());
592                 }
593                 PBD::info << _("CoreAudioBackend: adjusted output channel count to match device.") << endmsg;
594         }
595
596         if (_n_inputs != _pcmio->n_capture_channels ()) {
597                 if (_n_inputs == 0) {
598                         _n_inputs = _pcmio->n_capture_channels ();
599                 } else {
600                         _n_inputs = std::min (_n_inputs, _pcmio->n_capture_channels ());
601                 }
602                 PBD::info << _("CoreAudioBackend: adjusted input channel count to match device.") << endmsg;
603         }
604
605         if (_pcmio->samples_per_period() != _samples_per_period) {
606                 _samples_per_period = _pcmio->samples_per_period();
607                 PBD::warning << _("CoreAudioBackend: samples per period does not match.") << endmsg;
608         }
609
610         if (_pcmio->sample_rate() != _samplerate) {
611                 _samplerate = _pcmio->sample_rate();
612                 engine.sample_rate_change (_samplerate);
613                 PBD::warning << _("CoreAudioBackend: sample rate does not match.") << endmsg;
614         }
615
616         _measure_latency = for_latency_measurement;
617
618         _preinit = true;
619         _run = true;
620         _port_change_flag = false;
621
622         if (_midi_driver_option == _("CoreMidi")) {
623                 _midiio->set_enabled(true);
624                 _midiio->set_port_changed_callback(midi_port_change, this);
625                 _midiio->start(); // triggers port discovery, callback coremidi_rediscover()
626         }
627
628         if (register_system_audio_ports()) {
629                 PBD::error << _("CoreAudioBackend: failed to register system ports.") << endmsg;
630                 _run = false;
631                 return PortRegistrationError;
632         }
633
634         engine.sample_rate_change (_samplerate);
635         engine.buffer_size_change (_samples_per_period);
636
637         if (engine.reestablish_ports ()) {
638                 PBD::error << _("CoreAudioBackend: Could not re-establish ports.") << endmsg;
639                 _run = false;
640                 return PortReconnectError;
641         }
642
643         if (pthread_create (&_freeewheel_thread, NULL, pthread_freewheel, this))
644         {
645                 PBD::error << _("CoreAudioBackend: failed to create process thread.") << endmsg;
646                 delete _pcmio; _pcmio = 0;
647                 _run = false;
648                 return ProcessThreadStartError;
649         }
650
651         int timeout = 5000;
652         while ((!_active_ca || !_active_fw) && --timeout > 0) { Glib::usleep (1000); }
653
654         if (timeout == 0) {
655                 PBD::error << _("CoreAudioBackend: failed to start.") << endmsg;
656         }
657
658         if (!_active_fw) {
659                 PBD::error << _("CoreAudioBackend: failed to start freewheeling thread.") << endmsg;
660                 _run = false;
661                 _pcmio->pcm_stop();
662                 unregister_ports();
663                 _active_ca = false;
664                 _active_fw = false;
665                 return FreewheelThreadStartError;
666         }
667
668         if (!_active_ca) {
669                 PBD::error << _("CoreAudioBackend: failed to start coreaudio.") << endmsg;
670                 stop();
671                 _run = false;
672                 return ProcessThreadStartError;
673         }
674
675         engine.reconnect_ports ();
676
677         // force  an initial registration_callback() & latency re-compute
678         _port_change_flag = true;
679         pre_process ();
680
681         // all systems go.
682         _pcmio->set_xrun_callback (xrun_callback_ptr, this);
683         _preinit = false;
684
685         return NoError;
686 }
687
688 int
689 CoreAudioBackend::stop ()
690 {
691         void *status;
692         if (!_run) {
693                 return 0;
694         }
695
696         _run = false;
697         _pcmio->pcm_stop();
698         _midiio->set_port_changed_callback(NULL, NULL);
699         _midiio->stop();
700
701         pthread_mutex_lock (&_freewheel_mutex);
702         pthread_cond_signal (&_freewheel_signal);
703         pthread_mutex_unlock (&_freewheel_mutex);
704
705         if (pthread_join (_freeewheel_thread, &status)) {
706                 PBD::error << _("CoreAudioBackend: failed to terminate.") << endmsg;
707                 return -1;
708         }
709
710         unregister_ports();
711
712         _active_ca = false;
713         _active_fw = false; // ??
714
715         return 0;
716 }
717
718 int
719 CoreAudioBackend::freewheel (bool onoff)
720 {
721         if (onoff == _freewheeling) {
722                 return 0;
723         }
724         _freewheeling = onoff;
725         // wake up freewheeling thread
726         if (0 == pthread_mutex_trylock (&_freewheel_mutex)) {
727                 pthread_cond_signal (&_freewheel_signal);
728                 pthread_mutex_unlock (&_freewheel_mutex);
729         }
730         return 0;
731 }
732
733 float
734 CoreAudioBackend::dsp_load () const
735 {
736         return 100.f * _dsp_load;
737 }
738
739 size_t
740 CoreAudioBackend::raw_buffer_size (DataType t)
741 {
742         switch (t) {
743         case DataType::AUDIO:
744                 return _samples_per_period * sizeof(Sample);
745         case DataType::MIDI:
746                 return _max_buffer_size; // XXX not really limited
747         }
748         return 0;
749 }
750
751 /* Process time */
752 framepos_t
753 CoreAudioBackend::sample_time ()
754 {
755         return _processed_samples;
756 }
757
758 framepos_t
759 CoreAudioBackend::sample_time_at_cycle_start ()
760 {
761         return _processed_samples;
762 }
763
764 pframes_t
765 CoreAudioBackend::samples_since_cycle_start ()
766 {
767         if (!_active_ca || !_run || _freewheeling || _freewheel) {
768                 return 0;
769         }
770         if (_last_process_start == 0) {
771                 return 0;
772         }
773
774         const uint64_t now = AudioGetCurrentHostTime ();
775         const int64_t elapsed_time_ns = AudioConvertHostTimeToNanos(now - _last_process_start);
776         return std::max((pframes_t)0, (pframes_t)rint(1e-9 * elapsed_time_ns * _samplerate));
777 }
778
779 uint32_t
780 CoreAudioBackend::name_to_id(std::string device_name) const {
781         uint32_t device_id = UINT32_MAX;
782         std::map<size_t, std::string> devices;
783         _pcmio->device_list(devices);
784
785         for (std::map<size_t, std::string>::const_iterator i = devices.begin (); i != devices.end(); ++i) {
786                 if (i->second == device_name) {
787                         device_id = i->first;
788                         break;
789                 }
790         }
791         return device_id;
792 }
793
794 void *
795 CoreAudioBackend::coreaudio_process_thread (void *arg)
796 {
797         ThreadData* td = reinterpret_cast<ThreadData*> (arg);
798         boost::function<void ()> f = td->f;
799         delete td;
800         f ();
801         return 0;
802 }
803
804 int
805 CoreAudioBackend::create_process_thread (boost::function<void()> func)
806 {
807         pthread_t thread_id;
808         pthread_attr_t attr;
809         size_t stacksize = 100000;
810
811         ThreadData* td = new ThreadData (this, func, stacksize);
812
813         if (_realtime_pthread_create (SCHED_FIFO, -21, stacksize,
814                                       &thread_id, coreaudio_process_thread, td)) {
815                 pthread_attr_init (&attr);
816                 pthread_attr_setstacksize (&attr, stacksize);
817                 if (pthread_create (&thread_id, &attr, coreaudio_process_thread, td)) {
818                         PBD::error << _("AudioEngine: cannot create process thread.") << endmsg;
819                         pthread_attr_destroy (&attr);
820                         return -1;
821                 }
822                 pthread_attr_destroy (&attr);
823         }
824
825         _threads.push_back (thread_id);
826         return 0;
827 }
828
829 int
830 CoreAudioBackend::join_process_threads ()
831 {
832         int rv = 0;
833
834         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
835         {
836                 void *status;
837                 if (pthread_join (*i, &status)) {
838                         PBD::error << _("AudioEngine: cannot terminate process thread.") << endmsg;
839                         rv -= 1;
840                 }
841         }
842         _threads.clear ();
843         return rv;
844 }
845
846 bool
847 CoreAudioBackend::in_process_thread ()
848 {
849         if (pthread_equal (_main_thread, pthread_self()) != 0) {
850                 return true;
851         }
852
853         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
854         {
855                 if (pthread_equal (*i, pthread_self ()) != 0) {
856                         return true;
857                 }
858         }
859         return false;
860 }
861
862 uint32_t
863 CoreAudioBackend::process_thread_count ()
864 {
865         return _threads.size ();
866 }
867
868 void
869 CoreAudioBackend::update_latencies ()
870 {
871         // trigger latency callback in RT thread (locked graph)
872         port_connect_add_remove_callback();
873 }
874
875 /* PORTENGINE API */
876
877 void*
878 CoreAudioBackend::private_handle () const
879 {
880         return NULL;
881 }
882
883 const std::string&
884 CoreAudioBackend::my_name () const
885 {
886         return _instance_name;
887 }
888
889 bool
890 CoreAudioBackend::available () const
891 {
892         return _run && _active_fw && _active_ca;
893 }
894
895 uint32_t
896 CoreAudioBackend::port_name_size () const
897 {
898         return 256;
899 }
900
901 int
902 CoreAudioBackend::set_port_name (PortEngine::PortHandle port, const std::string& name)
903 {
904         if (!valid_port (port)) {
905                 PBD::warning << _("CoreAudioBackend::set_port_name: Invalid Port(s)") << endmsg;
906                 return -1;
907         }
908         return static_cast<CoreBackendPort*>(port)->set_name (_instance_name + ":" + name);
909 }
910
911 std::string
912 CoreAudioBackend::get_port_name (PortEngine::PortHandle port) const
913 {
914         if (!valid_port (port)) {
915                 PBD::warning << _("CoreAudioBackend::get_port_name: Invalid Port(s)") << endmsg;
916                 return std::string ();
917         }
918         return static_cast<CoreBackendPort*>(port)->name ();
919 }
920
921 int
922 CoreAudioBackend::get_port_property (PortHandle port, const std::string& key, std::string& value, std::string& type) const
923 {
924         if (!valid_port (port)) {
925                 PBD::warning << _("CoreAudioBackend::get_port_name: Invalid Port(s)") << endmsg;
926                 return -1;
927         }
928         if (key == "http://jackaudio.org/metadata/pretty-name") {
929                 type = "";
930                 value = static_cast<CoreBackendPort*>(port)->pretty_name ();
931                 if (!value.empty()) {
932                         return 0;
933                 }
934         }
935         return -1;
936 }
937
938 PortEngine::PortHandle
939 CoreAudioBackend::get_port_by_name (const std::string& name) const
940 {
941         PortHandle port = (PortHandle) find_port (name);
942         return port;
943 }
944
945 int
946 CoreAudioBackend::get_ports (
947         const std::string& port_name_pattern,
948         DataType type, PortFlags flags,
949         std::vector<std::string>& port_names) const
950 {
951         int rv = 0;
952         regex_t port_regex;
953         bool use_regexp = false;
954         if (port_name_pattern.size () > 0) {
955                 if (!regcomp (&port_regex, port_name_pattern.c_str (), REG_EXTENDED|REG_NOSUB)) {
956                         use_regexp = true;
957                 }
958         }
959         for (size_t i = 0; i < _ports.size (); ++i) {
960                 CoreBackendPort* port = _ports[i];
961                 if ((port->type () == type) && flags == (port->flags () & flags)) {
962                         if (!use_regexp || !regexec (&port_regex, port->name ().c_str (), 0, NULL, 0)) {
963                                 port_names.push_back (port->name ());
964                                 ++rv;
965                         }
966                 }
967         }
968         if (use_regexp) {
969                 regfree (&port_regex);
970         }
971         return rv;
972 }
973
974 DataType
975 CoreAudioBackend::port_data_type (PortEngine::PortHandle port) const
976 {
977         if (!valid_port (port)) {
978                 return DataType::NIL;
979         }
980         return static_cast<CoreBackendPort*>(port)->type ();
981 }
982
983 PortEngine::PortHandle
984 CoreAudioBackend::register_port (
985         const std::string& name,
986         ARDOUR::DataType type,
987         ARDOUR::PortFlags flags)
988 {
989         if (name.size () == 0) { return 0; }
990         if (flags & IsPhysical) { return 0; }
991         return add_port (_instance_name + ":" + name, type, flags);
992 }
993
994 PortEngine::PortHandle
995 CoreAudioBackend::add_port (
996         const std::string& name,
997         ARDOUR::DataType type,
998         ARDOUR::PortFlags flags)
999 {
1000         assert(name.size ());
1001         if (find_port (name)) {
1002                 PBD::warning << _("CoreAudioBackend::register_port: Port already exists:")
1003                              << " (" << name << ")" << endmsg;
1004                 return 0;
1005         }
1006         CoreBackendPort* port = NULL;
1007         switch (type) {
1008         case DataType::AUDIO:
1009                 port = new CoreAudioPort (*this, name, flags);
1010                 break;
1011         case DataType::MIDI:
1012                 port = new CoreMidiPort (*this, name, flags);
1013                 break;
1014         default:
1015                 PBD::error << _("CoreAudioBackend::register_port: Invalid Data Type.") << endmsg;
1016                 return 0;
1017         }
1018
1019         _ports.push_back (port);
1020
1021         return port;
1022 }
1023
1024 void
1025 CoreAudioBackend::unregister_port (PortEngine::PortHandle port_handle)
1026 {
1027         if (!_run) {
1028                 return;
1029         }
1030         CoreBackendPort* port = static_cast<CoreBackendPort*>(port_handle);
1031         std::vector<CoreBackendPort*>::iterator i = std::find (_ports.begin (), _ports.end (), static_cast<CoreBackendPort*>(port_handle));
1032         if (i == _ports.end ()) {
1033                 PBD::warning << _("CoreAudioBackend::unregister_port: Failed to find port") << endmsg;
1034                 return;
1035         }
1036         disconnect_all(port_handle);
1037         _ports.erase (i);
1038         delete port;
1039 }
1040
1041 int
1042 CoreAudioBackend::register_system_audio_ports()
1043 {
1044         LatencyRange lr;
1045
1046         const uint32_t a_ins = _n_inputs;
1047         const uint32_t a_out = _n_outputs;
1048
1049         const uint32_t coreaudio_reported_input_latency = _pcmio->get_latency(name_to_id(_input_audio_device), true);
1050         const uint32_t coreaudio_reported_output_latency = _pcmio->get_latency(name_to_id(_output_audio_device), false);
1051
1052 #ifndef NDEBUG
1053         printf("COREAUDIO LATENCY: i:%d, o:%d\n",
1054                coreaudio_reported_input_latency,
1055                coreaudio_reported_output_latency);
1056 #endif
1057
1058         /* audio ports */
1059         lr.min = lr.max = coreaudio_reported_input_latency + (_measure_latency ? 0 : _systemic_audio_input_latency);
1060         for (uint32_t i = 0; i < a_ins; ++i) {
1061                 char tmp[64];
1062                 snprintf(tmp, sizeof(tmp), "system:capture_%d", i+1);
1063                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
1064                 if (!p) return -1;
1065                 set_latency_range (p, false, lr);
1066                 CoreBackendPort *cp = static_cast<CoreBackendPort*>(p);
1067                 cp->set_pretty_name (_pcmio->cached_port_name(i, true));
1068                 _system_inputs.push_back(cp);
1069         }
1070
1071         lr.min = lr.max = coreaudio_reported_output_latency + (_measure_latency ? 0 : _systemic_audio_output_latency);
1072         for (uint32_t i = 0; i < a_out; ++i) {
1073                 char tmp[64];
1074                 snprintf(tmp, sizeof(tmp), "system:playback_%d", i+1);
1075                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
1076                 if (!p) return -1;
1077                 set_latency_range (p, true, lr);
1078                 CoreBackendPort *cp = static_cast<CoreBackendPort*>(p);
1079                 cp->set_pretty_name (_pcmio->cached_port_name(i, false));
1080                 _system_outputs.push_back(cp);
1081         }
1082         return 0;
1083 }
1084
1085 void
1086 CoreAudioBackend::coremidi_rediscover()
1087 {
1088         if (!_run) { return; }
1089         assert(_midi_driver_option == _("CoreMidi"));
1090
1091         pthread_mutex_lock (&_process_callback_mutex);
1092
1093         for (std::vector<CoreBackendPort*>::iterator it = _system_midi_out.begin (); it != _system_midi_out.end ();) {
1094                 bool found = false;
1095                 for (size_t i = 0; i < _midiio->n_midi_outputs(); ++i) {
1096                         if ((*it)->name() == _midiio->port_id(i, false)) {
1097                                 found = true;
1098                                 break;
1099                         }
1100                 }
1101                 if (found) {
1102                         ++it;
1103                 } else {
1104 #ifndef NDEBUG
1105                         printf("unregister MIDI Output: %s\n", (*it)->name().c_str());
1106 #endif
1107                         _port_change_flag = true;
1108                         unregister_port((*it));
1109                         it = _system_midi_out.erase(it);
1110                 }
1111         }
1112
1113         for (std::vector<CoreBackendPort*>::iterator it = _system_midi_in.begin (); it != _system_midi_in.end ();) {
1114                 bool found = false;
1115                 for (size_t i = 0; i < _midiio->n_midi_inputs(); ++i) {
1116                         if ((*it)->name() == _midiio->port_id(i, true)) {
1117                                 found = true;
1118                                 break;
1119                         }
1120                 }
1121                 if (found) {
1122                         ++it;
1123                 } else {
1124 #ifndef NDEBUG
1125                         printf("unregister MIDI Input: %s\n", (*it)->name().c_str());
1126 #endif
1127                         _port_change_flag = true;
1128                         unregister_port((*it));
1129                         it = _system_midi_in.erase(it);
1130                 }
1131         }
1132
1133         for (size_t i = 0; i < _midiio->n_midi_inputs(); ++i) {
1134                 std::string name = _midiio->port_id(i, true);
1135                 if (find_port_in(_system_midi_in, name)) {
1136                         continue;
1137                 }
1138
1139 #ifndef NDEBUG
1140                 printf("register MIDI Input: %s\n", name.c_str());
1141 #endif
1142                 PortHandle p = add_port(name, DataType::MIDI, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
1143                 if (!p) {
1144                         fprintf(stderr, "failed to register MIDI IN: %s\n", name.c_str());
1145                         continue;
1146                 }
1147                 LatencyRange lr;
1148                 lr.min = lr.max = _samples_per_period; // TODO add per-port midi-systemic latency
1149                 set_latency_range (p, false, lr);
1150                 CoreBackendPort *pp = static_cast<CoreBackendPort*>(p);
1151                 pp->set_pretty_name(_midiio->port_name(i, true));
1152                 _system_midi_in.push_back(pp);
1153                 _port_change_flag = true;
1154         }
1155
1156         for (size_t i = 0; i < _midiio->n_midi_outputs(); ++i) {
1157                 std::string name = _midiio->port_id(i, false);
1158                 if (find_port_in(_system_midi_out, name)) {
1159                         continue;
1160                 }
1161
1162 #ifndef NDEBUG
1163                 printf("register MIDI OUT: %s\n", name.c_str());
1164 #endif
1165                 PortHandle p = add_port(name, DataType::MIDI, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
1166                 if (!p) {
1167                         fprintf(stderr, "failed to register MIDI OUT: %s\n", name.c_str());
1168                         continue;
1169                 }
1170                 LatencyRange lr;
1171                 lr.min = lr.max = _samples_per_period; // TODO add per-port midi-systemic latency
1172                 set_latency_range (p, false, lr);
1173                 CoreBackendPort *pp = static_cast<CoreBackendPort*>(p);
1174                 pp->set_pretty_name(_midiio->port_name(i, false));
1175                 _system_midi_out.push_back(pp);
1176                 _port_change_flag = true;
1177         }
1178
1179
1180         assert(_system_midi_out.size() == _midiio->n_midi_outputs());
1181         assert(_system_midi_in.size() == _midiio->n_midi_inputs());
1182
1183         pthread_mutex_unlock (&_process_callback_mutex);
1184 }
1185
1186 void
1187 CoreAudioBackend::unregister_ports (bool system_only)
1188 {
1189         size_t i = 0;
1190         _system_inputs.clear();
1191         _system_outputs.clear();
1192         _system_midi_in.clear();
1193         _system_midi_out.clear();
1194         while (i <  _ports.size ()) {
1195                 CoreBackendPort* port = _ports[i];
1196                 if (! system_only || (port->is_physical () && port->is_terminal ())) {
1197                         port->disconnect_all ();
1198                         delete port;
1199                         _ports.erase (_ports.begin() + i);
1200                 } else {
1201                         ++i;
1202                 }
1203         }
1204 }
1205
1206 int
1207 CoreAudioBackend::connect (const std::string& src, const std::string& dst)
1208 {
1209         CoreBackendPort* src_port = find_port (src);
1210         CoreBackendPort* dst_port = find_port (dst);
1211
1212         if (!src_port) {
1213                 PBD::warning << _("CoreAudioBackend::connect: Invalid Source port:")
1214                              << " (" << src <<")" << endmsg;
1215                 return -1;
1216         }
1217         if (!dst_port) {
1218                 PBD::warning << _("CoreAudioBackend::connect: Invalid Destination port:")
1219                              << " (" << dst <<")" << endmsg;
1220                 return -1;
1221         }
1222         return src_port->connect (dst_port);
1223 }
1224
1225 int
1226 CoreAudioBackend::disconnect (const std::string& src, const std::string& dst)
1227 {
1228         CoreBackendPort* src_port = find_port (src);
1229         CoreBackendPort* dst_port = find_port (dst);
1230
1231         if (!src_port || !dst_port) {
1232                 PBD::warning << _("CoreAudioBackend::disconnect: Invalid Port(s)") << endmsg;
1233                 return -1;
1234         }
1235         return src_port->disconnect (dst_port);
1236 }
1237
1238 int
1239 CoreAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
1240 {
1241         CoreBackendPort* dst_port = find_port (dst);
1242         if (!valid_port (src)) {
1243                 PBD::warning << _("CoreAudioBackend::connect: Invalid Source Port Handle") << endmsg;
1244                 return -1;
1245         }
1246         if (!dst_port) {
1247                 PBD::warning << _("CoreAudioBackend::connect: Invalid Destination Port")
1248                              << " (" << dst << ")" << endmsg;
1249                 return -1;
1250         }
1251         return static_cast<CoreBackendPort*>(src)->connect (dst_port);
1252 }
1253
1254 int
1255 CoreAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
1256 {
1257         CoreBackendPort* dst_port = find_port (dst);
1258         if (!valid_port (src) || !dst_port) {
1259                 PBD::warning << _("CoreAudioBackend::disconnect: Invalid Port(s)") << endmsg;
1260                 return -1;
1261         }
1262         return static_cast<CoreBackendPort*>(src)->disconnect (dst_port);
1263 }
1264
1265 int
1266 CoreAudioBackend::disconnect_all (PortEngine::PortHandle port)
1267 {
1268         if (!valid_port (port)) {
1269                 PBD::warning << _("CoreAudioBackend::disconnect_all: Invalid Port") << endmsg;
1270                 return -1;
1271         }
1272         static_cast<CoreBackendPort*>(port)->disconnect_all ();
1273         return 0;
1274 }
1275
1276 bool
1277 CoreAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
1278 {
1279         if (!valid_port (port)) {
1280                 PBD::warning << _("CoreAudioBackend::disconnect_all: Invalid Port") << endmsg;
1281                 return false;
1282         }
1283         return static_cast<CoreBackendPort*>(port)->is_connected ();
1284 }
1285
1286 bool
1287 CoreAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
1288 {
1289         CoreBackendPort* dst_port = find_port (dst);
1290         if (!valid_port (src) || !dst_port) {
1291                 PBD::warning << _("CoreAudioBackend::connected_to: Invalid Port") << endmsg;
1292                 return false;
1293         }
1294         return static_cast<CoreBackendPort*>(src)->is_connected (dst_port);
1295 }
1296
1297 bool
1298 CoreAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
1299 {
1300         if (!valid_port (port)) {
1301                 PBD::warning << _("CoreAudioBackend::physically_connected: Invalid Port") << endmsg;
1302                 return false;
1303         }
1304         return static_cast<CoreBackendPort*>(port)->is_physically_connected ();
1305 }
1306
1307 int
1308 CoreAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
1309 {
1310         if (!valid_port (port)) {
1311                 PBD::warning << _("CoreAudioBackend::get_connections: Invalid Port") << endmsg;
1312                 return -1;
1313         }
1314
1315         assert (0 == names.size ());
1316
1317         const std::vector<CoreBackendPort*>& connected_ports = static_cast<CoreBackendPort*>(port)->get_connections ();
1318
1319         for (std::vector<CoreBackendPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
1320                 names.push_back ((*i)->name ());
1321         }
1322
1323         return (int)names.size ();
1324 }
1325
1326 /* MIDI */
1327 int
1328 CoreAudioBackend::midi_event_get (
1329         pframes_t& timestamp,
1330         size_t& size, uint8_t** buf, void* port_buffer,
1331         uint32_t event_index)
1332 {
1333         if (!buf || !port_buffer) return -1;
1334         CoreMidiBuffer& source = * static_cast<CoreMidiBuffer*>(port_buffer);
1335         if (event_index >= source.size ()) {
1336                 return -1;
1337         }
1338         CoreMidiEvent * const event = source[event_index].get ();
1339
1340         timestamp = event->timestamp ();
1341         size = event->size ();
1342         *buf = event->data ();
1343         return 0;
1344 }
1345
1346 int
1347 CoreAudioBackend::_midi_event_put (
1348         void* port_buffer,
1349         pframes_t timestamp,
1350         const uint8_t* buffer, size_t size)
1351 {
1352         if (!buffer || !port_buffer) return -1;
1353         CoreMidiBuffer& dst = * static_cast<CoreMidiBuffer*>(port_buffer);
1354         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
1355 #ifndef NDEBUG
1356                 // nevermind, ::get_buffer() sorts events
1357                 fprintf (stderr, "CoreMidiBuffer: unordered event: %d > %d\n",
1358                          (pframes_t)dst.back ()->timestamp (), timestamp);
1359 #endif
1360         }
1361         dst.push_back (boost::shared_ptr<CoreMidiEvent>(new CoreMidiEvent (timestamp, buffer, size)));
1362         return 0;
1363 }
1364
1365
1366 uint32_t
1367 CoreAudioBackend::get_midi_event_count (void* port_buffer)
1368 {
1369         if (!port_buffer) return 0;
1370         return static_cast<CoreMidiBuffer*>(port_buffer)->size ();
1371 }
1372
1373 void
1374 CoreAudioBackend::midi_clear (void* port_buffer)
1375 {
1376         if (!port_buffer) return;
1377         CoreMidiBuffer * buf = static_cast<CoreMidiBuffer*>(port_buffer);
1378         assert (buf);
1379         buf->clear ();
1380 }
1381
1382 /* Monitoring */
1383
1384 bool
1385 CoreAudioBackend::can_monitor_input () const
1386 {
1387         return false;
1388 }
1389
1390 int
1391 CoreAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1392 {
1393         return -1;
1394 }
1395
1396 int
1397 CoreAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1398 {
1399         return -1;
1400 }
1401
1402 bool
1403 CoreAudioBackend::monitoring_input (PortEngine::PortHandle)
1404 {
1405         return false;
1406 }
1407
1408 /* Latency management */
1409
1410 void
1411 CoreAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1412 {
1413         if (!valid_port (port)) {
1414                 PBD::warning << _("CoreBackendPort::set_latency_range (): invalid port.") << endmsg;
1415                 return;
1416         }
1417         static_cast<CoreBackendPort*>(port)->set_latency_range (latency_range, for_playback);
1418 }
1419
1420 LatencyRange
1421 CoreAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1422 {
1423         LatencyRange r;
1424         if (!valid_port (port)) {
1425                 PBD::warning << _("CoreBackendPort::get_latency_range (): invalid port.") << endmsg;
1426                 r.min = 0;
1427                 r.max = 0;
1428                 return r;
1429         }
1430         CoreBackendPort* p = static_cast<CoreBackendPort*>(port);
1431         assert(p);
1432
1433         r = p->latency_range (for_playback);
1434         if (p->is_physical() && p->is_terminal() && p->type() == DataType::AUDIO) {
1435                 if (p->is_input() && for_playback) {
1436                         r.min += _samples_per_period;
1437                         r.max += _samples_per_period;
1438                 }
1439                 if (p->is_output() && !for_playback) {
1440                         r.min += _samples_per_period;
1441                         r.max += _samples_per_period;
1442                 }
1443         }
1444         return r;
1445 }
1446
1447 /* Discovering physical ports */
1448
1449 bool
1450 CoreAudioBackend::port_is_physical (PortEngine::PortHandle port) const
1451 {
1452         if (!valid_port (port)) {
1453                 PBD::warning << _("CoreBackendPort::port_is_physical (): invalid port.") << endmsg;
1454                 return false;
1455         }
1456         return static_cast<CoreBackendPort*>(port)->is_physical ();
1457 }
1458
1459 void
1460 CoreAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1461 {
1462         for (size_t i = 0; i < _ports.size (); ++i) {
1463                 CoreBackendPort* port = _ports[i];
1464                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1465                         port_names.push_back (port->name ());
1466                 }
1467         }
1468 }
1469
1470 void
1471 CoreAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1472 {
1473         for (size_t i = 0; i < _ports.size (); ++i) {
1474                 CoreBackendPort* port = _ports[i];
1475                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1476                         port_names.push_back (port->name ());
1477                 }
1478         }
1479 }
1480
1481 ChanCount
1482 CoreAudioBackend::n_physical_outputs () const
1483 {
1484         int n_midi = 0;
1485         int n_audio = 0;
1486         for (size_t i = 0; i < _ports.size (); ++i) {
1487                 CoreBackendPort* port = _ports[i];
1488                 if (port->is_output () && port->is_physical ()) {
1489                         switch (port->type ()) {
1490                         case DataType::AUDIO: ++n_audio; break;
1491                         case DataType::MIDI: ++n_midi; break;
1492                         default: break;
1493                         }
1494                 }
1495         }
1496         ChanCount cc;
1497         cc.set (DataType::AUDIO, n_audio);
1498         cc.set (DataType::MIDI, n_midi);
1499         return cc;
1500 }
1501
1502 ChanCount
1503 CoreAudioBackend::n_physical_inputs () const
1504 {
1505         int n_midi = 0;
1506         int n_audio = 0;
1507         for (size_t i = 0; i < _ports.size (); ++i) {
1508                 CoreBackendPort* port = _ports[i];
1509                 if (port->is_input () && port->is_physical ()) {
1510                         switch (port->type ()) {
1511                         case DataType::AUDIO: ++n_audio; break;
1512                         case DataType::MIDI: ++n_midi; break;
1513                         default: break;
1514                         }
1515                 }
1516         }
1517         ChanCount cc;
1518         cc.set (DataType::AUDIO, n_audio);
1519         cc.set (DataType::MIDI, n_midi);
1520         return cc;
1521 }
1522
1523 /* Getting access to the data buffer for a port */
1524
1525 void*
1526 CoreAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1527 {
1528         if (!port || !valid_port (port)) return NULL;
1529         return static_cast<CoreBackendPort*>(port)->get_buffer (nframes);
1530 }
1531
1532 void
1533 CoreAudioBackend::pre_process ()
1534 {
1535         bool connections_changed = false;
1536         bool ports_changed = false;
1537         if (!pthread_mutex_trylock (&_port_callback_mutex)) {
1538                 if (_port_change_flag) {
1539                         ports_changed = true;
1540                         _port_change_flag = false;
1541                 }
1542                 if (!_port_connection_queue.empty ()) {
1543                         connections_changed = true;
1544                 }
1545                 while (!_port_connection_queue.empty ()) {
1546                         PortConnectData *c = _port_connection_queue.back ();
1547                         manager.connect_callback (c->a, c->b, c->c);
1548                         _port_connection_queue.pop_back ();
1549                         delete c;
1550                 }
1551                 pthread_mutex_unlock (&_port_callback_mutex);
1552         }
1553         if (ports_changed) {
1554                 manager.registration_callback();
1555         }
1556         if (connections_changed) {
1557                 manager.graph_order_callback();
1558         }
1559         if (connections_changed || ports_changed) {
1560                 engine.latency_callback(false);
1561                 engine.latency_callback(true);
1562         }
1563 }
1564
1565 void
1566 CoreAudioBackend::reset_midi_parsers ()
1567 {
1568         for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it) {
1569                 CoreMidiPort* port = dynamic_cast<CoreMidiPort*>(*it);
1570                 if (port) {
1571                         port->reset_parser ();
1572                 }
1573         }
1574 }
1575
1576 void *
1577 CoreAudioBackend::freewheel_thread ()
1578 {
1579         _active_fw = true;
1580         bool first_run = false;
1581         /* Freewheeling - use for export.   The first call to
1582          * engine.process_callback() after engine.freewheel_callback will
1583          * if the first export cycle.
1584          * For reliable precise export timing, the calls need to be in sync.
1585          *
1586          * Furthermore we need to make sure the registered process thread
1587          * is correct.
1588          *
1589          * _freewheeling = GUI thread state as set by ::freewheel()
1590          * _freewheel = in sync here (export thread)
1591          */
1592         pthread_mutex_lock (&_freewheel_mutex);
1593         while (_run) {
1594                 // check if we should run,
1595                 if (_freewheeling != _freewheel) {
1596                         if (!_freewheeling) {
1597                                 // prepare leaving freewheeling mode
1598                                 _freewheel = false; // first mark as disabled
1599                                 _reinit_thread_callback = true; // hand over _main_thread
1600                                 _freewheel_ack = false; // prepare next handshake
1601                                 reset_midi_parsers ();
1602                                 _midiio->set_enabled(true);
1603                                 engine.freewheel_callback (_freewheeling);
1604                         } else {
1605                                 first_run = true;
1606                                 _freewheel = true;
1607                         }
1608                 }
1609
1610                 if (!_freewheel || !_freewheel_ack) {
1611                         // wait for a change, we use a timed wait to
1612                         // terminate early in case some error sets _run = 0
1613                         struct timeval tv;
1614                         struct timespec ts;
1615                         gettimeofday (&tv, NULL);
1616                         ts.tv_sec = tv.tv_sec + 3;
1617                         ts.tv_nsec = 0;
1618                         pthread_cond_timedwait (&_freewheel_signal, &_freewheel_mutex, &ts);
1619                         continue;
1620                 }
1621
1622                 if (first_run) {
1623                         // tell the engine we're ready to GO.
1624                         engine.freewheel_callback (_freewheeling);
1625                         first_run = false;
1626                         _main_thread = pthread_self();
1627                         AudioEngine::thread_init_callback (this);
1628                         _midiio->set_enabled(false);
1629                         reset_midi_parsers ();
1630                 }
1631
1632                 // process port updates first in every cycle.
1633                 pre_process();
1634
1635                 // prevent coreaudio device changes
1636                 pthread_mutex_lock (&_process_callback_mutex);
1637
1638                 /* Freewheelin' */
1639
1640                 // clear input buffers
1641                 for (std::vector<CoreBackendPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
1642                         memset ((*it)->get_buffer (_samples_per_period), 0, _samples_per_period * sizeof (Sample));
1643                 }
1644                 for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it) {
1645                         static_cast<CoreMidiBuffer*>((*it)->get_buffer(0))->clear ();
1646                 }
1647
1648                 _last_process_start = 0;
1649                 if (engine.process_callback (_samples_per_period)) {
1650                         pthread_mutex_unlock (&_process_callback_mutex);
1651                         break;
1652                 }
1653
1654                 pthread_mutex_unlock (&_process_callback_mutex);
1655                 _dsp_load = 1.0;
1656                 Glib::usleep (100); // don't hog cpu
1657         }
1658
1659         pthread_mutex_unlock (&_freewheel_mutex);
1660
1661         _active_fw = false;
1662
1663         if (_run) {
1664                 // engine.process_callback() returner error
1665                 engine.halted_callback("CoreAudio Freehweeling aborted.");
1666         }
1667         return 0;
1668 }
1669 int
1670 CoreAudioBackend::process_callback (const uint32_t n_samples, const uint64_t host_time)
1671 {
1672         uint32_t i = 0;
1673         uint64_t clock1;
1674
1675         _active_ca = true;
1676
1677         if (_run && _freewheel && !_freewheel_ack) {
1678                 // acknowledge freewheeling; hand-over thread ID
1679                 pthread_mutex_lock (&_freewheel_mutex);
1680                 if (_freewheel) _freewheel_ack = true;
1681                 pthread_cond_signal (&_freewheel_signal);
1682                 pthread_mutex_unlock (&_freewheel_mutex);
1683         }
1684
1685         if (!_run || _freewheel || _preinit) {
1686                 // NB if we return 1, the output is
1687                 // zeroed by the coreaudio callback
1688                 return 1;
1689         }
1690
1691         if (_reinit_thread_callback || _main_thread != pthread_self()) {
1692                 _reinit_thread_callback = false;
1693                 _main_thread = pthread_self();
1694                 AudioEngine::thread_init_callback (this);
1695         }
1696
1697         if (pthread_mutex_trylock (&_process_callback_mutex)) {
1698                 // block while devices are added/removed
1699 #ifndef NDEBUG
1700                 printf("Xrun due to device change\n");
1701 #endif
1702                 engine.Xrun();
1703                 return 1;
1704         }
1705         /* port-connection change */
1706         pre_process();
1707
1708         // cycle-length in usec
1709         const double nominal_time = 1e6 * n_samples / _samplerate;
1710
1711         clock1 = g_get_monotonic_time();
1712
1713         /* get midi */
1714         i=0;
1715         for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++i) {
1716                 CoreMidiPort* port = dynamic_cast<CoreMidiPort*> (*it);
1717                 if (!port) {
1718                         continue;
1719                 }
1720                 uint64_t time_ns;
1721                 uint8_t data[128]; // matches CoreMidi's MIDIPacket
1722                 size_t size = sizeof(data);
1723
1724                 port->clear_events ();
1725
1726                 while (_midiio->recv_event (i, nominal_time, time_ns, data, size)) {
1727                         pframes_t time = floor((float) time_ns * _samplerate * 1e-9);
1728                         assert (time < n_samples);
1729                         port->parse_events (time, data, size);
1730                         size = sizeof(data); /* prepare for next call to recv_event */
1731                 }
1732         }
1733
1734         /* get audio */
1735         i = 0;
1736         for (std::vector<CoreBackendPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++i) {
1737                 _pcmio->get_capture_channel (i, (float*)((*it)->get_buffer(n_samples)), n_samples);
1738         }
1739
1740         /* clear output buffers */
1741         for (std::vector<CoreBackendPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it) {
1742                 memset ((*it)->get_buffer (n_samples), 0, n_samples * sizeof (Sample));
1743         }
1744
1745         _midiio->start_cycle();
1746         _last_process_start = host_time;
1747
1748         if (engine.process_callback (n_samples)) {
1749                 fprintf(stderr, "ENGINE PROCESS ERROR\n");
1750                 //_pcmio->pcm_stop ();
1751                 _active_ca = false;
1752                 pthread_mutex_unlock (&_process_callback_mutex);
1753                 return -1;
1754         }
1755
1756         /* mixdown midi */
1757         for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it) {
1758                 static_cast<CoreMidiPort*>(*it)->get_buffer(0);
1759         }
1760
1761         /* queue outgoing midi */
1762         i = 0;
1763         for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it, ++i) {
1764 #if 0 // something's still b0rked with CoreMidiIo::send_events()
1765                 const CoreMidiBuffer *src = static_cast<const CoreMidiPort*>(*it)->const_buffer();
1766                 _midiio->send_events (i, nominal_time, (void*)src);
1767 #else // works..
1768                 const CoreMidiBuffer *src = static_cast<const CoreMidiPort*>(*it)->const_buffer();
1769                 for (CoreMidiBuffer::const_iterator mit = src->begin (); mit != src->end (); ++mit) {
1770                         _midiio->send_event (i, (*mit)->timestamp() / nominal_time, (*mit)->data(), (*mit)->size());
1771                 }
1772 #endif
1773         }
1774
1775         /* write back audio */
1776         i = 0;
1777         for (std::vector<CoreBackendPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it, ++i) {
1778                 _pcmio->set_playback_channel (i, (float const*)(*it)->get_buffer (n_samples), n_samples);
1779         }
1780
1781         _processed_samples += n_samples;
1782
1783         /* calc DSP load. */
1784         _dsp_load_calc.set_max_time (_samplerate, _samples_per_period);
1785         _dsp_load_calc.set_start_timestamp_us (clock1);
1786         _dsp_load_calc.set_stop_timestamp_us (g_get_monotonic_time());
1787         _dsp_load = _dsp_load_calc.get_dsp_load ();
1788
1789         pthread_mutex_unlock (&_process_callback_mutex);
1790         return 0;
1791 }
1792
1793 void
1794 CoreAudioBackend::error_callback ()
1795 {
1796         _pcmio->set_error_callback (NULL, NULL);
1797         _pcmio->set_sample_rate_callback (NULL, NULL);
1798         _pcmio->set_xrun_callback (NULL, NULL);
1799         _midiio->set_port_changed_callback(NULL, NULL);
1800         engine.halted_callback("CoreAudio Process aborted.");
1801         _active_ca = false;
1802 }
1803
1804 void
1805 CoreAudioBackend::xrun_callback ()
1806 {
1807         engine.Xrun ();
1808 }
1809
1810 void
1811 CoreAudioBackend::buffer_size_callback ()
1812 {
1813         uint32_t bs = _pcmio->samples_per_period();
1814         if (bs == _samples_per_period) {
1815                 return;
1816         }
1817         _samples_per_period = bs;
1818         engine.buffer_size_change (_samples_per_period);
1819 }
1820
1821 void
1822 CoreAudioBackend::sample_rate_callback ()
1823 {
1824         if (_preinit) {
1825 #ifndef NDEBUG
1826                 printf("Samplerate change during initialization.\n");
1827 #endif
1828                 return;
1829         }
1830         _pcmio->set_error_callback (NULL, NULL);
1831         _pcmio->set_sample_rate_callback (NULL, NULL);
1832         _pcmio->set_xrun_callback (NULL, NULL);
1833         _midiio->set_port_changed_callback(NULL, NULL);
1834         engine.halted_callback("Sample Rate Changed.");
1835         stop();
1836 }
1837
1838 void
1839 CoreAudioBackend::hw_changed_callback ()
1840 {
1841         _reinit_thread_callback = true;
1842         engine.request_device_list_update();
1843 }
1844
1845 /******************************************************************************/
1846
1847 static boost::shared_ptr<CoreAudioBackend> _instance;
1848
1849 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
1850 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
1851 static int deinstantiate ();
1852 static bool already_configured ();
1853 static bool available ();
1854
1855 static ARDOUR::AudioBackendInfo _descriptor = {
1856         "CoreAudio",
1857         instantiate,
1858         deinstantiate,
1859         backend_factory,
1860         already_configured,
1861         available
1862 };
1863
1864 static boost::shared_ptr<AudioBackend>
1865 backend_factory (AudioEngine& e)
1866 {
1867         if (!_instance) {
1868                 _instance.reset (new CoreAudioBackend (e, _descriptor));
1869         }
1870         return _instance;
1871 }
1872
1873 static int
1874 instantiate (const std::string& arg1, const std::string& /* arg2 */)
1875 {
1876         s_instance_name = arg1;
1877         return 0;
1878 }
1879
1880 static int
1881 deinstantiate ()
1882 {
1883         _instance.reset ();
1884         return 0;
1885 }
1886
1887 static bool
1888 already_configured ()
1889 {
1890         return false;
1891 }
1892
1893 static bool
1894 available ()
1895 {
1896         return true;
1897 }
1898
1899 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
1900 {
1901         return &_descriptor;
1902 }
1903
1904
1905 /******************************************************************************/
1906 CoreBackendPort::CoreBackendPort (CoreAudioBackend &b, const std::string& name, PortFlags flags)
1907         : _osx_backend (b)
1908         , _name  (name)
1909         , _flags (flags)
1910 {
1911         _capture_latency_range.min = 0;
1912         _capture_latency_range.max = 0;
1913         _playback_latency_range.min = 0;
1914         _playback_latency_range.max = 0;
1915 }
1916
1917 CoreBackendPort::~CoreBackendPort () {
1918         disconnect_all ();
1919 }
1920
1921
1922 int CoreBackendPort::connect (CoreBackendPort *port)
1923 {
1924         if (!port) {
1925                 PBD::warning << _("CoreBackendPort::connect (): invalid (null) port") << endmsg;
1926                 return -1;
1927         }
1928
1929         if (type () != port->type ()) {
1930                 PBD::warning << _("CoreBackendPort::connect (): wrong port-type") << endmsg;
1931                 return -1;
1932         }
1933
1934         if (is_output () && port->is_output ()) {
1935                 PBD::warning << _("CoreBackendPort::connect (): cannot inter-connect output ports.") << endmsg;
1936                 return -1;
1937         }
1938
1939         if (is_input () && port->is_input ()) {
1940                 PBD::warning << _("CoreBackendPort::connect (): cannot inter-connect input ports.") << endmsg;
1941                 return -1;
1942         }
1943
1944         if (this == port) {
1945                 PBD::warning << _("CoreBackendPort::connect (): cannot self-connect ports.") << endmsg;
1946                 return -1;
1947         }
1948
1949         if (is_connected (port)) {
1950 #if 0 // don't bother to warn about this for now. just ignore it
1951                 PBD::info << _("CoreBackendPort::connect (): ports are already connected:")
1952                           << " (" << name () << ") -> (" << port->name () << ")"
1953                           << endmsg;
1954 #endif
1955                 return -1;
1956         }
1957
1958         _connect (port, true);
1959         return 0;
1960 }
1961
1962
1963 void CoreBackendPort::_connect (CoreBackendPort *port, bool callback)
1964 {
1965         _connections.push_back (port);
1966         if (callback) {
1967                 port->_connect (this, false);
1968                 _osx_backend.port_connect_callback (name(),  port->name(), true);
1969         }
1970 }
1971
1972 int CoreBackendPort::disconnect (CoreBackendPort *port)
1973 {
1974         if (!port) {
1975                 PBD::warning << _("CoreBackendPort::disconnect (): invalid (null) port") << endmsg;
1976                 return -1;
1977         }
1978
1979         if (!is_connected (port)) {
1980                 PBD::warning << _("CoreBackendPort::disconnect (): ports are not connected:")
1981                              << " (" << name () << ") -> (" << port->name () << ")"
1982                              << endmsg;
1983                 return -1;
1984         }
1985         _disconnect (port, true);
1986         return 0;
1987 }
1988
1989 void CoreBackendPort::_disconnect (CoreBackendPort *port, bool callback)
1990 {
1991         std::vector<CoreBackendPort*>::iterator it = std::find (_connections.begin (), _connections.end (), port);
1992
1993         assert (it != _connections.end ());
1994
1995         _connections.erase (it);
1996
1997         if (callback) {
1998                 port->_disconnect (this, false);
1999                 _osx_backend.port_connect_callback (name(),  port->name(), false);
2000         }
2001 }
2002
2003
2004 void CoreBackendPort::disconnect_all ()
2005 {
2006         while (!_connections.empty ()) {
2007                 _connections.back ()->_disconnect (this, false);
2008                 _osx_backend.port_connect_callback (name(),  _connections.back ()->name(), false);
2009                 _connections.pop_back ();
2010         }
2011 }
2012
2013 bool
2014 CoreBackendPort::is_connected (const CoreBackendPort *port) const
2015 {
2016         return std::find (_connections.begin (), _connections.end (), port) != _connections.end ();
2017 }
2018
2019 bool CoreBackendPort::is_physically_connected () const
2020 {
2021         for (std::vector<CoreBackendPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
2022                 if ((*it)->is_physical ()) {
2023                         return true;
2024                 }
2025         }
2026         return false;
2027 }
2028
2029 /******************************************************************************/
2030
2031 CoreAudioPort::CoreAudioPort (CoreAudioBackend &b, const std::string& name, PortFlags flags)
2032         : CoreBackendPort (b, name, flags)
2033 {
2034         memset (_buffer, 0, sizeof (_buffer));
2035         mlock(_buffer, sizeof (_buffer));
2036 }
2037
2038 CoreAudioPort::~CoreAudioPort () { }
2039
2040 void* CoreAudioPort::get_buffer (pframes_t n_samples)
2041 {
2042         if (is_input ()) {
2043                 std::vector<CoreBackendPort*>::const_iterator it = get_connections ().begin ();
2044                 if (it == get_connections ().end ()) {
2045                         memset (_buffer, 0, n_samples * sizeof (Sample));
2046                 } else {
2047                         CoreAudioPort const * source = static_cast<const CoreAudioPort*>(*it);
2048                         assert (source && source->is_output ());
2049                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
2050                         while (++it != get_connections ().end ()) {
2051                                 source = static_cast<const CoreAudioPort*>(*it);
2052                                 assert (source && source->is_output ());
2053                                 Sample* dst = buffer ();
2054                                 const Sample* src = source->const_buffer ();
2055                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
2056                                         *dst += *src;
2057                                 }
2058                         }
2059                 }
2060         }
2061         return _buffer;
2062 }
2063
2064
2065 CoreMidiPort::CoreMidiPort (CoreAudioBackend &b, const std::string& name, PortFlags flags)
2066         : CoreBackendPort (b, name, flags)
2067         , _n_periods (1)
2068         , _bufperiod (0)
2069         , _event (0, 0)
2070         , _first_time(true)
2071         , _unbuffered_bytes(0)
2072         , _total_bytes(0)
2073         , _expected_bytes(0)
2074         , _status_byte(0)
2075
2076 {
2077         _buffer[0].clear ();
2078         _buffer[1].clear ();
2079 }
2080
2081 CoreMidiPort::~CoreMidiPort () { }
2082
2083 struct MidiEventSorter {
2084         bool operator() (const boost::shared_ptr<CoreMidiEvent>& a, const boost::shared_ptr<CoreMidiEvent>& b) {
2085                 return *a < *b;
2086         }
2087 };
2088
2089 void* CoreMidiPort::get_buffer (pframes_t /* nframes */)
2090 {
2091         if (is_input ()) {
2092                 (_buffer[_bufperiod]).clear ();
2093                 for (std::vector<CoreBackendPort*>::const_iterator i = get_connections ().begin ();
2094                      i != get_connections ().end ();
2095                      ++i) {
2096                         const CoreMidiBuffer * src = static_cast<const CoreMidiPort*>(*i)->const_buffer ();
2097                         for (CoreMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
2098                                 (_buffer[_bufperiod]).push_back (boost::shared_ptr<CoreMidiEvent>(new CoreMidiEvent (**it)));
2099                         }
2100                 }
2101                 std::sort ((_buffer[_bufperiod]).begin (), (_buffer[_bufperiod]).end (), MidiEventSorter());
2102         }
2103
2104         return &(_buffer[_bufperiod]);
2105 }
2106
2107 int
2108 CoreMidiPort::queue_event (
2109         void* port_buffer,
2110         pframes_t timestamp,
2111         const uint8_t* buffer, size_t size)
2112 {
2113         const int ret = CoreAudioBackend::_midi_event_put (port_buffer, timestamp, buffer, size);
2114         if (!ret) { /* success */
2115                 _event._pending = false;
2116         }
2117         return ret;
2118 }
2119
2120 void
2121 CoreMidiPort::reset_parser ()
2122 {
2123         _event._pending = false;
2124         _first_time = true;
2125         _unbuffered_bytes = 0;
2126         _total_bytes = 0;
2127         _expected_bytes = 0;
2128         _status_byte = 0;
2129 }
2130
2131 void
2132 CoreMidiPort::clear_events ()
2133 {
2134         CoreMidiBuffer* mbuf = static_cast<CoreMidiBuffer*>(get_buffer(0));
2135         mbuf->clear();
2136 }
2137
2138 void
2139 CoreMidiPort::parse_events (const uint64_t time, const uint8_t *data, const size_t size)
2140 {
2141         CoreMidiBuffer* mbuf = static_cast<CoreMidiBuffer*>(get_buffer(0));
2142
2143         if (_event._pending) {
2144                 if (queue_event (mbuf, _event._time, _parser_buffer, _event._size)) {
2145                         return;
2146                 }
2147         }
2148
2149         for (size_t i = 0; i < size; ++i) {
2150                 if (_first_time && !(data[i] & 0x80)) {
2151                         continue;
2152                 }
2153
2154                 _first_time = false;
2155
2156                 if (process_byte(time, data[i])) {
2157                         if (queue_event (mbuf, _event._time, _parser_buffer, _event._size)) {
2158                                 return;
2159                         }
2160                 }
2161         }
2162 }
2163
2164 // based on JackMidiRawInputWriteQueue by Devin Anderson //
2165 bool
2166 CoreMidiPort::process_byte(const uint64_t time, const uint8_t byte)
2167 {
2168         if (byte >= 0xf8) {
2169                 // Realtime
2170                 if (byte == 0xfd) {
2171                         return false;
2172                 }
2173                 _parser_buffer[0] = byte;
2174                 prepare_byte_event(time, byte);
2175                 return true;
2176         }
2177         if (byte == 0xf7) {
2178                 // Sysex end
2179                 if (_status_byte == 0xf0) {
2180                         record_byte(byte);
2181                         return prepare_buffered_event(time);
2182                 }
2183                 _total_bytes = 0;
2184                 _unbuffered_bytes = 0;
2185                 _expected_bytes = 0;
2186                 _status_byte = 0;
2187                 return false;
2188         }
2189         if (byte >= 0x80) {
2190                 // Non-realtime status byte
2191                 if (_total_bytes) {
2192                         printf ("CoreMidiPort: discarded bogus midi message\n");
2193 #if 0
2194                         for (size_t i=0; i < _total_bytes; ++i) {
2195                                 printf("%02x ", _parser_buffer[i]);
2196                         }
2197                         printf("\n");
2198 #endif
2199                         _total_bytes = 0;
2200                         _unbuffered_bytes = 0;
2201                 }
2202                 _status_byte = byte;
2203                 switch (byte & 0xf0) {
2204                 case 0x80:
2205                 case 0x90:
2206                 case 0xa0:
2207                 case 0xb0:
2208                 case 0xe0:
2209                         // Note On, Note Off, Aftertouch, Control Change, Pitch Wheel
2210                         _expected_bytes = 3;
2211                         break;
2212                 case 0xc0:
2213                 case 0xd0:
2214                         // Program Change, Channel Pressure
2215                         _expected_bytes = 2;
2216                         break;
2217                 case 0xf0:
2218                         switch (byte) {
2219                         case 0xf0:
2220                                 // Sysex
2221                                 _expected_bytes = 0;
2222                                 break;
2223                         case 0xf1:
2224                         case 0xf3:
2225                                 // MTC Quarter Frame, Song Select
2226                                 _expected_bytes = 2;
2227                                 break;
2228                         case 0xf2:
2229                                 // Song Position
2230                                 _expected_bytes = 3;
2231                                 break;
2232                         case 0xf4:
2233                         case 0xf5:
2234                                 // Undefined
2235                                 _expected_bytes = 0;
2236                                 _status_byte = 0;
2237                                 return false;
2238                         case 0xf6:
2239                                 // Tune Request
2240                                 prepare_byte_event(time, byte);
2241                                 _expected_bytes = 0;
2242                                 _status_byte = 0;
2243                                 return true;
2244                         }
2245                 }
2246                 record_byte(byte);
2247                 return false;
2248         }
2249         // Data byte
2250         if (! _status_byte) {
2251                 // Data bytes without a status will be discarded.
2252                 _total_bytes++;
2253                 _unbuffered_bytes++;
2254                 return false;
2255         }
2256         if (! _total_bytes) {
2257                 record_byte(_status_byte);
2258         }
2259         record_byte(byte);
2260         return (_total_bytes == _expected_bytes) ? prepare_buffered_event(time) : false;
2261 }
2262
2263
2264 CoreMidiEvent::CoreMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
2265         : _size (size)
2266         , _timestamp (timestamp)
2267         , _data (0)
2268 {
2269         if (size > 0) {
2270                 _data = (uint8_t*) malloc (size);
2271                 memcpy (_data, data, size);
2272         }
2273 }
2274
2275 CoreMidiEvent::CoreMidiEvent (const CoreMidiEvent& other)
2276         : _size (other.size ())
2277         , _timestamp (other.timestamp ())
2278         , _data (0)
2279 {
2280         if (other.size () && other.const_data ()) {
2281                 _data = (uint8_t*) malloc (other.size ());
2282                 memcpy (_data, other.const_data (), other.size ());
2283         }
2284 };
2285
2286 CoreMidiEvent::~CoreMidiEvent () {
2287         free (_data);
2288 };