enough with umpteen "i18n.h" files. Consolidate on pbd/i18n.h
[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);
207         const uint32_t out = name_to_id (output_device);
208
209         if (inp == UINT32_MAX && out == UINT32_MAX) {
210                 return sr;
211         } else if (inp == UINT32_MAX) {
212                 _pcmio->available_sample_rates (out, sr_out);
213                 return sr_out;
214         } else if (out == UINT32_MAX) {
215                 _pcmio->available_sample_rates (inp, sr_in);
216                 return sr_in;
217         } else {
218                 _pcmio->available_sample_rates (inp, sr_in);
219                 _pcmio->available_sample_rates (out, sr_out);
220                 // TODO allow to use different SR per device, tweak aggregate
221                 std::set_intersection (sr_in.begin(), sr_in.end(), sr_out.begin(), sr_out.end(), std::back_inserter(sr));
222                 return sr;
223         }
224 }
225
226 std::vector<uint32_t>
227 CoreAudioBackend::available_buffer_sizes (const std::string& device) const
228 {
229         std::vector<uint32_t> bs;
230         _pcmio->available_buffer_sizes (name_to_id (device), bs);
231         return bs;
232 }
233
234 std::vector<uint32_t>
235 CoreAudioBackend::available_buffer_sizes2 (const std::string& input_device, const std::string& output_device) const
236 {
237         std::vector<uint32_t> bs;
238         std::vector<uint32_t> bs_in;
239         std::vector<uint32_t> bs_out;
240         const uint32_t inp = name_to_id (input_device);
241         const uint32_t out = name_to_id (output_device);
242         if (inp == UINT32_MAX && out == UINT32_MAX) {
243                 return bs;
244         } else if (inp == UINT32_MAX) {
245                 _pcmio->available_buffer_sizes (out, bs_out);
246                 return bs_out;
247         } else if (out == UINT32_MAX) {
248                 _pcmio->available_buffer_sizes (inp, bs_in);
249                 return bs_in;
250         } else {
251                 _pcmio->available_buffer_sizes (inp, bs_in);
252                 _pcmio->available_buffer_sizes (out, bs_out);
253                 std::set_intersection (bs_in.begin(), bs_in.end(), bs_out.begin(), bs_out.end(), std::back_inserter(bs));
254                 return bs;
255         }
256 }
257
258 uint32_t
259 CoreAudioBackend::available_input_channel_count (const std::string&) const
260 {
261         return 128; // TODO query current device
262 }
263
264 uint32_t
265 CoreAudioBackend::available_output_channel_count (const std::string&) const
266 {
267         return 128; // TODO query current device
268 }
269
270 bool
271 CoreAudioBackend::can_change_sample_rate_when_running () const
272 {
273         return false;
274 }
275
276 bool
277 CoreAudioBackend::can_change_buffer_size_when_running () const
278 {
279         return true;
280 }
281
282 int
283 CoreAudioBackend::set_device_name (const std::string& d)
284 {
285         int rv = 0;
286         rv |= set_input_device_name (d);
287         rv |= set_output_device_name (d);
288         return rv;
289 }
290
291 int
292 CoreAudioBackend::set_input_device_name (const std::string& d)
293 {
294         _input_audio_device = d;
295         const float sr = _pcmio->current_sample_rate(name_to_id(_input_audio_device));
296         if (sr > 0) { set_sample_rate(sr); }
297         return 0;
298 }
299
300 int
301 CoreAudioBackend::set_output_device_name (const std::string& d)
302 {
303         _output_audio_device = d;
304         // TODO check SR.
305         const float sr = _pcmio->current_sample_rate(name_to_id(_output_audio_device));
306         if (sr > 0) { set_sample_rate(sr); }
307         return 0;
308 }
309
310 int
311 CoreAudioBackend::set_sample_rate (float sr)
312 {
313         std::vector<float> srs = available_sample_rates2 (_input_audio_device, _output_audio_device);
314         if (std::find(srs.begin(), srs.end(), sr) == srs.end()) {
315                 return -1;
316         }
317         _samplerate = sr;
318         engine.sample_rate_change (sr);
319         return 0;
320 }
321
322 int
323 CoreAudioBackend::set_buffer_size (uint32_t bs)
324 {
325         if (bs <= 0 || bs >= _max_buffer_size) {
326                 return -1;
327         }
328         _samples_per_period = bs;
329         _pcmio->set_samples_per_period(bs);
330         engine.buffer_size_change (bs);
331         return 0;
332 }
333
334 int
335 CoreAudioBackend::set_interleaved (bool yn)
336 {
337         if (!yn) { return 0; }
338         return -1;
339 }
340
341 int
342 CoreAudioBackend::set_input_channels (uint32_t cc)
343 {
344         _n_inputs = cc;
345         return 0;
346 }
347
348 int
349 CoreAudioBackend::set_output_channels (uint32_t cc)
350 {
351         _n_outputs = cc;
352         return 0;
353 }
354
355 int
356 CoreAudioBackend::set_systemic_input_latency (uint32_t sl)
357 {
358         _systemic_audio_input_latency = sl;
359         return 0;
360 }
361
362 int
363 CoreAudioBackend::set_systemic_output_latency (uint32_t sl)
364 {
365         _systemic_audio_output_latency = sl;
366         return 0;
367 }
368
369 /* Retrieving parameters */
370 std::string
371 CoreAudioBackend::device_name () const
372 {
373         return "";
374 }
375
376 std::string
377 CoreAudioBackend::input_device_name () const
378 {
379         return _input_audio_device;
380 }
381
382 std::string
383 CoreAudioBackend::output_device_name () const
384 {
385         return _output_audio_device;
386 }
387
388 float
389 CoreAudioBackend::sample_rate () const
390 {
391         return _samplerate;
392 }
393
394 uint32_t
395 CoreAudioBackend::buffer_size () const
396 {
397         return _samples_per_period;
398 }
399
400 bool
401 CoreAudioBackend::interleaved () const
402 {
403         return false;
404 }
405
406 uint32_t
407 CoreAudioBackend::input_channels () const
408 {
409         return _n_inputs;
410 }
411
412 uint32_t
413 CoreAudioBackend::output_channels () const
414 {
415         return _n_outputs;
416 }
417
418 uint32_t
419 CoreAudioBackend::systemic_input_latency () const
420 {
421         return _systemic_audio_input_latency;
422 }
423
424 uint32_t
425 CoreAudioBackend::systemic_output_latency () const
426 {
427         return _systemic_audio_output_latency;
428 }
429
430 /* MIDI */
431
432 std::vector<std::string>
433 CoreAudioBackend::enumerate_midi_options () const
434 {
435         if (_midi_options.empty()) {
436                 _midi_options.push_back (_("CoreMidi"));
437                 _midi_options.push_back (get_standard_device_name(DeviceNone));
438         }
439         return _midi_options;
440 }
441
442 int
443 CoreAudioBackend::set_midi_option (const std::string& opt)
444 {
445         if (opt != get_standard_device_name(DeviceNone) && opt != _("CoreMidi")) {
446                 return -1;
447         }
448         _midi_driver_option = opt;
449         return 0;
450 }
451
452 std::string
453 CoreAudioBackend::midi_option () const
454 {
455         return _midi_driver_option;
456 }
457
458 void
459 CoreAudioBackend::launch_control_app ()
460 {
461         if (name_to_id (_input_audio_device) != UINT32_MAX) {
462                 _pcmio->launch_control_app(name_to_id(_input_audio_device));
463         }
464         if (name_to_id (_output_audio_device) != UINT32_MAX) {
465                 _pcmio->launch_control_app(name_to_id(_output_audio_device));
466         }
467 }
468
469 /* State Control */
470
471 static void * pthread_freewheel (void *arg)
472 {
473         CoreAudioBackend *d = static_cast<CoreAudioBackend *>(arg);
474         d->freewheel_thread ();
475         pthread_exit (0);
476         return 0;
477 }
478
479 static int process_callback_ptr (void *arg, const uint32_t n_samples, const uint64_t host_time)
480 {
481         CoreAudioBackend *d = static_cast<CoreAudioBackend*> (arg);
482         return d->process_callback(n_samples, host_time);
483 }
484
485 int
486 CoreAudioBackend::_start (bool for_latency_measurement)
487 {
488         AudioBackend::ErrorCode error_code = NoError;
489
490         if ((!_active_ca || !_active_fw)  && _run) {
491                 // recover from 'halted', reap threads
492                 stop();
493         }
494
495         if (_active_ca || _active_fw || _run) {
496                 PBD::error << _("CoreAudioBackend: already active.") << endmsg;
497                 return BackendReinitializationError;
498         }
499
500         if (_ports.size () || _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);
511         uint32_t device2 = name_to_id(_output_audio_device);
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) const {
782         uint32_t device_id = UINT32_MAX;
783         std::map<size_t, std::string> devices;
784         _pcmio->device_list(devices);
785
786         for (std::map<size_t, std::string>::const_iterator i = devices.begin (); i != devices.end(); ++i) {
787                 if (i->second == device_name) {
788                         device_id = i->first;
789                         break;
790                 }
791         }
792         return device_id;
793 }
794
795 void *
796 CoreAudioBackend::coreaudio_process_thread (void *arg)
797 {
798         ThreadData* td = reinterpret_cast<ThreadData*> (arg);
799         boost::function<void ()> f = td->f;
800         delete td;
801         f ();
802         return 0;
803 }
804
805 int
806 CoreAudioBackend::create_process_thread (boost::function<void()> func)
807 {
808         pthread_t thread_id;
809         pthread_attr_t attr;
810         size_t stacksize = 100000;
811
812         ThreadData* td = new ThreadData (this, func, stacksize);
813
814         if (_realtime_pthread_create (SCHED_FIFO, -21, stacksize,
815                                       &thread_id, coreaudio_process_thread, td)) {
816                 pthread_attr_init (&attr);
817                 pthread_attr_setstacksize (&attr, stacksize);
818                 if (pthread_create (&thread_id, &attr, coreaudio_process_thread, td)) {
819                         PBD::error << _("AudioEngine: cannot create process thread.") << endmsg;
820                         pthread_attr_destroy (&attr);
821                         return -1;
822                 }
823                 pthread_attr_destroy (&attr);
824         }
825
826         _threads.push_back (thread_id);
827         return 0;
828 }
829
830 int
831 CoreAudioBackend::join_process_threads ()
832 {
833         int rv = 0;
834
835         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
836         {
837                 void *status;
838                 if (pthread_join (*i, &status)) {
839                         PBD::error << _("AudioEngine: cannot terminate process thread.") << endmsg;
840                         rv -= 1;
841                 }
842         }
843         _threads.clear ();
844         return rv;
845 }
846
847 bool
848 CoreAudioBackend::in_process_thread ()
849 {
850         if (pthread_equal (_main_thread, pthread_self()) != 0) {
851                 return true;
852         }
853
854         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
855         {
856                 if (pthread_equal (*i, pthread_self ()) != 0) {
857                         return true;
858                 }
859         }
860         return false;
861 }
862
863 uint32_t
864 CoreAudioBackend::process_thread_count ()
865 {
866         return _threads.size ();
867 }
868
869 void
870 CoreAudioBackend::update_latencies ()
871 {
872         // trigger latency callback in RT thread (locked graph)
873         port_connect_add_remove_callback();
874 }
875
876 /* PORTENGINE API */
877
878 void*
879 CoreAudioBackend::private_handle () const
880 {
881         return NULL;
882 }
883
884 const std::string&
885 CoreAudioBackend::my_name () const
886 {
887         return _instance_name;
888 }
889
890 bool
891 CoreAudioBackend::available () const
892 {
893         return _run && _active_fw && _active_ca;
894 }
895
896 uint32_t
897 CoreAudioBackend::port_name_size () const
898 {
899         return 256;
900 }
901
902 int
903 CoreAudioBackend::set_port_name (PortEngine::PortHandle port, const std::string& name)
904 {
905         std::string newname (_instance_name + ":" + name);
906         if (!valid_port (port)) {
907                 PBD::warning << _("CoreAudioBackend::set_port_name: Invalid Port(s)") << endmsg;
908                 return -1;
909         }
910         if (find_port (newname)) {
911                 PBD::error << _("CoreAudioBackend::set_port_name: Port with given name already exists") << endmsg;
912                 return -1;
913         }
914
915         CoreBackendPort* p = static_cast<CoreBackendPort*>(port);
916         _portmap.erase (p->name());
917         _portmap.insert (make_pair (newname, p));
918         return p->set_name (newname);
919 }
920
921 std::string
922 CoreAudioBackend::get_port_name (PortEngine::PortHandle port) const
923 {
924         if (!valid_port (port)) {
925                 PBD::warning << _("CoreAudioBackend::get_port_name: Invalid Port(s)") << endmsg;
926                 return std::string ();
927         }
928         return static_cast<CoreBackendPort*>(port)->name ();
929 }
930
931 int
932 CoreAudioBackend::get_port_property (PortHandle port, const std::string& key, std::string& value, std::string& type) const
933 {
934         if (!valid_port (port)) {
935                 PBD::warning << _("CoreAudioBackend::get_port_property: Invalid Port(s)") << endmsg;
936                 return -1;
937         }
938         if (key == "http://jackaudio.org/metadata/pretty-name") {
939                 type = "";
940                 value = static_cast<CoreBackendPort*>(port)->pretty_name ();
941                 if (!value.empty()) {
942                         return 0;
943                 }
944         }
945         return -1;
946 }
947
948 int
949 CoreAudioBackend::set_port_property (PortHandle port, const std::string& key, const std::string& value, const std::string& type)
950 {
951         if (!valid_port (port)) {
952                 PBD::warning << _("CoreAudioBackend::set_port_property: Invalid Port(s)") << endmsg;
953                 return -1;
954         }
955         if (key == "http://jackaudio.org/metadata/pretty-name" && type.empty ()) {
956                 static_cast<CoreBackendPort*>(port)->set_pretty_name (value);
957                 return 0;
958         }
959         return -1;
960 }
961
962 PortEngine::PortHandle
963 CoreAudioBackend::get_port_by_name (const std::string& name) const
964 {
965         PortHandle port = (PortHandle) find_port (name);
966         return port;
967 }
968
969 int
970 CoreAudioBackend::get_ports (
971         const std::string& port_name_pattern,
972         DataType type, PortFlags flags,
973         std::vector<std::string>& port_names) const
974 {
975         int rv = 0;
976         regex_t port_regex;
977         bool use_regexp = false;
978         if (port_name_pattern.size () > 0) {
979                 if (!regcomp (&port_regex, port_name_pattern.c_str (), REG_EXTENDED|REG_NOSUB)) {
980                         use_regexp = true;
981                 }
982         }
983
984         for (PortIndex::const_iterator i = _ports.begin (); i != _ports.end (); ++i) {
985                 CoreBackendPort* port = *i;
986                 if ((port->type () == type) && flags == (port->flags () & flags)) {
987                         if (!use_regexp || !regexec (&port_regex, port->name ().c_str (), 0, NULL, 0)) {
988                                 port_names.push_back (port->name ());
989                                 ++rv;
990                         }
991                 }
992         }
993         if (use_regexp) {
994                 regfree (&port_regex);
995         }
996         return rv;
997 }
998
999 DataType
1000 CoreAudioBackend::port_data_type (PortEngine::PortHandle port) const
1001 {
1002         if (!valid_port (port)) {
1003                 return DataType::NIL;
1004         }
1005         return static_cast<CoreBackendPort*>(port)->type ();
1006 }
1007
1008 PortEngine::PortHandle
1009 CoreAudioBackend::register_port (
1010         const std::string& name,
1011         ARDOUR::DataType type,
1012         ARDOUR::PortFlags flags)
1013 {
1014         if (name.size () == 0) { return 0; }
1015         if (flags & IsPhysical) { return 0; }
1016         return add_port (_instance_name + ":" + name, type, flags);
1017 }
1018
1019 PortEngine::PortHandle
1020 CoreAudioBackend::add_port (
1021         const std::string& name,
1022         ARDOUR::DataType type,
1023         ARDOUR::PortFlags flags)
1024 {
1025         assert(name.size ());
1026         if (find_port (name)) {
1027                 PBD::warning << _("CoreAudioBackend::register_port: Port already exists:")
1028                              << " (" << name << ")" << endmsg;
1029                 return 0;
1030         }
1031         CoreBackendPort* port = NULL;
1032         switch (type) {
1033         case DataType::AUDIO:
1034                 port = new CoreAudioPort (*this, name, flags);
1035                 break;
1036         case DataType::MIDI:
1037                 port = new CoreMidiPort (*this, name, flags);
1038                 break;
1039         default:
1040                 PBD::error << _("CoreAudioBackend::register_port: Invalid Data Type.") << endmsg;
1041                 return 0;
1042         }
1043
1044         _ports.insert (port);
1045         _portmap.insert (make_pair (name, port));
1046
1047         return port;
1048 }
1049
1050 void
1051 CoreAudioBackend::unregister_port (PortEngine::PortHandle port_handle)
1052 {
1053         if (!_run) {
1054                 return;
1055         }
1056         CoreBackendPort* port = static_cast<CoreBackendPort*>(port_handle);
1057         PortIndex::iterator i = std::find (_ports.begin(), _ports.end(), static_cast<CoreBackendPort*>(port_handle));
1058         if (i == _ports.end ()) {
1059                 PBD::warning << _("CoreAudioBackend::unregister_port: Failed to find port") << endmsg;
1060                 return;
1061         }
1062         disconnect_all(port_handle);
1063         _portmap.erase (port->name());
1064         _ports.erase (i);
1065         delete port;
1066 }
1067
1068 int
1069 CoreAudioBackend::register_system_audio_ports()
1070 {
1071         LatencyRange lr;
1072
1073         const uint32_t a_ins = _n_inputs;
1074         const uint32_t a_out = _n_outputs;
1075
1076         const uint32_t coreaudio_reported_input_latency = _pcmio->get_latency(name_to_id(_input_audio_device), true);
1077         const uint32_t coreaudio_reported_output_latency = _pcmio->get_latency(name_to_id(_output_audio_device), false);
1078
1079 #ifndef NDEBUG
1080         printf("COREAUDIO LATENCY: i:%d, o:%d\n",
1081                coreaudio_reported_input_latency,
1082                coreaudio_reported_output_latency);
1083 #endif
1084
1085         /* audio ports */
1086         lr.min = lr.max = coreaudio_reported_input_latency + (_measure_latency ? 0 : _systemic_audio_input_latency);
1087         for (uint32_t i = 0; i < a_ins; ++i) {
1088                 char tmp[64];
1089                 snprintf(tmp, sizeof(tmp), "system:capture_%d", i+1);
1090                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
1091                 if (!p) return -1;
1092                 set_latency_range (p, false, lr);
1093                 CoreBackendPort *cp = static_cast<CoreBackendPort*>(p);
1094                 cp->set_pretty_name (_pcmio->cached_port_name(i, true));
1095                 _system_inputs.push_back(cp);
1096         }
1097
1098         lr.min = lr.max = coreaudio_reported_output_latency + (_measure_latency ? 0 : _systemic_audio_output_latency);
1099         for (uint32_t i = 0; i < a_out; ++i) {
1100                 char tmp[64];
1101                 snprintf(tmp, sizeof(tmp), "system:playback_%d", i+1);
1102                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
1103                 if (!p) return -1;
1104                 set_latency_range (p, true, lr);
1105                 CoreBackendPort *cp = static_cast<CoreBackendPort*>(p);
1106                 cp->set_pretty_name (_pcmio->cached_port_name(i, false));
1107                 _system_outputs.push_back(cp);
1108         }
1109         return 0;
1110 }
1111
1112 void
1113 CoreAudioBackend::coremidi_rediscover()
1114 {
1115         if (!_run) { return; }
1116         assert(_midi_driver_option == _("CoreMidi"));
1117
1118         pthread_mutex_lock (&_process_callback_mutex);
1119
1120         for (std::vector<CoreBackendPort*>::iterator it = _system_midi_out.begin (); it != _system_midi_out.end ();) {
1121                 bool found = false;
1122                 for (size_t i = 0; i < _midiio->n_midi_outputs(); ++i) {
1123                         if ((*it)->name() == _midiio->port_id(i, false)) {
1124                                 found = true;
1125                                 break;
1126                         }
1127                 }
1128                 if (found) {
1129                         ++it;
1130                 } else {
1131 #ifndef NDEBUG
1132                         printf("unregister MIDI Output: %s\n", (*it)->name().c_str());
1133 #endif
1134                         _port_change_flag = true;
1135                         unregister_port((*it));
1136                         it = _system_midi_out.erase(it);
1137                 }
1138         }
1139
1140         for (std::vector<CoreBackendPort*>::iterator it = _system_midi_in.begin (); it != _system_midi_in.end ();) {
1141                 bool found = false;
1142                 for (size_t i = 0; i < _midiio->n_midi_inputs(); ++i) {
1143                         if ((*it)->name() == _midiio->port_id(i, true)) {
1144                                 found = true;
1145                                 break;
1146                         }
1147                 }
1148                 if (found) {
1149                         ++it;
1150                 } else {
1151 #ifndef NDEBUG
1152                         printf("unregister MIDI Input: %s\n", (*it)->name().c_str());
1153 #endif
1154                         _port_change_flag = true;
1155                         unregister_port((*it));
1156                         it = _system_midi_in.erase(it);
1157                 }
1158         }
1159
1160         for (size_t i = 0; i < _midiio->n_midi_inputs(); ++i) {
1161                 std::string name = _midiio->port_id(i, true);
1162                 if (find_port_in(_system_midi_in, name)) {
1163                         continue;
1164                 }
1165
1166 #ifndef NDEBUG
1167                 printf("register MIDI Input: %s\n", name.c_str());
1168 #endif
1169                 PortHandle p = add_port(name, DataType::MIDI, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
1170                 if (!p) {
1171                         fprintf(stderr, "failed to register MIDI IN: %s\n", name.c_str());
1172                         continue;
1173                 }
1174                 LatencyRange lr;
1175                 lr.min = lr.max = _samples_per_period; // TODO add per-port midi-systemic latency
1176                 set_latency_range (p, false, lr);
1177                 CoreBackendPort *pp = static_cast<CoreBackendPort*>(p);
1178                 pp->set_pretty_name(_midiio->port_name(i, true));
1179                 _system_midi_in.push_back(pp);
1180                 _port_change_flag = true;
1181         }
1182
1183         for (size_t i = 0; i < _midiio->n_midi_outputs(); ++i) {
1184                 std::string name = _midiio->port_id(i, false);
1185                 if (find_port_in(_system_midi_out, name)) {
1186                         continue;
1187                 }
1188
1189 #ifndef NDEBUG
1190                 printf("register MIDI OUT: %s\n", name.c_str());
1191 #endif
1192                 PortHandle p = add_port(name, DataType::MIDI, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
1193                 if (!p) {
1194                         fprintf(stderr, "failed to register MIDI OUT: %s\n", name.c_str());
1195                         continue;
1196                 }
1197                 LatencyRange lr;
1198                 lr.min = lr.max = _samples_per_period; // TODO add per-port midi-systemic latency
1199                 set_latency_range (p, false, lr);
1200                 CoreBackendPort *pp = static_cast<CoreBackendPort*>(p);
1201                 pp->set_pretty_name(_midiio->port_name(i, false));
1202                 _system_midi_out.push_back(pp);
1203                 _port_change_flag = true;
1204         }
1205
1206
1207         assert(_system_midi_out.size() == _midiio->n_midi_outputs());
1208         assert(_system_midi_in.size() == _midiio->n_midi_inputs());
1209
1210         pthread_mutex_unlock (&_process_callback_mutex);
1211 }
1212
1213 void
1214 CoreAudioBackend::unregister_ports (bool system_only)
1215 {
1216         _system_inputs.clear();
1217         _system_outputs.clear();
1218         _system_midi_in.clear();
1219         _system_midi_out.clear();
1220
1221         for (PortIndex::iterator i = _ports.begin (); i != _ports.end ();) {
1222                 PortIndex::iterator cur = i++;
1223                 CoreBackendPort* port = *cur;
1224                 if (! system_only || (port->is_physical () && port->is_terminal ())) {
1225                         port->disconnect_all ();
1226                         _portmap.erase (port->name());
1227                         delete port;
1228                         _ports.erase (cur);
1229                 }
1230         }
1231 }
1232
1233 int
1234 CoreAudioBackend::connect (const std::string& src, const std::string& dst)
1235 {
1236         CoreBackendPort* src_port = find_port (src);
1237         CoreBackendPort* dst_port = find_port (dst);
1238
1239         if (!src_port) {
1240                 PBD::warning << _("CoreAudioBackend::connect: Invalid Source port:")
1241                              << " (" << src <<")" << endmsg;
1242                 return -1;
1243         }
1244         if (!dst_port) {
1245                 PBD::warning << _("CoreAudioBackend::connect: Invalid Destination port:")
1246                              << " (" << dst <<")" << endmsg;
1247                 return -1;
1248         }
1249         return src_port->connect (dst_port);
1250 }
1251
1252 int
1253 CoreAudioBackend::disconnect (const std::string& src, const std::string& dst)
1254 {
1255         CoreBackendPort* src_port = find_port (src);
1256         CoreBackendPort* dst_port = find_port (dst);
1257
1258         if (!src_port || !dst_port) {
1259                 PBD::warning << _("CoreAudioBackend::disconnect: Invalid Port(s)") << endmsg;
1260                 return -1;
1261         }
1262         return src_port->disconnect (dst_port);
1263 }
1264
1265 int
1266 CoreAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
1267 {
1268         CoreBackendPort* dst_port = find_port (dst);
1269         if (!valid_port (src)) {
1270                 PBD::warning << _("CoreAudioBackend::connect: Invalid Source Port Handle") << endmsg;
1271                 return -1;
1272         }
1273         if (!dst_port) {
1274                 PBD::warning << _("CoreAudioBackend::connect: Invalid Destination Port")
1275                              << " (" << dst << ")" << endmsg;
1276                 return -1;
1277         }
1278         return static_cast<CoreBackendPort*>(src)->connect (dst_port);
1279 }
1280
1281 int
1282 CoreAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
1283 {
1284         CoreBackendPort* dst_port = find_port (dst);
1285         if (!valid_port (src) || !dst_port) {
1286                 PBD::warning << _("CoreAudioBackend::disconnect: Invalid Port(s)") << endmsg;
1287                 return -1;
1288         }
1289         return static_cast<CoreBackendPort*>(src)->disconnect (dst_port);
1290 }
1291
1292 int
1293 CoreAudioBackend::disconnect_all (PortEngine::PortHandle port)
1294 {
1295         if (!valid_port (port)) {
1296                 PBD::warning << _("CoreAudioBackend::disconnect_all: Invalid Port") << endmsg;
1297                 return -1;
1298         }
1299         static_cast<CoreBackendPort*>(port)->disconnect_all ();
1300         return 0;
1301 }
1302
1303 bool
1304 CoreAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
1305 {
1306         if (!valid_port (port)) {
1307                 PBD::warning << _("CoreAudioBackend::disconnect_all: Invalid Port") << endmsg;
1308                 return false;
1309         }
1310         return static_cast<CoreBackendPort*>(port)->is_connected ();
1311 }
1312
1313 bool
1314 CoreAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
1315 {
1316         CoreBackendPort* dst_port = find_port (dst);
1317 #ifndef NDEBUG
1318         if (!valid_port (src) || !dst_port) {
1319                 PBD::warning << _("CoreAudioBackend::connected_to: Invalid Port") << endmsg;
1320                 return false;
1321         }
1322 #endif
1323         return static_cast<CoreBackendPort*>(src)->is_connected (dst_port);
1324 }
1325
1326 bool
1327 CoreAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
1328 {
1329         if (!valid_port (port)) {
1330                 PBD::warning << _("CoreAudioBackend::physically_connected: Invalid Port") << endmsg;
1331                 return false;
1332         }
1333         return static_cast<CoreBackendPort*>(port)->is_physically_connected ();
1334 }
1335
1336 int
1337 CoreAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
1338 {
1339         if (!valid_port (port)) {
1340                 PBD::warning << _("CoreAudioBackend::get_connections: Invalid Port") << endmsg;
1341                 return -1;
1342         }
1343
1344         assert (0 == names.size ());
1345
1346         const std::set<CoreBackendPort*>& connected_ports = static_cast<CoreBackendPort*>(port)->get_connections ();
1347
1348         for (std::set<CoreBackendPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
1349                 names.push_back ((*i)->name ());
1350         }
1351
1352         return (int)names.size ();
1353 }
1354
1355 /* MIDI */
1356 int
1357 CoreAudioBackend::midi_event_get (
1358         pframes_t& timestamp,
1359         size_t& size, uint8_t** buf, void* port_buffer,
1360         uint32_t event_index)
1361 {
1362         if (!buf || !port_buffer) return -1;
1363         CoreMidiBuffer& source = * static_cast<CoreMidiBuffer*>(port_buffer);
1364         if (event_index >= source.size ()) {
1365                 return -1;
1366         }
1367         CoreMidiEvent * const event = source[event_index].get ();
1368
1369         timestamp = event->timestamp ();
1370         size = event->size ();
1371         *buf = event->data ();
1372         return 0;
1373 }
1374
1375 int
1376 CoreAudioBackend::_midi_event_put (
1377         void* port_buffer,
1378         pframes_t timestamp,
1379         const uint8_t* buffer, size_t size)
1380 {
1381         if (!buffer || !port_buffer) return -1;
1382         CoreMidiBuffer& dst = * static_cast<CoreMidiBuffer*>(port_buffer);
1383         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
1384 #ifndef NDEBUG
1385                 // nevermind, ::get_buffer() sorts events
1386                 fprintf (stderr, "CoreMidiBuffer: unordered event: %d > %d\n",
1387                          (pframes_t)dst.back ()->timestamp (), timestamp);
1388 #endif
1389         }
1390         dst.push_back (boost::shared_ptr<CoreMidiEvent>(new CoreMidiEvent (timestamp, buffer, size)));
1391         return 0;
1392 }
1393
1394
1395 uint32_t
1396 CoreAudioBackend::get_midi_event_count (void* port_buffer)
1397 {
1398         if (!port_buffer) return 0;
1399         return static_cast<CoreMidiBuffer*>(port_buffer)->size ();
1400 }
1401
1402 void
1403 CoreAudioBackend::midi_clear (void* port_buffer)
1404 {
1405         if (!port_buffer) return;
1406         CoreMidiBuffer * buf = static_cast<CoreMidiBuffer*>(port_buffer);
1407         assert (buf);
1408         buf->clear ();
1409 }
1410
1411 /* Monitoring */
1412
1413 bool
1414 CoreAudioBackend::can_monitor_input () const
1415 {
1416         return false;
1417 }
1418
1419 int
1420 CoreAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1421 {
1422         return -1;
1423 }
1424
1425 int
1426 CoreAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1427 {
1428         return -1;
1429 }
1430
1431 bool
1432 CoreAudioBackend::monitoring_input (PortEngine::PortHandle)
1433 {
1434         return false;
1435 }
1436
1437 /* Latency management */
1438
1439 void
1440 CoreAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1441 {
1442         if (!valid_port (port)) {
1443                 PBD::warning << _("CoreBackendPort::set_latency_range (): invalid port.") << endmsg;
1444                 return;
1445         }
1446         static_cast<CoreBackendPort*>(port)->set_latency_range (latency_range, for_playback);
1447 }
1448
1449 LatencyRange
1450 CoreAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1451 {
1452         LatencyRange r;
1453         if (!valid_port (port)) {
1454                 PBD::warning << _("CoreBackendPort::get_latency_range (): invalid port.") << endmsg;
1455                 r.min = 0;
1456                 r.max = 0;
1457                 return r;
1458         }
1459         CoreBackendPort* p = static_cast<CoreBackendPort*>(port);
1460         assert(p);
1461
1462         r = p->latency_range (for_playback);
1463         if (p->is_physical() && p->is_terminal() && p->type() == DataType::AUDIO) {
1464                 if (p->is_input() && for_playback) {
1465                         r.min += _samples_per_period;
1466                         r.max += _samples_per_period;
1467                 }
1468                 if (p->is_output() && !for_playback) {
1469                         r.min += _samples_per_period;
1470                         r.max += _samples_per_period;
1471                 }
1472         }
1473         return r;
1474 }
1475
1476 /* Discovering physical ports */
1477
1478 bool
1479 CoreAudioBackend::port_is_physical (PortEngine::PortHandle port) const
1480 {
1481         if (!valid_port (port)) {
1482                 PBD::warning << _("CoreBackendPort::port_is_physical (): invalid port.") << endmsg;
1483                 return false;
1484         }
1485         return static_cast<CoreBackendPort*>(port)->is_physical ();
1486 }
1487
1488 void
1489 CoreAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1490 {
1491         for (PortIndex::iterator i = _ports.begin (); i != _ports.end (); ++i) {
1492                 CoreBackendPort* port = *i;
1493                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1494                         port_names.push_back (port->name ());
1495                 }
1496         }
1497 }
1498
1499 void
1500 CoreAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1501 {
1502         for (PortIndex::iterator i = _ports.begin (); i != _ports.end (); ++i) {
1503                 CoreBackendPort* port = *i;
1504                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1505                         port_names.push_back (port->name ());
1506                 }
1507         }
1508 }
1509
1510 ChanCount
1511 CoreAudioBackend::n_physical_outputs () const
1512 {
1513         int n_midi = 0;
1514         int n_audio = 0;
1515         for (PortIndex::const_iterator i = _ports.begin (); i != _ports.end (); ++i) {
1516                 CoreBackendPort* port = *i;
1517                 if (port->is_output () && port->is_physical ()) {
1518                         switch (port->type ()) {
1519                         case DataType::AUDIO: ++n_audio; break;
1520                         case DataType::MIDI: ++n_midi; break;
1521                         default: break;
1522                         }
1523                 }
1524         }
1525         ChanCount cc;
1526         cc.set (DataType::AUDIO, n_audio);
1527         cc.set (DataType::MIDI, n_midi);
1528         return cc;
1529 }
1530
1531 ChanCount
1532 CoreAudioBackend::n_physical_inputs () const
1533 {
1534         int n_midi = 0;
1535         int n_audio = 0;
1536         for (PortIndex::const_iterator i = _ports.begin (); i != _ports.end (); ++i) {
1537                 CoreBackendPort* port = *i;
1538                 if (port->is_input () && port->is_physical ()) {
1539                         switch (port->type ()) {
1540                         case DataType::AUDIO: ++n_audio; break;
1541                         case DataType::MIDI: ++n_midi; break;
1542                         default: break;
1543                         }
1544                 }
1545         }
1546         ChanCount cc;
1547         cc.set (DataType::AUDIO, n_audio);
1548         cc.set (DataType::MIDI, n_midi);
1549         return cc;
1550 }
1551
1552 /* Getting access to the data buffer for a port */
1553
1554 void*
1555 CoreAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1556 {
1557         if (!port || !valid_port (port)) return NULL;
1558         return static_cast<CoreBackendPort*>(port)->get_buffer (nframes);
1559 }
1560
1561 void
1562 CoreAudioBackend::pre_process ()
1563 {
1564         bool connections_changed = false;
1565         bool ports_changed = false;
1566         if (!pthread_mutex_trylock (&_port_callback_mutex)) {
1567                 if (_port_change_flag) {
1568                         ports_changed = true;
1569                         _port_change_flag = false;
1570                 }
1571                 if (!_port_connection_queue.empty ()) {
1572                         connections_changed = true;
1573                 }
1574                 while (!_port_connection_queue.empty ()) {
1575                         PortConnectData *c = _port_connection_queue.back ();
1576                         manager.connect_callback (c->a, c->b, c->c);
1577                         _port_connection_queue.pop_back ();
1578                         delete c;
1579                 }
1580                 pthread_mutex_unlock (&_port_callback_mutex);
1581         }
1582         if (ports_changed) {
1583                 manager.registration_callback();
1584         }
1585         if (connections_changed) {
1586                 manager.graph_order_callback();
1587         }
1588         if (connections_changed || ports_changed) {
1589                 engine.latency_callback(false);
1590                 engine.latency_callback(true);
1591         }
1592 }
1593
1594 void
1595 CoreAudioBackend::reset_midi_parsers ()
1596 {
1597         for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it) {
1598                 CoreMidiPort* port = dynamic_cast<CoreMidiPort*>(*it);
1599                 if (port) {
1600                         port->reset_parser ();
1601                 }
1602         }
1603 }
1604
1605 void *
1606 CoreAudioBackend::freewheel_thread ()
1607 {
1608         _active_fw = true;
1609         bool first_run = false;
1610         /* Freewheeling - use for export.   The first call to
1611          * engine.process_callback() after engine.freewheel_callback will
1612          * if the first export cycle.
1613          * For reliable precise export timing, the calls need to be in sync.
1614          *
1615          * Furthermore we need to make sure the registered process thread
1616          * is correct.
1617          *
1618          * _freewheeling = GUI thread state as set by ::freewheel()
1619          * _freewheel = in sync here (export thread)
1620          */
1621         pthread_mutex_lock (&_freewheel_mutex);
1622         while (_run) {
1623                 // check if we should run,
1624                 if (_freewheeling != _freewheel) {
1625                         if (!_freewheeling) {
1626                                 // prepare leaving freewheeling mode
1627                                 _freewheel = false; // first mark as disabled
1628                                 _reinit_thread_callback = true; // hand over _main_thread
1629                                 _freewheel_ack = false; // prepare next handshake
1630                                 reset_midi_parsers ();
1631                                 _midiio->set_enabled(true);
1632                                 engine.freewheel_callback (_freewheeling);
1633                         } else {
1634                                 first_run = true;
1635                                 _freewheel = true;
1636                         }
1637                 }
1638
1639                 if (!_freewheel || !_freewheel_ack) {
1640                         // wait for a change, we use a timed wait to
1641                         // terminate early in case some error sets _run = 0
1642                         struct timeval tv;
1643                         struct timespec ts;
1644                         gettimeofday (&tv, NULL);
1645                         ts.tv_sec = tv.tv_sec + 3;
1646                         ts.tv_nsec = 0;
1647                         pthread_cond_timedwait (&_freewheel_signal, &_freewheel_mutex, &ts);
1648                         continue;
1649                 }
1650
1651                 if (first_run) {
1652                         // tell the engine we're ready to GO.
1653                         engine.freewheel_callback (_freewheeling);
1654                         first_run = false;
1655                         _main_thread = pthread_self();
1656                         AudioEngine::thread_init_callback (this);
1657                         _midiio->set_enabled(false);
1658                         reset_midi_parsers ();
1659                 }
1660
1661                 // process port updates first in every cycle.
1662                 pre_process();
1663
1664                 // prevent coreaudio device changes
1665                 pthread_mutex_lock (&_process_callback_mutex);
1666
1667                 /* Freewheelin' */
1668
1669                 // clear input buffers
1670                 for (std::vector<CoreBackendPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
1671                         memset ((*it)->get_buffer (_samples_per_period), 0, _samples_per_period * sizeof (Sample));
1672                 }
1673                 for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it) {
1674                         static_cast<CoreMidiBuffer*>((*it)->get_buffer(0))->clear ();
1675                 }
1676
1677                 _last_process_start = 0;
1678                 if (engine.process_callback (_samples_per_period)) {
1679                         pthread_mutex_unlock (&_process_callback_mutex);
1680                         break;
1681                 }
1682
1683                 pthread_mutex_unlock (&_process_callback_mutex);
1684                 _dsp_load = 1.0;
1685                 Glib::usleep (100); // don't hog cpu
1686         }
1687
1688         pthread_mutex_unlock (&_freewheel_mutex);
1689
1690         _active_fw = false;
1691
1692         if (_run) {
1693                 // engine.process_callback() returner error
1694                 engine.halted_callback("CoreAudio Freehweeling aborted.");
1695         }
1696         return 0;
1697 }
1698 int
1699 CoreAudioBackend::process_callback (const uint32_t n_samples, const uint64_t host_time)
1700 {
1701         uint32_t i = 0;
1702         uint64_t clock1;
1703
1704         _active_ca = true;
1705
1706         if (_run && _freewheel && !_freewheel_ack) {
1707                 // acknowledge freewheeling; hand-over thread ID
1708                 pthread_mutex_lock (&_freewheel_mutex);
1709                 if (_freewheel) _freewheel_ack = true;
1710                 pthread_cond_signal (&_freewheel_signal);
1711                 pthread_mutex_unlock (&_freewheel_mutex);
1712         }
1713
1714         if (!_run || _freewheel || _preinit) {
1715                 // NB if we return 1, the output is
1716                 // zeroed by the coreaudio callback
1717                 return 1;
1718         }
1719
1720         if (_reinit_thread_callback || _main_thread != pthread_self()) {
1721                 _reinit_thread_callback = false;
1722                 _main_thread = pthread_self();
1723                 AudioEngine::thread_init_callback (this);
1724         }
1725
1726         if (pthread_mutex_trylock (&_process_callback_mutex)) {
1727                 // block while devices are added/removed
1728 #ifndef NDEBUG
1729                 printf("Xrun due to device change\n");
1730 #endif
1731                 engine.Xrun();
1732                 return 1;
1733         }
1734         /* port-connection change */
1735         pre_process();
1736
1737         // cycle-length in usec
1738         const double nominal_time = 1e6 * n_samples / _samplerate;
1739
1740         clock1 = g_get_monotonic_time();
1741
1742         /* get midi */
1743         i=0;
1744         for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++i) {
1745                 CoreMidiPort* port = dynamic_cast<CoreMidiPort*> (*it);
1746                 if (!port) {
1747                         continue;
1748                 }
1749                 uint64_t time_ns;
1750                 uint8_t data[128]; // matches CoreMidi's MIDIPacket
1751                 size_t size = sizeof(data);
1752
1753                 port->clear_events ();
1754
1755                 while (_midiio->recv_event (i, nominal_time, time_ns, data, size)) {
1756                         pframes_t time = floor((float) time_ns * _samplerate * 1e-9);
1757                         assert (time < n_samples);
1758                         port->parse_events (time, data, size);
1759                         size = sizeof(data); /* prepare for next call to recv_event */
1760                 }
1761         }
1762
1763         /* get audio */
1764         i = 0;
1765         for (std::vector<CoreBackendPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++i) {
1766                 _pcmio->get_capture_channel (i, (float*)((*it)->get_buffer(n_samples)), n_samples);
1767         }
1768
1769         /* clear output buffers */
1770         for (std::vector<CoreBackendPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it) {
1771                 memset ((*it)->get_buffer (n_samples), 0, n_samples * sizeof (Sample));
1772         }
1773
1774         _midiio->start_cycle();
1775         _last_process_start = host_time;
1776
1777         if (engine.process_callback (n_samples)) {
1778                 fprintf(stderr, "ENGINE PROCESS ERROR\n");
1779                 //_pcmio->pcm_stop ();
1780                 _active_ca = false;
1781                 pthread_mutex_unlock (&_process_callback_mutex);
1782                 return -1;
1783         }
1784
1785         /* mixdown midi */
1786         for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it) {
1787                 static_cast<CoreMidiPort*>(*it)->get_buffer(0);
1788         }
1789
1790         /* queue outgoing midi */
1791         i = 0;
1792         for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it, ++i) {
1793 #if 0 // something's still b0rked with CoreMidiIo::send_events()
1794                 const CoreMidiBuffer *src = static_cast<const CoreMidiPort*>(*it)->const_buffer();
1795                 _midiio->send_events (i, nominal_time, (void*)src);
1796 #else // works..
1797                 const CoreMidiBuffer *src = static_cast<const CoreMidiPort*>(*it)->const_buffer();
1798                 for (CoreMidiBuffer::const_iterator mit = src->begin (); mit != src->end (); ++mit) {
1799                         _midiio->send_event (i, (*mit)->timestamp() / nominal_time, (*mit)->data(), (*mit)->size());
1800                 }
1801 #endif
1802         }
1803
1804         /* write back audio */
1805         i = 0;
1806         for (std::vector<CoreBackendPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it, ++i) {
1807                 _pcmio->set_playback_channel (i, (float const*)(*it)->get_buffer (n_samples), n_samples);
1808         }
1809
1810         _processed_samples += n_samples;
1811
1812         /* calc DSP load. */
1813         _dsp_load_calc.set_max_time (_samplerate, _samples_per_period);
1814         _dsp_load_calc.set_start_timestamp_us (clock1);
1815         _dsp_load_calc.set_stop_timestamp_us (g_get_monotonic_time());
1816         _dsp_load = _dsp_load_calc.get_dsp_load ();
1817
1818         pthread_mutex_unlock (&_process_callback_mutex);
1819         return 0;
1820 }
1821
1822 void
1823 CoreAudioBackend::error_callback ()
1824 {
1825         _pcmio->set_error_callback (NULL, NULL);
1826         _pcmio->set_sample_rate_callback (NULL, NULL);
1827         _pcmio->set_xrun_callback (NULL, NULL);
1828         _midiio->set_port_changed_callback(NULL, NULL);
1829         engine.halted_callback("CoreAudio Process aborted.");
1830         _active_ca = false;
1831 }
1832
1833 void
1834 CoreAudioBackend::xrun_callback ()
1835 {
1836         engine.Xrun ();
1837 }
1838
1839 void
1840 CoreAudioBackend::buffer_size_callback ()
1841 {
1842         uint32_t bs = _pcmio->samples_per_period();
1843         if (bs == _samples_per_period) {
1844                 return;
1845         }
1846         _samples_per_period = bs;
1847         engine.buffer_size_change (_samples_per_period);
1848 }
1849
1850 void
1851 CoreAudioBackend::sample_rate_callback ()
1852 {
1853         if (_preinit) {
1854 #ifndef NDEBUG
1855                 printf("Samplerate change during initialization.\n");
1856 #endif
1857                 return;
1858         }
1859         _pcmio->set_error_callback (NULL, NULL);
1860         _pcmio->set_sample_rate_callback (NULL, NULL);
1861         _pcmio->set_xrun_callback (NULL, NULL);
1862         _midiio->set_port_changed_callback(NULL, NULL);
1863         engine.halted_callback("Sample Rate Changed.");
1864         stop();
1865 }
1866
1867 void
1868 CoreAudioBackend::hw_changed_callback ()
1869 {
1870         _reinit_thread_callback = true;
1871         engine.request_device_list_update();
1872 }
1873
1874 /******************************************************************************/
1875
1876 static boost::shared_ptr<CoreAudioBackend> _instance;
1877
1878 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
1879 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
1880 static int deinstantiate ();
1881 static bool already_configured ();
1882 static bool available ();
1883
1884 static ARDOUR::AudioBackendInfo _descriptor = {
1885         "CoreAudio",
1886         instantiate,
1887         deinstantiate,
1888         backend_factory,
1889         already_configured,
1890         available
1891 };
1892
1893 static boost::shared_ptr<AudioBackend>
1894 backend_factory (AudioEngine& e)
1895 {
1896         if (!_instance) {
1897                 _instance.reset (new CoreAudioBackend (e, _descriptor));
1898         }
1899         return _instance;
1900 }
1901
1902 static int
1903 instantiate (const std::string& arg1, const std::string& /* arg2 */)
1904 {
1905         s_instance_name = arg1;
1906         return 0;
1907 }
1908
1909 static int
1910 deinstantiate ()
1911 {
1912         _instance.reset ();
1913         return 0;
1914 }
1915
1916 static bool
1917 already_configured ()
1918 {
1919         return false;
1920 }
1921
1922 static bool
1923 available ()
1924 {
1925         return true;
1926 }
1927
1928 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
1929 {
1930         return &_descriptor;
1931 }
1932
1933
1934 /******************************************************************************/
1935 CoreBackendPort::CoreBackendPort (CoreAudioBackend &b, const std::string& name, PortFlags flags)
1936         : _osx_backend (b)
1937         , _name  (name)
1938         , _flags (flags)
1939 {
1940         _capture_latency_range.min = 0;
1941         _capture_latency_range.max = 0;
1942         _playback_latency_range.min = 0;
1943         _playback_latency_range.max = 0;
1944 }
1945
1946 CoreBackendPort::~CoreBackendPort () {
1947         disconnect_all ();
1948 }
1949
1950
1951 int CoreBackendPort::connect (CoreBackendPort *port)
1952 {
1953         if (!port) {
1954                 PBD::warning << _("CoreBackendPort::connect (): invalid (null) port") << endmsg;
1955                 return -1;
1956         }
1957
1958         if (type () != port->type ()) {
1959                 PBD::warning << _("CoreBackendPort::connect (): wrong port-type") << endmsg;
1960                 return -1;
1961         }
1962
1963         if (is_output () && port->is_output ()) {
1964                 PBD::warning << _("CoreBackendPort::connect (): cannot inter-connect output ports.") << endmsg;
1965                 return -1;
1966         }
1967
1968         if (is_input () && port->is_input ()) {
1969                 PBD::warning << _("CoreBackendPort::connect (): cannot inter-connect input ports.") << endmsg;
1970                 return -1;
1971         }
1972
1973         if (this == port) {
1974                 PBD::warning << _("CoreBackendPort::connect (): cannot self-connect ports.") << endmsg;
1975                 return -1;
1976         }
1977
1978         if (is_connected (port)) {
1979 #if 0 // don't bother to warn about this for now. just ignore it
1980                 PBD::info << _("CoreBackendPort::connect (): ports are already connected:")
1981                           << " (" << name () << ") -> (" << port->name () << ")"
1982                           << endmsg;
1983 #endif
1984                 return -1;
1985         }
1986
1987         _connect (port, true);
1988         return 0;
1989 }
1990
1991
1992 void CoreBackendPort::_connect (CoreBackendPort *port, bool callback)
1993 {
1994         _connections.insert (port);
1995         if (callback) {
1996                 port->_connect (this, false);
1997                 _osx_backend.port_connect_callback (name(),  port->name(), true);
1998         }
1999 }
2000
2001 int CoreBackendPort::disconnect (CoreBackendPort *port)
2002 {
2003         if (!port) {
2004                 PBD::warning << _("CoreBackendPort::disconnect (): invalid (null) port") << endmsg;
2005                 return -1;
2006         }
2007
2008         if (!is_connected (port)) {
2009                 PBD::warning << _("CoreBackendPort::disconnect (): ports are not connected:")
2010                              << " (" << name () << ") -> (" << port->name () << ")"
2011                              << endmsg;
2012                 return -1;
2013         }
2014         _disconnect (port, true);
2015         return 0;
2016 }
2017
2018 void CoreBackendPort::_disconnect (CoreBackendPort *port, bool callback)
2019 {
2020         std::set<CoreBackendPort*>::iterator it = _connections.find (port);
2021         assert (it != _connections.end ());
2022         _connections.erase (it);
2023         if (callback) {
2024                 port->_disconnect (this, false);
2025                 _osx_backend.port_connect_callback (name(),  port->name(), false);
2026         }
2027 }
2028
2029
2030 void CoreBackendPort::disconnect_all ()
2031 {
2032         while (!_connections.empty ()) {
2033                 std::set<CoreBackendPort*>::iterator it = _connections.begin ();
2034                 (*it)->_disconnect (this, false);
2035                 _osx_backend.port_connect_callback (name(), (*it)->name(), false);
2036                 _connections.erase (it);
2037         }
2038 }
2039
2040 bool
2041 CoreBackendPort::is_connected (const CoreBackendPort *port) const
2042 {
2043         return _connections.find (const_cast<CoreBackendPort *>(port)) != _connections.end ();
2044 }
2045
2046 bool CoreBackendPort::is_physically_connected () const
2047 {
2048         for (std::set<CoreBackendPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
2049                 if ((*it)->is_physical ()) {
2050                         return true;
2051                 }
2052         }
2053         return false;
2054 }
2055
2056 /******************************************************************************/
2057
2058 CoreAudioPort::CoreAudioPort (CoreAudioBackend &b, const std::string& name, PortFlags flags)
2059         : CoreBackendPort (b, name, flags)
2060 {
2061         memset (_buffer, 0, sizeof (_buffer));
2062         mlock(_buffer, sizeof (_buffer));
2063 }
2064
2065 CoreAudioPort::~CoreAudioPort () { }
2066
2067 void* CoreAudioPort::get_buffer (pframes_t n_samples)
2068 {
2069         if (is_input ()) {
2070                 const std::set<CoreBackendPort *>& connections = get_connections ();
2071                 std::set<CoreBackendPort*>::const_iterator it = connections.begin ();
2072                 if (it == connections.end ()) {
2073                         memset (_buffer, 0, n_samples * sizeof (Sample));
2074                 } else {
2075                         CoreAudioPort const * source = static_cast<const CoreAudioPort*>(*it);
2076                         assert (source && source->is_output ());
2077                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
2078                         while (++it != connections.end ()) {
2079                                 source = static_cast<const CoreAudioPort*>(*it);
2080                                 assert (source && source->is_output ());
2081                                 Sample* dst = buffer ();
2082                                 const Sample* src = source->const_buffer ();
2083                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
2084                                         *dst += *src;
2085                                 }
2086                         }
2087                 }
2088         }
2089         return _buffer;
2090 }
2091
2092
2093 CoreMidiPort::CoreMidiPort (CoreAudioBackend &b, const std::string& name, PortFlags flags)
2094         : CoreBackendPort (b, name, flags)
2095         , _n_periods (1)
2096         , _bufperiod (0)
2097         , _event (0, 0)
2098         , _first_time(true)
2099         , _unbuffered_bytes(0)
2100         , _total_bytes(0)
2101         , _expected_bytes(0)
2102         , _status_byte(0)
2103
2104 {
2105         _buffer[0].clear ();
2106         _buffer[1].clear ();
2107 }
2108
2109 CoreMidiPort::~CoreMidiPort () { }
2110
2111 struct MidiEventSorter {
2112         bool operator() (const boost::shared_ptr<CoreMidiEvent>& a, const boost::shared_ptr<CoreMidiEvent>& b) {
2113                 return *a < *b;
2114         }
2115 };
2116
2117 void* CoreMidiPort::get_buffer (pframes_t /* nframes */)
2118 {
2119         if (is_input ()) {
2120                 (_buffer[_bufperiod]).clear ();
2121                 const std::set<CoreBackendPort*>& connections = get_connections ();
2122                 for (std::set<CoreBackendPort*>::const_iterator i = connections.begin ();
2123                      i != connections.end ();
2124                      ++i) {
2125                         const CoreMidiBuffer * src = static_cast<const CoreMidiPort*>(*i)->const_buffer ();
2126                         for (CoreMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
2127                                 (_buffer[_bufperiod]).push_back (boost::shared_ptr<CoreMidiEvent>(new CoreMidiEvent (**it)));
2128                         }
2129                 }
2130                 std::sort ((_buffer[_bufperiod]).begin (), (_buffer[_bufperiod]).end (), MidiEventSorter());
2131         }
2132
2133         return &(_buffer[_bufperiod]);
2134 }
2135
2136 int
2137 CoreMidiPort::queue_event (
2138         void* port_buffer,
2139         pframes_t timestamp,
2140         const uint8_t* buffer, size_t size)
2141 {
2142         const int ret = CoreAudioBackend::_midi_event_put (port_buffer, timestamp, buffer, size);
2143         if (!ret) { /* success */
2144                 _event._pending = false;
2145         }
2146         return ret;
2147 }
2148
2149 void
2150 CoreMidiPort::reset_parser ()
2151 {
2152         _event._pending = false;
2153         _first_time = true;
2154         _unbuffered_bytes = 0;
2155         _total_bytes = 0;
2156         _expected_bytes = 0;
2157         _status_byte = 0;
2158 }
2159
2160 void
2161 CoreMidiPort::clear_events ()
2162 {
2163         CoreMidiBuffer* mbuf = static_cast<CoreMidiBuffer*>(get_buffer(0));
2164         mbuf->clear();
2165 }
2166
2167 void
2168 CoreMidiPort::parse_events (const uint64_t time, const uint8_t *data, const size_t size)
2169 {
2170         CoreMidiBuffer* mbuf = static_cast<CoreMidiBuffer*>(get_buffer(0));
2171
2172         if (_event._pending) {
2173                 if (queue_event (mbuf, _event._time, _parser_buffer, _event._size)) {
2174                         return;
2175                 }
2176         }
2177
2178         for (size_t i = 0; i < size; ++i) {
2179                 if (_first_time && !(data[i] & 0x80)) {
2180                         continue;
2181                 }
2182
2183                 _first_time = false;
2184
2185                 if (process_byte(time, data[i])) {
2186                         if (queue_event (mbuf, _event._time, _parser_buffer, _event._size)) {
2187                                 return;
2188                         }
2189                 }
2190         }
2191 }
2192
2193 // based on JackMidiRawInputWriteQueue by Devin Anderson //
2194 bool
2195 CoreMidiPort::process_byte(const uint64_t time, const uint8_t byte)
2196 {
2197         if (byte >= 0xf8) {
2198                 // Realtime
2199                 if (byte == 0xfd) {
2200                         return false;
2201                 }
2202                 _parser_buffer[0] = byte;
2203                 prepare_byte_event(time, byte);
2204                 return true;
2205         }
2206         if (byte == 0xf7) {
2207                 // Sysex end
2208                 if (_status_byte == 0xf0) {
2209                         record_byte(byte);
2210                         return prepare_buffered_event(time);
2211                 }
2212                 _total_bytes = 0;
2213                 _unbuffered_bytes = 0;
2214                 _expected_bytes = 0;
2215                 _status_byte = 0;
2216                 return false;
2217         }
2218         if (byte >= 0x80) {
2219                 // Non-realtime status byte
2220                 if (_total_bytes) {
2221                         printf ("CoreMidiPort: discarded bogus midi message\n");
2222 #if 0
2223                         for (size_t i=0; i < _total_bytes; ++i) {
2224                                 printf("%02x ", _parser_buffer[i]);
2225                         }
2226                         printf("\n");
2227 #endif
2228                         _total_bytes = 0;
2229                         _unbuffered_bytes = 0;
2230                 }
2231                 _status_byte = byte;
2232                 switch (byte & 0xf0) {
2233                 case 0x80:
2234                 case 0x90:
2235                 case 0xa0:
2236                 case 0xb0:
2237                 case 0xe0:
2238                         // Note On, Note Off, Aftertouch, Control Change, Pitch Wheel
2239                         _expected_bytes = 3;
2240                         break;
2241                 case 0xc0:
2242                 case 0xd0:
2243                         // Program Change, Channel Pressure
2244                         _expected_bytes = 2;
2245                         break;
2246                 case 0xf0:
2247                         switch (byte) {
2248                         case 0xf0:
2249                                 // Sysex
2250                                 _expected_bytes = 0;
2251                                 break;
2252                         case 0xf1:
2253                         case 0xf3:
2254                                 // MTC Quarter Frame, Song Select
2255                                 _expected_bytes = 2;
2256                                 break;
2257                         case 0xf2:
2258                                 // Song Position
2259                                 _expected_bytes = 3;
2260                                 break;
2261                         case 0xf4:
2262                         case 0xf5:
2263                                 // Undefined
2264                                 _expected_bytes = 0;
2265                                 _status_byte = 0;
2266                                 return false;
2267                         case 0xf6:
2268                                 // Tune Request
2269                                 prepare_byte_event(time, byte);
2270                                 _expected_bytes = 0;
2271                                 _status_byte = 0;
2272                                 return true;
2273                         }
2274                 }
2275                 record_byte(byte);
2276                 return false;
2277         }
2278         // Data byte
2279         if (! _status_byte) {
2280                 // Data bytes without a status will be discarded.
2281                 _total_bytes++;
2282                 _unbuffered_bytes++;
2283                 return false;
2284         }
2285         if (! _total_bytes) {
2286                 record_byte(_status_byte);
2287         }
2288         record_byte(byte);
2289         return (_total_bytes == _expected_bytes) ? prepare_buffered_event(time) : false;
2290 }
2291
2292
2293 CoreMidiEvent::CoreMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
2294         : _size (size)
2295         , _timestamp (timestamp)
2296         , _data (0)
2297 {
2298         if (size > 0) {
2299                 _data = (uint8_t*) malloc (size);
2300                 memcpy (_data, data, size);
2301         }
2302 }
2303
2304 CoreMidiEvent::CoreMidiEvent (const CoreMidiEvent& other)
2305         : _size (other.size ())
2306         , _timestamp (other.timestamp ())
2307         , _data (0)
2308 {
2309         if (other.size () && other.const_data ()) {
2310                 _data = (uint8_t*) malloc (other.size ());
2311                 memcpy (_data, other.const_data (), other.size ());
2312         }
2313 };
2314
2315 CoreMidiEvent::~CoreMidiEvent () {
2316         free (_data);
2317 };