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