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