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