Rename variables in PortaudioBackend in preparation for using PA callback API
[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 #include <glibmm.h>
28
29 #include "portaudio_backend.h"
30 #include "rt_thread.h"
31
32 #include "pbd/compose.h"
33 #include "pbd/error.h"
34 #include "pbd/file_utils.h"
35
36 #include "ardour/filesystem_paths.h"
37 #include "ardour/port_manager.h"
38 #include "i18n.h"
39
40 #include "win_utils.h"
41 #include "mmcss.h"
42
43 #include "debug.h"
44
45 using namespace ARDOUR;
46
47 namespace {
48
49 const char * const winmme_driver_name = X_("WinMME");
50
51 }
52
53 static std::string s_instance_name;
54 size_t PortAudioBackend::_max_buffer_size = 8192;
55 std::vector<std::string> PortAudioBackend::_midi_options;
56 std::vector<AudioBackend::DeviceStatus> PortAudioBackend::_input_audio_device_status;
57 std::vector<AudioBackend::DeviceStatus> PortAudioBackend::_output_audio_device_status;
58
59 PortAudioBackend::PortAudioBackend (AudioEngine& e, AudioBackendInfo& info)
60         : AudioBackend (e, info)
61         , _pcmio (0)
62         , _run (false)
63         , _active (false)
64         , _freewheel (false)
65         , _measure_latency (false)
66         , m_cycle_count(0)
67         , m_total_deviation_us(0)
68         , m_max_deviation_us(0)
69         , _input_audio_device("")
70         , _output_audio_device("")
71         , _midi_driver_option(get_standard_device_name(DeviceNone))
72         , _samplerate (48000)
73         , _samples_per_period (1024)
74         , _n_inputs (0)
75         , _n_outputs (0)
76         , _systemic_audio_input_latency (0)
77         , _systemic_audio_output_latency (0)
78         , _dsp_load (0)
79         , _processed_samples (0)
80         , _port_change_flag (false)
81 {
82         _instance_name = s_instance_name;
83         pthread_mutex_init (&_port_callback_mutex, 0);
84
85         mmcss::initialize ();
86
87         _pcmio = new PortAudioIO ();
88         _midiio = new WinMMEMidiIO ();
89 }
90
91 PortAudioBackend::~PortAudioBackend ()
92 {
93         delete _pcmio; _pcmio = 0;
94         delete _midiio; _midiio = 0;
95
96         mmcss::deinitialize ();
97
98         pthread_mutex_destroy (&_port_callback_mutex);
99 }
100
101 /* AUDIOBACKEND API */
102
103 std::string
104 PortAudioBackend::name () const
105 {
106         return X_("PortAudio");
107 }
108
109 bool
110 PortAudioBackend::is_realtime () const
111 {
112         return true;
113 }
114
115 bool
116 PortAudioBackend::requires_driver_selection() const
117 {
118         // we could do this but implementation would need changing
119         /*
120         if (enumerate_drivers().size() == 1) {
121                 return false;
122         }
123         */
124         return true;
125 }
126
127 std::vector<std::string>
128 PortAudioBackend::enumerate_drivers () const
129 {
130         DEBUG_AUDIO ("Portaudio: enumerate_drivers\n");
131         std::vector<std::string> currently_available;
132         _pcmio->host_api_list (currently_available);
133         return currently_available;
134 }
135
136 int
137 PortAudioBackend::set_driver (const std::string& name)
138 {
139         DEBUG_AUDIO (string_compose ("Portaudio: set_driver %1 \n", name));
140         if (!_pcmio->set_host_api (name)) {
141                 DEBUG_AUDIO (string_compose ("Portaudio: Unable to set_driver %1 \n", name));
142                 return -1;
143         }
144         _pcmio->update_devices();
145         return 0;
146 }
147
148 bool
149 PortAudioBackend::update_devices ()
150 {
151         return _pcmio->update_devices();
152 }
153
154 std::string
155 PortAudioBackend::driver_name () const
156 {
157         std::string driver_name = _pcmio->get_host_api ();
158         DEBUG_AUDIO (string_compose ("Portaudio: driver_name %1 \n", driver_name));
159         return driver_name;
160 }
161
162 bool
163 PortAudioBackend::use_separate_input_and_output_devices () const
164 {
165         return true;
166 }
167
168 std::vector<AudioBackend::DeviceStatus>
169 PortAudioBackend::enumerate_devices () const
170 {
171         DEBUG_AUDIO ("Portaudio: ERROR enumerate devices should not be called \n");
172         return std::vector<AudioBackend::DeviceStatus>();
173 }
174
175 std::vector<AudioBackend::DeviceStatus>
176 PortAudioBackend::enumerate_input_devices () const
177 {
178         _input_audio_device_status.clear();
179         std::map<int, std::string> input_devices;
180         _pcmio->input_device_list(input_devices);
181
182         for (std::map<int, std::string>::const_iterator i = input_devices.begin (); i != input_devices.end(); ++i) {
183                 if (_input_audio_device == "") _input_audio_device = i->second;
184                 _input_audio_device_status.push_back (DeviceStatus (i->second, true));
185         }
186         return _input_audio_device_status;
187 }
188
189 std::vector<AudioBackend::DeviceStatus>
190 PortAudioBackend::enumerate_output_devices () const
191 {
192         _output_audio_device_status.clear();
193         std::map<int, std::string> output_devices;
194         _pcmio->output_device_list(output_devices);
195
196         for (std::map<int, std::string>::const_iterator i = output_devices.begin (); i != output_devices.end(); ++i) {
197                 if (_output_audio_device == "") _output_audio_device = i->second;
198                 _output_audio_device_status.push_back (DeviceStatus (i->second, true));
199         }
200         return _output_audio_device_status;
201 }
202
203 std::vector<float>
204 PortAudioBackend::available_sample_rates (const std::string&) const
205 {
206         DEBUG_AUDIO ("Portaudio: available_sample_rates\n");
207         std::vector<float> sr;
208         _pcmio->available_sample_rates(name_to_id(_input_audio_device), sr);
209         return sr;
210 }
211
212 std::vector<uint32_t>
213 PortAudioBackend::available_buffer_sizes (const std::string&) const
214 {
215         DEBUG_AUDIO ("Portaudio: available_buffer_sizes\n");
216         std::vector<uint32_t> bs;
217         _pcmio->available_buffer_sizes(name_to_id(_input_audio_device), bs);
218         return bs;
219 }
220
221 uint32_t
222 PortAudioBackend::available_input_channel_count (const std::string&) const
223 {
224         return 128; // TODO query current device
225 }
226
227 uint32_t
228 PortAudioBackend::available_output_channel_count (const std::string&) const
229 {
230         return 128; // TODO query current device
231 }
232
233 bool
234 PortAudioBackend::can_change_sample_rate_when_running () const
235 {
236         return false;
237 }
238
239 bool
240 PortAudioBackend::can_change_buffer_size_when_running () const
241 {
242         return false; // TODO
243 }
244
245 int
246 PortAudioBackend::set_device_name (const std::string& d)
247 {
248         DEBUG_AUDIO ("Portaudio: set_device_name should not be called\n");
249         return 0;
250 }
251
252 int
253 PortAudioBackend::set_input_device_name (const std::string& d)
254 {
255         DEBUG_AUDIO (string_compose ("Portaudio: set_input_device_name %1\n", d));
256         _input_audio_device = d;
257         return 0;
258 }
259
260 int
261 PortAudioBackend::set_output_device_name (const std::string& d)
262 {
263         DEBUG_AUDIO (string_compose ("Portaudio: set_output_device_name %1\n", d));
264         _output_audio_device = d;
265         return 0;
266 }
267
268 int
269 PortAudioBackend::set_sample_rate (float sr)
270 {
271         if (sr <= 0) { return -1; }
272         // TODO check if it's in the list of valid SR
273         _samplerate = sr;
274         engine.sample_rate_change (sr);
275         return 0;
276 }
277
278 int
279 PortAudioBackend::set_buffer_size (uint32_t bs)
280 {
281         if (bs <= 0 || bs >= _max_buffer_size) {
282                 return -1;
283         }
284         _samples_per_period = bs;
285         engine.buffer_size_change (bs);
286         return 0;
287 }
288
289 int
290 PortAudioBackend::set_interleaved (bool yn)
291 {
292         if (!yn) { return 0; }
293         return -1;
294 }
295
296 int
297 PortAudioBackend::set_input_channels (uint32_t cc)
298 {
299         _n_inputs = cc;
300         return 0;
301 }
302
303 int
304 PortAudioBackend::set_output_channels (uint32_t cc)
305 {
306         _n_outputs = cc;
307         return 0;
308 }
309
310 int
311 PortAudioBackend::set_systemic_input_latency (uint32_t sl)
312 {
313         _systemic_audio_input_latency = sl;
314         return 0;
315 }
316
317 int
318 PortAudioBackend::set_systemic_output_latency (uint32_t sl)
319 {
320         _systemic_audio_output_latency = sl;
321         return 0;
322 }
323
324 /* Retrieving parameters */
325 std::string
326 PortAudioBackend::device_name () const
327 {
328         return "Unused";
329 }
330
331 std::string
332 PortAudioBackend::input_device_name () const
333 {
334         return _input_audio_device;
335 }
336
337 std::string
338 PortAudioBackend::output_device_name () const
339 {
340         return _output_audio_device;
341 }
342
343 float
344 PortAudioBackend::sample_rate () const
345 {
346         return _samplerate;
347 }
348
349 uint32_t
350 PortAudioBackend::buffer_size () const
351 {
352         return _samples_per_period;
353 }
354
355 bool
356 PortAudioBackend::interleaved () const
357 {
358         return false;
359 }
360
361 uint32_t
362 PortAudioBackend::input_channels () const
363 {
364         return _n_inputs;
365 }
366
367 uint32_t
368 PortAudioBackend::output_channels () const
369 {
370         return _n_outputs;
371 }
372
373 uint32_t
374 PortAudioBackend::systemic_input_latency () const
375 {
376         return _systemic_audio_input_latency;
377 }
378
379 uint32_t
380 PortAudioBackend::systemic_output_latency () const
381 {
382         return _systemic_audio_output_latency;
383 }
384
385 std::string
386 PortAudioBackend::control_app_name () const
387 {
388         return _pcmio->control_app_name (name_to_id (_input_audio_device));
389 }
390
391 void
392 PortAudioBackend::launch_control_app ()
393 {
394         return _pcmio->launch_control_app (name_to_id(_input_audio_device));
395 }
396
397 /* MIDI */
398
399 std::vector<std::string>
400 PortAudioBackend::enumerate_midi_options () const
401 {
402         if (_midi_options.empty()) {
403                 _midi_options.push_back (winmme_driver_name);
404                 _midi_options.push_back (get_standard_device_name(DeviceNone));
405         }
406         return _midi_options;
407 }
408
409 int
410 PortAudioBackend::set_midi_option (const std::string& opt)
411 {
412         if (opt != get_standard_device_name(DeviceNone) && opt != winmme_driver_name) {
413                 return -1;
414         }
415         DEBUG_MIDI (string_compose ("Setting midi option to %1\n", opt));
416         _midi_driver_option = opt;
417         return 0;
418 }
419
420 std::string
421 PortAudioBackend::midi_option () const
422 {
423         return _midi_driver_option;
424 }
425
426 /* State Control */
427
428 static void * pthread_process (void *arg)
429 {
430         PortAudioBackend *d = static_cast<PortAudioBackend *>(arg);
431         d->main_blocking_process_thread ();
432         pthread_exit (0);
433         return 0;
434 }
435
436 int
437 PortAudioBackend::_start (bool for_latency_measurement)
438 {
439         if (!_active && _run) {
440                 // recover from 'halted', reap threads
441                 stop();
442         }
443
444         if (_active || _run) {
445                 DEBUG_AUDIO("Already active.\n");
446                 return -1;
447         }
448
449         if (_ports.size()) {
450                 DEBUG_AUDIO(
451                     "Recovering from unclean shutdown, port registry is not empty.\n");
452                 _system_inputs.clear();
453                 _system_outputs.clear();
454                 _system_midi_in.clear();
455                 _system_midi_out.clear();
456                 _ports.clear();
457         }
458
459         /* reset internal state */
460         _dsp_load = 0;
461         _freewheeling = false;
462         _freewheel = false;
463
464         PortAudioIO::ErrorCode err;
465
466         err = _pcmio->open_blocking_stream(name_to_id(_input_audio_device),
467                                            name_to_id(_output_audio_device),
468                                            _samplerate,
469                                            _samples_per_period);
470
471         switch (err) {
472         case PortAudioIO::NoError:
473                 break;
474         case PortAudioIO::DeviceConfigNotSupportedError:
475                 PBD::error << get_error_string(DeviceConfigurationNotSupportedError)
476                            << endmsg;
477                 return -1;
478         default:
479                 PBD::error << get_error_string(AudioDeviceOpenError) << endmsg;
480                 return -1;
481         }
482
483         if (_n_outputs != _pcmio->n_playback_channels ()) {
484                 _n_outputs = _pcmio->n_playback_channels ();
485                 PBD::info << get_error_string(OutputChannelCountNotSupportedError) << endmsg;
486         }
487
488         if (_n_inputs != _pcmio->n_capture_channels ()) {
489                 _n_inputs = _pcmio->n_capture_channels ();
490                 PBD::info << get_error_string(InputChannelCountNotSupportedError) << endmsg;
491         }
492 #if 0
493         if (_pcmio->samples_per_period() != _samples_per_period) {
494                 _samples_per_period = _pcmio->samples_per_period();
495                 PBD::warning << _("PortAudioBackend: samples per period does not match.") << endmsg;
496         }
497 #endif
498
499         if (_pcmio->sample_rate() != _samplerate) {
500                 _samplerate = _pcmio->sample_rate();
501                 engine.sample_rate_change (_samplerate);
502                 PBD::warning << get_error_string(SampleRateNotSupportedError) << endmsg;
503         }
504
505         _measure_latency = for_latency_measurement;
506
507         _run = true;
508         _port_change_flag = false;
509
510         if (_midi_driver_option == winmme_driver_name) {
511                 _midiio->set_enabled(true);
512                 //_midiio->set_port_changed_callback(midi_port_change, this);
513                 _midiio->start(); // triggers port discovery, callback coremidi_rediscover()
514         }
515
516         m_cycle_timer.set_samplerate(_samplerate);
517         m_cycle_timer.set_samples_per_cycle(_samples_per_period);
518
519         DEBUG_MIDI ("Registering MIDI ports\n");
520
521         if (register_system_midi_ports () != 0) {
522                 DEBUG_PORTS("Failed to register system midi ports.\n")
523                 _run = false;
524                 return -1;
525         }
526
527         DEBUG_AUDIO ("Registering Audio ports\n");
528
529         if (register_system_audio_ports()) {
530                 DEBUG_PORTS("Failed to register system audio ports.\n");
531                 _run = false;
532                 return -1;
533         }
534
535         engine.sample_rate_change (_samplerate);
536         engine.buffer_size_change (_samples_per_period);
537
538         if (engine.reestablish_ports ()) {
539                 DEBUG_PORTS("Could not re-establish ports.\n");
540                 _run = false;
541                 return -1;
542         }
543
544         engine.reconnect_ports ();
545         _run = true;
546         _port_change_flag = false;
547
548         if (!start_blocking_process_thread()) {
549                 return -1;
550         }
551
552         return 0;
553 }
554
555 bool
556 PortAudioBackend::start_blocking_process_thread ()
557 {
558         if (_realtime_pthread_create (SCHED_FIFO, -20, 100000,
559                                 &_main_blocking_thread, pthread_process, this))
560         {
561                 if (pthread_create (&_main_blocking_thread, NULL, pthread_process, this))
562                 {
563                         DEBUG_AUDIO("Failed to create main audio thread\n");
564                         _run = false;
565                         return false;
566                 } else {
567                         PBD::warning << get_error_string(AquireRealtimePermissionError) << endmsg;
568                 }
569         }
570
571         int timeout = 5000;
572         while (!_active && --timeout > 0) { Glib::usleep (1000); }
573
574         if (timeout == 0 || !_active) {
575                 DEBUG_AUDIO("Failed to start main audio thread\n");
576                 _pcmio->close_stream();
577                 _run = false;
578                 unregister_ports();
579                 _active = false;
580                 return false;
581         }
582         return true;
583 }
584
585 bool
586 PortAudioBackend::stop_blocking_process_thread ()
587 {
588         void *status;
589
590         if (pthread_join (_main_blocking_thread, &status)) {
591                 DEBUG_AUDIO("Failed to stop main audio thread\n");
592                 return false;
593         }
594
595         return true;
596 }
597
598 int
599 PortAudioBackend::stop ()
600 {
601         if (!_run) {
602                 return 0;
603         }
604
605         _midiio->stop();
606
607         _run = false;
608
609         if (!stop_blocking_process_thread ()) {
610                 return -1;
611         }
612
613         unregister_ports();
614
615         return (_active == false) ? 0 : -1;
616 }
617
618 int
619 PortAudioBackend::freewheel (bool onoff)
620 {
621         if (onoff == _freewheeling) {
622                 return 0;
623         }
624         _freewheeling = onoff;
625         return 0;
626 }
627
628 float
629 PortAudioBackend::dsp_load () const
630 {
631         return 100.f * _dsp_load;
632 }
633
634 size_t
635 PortAudioBackend::raw_buffer_size (DataType t)
636 {
637         switch (t) {
638         case DataType::AUDIO:
639                 return _samples_per_period * sizeof(Sample);
640         case DataType::MIDI:
641                 return _max_buffer_size; // XXX not really limited
642         }
643         return 0;
644 }
645
646 /* Process time */
647 framepos_t
648 PortAudioBackend::sample_time ()
649 {
650         return _processed_samples;
651 }
652
653 framepos_t
654 PortAudioBackend::sample_time_at_cycle_start ()
655 {
656         return _processed_samples;
657 }
658
659 pframes_t
660 PortAudioBackend::samples_since_cycle_start ()
661 {
662         if (!_active || !_run || _freewheeling || _freewheel) {
663                 return 0;
664         }
665         if (!m_cycle_timer.valid()) {
666                 return 0;
667         }
668
669         return m_cycle_timer.samples_since_cycle_start (utils::get_microseconds());
670 }
671
672 int
673 PortAudioBackend::name_to_id(std::string device_name) const {
674         uint32_t device_id = UINT32_MAX;
675         std::map<int, std::string> devices;
676         _pcmio->input_device_list(devices);
677         _pcmio->output_device_list(devices);
678
679         for (std::map<int, std::string>::const_iterator i = devices.begin (); i != devices.end(); ++i) {
680                 if (i->second == device_name) {
681                         device_id = i->first;
682                         break;
683                 }
684         }
685         return device_id;
686 }
687
688 void *
689 PortAudioBackend::portaudio_process_thread (void *arg)
690 {
691         ThreadData* td = reinterpret_cast<ThreadData*> (arg);
692         boost::function<void ()> f = td->f;
693         delete td;
694
695 #ifdef USE_MMCSS_THREAD_PRIORITIES
696         HANDLE task_handle;
697
698         mmcss::set_thread_characteristics ("Pro Audio", &task_handle);
699         if (!mmcss::set_thread_priority(task_handle, mmcss::AVRT_PRIORITY_NORMAL)) {
700                 PBD::warning << get_error_string(SettingAudioThreadPriorityError)
701                              << endmsg;
702         }
703 #endif
704
705         DWORD tid = GetCurrentThreadId ();
706         DEBUG_THREADS (string_compose ("Process Thread Child ID: %1\n", tid));
707
708         f ();
709
710 #ifdef USE_MMCSS_THREAD_PRIORITIES
711         mmcss::revert_thread_characteristics (task_handle);
712 #endif
713
714         return 0;
715 }
716
717 int
718 PortAudioBackend::create_process_thread (boost::function<void()> func)
719 {
720         pthread_t thread_id;
721         pthread_attr_t attr;
722         size_t stacksize = 100000;
723
724         ThreadData* td = new ThreadData (this, func, stacksize);
725
726         if (_realtime_pthread_create (SCHED_FIFO, -21, stacksize,
727                                 &thread_id, portaudio_process_thread, td)) {
728                 pthread_attr_init (&attr);
729                 pthread_attr_setstacksize (&attr, stacksize);
730                 if (pthread_create (&thread_id, &attr, portaudio_process_thread, td)) {
731                         DEBUG_AUDIO("Cannot create process thread.");
732                         pthread_attr_destroy (&attr);
733                         return -1;
734                 }
735                 pthread_attr_destroy (&attr);
736         }
737
738         _threads.push_back (thread_id);
739         return 0;
740 }
741
742 int
743 PortAudioBackend::join_process_threads ()
744 {
745         int rv = 0;
746
747         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
748         {
749                 void *status;
750                 if (pthread_join (*i, &status)) {
751                         DEBUG_AUDIO("Cannot terminate process thread.");
752                         rv -= 1;
753                 }
754         }
755         _threads.clear ();
756         return rv;
757 }
758
759 bool
760 PortAudioBackend::in_process_thread ()
761 {
762         if (pthread_equal (_main_blocking_thread, pthread_self()) != 0) {
763                 return true;
764         }
765
766         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
767         {
768                 if (pthread_equal (*i, pthread_self ()) != 0) {
769                         return true;
770                 }
771         }
772         return false;
773 }
774
775 uint32_t
776 PortAudioBackend::process_thread_count ()
777 {
778         return _threads.size ();
779 }
780
781 void
782 PortAudioBackend::update_latencies ()
783 {
784         // trigger latency callback in RT thread (locked graph)
785         port_connect_add_remove_callback();
786 }
787
788 /* PORTENGINE API */
789
790 void*
791 PortAudioBackend::private_handle () const
792 {
793         return NULL;
794 }
795
796 const std::string&
797 PortAudioBackend::my_name () const
798 {
799         return _instance_name;
800 }
801
802 bool
803 PortAudioBackend::available () const
804 {
805         return _run && _active;
806 }
807
808 uint32_t
809 PortAudioBackend::port_name_size () const
810 {
811         return 256;
812 }
813
814 int
815 PortAudioBackend::set_port_name (PortEngine::PortHandle port, const std::string& name)
816 {
817         if (!valid_port (port)) {
818                 DEBUG_PORTS("set_port_name: Invalid Port(s)\n");
819                 return -1;
820         }
821         return static_cast<PamPort*>(port)->set_name (_instance_name + ":" + name);
822 }
823
824 std::string
825 PortAudioBackend::get_port_name (PortEngine::PortHandle port) const
826 {
827         if (!valid_port (port)) {
828                 DEBUG_PORTS("get_port_name: Invalid Port(s)\n");
829                 return std::string ();
830         }
831         return static_cast<PamPort*>(port)->name ();
832 }
833
834 int
835 PortAudioBackend::get_port_property (PortHandle port,
836                                      const std::string& key,
837                                      std::string& value,
838                                      std::string& type) const
839 {
840         if (!valid_port (port)) {
841                 DEBUG_PORTS("get_port_name: Invalid Port(s)\n");
842                 return -1;
843         }
844
845         if (key == "http://jackaudio.org/metadata/pretty-name") {
846                 type = "";
847                 value = static_cast<PamPort*>(port)->pretty_name ();
848                 if (!value.empty()) {
849                         return 0;
850                 }
851         }
852         return -1;
853 }
854
855 PortEngine::PortHandle
856 PortAudioBackend::get_port_by_name (const std::string& name) const
857 {
858         PortHandle port = (PortHandle) find_port (name);
859         return port;
860 }
861
862 int
863 PortAudioBackend::get_ports (
864                 const std::string& port_name_pattern,
865                 DataType type, PortFlags flags,
866                 std::vector<std::string>& port_names) const
867 {
868         int rv = 0;
869         regex_t port_regex;
870         bool use_regexp = false;
871         if (port_name_pattern.size () > 0) {
872                 if (!regcomp (&port_regex, port_name_pattern.c_str (), REG_EXTENDED|REG_NOSUB)) {
873                         use_regexp = true;
874                 }
875         }
876         for (size_t i = 0; i < _ports.size (); ++i) {
877                 PamPort* port = _ports[i];
878                 if ((port->type () == type) && flags == (port->flags () & flags)) {
879                         if (!use_regexp || !regexec (&port_regex, port->name ().c_str (), 0, NULL, 0)) {
880                                 port_names.push_back (port->name ());
881                                 ++rv;
882                         }
883                 }
884         }
885         if (use_regexp) {
886                 regfree (&port_regex);
887         }
888         return rv;
889 }
890
891 DataType
892 PortAudioBackend::port_data_type (PortEngine::PortHandle port) const
893 {
894         if (!valid_port (port)) {
895                 return DataType::NIL;
896         }
897         return static_cast<PamPort*>(port)->type ();
898 }
899
900 PortEngine::PortHandle
901 PortAudioBackend::register_port (
902                 const std::string& name,
903                 ARDOUR::DataType type,
904                 ARDOUR::PortFlags flags)
905 {
906         if (name.size () == 0) { return 0; }
907         if (flags & IsPhysical) { return 0; }
908         return add_port (_instance_name + ":" + name, type, flags);
909 }
910
911 PortEngine::PortHandle
912 PortAudioBackend::add_port (
913                 const std::string& name,
914                 ARDOUR::DataType type,
915                 ARDOUR::PortFlags flags)
916 {
917         assert(name.size ());
918         if (find_port (name)) {
919                 DEBUG_PORTS(
920                     string_compose("register_port: Port already exists: (%1)\n", name));
921                 return 0;
922         }
923         PamPort* port = NULL;
924         switch (type) {
925         case DataType::AUDIO:
926                 port = new PortAudioPort(*this, name, flags);
927                 break;
928         case DataType::MIDI:
929                 port = new PortMidiPort(*this, name, flags);
930                 break;
931         default:
932                 DEBUG_PORTS("register_port: Invalid Data Type.\n");
933                 return 0;
934         }
935
936         _ports.push_back (port);
937
938         return port;
939 }
940
941 void
942 PortAudioBackend::unregister_port (PortEngine::PortHandle port_handle)
943 {
944         if (!_run) {
945                 return;
946         }
947         PamPort* port = static_cast<PamPort*>(port_handle);
948         std::vector<PamPort*>::iterator i = std::find (_ports.begin (), _ports.end (), static_cast<PamPort*>(port_handle));
949         if (i == _ports.end ()) {
950                 DEBUG_PORTS("unregister_port: Failed to find port\n");
951                 return;
952         }
953         disconnect_all(port_handle);
954         _ports.erase (i);
955         delete port;
956 }
957
958 int
959 PortAudioBackend::register_system_audio_ports()
960 {
961         LatencyRange lr;
962
963         const uint32_t a_ins = _n_inputs;
964         const uint32_t a_out = _n_outputs;
965
966         // XXX PA reported stream latencies don't match measurements
967         const uint32_t portaudio_reported_input_latency =  _samples_per_period ; //  _pcmio->capture_latency();
968         const uint32_t portaudio_reported_output_latency = /* _samples_per_period + */ _pcmio->playback_latency();
969
970         /* audio ports */
971         lr.min = lr.max = portaudio_reported_input_latency + (_measure_latency ? 0 : _systemic_audio_input_latency);
972         for (uint32_t i = 0; i < a_ins; ++i) {
973                 char tmp[64];
974                 snprintf(tmp, sizeof(tmp), "system:capture_%d", i+1);
975                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
976                 if (!p) return -1;
977                 set_latency_range (p, false, lr);
978                 PortAudioPort* audio_port = static_cast<PortAudioPort*>(p);
979                 audio_port->set_pretty_name (
980                     _pcmio->get_input_channel_name (name_to_id (_input_audio_device), i));
981                 _system_inputs.push_back (audio_port);
982         }
983
984         lr.min = lr.max = portaudio_reported_output_latency + (_measure_latency ? 0 : _systemic_audio_output_latency);
985         for (uint32_t i = 0; i < a_out; ++i) {
986                 char tmp[64];
987                 snprintf(tmp, sizeof(tmp), "system:playback_%d", i+1);
988                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
989                 if (!p) return -1;
990                 set_latency_range (p, true, lr);
991                 PortAudioPort* audio_port = static_cast<PortAudioPort*>(p);
992                 audio_port->set_pretty_name (
993                     _pcmio->get_output_channel_name (name_to_id (_output_audio_device), i));
994                 _system_outputs.push_back(audio_port);
995         }
996         return 0;
997 }
998
999 int
1000 PortAudioBackend::register_system_midi_ports()
1001 {
1002         if (_midi_driver_option == get_standard_device_name(DeviceNone)) {
1003                 DEBUG_MIDI("No MIDI backend selected, not system midi ports available\n");
1004                 return 0;
1005         }
1006
1007         LatencyRange lr;
1008         lr.min = lr.max = _samples_per_period;
1009
1010         const std::vector<WinMMEMidiInputDevice*> inputs = _midiio->get_inputs();
1011
1012         for (std::vector<WinMMEMidiInputDevice*>::const_iterator i = inputs.begin ();
1013              i != inputs.end ();
1014              ++i) {
1015                 std::string port_name = "system_midi:" + (*i)->name() + " capture";
1016                 PortHandle p =
1017                     add_port (port_name,
1018                               DataType::MIDI,
1019                               static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
1020                 if (!p) return -1;
1021                 set_latency_range (p, false, lr);
1022                 PortMidiPort* midi_port = static_cast<PortMidiPort*>(p);
1023                 midi_port->set_pretty_name ((*i)->name());
1024                 _system_midi_in.push_back (midi_port);
1025                 DEBUG_MIDI (string_compose ("Registered MIDI input port: %1\n", port_name));
1026         }
1027
1028         const std::vector<WinMMEMidiOutputDevice*> outputs = _midiio->get_outputs();
1029
1030         for (std::vector<WinMMEMidiOutputDevice*>::const_iterator i = outputs.begin ();
1031              i != outputs.end ();
1032              ++i) {
1033                 std::string port_name = "system_midi:" + (*i)->name() + " playback";
1034                 PortHandle p =
1035                     add_port (port_name,
1036                               DataType::MIDI,
1037                               static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
1038                 if (!p) return -1;
1039                 set_latency_range (p, false, lr);
1040                 PortMidiPort* midi_port = static_cast<PortMidiPort*>(p);
1041                 midi_port->set_n_periods(2);
1042                 midi_port->set_pretty_name ((*i)->name());
1043                 _system_midi_out.push_back (midi_port);
1044                 DEBUG_MIDI (string_compose ("Registered MIDI output port: %1\n", port_name));
1045         }
1046         return 0;
1047 }
1048
1049 void
1050 PortAudioBackend::unregister_ports (bool system_only)
1051 {
1052         size_t i = 0;
1053         _system_inputs.clear();
1054         _system_outputs.clear();
1055         _system_midi_in.clear();
1056         _system_midi_out.clear();
1057         while (i <  _ports.size ()) {
1058                 PamPort* port = _ports[i];
1059                 if (! system_only || (port->is_physical () && port->is_terminal ())) {
1060                         port->disconnect_all ();
1061                         delete port;
1062                         _ports.erase (_ports.begin() + i);
1063                 } else {
1064                         ++i;
1065                 }
1066         }
1067 }
1068
1069 int
1070 PortAudioBackend::connect (const std::string& src, const std::string& dst)
1071 {
1072         PamPort* src_port = find_port (src);
1073         PamPort* dst_port = find_port (dst);
1074
1075         if (!src_port) {
1076                 DEBUG_PORTS(string_compose("connect: Invalid Source port: (%1)\n", src));
1077                 return -1;
1078         }
1079         if (!dst_port) {
1080                 DEBUG_PORTS(string_compose("connect: Invalid Destination port: (%1)\n", dst));
1081                 return -1;
1082         }
1083         return src_port->connect (dst_port);
1084 }
1085
1086 int
1087 PortAudioBackend::disconnect (const std::string& src, const std::string& dst)
1088 {
1089         PamPort* src_port = find_port (src);
1090         PamPort* dst_port = find_port (dst);
1091
1092         if (!src_port || !dst_port) {
1093                 DEBUG_PORTS("disconnect: Invalid Port(s)\n");
1094                 return -1;
1095         }
1096         return src_port->disconnect (dst_port);
1097 }
1098
1099 int
1100 PortAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
1101 {
1102         PamPort* dst_port = find_port (dst);
1103         if (!valid_port (src)) {
1104                 DEBUG_PORTS("connect: Invalid Source Port Handle\n");
1105                 return -1;
1106         }
1107         if (!dst_port) {
1108                 DEBUG_PORTS(string_compose("connect: Invalid Destination Port (%1)\n", dst));
1109                 return -1;
1110         }
1111         return static_cast<PamPort*>(src)->connect (dst_port);
1112 }
1113
1114 int
1115 PortAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
1116 {
1117         PamPort* dst_port = find_port (dst);
1118         if (!valid_port (src) || !dst_port) {
1119                 DEBUG_PORTS("disconnect: Invalid Port(s)\n");
1120                 return -1;
1121         }
1122         return static_cast<PamPort*>(src)->disconnect (dst_port);
1123 }
1124
1125 int
1126 PortAudioBackend::disconnect_all (PortEngine::PortHandle port)
1127 {
1128         if (!valid_port (port)) {
1129                 DEBUG_PORTS("disconnect_all: Invalid Port\n");
1130                 return -1;
1131         }
1132         static_cast<PamPort*>(port)->disconnect_all ();
1133         return 0;
1134 }
1135
1136 bool
1137 PortAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
1138 {
1139         if (!valid_port (port)) {
1140                 DEBUG_PORTS("disconnect_all: Invalid Port\n");
1141                 return false;
1142         }
1143         return static_cast<PamPort*>(port)->is_connected ();
1144 }
1145
1146 bool
1147 PortAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
1148 {
1149         PamPort* dst_port = find_port (dst);
1150         if (!valid_port (src) || !dst_port) {
1151                 DEBUG_PORTS("connected_to: Invalid Port\n");
1152                 return false;
1153         }
1154         return static_cast<PamPort*>(src)->is_connected (dst_port);
1155 }
1156
1157 bool
1158 PortAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
1159 {
1160         if (!valid_port (port)) {
1161                 DEBUG_PORTS("physically_connected: Invalid Port\n");
1162                 return false;
1163         }
1164         return static_cast<PamPort*>(port)->is_physically_connected ();
1165 }
1166
1167 int
1168 PortAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
1169 {
1170         if (!valid_port (port)) {
1171                 DEBUG_PORTS("get_connections: Invalid Port\n");
1172                 return -1;
1173         }
1174
1175         assert (0 == names.size ());
1176
1177         const std::vector<PamPort*>& connected_ports = static_cast<PamPort*>(port)->get_connections ();
1178
1179         for (std::vector<PamPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
1180                 names.push_back ((*i)->name ());
1181         }
1182
1183         return (int)names.size ();
1184 }
1185
1186 /* MIDI */
1187 int
1188 PortAudioBackend::midi_event_get (
1189                 pframes_t& timestamp,
1190                 size_t& size, uint8_t** buf, void* port_buffer,
1191                 uint32_t event_index)
1192 {
1193         if (!buf || !port_buffer) return -1;
1194         PortMidiBuffer& source = * static_cast<PortMidiBuffer*>(port_buffer);
1195         if (event_index >= source.size ()) {
1196                 return -1;
1197         }
1198         PortMidiEvent * const event = source[event_index].get ();
1199
1200         timestamp = event->timestamp ();
1201         size = event->size ();
1202         *buf = event->data ();
1203         return 0;
1204 }
1205
1206 int
1207 PortAudioBackend::midi_event_put (
1208                 void* port_buffer,
1209                 pframes_t timestamp,
1210                 const uint8_t* buffer, size_t size)
1211 {
1212         if (!buffer || !port_buffer) return -1;
1213         PortMidiBuffer& dst = * static_cast<PortMidiBuffer*>(port_buffer);
1214         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
1215                 // nevermind, ::get_buffer() sorts events
1216                 DEBUG_MIDI (string_compose ("PortMidiBuffer: unordered event: %1 > %2\n",
1217                                             (pframes_t)dst.back ()->timestamp (),
1218                                             timestamp));
1219         }
1220         dst.push_back (boost::shared_ptr<PortMidiEvent>(new PortMidiEvent (timestamp, buffer, size)));
1221         return 0;
1222 }
1223
1224 uint32_t
1225 PortAudioBackend::get_midi_event_count (void* port_buffer)
1226 {
1227         if (!port_buffer) return 0;
1228         return static_cast<PortMidiBuffer*>(port_buffer)->size ();
1229 }
1230
1231 void
1232 PortAudioBackend::midi_clear (void* port_buffer)
1233 {
1234         if (!port_buffer) return;
1235         PortMidiBuffer * buf = static_cast<PortMidiBuffer*>(port_buffer);
1236         assert (buf);
1237         buf->clear ();
1238 }
1239
1240 /* Monitoring */
1241
1242 bool
1243 PortAudioBackend::can_monitor_input () const
1244 {
1245         return false;
1246 }
1247
1248 int
1249 PortAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1250 {
1251         return -1;
1252 }
1253
1254 int
1255 PortAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1256 {
1257         return -1;
1258 }
1259
1260 bool
1261 PortAudioBackend::monitoring_input (PortEngine::PortHandle)
1262 {
1263         return false;
1264 }
1265
1266 /* Latency management */
1267
1268 void
1269 PortAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1270 {
1271         if (!valid_port (port)) {
1272                 DEBUG_PORTS("PamPort::set_latency_range (): invalid port.\n");
1273         }
1274         static_cast<PamPort*>(port)->set_latency_range (latency_range, for_playback);
1275 }
1276
1277 LatencyRange
1278 PortAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1279 {
1280         LatencyRange r;
1281         if (!valid_port (port)) {
1282                 DEBUG_PORTS("PamPort::get_latency_range (): invalid port.\n");
1283                 r.min = 0;
1284                 r.max = 0;
1285                 return r;
1286         }
1287         PamPort* p = static_cast<PamPort*>(port);
1288         assert(p);
1289
1290         r = p->latency_range (for_playback);
1291         // TODO MIDI
1292         if (p->is_physical() && p->is_terminal() && p->type() == DataType::AUDIO) {
1293                 if (p->is_input() && for_playback) {
1294                         r.min += _samples_per_period;
1295                         r.max += _samples_per_period;
1296                 }
1297                 if (p->is_output() && !for_playback) {
1298                         r.min += _samples_per_period;
1299                         r.max += _samples_per_period;
1300                 }
1301         }
1302         return r;
1303 }
1304
1305 /* Discovering physical ports */
1306
1307 bool
1308 PortAudioBackend::port_is_physical (PortEngine::PortHandle port) const
1309 {
1310         if (!valid_port (port)) {
1311                 DEBUG_PORTS("PamPort::port_is_physical (): invalid port.\n");
1312                 return false;
1313         }
1314         return static_cast<PamPort*>(port)->is_physical ();
1315 }
1316
1317 void
1318 PortAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1319 {
1320         for (size_t i = 0; i < _ports.size (); ++i) {
1321                 PamPort* port = _ports[i];
1322                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1323                         port_names.push_back (port->name ());
1324                 }
1325         }
1326 }
1327
1328 void
1329 PortAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1330 {
1331         for (size_t i = 0; i < _ports.size (); ++i) {
1332                 PamPort* port = _ports[i];
1333                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1334                         port_names.push_back (port->name ());
1335                 }
1336         }
1337 }
1338
1339 ChanCount
1340 PortAudioBackend::n_physical_outputs () const
1341 {
1342         int n_midi = 0;
1343         int n_audio = 0;
1344         for (size_t i = 0; i < _ports.size (); ++i) {
1345                 PamPort* port = _ports[i];
1346                 if (port->is_output () && port->is_physical ()) {
1347                         switch (port->type ()) {
1348                         case DataType::AUDIO:
1349                                 ++n_audio;
1350                                 break;
1351                         case DataType::MIDI:
1352                                 ++n_midi;
1353                                 break;
1354                         default:
1355                                 break;
1356                         }
1357                 }
1358         }
1359         ChanCount cc;
1360         cc.set (DataType::AUDIO, n_audio);
1361         cc.set (DataType::MIDI, n_midi);
1362         return cc;
1363 }
1364
1365 ChanCount
1366 PortAudioBackend::n_physical_inputs () const
1367 {
1368         int n_midi = 0;
1369         int n_audio = 0;
1370         for (size_t i = 0; i < _ports.size (); ++i) {
1371                 PamPort* port = _ports[i];
1372                 if (port->is_input () && port->is_physical ()) {
1373                         switch (port->type ()) {
1374                         case DataType::AUDIO:
1375                                 ++n_audio;
1376                                 break;
1377                         case DataType::MIDI:
1378                                 ++n_midi;
1379                                 break;
1380                         default:
1381                                 break;
1382                         }
1383                 }
1384         }
1385         ChanCount cc;
1386         cc.set (DataType::AUDIO, n_audio);
1387         cc.set (DataType::MIDI, n_midi);
1388         return cc;
1389 }
1390
1391 /* Getting access to the data buffer for a port */
1392
1393 void*
1394 PortAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1395 {
1396         if (!port || !valid_port (port)) return NULL;
1397         return static_cast<PamPort*>(port)->get_buffer (nframes);
1398 }
1399
1400
1401 void *
1402 PortAudioBackend::main_blocking_process_thread ()
1403 {
1404         AudioEngine::thread_init_callback (this);
1405         _active = true;
1406         _processed_samples = 0;
1407
1408         uint64_t clock1, clock2;
1409         int64_t min_elapsed_us = 1000000;
1410         int64_t max_elapsed_us = 0;
1411         const int64_t nomial_time = 1e6 * _samples_per_period / _samplerate;
1412         // const int64_t nomial_time = m_cycle_timer.get_length_us();
1413
1414         manager.registration_callback();
1415         manager.graph_order_callback();
1416
1417         if (_pcmio->start_stream() != PortAudioIO::NoError) {
1418                 _pcmio->close_stream ();
1419                 _active = false;
1420                 engine.halted_callback(get_error_string(AudioDeviceIOError).c_str());
1421         }
1422
1423 #ifdef USE_MMCSS_THREAD_PRIORITIES
1424         HANDLE task_handle;
1425
1426         mmcss::set_thread_characteristics ("Pro Audio", &task_handle);
1427         if (!mmcss::set_thread_priority(task_handle, mmcss::AVRT_PRIORITY_NORMAL)) {
1428                 PBD::warning << get_error_string(SettingAudioThreadPriorityError)
1429                              << endmsg;
1430         }
1431 #endif
1432
1433         DWORD tid = GetCurrentThreadId ();
1434         DEBUG_THREADS (string_compose ("Process Thread Master ID: %1\n", tid));
1435
1436         while (_run) {
1437
1438                 if (_freewheeling != _freewheel) {
1439                         _freewheel = _freewheeling;
1440                         engine.freewheel_callback (_freewheel);
1441                 }
1442
1443                 if (!_freewheel) {
1444
1445                         switch (_pcmio->next_cycle (_samples_per_period)) {
1446                         case 0: // OK
1447                                 break;
1448                         case 1:
1449                                 DEBUG_AUDIO("PortAudio: Xrun\n");
1450                                 engine.Xrun();
1451                                 break;
1452                         default:
1453                                 PBD::error << get_error_string(AudioDeviceIOError) << endmsg;
1454                                 break;
1455                         }
1456
1457                         uint32_t i = 0;
1458                         clock1 = utils::get_microseconds ();
1459
1460                         /* get audio */
1461                         i = 0;
1462                         for (std::vector<PamPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++i) {
1463                                 _pcmio->get_capture_channel (i, (float*)((*it)->get_buffer(_samples_per_period)), _samples_per_period);
1464                         }
1465
1466                         /* de-queue incoming midi*/
1467                         i=0;
1468                         for (std::vector<PamPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++i) {
1469                                 PortMidiBuffer* mbuf = static_cast<PortMidiBuffer*>((*it)->get_buffer(0));
1470                                 mbuf->clear();
1471                                 uint64_t timestamp;
1472                                 pframes_t sample_offset;
1473                                 uint8_t data[256];
1474                                 size_t size = sizeof(data);
1475                                 while (_midiio->dequeue_input_event (i,
1476                                                                      m_cycle_timer.get_start (),
1477                                                                      m_cycle_timer.get_next_start (),
1478                                                                      timestamp,
1479                                                                      data,
1480                                                                      size)) {
1481                                         sample_offset = m_cycle_timer.samples_since_cycle_start (timestamp);
1482                                         midi_event_put (mbuf, sample_offset, data, size);
1483                                         DEBUG_MIDI (string_compose ("Dequeuing incoming MIDI data for device: %1 "
1484                                                                     "sample_offset: %2 timestamp: %3, size: %4\n",
1485                                                                     _midiio->get_inputs ()[i]->name (),
1486                                                                     sample_offset,
1487                                                                     timestamp,
1488                                                                     size));
1489                                         size = sizeof(data);
1490                                 }
1491                         }
1492
1493                         /* clear output buffers */
1494                         for (std::vector<PamPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it) {
1495                                 memset ((*it)->get_buffer (_samples_per_period), 0, _samples_per_period * sizeof (Sample));
1496                         }
1497
1498                         m_last_cycle_start = m_cycle_timer.get_start ();
1499                         m_cycle_timer.reset_start(utils::get_microseconds());
1500                         m_cycle_count++;
1501
1502                         uint64_t cycle_diff_us = (m_cycle_timer.get_start () - m_last_cycle_start);
1503                         int64_t deviation_us = (cycle_diff_us - m_cycle_timer.get_length_us());
1504                         m_total_deviation_us += ::llabs(deviation_us);
1505                         m_max_deviation_us =
1506                                 std::max (m_max_deviation_us, (uint64_t)::llabs (deviation_us));
1507
1508                         if ((m_cycle_count % 1000) == 0) {
1509                                 uint64_t mean_deviation_us = m_total_deviation_us / m_cycle_count;
1510                                 DEBUG_TIMING (
1511                                     string_compose ("Mean avg cycle deviation: %1(ms), max %2(ms)\n",
1512                                                     mean_deviation_us * 1e-3,
1513                                                     m_max_deviation_us * 1e-3));
1514                         }
1515
1516                         if (::llabs(deviation_us) > m_cycle_timer.get_length_us()) {
1517                                 DEBUG_TIMING (string_compose (
1518                                     "time between process(ms): %1, Est(ms): %2, Dev(ms): %3\n",
1519                                     cycle_diff_us * 1e-3,
1520                                     m_cycle_timer.get_length_us () * 1e-3,
1521                                     deviation_us * 1e-3));
1522                         }
1523
1524                         /* call engine process callback */
1525                         if (engine.process_callback (_samples_per_period)) {
1526                                 _pcmio->close_stream ();
1527                                 _active = false;
1528                                 return 0;
1529                         }
1530                         /* mixdown midi */
1531                         for (std::vector<PamPort*>::iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it) {
1532                                 static_cast<PortMidiPort*>(*it)->next_period();
1533                         }
1534                         /* queue outgoing midi */
1535                         i = 0;
1536                         for (std::vector<PamPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it, ++i) {
1537                                 const PortMidiBuffer* src = static_cast<const PortMidiPort*>(*it)->const_buffer();
1538
1539                                 for (PortMidiBuffer::const_iterator mit = src->begin (); mit != src->end (); ++mit) {
1540                                         uint64_t timestamp =
1541                                             m_cycle_timer.timestamp_from_sample_offset ((*mit)->timestamp ());
1542                                         DEBUG_MIDI (
1543                                             string_compose ("Queuing outgoing MIDI data for device: "
1544                                                             "%1 sample_offset: %2 timestamp: %3, size: %4\n",
1545                                                             _midiio->get_outputs ()[i]->name (),
1546                                                             (*mit)->timestamp (),
1547                                                             timestamp,
1548                                                             (*mit)->size ()));
1549                                         _midiio->enqueue_output_event (
1550                                             i, timestamp, (*mit)->data (), (*mit)->size ());
1551                                 }
1552                         }
1553
1554                         /* write back audio */
1555                         i = 0;
1556                         for (std::vector<PamPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it, ++i) {
1557                                 _pcmio->set_playback_channel (i, (float const*)(*it)->get_buffer (_samples_per_period), _samples_per_period);
1558                         }
1559
1560                         _processed_samples += _samples_per_period;
1561
1562                         /* calculate DSP load */
1563                         clock2 = utils::get_microseconds ();
1564                         const int64_t elapsed_time = clock2 - clock1;
1565                         _dsp_load = elapsed_time / (float) nomial_time;
1566
1567                         max_elapsed_us = std::max (elapsed_time, max_elapsed_us);
1568                         min_elapsed_us = std::min (elapsed_time, min_elapsed_us);
1569                         if ((m_cycle_count % 1000) == 0) {
1570                                 DEBUG_TIMING (
1571                                     string_compose ("Elapsed process time(usecs) max: %1, min: %2\n",
1572                                                     max_elapsed_us,
1573                                                     min_elapsed_us));
1574                         }
1575
1576                 } else {
1577                         // Freewheelin'
1578
1579                         // zero audio input buffers
1580                         for (std::vector<PamPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
1581                                 memset ((*it)->get_buffer (_samples_per_period), 0, _samples_per_period * sizeof (Sample));
1582                         }
1583
1584                         clock1 = utils::get_microseconds ();
1585
1586                         // TODO clear midi or stop midi recv when entering fwheelin'
1587
1588                         if (engine.process_callback (_samples_per_period)) {
1589                                 _pcmio->close_stream();
1590                                 _active = false;
1591                                 return 0;
1592                         }
1593
1594                         // drop all outgoing MIDI messages
1595                         for (std::vector<PamPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it) {
1596                                         void *bptr = (*it)->get_buffer(0);
1597                                         midi_clear(bptr);
1598                         }
1599
1600                         _dsp_load = 1.0;
1601                         Glib::usleep (100); // don't hog cpu
1602                 }
1603
1604                 bool connections_changed = false;
1605                 bool ports_changed = false;
1606                 if (!pthread_mutex_trylock (&_port_callback_mutex)) {
1607                         if (_port_change_flag) {
1608                                 ports_changed = true;
1609                                 _port_change_flag = false;
1610                         }
1611                         if (!_port_connection_queue.empty ()) {
1612                                 connections_changed = true;
1613                         }
1614                         while (!_port_connection_queue.empty ()) {
1615                                 PortConnectData *c = _port_connection_queue.back ();
1616                                 manager.connect_callback (c->a, c->b, c->c);
1617                                 _port_connection_queue.pop_back ();
1618                                 delete c;
1619                         }
1620                         pthread_mutex_unlock (&_port_callback_mutex);
1621                 }
1622                 if (ports_changed) {
1623                         manager.registration_callback();
1624                 }
1625                 if (connections_changed) {
1626                         manager.graph_order_callback();
1627                 }
1628                 if (connections_changed || ports_changed) {
1629                         engine.latency_callback(false);
1630                         engine.latency_callback(true);
1631                 }
1632
1633         }
1634         _pcmio->close_stream();
1635         _active = false;
1636         if (_run) {
1637                 engine.halted_callback(get_error_string(AudioDeviceIOError).c_str());
1638         }
1639
1640 #ifdef USE_MMCSS_THREAD_PRIORITIES
1641         mmcss::revert_thread_characteristics (task_handle);
1642 #endif
1643
1644         return 0;
1645 }
1646
1647
1648 /******************************************************************************/
1649
1650 static boost::shared_ptr<PortAudioBackend> _instance;
1651
1652 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
1653 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
1654 static int deinstantiate ();
1655 static bool already_configured ();
1656 static bool available ();
1657
1658 static ARDOUR::AudioBackendInfo _descriptor = {
1659         "PortAudio",
1660         instantiate,
1661         deinstantiate,
1662         backend_factory,
1663         already_configured,
1664         available
1665 };
1666
1667 static boost::shared_ptr<AudioBackend>
1668 backend_factory (AudioEngine& e)
1669 {
1670         if (!_instance) {
1671                 _instance.reset (new PortAudioBackend (e, _descriptor));
1672         }
1673         return _instance;
1674 }
1675
1676 static int
1677 instantiate (const std::string& arg1, const std::string& /* arg2 */)
1678 {
1679         s_instance_name = arg1;
1680         return 0;
1681 }
1682
1683 static int
1684 deinstantiate ()
1685 {
1686         _instance.reset ();
1687         return 0;
1688 }
1689
1690 static bool
1691 already_configured ()
1692 {
1693         return false;
1694 }
1695
1696 static bool
1697 available ()
1698 {
1699         return true;
1700 }
1701
1702 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
1703 {
1704         return &_descriptor;
1705 }
1706
1707
1708 /******************************************************************************/
1709 PamPort::PamPort (PortAudioBackend &b, const std::string& name, PortFlags flags)
1710         : _osx_backend (b)
1711         , _name  (name)
1712         , _flags (flags)
1713 {
1714         _capture_latency_range.min = 0;
1715         _capture_latency_range.max = 0;
1716         _playback_latency_range.min = 0;
1717         _playback_latency_range.max = 0;
1718 }
1719
1720 PamPort::~PamPort () {
1721         disconnect_all ();
1722 }
1723
1724
1725 int PamPort::connect (PamPort *port)
1726 {
1727         if (!port) {
1728                 DEBUG_PORTS("PamPort::connect (): invalid (null) port\n");
1729                 return -1;
1730         }
1731
1732         if (type () != port->type ()) {
1733                 DEBUG_PORTS("PamPort::connect (): wrong port-type\n");
1734                 return -1;
1735         }
1736
1737         if (is_output () && port->is_output ()) {
1738                 DEBUG_PORTS("PamPort::connect (): cannot inter-connect output ports.\n");
1739                 return -1;
1740         }
1741
1742         if (is_input () && port->is_input ()) {
1743                 DEBUG_PORTS("PamPort::connect (): cannot inter-connect input ports.\n");
1744                 return -1;
1745         }
1746
1747         if (this == port) {
1748                 DEBUG_PORTS("PamPort::connect (): cannot self-connect ports.\n");
1749                 return -1;
1750         }
1751
1752         if (is_connected (port)) {
1753 #if 0 // don't bother to warn about this for now. just ignore it
1754                 PBD::error << _("PamPort::connect (): ports are already connected:")
1755                         << " (" << name () << ") -> (" << port->name () << ")"
1756                         << endmsg;
1757 #endif
1758                 return -1;
1759         }
1760
1761         _connect (port, true);
1762         return 0;
1763 }
1764
1765
1766 void PamPort::_connect (PamPort *port, bool callback)
1767 {
1768         _connections.push_back (port);
1769         if (callback) {
1770                 port->_connect (this, false);
1771                 _osx_backend.port_connect_callback (name(),  port->name(), true);
1772         }
1773 }
1774
1775 int PamPort::disconnect (PamPort *port)
1776 {
1777         if (!port) {
1778                 DEBUG_PORTS("PamPort::disconnect (): invalid (null) port\n");
1779                 return -1;
1780         }
1781
1782         if (!is_connected (port)) {
1783                 DEBUG_PORTS(string_compose(
1784                     "PamPort::disconnect (): ports are not connected: (%1) -> (%2)\n",
1785                     name(),
1786                     port->name()));
1787                 return -1;
1788         }
1789         _disconnect (port, true);
1790         return 0;
1791 }
1792
1793 void PamPort::_disconnect (PamPort *port, bool callback)
1794 {
1795         std::vector<PamPort*>::iterator it = std::find (_connections.begin (), _connections.end (), port);
1796
1797         assert (it != _connections.end ());
1798
1799         _connections.erase (it);
1800
1801         if (callback) {
1802                 port->_disconnect (this, false);
1803                 _osx_backend.port_connect_callback (name(),  port->name(), false);
1804         }
1805 }
1806
1807
1808 void PamPort::disconnect_all ()
1809 {
1810         while (!_connections.empty ()) {
1811                 _connections.back ()->_disconnect (this, false);
1812                 _osx_backend.port_connect_callback (name(),  _connections.back ()->name(), false);
1813                 _connections.pop_back ();
1814         }
1815 }
1816
1817 bool
1818 PamPort::is_connected (const PamPort *port) const
1819 {
1820         return std::find (_connections.begin (), _connections.end (), port) != _connections.end ();
1821 }
1822
1823 bool PamPort::is_physically_connected () const
1824 {
1825         for (std::vector<PamPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
1826                 if ((*it)->is_physical ()) {
1827                         return true;
1828                 }
1829         }
1830         return false;
1831 }
1832
1833 /******************************************************************************/
1834
1835 PortAudioPort::PortAudioPort (PortAudioBackend &b, const std::string& name, PortFlags flags)
1836         : PamPort (b, name, flags)
1837 {
1838         memset (_buffer, 0, sizeof (_buffer));
1839 #ifndef PLATFORM_WINDOWS
1840         mlock(_buffer, sizeof (_buffer));
1841 #endif
1842 }
1843
1844 PortAudioPort::~PortAudioPort () { }
1845
1846 void* PortAudioPort::get_buffer (pframes_t n_samples)
1847 {
1848         if (is_input ()) {
1849                 std::vector<PamPort*>::const_iterator it = get_connections ().begin ();
1850                 if (it == get_connections ().end ()) {
1851                         memset (_buffer, 0, n_samples * sizeof (Sample));
1852                 } else {
1853                         PortAudioPort const * source = static_cast<const PortAudioPort*>(*it);
1854                         assert (source && source->is_output ());
1855                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
1856                         while (++it != get_connections ().end ()) {
1857                                 source = static_cast<const PortAudioPort*>(*it);
1858                                 assert (source && source->is_output ());
1859                                 Sample* dst = buffer ();
1860                                 const Sample* src = source->const_buffer ();
1861                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
1862                                         *dst += *src;
1863                                 }
1864                         }
1865                 }
1866         }
1867         return _buffer;
1868 }
1869
1870
1871 PortMidiPort::PortMidiPort (PortAudioBackend &b, const std::string& name, PortFlags flags)
1872         : PamPort (b, name, flags)
1873         , _n_periods (1)
1874         , _bufperiod (0)
1875 {
1876         _buffer[0].clear ();
1877         _buffer[1].clear ();
1878 }
1879
1880 PortMidiPort::~PortMidiPort () { }
1881
1882 struct MidiEventSorter {
1883         bool operator() (const boost::shared_ptr<PortMidiEvent>& a, const boost::shared_ptr<PortMidiEvent>& b) {
1884                 return *a < *b;
1885         }
1886 };
1887
1888 void* PortMidiPort::get_buffer (pframes_t /* nframes */)
1889 {
1890         if (is_input ()) {
1891                 (_buffer[_bufperiod]).clear ();
1892                 for (std::vector<PamPort*>::const_iterator i = get_connections ().begin ();
1893                                 i != get_connections ().end ();
1894                                 ++i) {
1895                         const PortMidiBuffer * src = static_cast<const PortMidiPort*>(*i)->const_buffer ();
1896                         for (PortMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
1897                                 (_buffer[_bufperiod]).push_back (boost::shared_ptr<PortMidiEvent>(new PortMidiEvent (**it)));
1898                         }
1899                 }
1900                 std::sort ((_buffer[_bufperiod]).begin (), (_buffer[_bufperiod]).end (), MidiEventSorter());
1901         }
1902         return &(_buffer[_bufperiod]);
1903 }
1904
1905 PortMidiEvent::PortMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
1906         : _size (size)
1907         , _timestamp (timestamp)
1908         , _data (0)
1909 {
1910         if (size > 0) {
1911                 _data = (uint8_t*) malloc (size);
1912                 memcpy (_data, data, size);
1913         }
1914 }
1915
1916 PortMidiEvent::PortMidiEvent (const PortMidiEvent& other)
1917         : _size (other.size ())
1918         , _timestamp (other.timestamp ())
1919         , _data (0)
1920 {
1921         if (other.size () && other.const_data ()) {
1922                 _data = (uint8_t*) malloc (other.size ());
1923                 memcpy (_data, other.const_data (), other.size ());
1924         }
1925 };
1926
1927 PortMidiEvent::~PortMidiEvent () {
1928         free (_data);
1929 };