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