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