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