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