4e2349cd7fdfa6e2c4eb7d25f990e29d133f1c58
[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::freewheel_thread ()
1567 {
1568         _active_fw = true;
1569         bool first_run = false;
1570         /* Freewheeling - use for export.   The first call to
1571          * engine.process_callback() after engine.freewheel_callback will
1572          * if the first export cycle.
1573          * For reliable precise export timing, the calls need to be in sync.
1574          *
1575          * Furthermore we need to make sure the registered process thread
1576          * is correct.
1577          *
1578          * _freewheeling = GUI thread state as set by ::freewheel()
1579          * _freewheel = in sync here (export thread)
1580          */
1581         pthread_mutex_lock (&_freewheel_mutex);
1582         while (_run) {
1583                 // check if we should run,
1584                 if (_freewheeling != _freewheel) {
1585                         if (!_freewheeling) {
1586                                 // prepare leaving freewheeling mode
1587                                 _freewheel = false; // first mark as disabled
1588                                 _reinit_thread_callback = true; // hand over _main_thread
1589                                 _freewheel_ack = false; // prepare next handshake
1590                                 _midiio->set_enabled(true);
1591                                 engine.freewheel_callback (_freewheeling);
1592                         } else {
1593                                 first_run = true;
1594                                 _freewheel = true;
1595                         }
1596                 }
1597
1598                 if (!_freewheel || !_freewheel_ack) {
1599                         // wait for a change, we use a timed wait to
1600                         // terminate early in case some error sets _run = 0
1601                         struct timeval tv;
1602                         struct timespec ts;
1603                         gettimeofday (&tv, NULL);
1604                         ts.tv_sec = tv.tv_sec + 3;
1605                         ts.tv_nsec = 0;
1606                         pthread_cond_timedwait (&_freewheel_signal, &_freewheel_mutex, &ts);
1607                         continue;
1608                 }
1609
1610                 if (first_run) {
1611                         // tell the engine we're ready to GO.
1612                         engine.freewheel_callback (_freewheeling);
1613                         first_run = false;
1614                         _main_thread = pthread_self();
1615                         AudioEngine::thread_init_callback (this);
1616                         _midiio->set_enabled(false);
1617                 }
1618
1619                 // process port updates first in every cycle.
1620                 pre_process();
1621
1622                 // prevent coreaudio device changes
1623                 pthread_mutex_lock (&_process_callback_mutex);
1624
1625                 /* Freewheelin' */
1626
1627                 // clear input buffers
1628                 for (std::vector<CoreBackendPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
1629                         memset ((*it)->get_buffer (_samples_per_period), 0, _samples_per_period * sizeof (Sample));
1630                 }
1631                 for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it) {
1632                         static_cast<CoreMidiBuffer*>((*it)->get_buffer(0))->clear ();
1633                 }
1634
1635                 _last_process_start = 0;
1636                 if (engine.process_callback (_samples_per_period)) {
1637                         pthread_mutex_unlock (&_process_callback_mutex);
1638                         break;
1639                 }
1640
1641                 pthread_mutex_unlock (&_process_callback_mutex);
1642                 _dsp_load = 1.0;
1643                 Glib::usleep (100); // don't hog cpu
1644         }
1645
1646         pthread_mutex_unlock (&_freewheel_mutex);
1647
1648         _active_fw = false;
1649
1650         if (_run) {
1651                 // engine.process_callback() returner error
1652                 engine.halted_callback("CoreAudio Freehweeling aborted.");
1653         }
1654         return 0;
1655 }
1656 int
1657 CoreAudioBackend::process_callback (const uint32_t n_samples, const uint64_t host_time)
1658 {
1659         uint32_t i = 0;
1660         uint64_t clock1;
1661
1662         _active_ca = true;
1663
1664         if (_run && _freewheel && !_freewheel_ack) {
1665                 // acknowledge freewheeling; hand-over thread ID
1666                 pthread_mutex_lock (&_freewheel_mutex);
1667                 if (_freewheel) _freewheel_ack = true;
1668                 pthread_cond_signal (&_freewheel_signal);
1669                 pthread_mutex_unlock (&_freewheel_mutex);
1670         }
1671
1672         if (!_run || _freewheel || _preinit) {
1673                 // NB if we return 1, the output is
1674                 // zeroed by the coreaudio callback
1675                 return 1;
1676         }
1677
1678         if (_reinit_thread_callback || _main_thread != pthread_self()) {
1679                 _reinit_thread_callback = false;
1680                 _main_thread = pthread_self();
1681                 AudioEngine::thread_init_callback (this);
1682         }
1683
1684         if (pthread_mutex_trylock (&_process_callback_mutex)) {
1685                 // block while devices are added/removed
1686 #ifndef NDEBUG
1687                 printf("Xrun due to device change\n");
1688 #endif
1689                 engine.Xrun();
1690                 return 1;
1691         }
1692         /* port-connection change */
1693         pre_process();
1694
1695         // cycle-length in usec
1696         const double nominal_time = 1e6 * n_samples / _samplerate;
1697
1698         clock1 = g_get_monotonic_time();
1699
1700         /* get midi */
1701         i=0;
1702         for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++i) {
1703                 CoreMidiPort* port = dynamic_cast<CoreMidiPort*> (*it);
1704                 if (!port) {
1705                         continue;
1706                 }
1707                 uint64_t time_ns;
1708                 uint8_t data[128]; // matches CoreMidi's MIDIPacket
1709                 size_t size = sizeof(data);
1710                 
1711                 while (_midiio->recv_event (i, nominal_time, time_ns, data, size)) {
1712                         pframes_t time = floor((float) time_ns * _samplerate * 1e-9);
1713                         assert (time < n_samples);
1714                         port->parse_events (time, data, size);
1715                         size = sizeof(data); /* prepare for next call to recv_event */
1716                 }
1717         }
1718
1719         /* get audio */
1720         i = 0;
1721         for (std::vector<CoreBackendPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++i) {
1722                 _pcmio->get_capture_channel (i, (float*)((*it)->get_buffer(n_samples)), n_samples);
1723         }
1724
1725         /* clear output buffers */
1726         for (std::vector<CoreBackendPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it) {
1727                 memset ((*it)->get_buffer (n_samples), 0, n_samples * sizeof (Sample));
1728         }
1729
1730         _midiio->start_cycle();
1731         _last_process_start = host_time;
1732
1733         if (engine.process_callback (n_samples)) {
1734                 fprintf(stderr, "ENGINE PROCESS ERROR\n");
1735                 //_pcmio->pcm_stop ();
1736                 _active_ca = false;
1737                 pthread_mutex_unlock (&_process_callback_mutex);
1738                 return -1;
1739         }
1740
1741         /* mixdown midi */
1742         for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it) {
1743                 static_cast<CoreMidiPort*>(*it)->get_buffer(0);
1744         }
1745
1746         /* queue outgoing midi */
1747         i = 0;
1748         for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it, ++i) {
1749 #if 0 // something's still b0rked with CoreMidiIo::send_events()
1750                 const CoreMidiBuffer *src = static_cast<const CoreMidiPort*>(*it)->const_buffer();
1751                 _midiio->send_events (i, nominal_time, (void*)src);
1752 #else // works..
1753                 const CoreMidiBuffer *src = static_cast<const CoreMidiPort*>(*it)->const_buffer();
1754                 for (CoreMidiBuffer::const_iterator mit = src->begin (); mit != src->end (); ++mit) {
1755                         _midiio->send_event (i, (*mit)->timestamp() / nominal_time, (*mit)->data(), (*mit)->size());
1756                 }
1757 #endif
1758         }
1759
1760         /* write back audio */
1761         i = 0;
1762         for (std::vector<CoreBackendPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it, ++i) {
1763                 _pcmio->set_playback_channel (i, (float const*)(*it)->get_buffer (n_samples), n_samples);
1764         }
1765
1766         _processed_samples += n_samples;
1767
1768         /* calc DSP load. */
1769         _dsp_load_calc.set_max_time (_samplerate, _samples_per_period);
1770         _dsp_load_calc.set_start_timestamp_us (clock1);
1771         _dsp_load_calc.set_stop_timestamp_us (g_get_monotonic_time());
1772         _dsp_load = _dsp_load_calc.get_dsp_load ();
1773
1774         pthread_mutex_unlock (&_process_callback_mutex);
1775         return 0;
1776 }
1777
1778 void
1779 CoreAudioBackend::error_callback ()
1780 {
1781         _pcmio->set_error_callback (NULL, NULL);
1782         _pcmio->set_sample_rate_callback (NULL, NULL);
1783         _pcmio->set_xrun_callback (NULL, NULL);
1784         _midiio->set_port_changed_callback(NULL, NULL);
1785         engine.halted_callback("CoreAudio Process aborted.");
1786         _active_ca = false;
1787 }
1788
1789 void
1790 CoreAudioBackend::xrun_callback ()
1791 {
1792         engine.Xrun ();
1793 }
1794
1795 void
1796 CoreAudioBackend::buffer_size_callback ()
1797 {
1798         uint32_t bs = _pcmio->samples_per_period();
1799         if (bs == _samples_per_period) {
1800                 return;
1801         }
1802         _samples_per_period = bs;
1803         engine.buffer_size_change (_samples_per_period);
1804 }
1805
1806 void
1807 CoreAudioBackend::sample_rate_callback ()
1808 {
1809         if (_preinit) {
1810 #ifndef NDEBUG
1811                 printf("Samplerate change during initialization.\n");
1812 #endif
1813                 return;
1814         }
1815         _pcmio->set_error_callback (NULL, NULL);
1816         _pcmio->set_sample_rate_callback (NULL, NULL);
1817         _pcmio->set_xrun_callback (NULL, NULL);
1818         _midiio->set_port_changed_callback(NULL, NULL);
1819         engine.halted_callback("Sample Rate Changed.");
1820         stop();
1821 }
1822
1823 void
1824 CoreAudioBackend::hw_changed_callback ()
1825 {
1826         _reinit_thread_callback = true;
1827         engine.request_device_list_update();
1828 }
1829
1830 /******************************************************************************/
1831
1832 static boost::shared_ptr<CoreAudioBackend> _instance;
1833
1834 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
1835 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
1836 static int deinstantiate ();
1837 static bool already_configured ();
1838 static bool available ();
1839
1840 static ARDOUR::AudioBackendInfo _descriptor = {
1841         "CoreAudio",
1842         instantiate,
1843         deinstantiate,
1844         backend_factory,
1845         already_configured,
1846         available
1847 };
1848
1849 static boost::shared_ptr<AudioBackend>
1850 backend_factory (AudioEngine& e)
1851 {
1852         if (!_instance) {
1853                 _instance.reset (new CoreAudioBackend (e, _descriptor));
1854         }
1855         return _instance;
1856 }
1857
1858 static int
1859 instantiate (const std::string& arg1, const std::string& /* arg2 */)
1860 {
1861         s_instance_name = arg1;
1862         return 0;
1863 }
1864
1865 static int
1866 deinstantiate ()
1867 {
1868         _instance.reset ();
1869         return 0;
1870 }
1871
1872 static bool
1873 already_configured ()
1874 {
1875         return false;
1876 }
1877
1878 static bool
1879 available ()
1880 {
1881         return true;
1882 }
1883
1884 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
1885 {
1886         return &_descriptor;
1887 }
1888
1889
1890 /******************************************************************************/
1891 CoreBackendPort::CoreBackendPort (CoreAudioBackend &b, const std::string& name, PortFlags flags)
1892         : _osx_backend (b)
1893         , _name  (name)
1894         , _flags (flags)
1895 {
1896         _capture_latency_range.min = 0;
1897         _capture_latency_range.max = 0;
1898         _playback_latency_range.min = 0;
1899         _playback_latency_range.max = 0;
1900 }
1901
1902 CoreBackendPort::~CoreBackendPort () {
1903         disconnect_all ();
1904 }
1905
1906
1907 int CoreBackendPort::connect (CoreBackendPort *port)
1908 {
1909         if (!port) {
1910                 PBD::warning << _("CoreBackendPort::connect (): invalid (null) port") << endmsg;
1911                 return -1;
1912         }
1913
1914         if (type () != port->type ()) {
1915                 PBD::warning << _("CoreBackendPort::connect (): wrong port-type") << endmsg;
1916                 return -1;
1917         }
1918
1919         if (is_output () && port->is_output ()) {
1920                 PBD::warning << _("CoreBackendPort::connect (): cannot inter-connect output ports.") << endmsg;
1921                 return -1;
1922         }
1923
1924         if (is_input () && port->is_input ()) {
1925                 PBD::warning << _("CoreBackendPort::connect (): cannot inter-connect input ports.") << endmsg;
1926                 return -1;
1927         }
1928
1929         if (this == port) {
1930                 PBD::warning << _("CoreBackendPort::connect (): cannot self-connect ports.") << endmsg;
1931                 return -1;
1932         }
1933
1934         if (is_connected (port)) {
1935 #if 0 // don't bother to warn about this for now. just ignore it
1936                 PBD::info << _("CoreBackendPort::connect (): ports are already connected:")
1937                         << " (" << name () << ") -> (" << port->name () << ")"
1938                         << endmsg;
1939 #endif
1940                 return -1;
1941         }
1942
1943         _connect (port, true);
1944         return 0;
1945 }
1946
1947
1948 void CoreBackendPort::_connect (CoreBackendPort *port, bool callback)
1949 {
1950         _connections.push_back (port);
1951         if (callback) {
1952                 port->_connect (this, false);
1953                 _osx_backend.port_connect_callback (name(),  port->name(), true);
1954         }
1955 }
1956
1957 int CoreBackendPort::disconnect (CoreBackendPort *port)
1958 {
1959         if (!port) {
1960                 PBD::warning << _("CoreBackendPort::disconnect (): invalid (null) port") << endmsg;
1961                 return -1;
1962         }
1963
1964         if (!is_connected (port)) {
1965                 PBD::warning << _("CoreBackendPort::disconnect (): ports are not connected:")
1966                         << " (" << name () << ") -> (" << port->name () << ")"
1967                         << endmsg;
1968                 return -1;
1969         }
1970         _disconnect (port, true);
1971         return 0;
1972 }
1973
1974 void CoreBackendPort::_disconnect (CoreBackendPort *port, bool callback)
1975 {
1976         std::vector<CoreBackendPort*>::iterator it = std::find (_connections.begin (), _connections.end (), port);
1977
1978         assert (it != _connections.end ());
1979
1980         _connections.erase (it);
1981
1982         if (callback) {
1983                 port->_disconnect (this, false);
1984                 _osx_backend.port_connect_callback (name(),  port->name(), false);
1985         }
1986 }
1987
1988
1989 void CoreBackendPort::disconnect_all ()
1990 {
1991         while (!_connections.empty ()) {
1992                 _connections.back ()->_disconnect (this, false);
1993                 _osx_backend.port_connect_callback (name(),  _connections.back ()->name(), false);
1994                 _connections.pop_back ();
1995         }
1996 }
1997
1998 bool
1999 CoreBackendPort::is_connected (const CoreBackendPort *port) const
2000 {
2001         return std::find (_connections.begin (), _connections.end (), port) != _connections.end ();
2002 }
2003
2004 bool CoreBackendPort::is_physically_connected () const
2005 {
2006         for (std::vector<CoreBackendPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
2007                 if ((*it)->is_physical ()) {
2008                         return true;
2009                 }
2010         }
2011         return false;
2012 }
2013
2014 /******************************************************************************/
2015
2016 CoreAudioPort::CoreAudioPort (CoreAudioBackend &b, const std::string& name, PortFlags flags)
2017         : CoreBackendPort (b, name, flags)
2018 {
2019         memset (_buffer, 0, sizeof (_buffer));
2020         mlock(_buffer, sizeof (_buffer));
2021 }
2022
2023 CoreAudioPort::~CoreAudioPort () { }
2024
2025 void* CoreAudioPort::get_buffer (pframes_t n_samples)
2026 {
2027         if (is_input ()) {
2028                 std::vector<CoreBackendPort*>::const_iterator it = get_connections ().begin ();
2029                 if (it == get_connections ().end ()) {
2030                         memset (_buffer, 0, n_samples * sizeof (Sample));
2031                 } else {
2032                         CoreAudioPort const * source = static_cast<const CoreAudioPort*>(*it);
2033                         assert (source && source->is_output ());
2034                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
2035                         while (++it != get_connections ().end ()) {
2036                                 source = static_cast<const CoreAudioPort*>(*it);
2037                                 assert (source && source->is_output ());
2038                                 Sample* dst = buffer ();
2039                                 const Sample* src = source->const_buffer ();
2040                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
2041                                         *dst += *src;
2042                                 }
2043                         }
2044                 }
2045         }
2046         return _buffer;
2047 }
2048
2049
2050 CoreMidiPort::CoreMidiPort (CoreAudioBackend &b, const std::string& name, PortFlags flags)
2051         : CoreBackendPort (b, name, flags)
2052         , _n_periods (1)
2053         , _bufperiod (0)
2054         , _event (0, 0)
2055         , _first_time(true)
2056         , _unbuffered_bytes(0)
2057         , _total_bytes(0)
2058         , _expected_bytes(0)
2059         , _status_byte(0)
2060
2061 {
2062         _buffer[0].clear ();
2063         _buffer[1].clear ();
2064 }
2065
2066 CoreMidiPort::~CoreMidiPort () { }
2067
2068 struct MidiEventSorter {
2069         bool operator() (const boost::shared_ptr<CoreMidiEvent>& a, const boost::shared_ptr<CoreMidiEvent>& b) {
2070                 return *a < *b;
2071         }
2072 };
2073
2074 void* CoreMidiPort::get_buffer (pframes_t /* nframes */)
2075 {
2076         if (is_input ()) {
2077                 (_buffer[_bufperiod]).clear ();
2078                 for (std::vector<CoreBackendPort*>::const_iterator i = get_connections ().begin ();
2079                                 i != get_connections ().end ();
2080                                 ++i) {
2081                         const CoreMidiBuffer * src = static_cast<const CoreMidiPort*>(*i)->const_buffer ();
2082                         for (CoreMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
2083                                 (_buffer[_bufperiod]).push_back (boost::shared_ptr<CoreMidiEvent>(new CoreMidiEvent (**it)));
2084                         }
2085                 }
2086                 std::sort ((_buffer[_bufperiod]).begin (), (_buffer[_bufperiod]).end (), MidiEventSorter());
2087         }
2088         if (!_buffer[_bufperiod].empty()) {
2089                 fprintf (stderr, "COREMIDI: %s have data in buffer (%d events)\n", name().c_str(), _buffer[_bufperiod].size());
2090         }
2091         return &(_buffer[_bufperiod]);
2092 }
2093
2094 int
2095 CoreMidiPort::queue_event (
2096         void* port_buffer,
2097         pframes_t timestamp,
2098         const uint8_t* buffer, size_t size)
2099 {
2100         if (!buffer || !port_buffer) return -1;
2101         _event._pending = false;
2102         CoreMidiBuffer& dst = * static_cast<CoreMidiBuffer*>(port_buffer);
2103         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
2104 #ifndef NDEBUG
2105                 // nevermind, ::get_buffer() sorts events
2106                 fprintf (stderr, "CoreMidiBuffer: unordered event: %d > %d\n",
2107                                 (pframes_t)dst.back ()->timestamp (), timestamp);
2108 #endif
2109         }
2110         fprintf (stderr, "coremidi: queue event/buffer size %d @ %d\n", size, timestamp);
2111         dst.push_back (boost::shared_ptr<CoreMidiEvent>(new CoreMidiEvent (timestamp, buffer, size)));
2112         return 0;
2113 }
2114
2115 void
2116 CoreMidiPort::parse_events (const uint64_t time, const uint8_t *data, const size_t size) 
2117 {
2118         CoreMidiBuffer* mbuf = static_cast<CoreMidiBuffer*>(get_buffer(0));
2119
2120         mbuf->clear();
2121         
2122         if (_event._pending) {
2123                 if (queue_event (mbuf, _event._time, _parser_buffer, _event._size)) {
2124                         return;
2125                 }
2126         }
2127
2128         for (size_t i = 0; i < size; ++i) {
2129                 if (_first_time && !(data[i] & 0x80)) {
2130                         continue;
2131                 }
2132
2133                 _first_time = false; 
2134                 
2135                 if (process_byte(time, data[i])) {
2136                         if (queue_event (mbuf, _event._time, _parser_buffer, _event._size)) {
2137                                 return;
2138                         }
2139                 }
2140         }
2141 }
2142
2143 // based on JackMidiRawInputWriteQueue by Devin Anderson //
2144 bool
2145 CoreMidiPort::process_byte(const uint64_t time, const uint8_t byte)
2146 {
2147         if (byte >= 0xf8) {
2148                 // Realtime
2149                 if (byte == 0xfd) {
2150                         return false;
2151                 }
2152                 _parser_buffer[0] = byte;
2153                 prepare_byte_event(time, byte);
2154                 return true;
2155         }
2156         if (byte == 0xf7) {
2157                 // Sysex end
2158                 if (_status_byte == 0xf0) {
2159                         record_byte(byte);
2160                         return prepare_buffered_event(time);
2161                 }
2162     _total_bytes = 0;
2163     _unbuffered_bytes = 0;
2164                 _expected_bytes = 0;
2165                 _status_byte = 0;
2166                 return false;
2167         }
2168         if (byte >= 0x80) {
2169                 // Non-realtime status byte
2170                 if (_total_bytes) {
2171                         printf ("CoreMidiPort: discarded bogus midi message\n");
2172 #if 0
2173                         for (size_t i=0; i < _total_bytes; ++i) {
2174                                 printf("%02x ", _parser_buffer[i]);
2175                         }
2176                         printf("\n");
2177 #endif
2178                         _total_bytes = 0;
2179                         _unbuffered_bytes = 0;
2180                 }
2181                 _status_byte = byte;
2182                 switch (byte & 0xf0) {
2183                         case 0x80:
2184                         case 0x90:
2185                         case 0xa0:
2186                         case 0xb0:
2187                         case 0xe0:
2188                                 // Note On, Note Off, Aftertouch, Control Change, Pitch Wheel
2189                                 _expected_bytes = 3;
2190                                 break;
2191                         case 0xc0:
2192                         case 0xd0:
2193                                 // Program Change, Channel Pressure
2194                                 _expected_bytes = 2;
2195                                 break;
2196                         case 0xf0:
2197                                 switch (byte) {
2198                                         case 0xf0:
2199                                                 // Sysex
2200                                                 _expected_bytes = 0;
2201                                                 break;
2202                                         case 0xf1:
2203                                         case 0xf3:
2204                                                 // MTC Quarter Frame, Song Select
2205                                                 _expected_bytes = 2;
2206                                                 break;
2207                                         case 0xf2:
2208                                                 // Song Position
2209                                                 _expected_bytes = 3;
2210                                                 break;
2211                                         case 0xf4:
2212                                         case 0xf5:
2213                                                 // Undefined
2214                                                 _expected_bytes = 0;
2215                                                 _status_byte = 0;
2216                                                 return false;
2217                                         case 0xf6:
2218                                                 // Tune Request
2219                                                 prepare_byte_event(time, byte);
2220                                                 _expected_bytes = 0;
2221                                                 _status_byte = 0;
2222                                                 return true;
2223                                 }
2224                 }
2225                 record_byte(byte);
2226                 return false;
2227         }
2228         // Data byte
2229         if (! _status_byte) {
2230                 // Data bytes without a status will be discarded.
2231                 _total_bytes++;
2232                 _unbuffered_bytes++;
2233                 return false;
2234         }
2235         if (! _total_bytes) {
2236                 record_byte(_status_byte);
2237         }
2238         record_byte(byte);
2239         return (_total_bytes == _expected_bytes) ? prepare_buffered_event(time) : false;
2240 }
2241
2242
2243 CoreMidiEvent::CoreMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
2244         : _size (size)
2245         , _timestamp (timestamp)
2246         , _data (0)
2247 {
2248         if (size > 0) {
2249                 _data = (uint8_t*) malloc (size);
2250                 memcpy (_data, data, size);
2251         }
2252 }
2253
2254 CoreMidiEvent::CoreMidiEvent (const CoreMidiEvent& other)
2255         : _size (other.size ())
2256         , _timestamp (other.timestamp ())
2257         , _data (0)
2258 {
2259         if (other.size () && other.const_data ()) {
2260                 _data = (uint8_t*) malloc (other.size ());
2261                 memcpy (_data, other.const_data (), other.size ());
2262         }
2263 };
2264
2265 CoreMidiEvent::~CoreMidiEvent () {
2266         free (_data);
2267 };