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