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