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