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