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