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