c9b74058ab45bb6d74dcee59faa802a2cf5cf56f
[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         std::map<std::string, std::string> devices;
386         get_alsa_rawmidi_device_names(devices);
387         for (std::map<std::string, std::string>::const_iterator i = devices.begin (); i != devices.end(); ++i) {
388                 if (i->first == name) {
389                         _midi_devices[name] = new AlsaMidiDeviceInfo();
390                         return _midi_devices[name];
391                 }
392         }
393         return 0;
394 }
395
396 std::vector<std::string>
397 AlsaAudioBackend::enumerate_midi_options () const
398 {
399         std::vector<std::string> m;
400         m.push_back (_("None"));
401         m.push_back (_("ALSA raw devices"));
402         return m;
403 }
404
405 std::vector<AudioBackend::DeviceStatus>
406 AlsaAudioBackend::enumerate_midi_devices () const
407 {
408         std::vector<AudioBackend::DeviceStatus> s;
409         if (_midi_driver_option == _("None")) {
410                 return s;
411         }
412
413         std::map<std::string, std::string> devices;
414         get_alsa_rawmidi_device_names(devices);
415
416         for (std::map<std::string, std::string>::const_iterator i = devices.begin (); i != devices.end(); ++i) {
417                 s.push_back (DeviceStatus (i->first, true));
418         }
419         return s;
420 }
421
422 int
423 AlsaAudioBackend::set_midi_option (const std::string& opt)
424 {
425         if (opt != _("None") && opt != _("ALSA raw devices")) {
426                 return -1;
427         }
428         _midi_driver_option = opt;
429         return 0;
430 }
431
432 std::string
433 AlsaAudioBackend::midi_option () const
434 {
435         return _midi_driver_option;
436 }
437
438 int
439 AlsaAudioBackend::set_midi_device_enabled (std::string const device, bool enable)
440 {
441         struct AlsaMidiDeviceInfo * nfo = midi_device_info(device);
442         if (!nfo) return -1;
443         nfo->enabled = enable;
444         return 0;
445 }
446
447 bool
448 AlsaAudioBackend::midi_device_enabled (std::string const device) const
449 {
450         struct AlsaMidiDeviceInfo * nfo = midi_device_info(device);
451         if (!nfo) return false;
452         return nfo->enabled;
453 }
454
455 /* State Control */
456
457 static void * pthread_process (void *arg)
458 {
459         AlsaAudioBackend *d = static_cast<AlsaAudioBackend *>(arg);
460         d->main_process_thread ();
461         pthread_exit (0);
462         return 0;
463 }
464
465 int
466 AlsaAudioBackend::_start (bool for_latency_measurement)
467 {
468         if (!_active && _run) {
469                 // recover from 'halted', reap threads
470                 stop();
471         }
472
473         if (_active || _run) {
474                 PBD::error << _("AlsaAudioBackend: already active.") << endmsg;
475                 return -1;
476         }
477
478         if (_ports.size()) {
479                 PBD::warning << _("AlsaAudioBackend: recovering from unclean shutdown, port registry is not empty.") << endmsg;
480                 _system_inputs.clear();
481                 _system_outputs.clear();
482                 _system_midi_in.clear();
483                 _system_midi_out.clear();
484                 _ports.clear();
485         }
486
487         release_device();
488
489         assert(_rmidi_in.size() == 0);
490         assert(_rmidi_out.size() == 0);
491         assert(_pcmi == 0);
492
493         std::string alsa_device;
494         std::map<std::string, std::string> devices;
495         get_alsa_audio_device_names(devices);
496         for (std::map<std::string, std::string>::const_iterator i = devices.begin (); i != devices.end(); ++i) {
497                 if (i->first == _audio_device) {
498                         alsa_device = i->second;
499                         break;
500                 }
501         }
502
503         acquire_device(alsa_device.c_str());
504         _pcmi = new Alsa_pcmi (alsa_device.c_str(), alsa_device.c_str(), 0, _samplerate, _samples_per_period, _periods_per_cycle, 0);
505         switch (_pcmi->state ()) {
506                 case 0: /* OK */ break;
507                 case -1: PBD::error << _("AlsaAudioBackend: failed to open device.") << endmsg; break;
508                 case -2: PBD::error << _("AlsaAudioBackend: failed to allocate parameters.") << endmsg; break;
509                 case -3: PBD::error << _("AlsaAudioBackend: cannot set requested sample rate.") << endmsg; break;
510                 case -4: PBD::error << _("AlsaAudioBackend: cannot set requested period size.") << endmsg; break;
511                 case -5: PBD::error << _("AlsaAudioBackend: cannot set requested number of periods.") << endmsg; break;
512                 case -6: PBD::error << _("AlsaAudioBackend: unsupported sample format.") << endmsg; break;
513                 default: PBD::error << _("AlsaAudioBackend: initialization failed.") << endmsg; break;
514         }
515         if (_pcmi->state ()) {
516                 delete _pcmi; _pcmi = 0;
517                 release_device();
518                 return -1;
519         }
520
521 #ifndef NDEBUG
522         _pcmi->printinfo ();
523 #endif
524
525         if (_n_outputs != _pcmi->nplay ()) {
526                 if (_n_outputs == 0) {
527                  _n_outputs = _pcmi->nplay ();
528                 } else {
529                  _n_outputs = std::min (_n_outputs, _pcmi->nplay ());
530                 }
531                 PBD::warning << _("AlsaAudioBackend: adjusted output channel count to match device.") << endmsg;
532         }
533
534         if (_n_inputs != _pcmi->ncapt ()) {
535                 if (_n_inputs == 0) {
536                  _n_inputs = _pcmi->ncapt ();
537                 } else {
538                  _n_inputs = std::min (_n_inputs, _pcmi->ncapt ());
539                 }
540                 PBD::warning << _("AlsaAudioBackend: adjusted input channel count to match device.") << endmsg;
541         }
542
543         if (_pcmi->fsize() != _samples_per_period) {
544                 _samples_per_period = _pcmi->fsize();
545                 PBD::warning << _("AlsaAudioBackend: samples per period does not match.") << endmsg;
546         }
547
548         if (_pcmi->fsamp() != _samplerate) {
549                 _samplerate = _pcmi->fsamp();
550                 engine.sample_rate_change (_samplerate);
551                 PBD::warning << _("AlsaAudioBackend: sample rate does not match.") << endmsg;
552         }
553
554         _measure_latency = for_latency_measurement;
555
556         register_system_midi_ports();
557
558         if (register_system_audio_ports()) {
559                 PBD::error << _("AlsaAudioBackend: failed to register system ports.") << endmsg;
560                 delete _pcmi; _pcmi = 0;
561                 release_device();
562                 return -1;
563         }
564
565         engine.sample_rate_change (_samplerate);
566         engine.buffer_size_change (_samples_per_period);
567
568         if (engine.reestablish_ports ()) {
569                 PBD::error << _("AlsaAudioBackend: Could not re-establish ports.") << endmsg;
570                 delete _pcmi; _pcmi = 0;
571                 release_device();
572                 return -1;
573         }
574
575         engine.reconnect_ports ();
576         _run = true;
577         _port_change_flag = false;
578
579         if (_realtime_pthread_create (SCHED_FIFO, -20, 100000,
580                                 &_main_thread, pthread_process, this))
581         {
582                 if (pthread_create (&_main_thread, NULL, pthread_process, this))
583                 {
584                         PBD::error << _("AlsaAudioBackend: failed to create process thread.") << endmsg;
585                         delete _pcmi; _pcmi = 0;
586                         release_device();
587                         _run = false;
588                         return -1;
589                 } else {
590                         PBD::warning << _("AlsaAudioBackend: cannot acquire realtime permissions.") << endmsg;
591                 }
592         }
593
594         int timeout = 5000;
595         while (!_active && --timeout > 0) { Glib::usleep (1000); }
596
597         if (timeout == 0 || !_active) {
598                 PBD::error << _("AlsaAudioBackend: failed to start process thread.") << endmsg;
599                 delete _pcmi; _pcmi = 0;
600                 release_device();
601                 _run = false;
602                 return -1;
603         }
604
605         return 0;
606 }
607
608 int
609 AlsaAudioBackend::stop ()
610 {
611         void *status;
612         if (!_run) {
613                 return 0;
614         }
615
616         _run = false;
617         if (pthread_join (_main_thread, &status)) {
618                 PBD::error << _("AlsaAudioBackend: failed to terminate.") << endmsg;
619                 return -1;
620         }
621
622         while (!_rmidi_out.empty ()) {
623                 AlsaRawMidiIO *m = _rmidi_out.back ();
624                 m->stop();
625                 _rmidi_out.pop_back ();
626                 delete m;
627         }
628         while (!_rmidi_in.empty ()) {
629                 AlsaRawMidiIO *m = _rmidi_in.back ();
630                 m->stop();
631                 _rmidi_in.pop_back ();
632                 delete m;
633         }
634
635         unregister_system_ports();
636         delete _pcmi; _pcmi = 0;
637         release_device();
638
639         return (_active == false) ? 0 : -1;
640 }
641
642 int
643 AlsaAudioBackend::freewheel (bool onoff)
644 {
645         if (onoff == _freewheeling) {
646                 return 0;
647         }
648         _freewheeling = onoff;
649         engine.freewheel_callback (onoff);
650         return 0;
651 }
652
653 float
654 AlsaAudioBackend::dsp_load () const
655 {
656         return 100.f * _dsp_load;
657 }
658
659 size_t
660 AlsaAudioBackend::raw_buffer_size (DataType t)
661 {
662         switch (t) {
663                 case DataType::AUDIO:
664                         return _samples_per_period * sizeof(Sample);
665                 case DataType::MIDI:
666                         return _max_buffer_size; // XXX not really limited
667         }
668         return 0;
669 }
670
671 /* Process time */
672 pframes_t
673 AlsaAudioBackend::sample_time ()
674 {
675         return _processed_samples;
676 }
677
678 pframes_t
679 AlsaAudioBackend::sample_time_at_cycle_start ()
680 {
681         return _processed_samples;
682 }
683
684 pframes_t
685 AlsaAudioBackend::samples_since_cycle_start ()
686 {
687         return 0;
688 }
689
690
691 void *
692 AlsaAudioBackend::alsa_process_thread (void *arg)
693 {
694         ThreadData* td = reinterpret_cast<ThreadData*> (arg);
695         boost::function<void ()> f = td->f;
696         delete td;
697         f ();
698         return 0;
699 }
700
701 int
702 AlsaAudioBackend::create_process_thread (boost::function<void()> func)
703 {
704         pthread_t thread_id;
705         pthread_attr_t attr;
706         size_t stacksize = 100000;
707
708         ThreadData* td = new ThreadData (this, func, stacksize);
709
710         if (_realtime_pthread_create (SCHED_FIFO, -21, stacksize,
711                                 &thread_id, alsa_process_thread, td)) {
712                 pthread_attr_init (&attr);
713                 pthread_attr_setstacksize (&attr, stacksize);
714                 if (pthread_create (&thread_id, &attr, alsa_process_thread, td)) {
715                         PBD::error << _("AudioEngine: cannot create process thread.") << endmsg;
716                         pthread_attr_destroy (&attr);
717                         return -1;
718                 }
719                 pthread_attr_destroy (&attr);
720         }
721
722         _threads.push_back (thread_id);
723         return 0;
724 }
725
726 int
727 AlsaAudioBackend::join_process_threads ()
728 {
729         int rv = 0;
730
731         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
732         {
733                 void *status;
734                 if (pthread_join (*i, &status)) {
735                         PBD::error << _("AudioEngine: cannot terminate process thread.") << endmsg;
736                         rv -= 1;
737                 }
738         }
739         _threads.clear ();
740         return rv;
741 }
742
743 bool
744 AlsaAudioBackend::in_process_thread ()
745 {
746         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
747         {
748                 if (pthread_equal (*i, pthread_self ()) != 0) {
749                         return true;
750                 }
751         }
752         return false;
753 }
754
755 uint32_t
756 AlsaAudioBackend::process_thread_count ()
757 {
758         return _threads.size ();
759 }
760
761 void
762 AlsaAudioBackend::update_latencies ()
763 {
764         // trigger latency callback in RT thread (locked graph)
765         port_connect_add_remove_callback();
766 }
767
768 /* PORTENGINE API */
769
770 void*
771 AlsaAudioBackend::private_handle () const
772 {
773         return NULL;
774 }
775
776 const std::string&
777 AlsaAudioBackend::my_name () const
778 {
779         return _instance_name;
780 }
781
782 bool
783 AlsaAudioBackend::available () const
784 {
785         return _run && _active;
786 }
787
788 uint32_t
789 AlsaAudioBackend::port_name_size () const
790 {
791         return 256;
792 }
793
794 int
795 AlsaAudioBackend::set_port_name (PortEngine::PortHandle port, const std::string& name)
796 {
797         if (!valid_port (port)) {
798                 PBD::error << _("AlsaBackend::set_port_name: Invalid Port(s)") << endmsg;
799                 return -1;
800         }
801         return static_cast<AlsaPort*>(port)->set_name (_instance_name + ":" + name);
802 }
803
804 std::string
805 AlsaAudioBackend::get_port_name (PortEngine::PortHandle port) const
806 {
807         if (!valid_port (port)) {
808                 PBD::error << _("AlsaBackend::get_port_name: Invalid Port(s)") << endmsg;
809                 return std::string ();
810         }
811         return static_cast<AlsaPort*>(port)->name ();
812 }
813
814 PortEngine::PortHandle
815 AlsaAudioBackend::get_port_by_name (const std::string& name) const
816 {
817         PortHandle port = (PortHandle) find_port (name);
818         return port;
819 }
820
821 int
822 AlsaAudioBackend::get_ports (
823                 const std::string& port_name_pattern,
824                 DataType type, PortFlags flags,
825                 std::vector<std::string>& port_names) const
826 {
827         int rv = 0;
828         regex_t port_regex;
829         bool use_regexp = false;
830         if (port_name_pattern.size () > 0) {
831                 if (!regcomp (&port_regex, port_name_pattern.c_str (), REG_EXTENDED|REG_NOSUB)) {
832                         use_regexp = true;
833                 }
834         }
835         for (size_t i = 0; i < _ports.size (); ++i) {
836                 AlsaPort* port = _ports[i];
837                 if ((port->type () == type) && (port->flags () & flags)) {
838                         if (!use_regexp || !regexec (&port_regex, port->name ().c_str (), 0, NULL, 0)) {
839                                 port_names.push_back (port->name ());
840                                 ++rv;
841                         }
842                 }
843         }
844         if (use_regexp) {
845                 regfree (&port_regex);
846         }
847         return rv;
848 }
849
850 DataType
851 AlsaAudioBackend::port_data_type (PortEngine::PortHandle port) const
852 {
853         if (!valid_port (port)) {
854                 return DataType::NIL;
855         }
856         return static_cast<AlsaPort*>(port)->type ();
857 }
858
859 PortEngine::PortHandle
860 AlsaAudioBackend::register_port (
861                 const std::string& name,
862                 ARDOUR::DataType type,
863                 ARDOUR::PortFlags flags)
864 {
865         if (name.size () == 0) { return 0; }
866         if (flags & IsPhysical) { return 0; }
867         return add_port (_instance_name + ":" + name, type, flags);
868 }
869
870 PortEngine::PortHandle
871 AlsaAudioBackend::add_port (
872                 const std::string& name,
873                 ARDOUR::DataType type,
874                 ARDOUR::PortFlags flags)
875 {
876         assert(name.size ());
877         if (find_port (name)) {
878                 PBD::error << _("AlsaBackend::register_port: Port already exists:")
879                                 << " (" << name << ")" << endmsg;
880                 return 0;
881         }
882         AlsaPort* port = NULL;
883         switch (type) {
884                 case DataType::AUDIO:
885                         port = new AlsaAudioPort (*this, name, flags);
886                         break;
887                 case DataType::MIDI:
888                         port = new AlsaMidiPort (*this, name, flags);
889                         break;
890                 default:
891                         PBD::error << _("AlsaBackend::register_port: Invalid Data Type.") << endmsg;
892                         return 0;
893         }
894
895         _ports.push_back (port);
896
897         return port;
898 }
899
900 void
901 AlsaAudioBackend::unregister_port (PortEngine::PortHandle port_handle)
902 {
903         if (!valid_port (port_handle)) {
904                 PBD::error << _("AlsaBackend::unregister_port: Invalid Port.") << endmsg;
905         }
906         AlsaPort* port = static_cast<AlsaPort*>(port_handle);
907         std::vector<AlsaPort*>::iterator i = std::find (_ports.begin (), _ports.end (), static_cast<AlsaPort*>(port_handle));
908         if (i == _ports.end ()) {
909                 PBD::error << _("AlsaBackend::unregister_port: Failed to find port") << endmsg;
910                 return;
911         }
912         disconnect_all(port_handle);
913         _ports.erase (i);
914         delete port;
915 }
916
917 int
918 AlsaAudioBackend::register_system_audio_ports()
919 {
920         LatencyRange lr;
921
922         const int a_ins = _n_inputs > 0 ? _n_inputs : 2;
923         const int a_out = _n_outputs > 0 ? _n_outputs : 2;
924
925         /* audio ports */
926         lr.min = lr.max = _samples_per_period + (_measure_latency ? 0 : _systemic_audio_input_latency);
927         for (int i = 1; i <= a_ins; ++i) {
928                 char tmp[64];
929                 snprintf(tmp, sizeof(tmp), "system:capture_%d", i);
930                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
931                 if (!p) return -1;
932                 set_latency_range (p, false, lr);
933                 _system_inputs.push_back(static_cast<AlsaPort*>(p));
934         }
935
936         lr.min = lr.max = _samples_per_period + (_measure_latency ? 0 : _systemic_audio_output_latency);
937         for (int i = 1; i <= a_out; ++i) {
938                 char tmp[64];
939                 snprintf(tmp, sizeof(tmp), "system:playback_%d", i);
940                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
941                 if (!p) return -1;
942                 set_latency_range (p, true, lr);
943                 _system_outputs.push_back(static_cast<AlsaPort*>(p));
944         }
945         return 0;
946 }
947
948 int
949 AlsaAudioBackend::register_system_midi_ports()
950 {
951         std::map<std::string, std::string> devices;
952         int midi_ins = 0;
953         int midi_outs = 0;
954
955         if (_midi_driver_option == _("None")) {
956                 return 0;
957         }
958         get_alsa_rawmidi_device_names(devices);
959
960         for (std::map<std::string, std::string>::const_iterator i = devices.begin (); i != devices.end(); ++i) {
961                 struct AlsaMidiDeviceInfo * nfo = midi_device_info(i->first);
962                 if (!nfo) continue;
963                 if (!nfo->enabled) continue;
964
965                 AlsaRawMidiOut *mout = new AlsaRawMidiOut (i->second.c_str());
966                 if (mout->state ()) {
967                         PBD::warning << string_compose (
968                                         _("AlsaRawMidiOut: failed to open midi device '%1'."), i->second)
969                                 << endmsg;
970                         delete mout;
971                 } else {
972                         mout->setup_timing(_samples_per_period, _samplerate);
973                         mout->sync_time (g_get_monotonic_time());
974                         if (mout->start ()) {
975                                 PBD::warning << string_compose (
976                                                 _("AlsaRawMidiOut: failed to start midi device '%1'."), i->second)
977                                         << endmsg;
978                                 delete mout;
979                         } else {
980                                 char tmp[64];
981                                 snprintf(tmp, sizeof(tmp), "system:midi_playback_%d", ++midi_ins);
982                                 PortHandle p = add_port(std::string(tmp), DataType::MIDI, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
983                                 if (!p) {
984                                         mout->stop();
985                                         delete mout;
986                                 }
987                                 LatencyRange lr;
988                                 lr.min = lr.max = _samples_per_period + (_measure_latency ? 0 : nfo->systemic_output_latency);
989                                 set_latency_range (p, false, lr);
990                                 _system_midi_out.push_back(static_cast<AlsaPort*>(p));
991                                 _rmidi_out.push_back (mout);
992                         }
993                 }
994
995                 AlsaRawMidiIn *midin = new AlsaRawMidiIn (i->second.c_str());
996                 if (midin->state ()) {
997                         PBD::warning << string_compose (
998                                         _("AlsaRawMidiIn: failed to open midi device '%1'."), i->second)
999                                 << endmsg;
1000                         delete midin;
1001                 } else {
1002                         midin->setup_timing(_samples_per_period, _samplerate);
1003                         midin->sync_time (g_get_monotonic_time());
1004                         if (midin->start ()) {
1005                                 PBD::warning << string_compose (
1006                                                 _("AlsaRawMidiIn: failed to start midi device '%1'."), i->second)
1007                                         << endmsg;
1008                                 delete midin;
1009                         } else {
1010                                 char tmp[64];
1011                                 snprintf(tmp, sizeof(tmp), "system:midi_capture_%d", ++midi_outs);
1012                                 PortHandle p = add_port(std::string(tmp), DataType::MIDI, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
1013                                 if (!p) {
1014                                         midin->stop();
1015                                         delete midin;
1016                                         continue;
1017                                 }
1018                                 LatencyRange lr;
1019                                 lr.min = lr.max = _samples_per_period + (_measure_latency ? 0 : nfo->systemic_input_latency);
1020                                 set_latency_range (p, false, lr);
1021                                 _system_midi_in.push_back(static_cast<AlsaPort*>(p));
1022                                 _rmidi_in.push_back (midin);
1023                         }
1024                 }
1025         }
1026         return 0;
1027 }
1028
1029 void
1030 AlsaAudioBackend::unregister_system_ports()
1031 {
1032         size_t i = 0;
1033         _system_inputs.clear();
1034         _system_outputs.clear();
1035         _system_midi_in.clear();
1036         _system_midi_out.clear();
1037         while (i <  _ports.size ()) {
1038                 AlsaPort* port = _ports[i];
1039                 if (port->is_physical () && port->is_terminal ()) {
1040                         port->disconnect_all ();
1041                         _ports.erase (_ports.begin() + i);
1042                 } else {
1043                         ++i;
1044                 }
1045         }
1046 }
1047
1048 int
1049 AlsaAudioBackend::connect (const std::string& src, const std::string& dst)
1050 {
1051         AlsaPort* src_port = find_port (src);
1052         AlsaPort* dst_port = find_port (dst);
1053
1054         if (!src_port) {
1055                 PBD::error << _("AlsaBackend::connect: Invalid Source port:")
1056                                 << " (" << src <<")" << endmsg;
1057                 return -1;
1058         }
1059         if (!dst_port) {
1060                 PBD::error << _("AlsaBackend::connect: Invalid Destination port:")
1061                         << " (" << dst <<")" << endmsg;
1062                 return -1;
1063         }
1064         return src_port->connect (dst_port);
1065 }
1066
1067 int
1068 AlsaAudioBackend::disconnect (const std::string& src, const std::string& dst)
1069 {
1070         AlsaPort* src_port = find_port (src);
1071         AlsaPort* dst_port = find_port (dst);
1072
1073         if (!src_port || !dst_port) {
1074                 PBD::error << _("AlsaBackend::disconnect: Invalid Port(s)") << endmsg;
1075                 return -1;
1076         }
1077         return src_port->disconnect (dst_port);
1078 }
1079
1080 int
1081 AlsaAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
1082 {
1083         AlsaPort* dst_port = find_port (dst);
1084         if (!valid_port (src)) {
1085                 PBD::error << _("AlsaBackend::connect: Invalid Source Port Handle") << endmsg;
1086                 return -1;
1087         }
1088         if (!dst_port) {
1089                 PBD::error << _("AlsaBackend::connect: Invalid Destination Port")
1090                         << " (" << dst << ")" << endmsg;
1091                 return -1;
1092         }
1093         return static_cast<AlsaPort*>(src)->connect (dst_port);
1094 }
1095
1096 int
1097 AlsaAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
1098 {
1099         AlsaPort* dst_port = find_port (dst);
1100         if (!valid_port (src) || !dst_port) {
1101                 PBD::error << _("AlsaBackend::disconnect: Invalid Port(s)") << endmsg;
1102                 return -1;
1103         }
1104         return static_cast<AlsaPort*>(src)->disconnect (dst_port);
1105 }
1106
1107 int
1108 AlsaAudioBackend::disconnect_all (PortEngine::PortHandle port)
1109 {
1110         if (!valid_port (port)) {
1111                 PBD::error << _("AlsaBackend::disconnect_all: Invalid Port") << endmsg;
1112                 return -1;
1113         }
1114         static_cast<AlsaPort*>(port)->disconnect_all ();
1115         return 0;
1116 }
1117
1118 bool
1119 AlsaAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
1120 {
1121         if (!valid_port (port)) {
1122                 PBD::error << _("AlsaBackend::disconnect_all: Invalid Port") << endmsg;
1123                 return false;
1124         }
1125         return static_cast<AlsaPort*>(port)->is_connected ();
1126 }
1127
1128 bool
1129 AlsaAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
1130 {
1131         AlsaPort* dst_port = find_port (dst);
1132         if (!valid_port (src) || !dst_port) {
1133                 PBD::error << _("AlsaBackend::connected_to: Invalid Port") << endmsg;
1134                 return false;
1135         }
1136         return static_cast<AlsaPort*>(src)->is_connected (dst_port);
1137 }
1138
1139 bool
1140 AlsaAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
1141 {
1142         if (!valid_port (port)) {
1143                 PBD::error << _("AlsaBackend::physically_connected: Invalid Port") << endmsg;
1144                 return false;
1145         }
1146         return static_cast<AlsaPort*>(port)->is_physically_connected ();
1147 }
1148
1149 int
1150 AlsaAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
1151 {
1152         if (!valid_port (port)) {
1153                 PBD::error << _("AlsaBackend::get_connections: Invalid Port") << endmsg;
1154                 return -1;
1155         }
1156
1157         assert (0 == names.size ());
1158
1159         const std::vector<AlsaPort*>& connected_ports = static_cast<AlsaPort*>(port)->get_connections ();
1160
1161         for (std::vector<AlsaPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
1162                 names.push_back ((*i)->name ());
1163         }
1164
1165         return (int)names.size ();
1166 }
1167
1168 /* MIDI */
1169 int
1170 AlsaAudioBackend::midi_event_get (
1171                 pframes_t& timestamp,
1172                 size_t& size, uint8_t** buf, void* port_buffer,
1173                 uint32_t event_index)
1174 {
1175         assert (buf && port_buffer);
1176         AlsaMidiBuffer& source = * static_cast<AlsaMidiBuffer*>(port_buffer);
1177         if (event_index >= source.size ()) {
1178                 return -1;
1179         }
1180         AlsaMidiEvent * const event = source[event_index].get ();
1181
1182         timestamp = event->timestamp ();
1183         size = event->size ();
1184         *buf = event->data ();
1185         return 0;
1186 }
1187
1188 int
1189 AlsaAudioBackend::midi_event_put (
1190                 void* port_buffer,
1191                 pframes_t timestamp,
1192                 const uint8_t* buffer, size_t size)
1193 {
1194         assert (buffer && port_buffer);
1195         AlsaMidiBuffer& dst = * static_cast<AlsaMidiBuffer*>(port_buffer);
1196         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
1197                 fprintf (stderr, "AlsaMidiBuffer: it's too late for this event. %d > %d\n",
1198                                 (pframes_t)dst.back ()->timestamp (), timestamp);
1199                 return -1;
1200         }
1201         dst.push_back (boost::shared_ptr<AlsaMidiEvent>(new AlsaMidiEvent (timestamp, buffer, size)));
1202         return 0;
1203 }
1204
1205 uint32_t
1206 AlsaAudioBackend::get_midi_event_count (void* port_buffer)
1207 {
1208         assert (port_buffer);
1209         return static_cast<AlsaMidiBuffer*>(port_buffer)->size ();
1210 }
1211
1212 void
1213 AlsaAudioBackend::midi_clear (void* port_buffer)
1214 {
1215         assert (port_buffer);
1216         AlsaMidiBuffer * buf = static_cast<AlsaMidiBuffer*>(port_buffer);
1217         assert (buf);
1218         buf->clear ();
1219 }
1220
1221 /* Monitoring */
1222
1223 bool
1224 AlsaAudioBackend::can_monitor_input () const
1225 {
1226         return false;
1227 }
1228
1229 int
1230 AlsaAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1231 {
1232         return -1;
1233 }
1234
1235 int
1236 AlsaAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1237 {
1238         return -1;
1239 }
1240
1241 bool
1242 AlsaAudioBackend::monitoring_input (PortEngine::PortHandle)
1243 {
1244         return false;
1245 }
1246
1247 /* Latency management */
1248
1249 void
1250 AlsaAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1251 {
1252         if (!valid_port (port)) {
1253                 PBD::error << _("AlsaPort::set_latency_range (): invalid port.") << endmsg;
1254         }
1255         static_cast<AlsaPort*>(port)->set_latency_range (latency_range, for_playback);
1256 }
1257
1258 LatencyRange
1259 AlsaAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1260 {
1261         if (!valid_port (port)) {
1262                 PBD::error << _("AlsaPort::get_latency_range (): invalid port.") << endmsg;
1263                 LatencyRange r;
1264                 r.min = 0;
1265                 r.max = 0;
1266                 return r;
1267         }
1268         return static_cast<AlsaPort*>(port)->latency_range (for_playback);
1269 }
1270
1271 /* Discovering physical ports */
1272
1273 bool
1274 AlsaAudioBackend::port_is_physical (PortEngine::PortHandle port) const
1275 {
1276         if (!valid_port (port)) {
1277                 PBD::error << _("AlsaPort::port_is_physical (): invalid port.") << endmsg;
1278                 return false;
1279         }
1280         return static_cast<AlsaPort*>(port)->is_physical ();
1281 }
1282
1283 void
1284 AlsaAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1285 {
1286         for (size_t i = 0; i < _ports.size (); ++i) {
1287                 AlsaPort* port = _ports[i];
1288                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1289                         port_names.push_back (port->name ());
1290                 }
1291         }
1292 }
1293
1294 void
1295 AlsaAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1296 {
1297         for (size_t i = 0; i < _ports.size (); ++i) {
1298                 AlsaPort* port = _ports[i];
1299                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1300                         port_names.push_back (port->name ());
1301                 }
1302         }
1303 }
1304
1305 ChanCount
1306 AlsaAudioBackend::n_physical_outputs () const
1307 {
1308         int n_midi = 0;
1309         int n_audio = 0;
1310         for (size_t i = 0; i < _ports.size (); ++i) {
1311                 AlsaPort* port = _ports[i];
1312                 if (port->is_output () && port->is_physical ()) {
1313                         switch (port->type ()) {
1314                                 case DataType::AUDIO: ++n_audio; break;
1315                                 case DataType::MIDI: ++n_midi; break;
1316                                 default: break;
1317                         }
1318                 }
1319         }
1320         ChanCount cc;
1321         cc.set (DataType::AUDIO, n_audio);
1322         cc.set (DataType::MIDI, n_midi);
1323         return cc;
1324 }
1325
1326 ChanCount
1327 AlsaAudioBackend::n_physical_inputs () const
1328 {
1329         int n_midi = 0;
1330         int n_audio = 0;
1331         for (size_t i = 0; i < _ports.size (); ++i) {
1332                 AlsaPort* port = _ports[i];
1333                 if (port->is_input () && port->is_physical ()) {
1334                         switch (port->type ()) {
1335                                 case DataType::AUDIO: ++n_audio; break;
1336                                 case DataType::MIDI: ++n_midi; break;
1337                                 default: break;
1338                         }
1339                 }
1340         }
1341         ChanCount cc;
1342         cc.set (DataType::AUDIO, n_audio);
1343         cc.set (DataType::MIDI, n_midi);
1344         return cc;
1345 }
1346
1347 /* Getting access to the data buffer for a port */
1348
1349 void*
1350 AlsaAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1351 {
1352         assert (port);
1353         assert (valid_port (port));
1354         return static_cast<AlsaPort*>(port)->get_buffer (nframes);
1355 }
1356
1357 /* Engine Process */
1358 void *
1359 AlsaAudioBackend::main_process_thread ()
1360 {
1361         AudioEngine::thread_init_callback (this);
1362         _active = true;
1363         _processed_samples = 0;
1364
1365         uint64_t clock1, clock2;
1366         clock1 = g_get_monotonic_time();
1367         _pcmi->pcm_start ();
1368         int no_proc_errors = 0;
1369         const int bailout = 2 * _samplerate / _samples_per_period;
1370         const int64_t nomial_time = 1e6 * _samples_per_period / _samplerate;
1371
1372         manager.registration_callback();
1373         manager.graph_order_callback();
1374
1375         while (_run) {
1376                 long nr;
1377                 bool xrun = false;
1378                 if (!_freewheeling) {
1379                         nr = _pcmi->pcm_wait ();
1380
1381                         if (_pcmi->state () > 0) {
1382                                 ++no_proc_errors;
1383                                 xrun = true;
1384                         }
1385                         if (_pcmi->state () < 0 || no_proc_errors > bailout) {
1386                                 PBD::error << _("AlsaAudioBackend: I/O error. Audio Process Terminated.") << endmsg;
1387                                 break;
1388                         }
1389                         int gop = 0;
1390                         while (nr >= (long)_samples_per_period) {
1391                                 uint32_t i = 0;
1392                                 clock1 = g_get_monotonic_time();
1393                                 no_proc_errors = 0;
1394
1395                                 _pcmi->capt_init (_samples_per_period);
1396                                 for (std::vector<AlsaPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++i) {
1397                                         _pcmi->capt_chan (i, (float*)((*it)->get_buffer(_samples_per_period)), _samples_per_period);
1398                                 }
1399                                 _pcmi->capt_done (_samples_per_period);
1400
1401                                 /* de-queue midi*/
1402                                 i = 0;
1403                                 for (std::vector<AlsaPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++i) {
1404                                         assert (_rmidi_in.size() > i);
1405                                         AlsaRawMidiIn *rm = static_cast<AlsaRawMidiIn*>(_rmidi_in.at(i));
1406                                         void *bptr = (*it)->get_buffer(0);
1407                                         pframes_t time;
1408                                         uint8_t data[64]; // match MaxAlsaRawEventSize in alsa_rawmidi.cc
1409                                         size_t size = sizeof(data);
1410                                         midi_clear(bptr);
1411                                         while (rm->recv_event (time, data, size)) {
1412                                                 midi_event_put(bptr, time, data, size);
1413                                                 size = sizeof(data);
1414                                         }
1415                                         rm->sync_time (clock1);
1416                                 }
1417
1418                                 for (std::vector<AlsaPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it) {
1419                                         memset ((*it)->get_buffer (_samples_per_period), 0, _samples_per_period * sizeof (Sample));
1420                                 }
1421
1422                                 if (engine.process_callback (_samples_per_period)) {
1423                                         _pcmi->pcm_stop ();
1424                                         _active = false;
1425                                         return 0;
1426                                 }
1427
1428                                 i = 0;
1429                                 for (std::vector<AlsaPort*>::iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it, ++i) {
1430                                         static_cast<AlsaMidiPort*>(*it)->next_period();
1431                                 }
1432
1433                                 /* queue midi*/
1434                                 i = 0;
1435                                 for (std::vector<AlsaPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it, ++i) {
1436                                         assert (_rmidi_out.size() > i);
1437                                         const AlsaMidiBuffer src = static_cast<const AlsaMidiPort*>(*it)->const_buffer();
1438                                         AlsaRawMidiOut *rm = static_cast<AlsaRawMidiOut*>(_rmidi_out.at(i));
1439                                         rm->sync_time (clock1);
1440                                         for (AlsaMidiBuffer::const_iterator mit = src.begin (); mit != src.end (); ++mit) {
1441                                                 rm->send_event ((*mit)->timestamp(), (*mit)->data(), (*mit)->size());
1442                                         }
1443                                 }
1444
1445                                 /* write back audio */
1446                                 i = 0;
1447                                 _pcmi->play_init (_samples_per_period);
1448                                 for (std::vector<AlsaPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it, ++i) {
1449                                         _pcmi->play_chan (i, (const float*)(*it)->get_buffer (_samples_per_period), _samples_per_period);
1450                                 }
1451                                 for (; i < _pcmi->nplay (); ++i) {
1452                                         _pcmi->clear_chan (i, _samples_per_period);
1453                                 }
1454                                 _pcmi->play_done (_samples_per_period);
1455                                 nr -= _samples_per_period;
1456                                 _processed_samples += _samples_per_period;
1457
1458                                 /* calculate DSP load */
1459                                 clock2 = g_get_monotonic_time();
1460                                 const int64_t elapsed_time = clock2 - clock1;
1461                                 _dsp_load = elapsed_time / (float) nomial_time;
1462                                 ++gop;
1463                         }
1464                         if (gop != 1) {
1465                                 fprintf(stderr, "grouped audio periods %d != 1\n", gop);
1466                         }
1467
1468                         if (xrun && (_pcmi->capt_xrun() > 0 || _pcmi->play_xrun() > 0)) {
1469                                 engine.Xrun ();
1470 #if 0
1471                                 fprintf(stderr, "ALSA x-run read: %.1f ms, write: %.1f ms\n",
1472                                                 _pcmi->capt_xrun() * 1000.0, _pcmi->play_xrun() * 1000.0);
1473 #endif
1474                         }
1475                 } else {
1476                         // Freewheelin'
1477                         for (std::vector<AlsaPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
1478                                 memset ((*it)->get_buffer (_samples_per_period), 0, _samples_per_period * sizeof (Sample));
1479                         }
1480                         for (std::vector<AlsaPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it) {
1481                                 static_cast<AlsaMidiBuffer*>((*it)->get_buffer(0))->clear ();
1482                         }
1483
1484                         if (engine.process_callback (_samples_per_period)) {
1485                                 _pcmi->pcm_stop ();
1486                                 return 0;
1487                         }
1488                         _dsp_load = 1.0;
1489                         Glib::usleep (100); // don't hog cpu
1490                 }
1491
1492                 bool connections_changed = false;
1493                 bool ports_changed = false;
1494                 if (!pthread_mutex_trylock (&_port_callback_mutex)) {
1495                         if (_port_change_flag) {
1496                                 ports_changed = true;
1497                                 _port_change_flag = false;
1498                         }
1499                         if (!_port_connection_queue.empty ()) {
1500                                 connections_changed = true;
1501                         }
1502                         while (!_port_connection_queue.empty ()) {
1503                                 PortConnectData *c = _port_connection_queue.back ();
1504                                 manager.connect_callback (c->a, c->b, c->c);
1505                                 _port_connection_queue.pop_back ();
1506                                 delete c;
1507                         }
1508                         pthread_mutex_unlock (&_port_callback_mutex);
1509                 }
1510                 if (ports_changed) {
1511                         manager.registration_callback();
1512                 }
1513                 if (connections_changed) {
1514                         manager.graph_order_callback();
1515                 }
1516                 if (connections_changed || ports_changed) {
1517                         engine.latency_callback(false);
1518                         engine.latency_callback(true);
1519                 }
1520
1521         }
1522         _pcmi->pcm_stop ();
1523         _active = false;
1524         if (_run) {
1525                 engine.halted_callback("ALSA I/O error.");
1526         }
1527         return 0;
1528 }
1529
1530
1531 /******************************************************************************/
1532
1533 static boost::shared_ptr<AlsaAudioBackend> _instance;
1534
1535 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
1536 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
1537 static int deinstantiate ();
1538 static bool already_configured ();
1539
1540 static ARDOUR::AudioBackendInfo _descriptor = {
1541         "ALSA",
1542         instantiate,
1543         deinstantiate,
1544         backend_factory,
1545         already_configured,
1546 };
1547
1548 static boost::shared_ptr<AudioBackend>
1549 backend_factory (AudioEngine& e)
1550 {
1551         if (!_instance) {
1552                 _instance.reset (new AlsaAudioBackend (e, _descriptor));
1553         }
1554         return _instance;
1555 }
1556
1557 static int
1558 instantiate (const std::string& arg1, const std::string& /* arg2 */)
1559 {
1560         s_instance_name = arg1;
1561         return 0;
1562 }
1563
1564 static int
1565 deinstantiate ()
1566 {
1567         _instance.reset ();
1568         return 0;
1569 }
1570
1571 static bool
1572 already_configured ()
1573 {
1574         return false;
1575 }
1576
1577 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
1578 {
1579         return &_descriptor;
1580 }
1581
1582
1583 /******************************************************************************/
1584 AlsaPort::AlsaPort (AlsaAudioBackend &b, const std::string& name, PortFlags flags)
1585         : _alsa_backend (b)
1586         , _name  (name)
1587         , _flags (flags)
1588 {
1589         _capture_latency_range.min = 0;
1590         _capture_latency_range.max = 0;
1591         _playback_latency_range.min = 0;
1592         _playback_latency_range.max = 0;
1593 }
1594
1595 AlsaPort::~AlsaPort () {
1596         disconnect_all ();
1597 }
1598
1599
1600 int AlsaPort::connect (AlsaPort *port)
1601 {
1602         if (!port) {
1603                 PBD::error << _("AlsaPort::connect (): invalid (null) port") << endmsg;
1604                 return -1;
1605         }
1606
1607         if (type () != port->type ()) {
1608                 PBD::error << _("AlsaPort::connect (): wrong port-type") << endmsg;
1609                 return -1;
1610         }
1611
1612         if (is_output () && port->is_output ()) {
1613                 PBD::error << _("AlsaPort::connect (): cannot inter-connect output ports.") << endmsg;
1614                 return -1;
1615         }
1616
1617         if (is_input () && port->is_input ()) {
1618                 PBD::error << _("AlsaPort::connect (): cannot inter-connect input ports.") << endmsg;
1619                 return -1;
1620         }
1621
1622         if (this == port) {
1623                 PBD::error << _("AlsaPort::connect (): cannot self-connect ports.") << endmsg;
1624                 return -1;
1625         }
1626
1627         if (is_connected (port)) {
1628 #if 0 // don't bother to warn about this for now. just ignore it
1629                 PBD::error << _("AlsaPort::connect (): ports are already connected:")
1630                         << " (" << name () << ") -> (" << port->name () << ")"
1631                         << endmsg;
1632 #endif
1633                 return -1;
1634         }
1635
1636         _connect (port, true);
1637         return 0;
1638 }
1639
1640
1641 void AlsaPort::_connect (AlsaPort *port, bool callback)
1642 {
1643         _connections.push_back (port);
1644         if (callback) {
1645                 port->_connect (this, false);
1646                 _alsa_backend.port_connect_callback (name(),  port->name(), true);
1647         }
1648 }
1649
1650 int AlsaPort::disconnect (AlsaPort *port)
1651 {
1652         if (!port) {
1653                 PBD::error << _("AlsaPort::disconnect (): invalid (null) port") << endmsg;
1654                 return -1;
1655         }
1656
1657         if (!is_connected (port)) {
1658                 PBD::error << _("AlsaPort::disconnect (): ports are not connected:")
1659                         << " (" << name () << ") -> (" << port->name () << ")"
1660                         << endmsg;
1661                 return -1;
1662         }
1663         _disconnect (port, true);
1664         return 0;
1665 }
1666
1667 void AlsaPort::_disconnect (AlsaPort *port, bool callback)
1668 {
1669         std::vector<AlsaPort*>::iterator it = std::find (_connections.begin (), _connections.end (), port);
1670
1671         assert (it != _connections.end ());
1672
1673         _connections.erase (it);
1674
1675         if (callback) {
1676                 port->_disconnect (this, false);
1677                 _alsa_backend.port_connect_callback (name(),  port->name(), false);
1678         }
1679 }
1680
1681
1682 void AlsaPort::disconnect_all ()
1683 {
1684         while (!_connections.empty ()) {
1685                 _connections.back ()->_disconnect (this, false);
1686                 _alsa_backend.port_connect_callback (name(),  _connections.back ()->name(), false);
1687                 _connections.pop_back ();
1688         }
1689 }
1690
1691 bool
1692 AlsaPort::is_connected (const AlsaPort *port) const
1693 {
1694         return std::find (_connections.begin (), _connections.end (), port) != _connections.end ();
1695 }
1696
1697 bool AlsaPort::is_physically_connected () const
1698 {
1699         for (std::vector<AlsaPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
1700                 if ((*it)->is_physical ()) {
1701                         return true;
1702                 }
1703         }
1704         return false;
1705 }
1706
1707 /******************************************************************************/
1708
1709 AlsaAudioPort::AlsaAudioPort (AlsaAudioBackend &b, const std::string& name, PortFlags flags)
1710         : AlsaPort (b, name, flags)
1711 {
1712         memset (_buffer, 0, sizeof (_buffer));
1713         mlock(_buffer, sizeof (_buffer));
1714 }
1715
1716 AlsaAudioPort::~AlsaAudioPort () { }
1717
1718 void* AlsaAudioPort::get_buffer (pframes_t n_samples)
1719 {
1720         if (is_input ()) {
1721                 std::vector<AlsaPort*>::const_iterator it = get_connections ().begin ();
1722                 if (it == get_connections ().end ()) {
1723                         memset (_buffer, 0, n_samples * sizeof (Sample));
1724                 } else {
1725                         AlsaAudioPort const * source = static_cast<const AlsaAudioPort*>(*it);
1726                         assert (source && source->is_output ());
1727                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
1728                         while (++it != get_connections ().end ()) {
1729                                 source = static_cast<const AlsaAudioPort*>(*it);
1730                                 assert (source && source->is_output ());
1731                                 Sample* dst = buffer ();
1732                                 const Sample* src = source->const_buffer ();
1733                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
1734                                         *dst += *src;
1735                                 }
1736                         }
1737                 }
1738         }
1739         return _buffer;
1740 }
1741
1742
1743 AlsaMidiPort::AlsaMidiPort (AlsaAudioBackend &b, const std::string& name, PortFlags flags)
1744         : AlsaPort (b, name, flags)
1745         , _bufperiod (0)
1746 {
1747         _buffer[0].clear ();
1748         _buffer[1].clear ();
1749 }
1750
1751 AlsaMidiPort::~AlsaMidiPort () { }
1752
1753 struct MidiEventSorter {
1754         bool operator() (const boost::shared_ptr<AlsaMidiEvent>& a, const boost::shared_ptr<AlsaMidiEvent>& b) {
1755                 return *a < *b;
1756         }
1757 };
1758
1759 void* AlsaMidiPort::get_buffer (pframes_t /* nframes */)
1760 {
1761         if (is_input ()) {
1762                 (_buffer[_bufperiod]).clear ();
1763                 for (std::vector<AlsaPort*>::const_iterator i = get_connections ().begin ();
1764                                 i != get_connections ().end ();
1765                                 ++i) {
1766                         const AlsaMidiBuffer src = static_cast<const AlsaMidiPort*>(*i)->const_buffer ();
1767                         for (AlsaMidiBuffer::const_iterator it = src.begin (); it != src.end (); ++it) {
1768                                 (_buffer[_bufperiod]).push_back (boost::shared_ptr<AlsaMidiEvent>(new AlsaMidiEvent (**it)));
1769                         }
1770                 }
1771                 std::sort ((_buffer[_bufperiod]).begin (), (_buffer[_bufperiod]).end (), MidiEventSorter());
1772         }
1773         return &(_buffer[_bufperiod]);
1774 }
1775
1776 AlsaMidiEvent::AlsaMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
1777         : _size (size)
1778         , _timestamp (timestamp)
1779         , _data (0)
1780 {
1781         if (size > 0) {
1782                 _data = (uint8_t*) malloc (size);
1783                 memcpy (_data, data, size);
1784         }
1785 }
1786
1787 AlsaMidiEvent::AlsaMidiEvent (const AlsaMidiEvent& other)
1788         : _size (other.size ())
1789         , _timestamp (other.timestamp ())
1790         , _data (0)
1791 {
1792         if (other.size () && other.const_data ()) {
1793                 _data = (uint8_t*) malloc (other.size ());
1794                 memcpy (_data, other.const_data (), other.size ());
1795         }
1796 };
1797
1798 AlsaMidiEvent::~AlsaMidiEvent () {
1799         free (_data);
1800 };