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