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