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