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