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