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