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