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