Use pretty name infrastructure to display MIDI device name
[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 int
796 PortAudioBackend::get_port_property (PortHandle port,
797                                      const std::string& key,
798                                      std::string& value,
799                                      std::string& type) const
800 {
801         if (!valid_port (port)) {
802                 PBD::error << _ ("PortAudioBackend::get_port_name: Invalid Port(s)")
803                            << endmsg;
804                 return -1;
805         }
806
807         if (key == "http://jackaudio.org/metadata/pretty-name") {
808                 type = "";
809                 value = static_cast<PamPort*>(port)->pretty_name ();
810                 if (!value.empty()) {
811                         return 0;
812                 }
813         }
814         return -1;
815 }
816
817 PortEngine::PortHandle
818 PortAudioBackend::get_port_by_name (const std::string& name) const
819 {
820         PortHandle port = (PortHandle) find_port (name);
821         return port;
822 }
823
824 int
825 PortAudioBackend::get_ports (
826                 const std::string& port_name_pattern,
827                 DataType type, PortFlags flags,
828                 std::vector<std::string>& port_names) const
829 {
830         int rv = 0;
831         regex_t port_regex;
832         bool use_regexp = false;
833         if (port_name_pattern.size () > 0) {
834                 if (!regcomp (&port_regex, port_name_pattern.c_str (), REG_EXTENDED|REG_NOSUB)) {
835                         use_regexp = true;
836                 }
837         }
838         for (size_t i = 0; i < _ports.size (); ++i) {
839                 PamPort* port = _ports[i];
840                 if ((port->type () == type) && flags == (port->flags () & flags)) {
841                         if (!use_regexp || !regexec (&port_regex, port->name ().c_str (), 0, NULL, 0)) {
842                                 port_names.push_back (port->name ());
843                                 ++rv;
844                         }
845                 }
846         }
847         if (use_regexp) {
848                 regfree (&port_regex);
849         }
850         return rv;
851 }
852
853 DataType
854 PortAudioBackend::port_data_type (PortEngine::PortHandle port) const
855 {
856         if (!valid_port (port)) {
857                 return DataType::NIL;
858         }
859         return static_cast<PamPort*>(port)->type ();
860 }
861
862 PortEngine::PortHandle
863 PortAudioBackend::register_port (
864                 const std::string& name,
865                 ARDOUR::DataType type,
866                 ARDOUR::PortFlags flags)
867 {
868         if (name.size () == 0) { return 0; }
869         if (flags & IsPhysical) { return 0; }
870         return add_port (_instance_name + ":" + name, type, flags);
871 }
872
873 PortEngine::PortHandle
874 PortAudioBackend::add_port (
875                 const std::string& name,
876                 ARDOUR::DataType type,
877                 ARDOUR::PortFlags flags)
878 {
879         assert(name.size ());
880         if (find_port (name)) {
881                 PBD::error << _("PortAudioBackend::register_port: Port already exists:")
882                                 << " (" << name << ")" << endmsg;
883                 return 0;
884         }
885         PamPort* port = NULL;
886         switch (type) {
887                 case DataType::AUDIO:
888                         port = new PortAudioPort (*this, name, flags);
889                         break;
890                 case DataType::MIDI:
891                         port = new PortMidiPort (*this, name, flags);
892                         break;
893                 default:
894                         PBD::error << _("PortAudioBackend::register_port: Invalid Data Type.") << endmsg;
895                         return 0;
896         }
897
898         _ports.push_back (port);
899
900         return port;
901 }
902
903 void
904 PortAudioBackend::unregister_port (PortEngine::PortHandle port_handle)
905 {
906         if (!_run) {
907                 return;
908         }
909         PamPort* port = static_cast<PamPort*>(port_handle);
910         std::vector<PamPort*>::iterator i = std::find (_ports.begin (), _ports.end (), static_cast<PamPort*>(port_handle));
911         if (i == _ports.end ()) {
912                 PBD::error << _("PortAudioBackend::unregister_port: Failed to find port") << endmsg;
913                 return;
914         }
915         disconnect_all(port_handle);
916         _ports.erase (i);
917         delete port;
918 }
919
920 int
921 PortAudioBackend::register_system_audio_ports()
922 {
923         LatencyRange lr;
924
925         const uint32_t a_ins = _n_inputs;
926         const uint32_t a_out = _n_outputs;
927
928         // XXX PA reported stream latencies don't match measurements
929         const uint32_t portaudio_reported_input_latency =  _samples_per_period ; //  _pcmio->capture_latency();
930         const uint32_t portaudio_reported_output_latency = /* _samples_per_period + */ _pcmio->playback_latency();
931
932         /* audio ports */
933         lr.min = lr.max = portaudio_reported_input_latency + (_measure_latency ? 0 : _systemic_audio_input_latency);
934         for (uint32_t i = 0; i < a_ins; ++i) {
935                 char tmp[64];
936                 snprintf(tmp, sizeof(tmp), "system:capture_%d", i+1);
937                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
938                 if (!p) return -1;
939                 set_latency_range (p, false, lr);
940                 PortAudioPort* audio_port = static_cast<PortAudioPort*>(p);
941                 audio_port->set_pretty_name (
942                     _pcmio->get_input_channel_name (name_to_id (_input_audio_device), i));
943                 _system_inputs.push_back (audio_port);
944         }
945
946         lr.min = lr.max = portaudio_reported_output_latency + (_measure_latency ? 0 : _systemic_audio_output_latency);
947         for (uint32_t i = 0; i < a_out; ++i) {
948                 char tmp[64];
949                 snprintf(tmp, sizeof(tmp), "system:playback_%d", i+1);
950                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
951                 if (!p) return -1;
952                 set_latency_range (p, true, lr);
953                 PortAudioPort* audio_port = static_cast<PortAudioPort*>(p);
954                 audio_port->set_pretty_name (
955                     _pcmio->get_output_channel_name (name_to_id (_output_audio_device), i));
956                 _system_outputs.push_back(audio_port);
957         }
958         return 0;
959 }
960
961 int
962 PortAudioBackend::register_system_midi_ports()
963 {
964         if (_midi_driver_option == _("None")) {
965                 DEBUG_MIDI ("No MIDI backend selected, not system midi ports available\n");
966                 return 0;
967         }
968
969         LatencyRange lr;
970         lr.min = lr.max = _samples_per_period;
971
972         const std::vector<WinMMEMidiInputDevice*> inputs = _midiio->get_inputs();
973
974         for (std::vector<WinMMEMidiInputDevice*>::const_iterator i = inputs.begin ();
975              i != inputs.end ();
976              ++i) {
977                 std::string port_name = "system_midi:" + (*i)->name() + " capture";
978                 PortHandle p =
979                     add_port (port_name,
980                               DataType::MIDI,
981                               static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
982                 if (!p) return -1;
983                 set_latency_range (p, false, lr);
984                 PortMidiPort* midi_port = static_cast<PortMidiPort*>(p);
985                 midi_port->set_pretty_name ((*i)->name());
986                 _system_midi_in.push_back (midi_port);
987                 DEBUG_MIDI (string_compose ("Registered MIDI input port: %1\n", port_name));
988         }
989
990         const std::vector<WinMMEMidiOutputDevice*> outputs = _midiio->get_outputs();
991
992         for (std::vector<WinMMEMidiOutputDevice*>::const_iterator i = outputs.begin ();
993              i != outputs.end ();
994              ++i) {
995                 std::string port_name = "system_midi:" + (*i)->name() + " playback";
996                 PortHandle p =
997                     add_port (port_name,
998                               DataType::MIDI,
999                               static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
1000                 if (!p) return -1;
1001                 set_latency_range (p, false, lr);
1002                 PortMidiPort* midi_port = static_cast<PortMidiPort*>(p);
1003                 midi_port->set_n_periods(2);
1004                 midi_port->set_pretty_name ((*i)->name());
1005                 _system_midi_out.push_back (midi_port);
1006                 DEBUG_MIDI (string_compose ("Registered MIDI output port: %1\n", port_name));
1007         }
1008         return 0;
1009 }
1010
1011 void
1012 PortAudioBackend::unregister_ports (bool system_only)
1013 {
1014         size_t i = 0;
1015         _system_inputs.clear();
1016         _system_outputs.clear();
1017         _system_midi_in.clear();
1018         _system_midi_out.clear();
1019         while (i <  _ports.size ()) {
1020                 PamPort* port = _ports[i];
1021                 if (! system_only || (port->is_physical () && port->is_terminal ())) {
1022                         port->disconnect_all ();
1023                         delete port;
1024                         _ports.erase (_ports.begin() + i);
1025                 } else {
1026                         ++i;
1027                 }
1028         }
1029 }
1030
1031 int
1032 PortAudioBackend::connect (const std::string& src, const std::string& dst)
1033 {
1034         PamPort* src_port = find_port (src);
1035         PamPort* dst_port = find_port (dst);
1036
1037         if (!src_port) {
1038                 PBD::error << _("PortAudioBackend::connect: Invalid Source port:")
1039                                 << " (" << src <<")" << endmsg;
1040                 return -1;
1041         }
1042         if (!dst_port) {
1043                 PBD::error << _("PortAudioBackend::connect: Invalid Destination port:")
1044                         << " (" << dst <<")" << endmsg;
1045                 return -1;
1046         }
1047         return src_port->connect (dst_port);
1048 }
1049
1050 int
1051 PortAudioBackend::disconnect (const std::string& src, const std::string& dst)
1052 {
1053         PamPort* src_port = find_port (src);
1054         PamPort* dst_port = find_port (dst);
1055
1056         if (!src_port || !dst_port) {
1057                 PBD::error << _("PortAudioBackend::disconnect: Invalid Port(s)") << endmsg;
1058                 return -1;
1059         }
1060         return src_port->disconnect (dst_port);
1061 }
1062
1063 int
1064 PortAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
1065 {
1066         PamPort* dst_port = find_port (dst);
1067         if (!valid_port (src)) {
1068                 PBD::error << _("PortAudioBackend::connect: Invalid Source Port Handle") << endmsg;
1069                 return -1;
1070         }
1071         if (!dst_port) {
1072                 PBD::error << _("PortAudioBackend::connect: Invalid Destination Port")
1073                         << " (" << dst << ")" << endmsg;
1074                 return -1;
1075         }
1076         return static_cast<PamPort*>(src)->connect (dst_port);
1077 }
1078
1079 int
1080 PortAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
1081 {
1082         PamPort* dst_port = find_port (dst);
1083         if (!valid_port (src) || !dst_port) {
1084                 PBD::error << _("PortAudioBackend::disconnect: Invalid Port(s)") << endmsg;
1085                 return -1;
1086         }
1087         return static_cast<PamPort*>(src)->disconnect (dst_port);
1088 }
1089
1090 int
1091 PortAudioBackend::disconnect_all (PortEngine::PortHandle port)
1092 {
1093         if (!valid_port (port)) {
1094                 PBD::error << _("PortAudioBackend::disconnect_all: Invalid Port") << endmsg;
1095                 return -1;
1096         }
1097         static_cast<PamPort*>(port)->disconnect_all ();
1098         return 0;
1099 }
1100
1101 bool
1102 PortAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
1103 {
1104         if (!valid_port (port)) {
1105                 PBD::error << _("PortAudioBackend::disconnect_all: Invalid Port") << endmsg;
1106                 return false;
1107         }
1108         return static_cast<PamPort*>(port)->is_connected ();
1109 }
1110
1111 bool
1112 PortAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
1113 {
1114         PamPort* dst_port = find_port (dst);
1115         if (!valid_port (src) || !dst_port) {
1116                 PBD::error << _("PortAudioBackend::connected_to: Invalid Port") << endmsg;
1117                 return false;
1118         }
1119         return static_cast<PamPort*>(src)->is_connected (dst_port);
1120 }
1121
1122 bool
1123 PortAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
1124 {
1125         if (!valid_port (port)) {
1126                 PBD::error << _("PortAudioBackend::physically_connected: Invalid Port") << endmsg;
1127                 return false;
1128         }
1129         return static_cast<PamPort*>(port)->is_physically_connected ();
1130 }
1131
1132 int
1133 PortAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
1134 {
1135         if (!valid_port (port)) {
1136                 PBD::error << _("PortAudioBackend::get_connections: Invalid Port") << endmsg;
1137                 return -1;
1138         }
1139
1140         assert (0 == names.size ());
1141
1142         const std::vector<PamPort*>& connected_ports = static_cast<PamPort*>(port)->get_connections ();
1143
1144         for (std::vector<PamPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
1145                 names.push_back ((*i)->name ());
1146         }
1147
1148         return (int)names.size ();
1149 }
1150
1151 /* MIDI */
1152 int
1153 PortAudioBackend::midi_event_get (
1154                 pframes_t& timestamp,
1155                 size_t& size, uint8_t** buf, void* port_buffer,
1156                 uint32_t event_index)
1157 {
1158         if (!buf || !port_buffer) return -1;
1159         PortMidiBuffer& source = * static_cast<PortMidiBuffer*>(port_buffer);
1160         if (event_index >= source.size ()) {
1161                 return -1;
1162         }
1163         PortMidiEvent * const event = source[event_index].get ();
1164
1165         timestamp = event->timestamp ();
1166         size = event->size ();
1167         *buf = event->data ();
1168         return 0;
1169 }
1170
1171 int
1172 PortAudioBackend::midi_event_put (
1173                 void* port_buffer,
1174                 pframes_t timestamp,
1175                 const uint8_t* buffer, size_t size)
1176 {
1177         if (!buffer || !port_buffer) return -1;
1178         PortMidiBuffer& dst = * static_cast<PortMidiBuffer*>(port_buffer);
1179         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
1180                 // nevermind, ::get_buffer() sorts events
1181                 DEBUG_MIDI (string_compose ("PortMidiBuffer: unordered event: %1 > %2\n",
1182                                             (pframes_t)dst.back ()->timestamp (),
1183                                             timestamp));
1184         }
1185         dst.push_back (boost::shared_ptr<PortMidiEvent>(new PortMidiEvent (timestamp, buffer, size)));
1186         return 0;
1187 }
1188
1189 uint32_t
1190 PortAudioBackend::get_midi_event_count (void* port_buffer)
1191 {
1192         if (!port_buffer) return 0;
1193         return static_cast<PortMidiBuffer*>(port_buffer)->size ();
1194 }
1195
1196 void
1197 PortAudioBackend::midi_clear (void* port_buffer)
1198 {
1199         if (!port_buffer) return;
1200         PortMidiBuffer * buf = static_cast<PortMidiBuffer*>(port_buffer);
1201         assert (buf);
1202         buf->clear ();
1203 }
1204
1205 /* Monitoring */
1206
1207 bool
1208 PortAudioBackend::can_monitor_input () const
1209 {
1210         return false;
1211 }
1212
1213 int
1214 PortAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1215 {
1216         return -1;
1217 }
1218
1219 int
1220 PortAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1221 {
1222         return -1;
1223 }
1224
1225 bool
1226 PortAudioBackend::monitoring_input (PortEngine::PortHandle)
1227 {
1228         return false;
1229 }
1230
1231 /* Latency management */
1232
1233 void
1234 PortAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1235 {
1236         if (!valid_port (port)) {
1237                 PBD::error << _("PamPort::set_latency_range (): invalid port.") << endmsg;
1238         }
1239         static_cast<PamPort*>(port)->set_latency_range (latency_range, for_playback);
1240 }
1241
1242 LatencyRange
1243 PortAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1244 {
1245         LatencyRange r;
1246         if (!valid_port (port)) {
1247                 PBD::error << _("PamPort::get_latency_range (): invalid port.") << endmsg;
1248                 r.min = 0;
1249                 r.max = 0;
1250                 return r;
1251         }
1252         PamPort* p = static_cast<PamPort*>(port);
1253         assert(p);
1254
1255         r = p->latency_range (for_playback);
1256         // TODO MIDI
1257         if (p->is_physical() && p->is_terminal() && p->type() == DataType::AUDIO) {
1258                 if (p->is_input() && for_playback) {
1259                         r.min += _samples_per_period;
1260                         r.max += _samples_per_period;
1261                 }
1262                 if (p->is_output() && !for_playback) {
1263                         r.min += _samples_per_period;
1264                         r.max += _samples_per_period;
1265                 }
1266         }
1267         return r;
1268 }
1269
1270 /* Discovering physical ports */
1271
1272 bool
1273 PortAudioBackend::port_is_physical (PortEngine::PortHandle port) const
1274 {
1275         if (!valid_port (port)) {
1276                 PBD::error << _("PamPort::port_is_physical (): invalid port.") << endmsg;
1277                 return false;
1278         }
1279         return static_cast<PamPort*>(port)->is_physical ();
1280 }
1281
1282 void
1283 PortAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1284 {
1285         for (size_t i = 0; i < _ports.size (); ++i) {
1286                 PamPort* port = _ports[i];
1287                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1288                         port_names.push_back (port->name ());
1289                 }
1290         }
1291 }
1292
1293 void
1294 PortAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1295 {
1296         for (size_t i = 0; i < _ports.size (); ++i) {
1297                 PamPort* port = _ports[i];
1298                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1299                         port_names.push_back (port->name ());
1300                 }
1301         }
1302 }
1303
1304 ChanCount
1305 PortAudioBackend::n_physical_outputs () const
1306 {
1307         int n_midi = 0;
1308         int n_audio = 0;
1309         for (size_t i = 0; i < _ports.size (); ++i) {
1310                 PamPort* port = _ports[i];
1311                 if (port->is_output () && port->is_physical ()) {
1312                         switch (port->type ()) {
1313                                 case DataType::AUDIO: ++n_audio; break;
1314                                 case DataType::MIDI: ++n_midi; break;
1315                                 default: break;
1316                         }
1317                 }
1318         }
1319         ChanCount cc;
1320         cc.set (DataType::AUDIO, n_audio);
1321         cc.set (DataType::MIDI, n_midi);
1322         return cc;
1323 }
1324
1325 ChanCount
1326 PortAudioBackend::n_physical_inputs () const
1327 {
1328         int n_midi = 0;
1329         int n_audio = 0;
1330         for (size_t i = 0; i < _ports.size (); ++i) {
1331                 PamPort* port = _ports[i];
1332                 if (port->is_input () && port->is_physical ()) {
1333                         switch (port->type ()) {
1334                                 case DataType::AUDIO: ++n_audio; break;
1335                                 case DataType::MIDI: ++n_midi; break;
1336                                 default: break;
1337                         }
1338                 }
1339         }
1340         ChanCount cc;
1341         cc.set (DataType::AUDIO, n_audio);
1342         cc.set (DataType::MIDI, n_midi);
1343         return cc;
1344 }
1345
1346 /* Getting access to the data buffer for a port */
1347
1348 void*
1349 PortAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1350 {
1351         if (!port || !valid_port (port)) return NULL;
1352         return static_cast<PamPort*>(port)->get_buffer (nframes);
1353 }
1354
1355
1356 void *
1357 PortAudioBackend::main_process_thread ()
1358 {
1359         AudioEngine::thread_init_callback (this);
1360         _active = true;
1361         _processed_samples = 0;
1362
1363         uint64_t clock1, clock2;
1364         int64_t min_elapsed_us = 1000000;
1365         int64_t max_elapsed_us = 0;
1366         const int64_t nomial_time = 1e6 * _samples_per_period / _samplerate;
1367         // const int64_t nomial_time = m_cycle_timer.get_length_us();
1368
1369         manager.registration_callback();
1370         manager.graph_order_callback();
1371
1372         if (_pcmio->pcm_start()) {
1373                 _pcmio->pcm_stop ();
1374                 _active = false;
1375                 engine.halted_callback("PortAudio I/O error.");
1376         }
1377
1378 #ifdef USE_MMCSS_THREAD_PRIORITIES
1379         HANDLE task_handle;
1380
1381         mmcss::set_thread_characteristics ("Pro Audio", &task_handle);
1382         mmcss::set_thread_priority (task_handle, mmcss::AVRT_PRIORITY_NORMAL);
1383 #endif
1384
1385         DWORD tid = GetCurrentThreadId ();
1386         DEBUG_THREADS (string_compose ("Process Thread Master ID: %1\n", tid));
1387
1388         while (_run) {
1389
1390                 if (_freewheeling != _freewheel) {
1391                         _freewheel = _freewheeling;
1392                         engine.freewheel_callback (_freewheel);
1393                 }
1394
1395                 if (!_freewheel) {
1396
1397                         switch (_pcmio->next_cycle (_samples_per_period)) {
1398                                 case 0: // OK
1399                                         break;
1400                                 case 1:
1401                                         DEBUG_AUDIO ("PortAudio: Xrun\n");
1402                                         engine.Xrun ();
1403                                         break;
1404                                 default:
1405                                         PBD::error << _("PortAudioBackend: I/O error. Audio Process Terminated.") << endmsg;
1406                                         break;
1407                         }
1408
1409                         uint32_t i = 0;
1410                         clock1 = utils::get_microseconds ();
1411
1412                         /* get audio */
1413                         i = 0;
1414                         for (std::vector<PamPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++i) {
1415                                 _pcmio->get_capture_channel (i, (float*)((*it)->get_buffer(_samples_per_period)), _samples_per_period);
1416                         }
1417
1418                         /* de-queue incoming midi*/
1419                         i=0;
1420                         for (std::vector<PamPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++i) {
1421                                 PortMidiBuffer* mbuf = static_cast<PortMidiBuffer*>((*it)->get_buffer(0));
1422                                 mbuf->clear();
1423                                 uint64_t timestamp;
1424                                 pframes_t sample_offset;
1425                                 uint8_t data[256];
1426                                 size_t size = sizeof(data);
1427                                 while (_midiio->dequeue_input_event (i,
1428                                                                      m_cycle_timer.get_start (),
1429                                                                      m_cycle_timer.get_next_start (),
1430                                                                      timestamp,
1431                                                                      data,
1432                                                                      size)) {
1433                                         sample_offset = m_cycle_timer.samples_since_cycle_start (timestamp);
1434                                         midi_event_put (mbuf, sample_offset, data, size);
1435                                         DEBUG_MIDI (string_compose ("Dequeuing incoming MIDI data for device: %1 "
1436                                                                     "sample_offset: %2 timestamp: %3, size: %4\n",
1437                                                                     _midiio->get_inputs ()[i]->name (),
1438                                                                     sample_offset,
1439                                                                     timestamp,
1440                                                                     size));
1441                                         size = sizeof(data);
1442                                 }
1443                         }
1444
1445                         /* clear output buffers */
1446                         for (std::vector<PamPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it) {
1447                                 memset ((*it)->get_buffer (_samples_per_period), 0, _samples_per_period * sizeof (Sample));
1448                         }
1449
1450                         m_last_cycle_start = m_cycle_timer.get_start ();
1451                         m_cycle_timer.reset_start(utils::get_microseconds());
1452                         m_cycle_count++;
1453
1454                         uint64_t cycle_diff_us = (m_cycle_timer.get_start () - m_last_cycle_start);
1455                         int64_t deviation_us = (cycle_diff_us - m_cycle_timer.get_length_us());
1456                         m_total_deviation_us += ::llabs(deviation_us);
1457                         m_max_deviation_us =
1458                                 std::max (m_max_deviation_us, (uint64_t)::llabs (deviation_us));
1459
1460                         if ((m_cycle_count % 1000) == 0) {
1461                                 uint64_t mean_deviation_us = m_total_deviation_us / m_cycle_count;
1462                                 DEBUG_TIMING (
1463                                     string_compose ("Mean avg cycle deviation: %1(ms), max %2(ms)\n",
1464                                                     mean_deviation_us * 1e-3,
1465                                                     m_max_deviation_us * 1e-3));
1466                         }
1467
1468                         if (::llabs(deviation_us) > m_cycle_timer.get_length_us()) {
1469                                 DEBUG_TIMING (string_compose (
1470                                     "time between process(ms): %1, Est(ms): %2, Dev(ms): %3\n",
1471                                     cycle_diff_us * 1e-3,
1472                                     m_cycle_timer.get_length_us () * 1e-3,
1473                                     deviation_us * 1e-3));
1474                         }
1475
1476                         /* call engine process callback */
1477                         if (engine.process_callback (_samples_per_period)) {
1478                                 _pcmio->pcm_stop ();
1479                                 _active = false;
1480                                 return 0;
1481                         }
1482                         /* mixdown midi */
1483                         for (std::vector<PamPort*>::iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it) {
1484                                 static_cast<PortMidiPort*>(*it)->next_period();
1485                         }
1486                         /* queue outgoing midi */
1487                         i = 0;
1488                         for (std::vector<PamPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it, ++i) {
1489                                 const PortMidiBuffer* src = static_cast<const PortMidiPort*>(*it)->const_buffer();
1490
1491                                 for (PortMidiBuffer::const_iterator mit = src->begin (); mit != src->end (); ++mit) {
1492                                         uint64_t timestamp =
1493                                             m_cycle_timer.timestamp_from_sample_offset ((*mit)->timestamp ());
1494                                         DEBUG_MIDI (
1495                                             string_compose ("Queuing outgoing MIDI data for device: "
1496                                                             "%1 sample_offset: %2 timestamp: %3, size: %4\n",
1497                                                             _midiio->get_outputs ()[i]->name (),
1498                                                             (*mit)->timestamp (),
1499                                                             timestamp,
1500                                                             (*mit)->size ()));
1501                                         _midiio->enqueue_output_event (
1502                                             i, timestamp, (*mit)->data (), (*mit)->size ());
1503                                 }
1504                         }
1505
1506                         /* write back audio */
1507                         i = 0;
1508                         for (std::vector<PamPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it, ++i) {
1509                                 _pcmio->set_playback_channel (i, (float const*)(*it)->get_buffer (_samples_per_period), _samples_per_period);
1510                         }
1511
1512                         _processed_samples += _samples_per_period;
1513
1514                         /* calculate DSP load */
1515                         clock2 = utils::get_microseconds ();
1516                         const int64_t elapsed_time = clock2 - clock1;
1517                         _dsp_load = elapsed_time / (float) nomial_time;
1518
1519                         max_elapsed_us = std::max (elapsed_time, max_elapsed_us);
1520                         min_elapsed_us = std::min (elapsed_time, min_elapsed_us);
1521                         if ((m_cycle_count % 1000) == 0) {
1522                                 DEBUG_TIMING (
1523                                     string_compose ("Elapsed process time(usecs) max: %1, min: %2\n",
1524                                                     max_elapsed_us,
1525                                                     min_elapsed_us));
1526                         }
1527
1528                 } else {
1529                         // Freewheelin'
1530
1531                         // zero audio input buffers
1532                         for (std::vector<PamPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
1533                                 memset ((*it)->get_buffer (_samples_per_period), 0, _samples_per_period * sizeof (Sample));
1534                         }
1535
1536                         clock1 = utils::get_microseconds ();
1537
1538                         // TODO clear midi or stop midi recv when entering fwheelin'
1539
1540                         if (engine.process_callback (_samples_per_period)) {
1541                                 _pcmio->pcm_stop ();
1542                                 _active = false;
1543                                 return 0;
1544                         }
1545
1546                         // drop all outgoing MIDI messages
1547                         for (std::vector<PamPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it) {
1548                                         void *bptr = (*it)->get_buffer(0);
1549                                         midi_clear(bptr);
1550                         }
1551
1552                         _dsp_load = 1.0;
1553                         Glib::usleep (100); // don't hog cpu
1554                 }
1555
1556                 bool connections_changed = false;
1557                 bool ports_changed = false;
1558                 if (!pthread_mutex_trylock (&_port_callback_mutex)) {
1559                         if (_port_change_flag) {
1560                                 ports_changed = true;
1561                                 _port_change_flag = false;
1562                         }
1563                         if (!_port_connection_queue.empty ()) {
1564                                 connections_changed = true;
1565                         }
1566                         while (!_port_connection_queue.empty ()) {
1567                                 PortConnectData *c = _port_connection_queue.back ();
1568                                 manager.connect_callback (c->a, c->b, c->c);
1569                                 _port_connection_queue.pop_back ();
1570                                 delete c;
1571                         }
1572                         pthread_mutex_unlock (&_port_callback_mutex);
1573                 }
1574                 if (ports_changed) {
1575                         manager.registration_callback();
1576                 }
1577                 if (connections_changed) {
1578                         manager.graph_order_callback();
1579                 }
1580                 if (connections_changed || ports_changed) {
1581                         engine.latency_callback(false);
1582                         engine.latency_callback(true);
1583                 }
1584
1585         }
1586         _pcmio->pcm_stop ();
1587         _active = false;
1588         if (_run) {
1589                 engine.halted_callback("PortAudio I/O error.");
1590         }
1591
1592 #ifdef USE_MMCSS_THREAD_PRIORITIES
1593         mmcss::revert_thread_characteristics (task_handle);
1594 #endif
1595
1596         return 0;
1597 }
1598
1599
1600 /******************************************************************************/
1601
1602 static boost::shared_ptr<PortAudioBackend> _instance;
1603
1604 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
1605 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
1606 static int deinstantiate ();
1607 static bool already_configured ();
1608 static bool available ();
1609
1610 static ARDOUR::AudioBackendInfo _descriptor = {
1611         "PortAudio",
1612         instantiate,
1613         deinstantiate,
1614         backend_factory,
1615         already_configured,
1616         available
1617 };
1618
1619 static boost::shared_ptr<AudioBackend>
1620 backend_factory (AudioEngine& e)
1621 {
1622         if (!_instance) {
1623                 _instance.reset (new PortAudioBackend (e, _descriptor));
1624         }
1625         return _instance;
1626 }
1627
1628 static int
1629 instantiate (const std::string& arg1, const std::string& /* arg2 */)
1630 {
1631         s_instance_name = arg1;
1632         return 0;
1633 }
1634
1635 static int
1636 deinstantiate ()
1637 {
1638         _instance.reset ();
1639         return 0;
1640 }
1641
1642 static bool
1643 already_configured ()
1644 {
1645         return false;
1646 }
1647
1648 static bool
1649 available ()
1650 {
1651         return true;
1652 }
1653
1654 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
1655 {
1656         return &_descriptor;
1657 }
1658
1659
1660 /******************************************************************************/
1661 PamPort::PamPort (PortAudioBackend &b, const std::string& name, PortFlags flags)
1662         : _osx_backend (b)
1663         , _name  (name)
1664         , _flags (flags)
1665 {
1666         _capture_latency_range.min = 0;
1667         _capture_latency_range.max = 0;
1668         _playback_latency_range.min = 0;
1669         _playback_latency_range.max = 0;
1670 }
1671
1672 PamPort::~PamPort () {
1673         disconnect_all ();
1674 }
1675
1676
1677 int PamPort::connect (PamPort *port)
1678 {
1679         if (!port) {
1680                 PBD::error << _("PamPort::connect (): invalid (null) port") << endmsg;
1681                 return -1;
1682         }
1683
1684         if (type () != port->type ()) {
1685                 PBD::error << _("PamPort::connect (): wrong port-type") << endmsg;
1686                 return -1;
1687         }
1688
1689         if (is_output () && port->is_output ()) {
1690                 PBD::error << _("PamPort::connect (): cannot inter-connect output ports.") << endmsg;
1691                 return -1;
1692         }
1693
1694         if (is_input () && port->is_input ()) {
1695                 PBD::error << _("PamPort::connect (): cannot inter-connect input ports.") << endmsg;
1696                 return -1;
1697         }
1698
1699         if (this == port) {
1700                 PBD::error << _("PamPort::connect (): cannot self-connect ports.") << endmsg;
1701                 return -1;
1702         }
1703
1704         if (is_connected (port)) {
1705 #if 0 // don't bother to warn about this for now. just ignore it
1706                 PBD::error << _("PamPort::connect (): ports are already connected:")
1707                         << " (" << name () << ") -> (" << port->name () << ")"
1708                         << endmsg;
1709 #endif
1710                 return -1;
1711         }
1712
1713         _connect (port, true);
1714         return 0;
1715 }
1716
1717
1718 void PamPort::_connect (PamPort *port, bool callback)
1719 {
1720         _connections.push_back (port);
1721         if (callback) {
1722                 port->_connect (this, false);
1723                 _osx_backend.port_connect_callback (name(),  port->name(), true);
1724         }
1725 }
1726
1727 int PamPort::disconnect (PamPort *port)
1728 {
1729         if (!port) {
1730                 PBD::error << _("PamPort::disconnect (): invalid (null) port") << endmsg;
1731                 return -1;
1732         }
1733
1734         if (!is_connected (port)) {
1735                 PBD::error << _("PamPort::disconnect (): ports are not connected:")
1736                         << " (" << name () << ") -> (" << port->name () << ")"
1737                         << endmsg;
1738                 return -1;
1739         }
1740         _disconnect (port, true);
1741         return 0;
1742 }
1743
1744 void PamPort::_disconnect (PamPort *port, bool callback)
1745 {
1746         std::vector<PamPort*>::iterator it = std::find (_connections.begin (), _connections.end (), port);
1747
1748         assert (it != _connections.end ());
1749
1750         _connections.erase (it);
1751
1752         if (callback) {
1753                 port->_disconnect (this, false);
1754                 _osx_backend.port_connect_callback (name(),  port->name(), false);
1755         }
1756 }
1757
1758
1759 void PamPort::disconnect_all ()
1760 {
1761         while (!_connections.empty ()) {
1762                 _connections.back ()->_disconnect (this, false);
1763                 _osx_backend.port_connect_callback (name(),  _connections.back ()->name(), false);
1764                 _connections.pop_back ();
1765         }
1766 }
1767
1768 bool
1769 PamPort::is_connected (const PamPort *port) const
1770 {
1771         return std::find (_connections.begin (), _connections.end (), port) != _connections.end ();
1772 }
1773
1774 bool PamPort::is_physically_connected () const
1775 {
1776         for (std::vector<PamPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
1777                 if ((*it)->is_physical ()) {
1778                         return true;
1779                 }
1780         }
1781         return false;
1782 }
1783
1784 /******************************************************************************/
1785
1786 PortAudioPort::PortAudioPort (PortAudioBackend &b, const std::string& name, PortFlags flags)
1787         : PamPort (b, name, flags)
1788 {
1789         memset (_buffer, 0, sizeof (_buffer));
1790 #ifndef PLATFORM_WINDOWS
1791         mlock(_buffer, sizeof (_buffer));
1792 #endif
1793 }
1794
1795 PortAudioPort::~PortAudioPort () { }
1796
1797 void* PortAudioPort::get_buffer (pframes_t n_samples)
1798 {
1799         if (is_input ()) {
1800                 std::vector<PamPort*>::const_iterator it = get_connections ().begin ();
1801                 if (it == get_connections ().end ()) {
1802                         memset (_buffer, 0, n_samples * sizeof (Sample));
1803                 } else {
1804                         PortAudioPort const * source = static_cast<const PortAudioPort*>(*it);
1805                         assert (source && source->is_output ());
1806                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
1807                         while (++it != get_connections ().end ()) {
1808                                 source = static_cast<const PortAudioPort*>(*it);
1809                                 assert (source && source->is_output ());
1810                                 Sample* dst = buffer ();
1811                                 const Sample* src = source->const_buffer ();
1812                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
1813                                         *dst += *src;
1814                                 }
1815                         }
1816                 }
1817         }
1818         return _buffer;
1819 }
1820
1821
1822 PortMidiPort::PortMidiPort (PortAudioBackend &b, const std::string& name, PortFlags flags)
1823         : PamPort (b, name, flags)
1824         , _n_periods (1)
1825         , _bufperiod (0)
1826 {
1827         _buffer[0].clear ();
1828         _buffer[1].clear ();
1829 }
1830
1831 PortMidiPort::~PortMidiPort () { }
1832
1833 struct MidiEventSorter {
1834         bool operator() (const boost::shared_ptr<PortMidiEvent>& a, const boost::shared_ptr<PortMidiEvent>& b) {
1835                 return *a < *b;
1836         }
1837 };
1838
1839 void* PortMidiPort::get_buffer (pframes_t /* nframes */)
1840 {
1841         if (is_input ()) {
1842                 (_buffer[_bufperiod]).clear ();
1843                 for (std::vector<PamPort*>::const_iterator i = get_connections ().begin ();
1844                                 i != get_connections ().end ();
1845                                 ++i) {
1846                         const PortMidiBuffer * src = static_cast<const PortMidiPort*>(*i)->const_buffer ();
1847                         for (PortMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
1848                                 (_buffer[_bufperiod]).push_back (boost::shared_ptr<PortMidiEvent>(new PortMidiEvent (**it)));
1849                         }
1850                 }
1851                 std::sort ((_buffer[_bufperiod]).begin (), (_buffer[_bufperiod]).end (), MidiEventSorter());
1852         }
1853         return &(_buffer[_bufperiod]);
1854 }
1855
1856 PortMidiEvent::PortMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
1857         : _size (size)
1858         , _timestamp (timestamp)
1859         , _data (0)
1860 {
1861         if (size > 0) {
1862                 _data = (uint8_t*) malloc (size);
1863                 memcpy (_data, data, size);
1864         }
1865 }
1866
1867 PortMidiEvent::PortMidiEvent (const PortMidiEvent& other)
1868         : _size (other.size ())
1869         , _timestamp (other.timestamp ())
1870         , _data (0)
1871 {
1872         if (other.size () && other.const_data ()) {
1873                 _data = (uint8_t*) malloc (other.size ());
1874                 memcpy (_data, other.const_data (), other.size ());
1875         }
1876 };
1877
1878 PortMidiEvent::~PortMidiEvent () {
1879         free (_data);
1880 };