Fix build on El Capitan
[ardour.git] / libs / backends / portaudio / portaudio_backend.cc
1 /*
2  * Copyright (C) 2015-2015 Robin Gareus <robin@gareus.org>
3  * Copyright (C) 2013 Paul Davis
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19
20 #include <regex.h>
21
22 #ifndef PLATFORM_WINDOWS
23 #include <sys/mman.h>
24 #include <sys/time.h>
25 #endif
26
27 #ifdef COMPILER_MINGW
28 #include <sys/time.h>
29 #endif
30
31 #include <glibmm.h>
32
33 #include "portaudio_backend.h"
34 #include "rt_thread.h"
35
36 #include "pbd/compose.h"
37 #include "pbd/error.h"
38 #include "pbd/file_utils.h"
39 #include "pbd/windows_timer_utils.h"
40 #include "pbd/windows_mmcss.h"
41
42 #include "ardour/filesystem_paths.h"
43 #include "ardour/port_manager.h"
44 #include "i18n.h"
45
46 #include "audio_utils.h"
47
48 #include "debug.h"
49
50 using namespace ARDOUR;
51
52 namespace {
53
54 const char * const winmme_driver_name = X_("WinMME");
55
56 }
57
58 static std::string s_instance_name;
59 size_t PortAudioBackend::_max_buffer_size = 8192;
60 std::vector<std::string> PortAudioBackend::_midi_options;
61 std::vector<AudioBackend::DeviceStatus> PortAudioBackend::_input_audio_device_status;
62 std::vector<AudioBackend::DeviceStatus> PortAudioBackend::_output_audio_device_status;
63
64 PortAudioBackend::PortAudioBackend (AudioEngine& e, AudioBackendInfo& info)
65         : AudioBackend (e, info)
66         , _pcmio (0)
67         , _run (false)
68         , _active (false)
69         , _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 PortEngine::PortHandle
1242 PortAudioBackend::get_port_by_name (const std::string& name) const
1243 {
1244         PortHandle port = (PortHandle) find_port (name);
1245         return port;
1246 }
1247
1248 int
1249 PortAudioBackend::get_ports (
1250                 const std::string& port_name_pattern,
1251                 DataType type, PortFlags flags,
1252                 std::vector<std::string>& port_names) const
1253 {
1254         int rv = 0;
1255         regex_t port_regex;
1256         bool use_regexp = false;
1257         if (port_name_pattern.size () > 0) {
1258                 if (!regcomp (&port_regex, port_name_pattern.c_str (), REG_EXTENDED|REG_NOSUB)) {
1259                         use_regexp = true;
1260                 }
1261         }
1262         for (size_t i = 0; i < _ports.size (); ++i) {
1263                 PamPort* port = _ports[i];
1264                 if ((port->type () == type) && flags == (port->flags () & flags)) {
1265                         if (!use_regexp || !regexec (&port_regex, port->name ().c_str (), 0, NULL, 0)) {
1266                                 port_names.push_back (port->name ());
1267                                 ++rv;
1268                         }
1269                 }
1270         }
1271         if (use_regexp) {
1272                 regfree (&port_regex);
1273         }
1274         return rv;
1275 }
1276
1277 DataType
1278 PortAudioBackend::port_data_type (PortEngine::PortHandle port) const
1279 {
1280         if (!valid_port (port)) {
1281                 return DataType::NIL;
1282         }
1283         return static_cast<PamPort*>(port)->type ();
1284 }
1285
1286 PortEngine::PortHandle
1287 PortAudioBackend::register_port (
1288                 const std::string& name,
1289                 ARDOUR::DataType type,
1290                 ARDOUR::PortFlags flags)
1291 {
1292         if (name.size () == 0) { return 0; }
1293         if (flags & IsPhysical) { return 0; }
1294         return add_port (_instance_name + ":" + name, type, flags);
1295 }
1296
1297 PortEngine::PortHandle
1298 PortAudioBackend::add_port (
1299                 const std::string& name,
1300                 ARDOUR::DataType type,
1301                 ARDOUR::PortFlags flags)
1302 {
1303         assert(name.size ());
1304         if (find_port (name)) {
1305                 DEBUG_PORTS(
1306                     string_compose("register_port: Port already exists: (%1)\n", name));
1307                 return 0;
1308         }
1309         PamPort* port = NULL;
1310         switch (type) {
1311         case DataType::AUDIO:
1312                 port = new PortAudioPort(*this, name, flags);
1313                 break;
1314         case DataType::MIDI:
1315                 port = new PortMidiPort(*this, name, flags);
1316                 break;
1317         default:
1318                 DEBUG_PORTS("register_port: Invalid Data Type.\n");
1319                 return 0;
1320         }
1321
1322         _ports.push_back (port);
1323
1324         return port;
1325 }
1326
1327 void
1328 PortAudioBackend::unregister_port (PortEngine::PortHandle port_handle)
1329 {
1330         if (!_run) {
1331                 return;
1332         }
1333         PamPort* port = static_cast<PamPort*>(port_handle);
1334         std::vector<PamPort*>::iterator i = std::find (_ports.begin (), _ports.end (), static_cast<PamPort*>(port_handle));
1335         if (i == _ports.end ()) {
1336                 DEBUG_PORTS("unregister_port: Failed to find port\n");
1337                 return;
1338         }
1339         disconnect_all(port_handle);
1340         _ports.erase (i);
1341         delete port;
1342 }
1343
1344 int
1345 PortAudioBackend::register_system_audio_ports()
1346 {
1347         LatencyRange lr;
1348
1349         const uint32_t a_ins = _n_inputs;
1350         const uint32_t a_out = _n_outputs;
1351
1352         uint32_t capture_latency = 0;
1353         uint32_t playback_latency = 0;
1354
1355         // guard against erroneous latency values
1356         if (_pcmio->capture_latency() > _samples_per_period) {
1357                 capture_latency = _pcmio->capture_latency() - _samples_per_period;
1358         }
1359         if (_pcmio->playback_latency() > _samples_per_period) {
1360                 playback_latency = _pcmio->playback_latency() - _samples_per_period;
1361         }
1362
1363         /* audio ports */
1364         lr.min = lr.max = capture_latency + (_measure_latency ? 0 : _systemic_audio_input_latency);
1365         for (uint32_t i = 0; i < a_ins; ++i) {
1366                 char tmp[64];
1367                 snprintf(tmp, sizeof(tmp), "system:capture_%d", i+1);
1368                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
1369                 if (!p) return -1;
1370                 set_latency_range (p, false, lr);
1371                 PortAudioPort* audio_port = static_cast<PortAudioPort*>(p);
1372                 audio_port->set_pretty_name (
1373                     _pcmio->get_input_channel_name (name_to_id (_input_audio_device), i));
1374                 _system_inputs.push_back (audio_port);
1375         }
1376
1377         lr.min = lr.max = playback_latency + (_measure_latency ? 0 : _systemic_audio_output_latency);
1378         for (uint32_t i = 0; i < a_out; ++i) {
1379                 char tmp[64];
1380                 snprintf(tmp, sizeof(tmp), "system:playback_%d", i+1);
1381                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
1382                 if (!p) return -1;
1383                 set_latency_range (p, true, lr);
1384                 PortAudioPort* audio_port = static_cast<PortAudioPort*>(p);
1385                 audio_port->set_pretty_name (
1386                     _pcmio->get_output_channel_name (name_to_id (_output_audio_device), i));
1387                 _system_outputs.push_back(audio_port);
1388         }
1389         return 0;
1390 }
1391
1392 int
1393 PortAudioBackend::register_system_midi_ports()
1394 {
1395         if (_midi_driver_option == get_standard_device_name(DeviceNone)) {
1396                 DEBUG_MIDI("No MIDI backend selected, not system midi ports available\n");
1397                 return 0;
1398         }
1399
1400         LatencyRange lr;
1401         lr.min = lr.max = _samples_per_period;
1402
1403         const std::vector<WinMMEMidiInputDevice*> inputs = _midiio->get_inputs();
1404
1405         for (std::vector<WinMMEMidiInputDevice*>::const_iterator i = inputs.begin ();
1406              i != inputs.end ();
1407              ++i) {
1408                 std::string port_name = "system:midi_capture_" + (*i)->name();
1409                 PortHandle p =
1410                     add_port (port_name,
1411                               DataType::MIDI,
1412                               static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
1413                 if (!p) return -1;
1414
1415                 MidiDeviceInfo* info = _midiio->get_device_info((*i)->name());
1416                 if (info) { // assert?
1417                         lr.min = lr.max = _samples_per_period + info->systemic_input_latency;
1418                 }
1419                 set_latency_range (p, false, lr);
1420
1421                 PortMidiPort* midi_port = static_cast<PortMidiPort*>(p);
1422                 midi_port->set_pretty_name ((*i)->name());
1423                 _system_midi_in.push_back (midi_port);
1424                 DEBUG_MIDI (string_compose ("Registered MIDI input port: %1\n", port_name));
1425         }
1426
1427         const std::vector<WinMMEMidiOutputDevice*> outputs = _midiio->get_outputs();
1428
1429         for (std::vector<WinMMEMidiOutputDevice*>::const_iterator i = outputs.begin ();
1430              i != outputs.end ();
1431              ++i) {
1432                 std::string port_name = "system:midi_playback_" + (*i)->name();
1433                 PortHandle p =
1434                     add_port (port_name,
1435                               DataType::MIDI,
1436                               static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
1437                 if (!p) return -1;
1438
1439                 MidiDeviceInfo* info = _midiio->get_device_info((*i)->name());
1440                 if (info) { // assert?
1441                         lr.min = lr.max = _samples_per_period + info->systemic_output_latency;
1442                 }
1443                 set_latency_range (p, false, lr);
1444
1445                 PortMidiPort* midi_port = static_cast<PortMidiPort*>(p);
1446                 midi_port->set_n_periods(2);
1447                 midi_port->set_pretty_name ((*i)->name());
1448                 _system_midi_out.push_back (midi_port);
1449                 DEBUG_MIDI (string_compose ("Registered MIDI output port: %1\n", port_name));
1450         }
1451         return 0;
1452 }
1453
1454 void
1455 PortAudioBackend::unregister_ports (bool system_only)
1456 {
1457         size_t i = 0;
1458         _system_inputs.clear();
1459         _system_outputs.clear();
1460         _system_midi_in.clear();
1461         _system_midi_out.clear();
1462         while (i <  _ports.size ()) {
1463                 PamPort* port = _ports[i];
1464                 if (! system_only || (port->is_physical () && port->is_terminal ())) {
1465                         port->disconnect_all ();
1466                         delete port;
1467                         _ports.erase (_ports.begin() + i);
1468                 } else {
1469                         ++i;
1470                 }
1471         }
1472 }
1473
1474 int
1475 PortAudioBackend::connect (const std::string& src, const std::string& dst)
1476 {
1477         PamPort* src_port = find_port (src);
1478         PamPort* dst_port = find_port (dst);
1479
1480         if (!src_port) {
1481                 DEBUG_PORTS(string_compose("connect: Invalid Source port: (%1)\n", src));
1482                 return -1;
1483         }
1484         if (!dst_port) {
1485                 DEBUG_PORTS(string_compose("connect: Invalid Destination port: (%1)\n", dst));
1486                 return -1;
1487         }
1488         return src_port->connect (dst_port);
1489 }
1490
1491 int
1492 PortAudioBackend::disconnect (const std::string& src, const std::string& dst)
1493 {
1494         PamPort* src_port = find_port (src);
1495         PamPort* dst_port = find_port (dst);
1496
1497         if (!src_port || !dst_port) {
1498                 DEBUG_PORTS("disconnect: Invalid Port(s)\n");
1499                 return -1;
1500         }
1501         return src_port->disconnect (dst_port);
1502 }
1503
1504 int
1505 PortAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
1506 {
1507         PamPort* dst_port = find_port (dst);
1508         if (!valid_port (src)) {
1509                 DEBUG_PORTS("connect: Invalid Source Port Handle\n");
1510                 return -1;
1511         }
1512         if (!dst_port) {
1513                 DEBUG_PORTS(string_compose("connect: Invalid Destination Port (%1)\n", dst));
1514                 return -1;
1515         }
1516         return static_cast<PamPort*>(src)->connect (dst_port);
1517 }
1518
1519 int
1520 PortAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
1521 {
1522         PamPort* dst_port = find_port (dst);
1523         if (!valid_port (src) || !dst_port) {
1524                 DEBUG_PORTS("disconnect: Invalid Port(s)\n");
1525                 return -1;
1526         }
1527         return static_cast<PamPort*>(src)->disconnect (dst_port);
1528 }
1529
1530 int
1531 PortAudioBackend::disconnect_all (PortEngine::PortHandle port)
1532 {
1533         if (!valid_port (port)) {
1534                 DEBUG_PORTS("disconnect_all: Invalid Port\n");
1535                 return -1;
1536         }
1537         static_cast<PamPort*>(port)->disconnect_all ();
1538         return 0;
1539 }
1540
1541 bool
1542 PortAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
1543 {
1544         if (!valid_port (port)) {
1545                 DEBUG_PORTS("disconnect_all: Invalid Port\n");
1546                 return false;
1547         }
1548         return static_cast<PamPort*>(port)->is_connected ();
1549 }
1550
1551 bool
1552 PortAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
1553 {
1554         PamPort* dst_port = find_port (dst);
1555         if (!valid_port (src) || !dst_port) {
1556                 DEBUG_PORTS("connected_to: Invalid Port\n");
1557                 return false;
1558         }
1559         return static_cast<PamPort*>(src)->is_connected (dst_port);
1560 }
1561
1562 bool
1563 PortAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
1564 {
1565         if (!valid_port (port)) {
1566                 DEBUG_PORTS("physically_connected: Invalid Port\n");
1567                 return false;
1568         }
1569         return static_cast<PamPort*>(port)->is_physically_connected ();
1570 }
1571
1572 int
1573 PortAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
1574 {
1575         if (!valid_port (port)) {
1576                 DEBUG_PORTS("get_connections: Invalid Port\n");
1577                 return -1;
1578         }
1579
1580         assert (0 == names.size ());
1581
1582         const std::vector<PamPort*>& connected_ports = static_cast<PamPort*>(port)->get_connections ();
1583
1584         for (std::vector<PamPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
1585                 names.push_back ((*i)->name ());
1586         }
1587
1588         return (int)names.size ();
1589 }
1590
1591 /* MIDI */
1592 int
1593 PortAudioBackend::midi_event_get (
1594                 pframes_t& timestamp,
1595                 size_t& size, uint8_t** buf, void* port_buffer,
1596                 uint32_t event_index)
1597 {
1598         if (!buf || !port_buffer) return -1;
1599         PortMidiBuffer& source = * static_cast<PortMidiBuffer*>(port_buffer);
1600         if (event_index >= source.size ()) {
1601                 return -1;
1602         }
1603         PortMidiEvent * const event = source[event_index].get ();
1604
1605         timestamp = event->timestamp ();
1606         size = event->size ();
1607         *buf = event->data ();
1608         return 0;
1609 }
1610
1611 int
1612 PortAudioBackend::midi_event_put (
1613                 void* port_buffer,
1614                 pframes_t timestamp,
1615                 const uint8_t* buffer, size_t size)
1616 {
1617         if (!buffer || !port_buffer) return -1;
1618         PortMidiBuffer& dst = * static_cast<PortMidiBuffer*>(port_buffer);
1619         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
1620                 // nevermind, ::get_buffer() sorts events
1621                 DEBUG_MIDI (string_compose ("PortMidiBuffer: unordered event: %1 > %2\n",
1622                                             (pframes_t)dst.back ()->timestamp (),
1623                                             timestamp));
1624         }
1625         dst.push_back (boost::shared_ptr<PortMidiEvent>(new PortMidiEvent (timestamp, buffer, size)));
1626         return 0;
1627 }
1628
1629 uint32_t
1630 PortAudioBackend::get_midi_event_count (void* port_buffer)
1631 {
1632         if (!port_buffer) return 0;
1633         return static_cast<PortMidiBuffer*>(port_buffer)->size ();
1634 }
1635
1636 void
1637 PortAudioBackend::midi_clear (void* port_buffer)
1638 {
1639         if (!port_buffer) return;
1640         PortMidiBuffer * buf = static_cast<PortMidiBuffer*>(port_buffer);
1641         assert (buf);
1642         buf->clear ();
1643 }
1644
1645 /* Monitoring */
1646
1647 bool
1648 PortAudioBackend::can_monitor_input () const
1649 {
1650         return false;
1651 }
1652
1653 int
1654 PortAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1655 {
1656         return -1;
1657 }
1658
1659 int
1660 PortAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1661 {
1662         return -1;
1663 }
1664
1665 bool
1666 PortAudioBackend::monitoring_input (PortEngine::PortHandle)
1667 {
1668         return false;
1669 }
1670
1671 /* Latency management */
1672
1673 void
1674 PortAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1675 {
1676         if (!valid_port (port)) {
1677                 DEBUG_PORTS("PamPort::set_latency_range (): invalid port.\n");
1678         }
1679         static_cast<PamPort*>(port)->set_latency_range (latency_range, for_playback);
1680 }
1681
1682 LatencyRange
1683 PortAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1684 {
1685         LatencyRange r;
1686         if (!valid_port (port)) {
1687                 DEBUG_PORTS("PamPort::get_latency_range (): invalid port.\n");
1688                 r.min = 0;
1689                 r.max = 0;
1690                 return r;
1691         }
1692         PamPort* p = static_cast<PamPort*>(port);
1693         assert(p);
1694
1695         r = p->latency_range (for_playback);
1696         // TODO MIDI
1697         if (p->is_physical() && p->is_terminal() && p->type() == DataType::AUDIO) {
1698                 if (p->is_input() && for_playback) {
1699                         r.min += _samples_per_period;
1700                         r.max += _samples_per_period;
1701                 }
1702                 if (p->is_output() && !for_playback) {
1703                         r.min += _samples_per_period;
1704                         r.max += _samples_per_period;
1705                 }
1706         }
1707         return r;
1708 }
1709
1710 /* Discovering physical ports */
1711
1712 bool
1713 PortAudioBackend::port_is_physical (PortEngine::PortHandle port) const
1714 {
1715         if (!valid_port (port)) {
1716                 DEBUG_PORTS("PamPort::port_is_physical (): invalid port.\n");
1717                 return false;
1718         }
1719         return static_cast<PamPort*>(port)->is_physical ();
1720 }
1721
1722 void
1723 PortAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1724 {
1725         for (size_t i = 0; i < _ports.size (); ++i) {
1726                 PamPort* port = _ports[i];
1727                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1728                         port_names.push_back (port->name ());
1729                 }
1730         }
1731 }
1732
1733 void
1734 PortAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1735 {
1736         for (size_t i = 0; i < _ports.size (); ++i) {
1737                 PamPort* port = _ports[i];
1738                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1739                         port_names.push_back (port->name ());
1740                 }
1741         }
1742 }
1743
1744 ChanCount
1745 PortAudioBackend::n_physical_outputs () const
1746 {
1747         int n_midi = 0;
1748         int n_audio = 0;
1749         for (size_t i = 0; i < _ports.size (); ++i) {
1750                 PamPort* port = _ports[i];
1751                 if (port->is_output () && port->is_physical ()) {
1752                         switch (port->type ()) {
1753                         case DataType::AUDIO:
1754                                 ++n_audio;
1755                                 break;
1756                         case DataType::MIDI:
1757                                 ++n_midi;
1758                                 break;
1759                         default:
1760                                 break;
1761                         }
1762                 }
1763         }
1764         ChanCount cc;
1765         cc.set (DataType::AUDIO, n_audio);
1766         cc.set (DataType::MIDI, n_midi);
1767         return cc;
1768 }
1769
1770 ChanCount
1771 PortAudioBackend::n_physical_inputs () const
1772 {
1773         int n_midi = 0;
1774         int n_audio = 0;
1775         for (size_t i = 0; i < _ports.size (); ++i) {
1776                 PamPort* port = _ports[i];
1777                 if (port->is_input () && port->is_physical ()) {
1778                         switch (port->type ()) {
1779                         case DataType::AUDIO:
1780                                 ++n_audio;
1781                                 break;
1782                         case DataType::MIDI:
1783                                 ++n_midi;
1784                                 break;
1785                         default:
1786                                 break;
1787                         }
1788                 }
1789         }
1790         ChanCount cc;
1791         cc.set (DataType::AUDIO, n_audio);
1792         cc.set (DataType::MIDI, n_midi);
1793         return cc;
1794 }
1795
1796 /* Getting access to the data buffer for a port */
1797
1798 void*
1799 PortAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1800 {
1801         if (!port || !valid_port (port)) return NULL;
1802         return static_cast<PamPort*>(port)->get_buffer (nframes);
1803 }
1804
1805
1806 void *
1807 PortAudioBackend::blocking_process_thread ()
1808 {
1809         AudioEngine::thread_init_callback (this);
1810         _active = true;
1811         _processed_samples = 0;
1812
1813         manager.registration_callback();
1814         manager.graph_order_callback();
1815
1816         if (_pcmio->start_stream() != paNoError) {
1817                 _pcmio->close_stream ();
1818                 _active = false;
1819                 engine.halted_callback(get_error_string(AudioDeviceIOError).c_str());
1820         }
1821
1822 #ifdef USE_MMCSS_THREAD_PRIORITIES
1823         HANDLE task_handle;
1824         bool mmcss_success = set_mmcss_pro_audio (&task_handle);
1825 #endif
1826
1827         DWORD tid = GetCurrentThreadId ();
1828         DEBUG_THREADS (string_compose ("Process Thread Master ID: %1\n", tid));
1829
1830         while (_run) {
1831
1832                 if (_freewheeling != _freewheel) {
1833                         _freewheel = _freewheeling;
1834                         engine.freewheel_callback (_freewheel);
1835                 }
1836
1837                 if (!_freewheel) {
1838
1839                         switch (_pcmio->next_cycle (_samples_per_period)) {
1840                         case 0: // OK
1841                                 break;
1842                         case 1:
1843                                 DEBUG_AUDIO("PortAudio: Xrun\n");
1844                                 engine.Xrun();
1845                                 break;
1846                         default:
1847                                 PBD::error << get_error_string(AudioDeviceIOError) << endmsg;
1848                                 break;
1849                         }
1850
1851                         if (!blocking_process_main(_pcmio->get_capture_buffer(),
1852                                                    _pcmio->get_playback_buffer())) {
1853                                 return 0;
1854                         }
1855                 } else {
1856
1857                         if (!blocking_process_freewheel()) {
1858                                 return 0;
1859                         }
1860                 }
1861
1862                 process_port_connection_changes();
1863         }
1864         _pcmio->close_stream();
1865         _active = false;
1866         if (_run) {
1867                 engine.halted_callback(get_error_string(AudioDeviceIOError).c_str());
1868         }
1869
1870 #ifdef USE_MMCSS_THREAD_PRIORITIES
1871         if (mmcss_success) {
1872                 reset_mmcss(task_handle);
1873         }
1874 #endif
1875
1876         return 0;
1877 }
1878
1879 bool
1880 PortAudioBackend::blocking_process_main(const float* interleaved_input_data,
1881                                         float* interleaved_output_data)
1882 {
1883         uint32_t i = 0;
1884         int64_t min_elapsed_us = 1000000;
1885         int64_t max_elapsed_us = 0;
1886
1887         _dsp_calc.set_start_timestamp_us (PBD::get_microseconds());
1888
1889         i = 0;
1890         /* Copy input audio data into input port buffers */
1891         for (std::vector<PamPort*>::const_iterator it = _system_inputs.begin();
1892              it != _system_inputs.end();
1893              ++it, ++i) {
1894                 assert(_system_inputs.size() == _pcmio->n_capture_channels());
1895                 uint32_t channels = _system_inputs.size();
1896                 float* input_port_buffer = (float*)(*it)->get_buffer(_samples_per_period);
1897                 deinterleave_audio_data(
1898                     interleaved_input_data, input_port_buffer, _samples_per_period, i, channels);
1899         }
1900
1901         process_incoming_midi ();
1902
1903         /* clear output buffers */
1904         for (std::vector<PamPort*>::const_iterator it = _system_outputs.begin();
1905              it != _system_outputs.end();
1906              ++it) {
1907                 memset((*it)->get_buffer(_samples_per_period),
1908                        0,
1909                        _samples_per_period * sizeof(Sample));
1910         }
1911
1912         _last_cycle_start = _cycle_timer.get_start();
1913         _cycle_timer.reset_start(PBD::get_microseconds());
1914         _cycle_count++;
1915
1916         uint64_t cycle_diff_us = (_cycle_timer.get_start() - _last_cycle_start);
1917         int64_t deviation_us = (cycle_diff_us - _cycle_timer.get_length_us());
1918         _total_deviation_us += ::llabs(deviation_us);
1919         _max_deviation_us =
1920             std::max(_max_deviation_us, (uint64_t)::llabs(deviation_us));
1921
1922         if ((_cycle_count % 1000) == 0) {
1923                 uint64_t mean_deviation_us = _total_deviation_us / _cycle_count;
1924                 DEBUG_TIMING(string_compose("Mean avg cycle deviation: %1(ms), max %2(ms)\n",
1925                                             mean_deviation_us * 1e-3,
1926                                             _max_deviation_us * 1e-3));
1927         }
1928
1929         if (::llabs(deviation_us) > _cycle_timer.get_length_us()) {
1930                 DEBUG_TIMING(
1931                     string_compose("time between process(ms): %1, Est(ms): %2, Dev(ms): %3\n",
1932                                    cycle_diff_us * 1e-3,
1933                                    _cycle_timer.get_length_us() * 1e-3,
1934                                    deviation_us * 1e-3));
1935         }
1936
1937         /* call engine process callback */
1938         if (engine.process_callback(_samples_per_period)) {
1939                 _pcmio->close_stream();
1940                 _active = false;
1941                 return false;
1942         }
1943
1944         process_outgoing_midi ();
1945
1946         /* write back audio */
1947         i = 0;
1948         for (std::vector<PamPort*>::const_iterator it = _system_outputs.begin();
1949              it != _system_outputs.end();
1950              ++it, ++i) {
1951                 assert(_system_outputs.size() == _pcmio->n_playback_channels());
1952                 const uint32_t channels = _system_outputs.size();
1953                 float* output_port_buffer = (float*)(*it)->get_buffer(_samples_per_period);
1954                 interleave_audio_data(
1955                     output_port_buffer, interleaved_output_data, _samples_per_period, i, channels);
1956         }
1957
1958         _processed_samples += _samples_per_period;
1959
1960         /* calculate DSP load */
1961         _dsp_calc.set_stop_timestamp_us (PBD::get_microseconds());
1962         _dsp_load = _dsp_calc.get_dsp_load();
1963
1964         DEBUG_TIMING(string_compose("DSP Load: %1\n", _dsp_load));
1965
1966         max_elapsed_us = std::max(_dsp_calc.elapsed_time_us(), max_elapsed_us);
1967         min_elapsed_us = std::min(_dsp_calc.elapsed_time_us(), min_elapsed_us);
1968         if ((_cycle_count % 1000) == 0) {
1969                 DEBUG_TIMING(string_compose("Elapsed process time(usecs) max: %1, min: %2\n",
1970                                             max_elapsed_us,
1971                                             min_elapsed_us));
1972         }
1973
1974         return true;
1975 }
1976
1977 bool
1978 PortAudioBackend::blocking_process_freewheel()
1979 {
1980         // zero audio input buffers
1981         for (std::vector<PamPort*>::const_iterator it = _system_inputs.begin();
1982              it != _system_inputs.end();
1983              ++it) {
1984                 memset((*it)->get_buffer(_samples_per_period),
1985                        0,
1986                        _samples_per_period * sizeof(Sample));
1987         }
1988
1989         // TODO clear midi or stop midi recv when entering fwheelin'
1990
1991         if (engine.process_callback(_samples_per_period)) {
1992                 _pcmio->close_stream();
1993                 _active = false;
1994                 return false;
1995         }
1996
1997         // drop all outgoing MIDI messages
1998         for (std::vector<PamPort*>::const_iterator it = _system_midi_out.begin();
1999              it != _system_midi_out.end();
2000              ++it) {
2001                 void* bptr = (*it)->get_buffer(0);
2002                 midi_clear(bptr);
2003         }
2004
2005         _dsp_load = 1.0;
2006         Glib::usleep(100); // don't hog cpu
2007         return true;
2008 }
2009
2010 void
2011 PortAudioBackend::process_incoming_midi ()
2012 {
2013         uint32_t i = 0;
2014         for (std::vector<PamPort*>::const_iterator it = _system_midi_in.begin();
2015              it != _system_midi_in.end();
2016              ++it, ++i) {
2017                 PortMidiBuffer* mbuf = static_cast<PortMidiBuffer*>((*it)->get_buffer(0));
2018                 mbuf->clear();
2019                 uint64_t timestamp;
2020                 pframes_t sample_offset;
2021                 uint8_t data[256];
2022                 size_t size = sizeof(data);
2023                 while (_midiio->dequeue_input_event(i,
2024                                                     _cycle_timer.get_start(),
2025                                                     _cycle_timer.get_next_start(),
2026                                                     timestamp,
2027                                                     data,
2028                                                     size)) {
2029                         sample_offset = _cycle_timer.samples_since_cycle_start(timestamp);
2030                         midi_event_put(mbuf, sample_offset, data, size);
2031                         DEBUG_MIDI(string_compose("Dequeuing incoming MIDI data for device: %1 "
2032                                                   "sample_offset: %2 timestamp: %3, size: %4\n",
2033                                                   _midiio->get_inputs()[i]->name(),
2034                                                   sample_offset,
2035                                                   timestamp,
2036                                                   size));
2037                         size = sizeof(data);
2038                 }
2039         }
2040 }
2041
2042 void
2043 PortAudioBackend::process_outgoing_midi ()
2044 {
2045         /* mixdown midi */
2046         for (std::vector<PamPort*>::iterator it = _system_midi_out.begin();
2047              it != _system_midi_out.end();
2048              ++it) {
2049                 static_cast<PortMidiPort*>(*it)->next_period();
2050         }
2051         /* queue outgoing midi */
2052         uint32_t i = 0;
2053         for (std::vector<PamPort*>::const_iterator it = _system_midi_out.begin();
2054              it != _system_midi_out.end();
2055              ++it, ++i) {
2056                 const PortMidiBuffer* src =
2057                     static_cast<const PortMidiPort*>(*it)->const_buffer();
2058
2059                 for (PortMidiBuffer::const_iterator mit = src->begin(); mit != src->end();
2060                      ++mit) {
2061                         uint64_t timestamp =
2062                             _cycle_timer.timestamp_from_sample_offset((*mit)->timestamp());
2063                         DEBUG_MIDI(string_compose("Queuing outgoing MIDI data for device: "
2064                                                   "%1 sample_offset: %2 timestamp: %3, size: %4\n",
2065                                                   _midiio->get_outputs()[i]->name(),
2066                                                   (*mit)->timestamp(),
2067                                                   timestamp,
2068                                                   (*mit)->size()));
2069                         _midiio->enqueue_output_event(i, timestamp, (*mit)->data(), (*mit)->size());
2070                 }
2071         }
2072 }
2073
2074 void
2075 PortAudioBackend::process_port_connection_changes ()
2076 {
2077         bool connections_changed = false;
2078         bool ports_changed = false;
2079         if (!pthread_mutex_trylock (&_port_callback_mutex)) {
2080                 if (_port_change_flag) {
2081                         ports_changed = true;
2082                         _port_change_flag = false;
2083                 }
2084                 if (!_port_connection_queue.empty ()) {
2085                         connections_changed = true;
2086                 }
2087                 while (!_port_connection_queue.empty ()) {
2088                         PortConnectData *c = _port_connection_queue.back ();
2089                         manager.connect_callback (c->a, c->b, c->c);
2090                         _port_connection_queue.pop_back ();
2091                         delete c;
2092                 }
2093                 pthread_mutex_unlock (&_port_callback_mutex);
2094         }
2095         if (ports_changed) {
2096                 manager.registration_callback();
2097         }
2098         if (connections_changed) {
2099                 manager.graph_order_callback();
2100         }
2101         if (connections_changed || ports_changed) {
2102                 engine.latency_callback(false);
2103                 engine.latency_callback(true);
2104         }
2105 }
2106
2107 /******************************************************************************/
2108
2109 static boost::shared_ptr<PortAudioBackend> _instance;
2110
2111 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
2112 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
2113 static int deinstantiate ();
2114 static bool already_configured ();
2115 static bool available ();
2116
2117 static ARDOUR::AudioBackendInfo _descriptor = {
2118         BACKEND_NAME,
2119         instantiate,
2120         deinstantiate,
2121         backend_factory,
2122         already_configured,
2123         available
2124 };
2125
2126 static boost::shared_ptr<AudioBackend>
2127 backend_factory (AudioEngine& e)
2128 {
2129         if (!_instance) {
2130                 _instance.reset (new PortAudioBackend (e, _descriptor));
2131         }
2132         return _instance;
2133 }
2134
2135 static int
2136 instantiate (const std::string& arg1, const std::string& /* arg2 */)
2137 {
2138         s_instance_name = arg1;
2139         return 0;
2140 }
2141
2142 static int
2143 deinstantiate ()
2144 {
2145         _instance.reset ();
2146         return 0;
2147 }
2148
2149 static bool
2150 already_configured ()
2151 {
2152         return false;
2153 }
2154
2155 static bool
2156 available ()
2157 {
2158         return true;
2159 }
2160
2161 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
2162 {
2163         return &_descriptor;
2164 }
2165
2166
2167 /******************************************************************************/
2168 PamPort::PamPort (PortAudioBackend &b, const std::string& name, PortFlags flags)
2169         : _osx_backend (b)
2170         , _name  (name)
2171         , _flags (flags)
2172 {
2173         _capture_latency_range.min = 0;
2174         _capture_latency_range.max = 0;
2175         _playback_latency_range.min = 0;
2176         _playback_latency_range.max = 0;
2177 }
2178
2179 PamPort::~PamPort () {
2180         disconnect_all ();
2181 }
2182
2183
2184 int PamPort::connect (PamPort *port)
2185 {
2186         if (!port) {
2187                 DEBUG_PORTS("PamPort::connect (): invalid (null) port\n");
2188                 return -1;
2189         }
2190
2191         if (type () != port->type ()) {
2192                 DEBUG_PORTS("PamPort::connect (): wrong port-type\n");
2193                 return -1;
2194         }
2195
2196         if (is_output () && port->is_output ()) {
2197                 DEBUG_PORTS("PamPort::connect (): cannot inter-connect output ports.\n");
2198                 return -1;
2199         }
2200
2201         if (is_input () && port->is_input ()) {
2202                 DEBUG_PORTS("PamPort::connect (): cannot inter-connect input ports.\n");
2203                 return -1;
2204         }
2205
2206         if (this == port) {
2207                 DEBUG_PORTS("PamPort::connect (): cannot self-connect ports.\n");
2208                 return -1;
2209         }
2210
2211         if (is_connected (port)) {
2212 #if 0 // don't bother to warn about this for now. just ignore it
2213                 PBD::error << _("PamPort::connect (): ports are already connected:")
2214                         << " (" << name () << ") -> (" << port->name () << ")"
2215                         << endmsg;
2216 #endif
2217                 return -1;
2218         }
2219
2220         _connect (port, true);
2221         return 0;
2222 }
2223
2224
2225 void PamPort::_connect (PamPort *port, bool callback)
2226 {
2227         _connections.push_back (port);
2228         if (callback) {
2229                 port->_connect (this, false);
2230                 _osx_backend.port_connect_callback (name(),  port->name(), true);
2231         }
2232 }
2233
2234 int PamPort::disconnect (PamPort *port)
2235 {
2236         if (!port) {
2237                 DEBUG_PORTS("PamPort::disconnect (): invalid (null) port\n");
2238                 return -1;
2239         }
2240
2241         if (!is_connected (port)) {
2242                 DEBUG_PORTS(string_compose(
2243                     "PamPort::disconnect (): ports are not connected: (%1) -> (%2)\n",
2244                     name(),
2245                     port->name()));
2246                 return -1;
2247         }
2248         _disconnect (port, true);
2249         return 0;
2250 }
2251
2252 void PamPort::_disconnect (PamPort *port, bool callback)
2253 {
2254         std::vector<PamPort*>::iterator it = std::find (_connections.begin (), _connections.end (), port);
2255
2256         assert (it != _connections.end ());
2257
2258         _connections.erase (it);
2259
2260         if (callback) {
2261                 port->_disconnect (this, false);
2262                 _osx_backend.port_connect_callback (name(),  port->name(), false);
2263         }
2264 }
2265
2266
2267 void PamPort::disconnect_all ()
2268 {
2269         while (!_connections.empty ()) {
2270                 _connections.back ()->_disconnect (this, false);
2271                 _osx_backend.port_connect_callback (name(),  _connections.back ()->name(), false);
2272                 _connections.pop_back ();
2273         }
2274 }
2275
2276 bool
2277 PamPort::is_connected (const PamPort *port) const
2278 {
2279         return std::find (_connections.begin (), _connections.end (), port) != _connections.end ();
2280 }
2281
2282 bool PamPort::is_physically_connected () const
2283 {
2284         for (std::vector<PamPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
2285                 if ((*it)->is_physical ()) {
2286                         return true;
2287                 }
2288         }
2289         return false;
2290 }
2291
2292 /******************************************************************************/
2293
2294 PortAudioPort::PortAudioPort (PortAudioBackend &b, const std::string& name, PortFlags flags)
2295         : PamPort (b, name, flags)
2296 {
2297         memset (_buffer, 0, sizeof (_buffer));
2298 #ifndef PLATFORM_WINDOWS
2299         mlock(_buffer, sizeof (_buffer));
2300 #endif
2301 }
2302
2303 PortAudioPort::~PortAudioPort () { }
2304
2305 void* PortAudioPort::get_buffer (pframes_t n_samples)
2306 {
2307         if (is_input ()) {
2308                 std::vector<PamPort*>::const_iterator it = get_connections ().begin ();
2309                 if (it == get_connections ().end ()) {
2310                         memset (_buffer, 0, n_samples * sizeof (Sample));
2311                 } else {
2312                         PortAudioPort const * source = static_cast<const PortAudioPort*>(*it);
2313                         assert (source && source->is_output ());
2314                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
2315                         while (++it != get_connections ().end ()) {
2316                                 source = static_cast<const PortAudioPort*>(*it);
2317                                 assert (source && source->is_output ());
2318                                 Sample* dst = buffer ();
2319                                 const Sample* src = source->const_buffer ();
2320                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
2321                                         *dst += *src;
2322                                 }
2323                         }
2324                 }
2325         }
2326         return _buffer;
2327 }
2328
2329
2330 PortMidiPort::PortMidiPort (PortAudioBackend &b, const std::string& name, PortFlags flags)
2331         : PamPort (b, name, flags)
2332         , _n_periods (1)
2333         , _bufperiod (0)
2334 {
2335         _buffer[0].clear ();
2336         _buffer[1].clear ();
2337 }
2338
2339 PortMidiPort::~PortMidiPort () { }
2340
2341 struct MidiEventSorter {
2342         bool operator() (const boost::shared_ptr<PortMidiEvent>& a, const boost::shared_ptr<PortMidiEvent>& b) {
2343                 return *a < *b;
2344         }
2345 };
2346
2347 void* PortMidiPort::get_buffer (pframes_t /* nframes */)
2348 {
2349         if (is_input ()) {
2350                 (_buffer[_bufperiod]).clear ();
2351                 for (std::vector<PamPort*>::const_iterator i = get_connections ().begin ();
2352                                 i != get_connections ().end ();
2353                                 ++i) {
2354                         const PortMidiBuffer * src = static_cast<const PortMidiPort*>(*i)->const_buffer ();
2355                         for (PortMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
2356                                 (_buffer[_bufperiod]).push_back (boost::shared_ptr<PortMidiEvent>(new PortMidiEvent (**it)));
2357                         }
2358                 }
2359                 std::sort ((_buffer[_bufperiod]).begin (), (_buffer[_bufperiod]).end (), MidiEventSorter());
2360         }
2361         return &(_buffer[_bufperiod]);
2362 }
2363
2364 PortMidiEvent::PortMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
2365         : _size (size)
2366         , _timestamp (timestamp)
2367         , _data (0)
2368 {
2369         if (size > 0) {
2370                 _data = (uint8_t*) malloc (size);
2371                 memcpy (_data, data, size);
2372         }
2373 }
2374
2375 PortMidiEvent::PortMidiEvent (const PortMidiEvent& other)
2376         : _size (other.size ())
2377         , _timestamp (other.timestamp ())
2378         , _data (0)
2379 {
2380         if (other.size () && other.const_data ()) {
2381                 _data = (uint8_t*) malloc (other.size ());
2382                 memcpy (_data, other.const_data (), other.size ());
2383         }
2384 };
2385
2386 PortMidiEvent::~PortMidiEvent () {
2387         free (_data);
2388 };