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