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