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