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