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