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