ship both blocking and callback PA backends (for debug purposes)
[ardour.git] / libs / backends / portaudio / portaudio_backend.cc
1 /*
2  * Copyright (C) 2015-2015 Robin Gareus <robin@gareus.org>
3  * Copyright (C) 2013 Paul Davis
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19
20 #include <regex.h>
21
22 #ifndef PLATFORM_WINDOWS
23 #include <sys/mman.h>
24 #include <sys/time.h>
25 #endif
26
27 #ifdef COMPILER_MINGW
28 #include <sys/time.h>
29 #endif
30
31 #include <glibmm.h>
32
33 #include "portaudio_backend.h"
34 #include "rt_thread.h"
35
36 #include "pbd/compose.h"
37 #include "pbd/error.h"
38 #include "pbd/file_utils.h"
39 #include "pbd/windows_timer_utils.h"
40 #include "pbd/windows_mmcss.h"
41
42 #include "ardour/filesystem_paths.h"
43 #include "ardour/port_manager.h"
44 #include "i18n.h"
45
46 #include "audio_utils.h"
47
48 #include "debug.h"
49
50 using namespace ARDOUR;
51
52 namespace {
53
54 const char * const winmme_driver_name = X_("WinMME");
55
56 }
57
58 static std::string s_instance_name;
59 size_t PortAudioBackend::_max_buffer_size = 8192;
60 std::vector<std::string> PortAudioBackend::_midi_options;
61 std::vector<AudioBackend::DeviceStatus> PortAudioBackend::_input_audio_device_status;
62 std::vector<AudioBackend::DeviceStatus> PortAudioBackend::_output_audio_device_status;
63
64 PortAudioBackend::PortAudioBackend (AudioEngine& e, AudioBackendInfo& info)
65         : AudioBackend (e, info)
66         , _pcmio (0)
67         , _run (false)
68         , _active (false)
69         , _freewheel (false)
70         , _freewheeling (false)
71         , _freewheel_ack (false)
72         , _reinit_thread_callback (false)
73         , _measure_latency (false)
74         , _cycle_count(0)
75         , _total_deviation_us(0)
76         , _max_deviation_us(0)
77         , _input_audio_device("")
78         , _output_audio_device("")
79         , _midi_driver_option(get_standard_device_name(DeviceNone))
80         , _samplerate (48000)
81         , _samples_per_period (1024)
82         , _n_inputs (0)
83         , _n_outputs (0)
84         , _systemic_audio_input_latency (0)
85         , _systemic_audio_output_latency (0)
86         , _dsp_load (0)
87         , _processed_samples (0)
88         , _port_change_flag (false)
89 {
90         _instance_name = s_instance_name;
91         pthread_mutex_init (&_port_callback_mutex, 0);
92         pthread_mutex_init (&_freewheel_mutex, 0);
93         pthread_cond_init (&_freewheel_signal, 0);
94
95         _pcmio = new PortAudioIO ();
96         _midiio = new WinMMEMidiIO ();
97 }
98
99 PortAudioBackend::~PortAudioBackend ()
100 {
101         delete _pcmio; _pcmio = 0;
102         delete _midiio; _midiio = 0;
103
104         pthread_mutex_destroy (&_port_callback_mutex);
105         pthread_mutex_destroy (&_freewheel_mutex);
106         pthread_cond_destroy (&_freewheel_signal);
107 }
108
109 /* AUDIOBACKEND API */
110
111 std::string
112 PortAudioBackend::name () const
113 {
114         return X_("PortAudio");
115 }
116
117 bool
118 PortAudioBackend::is_realtime () const
119 {
120         return true;
121 }
122
123 bool
124 PortAudioBackend::requires_driver_selection() const
125 {
126         // we could do this but implementation would need changing
127         /*
128         if (enumerate_drivers().size() == 1) {
129                 return false;
130         }
131         */
132         return true;
133 }
134
135 std::vector<std::string>
136 PortAudioBackend::enumerate_drivers () const
137 {
138         DEBUG_AUDIO ("Portaudio: enumerate_drivers\n");
139         std::vector<std::string> currently_available;
140         _pcmio->host_api_list (currently_available);
141         return currently_available;
142 }
143
144 int
145 PortAudioBackend::set_driver (const std::string& name)
146 {
147         DEBUG_AUDIO (string_compose ("Portaudio: set_driver %1 \n", name));
148         if (!_pcmio->set_host_api (name)) {
149                 DEBUG_AUDIO (string_compose ("Portaudio: Unable to set_driver %1 \n", name));
150                 return -1;
151         }
152         _pcmio->update_devices();
153         return 0;
154 }
155
156 bool
157 PortAudioBackend::update_devices ()
158 {
159         return _pcmio->update_devices();
160 }
161
162 std::string
163 PortAudioBackend::driver_name () const
164 {
165         std::string driver_name = _pcmio->get_host_api ();
166         DEBUG_AUDIO (string_compose ("Portaudio: driver_name %1 \n", driver_name));
167         return driver_name;
168 }
169
170 bool
171 PortAudioBackend::use_separate_input_and_output_devices () const
172 {
173         return true;
174 }
175
176 std::vector<AudioBackend::DeviceStatus>
177 PortAudioBackend::enumerate_devices () const
178 {
179         DEBUG_AUDIO ("Portaudio: ERROR enumerate devices should not be called \n");
180         return std::vector<AudioBackend::DeviceStatus>();
181 }
182
183 std::vector<AudioBackend::DeviceStatus>
184 PortAudioBackend::enumerate_input_devices () const
185 {
186         _input_audio_device_status.clear();
187         std::map<int, std::string> input_devices;
188         _pcmio->input_device_list(input_devices);
189
190         for (std::map<int, std::string>::const_iterator i = input_devices.begin (); i != input_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 std::vector<AudioBackend::DeviceStatus>
198 PortAudioBackend::enumerate_output_devices () const
199 {
200         _output_audio_device_status.clear();
201         std::map<int, std::string> output_devices;
202         _pcmio->output_device_list(output_devices);
203
204         for (std::map<int, std::string>::const_iterator i = output_devices.begin (); i != output_devices.end(); ++i) {
205                 if (_output_audio_device == "") _output_audio_device = i->second;
206                 _output_audio_device_status.push_back (DeviceStatus (i->second, true));
207         }
208         return _output_audio_device_status;
209 }
210
211 std::vector<float>
212 PortAudioBackend::available_sample_rates (const std::string&) const
213 {
214         DEBUG_AUDIO ("Portaudio: available_sample_rates\n");
215         std::vector<float> sr;
216         _pcmio->available_sample_rates(name_to_id(_input_audio_device), sr);
217         return sr;
218 }
219
220 std::vector<uint32_t>
221 PortAudioBackend::available_buffer_sizes (const std::string&) const
222 {
223         DEBUG_AUDIO ("Portaudio: available_buffer_sizes\n");
224         std::vector<uint32_t> bs;
225         _pcmio->available_buffer_sizes(name_to_id(_input_audio_device), bs);
226         return bs;
227 }
228
229 uint32_t
230 PortAudioBackend::available_input_channel_count (const std::string&) const
231 {
232         return 128; // TODO query current device
233 }
234
235 uint32_t
236 PortAudioBackend::available_output_channel_count (const std::string&) const
237 {
238         return 128; // TODO query current device
239 }
240
241 bool
242 PortAudioBackend::can_change_sample_rate_when_running () const
243 {
244         return false;
245 }
246
247 bool
248 PortAudioBackend::can_change_buffer_size_when_running () const
249 {
250         return false; // TODO
251 }
252
253 int
254 PortAudioBackend::set_device_name (const std::string& d)
255 {
256         DEBUG_AUDIO ("Portaudio: set_device_name should not be called\n");
257         return 0;
258 }
259
260 int
261 PortAudioBackend::set_input_device_name (const std::string& d)
262 {
263         DEBUG_AUDIO (string_compose ("Portaudio: set_input_device_name %1\n", d));
264         _input_audio_device = d;
265         return 0;
266 }
267
268 int
269 PortAudioBackend::set_output_device_name (const std::string& d)
270 {
271         DEBUG_AUDIO (string_compose ("Portaudio: set_output_device_name %1\n", d));
272         _output_audio_device = d;
273         return 0;
274 }
275
276 int
277 PortAudioBackend::set_sample_rate (float sr)
278 {
279         if (sr <= 0) { return -1; }
280         // TODO check if it's in the list of valid SR
281         _samplerate = sr;
282         engine.sample_rate_change (sr);
283         return 0;
284 }
285
286 int
287 PortAudioBackend::set_buffer_size (uint32_t bs)
288 {
289         if (bs <= 0 || bs >= _max_buffer_size) {
290                 return -1;
291         }
292         _samples_per_period = bs;
293         engine.buffer_size_change (bs);
294         return 0;
295 }
296
297 int
298 PortAudioBackend::set_interleaved (bool yn)
299 {
300         if (!yn) { return 0; }
301         return -1;
302 }
303
304 int
305 PortAudioBackend::set_input_channels (uint32_t cc)
306 {
307         _n_inputs = cc;
308         return 0;
309 }
310
311 int
312 PortAudioBackend::set_output_channels (uint32_t cc)
313 {
314         _n_outputs = cc;
315         return 0;
316 }
317
318 int
319 PortAudioBackend::set_systemic_input_latency (uint32_t sl)
320 {
321         _systemic_audio_input_latency = sl;
322         return 0;
323 }
324
325 int
326 PortAudioBackend::set_systemic_output_latency (uint32_t sl)
327 {
328         _systemic_audio_output_latency = sl;
329         return 0;
330 }
331
332 /* Retrieving parameters */
333 std::string
334 PortAudioBackend::device_name () const
335 {
336         return "Unused";
337 }
338
339 std::string
340 PortAudioBackend::input_device_name () const
341 {
342         return _input_audio_device;
343 }
344
345 std::string
346 PortAudioBackend::output_device_name () const
347 {
348         return _output_audio_device;
349 }
350
351 float
352 PortAudioBackend::sample_rate () const
353 {
354         return _samplerate;
355 }
356
357 uint32_t
358 PortAudioBackend::buffer_size () const
359 {
360         return _samples_per_period;
361 }
362
363 bool
364 PortAudioBackend::interleaved () const
365 {
366         return false;
367 }
368
369 uint32_t
370 PortAudioBackend::input_channels () const
371 {
372         return _n_inputs;
373 }
374
375 uint32_t
376 PortAudioBackend::output_channels () const
377 {
378         return _n_outputs;
379 }
380
381 uint32_t
382 PortAudioBackend::systemic_input_latency () const
383 {
384         return _systemic_audio_input_latency;
385 }
386
387 uint32_t
388 PortAudioBackend::systemic_output_latency () const
389 {
390         return _systemic_audio_output_latency;
391 }
392
393 std::string
394 PortAudioBackend::control_app_name () const
395 {
396         return _pcmio->control_app_name (name_to_id (_input_audio_device));
397 }
398
399 void
400 PortAudioBackend::launch_control_app ()
401 {
402         return _pcmio->launch_control_app (name_to_id(_input_audio_device));
403 }
404
405 /* MIDI */
406
407 std::vector<std::string>
408 PortAudioBackend::enumerate_midi_options () const
409 {
410         if (_midi_options.empty()) {
411                 _midi_options.push_back (winmme_driver_name);
412                 _midi_options.push_back (get_standard_device_name(DeviceNone));
413         }
414         return _midi_options;
415 }
416
417 int
418 PortAudioBackend::set_midi_option (const std::string& opt)
419 {
420         if (opt != get_standard_device_name(DeviceNone) && opt != winmme_driver_name) {
421                 return -1;
422         }
423         DEBUG_MIDI (string_compose ("Setting midi option to %1\n", opt));
424         _midi_driver_option = opt;
425         return 0;
426 }
427
428 std::string
429 PortAudioBackend::midi_option () const
430 {
431         return _midi_driver_option;
432 }
433
434 /* State Control */
435
436 static void * blocking_thread_func (void *arg)
437 {
438         PortAudioBackend *d = static_cast<PortAudioBackend *>(arg);
439         d->blocking_process_thread ();
440         pthread_exit (0);
441         return 0;
442 }
443
444 bool
445 PortAudioBackend::engine_halted ()
446 {
447         return !_active && _run;
448 }
449
450 bool
451 PortAudioBackend::running ()
452 {
453         return _active || _run;
454 }
455
456 int
457 PortAudioBackend::_start (bool for_latency_measurement)
458 {
459         if (engine_halted()) {
460                 stop();
461         }
462
463         if (running()) {
464                 DEBUG_AUDIO("Already started.\n");
465                 return BackendReinitializationError;
466         }
467
468         if (_ports.size()) {
469                 DEBUG_AUDIO(
470                     "Recovering from unclean shutdown, port registry is not empty.\n");
471                 _system_inputs.clear();
472                 _system_outputs.clear();
473                 _system_midi_in.clear();
474                 _system_midi_out.clear();
475                 _ports.clear();
476         }
477
478         /* reset internal state */
479         _dsp_load = 0;
480         _freewheeling = false;
481         _freewheel = false;
482
483         PaErrorCode err = paNoError;
484
485 #ifdef USE_BLOCKING_API
486         err = _pcmio->open_blocking_stream(name_to_id(_input_audio_device),
487                                            name_to_id(_output_audio_device),
488                                            _samplerate,
489                                            _samples_per_period);
490
491 #else
492         err = _pcmio->open_callback_stream(name_to_id(_input_audio_device),
493                                            name_to_id(_output_audio_device),
494                                            _samplerate,
495                                            _samples_per_period,
496                                            portaudio_callback,
497                                            this);
498
499 #endif
500
501         // reintepret Portaudio error messages
502         switch (err) {
503         case paNoError:
504                 break;
505         case paBadIODeviceCombination:
506                 return DeviceConfigurationNotSupportedError;
507         case paInvalidChannelCount:
508                 return ChannelCountNotSupportedError;
509         case paInvalidSampleRate:
510                 return SampleRateNotSupportedError;
511         default:
512                 return AudioDeviceOpenError;
513         }
514
515         if (_n_outputs != _pcmio->n_playback_channels ()) {
516                 _n_outputs = _pcmio->n_playback_channels ();
517                 PBD::info << get_error_string(OutputChannelCountNotSupportedError) << endmsg;
518         }
519
520         if (_n_inputs != _pcmio->n_capture_channels ()) {
521                 _n_inputs = _pcmio->n_capture_channels ();
522                 PBD::info << get_error_string(InputChannelCountNotSupportedError) << endmsg;
523         }
524 #if 0
525         if (_pcmio->samples_per_period() != _samples_per_period) {
526                 _samples_per_period = _pcmio->samples_per_period();
527                 PBD::warning << _("PortAudioBackend: samples per period does not match.") << endmsg;
528         }
529 #endif
530
531         if (_pcmio->sample_rate() != _samplerate) {
532                 _samplerate = _pcmio->sample_rate();
533                 engine.sample_rate_change (_samplerate);
534                 PBD::warning << get_error_string(SampleRateNotSupportedError) << endmsg;
535         }
536
537         _measure_latency = for_latency_measurement;
538
539         _run = true;
540         _port_change_flag = false;
541
542         if (_midi_driver_option == winmme_driver_name) {
543                 _midiio->set_enabled(true);
544                 //_midiio->set_port_changed_callback(midi_port_change, this);
545                 _midiio->start(); // triggers port discovery, callback coremidi_rediscover()
546         }
547
548         _cycle_timer.set_samplerate(_samplerate);
549         _cycle_timer.set_samples_per_cycle(_samples_per_period);
550
551         _dsp_calc.set_max_time_us (_cycle_timer.get_length_us());
552
553         DEBUG_MIDI ("Registering MIDI ports\n");
554
555         if (register_system_midi_ports () != 0) {
556                 DEBUG_PORTS("Failed to register system midi ports.\n")
557                 _run = false;
558                 return PortRegistrationError;
559         }
560
561         DEBUG_AUDIO ("Registering Audio ports\n");
562
563         if (register_system_audio_ports()) {
564                 DEBUG_PORTS("Failed to register system audio ports.\n");
565                 _run = false;
566                 return PortRegistrationError;
567         }
568
569         engine.sample_rate_change (_samplerate);
570         engine.buffer_size_change (_samples_per_period);
571
572         if (engine.reestablish_ports ()) {
573                 DEBUG_PORTS("Could not re-establish ports.\n");
574                 _run = false;
575                 return PortReconnectError;
576         }
577
578         engine.reconnect_ports ();
579         _run = true;
580         _port_change_flag = false;
581
582 #ifdef USE_BLOCKING_API
583         if (!start_blocking_process_thread()) {
584                 return ProcessThreadStartError;
585         }
586 #else
587         if (_pcmio->start_stream() != paNoError) {
588                 DEBUG_AUDIO("Unable to start stream\n");
589                 return AudioDeviceOpenError;
590         }
591
592         if (!start_freewheel_process_thread()) {
593                 DEBUG_AUDIO("Unable to start freewheel thread\n");
594                 stop();
595                 return ProcessThreadStartError;
596         }
597 #endif
598
599         return NoError;
600 }
601
602 int
603 PortAudioBackend::portaudio_callback(const void* input,
604                                      void* output,
605                                      unsigned long frame_count,
606                                      const PaStreamCallbackTimeInfo* time_info,
607                                      PaStreamCallbackFlags status_flags,
608                                      void* user_data)
609 {
610         PortAudioBackend* pa_backend = static_cast<PortAudioBackend*>(user_data);
611
612         if (!pa_backend->process_callback((const float*)input,
613                                           (float*)output,
614                                           frame_count,
615                                           time_info,
616                                           status_flags)) {
617                 return paAbort;
618         }
619
620         return paContinue;
621 }
622
623 bool
624 PortAudioBackend::process_callback(const float* input,
625                                    float* output,
626                                    uint32_t frame_count,
627                                    const PaStreamCallbackTimeInfo* timeInfo,
628                                    PaStreamCallbackFlags statusFlags)
629 {
630         _active = true;
631
632         _dsp_calc.set_start_timestamp_us (PBD::get_microseconds());
633
634         if (_run && _freewheel && !_freewheel_ack) {
635                 // acknowledge freewheeling; hand-over thread ID
636                 pthread_mutex_lock (&_freewheel_mutex);
637                 if (_freewheel) {
638                         DEBUG_AUDIO("Setting _freewheel_ack = true;\n");
639                         _freewheel_ack = true;
640                 }
641                 DEBUG_AUDIO("Signalling freewheel thread\n");
642                 pthread_cond_signal (&_freewheel_signal);
643                 pthread_mutex_unlock (&_freewheel_mutex);
644         }
645
646         if (statusFlags & paInputUnderflow ||
647                 statusFlags & paInputOverflow ||
648                 statusFlags & paOutputUnderflow ||
649                 statusFlags & paOutputOverflow ) {
650                 DEBUG_AUDIO("PortAudio: Xrun\n");
651                 engine.Xrun();
652                 return true;
653         }
654
655         if (!_run || _freewheel) {
656                 memset(output, 0, frame_count * sizeof(float) * _system_outputs.size());
657                 return true;
658         }
659
660         bool in_main_thread = pthread_equal(_main_thread, pthread_self());
661
662         if (_reinit_thread_callback || !in_main_thread) {
663                 _reinit_thread_callback = false;
664                 _main_thread = pthread_self();
665                 AudioEngine::thread_init_callback (this);
666         }
667
668         process_port_connection_changes();
669
670         return blocking_process_main (input, output);
671 }
672
673 bool
674 PortAudioBackend::start_blocking_process_thread ()
675 {
676         if (_realtime_pthread_create (SCHED_FIFO, -20, 100000,
677                                 &_main_blocking_thread, blocking_thread_func, this))
678         {
679                 if (pthread_create (&_main_blocking_thread, NULL, blocking_thread_func, this))
680                 {
681                         DEBUG_AUDIO("Failed to create main audio thread\n");
682                         _run = false;
683                         return false;
684                 } else {
685                         PBD::warning << get_error_string(AquireRealtimePermissionError) << endmsg;
686                 }
687         }
688
689         int timeout = 5000;
690         while (!_active && --timeout > 0) { Glib::usleep (1000); }
691
692         if (timeout == 0 || !_active) {
693                 DEBUG_AUDIO("Failed to start main audio thread\n");
694                 _pcmio->close_stream();
695                 _run = false;
696                 unregister_ports();
697                 _active = false;
698                 return false;
699         }
700         return true;
701 }
702
703 bool
704 PortAudioBackend::stop_blocking_process_thread ()
705 {
706         void *status;
707
708         if (pthread_join (_main_blocking_thread, &status)) {
709                 DEBUG_AUDIO("Failed to stop main audio thread\n");
710                 return false;
711         }
712
713         return true;
714 }
715
716 int
717 PortAudioBackend::stop ()
718 {
719         if (!_run) {
720                 return 0;
721         }
722
723         _midiio->stop();
724
725         _run = false;
726
727 #ifdef USE_BLOCKING_API
728         if (!stop_blocking_process_thread ()) {
729                 return -1;
730         }
731 #else
732         _pcmio->close_stream ();
733         _active = false;
734
735         if (!stop_freewheel_process_thread ()) {
736                 return -1;
737         }
738
739 #endif
740
741         unregister_ports();
742
743         return (_active == false) ? 0 : -1;
744 }
745
746 static void* freewheel_thread(void* arg)
747 {
748         PortAudioBackend* d = static_cast<PortAudioBackend*>(arg);
749         d->freewheel_process_thread ();
750         pthread_exit (0);
751         return 0;
752 }
753
754 bool
755 PortAudioBackend::start_freewheel_process_thread ()
756 {
757         if (pthread_create(&_pthread_freewheel, NULL, freewheel_thread, this)) {
758                 DEBUG_AUDIO("Failed to create main audio thread\n");
759                 return false;
760         }
761
762         int timeout = 5000;
763         while (!_freewheel_thread_active && --timeout > 0) { Glib::usleep (1000); }
764
765         if (timeout == 0 || !_freewheel_thread_active) {
766                 DEBUG_AUDIO("Failed to start freewheel thread\n");
767                 return false;
768         }
769         return true;
770 }
771
772 bool
773 PortAudioBackend::stop_freewheel_process_thread ()
774 {
775         void *status;
776
777         if (!_freewheel_thread_active) {
778                 return true;
779         }
780
781         DEBUG_AUDIO("Signaling freewheel thread to stop\n");
782
783         pthread_mutex_lock (&_freewheel_mutex);
784         pthread_cond_signal (&_freewheel_signal);
785         pthread_mutex_unlock (&_freewheel_mutex);
786
787         if (pthread_join (_pthread_freewheel, &status) != 0) {
788                 DEBUG_AUDIO("Failed to stop freewheel thread\n");
789                 return false;
790         }
791
792         return true;
793 }
794
795 void*
796 PortAudioBackend::freewheel_process_thread()
797 {
798         _freewheel_thread_active = true;
799
800         bool first_run = false;
801
802         pthread_mutex_lock (&_freewheel_mutex);
803
804         while(_run) {
805                 // check if we should run,
806                 if (_freewheeling != _freewheel) {
807                         if (!_freewheeling) {
808                                 DEBUG_AUDIO("Leaving freewheel\n");
809                                 _freewheel = false; // first mark as disabled
810                                 _reinit_thread_callback = true; // hand over _main_thread
811                                 _freewheel_ack = false; // prepare next handshake
812                                 _midiio->set_enabled(true);
813                         } else {
814                                 first_run = true;
815                                 _freewheel = true;
816                         }
817                 }
818
819                 if (!_freewheel || !_freewheel_ack) {
820                         // wait for a change, we use a timed wait to
821                         // terminate early in case some error sets _run = 0
822                         struct timeval tv;
823                         struct timespec ts;
824                         gettimeofday (&tv, NULL);
825                         ts.tv_sec = tv.tv_sec + 3;
826                         ts.tv_nsec = 0;
827                         DEBUG_AUDIO("Waiting for freewheel change\n");
828                         pthread_cond_timedwait (&_freewheel_signal, &_freewheel_mutex, &ts);
829                         continue;
830                 }
831
832                 if (first_run) {
833                         // tell the engine we're ready to GO.
834                         engine.freewheel_callback (_freewheeling);
835                         first_run = false;
836                         _main_thread = pthread_self();
837                         AudioEngine::thread_init_callback (this);
838                         _midiio->set_enabled(false);
839                 }
840
841                 if (!blocking_process_freewheel()) {
842                         break;
843                 }
844
845                 process_port_connection_changes();
846         }
847
848         pthread_mutex_unlock (&_freewheel_mutex);
849
850         _freewheel_thread_active = false;
851
852         if (_run) {
853                 // engine.process_callback() returner error
854                 engine.halted_callback("CoreAudio Freehweeling aborted.");
855         }
856         return 0;
857 }
858
859 int
860 PortAudioBackend::freewheel (bool onoff)
861 {
862         if (onoff == _freewheeling) {
863                 return 0;
864         }
865         _freewheeling = onoff;
866
867         if (0 == pthread_mutex_trylock (&_freewheel_mutex)) {
868                 pthread_cond_signal (&_freewheel_signal);
869                 pthread_mutex_unlock (&_freewheel_mutex);
870         }
871         return 0;
872 }
873
874 float
875 PortAudioBackend::dsp_load () const
876 {
877         return 100.f * _dsp_load;
878 }
879
880 size_t
881 PortAudioBackend::raw_buffer_size (DataType t)
882 {
883         switch (t) {
884         case DataType::AUDIO:
885                 return _samples_per_period * sizeof(Sample);
886         case DataType::MIDI:
887                 return _max_buffer_size; // XXX not really limited
888         }
889         return 0;
890 }
891
892 /* Process time */
893 framepos_t
894 PortAudioBackend::sample_time ()
895 {
896         return _processed_samples;
897 }
898
899 framepos_t
900 PortAudioBackend::sample_time_at_cycle_start ()
901 {
902         return _processed_samples;
903 }
904
905 pframes_t
906 PortAudioBackend::samples_since_cycle_start ()
907 {
908         if (!_active || !_run || _freewheeling || _freewheel) {
909                 return 0;
910         }
911         if (!_cycle_timer.valid()) {
912                 return 0;
913         }
914
915         return _cycle_timer.samples_since_cycle_start (PBD::get_microseconds());
916 }
917
918 int
919 PortAudioBackend::name_to_id(std::string device_name) const {
920         uint32_t device_id = UINT32_MAX;
921         std::map<int, std::string> devices;
922         _pcmio->input_device_list(devices);
923         _pcmio->output_device_list(devices);
924
925         for (std::map<int, std::string>::const_iterator i = devices.begin (); i != devices.end(); ++i) {
926                 if (i->second == device_name) {
927                         device_id = i->first;
928                         break;
929                 }
930         }
931         return device_id;
932 }
933
934 bool
935 PortAudioBackend::set_mmcss_pro_audio (HANDLE* task_handle)
936 {
937         bool mmcss_success = PBD::MMCSS::set_thread_characteristics ("Pro Audio", task_handle);
938
939         if (!mmcss_success) {
940                 PBD::warning << get_error_string(SettingAudioThreadPriorityError) << endmsg;
941                 return false;
942         } else {
943                 DEBUG_THREADS("Thread characteristics set to Pro Audio\n");
944         }
945
946         bool mmcss_priority =
947                 PBD::MMCSS::set_thread_priority(*task_handle, PBD::MMCSS::AVRT_PRIORITY_NORMAL);
948
949         if (!mmcss_priority) {
950                 PBD::warning << get_error_string(SettingAudioThreadPriorityError) << endmsg;
951                 return false;
952         } else {
953                 DEBUG_THREADS("Thread priority set to AVRT_PRIORITY_NORMAL\n");
954         }
955
956         return true;
957 }
958
959 bool
960 PortAudioBackend::reset_mmcss (HANDLE task_handle)
961 {
962         if (!PBD::MMCSS::revert_thread_characteristics(task_handle)) {
963                 DEBUG_THREADS("Unable to reset process thread characteristics\n");
964                 return false;
965         }
966         return true;
967 }
968
969 void *
970 PortAudioBackend::portaudio_process_thread (void *arg)
971 {
972         ThreadData* td = reinterpret_cast<ThreadData*> (arg);
973         boost::function<void ()> f = td->f;
974         delete td;
975
976 #ifdef USE_MMCSS_THREAD_PRIORITIES
977         HANDLE task_handle;
978         bool mmcss_success = set_mmcss_pro_audio (&task_handle);
979 #endif
980
981         DWORD tid = GetCurrentThreadId ();
982         DEBUG_THREADS (string_compose ("Process Thread Child ID: %1\n", tid));
983
984         f ();
985
986 #ifdef USE_MMCSS_THREAD_PRIORITIES
987         if (mmcss_success) {
988                 reset_mmcss (task_handle);
989         }
990 #endif
991
992         return 0;
993 }
994
995 int
996 PortAudioBackend::create_process_thread (boost::function<void()> func)
997 {
998         pthread_t thread_id;
999         pthread_attr_t attr;
1000         size_t stacksize = 100000;
1001
1002         ThreadData* td = new ThreadData (this, func, stacksize);
1003
1004         if (_realtime_pthread_create (SCHED_FIFO, -21, stacksize,
1005                                 &thread_id, portaudio_process_thread, td)) {
1006                 pthread_attr_init (&attr);
1007                 pthread_attr_setstacksize (&attr, stacksize);
1008                 if (pthread_create (&thread_id, &attr, portaudio_process_thread, td)) {
1009                         DEBUG_AUDIO("Cannot create process thread.");
1010                         pthread_attr_destroy (&attr);
1011                         return -1;
1012                 }
1013                 pthread_attr_destroy (&attr);
1014         }
1015
1016         _threads.push_back (thread_id);
1017         return 0;
1018 }
1019
1020 int
1021 PortAudioBackend::join_process_threads ()
1022 {
1023         int rv = 0;
1024
1025         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
1026         {
1027                 void *status;
1028                 if (pthread_join (*i, &status)) {
1029                         DEBUG_AUDIO("Cannot terminate process thread.");
1030                         rv -= 1;
1031                 }
1032         }
1033         _threads.clear ();
1034         return rv;
1035 }
1036
1037 bool
1038 PortAudioBackend::in_process_thread ()
1039 {
1040 #ifdef USE_BLOCKING_API
1041         if (pthread_equal (_main_blocking_thread, pthread_self()) != 0) {
1042                 return true;
1043         }
1044 #else
1045         if (pthread_equal (_main_thread, pthread_self()) != 0) {
1046                 return true;
1047         }
1048 #endif
1049
1050         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
1051         {
1052                 if (pthread_equal (*i, pthread_self ()) != 0) {
1053                         return true;
1054                 }
1055         }
1056         return false;
1057 }
1058
1059 uint32_t
1060 PortAudioBackend::process_thread_count ()
1061 {
1062         return _threads.size ();
1063 }
1064
1065 void
1066 PortAudioBackend::update_latencies ()
1067 {
1068         // trigger latency callback in RT thread (locked graph)
1069         port_connect_add_remove_callback();
1070 }
1071
1072 /* PORTENGINE API */
1073
1074 void*
1075 PortAudioBackend::private_handle () const
1076 {
1077         return NULL;
1078 }
1079
1080 const std::string&
1081 PortAudioBackend::my_name () const
1082 {
1083         return _instance_name;
1084 }
1085
1086 bool
1087 PortAudioBackend::available () const
1088 {
1089         return _run && _active;
1090 }
1091
1092 uint32_t
1093 PortAudioBackend::port_name_size () const
1094 {
1095         return 256;
1096 }
1097
1098 int
1099 PortAudioBackend::set_port_name (PortEngine::PortHandle port, const std::string& name)
1100 {
1101         if (!valid_port (port)) {
1102                 DEBUG_PORTS("set_port_name: Invalid Port(s)\n");
1103                 return -1;
1104         }
1105         return static_cast<PamPort*>(port)->set_name (_instance_name + ":" + name);
1106 }
1107
1108 std::string
1109 PortAudioBackend::get_port_name (PortEngine::PortHandle port) const
1110 {
1111         if (!valid_port (port)) {
1112                 DEBUG_PORTS("get_port_name: Invalid Port(s)\n");
1113                 return std::string ();
1114         }
1115         return static_cast<PamPort*>(port)->name ();
1116 }
1117
1118 int
1119 PortAudioBackend::get_port_property (PortHandle port,
1120                                      const std::string& key,
1121                                      std::string& value,
1122                                      std::string& type) const
1123 {
1124         if (!valid_port (port)) {
1125                 DEBUG_PORTS("get_port_name: Invalid Port(s)\n");
1126                 return -1;
1127         }
1128
1129         if (key == "http://jackaudio.org/metadata/pretty-name") {
1130                 type = "";
1131                 value = static_cast<PamPort*>(port)->pretty_name ();
1132                 if (!value.empty()) {
1133                         return 0;
1134                 }
1135         }
1136         return -1;
1137 }
1138
1139 PortEngine::PortHandle
1140 PortAudioBackend::get_port_by_name (const std::string& name) const
1141 {
1142         PortHandle port = (PortHandle) find_port (name);
1143         return port;
1144 }
1145
1146 int
1147 PortAudioBackend::get_ports (
1148                 const std::string& port_name_pattern,
1149                 DataType type, PortFlags flags,
1150                 std::vector<std::string>& port_names) const
1151 {
1152         int rv = 0;
1153         regex_t port_regex;
1154         bool use_regexp = false;
1155         if (port_name_pattern.size () > 0) {
1156                 if (!regcomp (&port_regex, port_name_pattern.c_str (), REG_EXTENDED|REG_NOSUB)) {
1157                         use_regexp = true;
1158                 }
1159         }
1160         for (size_t i = 0; i < _ports.size (); ++i) {
1161                 PamPort* port = _ports[i];
1162                 if ((port->type () == type) && flags == (port->flags () & flags)) {
1163                         if (!use_regexp || !regexec (&port_regex, port->name ().c_str (), 0, NULL, 0)) {
1164                                 port_names.push_back (port->name ());
1165                                 ++rv;
1166                         }
1167                 }
1168         }
1169         if (use_regexp) {
1170                 regfree (&port_regex);
1171         }
1172         return rv;
1173 }
1174
1175 DataType
1176 PortAudioBackend::port_data_type (PortEngine::PortHandle port) const
1177 {
1178         if (!valid_port (port)) {
1179                 return DataType::NIL;
1180         }
1181         return static_cast<PamPort*>(port)->type ();
1182 }
1183
1184 PortEngine::PortHandle
1185 PortAudioBackend::register_port (
1186                 const std::string& name,
1187                 ARDOUR::DataType type,
1188                 ARDOUR::PortFlags flags)
1189 {
1190         if (name.size () == 0) { return 0; }
1191         if (flags & IsPhysical) { return 0; }
1192         return add_port (_instance_name + ":" + name, type, flags);
1193 }
1194
1195 PortEngine::PortHandle
1196 PortAudioBackend::add_port (
1197                 const std::string& name,
1198                 ARDOUR::DataType type,
1199                 ARDOUR::PortFlags flags)
1200 {
1201         assert(name.size ());
1202         if (find_port (name)) {
1203                 DEBUG_PORTS(
1204                     string_compose("register_port: Port already exists: (%1)\n", name));
1205                 return 0;
1206         }
1207         PamPort* port = NULL;
1208         switch (type) {
1209         case DataType::AUDIO:
1210                 port = new PortAudioPort(*this, name, flags);
1211                 break;
1212         case DataType::MIDI:
1213                 port = new PortMidiPort(*this, name, flags);
1214                 break;
1215         default:
1216                 DEBUG_PORTS("register_port: Invalid Data Type.\n");
1217                 return 0;
1218         }
1219
1220         _ports.push_back (port);
1221
1222         return port;
1223 }
1224
1225 void
1226 PortAudioBackend::unregister_port (PortEngine::PortHandle port_handle)
1227 {
1228         if (!_run) {
1229                 return;
1230         }
1231         PamPort* port = static_cast<PamPort*>(port_handle);
1232         std::vector<PamPort*>::iterator i = std::find (_ports.begin (), _ports.end (), static_cast<PamPort*>(port_handle));
1233         if (i == _ports.end ()) {
1234                 DEBUG_PORTS("unregister_port: Failed to find port\n");
1235                 return;
1236         }
1237         disconnect_all(port_handle);
1238         _ports.erase (i);
1239         delete port;
1240 }
1241
1242 int
1243 PortAudioBackend::register_system_audio_ports()
1244 {
1245         LatencyRange lr;
1246
1247         const uint32_t a_ins = _n_inputs;
1248         const uint32_t a_out = _n_outputs;
1249
1250         uint32_t capture_latency = 0;
1251         uint32_t playback_latency = 0;
1252
1253         // guard against erroneous latency values
1254         if (_pcmio->capture_latency() > _samples_per_period) {
1255                 capture_latency = _pcmio->capture_latency() - _samples_per_period;
1256         }
1257         if (_pcmio->playback_latency() > _samples_per_period) {
1258                 playback_latency = _pcmio->playback_latency() - _samples_per_period;
1259         }
1260
1261         /* audio ports */
1262         lr.min = lr.max = capture_latency + (_measure_latency ? 0 : _systemic_audio_input_latency);
1263         for (uint32_t i = 0; i < a_ins; ++i) {
1264                 char tmp[64];
1265                 snprintf(tmp, sizeof(tmp), "system:capture_%d", i+1);
1266                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
1267                 if (!p) return -1;
1268                 set_latency_range (p, false, lr);
1269                 PortAudioPort* audio_port = static_cast<PortAudioPort*>(p);
1270                 audio_port->set_pretty_name (
1271                     _pcmio->get_input_channel_name (name_to_id (_input_audio_device), i));
1272                 _system_inputs.push_back (audio_port);
1273         }
1274
1275         lr.min = lr.max = playback_latency + (_measure_latency ? 0 : _systemic_audio_output_latency);
1276         for (uint32_t i = 0; i < a_out; ++i) {
1277                 char tmp[64];
1278                 snprintf(tmp, sizeof(tmp), "system:playback_%d", i+1);
1279                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
1280                 if (!p) return -1;
1281                 set_latency_range (p, true, lr);
1282                 PortAudioPort* audio_port = static_cast<PortAudioPort*>(p);
1283                 audio_port->set_pretty_name (
1284                     _pcmio->get_output_channel_name (name_to_id (_output_audio_device), i));
1285                 _system_outputs.push_back(audio_port);
1286         }
1287         return 0;
1288 }
1289
1290 int
1291 PortAudioBackend::register_system_midi_ports()
1292 {
1293         if (_midi_driver_option == get_standard_device_name(DeviceNone)) {
1294                 DEBUG_MIDI("No MIDI backend selected, not system midi ports available\n");
1295                 return 0;
1296         }
1297
1298         LatencyRange lr;
1299         lr.min = lr.max = _samples_per_period;
1300
1301         const std::vector<WinMMEMidiInputDevice*> inputs = _midiio->get_inputs();
1302
1303         for (std::vector<WinMMEMidiInputDevice*>::const_iterator i = inputs.begin ();
1304              i != inputs.end ();
1305              ++i) {
1306                 std::string port_name = "system:midi_capture_" + (*i)->name();
1307                 PortHandle p =
1308                     add_port (port_name,
1309                               DataType::MIDI,
1310                               static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
1311                 if (!p) return -1;
1312                 set_latency_range (p, false, lr);
1313                 PortMidiPort* midi_port = static_cast<PortMidiPort*>(p);
1314                 midi_port->set_pretty_name ((*i)->name());
1315                 _system_midi_in.push_back (midi_port);
1316                 DEBUG_MIDI (string_compose ("Registered MIDI input port: %1\n", port_name));
1317         }
1318
1319         const std::vector<WinMMEMidiOutputDevice*> outputs = _midiio->get_outputs();
1320
1321         for (std::vector<WinMMEMidiOutputDevice*>::const_iterator i = outputs.begin ();
1322              i != outputs.end ();
1323              ++i) {
1324                 std::string port_name = "system:midi_playback_" + (*i)->name();
1325                 PortHandle p =
1326                     add_port (port_name,
1327                               DataType::MIDI,
1328                               static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
1329                 if (!p) return -1;
1330                 set_latency_range (p, false, lr);
1331                 PortMidiPort* midi_port = static_cast<PortMidiPort*>(p);
1332                 midi_port->set_n_periods(2);
1333                 midi_port->set_pretty_name ((*i)->name());
1334                 _system_midi_out.push_back (midi_port);
1335                 DEBUG_MIDI (string_compose ("Registered MIDI output port: %1\n", port_name));
1336         }
1337         return 0;
1338 }
1339
1340 void
1341 PortAudioBackend::unregister_ports (bool system_only)
1342 {
1343         size_t i = 0;
1344         _system_inputs.clear();
1345         _system_outputs.clear();
1346         _system_midi_in.clear();
1347         _system_midi_out.clear();
1348         while (i <  _ports.size ()) {
1349                 PamPort* port = _ports[i];
1350                 if (! system_only || (port->is_physical () && port->is_terminal ())) {
1351                         port->disconnect_all ();
1352                         delete port;
1353                         _ports.erase (_ports.begin() + i);
1354                 } else {
1355                         ++i;
1356                 }
1357         }
1358 }
1359
1360 int
1361 PortAudioBackend::connect (const std::string& src, const std::string& dst)
1362 {
1363         PamPort* src_port = find_port (src);
1364         PamPort* dst_port = find_port (dst);
1365
1366         if (!src_port) {
1367                 DEBUG_PORTS(string_compose("connect: Invalid Source port: (%1)\n", src));
1368                 return -1;
1369         }
1370         if (!dst_port) {
1371                 DEBUG_PORTS(string_compose("connect: Invalid Destination port: (%1)\n", dst));
1372                 return -1;
1373         }
1374         return src_port->connect (dst_port);
1375 }
1376
1377 int
1378 PortAudioBackend::disconnect (const std::string& src, const std::string& dst)
1379 {
1380         PamPort* src_port = find_port (src);
1381         PamPort* dst_port = find_port (dst);
1382
1383         if (!src_port || !dst_port) {
1384                 DEBUG_PORTS("disconnect: Invalid Port(s)\n");
1385                 return -1;
1386         }
1387         return src_port->disconnect (dst_port);
1388 }
1389
1390 int
1391 PortAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
1392 {
1393         PamPort* dst_port = find_port (dst);
1394         if (!valid_port (src)) {
1395                 DEBUG_PORTS("connect: Invalid Source Port Handle\n");
1396                 return -1;
1397         }
1398         if (!dst_port) {
1399                 DEBUG_PORTS(string_compose("connect: Invalid Destination Port (%1)\n", dst));
1400                 return -1;
1401         }
1402         return static_cast<PamPort*>(src)->connect (dst_port);
1403 }
1404
1405 int
1406 PortAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
1407 {
1408         PamPort* dst_port = find_port (dst);
1409         if (!valid_port (src) || !dst_port) {
1410                 DEBUG_PORTS("disconnect: Invalid Port(s)\n");
1411                 return -1;
1412         }
1413         return static_cast<PamPort*>(src)->disconnect (dst_port);
1414 }
1415
1416 int
1417 PortAudioBackend::disconnect_all (PortEngine::PortHandle port)
1418 {
1419         if (!valid_port (port)) {
1420                 DEBUG_PORTS("disconnect_all: Invalid Port\n");
1421                 return -1;
1422         }
1423         static_cast<PamPort*>(port)->disconnect_all ();
1424         return 0;
1425 }
1426
1427 bool
1428 PortAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
1429 {
1430         if (!valid_port (port)) {
1431                 DEBUG_PORTS("disconnect_all: Invalid Port\n");
1432                 return false;
1433         }
1434         return static_cast<PamPort*>(port)->is_connected ();
1435 }
1436
1437 bool
1438 PortAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
1439 {
1440         PamPort* dst_port = find_port (dst);
1441         if (!valid_port (src) || !dst_port) {
1442                 DEBUG_PORTS("connected_to: Invalid Port\n");
1443                 return false;
1444         }
1445         return static_cast<PamPort*>(src)->is_connected (dst_port);
1446 }
1447
1448 bool
1449 PortAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
1450 {
1451         if (!valid_port (port)) {
1452                 DEBUG_PORTS("physically_connected: Invalid Port\n");
1453                 return false;
1454         }
1455         return static_cast<PamPort*>(port)->is_physically_connected ();
1456 }
1457
1458 int
1459 PortAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
1460 {
1461         if (!valid_port (port)) {
1462                 DEBUG_PORTS("get_connections: Invalid Port\n");
1463                 return -1;
1464         }
1465
1466         assert (0 == names.size ());
1467
1468         const std::vector<PamPort*>& connected_ports = static_cast<PamPort*>(port)->get_connections ();
1469
1470         for (std::vector<PamPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
1471                 names.push_back ((*i)->name ());
1472         }
1473
1474         return (int)names.size ();
1475 }
1476
1477 /* MIDI */
1478 int
1479 PortAudioBackend::midi_event_get (
1480                 pframes_t& timestamp,
1481                 size_t& size, uint8_t** buf, void* port_buffer,
1482                 uint32_t event_index)
1483 {
1484         if (!buf || !port_buffer) return -1;
1485         PortMidiBuffer& source = * static_cast<PortMidiBuffer*>(port_buffer);
1486         if (event_index >= source.size ()) {
1487                 return -1;
1488         }
1489         PortMidiEvent * const event = source[event_index].get ();
1490
1491         timestamp = event->timestamp ();
1492         size = event->size ();
1493         *buf = event->data ();
1494         return 0;
1495 }
1496
1497 int
1498 PortAudioBackend::midi_event_put (
1499                 void* port_buffer,
1500                 pframes_t timestamp,
1501                 const uint8_t* buffer, size_t size)
1502 {
1503         if (!buffer || !port_buffer) return -1;
1504         PortMidiBuffer& dst = * static_cast<PortMidiBuffer*>(port_buffer);
1505         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
1506                 // nevermind, ::get_buffer() sorts events
1507                 DEBUG_MIDI (string_compose ("PortMidiBuffer: unordered event: %1 > %2\n",
1508                                             (pframes_t)dst.back ()->timestamp (),
1509                                             timestamp));
1510         }
1511         dst.push_back (boost::shared_ptr<PortMidiEvent>(new PortMidiEvent (timestamp, buffer, size)));
1512         return 0;
1513 }
1514
1515 uint32_t
1516 PortAudioBackend::get_midi_event_count (void* port_buffer)
1517 {
1518         if (!port_buffer) return 0;
1519         return static_cast<PortMidiBuffer*>(port_buffer)->size ();
1520 }
1521
1522 void
1523 PortAudioBackend::midi_clear (void* port_buffer)
1524 {
1525         if (!port_buffer) return;
1526         PortMidiBuffer * buf = static_cast<PortMidiBuffer*>(port_buffer);
1527         assert (buf);
1528         buf->clear ();
1529 }
1530
1531 /* Monitoring */
1532
1533 bool
1534 PortAudioBackend::can_monitor_input () const
1535 {
1536         return false;
1537 }
1538
1539 int
1540 PortAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1541 {
1542         return -1;
1543 }
1544
1545 int
1546 PortAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1547 {
1548         return -1;
1549 }
1550
1551 bool
1552 PortAudioBackend::monitoring_input (PortEngine::PortHandle)
1553 {
1554         return false;
1555 }
1556
1557 /* Latency management */
1558
1559 void
1560 PortAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1561 {
1562         if (!valid_port (port)) {
1563                 DEBUG_PORTS("PamPort::set_latency_range (): invalid port.\n");
1564         }
1565         static_cast<PamPort*>(port)->set_latency_range (latency_range, for_playback);
1566 }
1567
1568 LatencyRange
1569 PortAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1570 {
1571         LatencyRange r;
1572         if (!valid_port (port)) {
1573                 DEBUG_PORTS("PamPort::get_latency_range (): invalid port.\n");
1574                 r.min = 0;
1575                 r.max = 0;
1576                 return r;
1577         }
1578         PamPort* p = static_cast<PamPort*>(port);
1579         assert(p);
1580
1581         r = p->latency_range (for_playback);
1582         // TODO MIDI
1583         if (p->is_physical() && p->is_terminal() && p->type() == DataType::AUDIO) {
1584                 if (p->is_input() && for_playback) {
1585                         r.min += _samples_per_period;
1586                         r.max += _samples_per_period;
1587                 }
1588                 if (p->is_output() && !for_playback) {
1589                         r.min += _samples_per_period;
1590                         r.max += _samples_per_period;
1591                 }
1592         }
1593         return r;
1594 }
1595
1596 /* Discovering physical ports */
1597
1598 bool
1599 PortAudioBackend::port_is_physical (PortEngine::PortHandle port) const
1600 {
1601         if (!valid_port (port)) {
1602                 DEBUG_PORTS("PamPort::port_is_physical (): invalid port.\n");
1603                 return false;
1604         }
1605         return static_cast<PamPort*>(port)->is_physical ();
1606 }
1607
1608 void
1609 PortAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1610 {
1611         for (size_t i = 0; i < _ports.size (); ++i) {
1612                 PamPort* port = _ports[i];
1613                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1614                         port_names.push_back (port->name ());
1615                 }
1616         }
1617 }
1618
1619 void
1620 PortAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1621 {
1622         for (size_t i = 0; i < _ports.size (); ++i) {
1623                 PamPort* port = _ports[i];
1624                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1625                         port_names.push_back (port->name ());
1626                 }
1627         }
1628 }
1629
1630 ChanCount
1631 PortAudioBackend::n_physical_outputs () const
1632 {
1633         int n_midi = 0;
1634         int n_audio = 0;
1635         for (size_t i = 0; i < _ports.size (); ++i) {
1636                 PamPort* port = _ports[i];
1637                 if (port->is_output () && port->is_physical ()) {
1638                         switch (port->type ()) {
1639                         case DataType::AUDIO:
1640                                 ++n_audio;
1641                                 break;
1642                         case DataType::MIDI:
1643                                 ++n_midi;
1644                                 break;
1645                         default:
1646                                 break;
1647                         }
1648                 }
1649         }
1650         ChanCount cc;
1651         cc.set (DataType::AUDIO, n_audio);
1652         cc.set (DataType::MIDI, n_midi);
1653         return cc;
1654 }
1655
1656 ChanCount
1657 PortAudioBackend::n_physical_inputs () const
1658 {
1659         int n_midi = 0;
1660         int n_audio = 0;
1661         for (size_t i = 0; i < _ports.size (); ++i) {
1662                 PamPort* port = _ports[i];
1663                 if (port->is_input () && port->is_physical ()) {
1664                         switch (port->type ()) {
1665                         case DataType::AUDIO:
1666                                 ++n_audio;
1667                                 break;
1668                         case DataType::MIDI:
1669                                 ++n_midi;
1670                                 break;
1671                         default:
1672                                 break;
1673                         }
1674                 }
1675         }
1676         ChanCount cc;
1677         cc.set (DataType::AUDIO, n_audio);
1678         cc.set (DataType::MIDI, n_midi);
1679         return cc;
1680 }
1681
1682 /* Getting access to the data buffer for a port */
1683
1684 void*
1685 PortAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1686 {
1687         if (!port || !valid_port (port)) return NULL;
1688         return static_cast<PamPort*>(port)->get_buffer (nframes);
1689 }
1690
1691
1692 void *
1693 PortAudioBackend::blocking_process_thread ()
1694 {
1695         AudioEngine::thread_init_callback (this);
1696         _active = true;
1697         _processed_samples = 0;
1698
1699         manager.registration_callback();
1700         manager.graph_order_callback();
1701
1702         if (_pcmio->start_stream() != paNoError) {
1703                 _pcmio->close_stream ();
1704                 _active = false;
1705                 engine.halted_callback(get_error_string(AudioDeviceIOError).c_str());
1706         }
1707
1708 #ifdef USE_MMCSS_THREAD_PRIORITIES
1709         HANDLE task_handle;
1710         bool mmcss_success = set_mmcss_pro_audio (&task_handle);
1711 #endif
1712
1713         DWORD tid = GetCurrentThreadId ();
1714         DEBUG_THREADS (string_compose ("Process Thread Master ID: %1\n", tid));
1715
1716         while (_run) {
1717
1718                 if (_freewheeling != _freewheel) {
1719                         _freewheel = _freewheeling;
1720                         engine.freewheel_callback (_freewheel);
1721                 }
1722
1723                 if (!_freewheel) {
1724
1725                         switch (_pcmio->next_cycle (_samples_per_period)) {
1726                         case 0: // OK
1727                                 break;
1728                         case 1:
1729                                 DEBUG_AUDIO("PortAudio: Xrun\n");
1730                                 engine.Xrun();
1731                                 break;
1732                         default:
1733                                 PBD::error << get_error_string(AudioDeviceIOError) << endmsg;
1734                                 break;
1735                         }
1736
1737                         if (!blocking_process_main(_pcmio->get_capture_buffer(),
1738                                                    _pcmio->get_playback_buffer())) {
1739                                 return 0;
1740                         }
1741                 } else {
1742
1743                         if (!blocking_process_freewheel()) {
1744                                 return 0;
1745                         }
1746                 }
1747
1748                 process_port_connection_changes();
1749         }
1750         _pcmio->close_stream();
1751         _active = false;
1752         if (_run) {
1753                 engine.halted_callback(get_error_string(AudioDeviceIOError).c_str());
1754         }
1755
1756 #ifdef USE_MMCSS_THREAD_PRIORITIES
1757         if (mmcss_success) {
1758                 reset_mmcss(task_handle);
1759         }
1760 #endif
1761
1762         return 0;
1763 }
1764
1765 bool
1766 PortAudioBackend::blocking_process_main(const float* interleaved_input_data,
1767                                         float* interleaved_output_data)
1768 {
1769         uint32_t i = 0;
1770         int64_t min_elapsed_us = 1000000;
1771         int64_t max_elapsed_us = 0;
1772
1773         _dsp_calc.set_start_timestamp_us (PBD::get_microseconds());
1774
1775         i = 0;
1776         /* Copy input audio data into input port buffers */
1777         for (std::vector<PamPort*>::const_iterator it = _system_inputs.begin();
1778              it != _system_inputs.end();
1779              ++it, ++i) {
1780                 assert(_system_inputs.size() == _pcmio->n_capture_channels());
1781                 uint32_t channels = _system_inputs.size();
1782                 float* input_port_buffer = (float*)(*it)->get_buffer(_samples_per_period);
1783                 deinterleave_audio_data(
1784                     interleaved_input_data, input_port_buffer, _samples_per_period, i, channels);
1785         }
1786
1787         process_incoming_midi ();
1788
1789         /* clear output buffers */
1790         for (std::vector<PamPort*>::const_iterator it = _system_outputs.begin();
1791              it != _system_outputs.end();
1792              ++it) {
1793                 memset((*it)->get_buffer(_samples_per_period),
1794                        0,
1795                        _samples_per_period * sizeof(Sample));
1796         }
1797
1798         _last_cycle_start = _cycle_timer.get_start();
1799         _cycle_timer.reset_start(PBD::get_microseconds());
1800         _cycle_count++;
1801
1802         uint64_t cycle_diff_us = (_cycle_timer.get_start() - _last_cycle_start);
1803         int64_t deviation_us = (cycle_diff_us - _cycle_timer.get_length_us());
1804         _total_deviation_us += ::llabs(deviation_us);
1805         _max_deviation_us =
1806             std::max(_max_deviation_us, (uint64_t)::llabs(deviation_us));
1807
1808         if ((_cycle_count % 1000) == 0) {
1809                 uint64_t mean_deviation_us = _total_deviation_us / _cycle_count;
1810                 DEBUG_TIMING(string_compose("Mean avg cycle deviation: %1(ms), max %2(ms)\n",
1811                                             mean_deviation_us * 1e-3,
1812                                             _max_deviation_us * 1e-3));
1813         }
1814
1815         if (::llabs(deviation_us) > _cycle_timer.get_length_us()) {
1816                 DEBUG_TIMING(
1817                     string_compose("time between process(ms): %1, Est(ms): %2, Dev(ms): %3\n",
1818                                    cycle_diff_us * 1e-3,
1819                                    _cycle_timer.get_length_us() * 1e-3,
1820                                    deviation_us * 1e-3));
1821         }
1822
1823         /* call engine process callback */
1824         if (engine.process_callback(_samples_per_period)) {
1825                 _pcmio->close_stream();
1826                 _active = false;
1827                 return false;
1828         }
1829
1830         process_outgoing_midi ();
1831
1832         /* write back audio */
1833         i = 0;
1834         for (std::vector<PamPort*>::const_iterator it = _system_outputs.begin();
1835              it != _system_outputs.end();
1836              ++it, ++i) {
1837                 assert(_system_outputs.size() == _pcmio->n_playback_channels());
1838                 const uint32_t channels = _system_outputs.size();
1839                 float* output_port_buffer = (float*)(*it)->get_buffer(_samples_per_period);
1840                 interleave_audio_data(
1841                     output_port_buffer, interleaved_output_data, _samples_per_period, i, channels);
1842         }
1843
1844         _processed_samples += _samples_per_period;
1845
1846         /* calculate DSP load */
1847         _dsp_calc.set_stop_timestamp_us (PBD::get_microseconds());
1848         _dsp_load = _dsp_calc.get_dsp_load();
1849
1850         DEBUG_TIMING(string_compose("DSP Load: %1\n", _dsp_load));
1851
1852         max_elapsed_us = std::max(_dsp_calc.elapsed_time_us(), max_elapsed_us);
1853         min_elapsed_us = std::min(_dsp_calc.elapsed_time_us(), min_elapsed_us);
1854         if ((_cycle_count % 1000) == 0) {
1855                 DEBUG_TIMING(string_compose("Elapsed process time(usecs) max: %1, min: %2\n",
1856                                             max_elapsed_us,
1857                                             min_elapsed_us));
1858         }
1859
1860         return true;
1861 }
1862
1863 bool
1864 PortAudioBackend::blocking_process_freewheel()
1865 {
1866         // zero audio input buffers
1867         for (std::vector<PamPort*>::const_iterator it = _system_inputs.begin();
1868              it != _system_inputs.end();
1869              ++it) {
1870                 memset((*it)->get_buffer(_samples_per_period),
1871                        0,
1872                        _samples_per_period * sizeof(Sample));
1873         }
1874
1875         // TODO clear midi or stop midi recv when entering fwheelin'
1876
1877         if (engine.process_callback(_samples_per_period)) {
1878                 _pcmio->close_stream();
1879                 _active = false;
1880                 return false;
1881         }
1882
1883         // drop all outgoing MIDI messages
1884         for (std::vector<PamPort*>::const_iterator it = _system_midi_out.begin();
1885              it != _system_midi_out.end();
1886              ++it) {
1887                 void* bptr = (*it)->get_buffer(0);
1888                 midi_clear(bptr);
1889         }
1890
1891         _dsp_load = 1.0;
1892         Glib::usleep(100); // don't hog cpu
1893         return true;
1894 }
1895
1896 void
1897 PortAudioBackend::process_incoming_midi ()
1898 {
1899         uint32_t i = 0;
1900         for (std::vector<PamPort*>::const_iterator it = _system_midi_in.begin();
1901              it != _system_midi_in.end();
1902              ++it, ++i) {
1903                 PortMidiBuffer* mbuf = static_cast<PortMidiBuffer*>((*it)->get_buffer(0));
1904                 mbuf->clear();
1905                 uint64_t timestamp;
1906                 pframes_t sample_offset;
1907                 uint8_t data[256];
1908                 size_t size = sizeof(data);
1909                 while (_midiio->dequeue_input_event(i,
1910                                                     _cycle_timer.get_start(),
1911                                                     _cycle_timer.get_next_start(),
1912                                                     timestamp,
1913                                                     data,
1914                                                     size)) {
1915                         sample_offset = _cycle_timer.samples_since_cycle_start(timestamp);
1916                         midi_event_put(mbuf, sample_offset, data, size);
1917                         DEBUG_MIDI(string_compose("Dequeuing incoming MIDI data for device: %1 "
1918                                                   "sample_offset: %2 timestamp: %3, size: %4\n",
1919                                                   _midiio->get_inputs()[i]->name(),
1920                                                   sample_offset,
1921                                                   timestamp,
1922                                                   size));
1923                         size = sizeof(data);
1924                 }
1925         }
1926 }
1927
1928 void
1929 PortAudioBackend::process_outgoing_midi ()
1930 {
1931         /* mixdown midi */
1932         for (std::vector<PamPort*>::iterator it = _system_midi_out.begin();
1933              it != _system_midi_out.end();
1934              ++it) {
1935                 static_cast<PortMidiPort*>(*it)->next_period();
1936         }
1937         /* queue outgoing midi */
1938         uint32_t i = 0;
1939         for (std::vector<PamPort*>::const_iterator it = _system_midi_out.begin();
1940              it != _system_midi_out.end();
1941              ++it, ++i) {
1942                 const PortMidiBuffer* src =
1943                     static_cast<const PortMidiPort*>(*it)->const_buffer();
1944
1945                 for (PortMidiBuffer::const_iterator mit = src->begin(); mit != src->end();
1946                      ++mit) {
1947                         uint64_t timestamp =
1948                             _cycle_timer.timestamp_from_sample_offset((*mit)->timestamp());
1949                         DEBUG_MIDI(string_compose("Queuing outgoing MIDI data for device: "
1950                                                   "%1 sample_offset: %2 timestamp: %3, size: %4\n",
1951                                                   _midiio->get_outputs()[i]->name(),
1952                                                   (*mit)->timestamp(),
1953                                                   timestamp,
1954                                                   (*mit)->size()));
1955                         _midiio->enqueue_output_event(i, timestamp, (*mit)->data(), (*mit)->size());
1956                 }
1957         }
1958 }
1959
1960 void
1961 PortAudioBackend::process_port_connection_changes ()
1962 {
1963         bool connections_changed = false;
1964         bool ports_changed = false;
1965         if (!pthread_mutex_trylock (&_port_callback_mutex)) {
1966                 if (_port_change_flag) {
1967                         ports_changed = true;
1968                         _port_change_flag = false;
1969                 }
1970                 if (!_port_connection_queue.empty ()) {
1971                         connections_changed = true;
1972                 }
1973                 while (!_port_connection_queue.empty ()) {
1974                         PortConnectData *c = _port_connection_queue.back ();
1975                         manager.connect_callback (c->a, c->b, c->c);
1976                         _port_connection_queue.pop_back ();
1977                         delete c;
1978                 }
1979                 pthread_mutex_unlock (&_port_callback_mutex);
1980         }
1981         if (ports_changed) {
1982                 manager.registration_callback();
1983         }
1984         if (connections_changed) {
1985                 manager.graph_order_callback();
1986         }
1987         if (connections_changed || ports_changed) {
1988                 engine.latency_callback(false);
1989                 engine.latency_callback(true);
1990         }
1991 }
1992
1993 /******************************************************************************/
1994
1995 static boost::shared_ptr<PortAudioBackend> _instance;
1996
1997 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
1998 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
1999 static int deinstantiate ();
2000 static bool already_configured ();
2001 static bool available ();
2002
2003 static ARDOUR::AudioBackendInfo _descriptor = {
2004         BACKEND_NAME,
2005         instantiate,
2006         deinstantiate,
2007         backend_factory,
2008         already_configured,
2009         available
2010 };
2011
2012 static boost::shared_ptr<AudioBackend>
2013 backend_factory (AudioEngine& e)
2014 {
2015         if (!_instance) {
2016                 _instance.reset (new PortAudioBackend (e, _descriptor));
2017         }
2018         return _instance;
2019 }
2020
2021 static int
2022 instantiate (const std::string& arg1, const std::string& /* arg2 */)
2023 {
2024         s_instance_name = arg1;
2025         return 0;
2026 }
2027
2028 static int
2029 deinstantiate ()
2030 {
2031         _instance.reset ();
2032         return 0;
2033 }
2034
2035 static bool
2036 already_configured ()
2037 {
2038         return false;
2039 }
2040
2041 static bool
2042 available ()
2043 {
2044         return true;
2045 }
2046
2047 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
2048 {
2049         return &_descriptor;
2050 }
2051
2052
2053 /******************************************************************************/
2054 PamPort::PamPort (PortAudioBackend &b, const std::string& name, PortFlags flags)
2055         : _osx_backend (b)
2056         , _name  (name)
2057         , _flags (flags)
2058 {
2059         _capture_latency_range.min = 0;
2060         _capture_latency_range.max = 0;
2061         _playback_latency_range.min = 0;
2062         _playback_latency_range.max = 0;
2063 }
2064
2065 PamPort::~PamPort () {
2066         disconnect_all ();
2067 }
2068
2069
2070 int PamPort::connect (PamPort *port)
2071 {
2072         if (!port) {
2073                 DEBUG_PORTS("PamPort::connect (): invalid (null) port\n");
2074                 return -1;
2075         }
2076
2077         if (type () != port->type ()) {
2078                 DEBUG_PORTS("PamPort::connect (): wrong port-type\n");
2079                 return -1;
2080         }
2081
2082         if (is_output () && port->is_output ()) {
2083                 DEBUG_PORTS("PamPort::connect (): cannot inter-connect output ports.\n");
2084                 return -1;
2085         }
2086
2087         if (is_input () && port->is_input ()) {
2088                 DEBUG_PORTS("PamPort::connect (): cannot inter-connect input ports.\n");
2089                 return -1;
2090         }
2091
2092         if (this == port) {
2093                 DEBUG_PORTS("PamPort::connect (): cannot self-connect ports.\n");
2094                 return -1;
2095         }
2096
2097         if (is_connected (port)) {
2098 #if 0 // don't bother to warn about this for now. just ignore it
2099                 PBD::error << _("PamPort::connect (): ports are already connected:")
2100                         << " (" << name () << ") -> (" << port->name () << ")"
2101                         << endmsg;
2102 #endif
2103                 return -1;
2104         }
2105
2106         _connect (port, true);
2107         return 0;
2108 }
2109
2110
2111 void PamPort::_connect (PamPort *port, bool callback)
2112 {
2113         _connections.push_back (port);
2114         if (callback) {
2115                 port->_connect (this, false);
2116                 _osx_backend.port_connect_callback (name(),  port->name(), true);
2117         }
2118 }
2119
2120 int PamPort::disconnect (PamPort *port)
2121 {
2122         if (!port) {
2123                 DEBUG_PORTS("PamPort::disconnect (): invalid (null) port\n");
2124                 return -1;
2125         }
2126
2127         if (!is_connected (port)) {
2128                 DEBUG_PORTS(string_compose(
2129                     "PamPort::disconnect (): ports are not connected: (%1) -> (%2)\n",
2130                     name(),
2131                     port->name()));
2132                 return -1;
2133         }
2134         _disconnect (port, true);
2135         return 0;
2136 }
2137
2138 void PamPort::_disconnect (PamPort *port, bool callback)
2139 {
2140         std::vector<PamPort*>::iterator it = std::find (_connections.begin (), _connections.end (), port);
2141
2142         assert (it != _connections.end ());
2143
2144         _connections.erase (it);
2145
2146         if (callback) {
2147                 port->_disconnect (this, false);
2148                 _osx_backend.port_connect_callback (name(),  port->name(), false);
2149         }
2150 }
2151
2152
2153 void PamPort::disconnect_all ()
2154 {
2155         while (!_connections.empty ()) {
2156                 _connections.back ()->_disconnect (this, false);
2157                 _osx_backend.port_connect_callback (name(),  _connections.back ()->name(), false);
2158                 _connections.pop_back ();
2159         }
2160 }
2161
2162 bool
2163 PamPort::is_connected (const PamPort *port) const
2164 {
2165         return std::find (_connections.begin (), _connections.end (), port) != _connections.end ();
2166 }
2167
2168 bool PamPort::is_physically_connected () const
2169 {
2170         for (std::vector<PamPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
2171                 if ((*it)->is_physical ()) {
2172                         return true;
2173                 }
2174         }
2175         return false;
2176 }
2177
2178 /******************************************************************************/
2179
2180 PortAudioPort::PortAudioPort (PortAudioBackend &b, const std::string& name, PortFlags flags)
2181         : PamPort (b, name, flags)
2182 {
2183         memset (_buffer, 0, sizeof (_buffer));
2184 #ifndef PLATFORM_WINDOWS
2185         mlock(_buffer, sizeof (_buffer));
2186 #endif
2187 }
2188
2189 PortAudioPort::~PortAudioPort () { }
2190
2191 void* PortAudioPort::get_buffer (pframes_t n_samples)
2192 {
2193         if (is_input ()) {
2194                 std::vector<PamPort*>::const_iterator it = get_connections ().begin ();
2195                 if (it == get_connections ().end ()) {
2196                         memset (_buffer, 0, n_samples * sizeof (Sample));
2197                 } else {
2198                         PortAudioPort const * source = static_cast<const PortAudioPort*>(*it);
2199                         assert (source && source->is_output ());
2200                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
2201                         while (++it != get_connections ().end ()) {
2202                                 source = static_cast<const PortAudioPort*>(*it);
2203                                 assert (source && source->is_output ());
2204                                 Sample* dst = buffer ();
2205                                 const Sample* src = source->const_buffer ();
2206                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
2207                                         *dst += *src;
2208                                 }
2209                         }
2210                 }
2211         }
2212         return _buffer;
2213 }
2214
2215
2216 PortMidiPort::PortMidiPort (PortAudioBackend &b, const std::string& name, PortFlags flags)
2217         : PamPort (b, name, flags)
2218         , _n_periods (1)
2219         , _bufperiod (0)
2220 {
2221         _buffer[0].clear ();
2222         _buffer[1].clear ();
2223 }
2224
2225 PortMidiPort::~PortMidiPort () { }
2226
2227 struct MidiEventSorter {
2228         bool operator() (const boost::shared_ptr<PortMidiEvent>& a, const boost::shared_ptr<PortMidiEvent>& b) {
2229                 return *a < *b;
2230         }
2231 };
2232
2233 void* PortMidiPort::get_buffer (pframes_t /* nframes */)
2234 {
2235         if (is_input ()) {
2236                 (_buffer[_bufperiod]).clear ();
2237                 for (std::vector<PamPort*>::const_iterator i = get_connections ().begin ();
2238                                 i != get_connections ().end ();
2239                                 ++i) {
2240                         const PortMidiBuffer * src = static_cast<const PortMidiPort*>(*i)->const_buffer ();
2241                         for (PortMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
2242                                 (_buffer[_bufperiod]).push_back (boost::shared_ptr<PortMidiEvent>(new PortMidiEvent (**it)));
2243                         }
2244                 }
2245                 std::sort ((_buffer[_bufperiod]).begin (), (_buffer[_bufperiod]).end (), MidiEventSorter());
2246         }
2247         return &(_buffer[_bufperiod]);
2248 }
2249
2250 PortMidiEvent::PortMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
2251         : _size (size)
2252         , _timestamp (timestamp)
2253         , _data (0)
2254 {
2255         if (size > 0) {
2256                 _data = (uint8_t*) malloc (size);
2257                 memcpy (_data, data, size);
2258         }
2259 }
2260
2261 PortMidiEvent::PortMidiEvent (const PortMidiEvent& other)
2262         : _size (other.size ())
2263         , _timestamp (other.timestamp ())
2264         , _data (0)
2265 {
2266         if (other.size () && other.const_data ()) {
2267                 _data = (uint8_t*) malloc (other.size ());
2268                 memcpy (_data, other.const_data (), other.size ());
2269         }
2270 };
2271
2272 PortMidiEvent::~PortMidiEvent () {
2273         free (_data);
2274 };