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