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