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