Use a range of values for ASIO buffer sizes if provided by driver
[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         , m_cycle_count(0)
75         , m_total_deviation_us(0)
76         , m_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 (&m_freewheel_mutex, 0);
93         pthread_cond_init (&m_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 (&m_freewheel_mutex);
106         pthread_cond_destroy (&m_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 * pthread_process (void *arg)
437 {
438         PortAudioBackend *d = static_cast<PortAudioBackend *>(arg);
439         d->main_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         m_cycle_timer.set_samplerate(_samplerate);
549         m_cycle_timer.set_samples_per_cycle(_samples_per_period);
550
551         m_dsp_calc.set_max_time_us (m_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         return paContinue;
620 }
621
622 bool
623 PortAudioBackend::process_callback(const float* input,
624                                    float* output,
625                                    uint32_t frame_count,
626                                    const PaStreamCallbackTimeInfo* timeInfo,
627                                    PaStreamCallbackFlags statusFlags)
628 {
629         _active = true;
630
631         m_dsp_calc.set_start_timestamp_us (PBD::get_microseconds());
632
633         if (_run && _freewheel && !_freewheel_ack) {
634                 // acknowledge freewheeling; hand-over thread ID
635                 pthread_mutex_lock (&m_freewheel_mutex);
636                 if (_freewheel) {
637                         DEBUG_AUDIO("Setting _freewheel_ack = true;\n");
638                         _freewheel_ack = true;
639                 }
640                 DEBUG_AUDIO("Signalling freewheel thread\n");
641                 pthread_cond_signal (&m_freewheel_signal);
642                 pthread_mutex_unlock (&m_freewheel_mutex);
643         }
644
645         if (statusFlags & paInputUnderflow ||
646                 statusFlags & paInputOverflow ||
647                 statusFlags & paOutputUnderflow ||
648                 statusFlags & paOutputOverflow ) {
649                 DEBUG_AUDIO("PortAudio: Xrun\n");
650                 engine.Xrun();
651                 return true;
652         }
653
654         if (!_run || _freewheel) {
655                 memset(output, 0, frame_count * sizeof(float) * _system_outputs.size());
656                 return true;
657         }
658
659         if (_reinit_thread_callback || m_main_thread != pthread_self()) {
660                 _reinit_thread_callback = false;
661                 m_main_thread = pthread_self();
662                 AudioEngine::thread_init_callback (this);
663         }
664
665         return blocking_process_main (input, output);
666 }
667
668 bool
669 PortAudioBackend::start_blocking_process_thread ()
670 {
671         if (_realtime_pthread_create (SCHED_FIFO, -20, 100000,
672                                 &_main_blocking_thread, pthread_process, this))
673         {
674                 if (pthread_create (&_main_blocking_thread, NULL, pthread_process, this))
675                 {
676                         DEBUG_AUDIO("Failed to create main audio thread\n");
677                         _run = false;
678                         return false;
679                 } else {
680                         PBD::warning << get_error_string(AquireRealtimePermissionError) << endmsg;
681                 }
682         }
683
684         int timeout = 5000;
685         while (!_active && --timeout > 0) { Glib::usleep (1000); }
686
687         if (timeout == 0 || !_active) {
688                 DEBUG_AUDIO("Failed to start main audio thread\n");
689                 _pcmio->close_stream();
690                 _run = false;
691                 unregister_ports();
692                 _active = false;
693                 return false;
694         }
695         return true;
696 }
697
698 bool
699 PortAudioBackend::stop_blocking_process_thread ()
700 {
701         void *status;
702
703         if (pthread_join (_main_blocking_thread, &status)) {
704                 DEBUG_AUDIO("Failed to stop main audio thread\n");
705                 return false;
706         }
707
708         return true;
709 }
710
711 int
712 PortAudioBackend::stop ()
713 {
714         if (!_run) {
715                 return 0;
716         }
717
718         _midiio->stop();
719
720         _run = false;
721
722 #ifdef USE_BLOCKING_API
723         if (!stop_blocking_process_thread ()) {
724                 return -1;
725         }
726 #else
727         _pcmio->close_stream ();
728         _active = false;
729
730         if (!stop_freewheel_process_thread ()) {
731                 return -1;
732         }
733
734 #endif
735
736         unregister_ports();
737
738         return (_active == false) ? 0 : -1;
739 }
740
741 static void* freewheel_thread(void* arg)
742 {
743         PortAudioBackend* d = static_cast<PortAudioBackend*>(arg);
744         d->freewheel_process_thread ();
745         pthread_exit (0);
746         return 0;
747 }
748
749 bool
750 PortAudioBackend::start_freewheel_process_thread ()
751 {
752         if (pthread_create(&m_pthread_freewheel, NULL, freewheel_thread, this)) {
753                 DEBUG_AUDIO("Failed to create main audio thread\n");
754                 return false;
755         }
756
757         int timeout = 5000;
758         while (!m_freewheel_thread_active && --timeout > 0) { Glib::usleep (1000); }
759
760         if (timeout == 0 || !m_freewheel_thread_active) {
761                 DEBUG_AUDIO("Failed to start freewheel thread\n");
762                 return false;
763         }
764         return true;
765 }
766
767 bool
768 PortAudioBackend::stop_freewheel_process_thread ()
769 {
770         void *status;
771
772         if (!m_freewheel_thread_active) {
773                 return true;
774         }
775
776         DEBUG_AUDIO("Signaling freewheel thread to stop\n");
777
778         pthread_mutex_lock (&m_freewheel_mutex);
779         pthread_cond_signal (&m_freewheel_signal);
780         pthread_mutex_unlock (&m_freewheel_mutex);
781
782         if (pthread_join (m_pthread_freewheel, &status) != 0) {
783                 DEBUG_AUDIO("Failed to stop freewheel thread\n");
784                 return false;
785         }
786
787         return true;
788 }
789
790 void*
791 PortAudioBackend::freewheel_process_thread()
792 {
793         m_freewheel_thread_active = true;
794
795         bool first_run = false;
796
797         pthread_mutex_lock (&m_freewheel_mutex);
798
799         while(_run) {
800                 // check if we should run,
801                 if (_freewheeling != _freewheel) {
802                         if (!_freewheeling) {
803                                 DEBUG_AUDIO("Leaving freewheel\n");
804                                 _freewheel = false; // first mark as disabled
805                                 _reinit_thread_callback = true; // hand over _main_thread
806                                 _freewheel_ack = false; // prepare next handshake
807                                 _midiio->set_enabled(true);
808                         } else {
809                                 first_run = true;
810                                 _freewheel = true;
811                         }
812                 }
813
814                 if (!_freewheel || !_freewheel_ack) {
815                         // wait for a change, we use a timed wait to
816                         // terminate early in case some error sets _run = 0
817                         struct timeval tv;
818                         struct timespec ts;
819                         gettimeofday (&tv, NULL);
820                         ts.tv_sec = tv.tv_sec + 3;
821                         ts.tv_nsec = 0;
822                         DEBUG_AUDIO("Waiting for freewheel change\n");
823                         pthread_cond_timedwait (&m_freewheel_signal, &m_freewheel_mutex, &ts);
824                         continue;
825                 }
826
827                 if (first_run) {
828                         // tell the engine we're ready to GO.
829                         engine.freewheel_callback (_freewheeling);
830                         first_run = false;
831                         m_main_thread = pthread_self();
832                         AudioEngine::thread_init_callback (this);
833                         _midiio->set_enabled(false);
834                 }
835
836                 if (!blocking_process_freewheel()) {
837                         break;
838                 }
839         }
840
841         pthread_mutex_unlock (&m_freewheel_mutex);
842
843         m_freewheel_thread_active = false;
844
845         if (_run) {
846                 // engine.process_callback() returner error
847                 engine.halted_callback("CoreAudio Freehweeling aborted.");
848         }
849         return 0;
850 }
851
852 int
853 PortAudioBackend::freewheel (bool onoff)
854 {
855         if (onoff == _freewheeling) {
856                 return 0;
857         }
858         _freewheeling = onoff;
859
860         if (0 == pthread_mutex_trylock (&m_freewheel_mutex)) {
861                 pthread_cond_signal (&m_freewheel_signal);
862                 pthread_mutex_unlock (&m_freewheel_mutex);
863         }
864         return 0;
865 }
866
867 float
868 PortAudioBackend::dsp_load () const
869 {
870         return 100.f * _dsp_load;
871 }
872
873 size_t
874 PortAudioBackend::raw_buffer_size (DataType t)
875 {
876         switch (t) {
877         case DataType::AUDIO:
878                 return _samples_per_period * sizeof(Sample);
879         case DataType::MIDI:
880                 return _max_buffer_size; // XXX not really limited
881         }
882         return 0;
883 }
884
885 /* Process time */
886 framepos_t
887 PortAudioBackend::sample_time ()
888 {
889         return _processed_samples;
890 }
891
892 framepos_t
893 PortAudioBackend::sample_time_at_cycle_start ()
894 {
895         return _processed_samples;
896 }
897
898 pframes_t
899 PortAudioBackend::samples_since_cycle_start ()
900 {
901         if (!_active || !_run || _freewheeling || _freewheel) {
902                 return 0;
903         }
904         if (!m_cycle_timer.valid()) {
905                 return 0;
906         }
907
908         return m_cycle_timer.samples_since_cycle_start (PBD::get_microseconds());
909 }
910
911 int
912 PortAudioBackend::name_to_id(std::string device_name) const {
913         uint32_t device_id = UINT32_MAX;
914         std::map<int, std::string> devices;
915         _pcmio->input_device_list(devices);
916         _pcmio->output_device_list(devices);
917
918         for (std::map<int, std::string>::const_iterator i = devices.begin (); i != devices.end(); ++i) {
919                 if (i->second == device_name) {
920                         device_id = i->first;
921                         break;
922                 }
923         }
924         return device_id;
925 }
926
927 bool
928 PortAudioBackend::set_mmcss_pro_audio (HANDLE* task_handle)
929 {
930         bool mmcss_success = PBD::MMCSS::set_thread_characteristics ("Pro Audio", task_handle);
931
932         if (!mmcss_success) {
933                 PBD::warning << get_error_string(SettingAudioThreadPriorityError) << endmsg;
934                 return false;
935         } else {
936                 DEBUG_THREADS("Thread characteristics set to Pro Audio\n");
937         }
938
939         bool mmcss_priority =
940                 PBD::MMCSS::set_thread_priority(*task_handle, PBD::MMCSS::AVRT_PRIORITY_NORMAL);
941
942         if (!mmcss_priority) {
943                 PBD::warning << get_error_string(SettingAudioThreadPriorityError) << endmsg;
944                 return false;
945         } else {
946                 DEBUG_THREADS("Thread priority set to AVRT_PRIORITY_NORMAL\n");
947         }
948
949         return true;
950 }
951
952 bool
953 PortAudioBackend::reset_mmcss (HANDLE task_handle)
954 {
955         if (!PBD::MMCSS::revert_thread_characteristics(task_handle)) {
956                 DEBUG_THREADS("Unable to reset process thread characteristics\n");
957                 return false;
958         }
959         return true;
960 }
961
962 void *
963 PortAudioBackend::portaudio_process_thread (void *arg)
964 {
965         ThreadData* td = reinterpret_cast<ThreadData*> (arg);
966         boost::function<void ()> f = td->f;
967         delete td;
968
969 #ifdef USE_MMCSS_THREAD_PRIORITIES
970         HANDLE task_handle;
971         bool mmcss_success = set_mmcss_pro_audio (&task_handle);
972 #endif
973
974         DWORD tid = GetCurrentThreadId ();
975         DEBUG_THREADS (string_compose ("Process Thread Child ID: %1\n", tid));
976
977         f ();
978
979 #ifdef USE_MMCSS_THREAD_PRIORITIES
980         if (mmcss_success) {
981                 reset_mmcss (task_handle);
982         }
983 #endif
984
985         return 0;
986 }
987
988 int
989 PortAudioBackend::create_process_thread (boost::function<void()> func)
990 {
991         pthread_t thread_id;
992         pthread_attr_t attr;
993         size_t stacksize = 100000;
994
995         ThreadData* td = new ThreadData (this, func, stacksize);
996
997         if (_realtime_pthread_create (SCHED_FIFO, -21, stacksize,
998                                 &thread_id, portaudio_process_thread, td)) {
999                 pthread_attr_init (&attr);
1000                 pthread_attr_setstacksize (&attr, stacksize);
1001                 if (pthread_create (&thread_id, &attr, portaudio_process_thread, td)) {
1002                         DEBUG_AUDIO("Cannot create process thread.");
1003                         pthread_attr_destroy (&attr);
1004                         return -1;
1005                 }
1006                 pthread_attr_destroy (&attr);
1007         }
1008
1009         _threads.push_back (thread_id);
1010         return 0;
1011 }
1012
1013 int
1014 PortAudioBackend::join_process_threads ()
1015 {
1016         int rv = 0;
1017
1018         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
1019         {
1020                 void *status;
1021                 if (pthread_join (*i, &status)) {
1022                         DEBUG_AUDIO("Cannot terminate process thread.");
1023                         rv -= 1;
1024                 }
1025         }
1026         _threads.clear ();
1027         return rv;
1028 }
1029
1030 bool
1031 PortAudioBackend::in_process_thread ()
1032 {
1033 #ifdef USE_BLOCKING_API
1034         if (pthread_equal (_main_blocking_thread, pthread_self()) != 0) {
1035                 return true;
1036         }
1037 #else
1038         if (pthread_equal (m_main_thread, pthread_self()) != 0) {
1039                 return true;
1040         }
1041 #endif
1042
1043         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
1044         {
1045                 if (pthread_equal (*i, pthread_self ()) != 0) {
1046                         return true;
1047                 }
1048         }
1049         return false;
1050 }
1051
1052 uint32_t
1053 PortAudioBackend::process_thread_count ()
1054 {
1055         return _threads.size ();
1056 }
1057
1058 void
1059 PortAudioBackend::update_latencies ()
1060 {
1061         // trigger latency callback in RT thread (locked graph)
1062         port_connect_add_remove_callback();
1063 }
1064
1065 /* PORTENGINE API */
1066
1067 void*
1068 PortAudioBackend::private_handle () const
1069 {
1070         return NULL;
1071 }
1072
1073 const std::string&
1074 PortAudioBackend::my_name () const
1075 {
1076         return _instance_name;
1077 }
1078
1079 bool
1080 PortAudioBackend::available () const
1081 {
1082         return _run && _active;
1083 }
1084
1085 uint32_t
1086 PortAudioBackend::port_name_size () const
1087 {
1088         return 256;
1089 }
1090
1091 int
1092 PortAudioBackend::set_port_name (PortEngine::PortHandle port, const std::string& name)
1093 {
1094         if (!valid_port (port)) {
1095                 DEBUG_PORTS("set_port_name: Invalid Port(s)\n");
1096                 return -1;
1097         }
1098         return static_cast<PamPort*>(port)->set_name (_instance_name + ":" + name);
1099 }
1100
1101 std::string
1102 PortAudioBackend::get_port_name (PortEngine::PortHandle port) const
1103 {
1104         if (!valid_port (port)) {
1105                 DEBUG_PORTS("get_port_name: Invalid Port(s)\n");
1106                 return std::string ();
1107         }
1108         return static_cast<PamPort*>(port)->name ();
1109 }
1110
1111 int
1112 PortAudioBackend::get_port_property (PortHandle port,
1113                                      const std::string& key,
1114                                      std::string& value,
1115                                      std::string& type) const
1116 {
1117         if (!valid_port (port)) {
1118                 DEBUG_PORTS("get_port_name: Invalid Port(s)\n");
1119                 return -1;
1120         }
1121
1122         if (key == "http://jackaudio.org/metadata/pretty-name") {
1123                 type = "";
1124                 value = static_cast<PamPort*>(port)->pretty_name ();
1125                 if (!value.empty()) {
1126                         return 0;
1127                 }
1128         }
1129         return -1;
1130 }
1131
1132 PortEngine::PortHandle
1133 PortAudioBackend::get_port_by_name (const std::string& name) const
1134 {
1135         PortHandle port = (PortHandle) find_port (name);
1136         return port;
1137 }
1138
1139 int
1140 PortAudioBackend::get_ports (
1141                 const std::string& port_name_pattern,
1142                 DataType type, PortFlags flags,
1143                 std::vector<std::string>& port_names) const
1144 {
1145         int rv = 0;
1146         regex_t port_regex;
1147         bool use_regexp = false;
1148         if (port_name_pattern.size () > 0) {
1149                 if (!regcomp (&port_regex, port_name_pattern.c_str (), REG_EXTENDED|REG_NOSUB)) {
1150                         use_regexp = true;
1151                 }
1152         }
1153         for (size_t i = 0; i < _ports.size (); ++i) {
1154                 PamPort* port = _ports[i];
1155                 if ((port->type () == type) && flags == (port->flags () & flags)) {
1156                         if (!use_regexp || !regexec (&port_regex, port->name ().c_str (), 0, NULL, 0)) {
1157                                 port_names.push_back (port->name ());
1158                                 ++rv;
1159                         }
1160                 }
1161         }
1162         if (use_regexp) {
1163                 regfree (&port_regex);
1164         }
1165         return rv;
1166 }
1167
1168 DataType
1169 PortAudioBackend::port_data_type (PortEngine::PortHandle port) const
1170 {
1171         if (!valid_port (port)) {
1172                 return DataType::NIL;
1173         }
1174         return static_cast<PamPort*>(port)->type ();
1175 }
1176
1177 PortEngine::PortHandle
1178 PortAudioBackend::register_port (
1179                 const std::string& name,
1180                 ARDOUR::DataType type,
1181                 ARDOUR::PortFlags flags)
1182 {
1183         if (name.size () == 0) { return 0; }
1184         if (flags & IsPhysical) { return 0; }
1185         return add_port (_instance_name + ":" + name, type, flags);
1186 }
1187
1188 PortEngine::PortHandle
1189 PortAudioBackend::add_port (
1190                 const std::string& name,
1191                 ARDOUR::DataType type,
1192                 ARDOUR::PortFlags flags)
1193 {
1194         assert(name.size ());
1195         if (find_port (name)) {
1196                 DEBUG_PORTS(
1197                     string_compose("register_port: Port already exists: (%1)\n", name));
1198                 return 0;
1199         }
1200         PamPort* port = NULL;
1201         switch (type) {
1202         case DataType::AUDIO:
1203                 port = new PortAudioPort(*this, name, flags);
1204                 break;
1205         case DataType::MIDI:
1206                 port = new PortMidiPort(*this, name, flags);
1207                 break;
1208         default:
1209                 DEBUG_PORTS("register_port: Invalid Data Type.\n");
1210                 return 0;
1211         }
1212
1213         _ports.push_back (port);
1214
1215         return port;
1216 }
1217
1218 void
1219 PortAudioBackend::unregister_port (PortEngine::PortHandle port_handle)
1220 {
1221         if (!_run) {
1222                 return;
1223         }
1224         PamPort* port = static_cast<PamPort*>(port_handle);
1225         std::vector<PamPort*>::iterator i = std::find (_ports.begin (), _ports.end (), static_cast<PamPort*>(port_handle));
1226         if (i == _ports.end ()) {
1227                 DEBUG_PORTS("unregister_port: Failed to find port\n");
1228                 return;
1229         }
1230         disconnect_all(port_handle);
1231         _ports.erase (i);
1232         delete port;
1233 }
1234
1235 int
1236 PortAudioBackend::register_system_audio_ports()
1237 {
1238         LatencyRange lr;
1239
1240         const uint32_t a_ins = _n_inputs;
1241         const uint32_t a_out = _n_outputs;
1242
1243         // XXX PA reported stream latencies don't match measurements
1244         const uint32_t portaudio_reported_input_latency =  _samples_per_period ; //  _pcmio->capture_latency();
1245         const uint32_t portaudio_reported_output_latency = /* _samples_per_period + */ _pcmio->playback_latency();
1246
1247         /* audio ports */
1248         lr.min = lr.max = portaudio_reported_input_latency + (_measure_latency ? 0 : _systemic_audio_input_latency);
1249         for (uint32_t i = 0; i < a_ins; ++i) {
1250                 char tmp[64];
1251                 snprintf(tmp, sizeof(tmp), "system:capture_%d", i+1);
1252                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
1253                 if (!p) return -1;
1254                 set_latency_range (p, false, lr);
1255                 PortAudioPort* audio_port = static_cast<PortAudioPort*>(p);
1256                 audio_port->set_pretty_name (
1257                     _pcmio->get_input_channel_name (name_to_id (_input_audio_device), i));
1258                 _system_inputs.push_back (audio_port);
1259         }
1260
1261         lr.min = lr.max = portaudio_reported_output_latency + (_measure_latency ? 0 : _systemic_audio_output_latency);
1262         for (uint32_t i = 0; i < a_out; ++i) {
1263                 char tmp[64];
1264                 snprintf(tmp, sizeof(tmp), "system:playback_%d", i+1);
1265                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
1266                 if (!p) return -1;
1267                 set_latency_range (p, true, lr);
1268                 PortAudioPort* audio_port = static_cast<PortAudioPort*>(p);
1269                 audio_port->set_pretty_name (
1270                     _pcmio->get_output_channel_name (name_to_id (_output_audio_device), i));
1271                 _system_outputs.push_back(audio_port);
1272         }
1273         return 0;
1274 }
1275
1276 int
1277 PortAudioBackend::register_system_midi_ports()
1278 {
1279         if (_midi_driver_option == get_standard_device_name(DeviceNone)) {
1280                 DEBUG_MIDI("No MIDI backend selected, not system midi ports available\n");
1281                 return 0;
1282         }
1283
1284         LatencyRange lr;
1285         lr.min = lr.max = _samples_per_period;
1286
1287         const std::vector<WinMMEMidiInputDevice*> inputs = _midiio->get_inputs();
1288
1289         for (std::vector<WinMMEMidiInputDevice*>::const_iterator i = inputs.begin ();
1290              i != inputs.end ();
1291              ++i) {
1292                 std::string port_name = "system_midi:" + (*i)->name() + " capture";
1293                 PortHandle p =
1294                     add_port (port_name,
1295                               DataType::MIDI,
1296                               static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
1297                 if (!p) return -1;
1298                 set_latency_range (p, false, lr);
1299                 PortMidiPort* midi_port = static_cast<PortMidiPort*>(p);
1300                 midi_port->set_pretty_name ((*i)->name());
1301                 _system_midi_in.push_back (midi_port);
1302                 DEBUG_MIDI (string_compose ("Registered MIDI input port: %1\n", port_name));
1303         }
1304
1305         const std::vector<WinMMEMidiOutputDevice*> outputs = _midiio->get_outputs();
1306
1307         for (std::vector<WinMMEMidiOutputDevice*>::const_iterator i = outputs.begin ();
1308              i != outputs.end ();
1309              ++i) {
1310                 std::string port_name = "system_midi:" + (*i)->name() + " playback";
1311                 PortHandle p =
1312                     add_port (port_name,
1313                               DataType::MIDI,
1314                               static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
1315                 if (!p) return -1;
1316                 set_latency_range (p, false, lr);
1317                 PortMidiPort* midi_port = static_cast<PortMidiPort*>(p);
1318                 midi_port->set_n_periods(2);
1319                 midi_port->set_pretty_name ((*i)->name());
1320                 _system_midi_out.push_back (midi_port);
1321                 DEBUG_MIDI (string_compose ("Registered MIDI output port: %1\n", port_name));
1322         }
1323         return 0;
1324 }
1325
1326 void
1327 PortAudioBackend::unregister_ports (bool system_only)
1328 {
1329         size_t i = 0;
1330         _system_inputs.clear();
1331         _system_outputs.clear();
1332         _system_midi_in.clear();
1333         _system_midi_out.clear();
1334         while (i <  _ports.size ()) {
1335                 PamPort* port = _ports[i];
1336                 if (! system_only || (port->is_physical () && port->is_terminal ())) {
1337                         port->disconnect_all ();
1338                         delete port;
1339                         _ports.erase (_ports.begin() + i);
1340                 } else {
1341                         ++i;
1342                 }
1343         }
1344 }
1345
1346 int
1347 PortAudioBackend::connect (const std::string& src, const std::string& dst)
1348 {
1349         PamPort* src_port = find_port (src);
1350         PamPort* dst_port = find_port (dst);
1351
1352         if (!src_port) {
1353                 DEBUG_PORTS(string_compose("connect: Invalid Source port: (%1)\n", src));
1354                 return -1;
1355         }
1356         if (!dst_port) {
1357                 DEBUG_PORTS(string_compose("connect: Invalid Destination port: (%1)\n", dst));
1358                 return -1;
1359         }
1360         return src_port->connect (dst_port);
1361 }
1362
1363 int
1364 PortAudioBackend::disconnect (const std::string& src, const std::string& dst)
1365 {
1366         PamPort* src_port = find_port (src);
1367         PamPort* dst_port = find_port (dst);
1368
1369         if (!src_port || !dst_port) {
1370                 DEBUG_PORTS("disconnect: Invalid Port(s)\n");
1371                 return -1;
1372         }
1373         return src_port->disconnect (dst_port);
1374 }
1375
1376 int
1377 PortAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
1378 {
1379         PamPort* dst_port = find_port (dst);
1380         if (!valid_port (src)) {
1381                 DEBUG_PORTS("connect: Invalid Source Port Handle\n");
1382                 return -1;
1383         }
1384         if (!dst_port) {
1385                 DEBUG_PORTS(string_compose("connect: Invalid Destination Port (%1)\n", dst));
1386                 return -1;
1387         }
1388         return static_cast<PamPort*>(src)->connect (dst_port);
1389 }
1390
1391 int
1392 PortAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
1393 {
1394         PamPort* dst_port = find_port (dst);
1395         if (!valid_port (src) || !dst_port) {
1396                 DEBUG_PORTS("disconnect: Invalid Port(s)\n");
1397                 return -1;
1398         }
1399         return static_cast<PamPort*>(src)->disconnect (dst_port);
1400 }
1401
1402 int
1403 PortAudioBackend::disconnect_all (PortEngine::PortHandle port)
1404 {
1405         if (!valid_port (port)) {
1406                 DEBUG_PORTS("disconnect_all: Invalid Port\n");
1407                 return -1;
1408         }
1409         static_cast<PamPort*>(port)->disconnect_all ();
1410         return 0;
1411 }
1412
1413 bool
1414 PortAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
1415 {
1416         if (!valid_port (port)) {
1417                 DEBUG_PORTS("disconnect_all: Invalid Port\n");
1418                 return false;
1419         }
1420         return static_cast<PamPort*>(port)->is_connected ();
1421 }
1422
1423 bool
1424 PortAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
1425 {
1426         PamPort* dst_port = find_port (dst);
1427         if (!valid_port (src) || !dst_port) {
1428                 DEBUG_PORTS("connected_to: Invalid Port\n");
1429                 return false;
1430         }
1431         return static_cast<PamPort*>(src)->is_connected (dst_port);
1432 }
1433
1434 bool
1435 PortAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
1436 {
1437         if (!valid_port (port)) {
1438                 DEBUG_PORTS("physically_connected: Invalid Port\n");
1439                 return false;
1440         }
1441         return static_cast<PamPort*>(port)->is_physically_connected ();
1442 }
1443
1444 int
1445 PortAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
1446 {
1447         if (!valid_port (port)) {
1448                 DEBUG_PORTS("get_connections: Invalid Port\n");
1449                 return -1;
1450         }
1451
1452         assert (0 == names.size ());
1453
1454         const std::vector<PamPort*>& connected_ports = static_cast<PamPort*>(port)->get_connections ();
1455
1456         for (std::vector<PamPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
1457                 names.push_back ((*i)->name ());
1458         }
1459
1460         return (int)names.size ();
1461 }
1462
1463 /* MIDI */
1464 int
1465 PortAudioBackend::midi_event_get (
1466                 pframes_t& timestamp,
1467                 size_t& size, uint8_t** buf, void* port_buffer,
1468                 uint32_t event_index)
1469 {
1470         if (!buf || !port_buffer) return -1;
1471         PortMidiBuffer& source = * static_cast<PortMidiBuffer*>(port_buffer);
1472         if (event_index >= source.size ()) {
1473                 return -1;
1474         }
1475         PortMidiEvent * const event = source[event_index].get ();
1476
1477         timestamp = event->timestamp ();
1478         size = event->size ();
1479         *buf = event->data ();
1480         return 0;
1481 }
1482
1483 int
1484 PortAudioBackend::midi_event_put (
1485                 void* port_buffer,
1486                 pframes_t timestamp,
1487                 const uint8_t* buffer, size_t size)
1488 {
1489         if (!buffer || !port_buffer) return -1;
1490         PortMidiBuffer& dst = * static_cast<PortMidiBuffer*>(port_buffer);
1491         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
1492                 // nevermind, ::get_buffer() sorts events
1493                 DEBUG_MIDI (string_compose ("PortMidiBuffer: unordered event: %1 > %2\n",
1494                                             (pframes_t)dst.back ()->timestamp (),
1495                                             timestamp));
1496         }
1497         dst.push_back (boost::shared_ptr<PortMidiEvent>(new PortMidiEvent (timestamp, buffer, size)));
1498         return 0;
1499 }
1500
1501 uint32_t
1502 PortAudioBackend::get_midi_event_count (void* port_buffer)
1503 {
1504         if (!port_buffer) return 0;
1505         return static_cast<PortMidiBuffer*>(port_buffer)->size ();
1506 }
1507
1508 void
1509 PortAudioBackend::midi_clear (void* port_buffer)
1510 {
1511         if (!port_buffer) return;
1512         PortMidiBuffer * buf = static_cast<PortMidiBuffer*>(port_buffer);
1513         assert (buf);
1514         buf->clear ();
1515 }
1516
1517 /* Monitoring */
1518
1519 bool
1520 PortAudioBackend::can_monitor_input () const
1521 {
1522         return false;
1523 }
1524
1525 int
1526 PortAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1527 {
1528         return -1;
1529 }
1530
1531 int
1532 PortAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1533 {
1534         return -1;
1535 }
1536
1537 bool
1538 PortAudioBackend::monitoring_input (PortEngine::PortHandle)
1539 {
1540         return false;
1541 }
1542
1543 /* Latency management */
1544
1545 void
1546 PortAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1547 {
1548         if (!valid_port (port)) {
1549                 DEBUG_PORTS("PamPort::set_latency_range (): invalid port.\n");
1550         }
1551         static_cast<PamPort*>(port)->set_latency_range (latency_range, for_playback);
1552 }
1553
1554 LatencyRange
1555 PortAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1556 {
1557         LatencyRange r;
1558         if (!valid_port (port)) {
1559                 DEBUG_PORTS("PamPort::get_latency_range (): invalid port.\n");
1560                 r.min = 0;
1561                 r.max = 0;
1562                 return r;
1563         }
1564         PamPort* p = static_cast<PamPort*>(port);
1565         assert(p);
1566
1567         r = p->latency_range (for_playback);
1568         // TODO MIDI
1569         if (p->is_physical() && p->is_terminal() && p->type() == DataType::AUDIO) {
1570                 if (p->is_input() && for_playback) {
1571                         r.min += _samples_per_period;
1572                         r.max += _samples_per_period;
1573                 }
1574                 if (p->is_output() && !for_playback) {
1575                         r.min += _samples_per_period;
1576                         r.max += _samples_per_period;
1577                 }
1578         }
1579         return r;
1580 }
1581
1582 /* Discovering physical ports */
1583
1584 bool
1585 PortAudioBackend::port_is_physical (PortEngine::PortHandle port) const
1586 {
1587         if (!valid_port (port)) {
1588                 DEBUG_PORTS("PamPort::port_is_physical (): invalid port.\n");
1589                 return false;
1590         }
1591         return static_cast<PamPort*>(port)->is_physical ();
1592 }
1593
1594 void
1595 PortAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1596 {
1597         for (size_t i = 0; i < _ports.size (); ++i) {
1598                 PamPort* port = _ports[i];
1599                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1600                         port_names.push_back (port->name ());
1601                 }
1602         }
1603 }
1604
1605 void
1606 PortAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1607 {
1608         for (size_t i = 0; i < _ports.size (); ++i) {
1609                 PamPort* port = _ports[i];
1610                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1611                         port_names.push_back (port->name ());
1612                 }
1613         }
1614 }
1615
1616 ChanCount
1617 PortAudioBackend::n_physical_outputs () const
1618 {
1619         int n_midi = 0;
1620         int n_audio = 0;
1621         for (size_t i = 0; i < _ports.size (); ++i) {
1622                 PamPort* port = _ports[i];
1623                 if (port->is_output () && port->is_physical ()) {
1624                         switch (port->type ()) {
1625                         case DataType::AUDIO:
1626                                 ++n_audio;
1627                                 break;
1628                         case DataType::MIDI:
1629                                 ++n_midi;
1630                                 break;
1631                         default:
1632                                 break;
1633                         }
1634                 }
1635         }
1636         ChanCount cc;
1637         cc.set (DataType::AUDIO, n_audio);
1638         cc.set (DataType::MIDI, n_midi);
1639         return cc;
1640 }
1641
1642 ChanCount
1643 PortAudioBackend::n_physical_inputs () const
1644 {
1645         int n_midi = 0;
1646         int n_audio = 0;
1647         for (size_t i = 0; i < _ports.size (); ++i) {
1648                 PamPort* port = _ports[i];
1649                 if (port->is_input () && port->is_physical ()) {
1650                         switch (port->type ()) {
1651                         case DataType::AUDIO:
1652                                 ++n_audio;
1653                                 break;
1654                         case DataType::MIDI:
1655                                 ++n_midi;
1656                                 break;
1657                         default:
1658                                 break;
1659                         }
1660                 }
1661         }
1662         ChanCount cc;
1663         cc.set (DataType::AUDIO, n_audio);
1664         cc.set (DataType::MIDI, n_midi);
1665         return cc;
1666 }
1667
1668 /* Getting access to the data buffer for a port */
1669
1670 void*
1671 PortAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1672 {
1673         if (!port || !valid_port (port)) return NULL;
1674         return static_cast<PamPort*>(port)->get_buffer (nframes);
1675 }
1676
1677
1678 void *
1679 PortAudioBackend::main_blocking_process_thread ()
1680 {
1681         AudioEngine::thread_init_callback (this);
1682         _active = true;
1683         _processed_samples = 0;
1684
1685         manager.registration_callback();
1686         manager.graph_order_callback();
1687
1688         if (_pcmio->start_stream() != paNoError) {
1689                 _pcmio->close_stream ();
1690                 _active = false;
1691                 engine.halted_callback(get_error_string(AudioDeviceIOError).c_str());
1692         }
1693
1694 #ifdef USE_MMCSS_THREAD_PRIORITIES
1695         HANDLE task_handle;
1696         bool mmcss_success = set_mmcss_pro_audio (&task_handle);
1697 #endif
1698
1699         DWORD tid = GetCurrentThreadId ();
1700         DEBUG_THREADS (string_compose ("Process Thread Master ID: %1\n", tid));
1701
1702         while (_run) {
1703
1704                 if (_freewheeling != _freewheel) {
1705                         _freewheel = _freewheeling;
1706                         engine.freewheel_callback (_freewheel);
1707                 }
1708
1709                 if (!_freewheel) {
1710
1711                         switch (_pcmio->next_cycle (_samples_per_period)) {
1712                         case 0: // OK
1713                                 break;
1714                         case 1:
1715                                 DEBUG_AUDIO("PortAudio: Xrun\n");
1716                                 engine.Xrun();
1717                                 break;
1718                         default:
1719                                 PBD::error << get_error_string(AudioDeviceIOError) << endmsg;
1720                                 break;
1721                         }
1722
1723                         if (!blocking_process_main(_pcmio->get_capture_buffer(),
1724                                                    _pcmio->get_playback_buffer())) {
1725                                 return 0;
1726                         }
1727                 } else {
1728
1729                         if (!blocking_process_freewheel()) {
1730                                 return 0;
1731                         }
1732                 }
1733
1734                 process_port_connection_changes();
1735         }
1736         _pcmio->close_stream();
1737         _active = false;
1738         if (_run) {
1739                 engine.halted_callback(get_error_string(AudioDeviceIOError).c_str());
1740         }
1741
1742 #ifdef USE_MMCSS_THREAD_PRIORITIES
1743         if (mmcss_success) {
1744                 reset_mmcss(task_handle);
1745         }
1746 #endif
1747
1748         return 0;
1749 }
1750
1751 bool
1752 PortAudioBackend::blocking_process_main(const float* interleaved_input_data,
1753                                         float* interleaved_output_data)
1754 {
1755         uint32_t i = 0;
1756         int64_t min_elapsed_us = 1000000;
1757         int64_t max_elapsed_us = 0;
1758
1759         m_dsp_calc.set_start_timestamp_us (PBD::get_microseconds());
1760
1761         i = 0;
1762         /* Copy input audio data into input port buffers */
1763         for (std::vector<PamPort*>::const_iterator it = _system_inputs.begin();
1764              it != _system_inputs.end();
1765              ++it, ++i) {
1766                 assert(_system_inputs.size() == _pcmio->n_capture_channels());
1767                 uint32_t channels = _system_inputs.size();
1768                 float* input_port_buffer = (float*)(*it)->get_buffer(_samples_per_period);
1769                 deinterleave_audio_data(
1770                     interleaved_input_data, input_port_buffer, _samples_per_period, i, channels);
1771         }
1772
1773         process_incoming_midi ();
1774
1775         /* clear output buffers */
1776         for (std::vector<PamPort*>::const_iterator it = _system_outputs.begin();
1777              it != _system_outputs.end();
1778              ++it) {
1779                 memset((*it)->get_buffer(_samples_per_period),
1780                        0,
1781                        _samples_per_period * sizeof(Sample));
1782         }
1783
1784         m_last_cycle_start = m_cycle_timer.get_start();
1785         m_cycle_timer.reset_start(PBD::get_microseconds());
1786         m_cycle_count++;
1787
1788         uint64_t cycle_diff_us = (m_cycle_timer.get_start() - m_last_cycle_start);
1789         int64_t deviation_us = (cycle_diff_us - m_cycle_timer.get_length_us());
1790         m_total_deviation_us += ::llabs(deviation_us);
1791         m_max_deviation_us =
1792             std::max(m_max_deviation_us, (uint64_t)::llabs(deviation_us));
1793
1794         if ((m_cycle_count % 1000) == 0) {
1795                 uint64_t mean_deviation_us = m_total_deviation_us / m_cycle_count;
1796                 DEBUG_TIMING(string_compose("Mean avg cycle deviation: %1(ms), max %2(ms)\n",
1797                                             mean_deviation_us * 1e-3,
1798                                             m_max_deviation_us * 1e-3));
1799         }
1800
1801         if (::llabs(deviation_us) > m_cycle_timer.get_length_us()) {
1802                 DEBUG_TIMING(
1803                     string_compose("time between process(ms): %1, Est(ms): %2, Dev(ms): %3\n",
1804                                    cycle_diff_us * 1e-3,
1805                                    m_cycle_timer.get_length_us() * 1e-3,
1806                                    deviation_us * 1e-3));
1807         }
1808
1809         /* call engine process callback */
1810         if (engine.process_callback(_samples_per_period)) {
1811                 _pcmio->close_stream();
1812                 _active = false;
1813                 return false;
1814         }
1815
1816         process_outgoing_midi ();
1817
1818         /* write back audio */
1819         i = 0;
1820         for (std::vector<PamPort*>::const_iterator it = _system_outputs.begin();
1821              it != _system_outputs.end();
1822              ++it, ++i) {
1823                 assert(_system_outputs.size() == _pcmio->n_playback_channels());
1824                 const uint32_t channels = _system_outputs.size();
1825                 float* output_port_buffer = (float*)(*it)->get_buffer(_samples_per_period);
1826                 interleave_audio_data(
1827                     output_port_buffer, interleaved_output_data, _samples_per_period, i, channels);
1828         }
1829
1830         _processed_samples += _samples_per_period;
1831
1832         /* calculate DSP load */
1833         m_dsp_calc.set_stop_timestamp_us (PBD::get_microseconds());
1834         _dsp_load = m_dsp_calc.get_dsp_load();
1835
1836         DEBUG_TIMING(string_compose("DSP Load: %1\n", _dsp_load));
1837
1838         max_elapsed_us = std::max(m_dsp_calc.elapsed_time_us(), max_elapsed_us);
1839         min_elapsed_us = std::min(m_dsp_calc.elapsed_time_us(), min_elapsed_us);
1840         if ((m_cycle_count % 1000) == 0) {
1841                 DEBUG_TIMING(string_compose("Elapsed process time(usecs) max: %1, min: %2\n",
1842                                             max_elapsed_us,
1843                                             min_elapsed_us));
1844         }
1845
1846         return true;
1847 }
1848
1849 bool
1850 PortAudioBackend::blocking_process_freewheel()
1851 {
1852         // zero audio input buffers
1853         for (std::vector<PamPort*>::const_iterator it = _system_inputs.begin();
1854              it != _system_inputs.end();
1855              ++it) {
1856                 memset((*it)->get_buffer(_samples_per_period),
1857                        0,
1858                        _samples_per_period * sizeof(Sample));
1859         }
1860
1861         // TODO clear midi or stop midi recv when entering fwheelin'
1862
1863         if (engine.process_callback(_samples_per_period)) {
1864                 _pcmio->close_stream();
1865                 _active = false;
1866                 return false;
1867         }
1868
1869         // drop all outgoing MIDI messages
1870         for (std::vector<PamPort*>::const_iterator it = _system_midi_out.begin();
1871              it != _system_midi_out.end();
1872              ++it) {
1873                 void* bptr = (*it)->get_buffer(0);
1874                 midi_clear(bptr);
1875         }
1876
1877         _dsp_load = 1.0;
1878         Glib::usleep(100); // don't hog cpu
1879         return true;
1880 }
1881
1882 void
1883 PortAudioBackend::process_incoming_midi ()
1884 {
1885         uint32_t i = 0;
1886         for (std::vector<PamPort*>::const_iterator it = _system_midi_in.begin();
1887              it != _system_midi_in.end();
1888              ++it, ++i) {
1889                 PortMidiBuffer* mbuf = static_cast<PortMidiBuffer*>((*it)->get_buffer(0));
1890                 mbuf->clear();
1891                 uint64_t timestamp;
1892                 pframes_t sample_offset;
1893                 uint8_t data[256];
1894                 size_t size = sizeof(data);
1895                 while (_midiio->dequeue_input_event(i,
1896                                                     m_cycle_timer.get_start(),
1897                                                     m_cycle_timer.get_next_start(),
1898                                                     timestamp,
1899                                                     data,
1900                                                     size)) {
1901                         sample_offset = m_cycle_timer.samples_since_cycle_start(timestamp);
1902                         midi_event_put(mbuf, sample_offset, data, size);
1903                         DEBUG_MIDI(string_compose("Dequeuing incoming MIDI data for device: %1 "
1904                                                   "sample_offset: %2 timestamp: %3, size: %4\n",
1905                                                   _midiio->get_inputs()[i]->name(),
1906                                                   sample_offset,
1907                                                   timestamp,
1908                                                   size));
1909                         size = sizeof(data);
1910                 }
1911         }
1912 }
1913
1914 void
1915 PortAudioBackend::process_outgoing_midi ()
1916 {
1917         /* mixdown midi */
1918         for (std::vector<PamPort*>::iterator it = _system_midi_out.begin();
1919              it != _system_midi_out.end();
1920              ++it) {
1921                 static_cast<PortMidiPort*>(*it)->next_period();
1922         }
1923         /* queue outgoing midi */
1924         uint32_t i = 0;
1925         for (std::vector<PamPort*>::const_iterator it = _system_midi_out.begin();
1926              it != _system_midi_out.end();
1927              ++it, ++i) {
1928                 const PortMidiBuffer* src =
1929                     static_cast<const PortMidiPort*>(*it)->const_buffer();
1930
1931                 for (PortMidiBuffer::const_iterator mit = src->begin(); mit != src->end();
1932                      ++mit) {
1933                         uint64_t timestamp =
1934                             m_cycle_timer.timestamp_from_sample_offset((*mit)->timestamp());
1935                         DEBUG_MIDI(string_compose("Queuing outgoing MIDI data for device: "
1936                                                   "%1 sample_offset: %2 timestamp: %3, size: %4\n",
1937                                                   _midiio->get_outputs()[i]->name(),
1938                                                   (*mit)->timestamp(),
1939                                                   timestamp,
1940                                                   (*mit)->size()));
1941                         _midiio->enqueue_output_event(i, timestamp, (*mit)->data(), (*mit)->size());
1942                 }
1943         }
1944 }
1945
1946 void
1947 PortAudioBackend::process_port_connection_changes ()
1948 {
1949         bool connections_changed = false;
1950         bool ports_changed = false;
1951         if (!pthread_mutex_trylock (&_port_callback_mutex)) {
1952                 if (_port_change_flag) {
1953                         ports_changed = true;
1954                         _port_change_flag = false;
1955                 }
1956                 if (!_port_connection_queue.empty ()) {
1957                         connections_changed = true;
1958                 }
1959                 while (!_port_connection_queue.empty ()) {
1960                         PortConnectData *c = _port_connection_queue.back ();
1961                         manager.connect_callback (c->a, c->b, c->c);
1962                         _port_connection_queue.pop_back ();
1963                         delete c;
1964                 }
1965                 pthread_mutex_unlock (&_port_callback_mutex);
1966         }
1967         if (ports_changed) {
1968                 manager.registration_callback();
1969         }
1970         if (connections_changed) {
1971                 manager.graph_order_callback();
1972         }
1973         if (connections_changed || ports_changed) {
1974                 engine.latency_callback(false);
1975                 engine.latency_callback(true);
1976         }
1977 }
1978
1979 /******************************************************************************/
1980
1981 static boost::shared_ptr<PortAudioBackend> _instance;
1982
1983 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
1984 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
1985 static int deinstantiate ();
1986 static bool already_configured ();
1987 static bool available ();
1988
1989 static ARDOUR::AudioBackendInfo _descriptor = {
1990         "PortAudio",
1991         instantiate,
1992         deinstantiate,
1993         backend_factory,
1994         already_configured,
1995         available
1996 };
1997
1998 static boost::shared_ptr<AudioBackend>
1999 backend_factory (AudioEngine& e)
2000 {
2001         if (!_instance) {
2002                 _instance.reset (new PortAudioBackend (e, _descriptor));
2003         }
2004         return _instance;
2005 }
2006
2007 static int
2008 instantiate (const std::string& arg1, const std::string& /* arg2 */)
2009 {
2010         s_instance_name = arg1;
2011         return 0;
2012 }
2013
2014 static int
2015 deinstantiate ()
2016 {
2017         _instance.reset ();
2018         return 0;
2019 }
2020
2021 static bool
2022 already_configured ()
2023 {
2024         return false;
2025 }
2026
2027 static bool
2028 available ()
2029 {
2030         return true;
2031 }
2032
2033 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
2034 {
2035         return &_descriptor;
2036 }
2037
2038
2039 /******************************************************************************/
2040 PamPort::PamPort (PortAudioBackend &b, const std::string& name, PortFlags flags)
2041         : _osx_backend (b)
2042         , _name  (name)
2043         , _flags (flags)
2044 {
2045         _capture_latency_range.min = 0;
2046         _capture_latency_range.max = 0;
2047         _playback_latency_range.min = 0;
2048         _playback_latency_range.max = 0;
2049 }
2050
2051 PamPort::~PamPort () {
2052         disconnect_all ();
2053 }
2054
2055
2056 int PamPort::connect (PamPort *port)
2057 {
2058         if (!port) {
2059                 DEBUG_PORTS("PamPort::connect (): invalid (null) port\n");
2060                 return -1;
2061         }
2062
2063         if (type () != port->type ()) {
2064                 DEBUG_PORTS("PamPort::connect (): wrong port-type\n");
2065                 return -1;
2066         }
2067
2068         if (is_output () && port->is_output ()) {
2069                 DEBUG_PORTS("PamPort::connect (): cannot inter-connect output ports.\n");
2070                 return -1;
2071         }
2072
2073         if (is_input () && port->is_input ()) {
2074                 DEBUG_PORTS("PamPort::connect (): cannot inter-connect input ports.\n");
2075                 return -1;
2076         }
2077
2078         if (this == port) {
2079                 DEBUG_PORTS("PamPort::connect (): cannot self-connect ports.\n");
2080                 return -1;
2081         }
2082
2083         if (is_connected (port)) {
2084 #if 0 // don't bother to warn about this for now. just ignore it
2085                 PBD::error << _("PamPort::connect (): ports are already connected:")
2086                         << " (" << name () << ") -> (" << port->name () << ")"
2087                         << endmsg;
2088 #endif
2089                 return -1;
2090         }
2091
2092         _connect (port, true);
2093         return 0;
2094 }
2095
2096
2097 void PamPort::_connect (PamPort *port, bool callback)
2098 {
2099         _connections.push_back (port);
2100         if (callback) {
2101                 port->_connect (this, false);
2102                 _osx_backend.port_connect_callback (name(),  port->name(), true);
2103         }
2104 }
2105
2106 int PamPort::disconnect (PamPort *port)
2107 {
2108         if (!port) {
2109                 DEBUG_PORTS("PamPort::disconnect (): invalid (null) port\n");
2110                 return -1;
2111         }
2112
2113         if (!is_connected (port)) {
2114                 DEBUG_PORTS(string_compose(
2115                     "PamPort::disconnect (): ports are not connected: (%1) -> (%2)\n",
2116                     name(),
2117                     port->name()));
2118                 return -1;
2119         }
2120         _disconnect (port, true);
2121         return 0;
2122 }
2123
2124 void PamPort::_disconnect (PamPort *port, bool callback)
2125 {
2126         std::vector<PamPort*>::iterator it = std::find (_connections.begin (), _connections.end (), port);
2127
2128         assert (it != _connections.end ());
2129
2130         _connections.erase (it);
2131
2132         if (callback) {
2133                 port->_disconnect (this, false);
2134                 _osx_backend.port_connect_callback (name(),  port->name(), false);
2135         }
2136 }
2137
2138
2139 void PamPort::disconnect_all ()
2140 {
2141         while (!_connections.empty ()) {
2142                 _connections.back ()->_disconnect (this, false);
2143                 _osx_backend.port_connect_callback (name(),  _connections.back ()->name(), false);
2144                 _connections.pop_back ();
2145         }
2146 }
2147
2148 bool
2149 PamPort::is_connected (const PamPort *port) const
2150 {
2151         return std::find (_connections.begin (), _connections.end (), port) != _connections.end ();
2152 }
2153
2154 bool PamPort::is_physically_connected () const
2155 {
2156         for (std::vector<PamPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
2157                 if ((*it)->is_physical ()) {
2158                         return true;
2159                 }
2160         }
2161         return false;
2162 }
2163
2164 /******************************************************************************/
2165
2166 PortAudioPort::PortAudioPort (PortAudioBackend &b, const std::string& name, PortFlags flags)
2167         : PamPort (b, name, flags)
2168 {
2169         memset (_buffer, 0, sizeof (_buffer));
2170 #ifndef PLATFORM_WINDOWS
2171         mlock(_buffer, sizeof (_buffer));
2172 #endif
2173 }
2174
2175 PortAudioPort::~PortAudioPort () { }
2176
2177 void* PortAudioPort::get_buffer (pframes_t n_samples)
2178 {
2179         if (is_input ()) {
2180                 std::vector<PamPort*>::const_iterator it = get_connections ().begin ();
2181                 if (it == get_connections ().end ()) {
2182                         memset (_buffer, 0, n_samples * sizeof (Sample));
2183                 } else {
2184                         PortAudioPort const * source = static_cast<const PortAudioPort*>(*it);
2185                         assert (source && source->is_output ());
2186                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
2187                         while (++it != get_connections ().end ()) {
2188                                 source = static_cast<const PortAudioPort*>(*it);
2189                                 assert (source && source->is_output ());
2190                                 Sample* dst = buffer ();
2191                                 const Sample* src = source->const_buffer ();
2192                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
2193                                         *dst += *src;
2194                                 }
2195                         }
2196                 }
2197         }
2198         return _buffer;
2199 }
2200
2201
2202 PortMidiPort::PortMidiPort (PortAudioBackend &b, const std::string& name, PortFlags flags)
2203         : PamPort (b, name, flags)
2204         , _n_periods (1)
2205         , _bufperiod (0)
2206 {
2207         _buffer[0].clear ();
2208         _buffer[1].clear ();
2209 }
2210
2211 PortMidiPort::~PortMidiPort () { }
2212
2213 struct MidiEventSorter {
2214         bool operator() (const boost::shared_ptr<PortMidiEvent>& a, const boost::shared_ptr<PortMidiEvent>& b) {
2215                 return *a < *b;
2216         }
2217 };
2218
2219 void* PortMidiPort::get_buffer (pframes_t /* nframes */)
2220 {
2221         if (is_input ()) {
2222                 (_buffer[_bufperiod]).clear ();
2223                 for (std::vector<PamPort*>::const_iterator i = get_connections ().begin ();
2224                                 i != get_connections ().end ();
2225                                 ++i) {
2226                         const PortMidiBuffer * src = static_cast<const PortMidiPort*>(*i)->const_buffer ();
2227                         for (PortMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
2228                                 (_buffer[_bufperiod]).push_back (boost::shared_ptr<PortMidiEvent>(new PortMidiEvent (**it)));
2229                         }
2230                 }
2231                 std::sort ((_buffer[_bufperiod]).begin (), (_buffer[_bufperiod]).end (), MidiEventSorter());
2232         }
2233         return &(_buffer[_bufperiod]);
2234 }
2235
2236 PortMidiEvent::PortMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
2237         : _size (size)
2238         , _timestamp (timestamp)
2239         , _data (0)
2240 {
2241         if (size > 0) {
2242                 _data = (uint8_t*) malloc (size);
2243                 memcpy (_data, data, size);
2244         }
2245 }
2246
2247 PortMidiEvent::PortMidiEvent (const PortMidiEvent& other)
2248         : _size (other.size ())
2249         , _timestamp (other.timestamp ())
2250         , _data (0)
2251 {
2252         if (other.size () && other.const_data ()) {
2253                 _data = (uint8_t*) malloc (other.size ());
2254                 memcpy (_data, other.const_data (), other.size ());
2255         }
2256 };
2257
2258 PortMidiEvent::~PortMidiEvent () {
2259         free (_data);
2260 };