alsa: implement timing callback
[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         const int64_t nomial_time = 1e6 * _samples_per_period / _samplerate;
717
718         assert(elapsed_time_us >=0);
719
720         /* linear extrapolation, using [low pass] filtered process-speed. */
721         const pframes_t processed_samples = elapsed_time_us * _process_speed_samples_per_ms * 1e-3;
722
723         if (processed_samples >= _samples_per_period) {
724                 return _samples_per_period;
725         }
726         return processed_samples;
727 }
728
729
730 void *
731 AlsaAudioBackend::alsa_process_thread (void *arg)
732 {
733         ThreadData* td = reinterpret_cast<ThreadData*> (arg);
734         boost::function<void ()> f = td->f;
735         delete td;
736         f ();
737         return 0;
738 }
739
740 int
741 AlsaAudioBackend::create_process_thread (boost::function<void()> func)
742 {
743         pthread_t thread_id;
744         pthread_attr_t attr;
745         size_t stacksize = 100000;
746
747         ThreadData* td = new ThreadData (this, func, stacksize);
748
749         if (_realtime_pthread_create (SCHED_FIFO, -21, stacksize,
750                                 &thread_id, alsa_process_thread, td)) {
751                 pthread_attr_init (&attr);
752                 pthread_attr_setstacksize (&attr, stacksize);
753                 if (pthread_create (&thread_id, &attr, alsa_process_thread, td)) {
754                         PBD::error << _("AudioEngine: cannot create process thread.") << endmsg;
755                         pthread_attr_destroy (&attr);
756                         return -1;
757                 }
758                 pthread_attr_destroy (&attr);
759         }
760
761         _threads.push_back (thread_id);
762         return 0;
763 }
764
765 int
766 AlsaAudioBackend::join_process_threads ()
767 {
768         int rv = 0;
769
770         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
771         {
772                 void *status;
773                 if (pthread_join (*i, &status)) {
774                         PBD::error << _("AudioEngine: cannot terminate process thread.") << endmsg;
775                         rv -= 1;
776                 }
777         }
778         _threads.clear ();
779         return rv;
780 }
781
782 bool
783 AlsaAudioBackend::in_process_thread ()
784 {
785         if (pthread_equal (_main_thread, pthread_self()) != 0) {
786                 return true;
787         }
788
789         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
790         {
791                 if (pthread_equal (*i, pthread_self ()) != 0) {
792                         return true;
793                 }
794         }
795         return false;
796 }
797
798 uint32_t
799 AlsaAudioBackend::process_thread_count ()
800 {
801         return _threads.size ();
802 }
803
804 void
805 AlsaAudioBackend::update_latencies ()
806 {
807         // trigger latency callback in RT thread (locked graph)
808         port_connect_add_remove_callback();
809 }
810
811 /* PORTENGINE API */
812
813 void*
814 AlsaAudioBackend::private_handle () const
815 {
816         return NULL;
817 }
818
819 const std::string&
820 AlsaAudioBackend::my_name () const
821 {
822         return _instance_name;
823 }
824
825 bool
826 AlsaAudioBackend::available () const
827 {
828         return _run && _active;
829 }
830
831 uint32_t
832 AlsaAudioBackend::port_name_size () const
833 {
834         return 256;
835 }
836
837 int
838 AlsaAudioBackend::set_port_name (PortEngine::PortHandle port, const std::string& name)
839 {
840         if (!valid_port (port)) {
841                 PBD::error << _("AlsaBackend::set_port_name: Invalid Port(s)") << endmsg;
842                 return -1;
843         }
844         return static_cast<AlsaPort*>(port)->set_name (_instance_name + ":" + name);
845 }
846
847 std::string
848 AlsaAudioBackend::get_port_name (PortEngine::PortHandle port) const
849 {
850         if (!valid_port (port)) {
851                 PBD::error << _("AlsaBackend::get_port_name: Invalid Port(s)") << endmsg;
852                 return std::string ();
853         }
854         return static_cast<AlsaPort*>(port)->name ();
855 }
856
857 PortEngine::PortHandle
858 AlsaAudioBackend::get_port_by_name (const std::string& name) const
859 {
860         PortHandle port = (PortHandle) find_port (name);
861         return port;
862 }
863
864 int
865 AlsaAudioBackend::get_ports (
866                 const std::string& port_name_pattern,
867                 DataType type, PortFlags flags,
868                 std::vector<std::string>& port_names) const
869 {
870         int rv = 0;
871         regex_t port_regex;
872         bool use_regexp = false;
873         if (port_name_pattern.size () > 0) {
874                 if (!regcomp (&port_regex, port_name_pattern.c_str (), REG_EXTENDED|REG_NOSUB)) {
875                         use_regexp = true;
876                 }
877         }
878         for (size_t i = 0; i < _ports.size (); ++i) {
879                 AlsaPort* port = _ports[i];
880                 if ((port->type () == type) && (port->flags () & flags)) {
881                         if (!use_regexp || !regexec (&port_regex, port->name ().c_str (), 0, NULL, 0)) {
882                                 port_names.push_back (port->name ());
883                                 ++rv;
884                         }
885                 }
886         }
887         if (use_regexp) {
888                 regfree (&port_regex);
889         }
890         return rv;
891 }
892
893 DataType
894 AlsaAudioBackend::port_data_type (PortEngine::PortHandle port) const
895 {
896         if (!valid_port (port)) {
897                 return DataType::NIL;
898         }
899         return static_cast<AlsaPort*>(port)->type ();
900 }
901
902 PortEngine::PortHandle
903 AlsaAudioBackend::register_port (
904                 const std::string& name,
905                 ARDOUR::DataType type,
906                 ARDOUR::PortFlags flags)
907 {
908         if (name.size () == 0) { return 0; }
909         if (flags & IsPhysical) { return 0; }
910         return add_port (_instance_name + ":" + name, type, flags);
911 }
912
913 PortEngine::PortHandle
914 AlsaAudioBackend::add_port (
915                 const std::string& name,
916                 ARDOUR::DataType type,
917                 ARDOUR::PortFlags flags)
918 {
919         assert(name.size ());
920         if (find_port (name)) {
921                 PBD::error << _("AlsaBackend::register_port: Port already exists:")
922                                 << " (" << name << ")" << endmsg;
923                 return 0;
924         }
925         AlsaPort* port = NULL;
926         switch (type) {
927                 case DataType::AUDIO:
928                         port = new AlsaAudioPort (*this, name, flags);
929                         break;
930                 case DataType::MIDI:
931                         port = new AlsaMidiPort (*this, name, flags);
932                         break;
933                 default:
934                         PBD::error << _("AlsaBackend::register_port: Invalid Data Type.") << endmsg;
935                         return 0;
936         }
937
938         _ports.push_back (port);
939
940         return port;
941 }
942
943 void
944 AlsaAudioBackend::unregister_port (PortEngine::PortHandle port_handle)
945 {
946         if (!_run) {
947                 return;
948         }
949         AlsaPort* port = static_cast<AlsaPort*>(port_handle);
950         std::vector<AlsaPort*>::iterator i = std::find (_ports.begin (), _ports.end (), static_cast<AlsaPort*>(port_handle));
951         if (i == _ports.end ()) {
952                 PBD::error << _("AlsaBackend::unregister_port: Failed to find port") << endmsg;
953                 return;
954         }
955         disconnect_all(port_handle);
956         _ports.erase (i);
957         delete port;
958 }
959
960 int
961 AlsaAudioBackend::register_system_audio_ports()
962 {
963         LatencyRange lr;
964
965         const int a_ins = _n_inputs > 0 ? _n_inputs : 2;
966         const int a_out = _n_outputs > 0 ? _n_outputs : 2;
967
968         /* audio ports */
969         lr.min = lr.max = _samples_per_period + (_measure_latency ? 0 : _systemic_audio_input_latency);
970         for (int i = 1; i <= a_ins; ++i) {
971                 char tmp[64];
972                 snprintf(tmp, sizeof(tmp), "system:capture_%d", i);
973                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
974                 if (!p) return -1;
975                 set_latency_range (p, false, lr);
976                 _system_inputs.push_back(static_cast<AlsaPort*>(p));
977         }
978
979         lr.min = lr.max = _samples_per_period + (_measure_latency ? 0 : _systemic_audio_output_latency);
980         for (int i = 1; i <= a_out; ++i) {
981                 char tmp[64];
982                 snprintf(tmp, sizeof(tmp), "system:playback_%d", i);
983                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
984                 if (!p) return -1;
985                 set_latency_range (p, true, lr);
986                 _system_outputs.push_back(static_cast<AlsaPort*>(p));
987         }
988         return 0;
989 }
990
991 int
992 AlsaAudioBackend::register_system_midi_ports()
993 {
994         std::map<std::string, std::string> devices;
995         int midi_ins = 0;
996         int midi_outs = 0;
997
998         if (_midi_driver_option == _("None")) {
999                 return 0;
1000         } else if (_midi_driver_option == _("ALSA raw devices")) {
1001                 get_alsa_rawmidi_device_names(devices);
1002         } else {
1003                 get_alsa_sequencer_names (devices);
1004         }
1005
1006         for (std::map<std::string, std::string>::const_iterator i = devices.begin (); i != devices.end(); ++i) {
1007                 struct AlsaMidiDeviceInfo * nfo = midi_device_info(i->first);
1008                 if (!nfo) continue;
1009                 if (!nfo->enabled) continue;
1010
1011                 AlsaMidiOut *mout;
1012                 if (_midi_driver_option == _("ALSA raw devices")) {
1013                         mout = new AlsaRawMidiOut (i->second.c_str());
1014                 } else {
1015                         mout = new AlsaSeqMidiOut (i->second.c_str());
1016                 }
1017
1018                 if (mout->state ()) {
1019                         PBD::warning << string_compose (
1020                                         _("AlsaMidiOut: failed to open midi device '%1'."), i->second)
1021                                 << endmsg;
1022                         delete mout;
1023                 } else {
1024                         mout->setup_timing(_samples_per_period, _samplerate);
1025                         mout->sync_time (g_get_monotonic_time());
1026                         if (mout->start ()) {
1027                                 PBD::warning << string_compose (
1028                                                 _("AlsaMidiOut: failed to start midi device '%1'."), i->second)
1029                                         << endmsg;
1030                                 delete mout;
1031                         } else {
1032                                 char tmp[64];
1033                                 snprintf(tmp, sizeof(tmp), "system:midi_playback_%d", ++midi_ins);
1034                                 PortHandle p = add_port(std::string(tmp), DataType::MIDI, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
1035                                 if (!p) {
1036                                         mout->stop();
1037                                         delete mout;
1038                                 }
1039                                 LatencyRange lr;
1040                                 lr.min = lr.max = _samples_per_period + (_measure_latency ? 0 : nfo->systemic_output_latency);
1041                                 set_latency_range (p, false, lr);
1042                                 static_cast<AlsaMidiPort*>(p)->set_n_periods(2);
1043                                 _system_midi_out.push_back(static_cast<AlsaPort*>(p));
1044                                 _rmidi_out.push_back (mout);
1045                         }
1046                 }
1047
1048                 AlsaMidiIn *midin;
1049                 if (_midi_driver_option == _("ALSA raw devices")) {
1050                         midin = new AlsaRawMidiIn (i->second.c_str());
1051                 } else {
1052                         midin = new AlsaSeqMidiIn (i->second.c_str());
1053                 }
1054
1055                 if (midin->state ()) {
1056                         PBD::warning << string_compose (
1057                                         _("AlsaMidiIn: failed to open midi device '%1'."), i->second)
1058                                 << endmsg;
1059                         delete midin;
1060                 } else {
1061                         midin->setup_timing(_samples_per_period, _samplerate);
1062                         midin->sync_time (g_get_monotonic_time());
1063                         if (midin->start ()) {
1064                                 PBD::warning << string_compose (
1065                                                 _("AlsaMidiIn: failed to start midi device '%1'."), i->second)
1066                                         << endmsg;
1067                                 delete midin;
1068                         } else {
1069                                 char tmp[64];
1070                                 snprintf(tmp, sizeof(tmp), "system:midi_capture_%d", ++midi_outs);
1071                                 PortHandle p = add_port(std::string(tmp), DataType::MIDI, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
1072                                 if (!p) {
1073                                         midin->stop();
1074                                         delete midin;
1075                                         continue;
1076                                 }
1077                                 LatencyRange lr;
1078                                 lr.min = lr.max = _samples_per_period + (_measure_latency ? 0 : nfo->systemic_input_latency);
1079                                 set_latency_range (p, false, lr);
1080                                 _system_midi_in.push_back(static_cast<AlsaPort*>(p));
1081                                 _rmidi_in.push_back (midin);
1082                         }
1083                 }
1084         }
1085         return 0;
1086 }
1087
1088 void
1089 AlsaAudioBackend::unregister_ports (bool system_only)
1090 {
1091         size_t i = 0;
1092         _system_inputs.clear();
1093         _system_outputs.clear();
1094         _system_midi_in.clear();
1095         _system_midi_out.clear();
1096         while (i <  _ports.size ()) {
1097                 AlsaPort* port = _ports[i];
1098                 if (! system_only || (port->is_physical () && port->is_terminal ())) {
1099                         port->disconnect_all ();
1100                         delete port;
1101                         _ports.erase (_ports.begin() + i);
1102                 } else {
1103                         ++i;
1104                 }
1105         }
1106 }
1107
1108 int
1109 AlsaAudioBackend::connect (const std::string& src, const std::string& dst)
1110 {
1111         AlsaPort* src_port = find_port (src);
1112         AlsaPort* dst_port = find_port (dst);
1113
1114         if (!src_port) {
1115                 PBD::error << _("AlsaBackend::connect: Invalid Source port:")
1116                                 << " (" << src <<")" << endmsg;
1117                 return -1;
1118         }
1119         if (!dst_port) {
1120                 PBD::error << _("AlsaBackend::connect: Invalid Destination port:")
1121                         << " (" << dst <<")" << endmsg;
1122                 return -1;
1123         }
1124         return src_port->connect (dst_port);
1125 }
1126
1127 int
1128 AlsaAudioBackend::disconnect (const std::string& src, const std::string& dst)
1129 {
1130         AlsaPort* src_port = find_port (src);
1131         AlsaPort* dst_port = find_port (dst);
1132
1133         if (!src_port || !dst_port) {
1134                 PBD::error << _("AlsaBackend::disconnect: Invalid Port(s)") << endmsg;
1135                 return -1;
1136         }
1137         return src_port->disconnect (dst_port);
1138 }
1139
1140 int
1141 AlsaAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
1142 {
1143         AlsaPort* dst_port = find_port (dst);
1144         if (!valid_port (src)) {
1145                 PBD::error << _("AlsaBackend::connect: Invalid Source Port Handle") << endmsg;
1146                 return -1;
1147         }
1148         if (!dst_port) {
1149                 PBD::error << _("AlsaBackend::connect: Invalid Destination Port")
1150                         << " (" << dst << ")" << endmsg;
1151                 return -1;
1152         }
1153         return static_cast<AlsaPort*>(src)->connect (dst_port);
1154 }
1155
1156 int
1157 AlsaAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
1158 {
1159         AlsaPort* dst_port = find_port (dst);
1160         if (!valid_port (src) || !dst_port) {
1161                 PBD::error << _("AlsaBackend::disconnect: Invalid Port(s)") << endmsg;
1162                 return -1;
1163         }
1164         return static_cast<AlsaPort*>(src)->disconnect (dst_port);
1165 }
1166
1167 int
1168 AlsaAudioBackend::disconnect_all (PortEngine::PortHandle port)
1169 {
1170         if (!valid_port (port)) {
1171                 PBD::error << _("AlsaBackend::disconnect_all: Invalid Port") << endmsg;
1172                 return -1;
1173         }
1174         static_cast<AlsaPort*>(port)->disconnect_all ();
1175         return 0;
1176 }
1177
1178 bool
1179 AlsaAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
1180 {
1181         if (!valid_port (port)) {
1182                 PBD::error << _("AlsaBackend::disconnect_all: Invalid Port") << endmsg;
1183                 return false;
1184         }
1185         return static_cast<AlsaPort*>(port)->is_connected ();
1186 }
1187
1188 bool
1189 AlsaAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
1190 {
1191         AlsaPort* dst_port = find_port (dst);
1192         if (!valid_port (src) || !dst_port) {
1193                 PBD::error << _("AlsaBackend::connected_to: Invalid Port") << endmsg;
1194                 return false;
1195         }
1196         return static_cast<AlsaPort*>(src)->is_connected (dst_port);
1197 }
1198
1199 bool
1200 AlsaAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
1201 {
1202         if (!valid_port (port)) {
1203                 PBD::error << _("AlsaBackend::physically_connected: Invalid Port") << endmsg;
1204                 return false;
1205         }
1206         return static_cast<AlsaPort*>(port)->is_physically_connected ();
1207 }
1208
1209 int
1210 AlsaAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
1211 {
1212         if (!valid_port (port)) {
1213                 PBD::error << _("AlsaBackend::get_connections: Invalid Port") << endmsg;
1214                 return -1;
1215         }
1216
1217         assert (0 == names.size ());
1218
1219         const std::vector<AlsaPort*>& connected_ports = static_cast<AlsaPort*>(port)->get_connections ();
1220
1221         for (std::vector<AlsaPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
1222                 names.push_back ((*i)->name ());
1223         }
1224
1225         return (int)names.size ();
1226 }
1227
1228 /* MIDI */
1229 int
1230 AlsaAudioBackend::midi_event_get (
1231                 pframes_t& timestamp,
1232                 size_t& size, uint8_t** buf, void* port_buffer,
1233                 uint32_t event_index)
1234 {
1235         assert (buf && port_buffer);
1236         AlsaMidiBuffer& source = * static_cast<AlsaMidiBuffer*>(port_buffer);
1237         if (event_index >= source.size ()) {
1238                 return -1;
1239         }
1240         AlsaMidiEvent * const event = source[event_index].get ();
1241
1242         timestamp = event->timestamp ();
1243         size = event->size ();
1244         *buf = event->data ();
1245         return 0;
1246 }
1247
1248 int
1249 AlsaAudioBackend::midi_event_put (
1250                 void* port_buffer,
1251                 pframes_t timestamp,
1252                 const uint8_t* buffer, size_t size)
1253 {
1254         assert (buffer && port_buffer);
1255         AlsaMidiBuffer& dst = * static_cast<AlsaMidiBuffer*>(port_buffer);
1256         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
1257                 fprintf (stderr, "AlsaMidiBuffer: it's too late for this event. %d > %d\n",
1258                                 (pframes_t)dst.back ()->timestamp (), timestamp);
1259                 return -1;
1260         }
1261         dst.push_back (boost::shared_ptr<AlsaMidiEvent>(new AlsaMidiEvent (timestamp, buffer, size)));
1262         return 0;
1263 }
1264
1265 uint32_t
1266 AlsaAudioBackend::get_midi_event_count (void* port_buffer)
1267 {
1268         assert (port_buffer);
1269         return static_cast<AlsaMidiBuffer*>(port_buffer)->size ();
1270 }
1271
1272 void
1273 AlsaAudioBackend::midi_clear (void* port_buffer)
1274 {
1275         assert (port_buffer);
1276         AlsaMidiBuffer * buf = static_cast<AlsaMidiBuffer*>(port_buffer);
1277         assert (buf);
1278         buf->clear ();
1279 }
1280
1281 /* Monitoring */
1282
1283 bool
1284 AlsaAudioBackend::can_monitor_input () const
1285 {
1286         return false;
1287 }
1288
1289 int
1290 AlsaAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1291 {
1292         return -1;
1293 }
1294
1295 int
1296 AlsaAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1297 {
1298         return -1;
1299 }
1300
1301 bool
1302 AlsaAudioBackend::monitoring_input (PortEngine::PortHandle)
1303 {
1304         return false;
1305 }
1306
1307 /* Latency management */
1308
1309 void
1310 AlsaAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1311 {
1312         if (!valid_port (port)) {
1313                 PBD::error << _("AlsaPort::set_latency_range (): invalid port.") << endmsg;
1314         }
1315         static_cast<AlsaPort*>(port)->set_latency_range (latency_range, for_playback);
1316 }
1317
1318 LatencyRange
1319 AlsaAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1320 {
1321         if (!valid_port (port)) {
1322                 PBD::error << _("AlsaPort::get_latency_range (): invalid port.") << endmsg;
1323                 LatencyRange r;
1324                 r.min = 0;
1325                 r.max = 0;
1326                 return r;
1327         }
1328         return static_cast<AlsaPort*>(port)->latency_range (for_playback);
1329 }
1330
1331 /* Discovering physical ports */
1332
1333 bool
1334 AlsaAudioBackend::port_is_physical (PortEngine::PortHandle port) const
1335 {
1336         if (!valid_port (port)) {
1337                 PBD::error << _("AlsaPort::port_is_physical (): invalid port.") << endmsg;
1338                 return false;
1339         }
1340         return static_cast<AlsaPort*>(port)->is_physical ();
1341 }
1342
1343 void
1344 AlsaAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1345 {
1346         for (size_t i = 0; i < _ports.size (); ++i) {
1347                 AlsaPort* port = _ports[i];
1348                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1349                         port_names.push_back (port->name ());
1350                 }
1351         }
1352 }
1353
1354 void
1355 AlsaAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1356 {
1357         for (size_t i = 0; i < _ports.size (); ++i) {
1358                 AlsaPort* port = _ports[i];
1359                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1360                         port_names.push_back (port->name ());
1361                 }
1362         }
1363 }
1364
1365 ChanCount
1366 AlsaAudioBackend::n_physical_outputs () const
1367 {
1368         int n_midi = 0;
1369         int n_audio = 0;
1370         for (size_t i = 0; i < _ports.size (); ++i) {
1371                 AlsaPort* port = _ports[i];
1372                 if (port->is_output () && port->is_physical ()) {
1373                         switch (port->type ()) {
1374                                 case DataType::AUDIO: ++n_audio; break;
1375                                 case DataType::MIDI: ++n_midi; break;
1376                                 default: break;
1377                         }
1378                 }
1379         }
1380         ChanCount cc;
1381         cc.set (DataType::AUDIO, n_audio);
1382         cc.set (DataType::MIDI, n_midi);
1383         return cc;
1384 }
1385
1386 ChanCount
1387 AlsaAudioBackend::n_physical_inputs () const
1388 {
1389         int n_midi = 0;
1390         int n_audio = 0;
1391         for (size_t i = 0; i < _ports.size (); ++i) {
1392                 AlsaPort* port = _ports[i];
1393                 if (port->is_input () && port->is_physical ()) {
1394                         switch (port->type ()) {
1395                                 case DataType::AUDIO: ++n_audio; break;
1396                                 case DataType::MIDI: ++n_midi; break;
1397                                 default: break;
1398                         }
1399                 }
1400         }
1401         ChanCount cc;
1402         cc.set (DataType::AUDIO, n_audio);
1403         cc.set (DataType::MIDI, n_midi);
1404         return cc;
1405 }
1406
1407 /* Getting access to the data buffer for a port */
1408
1409 void*
1410 AlsaAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1411 {
1412         assert (port);
1413         assert (valid_port (port));
1414         return static_cast<AlsaPort*>(port)->get_buffer (nframes);
1415 }
1416
1417 /* Engine Process */
1418 void *
1419 AlsaAudioBackend::main_process_thread ()
1420 {
1421         AudioEngine::thread_init_callback (this);
1422         _active = true;
1423         _processed_samples = 0;
1424
1425         uint64_t clock1, clock2;
1426         _pcmi->pcm_start ();
1427         int no_proc_errors = 0;
1428         const int bailout = 2 * _samplerate / _samples_per_period;
1429         const int64_t nomial_time = 1e6 * _samples_per_period / _samplerate;
1430
1431         manager.registration_callback();
1432         manager.graph_order_callback();
1433
1434         while (_run) {
1435                 long nr;
1436                 bool xrun = false;
1437
1438                 if (_freewheeling != _freewheel) {
1439                         _freewheel = _freewheeling;
1440                         engine.freewheel_callback (_freewheel);
1441                 }
1442
1443                 if (!_freewheel) {
1444                         nr = _pcmi->pcm_wait ();
1445
1446                         if (_pcmi->state () > 0) {
1447                                 ++no_proc_errors;
1448                                 xrun = true;
1449                         }
1450                         if (_pcmi->state () < 0) {
1451                                 PBD::error << _("AlsaAudioBackend: I/O error. Audio Process Terminated.") << endmsg;
1452                                 break;
1453                         }
1454                         if (no_proc_errors > bailout) {
1455                                 PBD::error
1456                                         << string_compose (
1457                                                         _("AlsaAudioBackend: Audio Process Terminated after %1 consecutive x-runs."),
1458                                                         no_proc_errors)
1459                                         << endmsg;
1460                                 break;
1461                         }
1462
1463                         while (nr >= (long)_samples_per_period && _freewheeling == _freewheel) {
1464                                 uint32_t i = 0;
1465                                 clock1 = g_get_monotonic_time();
1466                                 no_proc_errors = 0;
1467
1468                                 _pcmi->capt_init (_samples_per_period);
1469                                 for (std::vector<AlsaPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++i) {
1470                                         _pcmi->capt_chan (i, (float*)((*it)->get_buffer(_samples_per_period)), _samples_per_period);
1471                                 }
1472                                 _pcmi->capt_done (_samples_per_period);
1473
1474                                 /* de-queue incoming midi*/
1475                                 i = 0;
1476                                 for (std::vector<AlsaPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++i) {
1477                                         assert (_rmidi_in.size() > i);
1478                                         AlsaMidiIn *rm = _rmidi_in.at(i);
1479                                         void *bptr = (*it)->get_buffer(0);
1480                                         pframes_t time;
1481                                         uint8_t data[64]; // match MaxAlsaEventSize in alsa_rawmidi.cc
1482                                         size_t size = sizeof(data);
1483                                         midi_clear(bptr);
1484                                         while (rm->recv_event (time, data, size)) {
1485                                                 midi_event_put(bptr, time, data, size);
1486                                                 size = sizeof(data);
1487                                         }
1488                                         rm->sync_time (clock1);
1489                                 }
1490
1491                                 for (std::vector<AlsaPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it) {
1492                                         memset ((*it)->get_buffer (_samples_per_period), 0, _samples_per_period * sizeof (Sample));
1493                                 }
1494
1495                                 /* call engine process callback */
1496                                 _last_process_start = g_get_monotonic_time();
1497                                 if (engine.process_callback (_samples_per_period)) {
1498                                         _pcmi->pcm_stop ();
1499                                         _active = false;
1500                                         return 0;
1501                                 }
1502
1503                                 for (std::vector<AlsaPort*>::iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it) {
1504                                         static_cast<AlsaMidiPort*>(*it)->next_period();
1505                                 }
1506
1507                                 /* queue outgoing midi */
1508                                 i = 0;
1509                                 for (std::vector<AlsaPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it, ++i) {
1510                                         assert (_rmidi_out.size() > i);
1511                                         const AlsaMidiBuffer * src = static_cast<const AlsaMidiPort*>(*it)->const_buffer();
1512                                         AlsaMidiOut *rm = _rmidi_out.at(i);
1513                                         rm->sync_time (clock1);
1514                                         for (AlsaMidiBuffer::const_iterator mit = src->begin (); mit != src->end (); ++mit) {
1515                                                 rm->send_event ((*mit)->timestamp(), (*mit)->data(), (*mit)->size());
1516                                         }
1517                                 }
1518
1519                                 /* write back audio */
1520                                 i = 0;
1521                                 _pcmi->play_init (_samples_per_period);
1522                                 for (std::vector<AlsaPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it, ++i) {
1523                                         _pcmi->play_chan (i, (const float*)(*it)->get_buffer (_samples_per_period), _samples_per_period);
1524                                 }
1525                                 for (; i < _pcmi->nplay (); ++i) {
1526                                         _pcmi->clear_chan (i, _samples_per_period);
1527                                 }
1528                                 _pcmi->play_done (_samples_per_period);
1529                                 nr -= _samples_per_period;
1530                                 _processed_samples += _samples_per_period;
1531
1532                                 /* calculate DSP load */
1533                                 clock2 = g_get_monotonic_time();
1534                                 const int64_t elapsed_time = clock2 - clock1;
1535                                 _dsp_load = elapsed_time / (float) nomial_time;
1536
1537                                 const double ps = 1e3 * _samples_per_period / elapsed_time;
1538                                 // low pass filter, The time-constant should really be
1539                                 // 1.0 - e^(-2.0 * Ï€ * v / SR);
1540                                 // with v = _samples_per_period / N, and SR = _samples_per_period;
1541                                 _process_speed_samples_per_ms  = _process_speed_samples_per_ms + .05 * (ps - _process_speed_samples_per_ms) + 1e-12;
1542                         }
1543
1544                         if (xrun && (_pcmi->capt_xrun() > 0 || _pcmi->play_xrun() > 0)) {
1545                                 engine.Xrun ();
1546 #if 0
1547                                 fprintf(stderr, "ALSA x-run read: %.2f ms, write: %.2f ms\n",
1548                                                 _pcmi->capt_xrun() * 1000.0, _pcmi->play_xrun() * 1000.0);
1549 #endif
1550                         }
1551                 } else {
1552                         // Freewheelin'
1553
1554                         // zero audio input buffers
1555                         for (std::vector<AlsaPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
1556                                 memset ((*it)->get_buffer (_samples_per_period), 0, _samples_per_period * sizeof (Sample));
1557                         }
1558
1559                         clock1 = g_get_monotonic_time();
1560                         uint32_t i = 0;
1561                         for (std::vector<AlsaPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++i) {
1562                                 static_cast<AlsaMidiBuffer*>((*it)->get_buffer(0))->clear ();
1563                                 AlsaMidiIn *rm = _rmidi_in.at(i);
1564                                 void *bptr = (*it)->get_buffer(0);
1565                                 midi_clear(bptr); // zero midi buffer
1566
1567                                 // TODO add an API call for this.
1568                                 pframes_t time;
1569                                 uint8_t data[64]; // match MaxAlsaEventSize in alsa_rawmidi.cc
1570                                 size_t size = sizeof(data);
1571                                 while (rm->recv_event (time, data, size)) {
1572                                         ; // discard midi-data from HW.
1573                                 }
1574                                 rm->sync_time (clock1);
1575                         }
1576
1577                         _last_process_start = -1;
1578                         if (engine.process_callback (_samples_per_period)) {
1579                                 _pcmi->pcm_stop ();
1580                                 _active = false;
1581                                 return 0;
1582                         }
1583
1584                         // drop all outgoing MIDI messages
1585                         for (std::vector<AlsaPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it) {
1586                                         void *bptr = (*it)->get_buffer(0);
1587                                         midi_clear(bptr);
1588                         }
1589
1590                         _dsp_load = 1.0;
1591                         Glib::usleep (100); // don't hog cpu
1592                 }
1593
1594                 bool connections_changed = false;
1595                 bool ports_changed = false;
1596                 if (!pthread_mutex_trylock (&_port_callback_mutex)) {
1597                         if (_port_change_flag) {
1598                                 ports_changed = true;
1599                                 _port_change_flag = false;
1600                         }
1601                         if (!_port_connection_queue.empty ()) {
1602                                 connections_changed = true;
1603                         }
1604                         while (!_port_connection_queue.empty ()) {
1605                                 PortConnectData *c = _port_connection_queue.back ();
1606                                 manager.connect_callback (c->a, c->b, c->c);
1607                                 _port_connection_queue.pop_back ();
1608                                 delete c;
1609                         }
1610                         pthread_mutex_unlock (&_port_callback_mutex);
1611                 }
1612                 if (ports_changed) {
1613                         manager.registration_callback();
1614                 }
1615                 if (connections_changed) {
1616                         manager.graph_order_callback();
1617                 }
1618                 if (connections_changed || ports_changed) {
1619                         engine.latency_callback(false);
1620                         engine.latency_callback(true);
1621                 }
1622
1623         }
1624         _pcmi->pcm_stop ();
1625         _active = false;
1626         if (_run) {
1627                 engine.halted_callback("ALSA I/O error.");
1628         }
1629         return 0;
1630 }
1631
1632
1633 /******************************************************************************/
1634
1635 static boost::shared_ptr<AlsaAudioBackend> _instance;
1636
1637 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
1638 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
1639 static int deinstantiate ();
1640 static bool already_configured ();
1641 static bool available ();
1642
1643 static ARDOUR::AudioBackendInfo _descriptor = {
1644         "ALSA",
1645         instantiate,
1646         deinstantiate,
1647         backend_factory,
1648         already_configured,
1649         available
1650 };
1651
1652 static boost::shared_ptr<AudioBackend>
1653 backend_factory (AudioEngine& e)
1654 {
1655         if (!_instance) {
1656                 _instance.reset (new AlsaAudioBackend (e, _descriptor));
1657         }
1658         return _instance;
1659 }
1660
1661 static int
1662 instantiate (const std::string& arg1, const std::string& /* arg2 */)
1663 {
1664         s_instance_name = arg1;
1665         return 0;
1666 }
1667
1668 static int
1669 deinstantiate ()
1670 {
1671         _instance.reset ();
1672         return 0;
1673 }
1674
1675 static bool
1676 already_configured ()
1677 {
1678         return false;
1679 }
1680
1681 static bool
1682 available ()
1683 {
1684         return true;
1685 }
1686
1687 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
1688 {
1689         return &_descriptor;
1690 }
1691
1692
1693 /******************************************************************************/
1694 AlsaPort::AlsaPort (AlsaAudioBackend &b, const std::string& name, PortFlags flags)
1695         : _alsa_backend (b)
1696         , _name  (name)
1697         , _flags (flags)
1698 {
1699         _capture_latency_range.min = 0;
1700         _capture_latency_range.max = 0;
1701         _playback_latency_range.min = 0;
1702         _playback_latency_range.max = 0;
1703 }
1704
1705 AlsaPort::~AlsaPort () {
1706         disconnect_all ();
1707 }
1708
1709
1710 int AlsaPort::connect (AlsaPort *port)
1711 {
1712         if (!port) {
1713                 PBD::error << _("AlsaPort::connect (): invalid (null) port") << endmsg;
1714                 return -1;
1715         }
1716
1717         if (type () != port->type ()) {
1718                 PBD::error << _("AlsaPort::connect (): wrong port-type") << endmsg;
1719                 return -1;
1720         }
1721
1722         if (is_output () && port->is_output ()) {
1723                 PBD::error << _("AlsaPort::connect (): cannot inter-connect output ports.") << endmsg;
1724                 return -1;
1725         }
1726
1727         if (is_input () && port->is_input ()) {
1728                 PBD::error << _("AlsaPort::connect (): cannot inter-connect input ports.") << endmsg;
1729                 return -1;
1730         }
1731
1732         if (this == port) {
1733                 PBD::error << _("AlsaPort::connect (): cannot self-connect ports.") << endmsg;
1734                 return -1;
1735         }
1736
1737         if (is_connected (port)) {
1738 #if 0 // don't bother to warn about this for now. just ignore it
1739                 PBD::error << _("AlsaPort::connect (): ports are already connected:")
1740                         << " (" << name () << ") -> (" << port->name () << ")"
1741                         << endmsg;
1742 #endif
1743                 return -1;
1744         }
1745
1746         _connect (port, true);
1747         return 0;
1748 }
1749
1750
1751 void AlsaPort::_connect (AlsaPort *port, bool callback)
1752 {
1753         _connections.push_back (port);
1754         if (callback) {
1755                 port->_connect (this, false);
1756                 _alsa_backend.port_connect_callback (name(),  port->name(), true);
1757         }
1758 }
1759
1760 int AlsaPort::disconnect (AlsaPort *port)
1761 {
1762         if (!port) {
1763                 PBD::error << _("AlsaPort::disconnect (): invalid (null) port") << endmsg;
1764                 return -1;
1765         }
1766
1767         if (!is_connected (port)) {
1768                 PBD::error << _("AlsaPort::disconnect (): ports are not connected:")
1769                         << " (" << name () << ") -> (" << port->name () << ")"
1770                         << endmsg;
1771                 return -1;
1772         }
1773         _disconnect (port, true);
1774         return 0;
1775 }
1776
1777 void AlsaPort::_disconnect (AlsaPort *port, bool callback)
1778 {
1779         std::vector<AlsaPort*>::iterator it = std::find (_connections.begin (), _connections.end (), port);
1780
1781         assert (it != _connections.end ());
1782
1783         _connections.erase (it);
1784
1785         if (callback) {
1786                 port->_disconnect (this, false);
1787                 _alsa_backend.port_connect_callback (name(),  port->name(), false);
1788         }
1789 }
1790
1791
1792 void AlsaPort::disconnect_all ()
1793 {
1794         while (!_connections.empty ()) {
1795                 _connections.back ()->_disconnect (this, false);
1796                 _alsa_backend.port_connect_callback (name(),  _connections.back ()->name(), false);
1797                 _connections.pop_back ();
1798         }
1799 }
1800
1801 bool
1802 AlsaPort::is_connected (const AlsaPort *port) const
1803 {
1804         return std::find (_connections.begin (), _connections.end (), port) != _connections.end ();
1805 }
1806
1807 bool AlsaPort::is_physically_connected () const
1808 {
1809         for (std::vector<AlsaPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
1810                 if ((*it)->is_physical ()) {
1811                         return true;
1812                 }
1813         }
1814         return false;
1815 }
1816
1817 /******************************************************************************/
1818
1819 AlsaAudioPort::AlsaAudioPort (AlsaAudioBackend &b, const std::string& name, PortFlags flags)
1820         : AlsaPort (b, name, flags)
1821 {
1822         memset (_buffer, 0, sizeof (_buffer));
1823         mlock(_buffer, sizeof (_buffer));
1824 }
1825
1826 AlsaAudioPort::~AlsaAudioPort () { }
1827
1828 void* AlsaAudioPort::get_buffer (pframes_t n_samples)
1829 {
1830         if (is_input ()) {
1831                 std::vector<AlsaPort*>::const_iterator it = get_connections ().begin ();
1832                 if (it == get_connections ().end ()) {
1833                         memset (_buffer, 0, n_samples * sizeof (Sample));
1834                 } else {
1835                         AlsaAudioPort const * source = static_cast<const AlsaAudioPort*>(*it);
1836                         assert (source && source->is_output ());
1837                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
1838                         while (++it != get_connections ().end ()) {
1839                                 source = static_cast<const AlsaAudioPort*>(*it);
1840                                 assert (source && source->is_output ());
1841                                 Sample* dst = buffer ();
1842                                 const Sample* src = source->const_buffer ();
1843                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
1844                                         *dst += *src;
1845                                 }
1846                         }
1847                 }
1848         }
1849         return _buffer;
1850 }
1851
1852
1853 AlsaMidiPort::AlsaMidiPort (AlsaAudioBackend &b, const std::string& name, PortFlags flags)
1854         : AlsaPort (b, name, flags)
1855         , _n_periods (1)
1856         , _bufperiod (0)
1857 {
1858         _buffer[0].clear ();
1859         _buffer[1].clear ();
1860 }
1861
1862 AlsaMidiPort::~AlsaMidiPort () { }
1863
1864 struct MidiEventSorter {
1865         bool operator() (const boost::shared_ptr<AlsaMidiEvent>& a, const boost::shared_ptr<AlsaMidiEvent>& b) {
1866                 return *a < *b;
1867         }
1868 };
1869
1870 void* AlsaMidiPort::get_buffer (pframes_t /* nframes */)
1871 {
1872         if (is_input ()) {
1873                 (_buffer[_bufperiod]).clear ();
1874                 for (std::vector<AlsaPort*>::const_iterator i = get_connections ().begin ();
1875                                 i != get_connections ().end ();
1876                                 ++i) {
1877                         const AlsaMidiBuffer * src = static_cast<const AlsaMidiPort*>(*i)->const_buffer ();
1878                         for (AlsaMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
1879                                 (_buffer[_bufperiod]).push_back (boost::shared_ptr<AlsaMidiEvent>(new AlsaMidiEvent (**it)));
1880                         }
1881                 }
1882                 std::sort ((_buffer[_bufperiod]).begin (), (_buffer[_bufperiod]).end (), MidiEventSorter());
1883         }
1884         return &(_buffer[_bufperiod]);
1885 }
1886
1887 AlsaMidiEvent::AlsaMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
1888         : _size (size)
1889         , _timestamp (timestamp)
1890         , _data (0)
1891 {
1892         if (size > 0) {
1893                 _data = (uint8_t*) malloc (size);
1894                 memcpy (_data, data, size);
1895         }
1896 }
1897
1898 AlsaMidiEvent::AlsaMidiEvent (const AlsaMidiEvent& other)
1899         : _size (other.size ())
1900         , _timestamp (other.timestamp ())
1901         , _data (0)
1902 {
1903         if (other.size () && other.const_data ()) {
1904                 _data = (uint8_t*) malloc (other.size ());
1905                 memcpy (_data, other.const_data (), other.size ());
1906         }
1907 };
1908
1909 AlsaMidiEvent::~AlsaMidiEvent () {
1910         free (_data);
1911 };