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