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