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