Modify our MSVC projects to build liblua as a DLL rather than a static lib
[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()) {
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         }
820
821         /* reset internal state */
822         _dsp_load = 0;
823         _freewheeling = false;
824         _freewheel = false;
825         _last_process_start = 0;
826
827         release_device();
828
829         assert(_rmidi_in.size() == 0);
830         assert(_rmidi_out.size() == 0);
831         assert(_pcmi == 0);
832
833         int duplex = 0;
834         std::string audio_device;
835         std::string alsa_device;
836         std::map<std::string, std::string> devices;
837
838         if (_input_audio_device == get_standard_device_name(DeviceNone) && _output_audio_device == get_standard_device_name(DeviceNone)) {
839                 PBD::error << _("AlsaAudioBackend: At least one of input or output device needs to be set.");
840                 return AudioDeviceInvalidError;
841         }
842
843         if (_input_audio_device != _output_audio_device) {
844                 if (_input_audio_device != get_standard_device_name(DeviceNone) && _output_audio_device != get_standard_device_name(DeviceNone)) {
845                         PBD::error << _("AlsaAudioBackend: Cannot use two different devices.");
846                         return AudioDeviceInvalidError;
847                 }
848                 if (_input_audio_device != get_standard_device_name(DeviceNone)) {
849                         get_alsa_audio_device_names(devices, HalfDuplexIn);
850                         audio_device = _input_audio_device;
851                         duplex = 1;
852                 } else {
853                         get_alsa_audio_device_names(devices, HalfDuplexOut);
854                         audio_device = _output_audio_device;
855                         duplex = 2;
856                 }
857         } else {
858                 get_alsa_audio_device_names(devices);
859                 audio_device = _input_audio_device;
860                 duplex = 3;
861         }
862
863         for (std::map<std::string, std::string>::const_iterator i = devices.begin (); i != devices.end(); ++i) {
864                 if (i->first == audio_device) {
865                         alsa_device = i->second;
866                         break;
867                 }
868         }
869         if (alsa_device == "") {
870                 PBD::error << _("AlsaAudioBackend: Cannot find configured device. Is it still connected?");
871                 return AudioDeviceNotAvailableError;
872         }
873
874         acquire_device(alsa_device.c_str());
875         _pcmi = new Alsa_pcmi (
876                         (duplex & 2) ? alsa_device.c_str() : NULL,
877                         (duplex & 1) ? alsa_device.c_str() : NULL,
878                         /* ctrl name */ 0,
879                         _samplerate, _samples_per_period,
880                         _periods_per_cycle, /* _periods_per_cycle */ 2,
881                         /* debug */ 0);
882
883         AudioBackend::ErrorCode error_code = NoError;
884         switch (_pcmi->state()) {
885         case 0: /* OK */
886                 break;
887         case -1:
888                 PBD::error << _("AlsaAudioBackend: failed to open device.") << endmsg;
889                 error_code = AudioDeviceOpenError;
890                 break;
891         case -2:
892                 PBD::error << _("AlsaAudioBackend: failed to allocate parameters.") << endmsg;
893                 error_code = AudioDeviceOpenError;
894                 break;
895         case -3:
896                 PBD::error << _("AlsaAudioBackend: cannot set requested sample rate.")
897                            << endmsg;
898                 error_code = SampleRateNotSupportedError;
899                 break;
900         case -4:
901                 PBD::error << _("AlsaAudioBackend: cannot set requested period size.")
902                            << endmsg;
903                 error_code = PeriodSizeNotSupportedError;
904                 break;
905         case -5:
906                 PBD::error << _("AlsaAudioBackend: cannot set requested number of periods.")
907                            << endmsg;
908                 error_code = PeriodCountNotSupportedError;
909                 break;
910         case -6:
911                 PBD::error << _("AlsaAudioBackend: unsupported sample format.") << endmsg;
912                 error_code = SampleFormatNotSupportedError;
913                 break;
914         default:
915                 PBD::error << _("AlsaAudioBackend: initialization failed.") << endmsg;
916                 error_code = AudioDeviceOpenError;
917                 break;
918         }
919
920         if (_pcmi->state ()) {
921                 delete _pcmi; _pcmi = 0;
922                 release_device();
923                 return error_code;
924         }
925
926 #ifndef NDEBUG
927         _pcmi->printinfo ();
928 #endif
929
930         if (_n_outputs != _pcmi->nplay ()) {
931                 if (_n_outputs == 0) {
932                  _n_outputs = _pcmi->nplay ();
933                 } else {
934                  _n_outputs = std::min (_n_outputs, _pcmi->nplay ());
935                 }
936                 PBD::warning << _("AlsaAudioBackend: adjusted output channel count to match device.") << endmsg;
937         }
938
939         if (_n_inputs != _pcmi->ncapt ()) {
940                 if (_n_inputs == 0) {
941                  _n_inputs = _pcmi->ncapt ();
942                 } else {
943                  _n_inputs = std::min (_n_inputs, _pcmi->ncapt ());
944                 }
945                 PBD::warning << _("AlsaAudioBackend: adjusted input channel count to match device.") << endmsg;
946         }
947
948         if (_pcmi->fsize() != _samples_per_period) {
949                 _samples_per_period = _pcmi->fsize();
950                 PBD::warning << _("AlsaAudioBackend: samples per period does not match.") << endmsg;
951         }
952
953         if (_pcmi->fsamp() != _samplerate) {
954                 _samplerate = _pcmi->fsamp();
955                 engine.sample_rate_change (_samplerate);
956                 PBD::warning << _("AlsaAudioBackend: sample rate does not match.") << endmsg;
957         }
958
959         _measure_latency = for_latency_measurement;
960
961         _midi_ins = _midi_outs = 0;
962         register_system_midi_ports();
963
964         if (register_system_audio_ports()) {
965                 PBD::error << _("AlsaAudioBackend: failed to register system ports.") << endmsg;
966                 delete _pcmi; _pcmi = 0;
967                 release_device();
968                 return PortRegistrationError;
969         }
970
971         engine.sample_rate_change (_samplerate);
972         engine.buffer_size_change (_samples_per_period);
973
974         if (engine.reestablish_ports ()) {
975                 PBD::error << _("AlsaAudioBackend: Could not re-establish ports.") << endmsg;
976                 delete _pcmi; _pcmi = 0;
977                 release_device();
978                 return PortReconnectError;
979         }
980
981         engine.reconnect_ports ();
982         _run = true;
983         _port_change_flag = false;
984
985         if (_realtime_pthread_create (SCHED_FIFO, -20, 100000,
986                                 &_main_thread, pthread_process, this))
987         {
988                 if (pthread_create (&_main_thread, NULL, pthread_process, this))
989                 {
990                         PBD::error << _("AlsaAudioBackend: failed to create process thread.") << endmsg;
991                         delete _pcmi; _pcmi = 0;
992                         release_device();
993                         _run = false;
994                         return ProcessThreadStartError;
995                 } else {
996                         PBD::warning << _("AlsaAudioBackend: cannot acquire realtime permissions.") << endmsg;
997                 }
998         }
999
1000         int timeout = 5000;
1001         while (!_active && --timeout > 0) { Glib::usleep (1000); }
1002
1003         if (timeout == 0 || !_active) {
1004                 PBD::error << _("AlsaAudioBackend: failed to start process thread.") << endmsg;
1005                 delete _pcmi; _pcmi = 0;
1006                 release_device();
1007                 _run = false;
1008                 return ProcessThreadStartError;
1009         }
1010
1011         return NoError;
1012 }
1013
1014 int
1015 AlsaAudioBackend::stop ()
1016 {
1017         void *status;
1018         if (!_run) {
1019                 return 0;
1020         }
1021
1022         _run = false;
1023         if (pthread_join (_main_thread, &status)) {
1024                 PBD::error << _("AlsaAudioBackend: failed to terminate.") << endmsg;
1025                 return -1;
1026         }
1027
1028         while (!_rmidi_out.empty ()) {
1029                 AlsaMidiIO *m = _rmidi_out.back ();
1030                 m->stop();
1031                 _rmidi_out.pop_back ();
1032                 delete m;
1033         }
1034         while (!_rmidi_in.empty ()) {
1035                 AlsaMidiIO *m = _rmidi_in.back ();
1036                 m->stop();
1037                 _rmidi_in.pop_back ();
1038                 delete m;
1039         }
1040
1041         unregister_ports();
1042         delete _pcmi; _pcmi = 0;
1043         _midi_ins = _midi_outs = 0;
1044         release_device();
1045
1046         return (_active == false) ? 0 : -1;
1047 }
1048
1049 int
1050 AlsaAudioBackend::freewheel (bool onoff)
1051 {
1052         _freewheeling = onoff;
1053         return 0;
1054 }
1055
1056 float
1057 AlsaAudioBackend::dsp_load () const
1058 {
1059         return 100.f * _dsp_load;
1060 }
1061
1062 size_t
1063 AlsaAudioBackend::raw_buffer_size (DataType t)
1064 {
1065         switch (t) {
1066                 case DataType::AUDIO:
1067                         return _samples_per_period * sizeof(Sample);
1068                 case DataType::MIDI:
1069                         return _max_buffer_size; // XXX not really limited
1070         }
1071         return 0;
1072 }
1073
1074 /* Process time */
1075 framepos_t
1076 AlsaAudioBackend::sample_time ()
1077 {
1078         return _processed_samples;
1079 }
1080
1081 framepos_t
1082 AlsaAudioBackend::sample_time_at_cycle_start ()
1083 {
1084         return _processed_samples;
1085 }
1086
1087 pframes_t
1088 AlsaAudioBackend::samples_since_cycle_start ()
1089 {
1090         if (!_active || !_run || _freewheeling || _freewheel) {
1091                 return 0;
1092         }
1093         if (_last_process_start == 0) {
1094                 return 0;
1095         }
1096
1097         const int64_t elapsed_time_us = g_get_monotonic_time() - _last_process_start;
1098         return std::max((pframes_t)0, (pframes_t)rint(1e-6 * elapsed_time_us * _samplerate));
1099 }
1100
1101
1102 void *
1103 AlsaAudioBackend::alsa_process_thread (void *arg)
1104 {
1105         ThreadData* td = reinterpret_cast<ThreadData*> (arg);
1106         boost::function<void ()> f = td->f;
1107         delete td;
1108         f ();
1109         return 0;
1110 }
1111
1112 int
1113 AlsaAudioBackend::create_process_thread (boost::function<void()> func)
1114 {
1115         pthread_t thread_id;
1116         pthread_attr_t attr;
1117         size_t stacksize = 100000;
1118
1119         ThreadData* td = new ThreadData (this, func, stacksize);
1120
1121         if (_realtime_pthread_create (SCHED_FIFO, -21, stacksize,
1122                                 &thread_id, alsa_process_thread, td)) {
1123                 pthread_attr_init (&attr);
1124                 pthread_attr_setstacksize (&attr, stacksize);
1125                 if (pthread_create (&thread_id, &attr, alsa_process_thread, td)) {
1126                         PBD::error << _("AudioEngine: cannot create process thread.") << endmsg;
1127                         pthread_attr_destroy (&attr);
1128                         return -1;
1129                 }
1130                 pthread_attr_destroy (&attr);
1131         }
1132
1133         _threads.push_back (thread_id);
1134         return 0;
1135 }
1136
1137 int
1138 AlsaAudioBackend::join_process_threads ()
1139 {
1140         int rv = 0;
1141
1142         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
1143         {
1144                 void *status;
1145                 if (pthread_join (*i, &status)) {
1146                         PBD::error << _("AudioEngine: cannot terminate process thread.") << endmsg;
1147                         rv -= 1;
1148                 }
1149         }
1150         _threads.clear ();
1151         return rv;
1152 }
1153
1154 bool
1155 AlsaAudioBackend::in_process_thread ()
1156 {
1157         if (pthread_equal (_main_thread, pthread_self()) != 0) {
1158                 return true;
1159         }
1160
1161         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
1162         {
1163                 if (pthread_equal (*i, pthread_self ()) != 0) {
1164                         return true;
1165                 }
1166         }
1167         return false;
1168 }
1169
1170 uint32_t
1171 AlsaAudioBackend::process_thread_count ()
1172 {
1173         return _threads.size ();
1174 }
1175
1176 void
1177 AlsaAudioBackend::update_latencies ()
1178 {
1179         // trigger latency callback in RT thread (locked graph)
1180         port_connect_add_remove_callback();
1181 }
1182
1183 /* PORTENGINE API */
1184
1185 void*
1186 AlsaAudioBackend::private_handle () const
1187 {
1188         return NULL;
1189 }
1190
1191 const std::string&
1192 AlsaAudioBackend::my_name () const
1193 {
1194         return _instance_name;
1195 }
1196
1197 bool
1198 AlsaAudioBackend::available () const
1199 {
1200         return _run && _active;
1201 }
1202
1203 uint32_t
1204 AlsaAudioBackend::port_name_size () const
1205 {
1206         return 256;
1207 }
1208
1209 int
1210 AlsaAudioBackend::set_port_name (PortEngine::PortHandle port, const std::string& name)
1211 {
1212         if (!valid_port (port)) {
1213                 PBD::error << _("AlsaBackend::set_port_name: Invalid Port(s)") << endmsg;
1214                 return -1;
1215         }
1216         return static_cast<AlsaPort*>(port)->set_name (_instance_name + ":" + name);
1217 }
1218
1219 std::string
1220 AlsaAudioBackend::get_port_name (PortEngine::PortHandle port) const
1221 {
1222         if (!valid_port (port)) {
1223                 PBD::warning << _("AlsaBackend::get_port_name: Invalid Port(s)") << endmsg;
1224                 return std::string ();
1225         }
1226         return static_cast<AlsaPort*>(port)->name ();
1227 }
1228
1229 int
1230 AlsaAudioBackend::get_port_property (PortHandle port, const std::string& key, std::string& value, std::string& type) const
1231 {
1232         if (!valid_port (port)) {
1233                 PBD::warning << _("AlsaBackend::get_port_property: Invalid Port(s)") << endmsg;
1234                 return -1;
1235         }
1236         if (key == "http://jackaudio.org/metadata/pretty-name") {
1237                 type = "";
1238                 value = static_cast<AlsaPort*>(port)->pretty_name ();
1239                 if (!value.empty()) {
1240                         return 0;
1241                 }
1242         }
1243         return -1;
1244 }
1245
1246 PortEngine::PortHandle
1247 AlsaAudioBackend::get_port_by_name (const std::string& name) const
1248 {
1249         PortHandle port = (PortHandle) find_port (name);
1250         return port;
1251 }
1252
1253 int
1254 AlsaAudioBackend::get_ports (
1255                 const std::string& port_name_pattern,
1256                 DataType type, PortFlags flags,
1257                 std::vector<std::string>& port_names) const
1258 {
1259         int rv = 0;
1260         regex_t port_regex;
1261         bool use_regexp = false;
1262         if (port_name_pattern.size () > 0) {
1263                 if (!regcomp (&port_regex, port_name_pattern.c_str (), REG_EXTENDED|REG_NOSUB)) {
1264                         use_regexp = true;
1265                 }
1266         }
1267         for (size_t i = 0; i < _ports.size (); ++i) {
1268                 AlsaPort* port = _ports[i];
1269                 if ((port->type () == type) && flags == (port->flags () & flags)) {
1270                         if (!use_regexp || !regexec (&port_regex, port->name ().c_str (), 0, NULL, 0)) {
1271                                 port_names.push_back (port->name ());
1272                                 ++rv;
1273                         }
1274                 }
1275         }
1276         if (use_regexp) {
1277                 regfree (&port_regex);
1278         }
1279         return rv;
1280 }
1281
1282 DataType
1283 AlsaAudioBackend::port_data_type (PortEngine::PortHandle port) const
1284 {
1285         if (!valid_port (port)) {
1286                 return DataType::NIL;
1287         }
1288         return static_cast<AlsaPort*>(port)->type ();
1289 }
1290
1291 PortEngine::PortHandle
1292 AlsaAudioBackend::register_port (
1293                 const std::string& name,
1294                 ARDOUR::DataType type,
1295                 ARDOUR::PortFlags flags)
1296 {
1297         if (name.size () == 0) { return 0; }
1298         if (flags & IsPhysical) { return 0; }
1299         return add_port (_instance_name + ":" + name, type, flags);
1300 }
1301
1302 PortEngine::PortHandle
1303 AlsaAudioBackend::add_port (
1304                 const std::string& name,
1305                 ARDOUR::DataType type,
1306                 ARDOUR::PortFlags flags)
1307 {
1308         assert(name.size ());
1309         if (find_port (name)) {
1310                 PBD::error << _("AlsaBackend::register_port: Port already exists:")
1311                                 << " (" << name << ")" << endmsg;
1312                 return 0;
1313         }
1314         AlsaPort* port = NULL;
1315         switch (type) {
1316                 case DataType::AUDIO:
1317                         port = new AlsaAudioPort (*this, name, flags);
1318                         break;
1319                 case DataType::MIDI:
1320                         port = new AlsaMidiPort (*this, name, flags);
1321                         break;
1322                 default:
1323                         PBD::error << _("AlsaBackend::register_port: Invalid Data Type.") << endmsg;
1324                         return 0;
1325         }
1326
1327         _ports.push_back (port);
1328
1329         return port;
1330 }
1331
1332 void
1333 AlsaAudioBackend::unregister_port (PortEngine::PortHandle port_handle)
1334 {
1335         if (!_run) {
1336                 return;
1337         }
1338         AlsaPort* port = static_cast<AlsaPort*>(port_handle);
1339         std::vector<AlsaPort*>::iterator i = std::find (_ports.begin (), _ports.end (), static_cast<AlsaPort*>(port_handle));
1340         if (i == _ports.end ()) {
1341                 PBD::error << _("AlsaBackend::unregister_port: Failed to find port") << endmsg;
1342                 return;
1343         }
1344         disconnect_all(port_handle);
1345         _ports.erase (i);
1346         delete port;
1347 }
1348
1349 int
1350 AlsaAudioBackend::register_system_audio_ports()
1351 {
1352         LatencyRange lr;
1353
1354         const int a_ins = _n_inputs;
1355         const int a_out = _n_outputs;
1356
1357         const uint32_t lcpp = (_periods_per_cycle - 2) * _samples_per_period;
1358
1359         /* audio ports */
1360         lr.min = lr.max = (_measure_latency ? 0 : _systemic_audio_input_latency);
1361         for (int i = 1; i <= a_ins; ++i) {
1362                 char tmp[64];
1363                 snprintf(tmp, sizeof(tmp), "system:capture_%d", i);
1364                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
1365                 if (!p) return -1;
1366                 set_latency_range (p, false, lr);
1367                 AlsaPort *ap = static_cast<AlsaPort*>(p);
1368                 //ap->set_pretty_name ("")
1369                 _system_inputs.push_back (ap);
1370         }
1371
1372         lr.min = lr.max = lcpp + (_measure_latency ? 0 : _systemic_audio_output_latency);
1373         for (int i = 1; i <= a_out; ++i) {
1374                 char tmp[64];
1375                 snprintf(tmp, sizeof(tmp), "system:playback_%d", i);
1376                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
1377                 if (!p) return -1;
1378                 set_latency_range (p, true, lr);
1379                 AlsaPort *ap = static_cast<AlsaPort*>(p);
1380                 //ap->set_pretty_name ("")
1381                 _system_outputs.push_back (ap);
1382         }
1383         return 0;
1384 }
1385
1386 int
1387 AlsaAudioBackend::register_system_midi_ports(const std::string device)
1388 {
1389         std::map<std::string, std::string> devices;
1390
1391         // TODO use consistent numbering when re-adding devices: _midi_ins, _midi_outs
1392
1393         if (_midi_driver_option == get_standard_device_name(DeviceNone)) {
1394                 return 0;
1395         } else if (_midi_driver_option == _("ALSA raw devices")) {
1396                 get_alsa_rawmidi_device_names(devices);
1397         } else {
1398                 get_alsa_sequencer_names (devices);
1399         }
1400
1401         for (std::map<std::string, std::string>::const_iterator i = devices.begin (); i != devices.end(); ++i) {
1402                 if (!device.empty() && device != i->first) {
1403                         continue;
1404                 }
1405                 struct AlsaMidiDeviceInfo * nfo = midi_device_info(i->first);
1406                 if (!nfo) continue;
1407                 if (!nfo->enabled) continue;
1408
1409                 AlsaMidiOut *mout;
1410                 if (_midi_driver_option == _("ALSA raw devices")) {
1411                         mout = new AlsaRawMidiOut (i->first, i->second.c_str());
1412                 } else {
1413                         mout = new AlsaSeqMidiOut (i->first, i->second.c_str());
1414                 }
1415
1416                 if (mout->state ()) {
1417                         PBD::warning << string_compose (
1418                                         _("AlsaMidiOut: failed to open midi device '%1'."), i->second)
1419                                 << endmsg;
1420                         delete mout;
1421                 } else {
1422                         mout->setup_timing(_samples_per_period, _samplerate);
1423                         mout->sync_time (g_get_monotonic_time());
1424                         if (mout->start ()) {
1425                                 PBD::warning << string_compose (
1426                                                 _("AlsaMidiOut: failed to start midi device '%1'."), i->second)
1427                                         << endmsg;
1428                                 delete mout;
1429                         } else {
1430                                 char tmp[64];
1431                                 snprintf(tmp, sizeof(tmp), "system:midi_playback_%d", ++_midi_ins);
1432                                 PortHandle p = add_port(std::string(tmp), DataType::MIDI, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
1433                                 if (!p) {
1434                                         mout->stop();
1435                                         delete mout;
1436                                 }
1437                                 LatencyRange lr;
1438                                 lr.min = lr.max = (_measure_latency ? 0 : nfo->systemic_output_latency);
1439                                 set_latency_range (p, true, lr);
1440                                 static_cast<AlsaMidiPort*>(p)->set_n_periods(_periods_per_cycle); // TODO check MIDI alignment
1441                                 AlsaPort *ap = static_cast<AlsaPort*>(p);
1442                                 ap->set_pretty_name (i->first);
1443                                 _system_midi_out.push_back (ap);
1444                                 _rmidi_out.push_back (mout);
1445                         }
1446                 }
1447
1448                 AlsaMidiIn *midin;
1449                 if (_midi_driver_option == _("ALSA raw devices")) {
1450                         midin = new AlsaRawMidiIn (i->first, i->second.c_str());
1451                 } else {
1452                         midin = new AlsaSeqMidiIn (i->first, i->second.c_str());
1453                 }
1454
1455                 if (midin->state ()) {
1456                         PBD::warning << string_compose (
1457                                         _("AlsaMidiIn: failed to open midi device '%1'."), i->second)
1458                                 << endmsg;
1459                         delete midin;
1460                 } else {
1461                         midin->setup_timing(_samples_per_period, _samplerate);
1462                         midin->sync_time (g_get_monotonic_time());
1463                         if (midin->start ()) {
1464                                 PBD::warning << string_compose (
1465                                                 _("AlsaMidiIn: failed to start midi device '%1'."), i->second)
1466                                         << endmsg;
1467                                 delete midin;
1468                         } else {
1469                                 char tmp[64];
1470                                 snprintf(tmp, sizeof(tmp), "system:midi_capture_%d", ++_midi_outs);
1471                                 PortHandle p = add_port(std::string(tmp), DataType::MIDI, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
1472                                 if (!p) {
1473                                         midin->stop();
1474                                         delete midin;
1475                                         continue;
1476                                 }
1477                                 LatencyRange lr;
1478                                 lr.min = lr.max = (_measure_latency ? 0 : nfo->systemic_input_latency);
1479                                 set_latency_range (p, false, lr);
1480                                 AlsaPort *ap = static_cast<AlsaPort*>(p);
1481                                 ap->set_pretty_name (i->first);
1482                                 _system_midi_in.push_back (ap);
1483                                 _rmidi_in.push_back (midin);
1484                         }
1485                 }
1486         }
1487         return 0;
1488 }
1489
1490 void
1491 AlsaAudioBackend::unregister_ports (bool system_only)
1492 {
1493         size_t i = 0;
1494         _system_inputs.clear();
1495         _system_outputs.clear();
1496         _system_midi_in.clear();
1497         _system_midi_out.clear();
1498         while (i <  _ports.size ()) {
1499                 AlsaPort* port = _ports[i];
1500                 if (! system_only || (port->is_physical () && port->is_terminal ())) {
1501                         port->disconnect_all ();
1502                         delete port;
1503                         _ports.erase (_ports.begin() + i);
1504                 } else {
1505                         ++i;
1506                 }
1507         }
1508 }
1509
1510 int
1511 AlsaAudioBackend::connect (const std::string& src, const std::string& dst)
1512 {
1513         AlsaPort* src_port = find_port (src);
1514         AlsaPort* dst_port = find_port (dst);
1515
1516         if (!src_port) {
1517                 PBD::error << _("AlsaBackend::connect: Invalid Source port:")
1518                                 << " (" << src <<")" << endmsg;
1519                 return -1;
1520         }
1521         if (!dst_port) {
1522                 PBD::error << _("AlsaBackend::connect: Invalid Destination port:")
1523                         << " (" << dst <<")" << endmsg;
1524                 return -1;
1525         }
1526         return src_port->connect (dst_port);
1527 }
1528
1529 int
1530 AlsaAudioBackend::disconnect (const std::string& src, const std::string& dst)
1531 {
1532         AlsaPort* src_port = find_port (src);
1533         AlsaPort* dst_port = find_port (dst);
1534
1535         if (!src_port || !dst_port) {
1536                 PBD::error << _("AlsaBackend::disconnect: Invalid Port(s)") << endmsg;
1537                 return -1;
1538         }
1539         return src_port->disconnect (dst_port);
1540 }
1541
1542 int
1543 AlsaAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
1544 {
1545         AlsaPort* dst_port = find_port (dst);
1546         if (!valid_port (src)) {
1547                 PBD::error << _("AlsaBackend::connect: Invalid Source Port Handle") << endmsg;
1548                 return -1;
1549         }
1550         if (!dst_port) {
1551                 PBD::error << _("AlsaBackend::connect: Invalid Destination Port")
1552                         << " (" << dst << ")" << endmsg;
1553                 return -1;
1554         }
1555         return static_cast<AlsaPort*>(src)->connect (dst_port);
1556 }
1557
1558 int
1559 AlsaAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
1560 {
1561         AlsaPort* dst_port = find_port (dst);
1562         if (!valid_port (src) || !dst_port) {
1563                 PBD::error << _("AlsaBackend::disconnect: Invalid Port(s)") << endmsg;
1564                 return -1;
1565         }
1566         return static_cast<AlsaPort*>(src)->disconnect (dst_port);
1567 }
1568
1569 int
1570 AlsaAudioBackend::disconnect_all (PortEngine::PortHandle port)
1571 {
1572         if (!valid_port (port)) {
1573                 PBD::error << _("AlsaBackend::disconnect_all: Invalid Port") << endmsg;
1574                 return -1;
1575         }
1576         static_cast<AlsaPort*>(port)->disconnect_all ();
1577         return 0;
1578 }
1579
1580 bool
1581 AlsaAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
1582 {
1583         if (!valid_port (port)) {
1584                 PBD::error << _("AlsaBackend::disconnect_all: Invalid Port") << endmsg;
1585                 return false;
1586         }
1587         return static_cast<AlsaPort*>(port)->is_connected ();
1588 }
1589
1590 bool
1591 AlsaAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
1592 {
1593         AlsaPort* dst_port = find_port (dst);
1594         if (!valid_port (src) || !dst_port) {
1595                 PBD::error << _("AlsaBackend::connected_to: Invalid Port") << endmsg;
1596                 return false;
1597         }
1598         return static_cast<AlsaPort*>(src)->is_connected (dst_port);
1599 }
1600
1601 bool
1602 AlsaAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
1603 {
1604         if (!valid_port (port)) {
1605                 PBD::error << _("AlsaBackend::physically_connected: Invalid Port") << endmsg;
1606                 return false;
1607         }
1608         return static_cast<AlsaPort*>(port)->is_physically_connected ();
1609 }
1610
1611 int
1612 AlsaAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
1613 {
1614         if (!valid_port (port)) {
1615                 PBD::error << _("AlsaBackend::get_connections: Invalid Port") << endmsg;
1616                 return -1;
1617         }
1618
1619         assert (0 == names.size ());
1620
1621         const std::vector<AlsaPort*>& connected_ports = static_cast<AlsaPort*>(port)->get_connections ();
1622
1623         for (std::vector<AlsaPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
1624                 names.push_back ((*i)->name ());
1625         }
1626
1627         return (int)names.size ();
1628 }
1629
1630 /* MIDI */
1631 int
1632 AlsaAudioBackend::midi_event_get (
1633                 pframes_t& timestamp,
1634                 size_t& size, uint8_t** buf, void* port_buffer,
1635                 uint32_t event_index)
1636 {
1637         assert (buf && port_buffer);
1638         AlsaMidiBuffer& source = * static_cast<AlsaMidiBuffer*>(port_buffer);
1639         if (event_index >= source.size ()) {
1640                 return -1;
1641         }
1642         AlsaMidiEvent * const event = source[event_index].get ();
1643
1644         timestamp = event->timestamp ();
1645         size = event->size ();
1646         *buf = event->data ();
1647         return 0;
1648 }
1649
1650 int
1651 AlsaAudioBackend::midi_event_put (
1652                 void* port_buffer,
1653                 pframes_t timestamp,
1654                 const uint8_t* buffer, size_t size)
1655 {
1656         assert (buffer && port_buffer);
1657         AlsaMidiBuffer& dst = * static_cast<AlsaMidiBuffer*>(port_buffer);
1658         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
1659 #ifndef NDEBUG
1660                 // nevermind, ::get_buffer() sorts events
1661                 fprintf (stderr, "AlsaMidiBuffer: it's too late for this event. %d > %d\n",
1662                                 (pframes_t)dst.back ()->timestamp (), timestamp);
1663 #endif
1664         }
1665         dst.push_back (boost::shared_ptr<AlsaMidiEvent>(new AlsaMidiEvent (timestamp, buffer, size)));
1666         return 0;
1667 }
1668
1669 uint32_t
1670 AlsaAudioBackend::get_midi_event_count (void* port_buffer)
1671 {
1672         assert (port_buffer);
1673         return static_cast<AlsaMidiBuffer*>(port_buffer)->size ();
1674 }
1675
1676 void
1677 AlsaAudioBackend::midi_clear (void* port_buffer)
1678 {
1679         assert (port_buffer);
1680         AlsaMidiBuffer * buf = static_cast<AlsaMidiBuffer*>(port_buffer);
1681         assert (buf);
1682         buf->clear ();
1683 }
1684
1685 /* Monitoring */
1686
1687 bool
1688 AlsaAudioBackend::can_monitor_input () const
1689 {
1690         return false;
1691 }
1692
1693 int
1694 AlsaAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1695 {
1696         return -1;
1697 }
1698
1699 int
1700 AlsaAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1701 {
1702         return -1;
1703 }
1704
1705 bool
1706 AlsaAudioBackend::monitoring_input (PortEngine::PortHandle)
1707 {
1708         return false;
1709 }
1710
1711 /* Latency management */
1712
1713 void
1714 AlsaAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1715 {
1716         if (!valid_port (port)) {
1717                 PBD::error << _("AlsaPort::set_latency_range (): invalid port.") << endmsg;
1718         }
1719         static_cast<AlsaPort*>(port)->set_latency_range (latency_range, for_playback);
1720 }
1721
1722 LatencyRange
1723 AlsaAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1724 {
1725         LatencyRange r;
1726         if (!valid_port (port)) {
1727                 PBD::error << _("AlsaPort::get_latency_range (): invalid port.") << endmsg;
1728                 r.min = 0;
1729                 r.max = 0;
1730                 return r;
1731         }
1732         AlsaPort *p = static_cast<AlsaPort*>(port);
1733         assert(p);
1734
1735         r = p->latency_range (for_playback);
1736         if (p->is_physical() && p->is_terminal()) {
1737                 if (p->is_input() && for_playback) {
1738                         r.min += _samples_per_period;
1739                         r.max += _samples_per_period;
1740                 }
1741                 if (p->is_output() && !for_playback) {
1742                         r.min += _samples_per_period;
1743                         r.max += _samples_per_period;
1744                 }
1745         }
1746         return r;
1747 }
1748
1749 /* Discovering physical ports */
1750
1751 bool
1752 AlsaAudioBackend::port_is_physical (PortEngine::PortHandle port) const
1753 {
1754         if (!valid_port (port)) {
1755                 PBD::error << _("AlsaPort::port_is_physical (): invalid port.") << endmsg;
1756                 return false;
1757         }
1758         return static_cast<AlsaPort*>(port)->is_physical ();
1759 }
1760
1761 void
1762 AlsaAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1763 {
1764         for (size_t i = 0; i < _ports.size (); ++i) {
1765                 AlsaPort* port = _ports[i];
1766                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1767                         port_names.push_back (port->name ());
1768                 }
1769         }
1770 }
1771
1772 void
1773 AlsaAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1774 {
1775         for (size_t i = 0; i < _ports.size (); ++i) {
1776                 AlsaPort* port = _ports[i];
1777                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1778                         port_names.push_back (port->name ());
1779                 }
1780         }
1781 }
1782
1783 ChanCount
1784 AlsaAudioBackend::n_physical_outputs () const
1785 {
1786         int n_midi = 0;
1787         int n_audio = 0;
1788         for (size_t i = 0; i < _ports.size (); ++i) {
1789                 AlsaPort* port = _ports[i];
1790                 if (port->is_output () && port->is_physical ()) {
1791                         switch (port->type ()) {
1792                                 case DataType::AUDIO: ++n_audio; break;
1793                                 case DataType::MIDI: ++n_midi; break;
1794                                 default: break;
1795                         }
1796                 }
1797         }
1798         ChanCount cc;
1799         cc.set (DataType::AUDIO, n_audio);
1800         cc.set (DataType::MIDI, n_midi);
1801         return cc;
1802 }
1803
1804 ChanCount
1805 AlsaAudioBackend::n_physical_inputs () const
1806 {
1807         int n_midi = 0;
1808         int n_audio = 0;
1809         for (size_t i = 0; i < _ports.size (); ++i) {
1810                 AlsaPort* port = _ports[i];
1811                 if (port->is_input () && port->is_physical ()) {
1812                         switch (port->type ()) {
1813                                 case DataType::AUDIO: ++n_audio; break;
1814                                 case DataType::MIDI: ++n_midi; break;
1815                                 default: break;
1816                         }
1817                 }
1818         }
1819         ChanCount cc;
1820         cc.set (DataType::AUDIO, n_audio);
1821         cc.set (DataType::MIDI, n_midi);
1822         return cc;
1823 }
1824
1825 /* Getting access to the data buffer for a port */
1826
1827 void*
1828 AlsaAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1829 {
1830         assert (port);
1831         assert (valid_port (port));
1832         return static_cast<AlsaPort*>(port)->get_buffer (nframes);
1833 }
1834
1835 /* Engine Process */
1836 void *
1837 AlsaAudioBackend::main_process_thread ()
1838 {
1839         AudioEngine::thread_init_callback (this);
1840         _active = true;
1841         _processed_samples = 0;
1842
1843         uint64_t clock1;
1844         _pcmi->pcm_start ();
1845         int no_proc_errors = 0;
1846         const int bailout = 2 * _samplerate / _samples_per_period;
1847
1848         manager.registration_callback();
1849         manager.graph_order_callback();
1850
1851         while (_run) {
1852                 long nr;
1853                 bool xrun = false;
1854
1855                 if (_freewheeling != _freewheel) {
1856                         _freewheel = _freewheeling;
1857                         engine.freewheel_callback (_freewheel);
1858                 }
1859
1860                 if (!_freewheel) {
1861                         nr = _pcmi->pcm_wait ();
1862
1863                         if (_pcmi->state () > 0) {
1864                                 ++no_proc_errors;
1865                                 xrun = true;
1866                         }
1867                         if (_pcmi->state () < 0) {
1868                                 PBD::error << _("AlsaAudioBackend: I/O error. Audio Process Terminated.") << endmsg;
1869                                 break;
1870                         }
1871                         if (no_proc_errors > bailout) {
1872                                 PBD::error
1873                                         << string_compose (
1874                                                         _("AlsaAudioBackend: Audio Process Terminated after %1 consecutive x-runs."),
1875                                                         no_proc_errors)
1876                                         << endmsg;
1877                                 break;
1878                         }
1879
1880                         while (nr >= (long)_samples_per_period && _freewheeling == _freewheel) {
1881                                 uint32_t i = 0;
1882                                 clock1 = g_get_monotonic_time();
1883                                 no_proc_errors = 0;
1884
1885                                 _pcmi->capt_init (_samples_per_period);
1886                                 for (std::vector<AlsaPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++i) {
1887                                         _pcmi->capt_chan (i, (float*)((*it)->get_buffer(_samples_per_period)), _samples_per_period);
1888                                 }
1889                                 _pcmi->capt_done (_samples_per_period);
1890
1891                                 /* de-queue incoming midi*/
1892                                 i = 0;
1893                                 for (std::vector<AlsaPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++i) {
1894                                         assert (_rmidi_in.size() > i);
1895                                         AlsaMidiIn *rm = _rmidi_in.at(i);
1896                                         void *bptr = (*it)->get_buffer(0);
1897                                         pframes_t time;
1898                                         uint8_t data[64]; // match MaxAlsaEventSize in alsa_rawmidi.cc
1899                                         size_t size = sizeof(data);
1900                                         midi_clear(bptr);
1901                                         while (rm->recv_event (time, data, size)) {
1902                                                 midi_event_put(bptr, time, data, size);
1903                                                 size = sizeof(data);
1904                                         }
1905                                         rm->sync_time (clock1);
1906                                 }
1907
1908                                 for (std::vector<AlsaPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it) {
1909                                         memset ((*it)->get_buffer (_samples_per_period), 0, _samples_per_period * sizeof (Sample));
1910                                 }
1911
1912                                 /* call engine process callback */
1913                                 _last_process_start = g_get_monotonic_time();
1914                                 if (engine.process_callback (_samples_per_period)) {
1915                                         _pcmi->pcm_stop ();
1916                                         _active = false;
1917                                         return 0;
1918                                 }
1919
1920                                 for (std::vector<AlsaPort*>::iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it) {
1921                                         static_cast<AlsaMidiPort*>(*it)->next_period();
1922                                 }
1923
1924                                 /* queue outgoing midi */
1925                                 i = 0;
1926                                 for (std::vector<AlsaPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it, ++i) {
1927                                         assert (_rmidi_out.size() > i);
1928                                         const AlsaMidiBuffer * src = static_cast<const AlsaMidiPort*>(*it)->const_buffer();
1929                                         AlsaMidiOut *rm = _rmidi_out.at(i);
1930                                         rm->sync_time (clock1);
1931                                         for (AlsaMidiBuffer::const_iterator mit = src->begin (); mit != src->end (); ++mit) {
1932                                                 rm->send_event ((*mit)->timestamp(), (*mit)->data(), (*mit)->size());
1933                                         }
1934                                 }
1935
1936                                 /* write back audio */
1937                                 i = 0;
1938                                 _pcmi->play_init (_samples_per_period);
1939                                 for (std::vector<AlsaPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it, ++i) {
1940                                         _pcmi->play_chan (i, (const float*)(*it)->get_buffer (_samples_per_period), _samples_per_period);
1941                                 }
1942                                 for (; i < _pcmi->nplay (); ++i) {
1943                                         _pcmi->clear_chan (i, _samples_per_period);
1944                                 }
1945                                 _pcmi->play_done (_samples_per_period);
1946                                 nr -= _samples_per_period;
1947                                 _processed_samples += _samples_per_period;
1948
1949                                 _dsp_load_calc.set_max_time(_samplerate, _samples_per_period);
1950                                 _dsp_load_calc.set_start_timestamp_us (clock1);
1951                                 _dsp_load_calc.set_stop_timestamp_us (g_get_monotonic_time());
1952                                 _dsp_load = _dsp_load_calc.get_dsp_load ();
1953                         }
1954
1955                         if (xrun && (_pcmi->capt_xrun() > 0 || _pcmi->play_xrun() > 0)) {
1956                                 engine.Xrun ();
1957 #if 0
1958                                 fprintf(stderr, "ALSA x-run read: %.2f ms, write: %.2f ms\n",
1959                                                 _pcmi->capt_xrun() * 1000.0, _pcmi->play_xrun() * 1000.0);
1960 #endif
1961                         }
1962                 } else {
1963                         // Freewheelin'
1964
1965                         // zero audio input buffers
1966                         for (std::vector<AlsaPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
1967                                 memset ((*it)->get_buffer (_samples_per_period), 0, _samples_per_period * sizeof (Sample));
1968                         }
1969
1970                         clock1 = g_get_monotonic_time();
1971                         uint32_t i = 0;
1972                         for (std::vector<AlsaPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++i) {
1973                                 static_cast<AlsaMidiBuffer*>((*it)->get_buffer(0))->clear ();
1974                                 AlsaMidiIn *rm = _rmidi_in.at(i);
1975                                 void *bptr = (*it)->get_buffer(0);
1976                                 midi_clear(bptr); // zero midi buffer
1977
1978                                 // TODO add an API call for this.
1979                                 pframes_t time;
1980                                 uint8_t data[64]; // match MaxAlsaEventSize in alsa_rawmidi.cc
1981                                 size_t size = sizeof(data);
1982                                 while (rm->recv_event (time, data, size)) {
1983                                         ; // discard midi-data from HW.
1984                                 }
1985                                 rm->sync_time (clock1);
1986                         }
1987
1988                         _last_process_start = 0;
1989                         if (engine.process_callback (_samples_per_period)) {
1990                                 _pcmi->pcm_stop ();
1991                                 _active = false;
1992                                 return 0;
1993                         }
1994
1995                         // drop all outgoing MIDI messages
1996                         for (std::vector<AlsaPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it) {
1997                                         void *bptr = (*it)->get_buffer(0);
1998                                         midi_clear(bptr);
1999                         }
2000
2001                         _dsp_load = 1.0;
2002                         Glib::usleep (100); // don't hog cpu
2003                 }
2004
2005                 bool connections_changed = false;
2006                 bool ports_changed = false;
2007                 if (!pthread_mutex_trylock (&_port_callback_mutex)) {
2008                         if (_port_change_flag) {
2009                                 ports_changed = true;
2010                                 _port_change_flag = false;
2011                         }
2012                         if (!_port_connection_queue.empty ()) {
2013                                 connections_changed = true;
2014                         }
2015                         while (!_port_connection_queue.empty ()) {
2016                                 PortConnectData *c = _port_connection_queue.back ();
2017                                 manager.connect_callback (c->a, c->b, c->c);
2018                                 _port_connection_queue.pop_back ();
2019                                 delete c;
2020                         }
2021                         pthread_mutex_unlock (&_port_callback_mutex);
2022                 }
2023                 if (ports_changed) {
2024                         manager.registration_callback();
2025                 }
2026                 if (connections_changed) {
2027                         manager.graph_order_callback();
2028                 }
2029                 if (connections_changed || ports_changed) {
2030                         engine.latency_callback(false);
2031                         engine.latency_callback(true);
2032                 }
2033
2034         }
2035         _pcmi->pcm_stop ();
2036         _active = false;
2037         if (_run) {
2038                 engine.halted_callback("ALSA I/O error.");
2039         }
2040         return 0;
2041 }
2042
2043
2044 /******************************************************************************/
2045
2046 static boost::shared_ptr<AlsaAudioBackend> _instance;
2047
2048 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
2049 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
2050 static int deinstantiate ();
2051 static bool already_configured ();
2052 static bool available ();
2053
2054 static ARDOUR::AudioBackendInfo _descriptor = {
2055         "ALSA",
2056         instantiate,
2057         deinstantiate,
2058         backend_factory,
2059         already_configured,
2060         available
2061 };
2062
2063 static boost::shared_ptr<AudioBackend>
2064 backend_factory (AudioEngine& e)
2065 {
2066         if (!_instance) {
2067                 _instance.reset (new AlsaAudioBackend (e, _descriptor));
2068         }
2069         return _instance;
2070 }
2071
2072 static int
2073 instantiate (const std::string& arg1, const std::string& /* arg2 */)
2074 {
2075         s_instance_name = arg1;
2076         return 0;
2077 }
2078
2079 static int
2080 deinstantiate ()
2081 {
2082         _instance.reset ();
2083         return 0;
2084 }
2085
2086 static bool
2087 already_configured ()
2088 {
2089         return false;
2090 }
2091
2092 static bool
2093 available ()
2094 {
2095         return true;
2096 }
2097
2098 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
2099 {
2100         return &_descriptor;
2101 }
2102
2103
2104 /******************************************************************************/
2105 AlsaPort::AlsaPort (AlsaAudioBackend &b, const std::string& name, PortFlags flags)
2106         : _alsa_backend (b)
2107         , _name  (name)
2108         , _flags (flags)
2109 {
2110         _capture_latency_range.min = 0;
2111         _capture_latency_range.max = 0;
2112         _playback_latency_range.min = 0;
2113         _playback_latency_range.max = 0;
2114 }
2115
2116 AlsaPort::~AlsaPort () {
2117         disconnect_all ();
2118 }
2119
2120
2121 int AlsaPort::connect (AlsaPort *port)
2122 {
2123         if (!port) {
2124                 PBD::error << _("AlsaPort::connect (): invalid (null) port") << endmsg;
2125                 return -1;
2126         }
2127
2128         if (type () != port->type ()) {
2129                 PBD::error << _("AlsaPort::connect (): wrong port-type") << endmsg;
2130                 return -1;
2131         }
2132
2133         if (is_output () && port->is_output ()) {
2134                 PBD::error << _("AlsaPort::connect (): cannot inter-connect output ports.") << endmsg;
2135                 return -1;
2136         }
2137
2138         if (is_input () && port->is_input ()) {
2139                 PBD::error << _("AlsaPort::connect (): cannot inter-connect input ports.") << endmsg;
2140                 return -1;
2141         }
2142
2143         if (this == port) {
2144                 PBD::error << _("AlsaPort::connect (): cannot self-connect ports.") << endmsg;
2145                 return -1;
2146         }
2147
2148         if (is_connected (port)) {
2149 #if 0 // don't bother to warn about this for now. just ignore it
2150                 PBD::error << _("AlsaPort::connect (): ports are already connected:")
2151                         << " (" << name () << ") -> (" << port->name () << ")"
2152                         << endmsg;
2153 #endif
2154                 return -1;
2155         }
2156
2157         _connect (port, true);
2158         return 0;
2159 }
2160
2161
2162 void AlsaPort::_connect (AlsaPort *port, bool callback)
2163 {
2164         _connections.push_back (port);
2165         if (callback) {
2166                 port->_connect (this, false);
2167                 _alsa_backend.port_connect_callback (name(),  port->name(), true);
2168         }
2169 }
2170
2171 int AlsaPort::disconnect (AlsaPort *port)
2172 {
2173         if (!port) {
2174                 PBD::error << _("AlsaPort::disconnect (): invalid (null) port") << endmsg;
2175                 return -1;
2176         }
2177
2178         if (!is_connected (port)) {
2179                 PBD::error << _("AlsaPort::disconnect (): ports are not connected:")
2180                         << " (" << name () << ") -> (" << port->name () << ")"
2181                         << endmsg;
2182                 return -1;
2183         }
2184         _disconnect (port, true);
2185         return 0;
2186 }
2187
2188 void AlsaPort::_disconnect (AlsaPort *port, bool callback)
2189 {
2190         std::vector<AlsaPort*>::iterator it = std::find (_connections.begin (), _connections.end (), port);
2191
2192         assert (it != _connections.end ());
2193
2194         _connections.erase (it);
2195
2196         if (callback) {
2197                 port->_disconnect (this, false);
2198                 _alsa_backend.port_connect_callback (name(),  port->name(), false);
2199         }
2200 }
2201
2202
2203 void AlsaPort::disconnect_all ()
2204 {
2205         while (!_connections.empty ()) {
2206                 _connections.back ()->_disconnect (this, false);
2207                 _alsa_backend.port_connect_callback (name(),  _connections.back ()->name(), false);
2208                 _connections.pop_back ();
2209         }
2210 }
2211
2212 bool
2213 AlsaPort::is_connected (const AlsaPort *port) const
2214 {
2215         return std::find (_connections.begin (), _connections.end (), port) != _connections.end ();
2216 }
2217
2218 bool AlsaPort::is_physically_connected () const
2219 {
2220         for (std::vector<AlsaPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
2221                 if ((*it)->is_physical ()) {
2222                         return true;
2223                 }
2224         }
2225         return false;
2226 }
2227
2228 /******************************************************************************/
2229
2230 AlsaAudioPort::AlsaAudioPort (AlsaAudioBackend &b, const std::string& name, PortFlags flags)
2231         : AlsaPort (b, name, flags)
2232 {
2233         memset (_buffer, 0, sizeof (_buffer));
2234         mlock(_buffer, sizeof (_buffer));
2235 }
2236
2237 AlsaAudioPort::~AlsaAudioPort () { }
2238
2239 void* AlsaAudioPort::get_buffer (pframes_t n_samples)
2240 {
2241         if (is_input ()) {
2242                 std::vector<AlsaPort*>::const_iterator it = get_connections ().begin ();
2243                 if (it == get_connections ().end ()) {
2244                         memset (_buffer, 0, n_samples * sizeof (Sample));
2245                 } else {
2246                         AlsaAudioPort const * source = static_cast<const AlsaAudioPort*>(*it);
2247                         assert (source && source->is_output ());
2248                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
2249                         while (++it != get_connections ().end ()) {
2250                                 source = static_cast<const AlsaAudioPort*>(*it);
2251                                 assert (source && source->is_output ());
2252                                 Sample* dst = buffer ();
2253                                 const Sample* src = source->const_buffer ();
2254                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
2255                                         *dst += *src;
2256                                 }
2257                         }
2258                 }
2259         }
2260         return _buffer;
2261 }
2262
2263
2264 AlsaMidiPort::AlsaMidiPort (AlsaAudioBackend &b, const std::string& name, PortFlags flags)
2265         : AlsaPort (b, name, flags)
2266         , _n_periods (1)
2267         , _bufperiod (0)
2268 {
2269         _buffer[0].clear ();
2270         _buffer[1].clear ();
2271 }
2272
2273 AlsaMidiPort::~AlsaMidiPort () { }
2274
2275 struct MidiEventSorter {
2276         bool operator() (const boost::shared_ptr<AlsaMidiEvent>& a, const boost::shared_ptr<AlsaMidiEvent>& b) {
2277                 return *a < *b;
2278         }
2279 };
2280
2281 void* AlsaMidiPort::get_buffer (pframes_t /* nframes */)
2282 {
2283         if (is_input ()) {
2284                 (_buffer[_bufperiod]).clear ();
2285                 for (std::vector<AlsaPort*>::const_iterator i = get_connections ().begin ();
2286                                 i != get_connections ().end ();
2287                                 ++i) {
2288                         const AlsaMidiBuffer * src = static_cast<const AlsaMidiPort*>(*i)->const_buffer ();
2289                         for (AlsaMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
2290                                 (_buffer[_bufperiod]).push_back (boost::shared_ptr<AlsaMidiEvent>(new AlsaMidiEvent (**it)));
2291                         }
2292                 }
2293                 std::sort ((_buffer[_bufperiod]).begin (), (_buffer[_bufperiod]).end (), MidiEventSorter());
2294         }
2295         return &(_buffer[_bufperiod]);
2296 }
2297
2298 AlsaMidiEvent::AlsaMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
2299         : _size (size)
2300         , _timestamp (timestamp)
2301         , _data (0)
2302 {
2303         if (size > 0) {
2304                 _data = (uint8_t*) malloc (size);
2305                 memcpy (_data, data, size);
2306         }
2307 }
2308
2309 AlsaMidiEvent::AlsaMidiEvent (const AlsaMidiEvent& other)
2310         : _size (other.size ())
2311         , _timestamp (other.timestamp ())
2312         , _data (0)
2313 {
2314         if (other.size () && other.const_data ()) {
2315                 _data = (uint8_t*) malloc (other.size ());
2316                 memcpy (_data, other.const_data (), other.size ());
2317         }
2318 };
2319
2320 AlsaMidiEvent::~AlsaMidiEvent () {
2321         free (_data);
2322 };