add backend support for port properties (CoreAudio)
[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_name(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_name(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_name(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                 _system_midi_in.push_back(static_cast<CoreBackendPort*>(p));
1026                 _port_change_flag = true;
1027         }
1028
1029         for (size_t i = 0; i < _midiio->n_midi_outputs(); ++i) {
1030                 std::string name = _midiio->port_name(i, false);
1031                 if (find_port_in(_system_midi_out, name)) {
1032                         continue;
1033                 }
1034
1035 #ifndef NDEBUG
1036                 printf("register MIDI OUT: %s\n", name.c_str());
1037 #endif
1038                 PortHandle p = add_port(name, DataType::MIDI, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
1039                 if (!p) {
1040                         fprintf(stderr, "failed to register MIDI OUT: %s\n", name.c_str());
1041                         continue;
1042                 }
1043                 LatencyRange lr;
1044                 lr.min = lr.max = _samples_per_period; // TODO add per-port midi-systemic latency
1045                 set_latency_range (p, false, lr);
1046                 _system_midi_out.push_back(static_cast<CoreBackendPort*>(p));
1047                 _port_change_flag = true;
1048         }
1049
1050
1051         assert(_system_midi_out.size() == _midiio->n_midi_outputs());
1052         assert(_system_midi_in.size() == _midiio->n_midi_inputs());
1053
1054         pthread_mutex_unlock (&_process_callback_mutex);
1055 }
1056
1057 void
1058 CoreAudioBackend::unregister_ports (bool system_only)
1059 {
1060         size_t i = 0;
1061         _system_inputs.clear();
1062         _system_outputs.clear();
1063         _system_midi_in.clear();
1064         _system_midi_out.clear();
1065         while (i <  _ports.size ()) {
1066                 CoreBackendPort* port = _ports[i];
1067                 if (! system_only || (port->is_physical () && port->is_terminal ())) {
1068                         port->disconnect_all ();
1069                         delete port;
1070                         _ports.erase (_ports.begin() + i);
1071                 } else {
1072                         ++i;
1073                 }
1074         }
1075 }
1076
1077 int
1078 CoreAudioBackend::connect (const std::string& src, const std::string& dst)
1079 {
1080         CoreBackendPort* src_port = find_port (src);
1081         CoreBackendPort* dst_port = find_port (dst);
1082
1083         if (!src_port) {
1084                 PBD::error << _("CoreAudioBackend::connect: Invalid Source port:")
1085                                 << " (" << src <<")" << endmsg;
1086                 return -1;
1087         }
1088         if (!dst_port) {
1089                 PBD::error << _("CoreAudioBackend::connect: Invalid Destination port:")
1090                         << " (" << dst <<")" << endmsg;
1091                 return -1;
1092         }
1093         return src_port->connect (dst_port);
1094 }
1095
1096 int
1097 CoreAudioBackend::disconnect (const std::string& src, const std::string& dst)
1098 {
1099         CoreBackendPort* src_port = find_port (src);
1100         CoreBackendPort* dst_port = find_port (dst);
1101
1102         if (!src_port || !dst_port) {
1103                 PBD::error << _("CoreAudioBackend::disconnect: Invalid Port(s)") << endmsg;
1104                 return -1;
1105         }
1106         return src_port->disconnect (dst_port);
1107 }
1108
1109 int
1110 CoreAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
1111 {
1112         CoreBackendPort* dst_port = find_port (dst);
1113         if (!valid_port (src)) {
1114                 PBD::error << _("CoreAudioBackend::connect: Invalid Source Port Handle") << endmsg;
1115                 return -1;
1116         }
1117         if (!dst_port) {
1118                 PBD::error << _("CoreAudioBackend::connect: Invalid Destination Port")
1119                         << " (" << dst << ")" << endmsg;
1120                 return -1;
1121         }
1122         return static_cast<CoreBackendPort*>(src)->connect (dst_port);
1123 }
1124
1125 int
1126 CoreAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
1127 {
1128         CoreBackendPort* dst_port = find_port (dst);
1129         if (!valid_port (src) || !dst_port) {
1130                 PBD::error << _("CoreAudioBackend::disconnect: Invalid Port(s)") << endmsg;
1131                 return -1;
1132         }
1133         return static_cast<CoreBackendPort*>(src)->disconnect (dst_port);
1134 }
1135
1136 int
1137 CoreAudioBackend::disconnect_all (PortEngine::PortHandle port)
1138 {
1139         if (!valid_port (port)) {
1140                 PBD::error << _("CoreAudioBackend::disconnect_all: Invalid Port") << endmsg;
1141                 return -1;
1142         }
1143         static_cast<CoreBackendPort*>(port)->disconnect_all ();
1144         return 0;
1145 }
1146
1147 bool
1148 CoreAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
1149 {
1150         if (!valid_port (port)) {
1151                 PBD::error << _("CoreAudioBackend::disconnect_all: Invalid Port") << endmsg;
1152                 return false;
1153         }
1154         return static_cast<CoreBackendPort*>(port)->is_connected ();
1155 }
1156
1157 bool
1158 CoreAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
1159 {
1160         CoreBackendPort* dst_port = find_port (dst);
1161         if (!valid_port (src) || !dst_port) {
1162                 PBD::error << _("CoreAudioBackend::connected_to: Invalid Port") << endmsg;
1163                 return false;
1164         }
1165         return static_cast<CoreBackendPort*>(src)->is_connected (dst_port);
1166 }
1167
1168 bool
1169 CoreAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
1170 {
1171         if (!valid_port (port)) {
1172                 PBD::error << _("CoreAudioBackend::physically_connected: Invalid Port") << endmsg;
1173                 return false;
1174         }
1175         return static_cast<CoreBackendPort*>(port)->is_physically_connected ();
1176 }
1177
1178 int
1179 CoreAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
1180 {
1181         if (!valid_port (port)) {
1182                 PBD::error << _("CoreAudioBackend::get_connections: Invalid Port") << endmsg;
1183                 return -1;
1184         }
1185
1186         assert (0 == names.size ());
1187
1188         const std::vector<CoreBackendPort*>& connected_ports = static_cast<CoreBackendPort*>(port)->get_connections ();
1189
1190         for (std::vector<CoreBackendPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
1191                 names.push_back ((*i)->name ());
1192         }
1193
1194         return (int)names.size ();
1195 }
1196
1197 /* MIDI */
1198 int
1199 CoreAudioBackend::midi_event_get (
1200                 pframes_t& timestamp,
1201                 size_t& size, uint8_t** buf, void* port_buffer,
1202                 uint32_t event_index)
1203 {
1204         assert (buf && port_buffer);
1205         CoreMidiBuffer& source = * static_cast<CoreMidiBuffer*>(port_buffer);
1206         if (event_index >= source.size ()) {
1207                 return -1;
1208         }
1209         CoreMidiEvent * const event = source[event_index].get ();
1210
1211         timestamp = event->timestamp ();
1212         size = event->size ();
1213         *buf = event->data ();
1214         return 0;
1215 }
1216
1217 int
1218 CoreAudioBackend::midi_event_put (
1219                 void* port_buffer,
1220                 pframes_t timestamp,
1221                 const uint8_t* buffer, size_t size)
1222 {
1223         assert (buffer && port_buffer);
1224         CoreMidiBuffer& dst = * static_cast<CoreMidiBuffer*>(port_buffer);
1225         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
1226                 fprintf (stderr, "CoreMidiBuffer: it's too late for this event. %d > %d\n",
1227                                 (pframes_t)dst.back ()->timestamp (), timestamp);
1228                 return -1;
1229         }
1230         dst.push_back (boost::shared_ptr<CoreMidiEvent>(new CoreMidiEvent (timestamp, buffer, size)));
1231         return 0;
1232 }
1233
1234 uint32_t
1235 CoreAudioBackend::get_midi_event_count (void* port_buffer)
1236 {
1237         assert (port_buffer);
1238         return static_cast<CoreMidiBuffer*>(port_buffer)->size ();
1239 }
1240
1241 void
1242 CoreAudioBackend::midi_clear (void* port_buffer)
1243 {
1244         assert (port_buffer);
1245         CoreMidiBuffer * buf = static_cast<CoreMidiBuffer*>(port_buffer);
1246         assert (buf);
1247         buf->clear ();
1248 }
1249
1250 /* Monitoring */
1251
1252 bool
1253 CoreAudioBackend::can_monitor_input () const
1254 {
1255         return false;
1256 }
1257
1258 int
1259 CoreAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1260 {
1261         return -1;
1262 }
1263
1264 int
1265 CoreAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1266 {
1267         return -1;
1268 }
1269
1270 bool
1271 CoreAudioBackend::monitoring_input (PortEngine::PortHandle)
1272 {
1273         return false;
1274 }
1275
1276 /* Latency management */
1277
1278 void
1279 CoreAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1280 {
1281         if (!valid_port (port)) {
1282                 PBD::error << _("CoreBackendPort::set_latency_range (): invalid port.") << endmsg;
1283         }
1284         static_cast<CoreBackendPort*>(port)->set_latency_range (latency_range, for_playback);
1285 }
1286
1287 LatencyRange
1288 CoreAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1289 {
1290         LatencyRange r;
1291         if (!valid_port (port)) {
1292                 PBD::error << _("CoreBackendPort::get_latency_range (): invalid port.") << endmsg;
1293                 r.min = 0;
1294                 r.max = 0;
1295         }
1296         CoreBackendPort* p = static_cast<CoreBackendPort*>(port);
1297         assert(p);
1298
1299         r = p->latency_range (for_playback);
1300         if (p->is_physical() && p->is_terminal() && p->type() == DataType::AUDIO) {
1301                 if (p->is_input() && for_playback) {
1302                         r.min += _samples_per_period;
1303                         r.max += _samples_per_period;
1304                 }
1305                 if (p->is_output() && !for_playback) {
1306                         r.min += _samples_per_period;
1307                         r.max += _samples_per_period;
1308                 }
1309         }
1310         return r;
1311 }
1312
1313 /* Discovering physical ports */
1314
1315 bool
1316 CoreAudioBackend::port_is_physical (PortEngine::PortHandle port) const
1317 {
1318         if (!valid_port (port)) {
1319                 PBD::error << _("CoreBackendPort::port_is_physical (): invalid port.") << endmsg;
1320                 return false;
1321         }
1322         return static_cast<CoreBackendPort*>(port)->is_physical ();
1323 }
1324
1325 void
1326 CoreAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1327 {
1328         for (size_t i = 0; i < _ports.size (); ++i) {
1329                 CoreBackendPort* port = _ports[i];
1330                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1331                         port_names.push_back (port->name ());
1332                 }
1333         }
1334 }
1335
1336 void
1337 CoreAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1338 {
1339         for (size_t i = 0; i < _ports.size (); ++i) {
1340                 CoreBackendPort* port = _ports[i];
1341                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1342                         port_names.push_back (port->name ());
1343                 }
1344         }
1345 }
1346
1347 ChanCount
1348 CoreAudioBackend::n_physical_outputs () const
1349 {
1350         int n_midi = 0;
1351         int n_audio = 0;
1352         for (size_t i = 0; i < _ports.size (); ++i) {
1353                 CoreBackendPort* port = _ports[i];
1354                 if (port->is_output () && port->is_physical ()) {
1355                         switch (port->type ()) {
1356                                 case DataType::AUDIO: ++n_audio; break;
1357                                 case DataType::MIDI: ++n_midi; break;
1358                                 default: break;
1359                         }
1360                 }
1361         }
1362         ChanCount cc;
1363         cc.set (DataType::AUDIO, n_audio);
1364         cc.set (DataType::MIDI, n_midi);
1365         return cc;
1366 }
1367
1368 ChanCount
1369 CoreAudioBackend::n_physical_inputs () const
1370 {
1371         int n_midi = 0;
1372         int n_audio = 0;
1373         for (size_t i = 0; i < _ports.size (); ++i) {
1374                 CoreBackendPort* port = _ports[i];
1375                 if (port->is_input () && port->is_physical ()) {
1376                         switch (port->type ()) {
1377                                 case DataType::AUDIO: ++n_audio; break;
1378                                 case DataType::MIDI: ++n_midi; break;
1379                                 default: break;
1380                         }
1381                 }
1382         }
1383         ChanCount cc;
1384         cc.set (DataType::AUDIO, n_audio);
1385         cc.set (DataType::MIDI, n_midi);
1386         return cc;
1387 }
1388
1389 /* Getting access to the data buffer for a port */
1390
1391 void*
1392 CoreAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1393 {
1394         assert (port);
1395         assert (valid_port (port));
1396         return static_cast<CoreBackendPort*>(port)->get_buffer (nframes);
1397 }
1398
1399 void
1400 CoreAudioBackend::pre_process ()
1401 {
1402         bool connections_changed = false;
1403         bool ports_changed = false;
1404         if (!pthread_mutex_trylock (&_port_callback_mutex)) {
1405                 if (_port_change_flag) {
1406                         ports_changed = true;
1407                         _port_change_flag = false;
1408                 }
1409                 if (!_port_connection_queue.empty ()) {
1410                         connections_changed = true;
1411                 }
1412                 while (!_port_connection_queue.empty ()) {
1413                         PortConnectData *c = _port_connection_queue.back ();
1414                         manager.connect_callback (c->a, c->b, c->c);
1415                         _port_connection_queue.pop_back ();
1416                         delete c;
1417                 }
1418                 pthread_mutex_unlock (&_port_callback_mutex);
1419         }
1420         if (ports_changed) {
1421                 manager.registration_callback();
1422         }
1423         if (connections_changed) {
1424                 manager.graph_order_callback();
1425         }
1426         if (connections_changed || ports_changed) {
1427                 engine.latency_callback(false);
1428                 engine.latency_callback(true);
1429         }
1430 }
1431
1432 void *
1433 CoreAudioBackend::freewheel_thread ()
1434 {
1435         _active_fw = true;
1436         bool first_run = false;
1437         /* Freewheeling - use for export.   The first call to
1438          * engine.process_callback() after engine.freewheel_callback will
1439          * if the first export cycle.
1440          * For reliable precise export timing, the calls need to be in sync.
1441          *
1442          * Furthermore we need to make sure the registered process thread
1443          * is correct.
1444          *
1445          * _freewheeling = GUI thread state as set by ::freewheel()
1446          * _freewheel = in sync here (export thread)
1447          */
1448         pthread_mutex_lock (&_freewheel_mutex);
1449         while (_run) {
1450                 // check if we should run,
1451                 if (_freewheeling != _freewheel) {
1452                         if (!_freewheeling) {
1453                                 // prepare leaving freewheeling mode
1454                                 _freewheel = false; // first mark as disabled
1455                                 _reinit_thread_callback = true; // hand over _main_thread
1456                                 _freewheel_ack = false; // prepare next handshake
1457                                 _midiio->set_enabled(true);
1458                         } else {
1459                                 first_run = true;
1460                                 _freewheel = true;
1461                         }
1462                 }
1463
1464                 if (!_freewheel || !_freewheel_ack) {
1465                         // wait for a change, we use a timed wait to
1466                         // terminate early in case some error sets _run = 0
1467                         struct timeval tv;
1468                         struct timespec ts;
1469                         gettimeofday (&tv, NULL);
1470                         ts.tv_sec = tv.tv_sec + 3;
1471                         ts.tv_nsec = 0;
1472                         pthread_cond_timedwait (&_freewheel_signal, &_freewheel_mutex, &ts);
1473                         continue;
1474                 }
1475
1476                 if (first_run) {
1477                         // tell the engine we're ready to GO.
1478                         engine.freewheel_callback (_freewheeling);
1479                         first_run = false;
1480                         _main_thread = pthread_self();
1481                         AudioEngine::thread_init_callback (this);
1482                         _midiio->set_enabled(false);
1483                 }
1484
1485                 // process port updates first in every cycle.
1486                 pre_process();
1487
1488                 // prevent coreaudio device changes
1489                 pthread_mutex_lock (&_process_callback_mutex);
1490
1491                 /* Freewheelin' */
1492                 
1493                 // clear input buffers
1494                 for (std::vector<CoreBackendPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
1495                         memset ((*it)->get_buffer (_samples_per_period), 0, _samples_per_period * sizeof (Sample));
1496                 }
1497                 for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it) {
1498                         static_cast<CoreMidiBuffer*>((*it)->get_buffer(0))->clear ();
1499                 }
1500
1501                 if (engine.process_callback (_samples_per_period)) {
1502                         pthread_mutex_unlock (&_process_callback_mutex);
1503                         break;
1504                 }
1505
1506                 pthread_mutex_unlock (&_process_callback_mutex);
1507                 _dsp_load = 1.0;
1508                 Glib::usleep (100); // don't hog cpu
1509         }
1510
1511         pthread_mutex_unlock (&_freewheel_mutex);
1512
1513         _active_fw = false;
1514
1515         if (_run) {
1516                 // engine.process_callback() returner error
1517                 engine.halted_callback("CoreAudio Freehweeling aborted.");
1518         }
1519         return 0;
1520 }
1521
1522 int
1523 CoreAudioBackend::process_callback ()
1524 {
1525         uint32_t i = 0;
1526         uint64_t clock1, clock2;
1527
1528         _active_ca = true;
1529
1530         if (_run && _freewheel && !_freewheel_ack) {
1531                 // acknowledge freewheeling; hand-over thread ID
1532                 pthread_mutex_lock (&_freewheel_mutex);
1533                 if (_freewheel) _freewheel_ack = true;
1534                 pthread_cond_signal (&_freewheel_signal);
1535                 pthread_mutex_unlock (&_freewheel_mutex);
1536         }
1537
1538         if (!_run || _freewheel || _preinit) {
1539                 // NB if we return 1, the output is
1540                 // zeroed by the coreaudio callback
1541                 return 1;
1542         }
1543
1544         if (pthread_mutex_trylock (&_process_callback_mutex)) {
1545                 // block while devices are added/removed
1546                 return 1;
1547         }
1548
1549         if (_reinit_thread_callback || _main_thread != pthread_self()) {
1550                 _reinit_thread_callback = false;
1551                 _main_thread = pthread_self();
1552                 AudioEngine::thread_init_callback (this);
1553         }
1554
1555         /* port-connection change */
1556         pre_process();
1557
1558         const uint32_t n_samples = _pcmio->n_samples();
1559
1560         // cycle-length in usec
1561         const int64_t nominal_time = 1e6 * n_samples / _samplerate;
1562
1563         clock1 = g_get_monotonic_time();
1564
1565         /* get midi */
1566         i=0;
1567         for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++i) {
1568                 CoreMidiBuffer* mbuf = static_cast<CoreMidiBuffer*>((*it)->get_buffer(0));
1569                 mbuf->clear();
1570                 uint64_t time_ns;
1571                 uint8_t data[64]; // match MaxAlsaEventSize in alsa_rawmidi.cc
1572                 size_t size = sizeof(data);
1573                 while (_midiio->recv_event (i, nominal_time, time_ns, data, size)) {
1574                         pframes_t time = floor((float) time_ns * _samplerate * 1e-9);
1575                         assert (time < n_samples);
1576                         midi_event_put((void*)mbuf, time, data, size);
1577                         size = sizeof(data);
1578                 }
1579         }
1580
1581         /* get audio */
1582         i = 0;
1583         for (std::vector<CoreBackendPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++i) {
1584                 _pcmio->get_capture_channel (i, (float*)((*it)->get_buffer(n_samples)), n_samples);
1585         }
1586
1587         /* clear output buffers */
1588         for (std::vector<CoreBackendPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it) {
1589                 memset ((*it)->get_buffer (n_samples), 0, n_samples * sizeof (Sample));
1590         }
1591
1592         _midiio->start_cycle();
1593
1594         if (engine.process_callback (n_samples)) {
1595                 fprintf(stderr, "ENGINE PROCESS ERROR\n");
1596                 //_pcmio->pcm_stop ();
1597                 _active_ca = false;
1598                 pthread_mutex_unlock (&_process_callback_mutex);
1599                 return -1;
1600         }
1601
1602         /* mixdown midi */
1603         for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it) {
1604                 static_cast<CoreMidiPort*>(*it)->get_buffer(0);
1605         }
1606
1607         /* queue outgoing midi */
1608         i = 0;
1609         for (std::vector<CoreBackendPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it, ++i) {
1610                 const CoreMidiBuffer *src = static_cast<const CoreMidiPort*>(*it)->const_buffer();
1611                 for (CoreMidiBuffer::const_iterator mit = src->begin (); mit != src->end (); ++mit) {
1612                         _midiio->send_event (i, (*mit)->timestamp() / nominal_time, (*mit)->data(), (*mit)->size());
1613                 }
1614         }
1615
1616         /* write back audio */
1617         i = 0;
1618         for (std::vector<CoreBackendPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it, ++i) {
1619                 _pcmio->set_playback_channel (i, (float const*)(*it)->get_buffer (n_samples), n_samples);
1620         }
1621
1622         _processed_samples += n_samples;
1623
1624         /* calc DSP load. */
1625         clock2 = g_get_monotonic_time();
1626         const int64_t elapsed_time = clock2 - clock1;
1627         _dsp_load = elapsed_time / (float) nominal_time;
1628
1629         pthread_mutex_unlock (&_process_callback_mutex);
1630         return 0;
1631 }
1632
1633 void
1634 CoreAudioBackend::error_callback ()
1635 {
1636         _pcmio->set_error_callback (NULL, NULL);
1637         _pcmio->set_sample_rate_callback (NULL, NULL);
1638         _pcmio->set_xrun_callback (NULL, NULL);
1639         _midiio->set_port_changed_callback(NULL, NULL);
1640         engine.halted_callback("CoreAudio Process aborted.");
1641         _active_ca = false;
1642 }
1643
1644 void
1645 CoreAudioBackend::xrun_callback ()
1646 {
1647         engine.Xrun ();
1648 }
1649
1650 void
1651 CoreAudioBackend::buffer_size_callback ()
1652 {
1653         uint32_t bs = _pcmio->samples_per_period();
1654         if (bs == _samples_per_period) {
1655                 return;
1656         }
1657         _samples_per_period = bs;
1658         engine.buffer_size_change (_samples_per_period);
1659 }
1660
1661 void
1662 CoreAudioBackend::sample_rate_callback ()
1663 {
1664         _pcmio->set_error_callback (NULL, NULL);
1665         _pcmio->set_sample_rate_callback (NULL, NULL);
1666         _pcmio->set_xrun_callback (NULL, NULL);
1667         _midiio->set_port_changed_callback(NULL, NULL);
1668         engine.halted_callback("Sample Rate Changed.");
1669         stop();
1670 }
1671
1672 void
1673 CoreAudioBackend::hw_changed_callback ()
1674 {
1675         _reinit_thread_callback = true;
1676         engine.request_device_list_update();
1677 }
1678
1679 /******************************************************************************/
1680
1681 static boost::shared_ptr<CoreAudioBackend> _instance;
1682
1683 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
1684 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
1685 static int deinstantiate ();
1686 static bool already_configured ();
1687 static bool available ();
1688
1689 static ARDOUR::AudioBackendInfo _descriptor = {
1690         "CoreAudio",
1691         instantiate,
1692         deinstantiate,
1693         backend_factory,
1694         already_configured,
1695         available
1696 };
1697
1698 static boost::shared_ptr<AudioBackend>
1699 backend_factory (AudioEngine& e)
1700 {
1701         if (!_instance) {
1702                 _instance.reset (new CoreAudioBackend (e, _descriptor));
1703         }
1704         return _instance;
1705 }
1706
1707 static int
1708 instantiate (const std::string& arg1, const std::string& /* arg2 */)
1709 {
1710         s_instance_name = arg1;
1711         return 0;
1712 }
1713
1714 static int
1715 deinstantiate ()
1716 {
1717         _instance.reset ();
1718         return 0;
1719 }
1720
1721 static bool
1722 already_configured ()
1723 {
1724         return false;
1725 }
1726
1727 static bool
1728 available ()
1729 {
1730         return true;
1731 }
1732
1733 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
1734 {
1735         return &_descriptor;
1736 }
1737
1738
1739 /******************************************************************************/
1740 CoreBackendPort::CoreBackendPort (CoreAudioBackend &b, const std::string& name, PortFlags flags)
1741         : _osx_backend (b)
1742         , _name  (name)
1743         , _flags (flags)
1744 {
1745         _capture_latency_range.min = 0;
1746         _capture_latency_range.max = 0;
1747         _playback_latency_range.min = 0;
1748         _playback_latency_range.max = 0;
1749 }
1750
1751 CoreBackendPort::~CoreBackendPort () {
1752         disconnect_all ();
1753 }
1754
1755
1756 int CoreBackendPort::connect (CoreBackendPort *port)
1757 {
1758         if (!port) {
1759                 PBD::error << _("CoreBackendPort::connect (): invalid (null) port") << endmsg;
1760                 return -1;
1761         }
1762
1763         if (type () != port->type ()) {
1764                 PBD::error << _("CoreBackendPort::connect (): wrong port-type") << endmsg;
1765                 return -1;
1766         }
1767
1768         if (is_output () && port->is_output ()) {
1769                 PBD::error << _("CoreBackendPort::connect (): cannot inter-connect output ports.") << endmsg;
1770                 return -1;
1771         }
1772
1773         if (is_input () && port->is_input ()) {
1774                 PBD::error << _("CoreBackendPort::connect (): cannot inter-connect input ports.") << endmsg;
1775                 return -1;
1776         }
1777
1778         if (this == port) {
1779                 PBD::error << _("CoreBackendPort::connect (): cannot self-connect ports.") << endmsg;
1780                 return -1;
1781         }
1782
1783         if (is_connected (port)) {
1784 #if 0 // don't bother to warn about this for now. just ignore it
1785                 PBD::error << _("CoreBackendPort::connect (): ports are already connected:")
1786                         << " (" << name () << ") -> (" << port->name () << ")"
1787                         << endmsg;
1788 #endif
1789                 return -1;
1790         }
1791
1792         _connect (port, true);
1793         return 0;
1794 }
1795
1796
1797 void CoreBackendPort::_connect (CoreBackendPort *port, bool callback)
1798 {
1799         _connections.push_back (port);
1800         if (callback) {
1801                 port->_connect (this, false);
1802                 _osx_backend.port_connect_callback (name(),  port->name(), true);
1803         }
1804 }
1805
1806 int CoreBackendPort::disconnect (CoreBackendPort *port)
1807 {
1808         if (!port) {
1809                 PBD::error << _("CoreBackendPort::disconnect (): invalid (null) port") << endmsg;
1810                 return -1;
1811         }
1812
1813         if (!is_connected (port)) {
1814                 PBD::error << _("CoreBackendPort::disconnect (): ports are not connected:")
1815                         << " (" << name () << ") -> (" << port->name () << ")"
1816                         << endmsg;
1817                 return -1;
1818         }
1819         _disconnect (port, true);
1820         return 0;
1821 }
1822
1823 void CoreBackendPort::_disconnect (CoreBackendPort *port, bool callback)
1824 {
1825         std::vector<CoreBackendPort*>::iterator it = std::find (_connections.begin (), _connections.end (), port);
1826
1827         assert (it != _connections.end ());
1828
1829         _connections.erase (it);
1830
1831         if (callback) {
1832                 port->_disconnect (this, false);
1833                 _osx_backend.port_connect_callback (name(),  port->name(), false);
1834         }
1835 }
1836
1837
1838 void CoreBackendPort::disconnect_all ()
1839 {
1840         while (!_connections.empty ()) {
1841                 _connections.back ()->_disconnect (this, false);
1842                 _osx_backend.port_connect_callback (name(),  _connections.back ()->name(), false);
1843                 _connections.pop_back ();
1844         }
1845 }
1846
1847 bool
1848 CoreBackendPort::is_connected (const CoreBackendPort *port) const
1849 {
1850         return std::find (_connections.begin (), _connections.end (), port) != _connections.end ();
1851 }
1852
1853 bool CoreBackendPort::is_physically_connected () const
1854 {
1855         for (std::vector<CoreBackendPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
1856                 if ((*it)->is_physical ()) {
1857                         return true;
1858                 }
1859         }
1860         return false;
1861 }
1862
1863 /******************************************************************************/
1864
1865 CoreAudioPort::CoreAudioPort (CoreAudioBackend &b, const std::string& name, PortFlags flags)
1866         : CoreBackendPort (b, name, flags)
1867 {
1868         memset (_buffer, 0, sizeof (_buffer));
1869         mlock(_buffer, sizeof (_buffer));
1870 }
1871
1872 CoreAudioPort::~CoreAudioPort () { }
1873
1874 void* CoreAudioPort::get_buffer (pframes_t n_samples)
1875 {
1876         if (is_input ()) {
1877                 std::vector<CoreBackendPort*>::const_iterator it = get_connections ().begin ();
1878                 if (it == get_connections ().end ()) {
1879                         memset (_buffer, 0, n_samples * sizeof (Sample));
1880                 } else {
1881                         CoreAudioPort const * source = static_cast<const CoreAudioPort*>(*it);
1882                         assert (source && source->is_output ());
1883                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
1884                         while (++it != get_connections ().end ()) {
1885                                 source = static_cast<const CoreAudioPort*>(*it);
1886                                 assert (source && source->is_output ());
1887                                 Sample* dst = buffer ();
1888                                 const Sample* src = source->const_buffer ();
1889                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
1890                                         *dst += *src;
1891                                 }
1892                         }
1893                 }
1894         }
1895         return _buffer;
1896 }
1897
1898
1899 CoreMidiPort::CoreMidiPort (CoreAudioBackend &b, const std::string& name, PortFlags flags)
1900         : CoreBackendPort (b, name, flags)
1901         , _n_periods (1)
1902         , _bufperiod (0)
1903 {
1904         _buffer[0].clear ();
1905         _buffer[1].clear ();
1906 }
1907
1908 CoreMidiPort::~CoreMidiPort () { }
1909
1910 struct MidiEventSorter {
1911         bool operator() (const boost::shared_ptr<CoreMidiEvent>& a, const boost::shared_ptr<CoreMidiEvent>& b) {
1912                 return *a < *b;
1913         }
1914 };
1915
1916 void* CoreMidiPort::get_buffer (pframes_t /* nframes */)
1917 {
1918         if (is_input ()) {
1919                 (_buffer[_bufperiod]).clear ();
1920                 for (std::vector<CoreBackendPort*>::const_iterator i = get_connections ().begin ();
1921                                 i != get_connections ().end ();
1922                                 ++i) {
1923                         const CoreMidiBuffer * src = static_cast<const CoreMidiPort*>(*i)->const_buffer ();
1924                         for (CoreMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
1925                                 (_buffer[_bufperiod]).push_back (boost::shared_ptr<CoreMidiEvent>(new CoreMidiEvent (**it)));
1926                         }
1927                 }
1928                 std::sort ((_buffer[_bufperiod]).begin (), (_buffer[_bufperiod]).end (), MidiEventSorter());
1929         }
1930         return &(_buffer[_bufperiod]);
1931 }
1932
1933 CoreMidiEvent::CoreMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
1934         : _size (size)
1935         , _timestamp (timestamp)
1936         , _data (0)
1937 {
1938         if (size > 0) {
1939                 _data = (uint8_t*) malloc (size);
1940                 memcpy (_data, data, size);
1941         }
1942 }
1943
1944 CoreMidiEvent::CoreMidiEvent (const CoreMidiEvent& other)
1945         : _size (other.size ())
1946         , _timestamp (other.timestamp ())
1947         , _data (0)
1948 {
1949         if (other.size () && other.const_data ()) {
1950                 _data = (uint8_t*) malloc (other.size ());
1951                 memcpy (_data, other.const_data (), other.size ());
1952         }
1953 };
1954
1955 CoreMidiEvent::~CoreMidiEvent () {
1956         free (_data);
1957 };