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