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