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