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