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