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