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