virtual abstraction of Alsa Raw+Seq
[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                                 _system_midi_out.push_back(static_cast<AlsaPort*>(p));
1012                                 _rmidi_out.push_back (mout);
1013                         }
1014                 }
1015
1016                 AlsaMidiIn *midin;
1017                 if (_midi_driver_option == _("ALSA raw devices")) {
1018                         midin = new AlsaRawMidiIn (i->second.c_str());
1019                 } else {
1020                         midin = new AlsaSeqMidiIn (i->second.c_str());
1021                 }
1022
1023                 if (midin->state ()) {
1024                         PBD::warning << string_compose (
1025                                         _("AlsaMidiIn: failed to open midi device '%1'."), i->second)
1026                                 << endmsg;
1027                         delete midin;
1028                 } else {
1029                         midin->setup_timing(_samples_per_period, _samplerate);
1030                         midin->sync_time (g_get_monotonic_time());
1031                         if (midin->start ()) {
1032                                 PBD::warning << string_compose (
1033                                                 _("AlsaMidiIn: failed to start midi device '%1'."), i->second)
1034                                         << endmsg;
1035                                 delete midin;
1036                         } else {
1037                                 char tmp[64];
1038                                 snprintf(tmp, sizeof(tmp), "system:midi_capture_%d", ++midi_outs);
1039                                 PortHandle p = add_port(std::string(tmp), DataType::MIDI, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
1040                                 if (!p) {
1041                                         midin->stop();
1042                                         delete midin;
1043                                         continue;
1044                                 }
1045                                 LatencyRange lr;
1046                                 lr.min = lr.max = _samples_per_period + (_measure_latency ? 0 : nfo->systemic_input_latency);
1047                                 set_latency_range (p, false, lr);
1048                                 _system_midi_in.push_back(static_cast<AlsaPort*>(p));
1049                                 _rmidi_in.push_back (midin);
1050                         }
1051                 }
1052         }
1053         return 0;
1054 }
1055
1056 void
1057 AlsaAudioBackend::unregister_system_ports()
1058 {
1059         size_t i = 0;
1060         _system_inputs.clear();
1061         _system_outputs.clear();
1062         _system_midi_in.clear();
1063         _system_midi_out.clear();
1064         while (i <  _ports.size ()) {
1065                 AlsaPort* port = _ports[i];
1066                 if (port->is_physical () && port->is_terminal ()) {
1067                         port->disconnect_all ();
1068                         _ports.erase (_ports.begin() + i);
1069                 } else {
1070                         ++i;
1071                 }
1072         }
1073 }
1074
1075 int
1076 AlsaAudioBackend::connect (const std::string& src, const std::string& dst)
1077 {
1078         AlsaPort* src_port = find_port (src);
1079         AlsaPort* dst_port = find_port (dst);
1080
1081         if (!src_port) {
1082                 PBD::error << _("AlsaBackend::connect: Invalid Source port:")
1083                                 << " (" << src <<")" << endmsg;
1084                 return -1;
1085         }
1086         if (!dst_port) {
1087                 PBD::error << _("AlsaBackend::connect: Invalid Destination port:")
1088                         << " (" << dst <<")" << endmsg;
1089                 return -1;
1090         }
1091         return src_port->connect (dst_port);
1092 }
1093
1094 int
1095 AlsaAudioBackend::disconnect (const std::string& src, const std::string& dst)
1096 {
1097         AlsaPort* src_port = find_port (src);
1098         AlsaPort* dst_port = find_port (dst);
1099
1100         if (!src_port || !dst_port) {
1101                 PBD::error << _("AlsaBackend::disconnect: Invalid Port(s)") << endmsg;
1102                 return -1;
1103         }
1104         return src_port->disconnect (dst_port);
1105 }
1106
1107 int
1108 AlsaAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
1109 {
1110         AlsaPort* dst_port = find_port (dst);
1111         if (!valid_port (src)) {
1112                 PBD::error << _("AlsaBackend::connect: Invalid Source Port Handle") << endmsg;
1113                 return -1;
1114         }
1115         if (!dst_port) {
1116                 PBD::error << _("AlsaBackend::connect: Invalid Destination Port")
1117                         << " (" << dst << ")" << endmsg;
1118                 return -1;
1119         }
1120         return static_cast<AlsaPort*>(src)->connect (dst_port);
1121 }
1122
1123 int
1124 AlsaAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
1125 {
1126         AlsaPort* dst_port = find_port (dst);
1127         if (!valid_port (src) || !dst_port) {
1128                 PBD::error << _("AlsaBackend::disconnect: Invalid Port(s)") << endmsg;
1129                 return -1;
1130         }
1131         return static_cast<AlsaPort*>(src)->disconnect (dst_port);
1132 }
1133
1134 int
1135 AlsaAudioBackend::disconnect_all (PortEngine::PortHandle port)
1136 {
1137         if (!valid_port (port)) {
1138                 PBD::error << _("AlsaBackend::disconnect_all: Invalid Port") << endmsg;
1139                 return -1;
1140         }
1141         static_cast<AlsaPort*>(port)->disconnect_all ();
1142         return 0;
1143 }
1144
1145 bool
1146 AlsaAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
1147 {
1148         if (!valid_port (port)) {
1149                 PBD::error << _("AlsaBackend::disconnect_all: Invalid Port") << endmsg;
1150                 return false;
1151         }
1152         return static_cast<AlsaPort*>(port)->is_connected ();
1153 }
1154
1155 bool
1156 AlsaAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
1157 {
1158         AlsaPort* dst_port = find_port (dst);
1159         if (!valid_port (src) || !dst_port) {
1160                 PBD::error << _("AlsaBackend::connected_to: Invalid Port") << endmsg;
1161                 return false;
1162         }
1163         return static_cast<AlsaPort*>(src)->is_connected (dst_port);
1164 }
1165
1166 bool
1167 AlsaAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
1168 {
1169         if (!valid_port (port)) {
1170                 PBD::error << _("AlsaBackend::physically_connected: Invalid Port") << endmsg;
1171                 return false;
1172         }
1173         return static_cast<AlsaPort*>(port)->is_physically_connected ();
1174 }
1175
1176 int
1177 AlsaAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
1178 {
1179         if (!valid_port (port)) {
1180                 PBD::error << _("AlsaBackend::get_connections: Invalid Port") << endmsg;
1181                 return -1;
1182         }
1183
1184         assert (0 == names.size ());
1185
1186         const std::vector<AlsaPort*>& connected_ports = static_cast<AlsaPort*>(port)->get_connections ();
1187
1188         for (std::vector<AlsaPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
1189                 names.push_back ((*i)->name ());
1190         }
1191
1192         return (int)names.size ();
1193 }
1194
1195 /* MIDI */
1196 int
1197 AlsaAudioBackend::midi_event_get (
1198                 pframes_t& timestamp,
1199                 size_t& size, uint8_t** buf, void* port_buffer,
1200                 uint32_t event_index)
1201 {
1202         assert (buf && port_buffer);
1203         AlsaMidiBuffer& source = * static_cast<AlsaMidiBuffer*>(port_buffer);
1204         if (event_index >= source.size ()) {
1205                 return -1;
1206         }
1207         AlsaMidiEvent * const event = source[event_index].get ();
1208
1209         timestamp = event->timestamp ();
1210         size = event->size ();
1211         *buf = event->data ();
1212         return 0;
1213 }
1214
1215 int
1216 AlsaAudioBackend::midi_event_put (
1217                 void* port_buffer,
1218                 pframes_t timestamp,
1219                 const uint8_t* buffer, size_t size)
1220 {
1221         assert (buffer && port_buffer);
1222         AlsaMidiBuffer& dst = * static_cast<AlsaMidiBuffer*>(port_buffer);
1223         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
1224                 fprintf (stderr, "AlsaMidiBuffer: it's too late for this event. %d > %d\n",
1225                                 (pframes_t)dst.back ()->timestamp (), timestamp);
1226                 return -1;
1227         }
1228         dst.push_back (boost::shared_ptr<AlsaMidiEvent>(new AlsaMidiEvent (timestamp, buffer, size)));
1229         return 0;
1230 }
1231
1232 uint32_t
1233 AlsaAudioBackend::get_midi_event_count (void* port_buffer)
1234 {
1235         assert (port_buffer);
1236         return static_cast<AlsaMidiBuffer*>(port_buffer)->size ();
1237 }
1238
1239 void
1240 AlsaAudioBackend::midi_clear (void* port_buffer)
1241 {
1242         assert (port_buffer);
1243         AlsaMidiBuffer * buf = static_cast<AlsaMidiBuffer*>(port_buffer);
1244         assert (buf);
1245         buf->clear ();
1246 }
1247
1248 /* Monitoring */
1249
1250 bool
1251 AlsaAudioBackend::can_monitor_input () const
1252 {
1253         return false;
1254 }
1255
1256 int
1257 AlsaAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1258 {
1259         return -1;
1260 }
1261
1262 int
1263 AlsaAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1264 {
1265         return -1;
1266 }
1267
1268 bool
1269 AlsaAudioBackend::monitoring_input (PortEngine::PortHandle)
1270 {
1271         return false;
1272 }
1273
1274 /* Latency management */
1275
1276 void
1277 AlsaAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1278 {
1279         if (!valid_port (port)) {
1280                 PBD::error << _("AlsaPort::set_latency_range (): invalid port.") << endmsg;
1281         }
1282         static_cast<AlsaPort*>(port)->set_latency_range (latency_range, for_playback);
1283 }
1284
1285 LatencyRange
1286 AlsaAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1287 {
1288         if (!valid_port (port)) {
1289                 PBD::error << _("AlsaPort::get_latency_range (): invalid port.") << endmsg;
1290                 LatencyRange r;
1291                 r.min = 0;
1292                 r.max = 0;
1293                 return r;
1294         }
1295         return static_cast<AlsaPort*>(port)->latency_range (for_playback);
1296 }
1297
1298 /* Discovering physical ports */
1299
1300 bool
1301 AlsaAudioBackend::port_is_physical (PortEngine::PortHandle port) const
1302 {
1303         if (!valid_port (port)) {
1304                 PBD::error << _("AlsaPort::port_is_physical (): invalid port.") << endmsg;
1305                 return false;
1306         }
1307         return static_cast<AlsaPort*>(port)->is_physical ();
1308 }
1309
1310 void
1311 AlsaAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1312 {
1313         for (size_t i = 0; i < _ports.size (); ++i) {
1314                 AlsaPort* port = _ports[i];
1315                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1316                         port_names.push_back (port->name ());
1317                 }
1318         }
1319 }
1320
1321 void
1322 AlsaAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1323 {
1324         for (size_t i = 0; i < _ports.size (); ++i) {
1325                 AlsaPort* port = _ports[i];
1326                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1327                         port_names.push_back (port->name ());
1328                 }
1329         }
1330 }
1331
1332 ChanCount
1333 AlsaAudioBackend::n_physical_outputs () const
1334 {
1335         int n_midi = 0;
1336         int n_audio = 0;
1337         for (size_t i = 0; i < _ports.size (); ++i) {
1338                 AlsaPort* port = _ports[i];
1339                 if (port->is_output () && port->is_physical ()) {
1340                         switch (port->type ()) {
1341                                 case DataType::AUDIO: ++n_audio; break;
1342                                 case DataType::MIDI: ++n_midi; break;
1343                                 default: break;
1344                         }
1345                 }
1346         }
1347         ChanCount cc;
1348         cc.set (DataType::AUDIO, n_audio);
1349         cc.set (DataType::MIDI, n_midi);
1350         return cc;
1351 }
1352
1353 ChanCount
1354 AlsaAudioBackend::n_physical_inputs () const
1355 {
1356         int n_midi = 0;
1357         int n_audio = 0;
1358         for (size_t i = 0; i < _ports.size (); ++i) {
1359                 AlsaPort* port = _ports[i];
1360                 if (port->is_input () && port->is_physical ()) {
1361                         switch (port->type ()) {
1362                                 case DataType::AUDIO: ++n_audio; break;
1363                                 case DataType::MIDI: ++n_midi; break;
1364                                 default: break;
1365                         }
1366                 }
1367         }
1368         ChanCount cc;
1369         cc.set (DataType::AUDIO, n_audio);
1370         cc.set (DataType::MIDI, n_midi);
1371         return cc;
1372 }
1373
1374 /* Getting access to the data buffer for a port */
1375
1376 void*
1377 AlsaAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1378 {
1379         assert (port);
1380         assert (valid_port (port));
1381         return static_cast<AlsaPort*>(port)->get_buffer (nframes);
1382 }
1383
1384 /* Engine Process */
1385 void *
1386 AlsaAudioBackend::main_process_thread ()
1387 {
1388         AudioEngine::thread_init_callback (this);
1389         _active = true;
1390         _processed_samples = 0;
1391
1392         uint64_t clock1, clock2;
1393         clock1 = g_get_monotonic_time();
1394         _pcmi->pcm_start ();
1395         int no_proc_errors = 0;
1396         const int bailout = 2 * _samplerate / _samples_per_period;
1397         const int64_t nomial_time = 1e6 * _samples_per_period / _samplerate;
1398
1399         manager.registration_callback();
1400         manager.graph_order_callback();
1401
1402         while (_run) {
1403                 long nr;
1404                 bool xrun = false;
1405                 if (!_freewheeling) {
1406                         nr = _pcmi->pcm_wait ();
1407
1408                         if (_pcmi->state () > 0) {
1409                                 ++no_proc_errors;
1410                                 xrun = true;
1411                         }
1412                         if (_pcmi->state () < 0 || no_proc_errors > bailout) {
1413                                 PBD::error << _("AlsaAudioBackend: I/O error. Audio Process Terminated.") << endmsg;
1414                                 break;
1415                         }
1416                         while (nr >= (long)_samples_per_period) {
1417                                 uint32_t i = 0;
1418                                 clock1 = g_get_monotonic_time();
1419                                 no_proc_errors = 0;
1420
1421                                 _pcmi->capt_init (_samples_per_period);
1422                                 for (std::vector<AlsaPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++i) {
1423                                         _pcmi->capt_chan (i, (float*)((*it)->get_buffer(_samples_per_period)), _samples_per_period);
1424                                 }
1425                                 _pcmi->capt_done (_samples_per_period);
1426
1427                                 /* de-queue midi*/
1428                                 i = 0;
1429                                 for (std::vector<AlsaPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++i) {
1430                                         assert (_rmidi_in.size() > i);
1431                                         AlsaMidiIn *rm = static_cast<AlsaMidiIn*>(_rmidi_in.at(i));
1432                                         void *bptr = (*it)->get_buffer(0);
1433                                         pframes_t time;
1434                                         uint8_t data[64]; // match MaxAlsaEventSize in alsa_rawmidi.cc
1435                                         size_t size = sizeof(data);
1436                                         midi_clear(bptr);
1437                                         while (rm->recv_event (time, data, size)) {
1438                                                 midi_event_put(bptr, time, data, size);
1439                                                 size = sizeof(data);
1440                                         }
1441                                         rm->sync_time (clock1);
1442                                 }
1443
1444                                 for (std::vector<AlsaPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it) {
1445                                         memset ((*it)->get_buffer (_samples_per_period), 0, _samples_per_period * sizeof (Sample));
1446                                 }
1447
1448                                 if (engine.process_callback (_samples_per_period)) {
1449                                         _pcmi->pcm_stop ();
1450                                         _active = false;
1451                                         return 0;
1452                                 }
1453
1454                                 i = 0;
1455                                 for (std::vector<AlsaPort*>::iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it, ++i) {
1456                                         static_cast<AlsaMidiPort*>(*it)->next_period();
1457                                 }
1458
1459                                 /* queue midi */
1460                                 i = 0;
1461                                 for (std::vector<AlsaPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it, ++i) {
1462                                         assert (_rmidi_out.size() > i);
1463                                         const AlsaMidiBuffer src = static_cast<const AlsaMidiPort*>(*it)->const_buffer();
1464                                         AlsaMidiOut *rm = static_cast<AlsaMidiOut*>(_rmidi_out.at(i));
1465                                         rm->sync_time (clock1);
1466                                         for (AlsaMidiBuffer::const_iterator mit = src.begin (); mit != src.end (); ++mit) {
1467                                                 rm->send_event ((*mit)->timestamp(), (*mit)->data(), (*mit)->size());
1468                                         }
1469                                 }
1470
1471                                 /* write back audio */
1472                                 i = 0;
1473                                 _pcmi->play_init (_samples_per_period);
1474                                 for (std::vector<AlsaPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it, ++i) {
1475                                         _pcmi->play_chan (i, (const float*)(*it)->get_buffer (_samples_per_period), _samples_per_period);
1476                                 }
1477                                 for (; i < _pcmi->nplay (); ++i) {
1478                                         _pcmi->clear_chan (i, _samples_per_period);
1479                                 }
1480                                 _pcmi->play_done (_samples_per_period);
1481                                 nr -= _samples_per_period;
1482                                 _processed_samples += _samples_per_period;
1483
1484                                 /* calculate DSP load */
1485                                 clock2 = g_get_monotonic_time();
1486                                 const int64_t elapsed_time = clock2 - clock1;
1487                                 _dsp_load = elapsed_time / (float) nomial_time;
1488                         }
1489
1490                         if (xrun && (_pcmi->capt_xrun() > 0 || _pcmi->play_xrun() > 0)) {
1491                                 engine.Xrun ();
1492 #if 0
1493                                 fprintf(stderr, "ALSA x-run read: %.1f ms, write: %.1f ms\n",
1494                                                 _pcmi->capt_xrun() * 1000.0, _pcmi->play_xrun() * 1000.0);
1495 #endif
1496                         }
1497                 } else {
1498                         // Freewheelin'
1499                         for (std::vector<AlsaPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
1500                                 memset ((*it)->get_buffer (_samples_per_period), 0, _samples_per_period * sizeof (Sample));
1501                         }
1502                         for (std::vector<AlsaPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it) {
1503                                 static_cast<AlsaMidiBuffer*>((*it)->get_buffer(0))->clear ();
1504                         }
1505
1506                         if (engine.process_callback (_samples_per_period)) {
1507                                 _pcmi->pcm_stop ();
1508                                 return 0;
1509                         }
1510                         _dsp_load = 1.0;
1511                         Glib::usleep (100); // don't hog cpu
1512                 }
1513
1514                 bool connections_changed = false;
1515                 bool ports_changed = false;
1516                 if (!pthread_mutex_trylock (&_port_callback_mutex)) {
1517                         if (_port_change_flag) {
1518                                 ports_changed = true;
1519                                 _port_change_flag = false;
1520                         }
1521                         if (!_port_connection_queue.empty ()) {
1522                                 connections_changed = true;
1523                         }
1524                         while (!_port_connection_queue.empty ()) {
1525                                 PortConnectData *c = _port_connection_queue.back ();
1526                                 manager.connect_callback (c->a, c->b, c->c);
1527                                 _port_connection_queue.pop_back ();
1528                                 delete c;
1529                         }
1530                         pthread_mutex_unlock (&_port_callback_mutex);
1531                 }
1532                 if (ports_changed) {
1533                         manager.registration_callback();
1534                 }
1535                 if (connections_changed) {
1536                         manager.graph_order_callback();
1537                 }
1538                 if (connections_changed || ports_changed) {
1539                         engine.latency_callback(false);
1540                         engine.latency_callback(true);
1541                 }
1542
1543         }
1544         _pcmi->pcm_stop ();
1545         _active = false;
1546         if (_run) {
1547                 engine.halted_callback("ALSA I/O error.");
1548         }
1549         return 0;
1550 }
1551
1552
1553 /******************************************************************************/
1554
1555 static boost::shared_ptr<AlsaAudioBackend> _instance;
1556
1557 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
1558 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
1559 static int deinstantiate ();
1560 static bool already_configured ();
1561
1562 static ARDOUR::AudioBackendInfo _descriptor = {
1563         "ALSA",
1564         instantiate,
1565         deinstantiate,
1566         backend_factory,
1567         already_configured,
1568 };
1569
1570 static boost::shared_ptr<AudioBackend>
1571 backend_factory (AudioEngine& e)
1572 {
1573         if (!_instance) {
1574                 _instance.reset (new AlsaAudioBackend (e, _descriptor));
1575         }
1576         return _instance;
1577 }
1578
1579 static int
1580 instantiate (const std::string& arg1, const std::string& /* arg2 */)
1581 {
1582         s_instance_name = arg1;
1583         return 0;
1584 }
1585
1586 static int
1587 deinstantiate ()
1588 {
1589         _instance.reset ();
1590         return 0;
1591 }
1592
1593 static bool
1594 already_configured ()
1595 {
1596         return false;
1597 }
1598
1599 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
1600 {
1601         return &_descriptor;
1602 }
1603
1604
1605 /******************************************************************************/
1606 AlsaPort::AlsaPort (AlsaAudioBackend &b, const std::string& name, PortFlags flags)
1607         : _alsa_backend (b)
1608         , _name  (name)
1609         , _flags (flags)
1610 {
1611         _capture_latency_range.min = 0;
1612         _capture_latency_range.max = 0;
1613         _playback_latency_range.min = 0;
1614         _playback_latency_range.max = 0;
1615 }
1616
1617 AlsaPort::~AlsaPort () {
1618         disconnect_all ();
1619 }
1620
1621
1622 int AlsaPort::connect (AlsaPort *port)
1623 {
1624         if (!port) {
1625                 PBD::error << _("AlsaPort::connect (): invalid (null) port") << endmsg;
1626                 return -1;
1627         }
1628
1629         if (type () != port->type ()) {
1630                 PBD::error << _("AlsaPort::connect (): wrong port-type") << endmsg;
1631                 return -1;
1632         }
1633
1634         if (is_output () && port->is_output ()) {
1635                 PBD::error << _("AlsaPort::connect (): cannot inter-connect output ports.") << endmsg;
1636                 return -1;
1637         }
1638
1639         if (is_input () && port->is_input ()) {
1640                 PBD::error << _("AlsaPort::connect (): cannot inter-connect input ports.") << endmsg;
1641                 return -1;
1642         }
1643
1644         if (this == port) {
1645                 PBD::error << _("AlsaPort::connect (): cannot self-connect ports.") << endmsg;
1646                 return -1;
1647         }
1648
1649         if (is_connected (port)) {
1650 #if 0 // don't bother to warn about this for now. just ignore it
1651                 PBD::error << _("AlsaPort::connect (): ports are already connected:")
1652                         << " (" << name () << ") -> (" << port->name () << ")"
1653                         << endmsg;
1654 #endif
1655                 return -1;
1656         }
1657
1658         _connect (port, true);
1659         return 0;
1660 }
1661
1662
1663 void AlsaPort::_connect (AlsaPort *port, bool callback)
1664 {
1665         _connections.push_back (port);
1666         if (callback) {
1667                 port->_connect (this, false);
1668                 _alsa_backend.port_connect_callback (name(),  port->name(), true);
1669         }
1670 }
1671
1672 int AlsaPort::disconnect (AlsaPort *port)
1673 {
1674         if (!port) {
1675                 PBD::error << _("AlsaPort::disconnect (): invalid (null) port") << endmsg;
1676                 return -1;
1677         }
1678
1679         if (!is_connected (port)) {
1680                 PBD::error << _("AlsaPort::disconnect (): ports are not connected:")
1681                         << " (" << name () << ") -> (" << port->name () << ")"
1682                         << endmsg;
1683                 return -1;
1684         }
1685         _disconnect (port, true);
1686         return 0;
1687 }
1688
1689 void AlsaPort::_disconnect (AlsaPort *port, bool callback)
1690 {
1691         std::vector<AlsaPort*>::iterator it = std::find (_connections.begin (), _connections.end (), port);
1692
1693         assert (it != _connections.end ());
1694
1695         _connections.erase (it);
1696
1697         if (callback) {
1698                 port->_disconnect (this, false);
1699                 _alsa_backend.port_connect_callback (name(),  port->name(), false);
1700         }
1701 }
1702
1703
1704 void AlsaPort::disconnect_all ()
1705 {
1706         while (!_connections.empty ()) {
1707                 _connections.back ()->_disconnect (this, false);
1708                 _alsa_backend.port_connect_callback (name(),  _connections.back ()->name(), false);
1709                 _connections.pop_back ();
1710         }
1711 }
1712
1713 bool
1714 AlsaPort::is_connected (const AlsaPort *port) const
1715 {
1716         return std::find (_connections.begin (), _connections.end (), port) != _connections.end ();
1717 }
1718
1719 bool AlsaPort::is_physically_connected () const
1720 {
1721         for (std::vector<AlsaPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
1722                 if ((*it)->is_physical ()) {
1723                         return true;
1724                 }
1725         }
1726         return false;
1727 }
1728
1729 /******************************************************************************/
1730
1731 AlsaAudioPort::AlsaAudioPort (AlsaAudioBackend &b, const std::string& name, PortFlags flags)
1732         : AlsaPort (b, name, flags)
1733 {
1734         memset (_buffer, 0, sizeof (_buffer));
1735         mlock(_buffer, sizeof (_buffer));
1736 }
1737
1738 AlsaAudioPort::~AlsaAudioPort () { }
1739
1740 void* AlsaAudioPort::get_buffer (pframes_t n_samples)
1741 {
1742         if (is_input ()) {
1743                 std::vector<AlsaPort*>::const_iterator it = get_connections ().begin ();
1744                 if (it == get_connections ().end ()) {
1745                         memset (_buffer, 0, n_samples * sizeof (Sample));
1746                 } else {
1747                         AlsaAudioPort const * source = static_cast<const AlsaAudioPort*>(*it);
1748                         assert (source && source->is_output ());
1749                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
1750                         while (++it != get_connections ().end ()) {
1751                                 source = static_cast<const AlsaAudioPort*>(*it);
1752                                 assert (source && source->is_output ());
1753                                 Sample* dst = buffer ();
1754                                 const Sample* src = source->const_buffer ();
1755                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
1756                                         *dst += *src;
1757                                 }
1758                         }
1759                 }
1760         }
1761         return _buffer;
1762 }
1763
1764
1765 AlsaMidiPort::AlsaMidiPort (AlsaAudioBackend &b, const std::string& name, PortFlags flags)
1766         : AlsaPort (b, name, flags)
1767         , _bufperiod (0)
1768 {
1769         _buffer[0].clear ();
1770         _buffer[1].clear ();
1771 }
1772
1773 AlsaMidiPort::~AlsaMidiPort () { }
1774
1775 struct MidiEventSorter {
1776         bool operator() (const boost::shared_ptr<AlsaMidiEvent>& a, const boost::shared_ptr<AlsaMidiEvent>& b) {
1777                 return *a < *b;
1778         }
1779 };
1780
1781 void* AlsaMidiPort::get_buffer (pframes_t /* nframes */)
1782 {
1783         if (is_input ()) {
1784                 (_buffer[_bufperiod]).clear ();
1785                 for (std::vector<AlsaPort*>::const_iterator i = get_connections ().begin ();
1786                                 i != get_connections ().end ();
1787                                 ++i) {
1788                         const AlsaMidiBuffer src = static_cast<const AlsaMidiPort*>(*i)->const_buffer ();
1789                         for (AlsaMidiBuffer::const_iterator it = src.begin (); it != src.end (); ++it) {
1790                                 (_buffer[_bufperiod]).push_back (boost::shared_ptr<AlsaMidiEvent>(new AlsaMidiEvent (**it)));
1791                         }
1792                 }
1793                 std::sort ((_buffer[_bufperiod]).begin (), (_buffer[_bufperiod]).end (), MidiEventSorter());
1794         }
1795         return &(_buffer[_bufperiod]);
1796 }
1797
1798 AlsaMidiEvent::AlsaMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
1799         : _size (size)
1800         , _timestamp (timestamp)
1801         , _data (0)
1802 {
1803         if (size > 0) {
1804                 _data = (uint8_t*) malloc (size);
1805                 memcpy (_data, data, size);
1806         }
1807 }
1808
1809 AlsaMidiEvent::AlsaMidiEvent (const AlsaMidiEvent& other)
1810         : _size (other.size ())
1811         , _timestamp (other.timestamp ())
1812         , _data (0)
1813 {
1814         if (other.size () && other.const_data ()) {
1815                 _data = (uint8_t*) malloc (other.size ());
1816                 memcpy (_data, other.const_data (), other.size ());
1817         }
1818 };
1819
1820 AlsaMidiEvent::~AlsaMidiEvent () {
1821         free (_data);
1822 };