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