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