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