optimize port lookup, adding/removing/reconnecting routes
[ardour.git] / libs / backends / dummy / dummy_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 <sys/time.h>
21 #include <regex.h>
22 #include <stdlib.h>
23
24 #include <glibmm.h>
25
26 #ifdef PLATFORM_WINDOWS
27 #include <windows.h>
28 #include <pbd/windows_timer_utils.h>
29 #endif
30
31 #include "dummy_audiobackend.h"
32 #include "dummy_midi_seq.h"
33
34 #include "pbd/error.h"
35 #include "ardour/port_manager.h"
36 #include "i18n.h"
37
38 using namespace ARDOUR;
39
40 static std::string s_instance_name;
41 size_t DummyAudioBackend::_max_buffer_size = 8192;
42 std::vector<std::string> DummyAudioBackend::_midi_options;
43 std::vector<AudioBackend::DeviceStatus> DummyAudioBackend::_device_status;
44
45 std::vector<DummyAudioBackend::DriverSpeed> DummyAudioBackend::_driver_speed;
46
47 static int64_t _x_get_monotonic_usec() {
48 #ifdef PLATFORM_WINDOWS
49         return PBD::get_microseconds();
50 #endif
51         return g_get_monotonic_time();
52 }
53
54 DummyAudioBackend::DummyAudioBackend (AudioEngine& e, AudioBackendInfo& info)
55         : AudioBackend (e, info)
56         , _running (false)
57         , _freewheel (false)
58         , _freewheeling (false)
59         , _speedup (1.0)
60         , _device ("")
61         , _samplerate (48000)
62         , _samples_per_period (1024)
63         , _dsp_load (0)
64         , _n_inputs (0)
65         , _n_outputs (0)
66         , _n_midi_inputs (0)
67         , _n_midi_outputs (0)
68         , _midi_mode (MidiNoEvents)
69         , _systemic_input_latency (0)
70         , _systemic_output_latency (0)
71         , _processed_samples (0)
72         , _port_change_flag (false)
73 {
74         _instance_name = s_instance_name;
75         _device = _("Silence");
76         pthread_mutex_init (&_port_callback_mutex, 0);
77
78         if (_driver_speed.empty()) {
79                 _driver_speed.push_back (DriverSpeed (_("Half Speed"),   2.0f));
80                 _driver_speed.push_back (DriverSpeed (_("Normal Speed"), 1.0f));
81                 _driver_speed.push_back (DriverSpeed (_("Double Speed"), 0.5f));
82                 _driver_speed.push_back (DriverSpeed (_("5x Speed"),     0.2f));
83                 _driver_speed.push_back (DriverSpeed (_("10x Speed"),    0.1f));
84                 _driver_speed.push_back (DriverSpeed (_("15x Speed"),    0.06666f));
85                 _driver_speed.push_back (DriverSpeed (_("20x Speed"),    0.05f));
86                 _driver_speed.push_back (DriverSpeed (_("50x Speed"),    0.02f));
87         }
88
89 }
90
91 DummyAudioBackend::~DummyAudioBackend ()
92 {
93         pthread_mutex_destroy (&_port_callback_mutex);
94 }
95
96 /* AUDIOBACKEND API */
97
98 std::string
99 DummyAudioBackend::name () const
100 {
101         return X_("Dummy"); // internal name
102 }
103
104 bool
105 DummyAudioBackend::is_realtime () const
106 {
107         return false;
108 }
109
110 std::vector<AudioBackend::DeviceStatus>
111 DummyAudioBackend::enumerate_devices () const
112 {
113         if (_device_status.empty()) {
114                 _device_status.push_back (DeviceStatus (_("Silence"), true));
115                 _device_status.push_back (DeviceStatus (_("Sine Wave"), true));
116                 _device_status.push_back (DeviceStatus (_("Square Wave"), true));
117                 _device_status.push_back (DeviceStatus (_("Impulses"), true));
118                 _device_status.push_back (DeviceStatus (_("Uniform White Noise"), true));
119                 _device_status.push_back (DeviceStatus (_("Gaussian White Noise"), true));
120                 _device_status.push_back (DeviceStatus (_("Pink Noise"), true));
121                 _device_status.push_back (DeviceStatus (_("Pink Noise (low CPU)"), true));
122                 _device_status.push_back (DeviceStatus (_("Sine Sweep"), true));
123                 _device_status.push_back (DeviceStatus (_("Sine Sweep Swell"), true));
124                 _device_status.push_back (DeviceStatus (_("Square Sweep"), true));
125                 _device_status.push_back (DeviceStatus (_("Square Sweep Swell"), true));
126                 _device_status.push_back (DeviceStatus (_("Loopback"), true));
127         }
128         return _device_status;
129 }
130
131 std::vector<float>
132 DummyAudioBackend::available_sample_rates (const std::string&) const
133 {
134         std::vector<float> sr;
135         sr.push_back (8000.0);
136         sr.push_back (22050.0);
137         sr.push_back (24000.0);
138         sr.push_back (44100.0);
139         sr.push_back (48000.0);
140         sr.push_back (88200.0);
141         sr.push_back (96000.0);
142         sr.push_back (176400.0);
143         sr.push_back (192000.0);
144         return sr;
145 }
146
147 std::vector<uint32_t>
148 DummyAudioBackend::available_buffer_sizes (const std::string&) const
149 {
150         std::vector<uint32_t> bs;
151         bs.push_back (4);
152         bs.push_back (8);
153         bs.push_back (16);
154         bs.push_back (32);
155         bs.push_back (64);
156         bs.push_back (128);
157         bs.push_back (256);
158         bs.push_back (512);
159         bs.push_back (1024);
160         bs.push_back (2048);
161         bs.push_back (4096);
162         bs.push_back (8192);
163         return bs;
164 }
165
166 uint32_t
167 DummyAudioBackend::available_input_channel_count (const std::string&) const
168 {
169         return 128;
170 }
171
172 uint32_t
173 DummyAudioBackend::available_output_channel_count (const std::string&) const
174 {
175         return 128;
176 }
177
178 bool
179 DummyAudioBackend::can_change_sample_rate_when_running () const
180 {
181         return true;
182 }
183
184 bool
185 DummyAudioBackend::can_change_buffer_size_when_running () const
186 {
187         return true;
188 }
189
190 std::vector<std::string>
191 DummyAudioBackend::enumerate_drivers () const
192 {
193         std::vector<std::string> speed_drivers;
194         for (std::vector<DriverSpeed>::const_iterator it = _driver_speed.begin () ; it != _driver_speed.end (); ++it) {
195                 speed_drivers.push_back (it->name);
196         }
197         return speed_drivers;
198 }
199
200 std::string
201 DummyAudioBackend::driver_name () const
202 {
203         for (std::vector<DriverSpeed>::const_iterator it = _driver_speed.begin () ; it != _driver_speed.end (); ++it) {
204                 if (rintf (1e6f * _speedup) == rintf (1e6f * it->speedup)) {
205                         return it->name;
206                 }
207         }
208         assert (0);
209         return _("Normal Speed");
210 }
211
212 int
213 DummyAudioBackend::set_driver (const std::string& d)
214 {
215         for (std::vector<DriverSpeed>::const_iterator it = _driver_speed.begin () ; it != _driver_speed.end (); ++it) {
216                 if (d == it->name) {
217                         _speedup = it->speedup;
218                         return 0;
219                 }
220         }
221         assert (0);
222         return -1;
223 }
224
225 int
226 DummyAudioBackend::set_device_name (const std::string& d)
227 {
228         _device = d;
229         return 0;
230 }
231
232 int
233 DummyAudioBackend::set_sample_rate (float sr)
234 {
235         if (sr <= 0) { return -1; }
236         _samplerate = sr;
237         engine.sample_rate_change (sr);
238         return 0;
239 }
240
241 int
242 DummyAudioBackend::set_buffer_size (uint32_t bs)
243 {
244         if (bs <= 0 || bs > _max_buffer_size) {
245                 return -1;
246         }
247         _samples_per_period = bs;
248
249         /* update port latencies
250          * with 'Loopback' there is exactly once cycle latency,
251          * divide it between In + Out;
252          */
253         LatencyRange lr;
254         lr.min = lr.max = _systemic_input_latency;
255         for (std::vector<DummyAudioPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
256                 set_latency_range (*it, false, lr);
257         }
258         for (std::vector<DummyMidiPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it) {
259                 set_latency_range (*it, false, lr);
260         }
261
262         lr.min = lr.max = _systemic_output_latency;
263         for (std::vector<DummyAudioPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it) {
264                 set_latency_range (*it, true, lr);
265         }
266         for (std::vector<DummyMidiPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it) {
267                 set_latency_range (*it, true, lr);
268         }
269
270         engine.buffer_size_change (bs);
271         return 0;
272 }
273
274 int
275 DummyAudioBackend::set_interleaved (bool yn)
276 {
277         if (!yn) { return 0; }
278         return -1;
279 }
280
281 int
282 DummyAudioBackend::set_input_channels (uint32_t cc)
283 {
284         _n_inputs = cc;
285         return 0;
286 }
287
288 int
289 DummyAudioBackend::set_output_channels (uint32_t cc)
290 {
291         _n_outputs = cc;
292         return 0;
293 }
294
295 int
296 DummyAudioBackend::set_systemic_input_latency (uint32_t sl)
297 {
298         _systemic_input_latency = sl;
299         return 0;
300 }
301
302 int
303 DummyAudioBackend::set_systemic_output_latency (uint32_t sl)
304 {
305         _systemic_output_latency = sl;
306         return 0;
307 }
308
309 /* Retrieving parameters */
310 std::string
311 DummyAudioBackend::device_name () const
312 {
313         return _device;
314 }
315
316 float
317 DummyAudioBackend::sample_rate () const
318 {
319         return _samplerate;
320 }
321
322 uint32_t
323 DummyAudioBackend::buffer_size () const
324 {
325         return _samples_per_period;
326 }
327
328 bool
329 DummyAudioBackend::interleaved () const
330 {
331         return false;
332 }
333
334 uint32_t
335 DummyAudioBackend::input_channels () const
336 {
337         return _n_inputs;
338 }
339
340 uint32_t
341 DummyAudioBackend::output_channels () const
342 {
343         return _n_outputs;
344 }
345
346 uint32_t
347 DummyAudioBackend::systemic_input_latency () const
348 {
349         return _systemic_input_latency;
350 }
351
352 uint32_t
353 DummyAudioBackend::systemic_output_latency () const
354 {
355         return _systemic_output_latency;
356 }
357
358
359 /* MIDI */
360 std::vector<std::string>
361 DummyAudioBackend::enumerate_midi_options () const
362 {
363         if (_midi_options.empty()) {
364                 _midi_options.push_back (_("1 in, 1 out, Silence"));
365                 _midi_options.push_back (_("2 in, 2 out, Silence"));
366                 _midi_options.push_back (_("8 in, 8 out, Silence"));
367                 _midi_options.push_back (_("Midi Event Generators"));
368                 _midi_options.push_back (_("8 in, 8 out, Loopback"));
369                 _midi_options.push_back (_("MIDI to Audio, Loopback"));
370                 _midi_options.push_back (_("No MIDI I/O"));
371         }
372         return _midi_options;
373 }
374
375 int
376 DummyAudioBackend::set_midi_option (const std::string& opt)
377 {
378         _midi_mode = MidiNoEvents;
379         if (opt == _("1 in, 1 out, Silence")) {
380                 _n_midi_inputs = _n_midi_outputs = 1;
381         }
382         else if (opt == _("2 in, 2 out, Silence")) {
383                 _n_midi_inputs = _n_midi_outputs = 2;
384         }
385         else if (opt == _("8 in, 8 out, Silence")) {
386                 _n_midi_inputs = _n_midi_outputs = 8;
387         }
388         else if (opt == _("Midi Event Generators")) {
389                 _n_midi_inputs = _n_midi_outputs = NUM_MIDI_EVENT_GENERATORS;
390                 _midi_mode = MidiGenerator;
391         }
392         else if (opt == _("8 in, 8 out, Loopback")) {
393                 _n_midi_inputs = _n_midi_outputs = 8;
394                 _midi_mode = MidiLoopback;
395         }
396         else if (opt == _("MIDI to Audio, Loopback")) {
397                 _n_midi_inputs = _n_midi_outputs = UINT32_MAX;
398                 _midi_mode = MidiToAudio;
399         }
400         else {
401                 _n_midi_inputs = _n_midi_outputs = 0;
402         }
403         return 0;
404 }
405
406 std::string
407 DummyAudioBackend::midi_option () const
408 {
409         return ""; // TODO
410 }
411
412 /* State Control */
413
414 static void * pthread_process (void *arg)
415 {
416         DummyAudioBackend *d = static_cast<DummyAudioBackend *>(arg);
417         d->main_process_thread ();
418         pthread_exit (0);
419         return 0;
420 }
421
422 int
423 DummyAudioBackend::_start (bool /*for_latency_measurement*/)
424 {
425         if (_running) {
426                 PBD::error << _("DummyAudioBackend: already active.") << endmsg;
427                 return BackendReinitializationError;
428         }
429
430         if (_ports.size () || _portmap.size ()) {
431                 PBD::warning << _("DummyAudioBackend: recovering from unclean shutdown, port registry is not empty.") << endmsg;
432                 for (PortIndex::const_iterator it = _ports.begin (); it != _ports.end (); ++it) {
433                         PBD::info << _("DummyAudioBackend: port '") << (*it)->name () << "' exists." << endmsg;
434                 }
435                 _system_inputs.clear();
436                 _system_outputs.clear();
437                 _system_midi_in.clear();
438                 _system_midi_out.clear();
439                 _ports.clear();
440                 _portmap.clear();
441         }
442
443         if (register_system_ports()) {
444                 PBD::error << _("DummyAudioBackend: failed to register system ports.") << endmsg;
445                 return PortRegistrationError;
446         }
447
448         engine.sample_rate_change (_samplerate);
449         engine.buffer_size_change (_samples_per_period);
450
451         _dsp_load_calc.set_max_time (_samplerate, _samples_per_period);
452
453         if (engine.reestablish_ports ()) {
454                 PBD::error << _("DummyAudioBackend: Could not re-establish ports.") << endmsg;
455                 stop ();
456                 return PortReconnectError;
457         }
458
459         engine.reconnect_ports ();
460         _port_change_flag = false;
461
462         if (pthread_create (&_main_thread, NULL, pthread_process, this)) {
463                 PBD::error << _("DummyAudioBackend: cannot start.") << endmsg;
464         }
465
466         int timeout = 5000;
467         while (!_running && --timeout > 0) { Glib::usleep (1000); }
468
469         if (timeout == 0 || !_running) {
470                 PBD::error << _("DummyAudioBackend: failed to start process thread.") << endmsg;
471                 return ProcessThreadStartError;
472         }
473
474         return NoError;
475 }
476
477 int
478 DummyAudioBackend::stop ()
479 {
480         void *status;
481         if (!_running) {
482                 return 0;
483         }
484
485         _running = false;
486         if (pthread_join (_main_thread, &status)) {
487                 PBD::error << _("DummyAudioBackend: failed to terminate.") << endmsg;
488                 return -1;
489         }
490         unregister_ports();
491         return 0;
492 }
493
494 int
495 DummyAudioBackend::freewheel (bool onoff)
496 {
497         _freewheeling = onoff;
498         return 0;
499 }
500
501 float
502 DummyAudioBackend::dsp_load () const
503 {
504         return 100.f * _dsp_load;
505 }
506
507 size_t
508 DummyAudioBackend::raw_buffer_size (DataType t)
509 {
510         switch (t) {
511                 case DataType::AUDIO:
512                         return _samples_per_period * sizeof(Sample);
513                 case DataType::MIDI:
514                         return _max_buffer_size; // XXX not really limited
515         }
516         return 0;
517 }
518
519 /* Process time */
520 framepos_t
521 DummyAudioBackend::sample_time ()
522 {
523         return _processed_samples;
524 }
525
526 framepos_t
527 DummyAudioBackend::sample_time_at_cycle_start ()
528 {
529         return _processed_samples;
530 }
531
532 pframes_t
533 DummyAudioBackend::samples_since_cycle_start ()
534 {
535         return 0;
536 }
537
538
539 void *
540 DummyAudioBackend::dummy_process_thread (void *arg)
541 {
542         ThreadData* td = reinterpret_cast<ThreadData*> (arg);
543         boost::function<void ()> f = td->f;
544         delete td;
545         f ();
546         return 0;
547 }
548
549 int
550 DummyAudioBackend::create_process_thread (boost::function<void()> func)
551 {
552         pthread_t thread_id;
553         pthread_attr_t attr;
554         size_t stacksize = 100000;
555
556         pthread_attr_init (&attr);
557         pthread_attr_setstacksize (&attr, stacksize);
558         ThreadData* td = new ThreadData (this, func, stacksize);
559
560         if (pthread_create (&thread_id, &attr, dummy_process_thread, td)) {
561                 PBD::error << _("AudioEngine: cannot create process thread.") << endmsg;
562                 pthread_attr_destroy (&attr);
563                 return -1;
564         }
565         pthread_attr_destroy (&attr);
566
567         _threads.push_back (thread_id);
568         return 0;
569 }
570
571 int
572 DummyAudioBackend::join_process_threads ()
573 {
574         int rv = 0;
575
576         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
577         {
578                 void *status;
579                 if (pthread_join (*i, &status)) {
580                         PBD::error << _("AudioEngine: cannot terminate process thread.") << endmsg;
581                         rv -= 1;
582                 }
583         }
584         _threads.clear ();
585         return rv;
586 }
587
588 bool
589 DummyAudioBackend::in_process_thread ()
590 {
591         if (pthread_equal (_main_thread, pthread_self()) != 0) {
592                 return true;
593         }
594
595         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
596         {
597                 if (pthread_equal (*i, pthread_self ()) != 0) {
598                         return true;
599                 }
600         }
601         return false;
602 }
603
604 uint32_t
605 DummyAudioBackend::process_thread_count ()
606 {
607         return _threads.size ();
608 }
609
610 void
611 DummyAudioBackend::update_latencies ()
612 {
613         // trigger latency callback in RT thread (locked graph)
614         port_connect_add_remove_callback();
615 }
616
617 /* PORTENGINE API */
618
619 void*
620 DummyAudioBackend::private_handle () const
621 {
622         return NULL;
623 }
624
625 const std::string&
626 DummyAudioBackend::my_name () const
627 {
628         return _instance_name;
629 }
630
631 bool
632 DummyAudioBackend::available () const
633 {
634         return true;
635 }
636
637 uint32_t
638 DummyAudioBackend::port_name_size () const
639 {
640         return 256;
641 }
642
643 int
644 DummyAudioBackend::set_port_name (PortEngine::PortHandle port, const std::string& name)
645 {
646         if (!valid_port (port)) {
647                 PBD::error << _("DummyBackend::set_port_name: Invalid Port(s)") << endmsg;
648                 return -1;
649         }
650         return static_cast<DummyPort*>(port)->set_name (_instance_name + ":" + name);
651 }
652
653 std::string
654 DummyAudioBackend::get_port_name (PortEngine::PortHandle port) const
655 {
656         if (!valid_port (port)) {
657                 PBD::error << _("DummyBackend::get_port_name: Invalid Port(s)") << endmsg;
658                 return std::string ();
659         }
660         return static_cast<DummyPort*>(port)->name ();
661 }
662
663 int
664 DummyAudioBackend::get_port_property (PortHandle port, const std::string& key, std::string& value, std::string& type) const
665 {
666         if (!valid_port (port)) {
667                 PBD::warning << _("DummyBackend::get_port_property: Invalid Port(s)") << endmsg;
668                 return -1;
669         }
670         if (key == "http://jackaudio.org/metadata/pretty-name") {
671                 type = "";
672                 value = static_cast<DummyPort*>(port)->pretty_name ();
673                 if (!value.empty()) {
674                         return 0;
675                 }
676         }
677         return -1;
678 }
679
680 int
681 DummyAudioBackend::set_port_property (PortHandle port, const std::string& key, const std::string& value, const std::string& type)
682 {
683         if (!valid_port (port)) {
684                 PBD::warning << _("DummyBackend::set_port_property: Invalid Port(s)") << endmsg;
685                 return -1;
686         }
687         if (key == "http://jackaudio.org/metadata/pretty-name" && type.empty ()) {
688                 static_cast<DummyPort*>(port)->set_pretty_name (value);
689                 return 0;
690         }
691         return -1;
692 }
693
694 PortEngine::PortHandle
695 DummyAudioBackend::get_port_by_name (const std::string& name) const
696 {
697         PortHandle port = (PortHandle) find_port (name);
698         return port;
699 }
700
701 int
702 DummyAudioBackend::get_ports (
703                 const std::string& port_name_pattern,
704                 DataType type, PortFlags flags,
705                 std::vector<std::string>& port_names) const
706 {
707         int rv = 0;
708         regex_t port_regex;
709         bool use_regexp = false;
710         if (port_name_pattern.size () > 0) {
711                 if (!regcomp (&port_regex, port_name_pattern.c_str (), REG_EXTENDED|REG_NOSUB)) {
712                         use_regexp = true;
713                 }
714         }
715
716         for (PortIndex::iterator i = _ports.begin (); i != _ports.end (); ++i) {
717                 DummyPort* port = *i;
718                 if ((port->type () == type) && flags == (port->flags () & flags)) {
719                         if (!use_regexp || !regexec (&port_regex, port->name ().c_str (), 0, NULL, 0)) {
720                                 port_names.push_back (port->name ());
721                                 ++rv;
722                         }
723                 }
724         }
725         if (use_regexp) {
726                 regfree (&port_regex);
727         }
728         return rv;
729 }
730
731 DataType
732 DummyAudioBackend::port_data_type (PortEngine::PortHandle port) const
733 {
734         if (!valid_port (port)) {
735                 return DataType::NIL;
736         }
737         return static_cast<DummyPort*>(port)->type ();
738 }
739
740 PortEngine::PortHandle
741 DummyAudioBackend::register_port (
742                 const std::string& name,
743                 ARDOUR::DataType type,
744                 ARDOUR::PortFlags flags)
745 {
746         if (name.size () == 0) { return 0; }
747         if (flags & IsPhysical) { return 0; }
748         if (!_running) {
749                 PBD::info << _("DummyBackend::register_port: Engine is not running.") << endmsg;
750         }
751         return add_port (_instance_name + ":" + name, type, flags);
752 }
753
754 PortEngine::PortHandle
755 DummyAudioBackend::add_port (
756                 const std::string& name,
757                 ARDOUR::DataType type,
758                 ARDOUR::PortFlags flags)
759 {
760         assert(name.size ());
761         if (find_port (name)) {
762                 PBD::error << _("DummyBackend::register_port: Port already exists:")
763                                 << " (" << name << ")" << endmsg;
764                 return 0;
765         }
766         DummyPort* port = NULL;
767         switch (type) {
768                 case DataType::AUDIO:
769                         port = new DummyAudioPort (*this, name, flags);
770                         break;
771                 case DataType::MIDI:
772                         port = new DummyMidiPort (*this, name, flags);
773                         break;
774                 default:
775                         PBD::error << _("DummyBackend::register_port: Invalid Data Type.") << endmsg;
776                         return 0;
777         }
778
779         _ports.insert (port);
780         _portmap.insert (make_pair (name, port));
781
782         return port;
783 }
784
785 void
786 DummyAudioBackend::unregister_port (PortEngine::PortHandle port_handle)
787 {
788         if (!_running) {
789                 PBD::info << _("DummyBackend::unregister_port: Engine is not running.") << endmsg;
790                 assert (!valid_port (port_handle));
791                 return;
792         }
793         DummyPort* port = static_cast<DummyPort*>(port_handle);
794         PortIndex::iterator i = _ports.find (static_cast<DummyPort*>(port_handle));
795         if (i == _ports.end ()) {
796                 PBD::error << _("DummyBackend::unregister_port: Failed to find port") << endmsg;
797                 return;
798         }
799         disconnect_all(port_handle);
800         PortMap::const_iterator it = _portmap.find ((*i)->name());
801         if (it != _portmap.end()) {
802                 _portmap.erase (it);
803         }
804         _ports.erase (i);
805         delete port;
806 }
807
808 int
809 DummyAudioBackend::register_system_ports()
810 {
811         LatencyRange lr;
812         enum DummyAudioPort::GeneratorType gt;
813         if (_device == _("Uniform White Noise")) {
814                 gt = DummyAudioPort::UniformWhiteNoise;
815         } else if (_device == _("Gaussian White Noise")) {
816                 gt = DummyAudioPort::GaussianWhiteNoise;
817         } else if (_device == _("Pink Noise")) {
818                 gt = DummyAudioPort::PinkNoise;
819         } else if (_device == _("Pink Noise (low CPU)")) {
820                 gt = DummyAudioPort::PonyNoise;
821         } else if (_device == _("Sine Wave")) {
822                 gt = DummyAudioPort::SineWave;
823         } else if (_device == _("Square Wave")) {
824                 gt = DummyAudioPort::SquareWave;
825         } else if (_device == _("Impulses")) {
826                 gt = DummyAudioPort::KronekerDelta;
827         } else if (_device == _("Sine Sweep")) {
828                 gt = DummyAudioPort::SineSweep;
829         } else if (_device == _("Sine Sweep Swell")) {
830                 gt = DummyAudioPort::SineSweepSwell;
831         } else if (_device == _("Square Sweep")) {
832                 gt = DummyAudioPort::SquareSweep;
833         } else if (_device == _("Square Sweep Swell")) {
834                 gt = DummyAudioPort::SquareSweepSwell;
835         } else if (_device == _("Loopback")) {
836                 gt = DummyAudioPort::Loopback;
837         } else {
838                 gt = DummyAudioPort::Silence;
839         }
840
841         if (_midi_mode == MidiToAudio) {
842                 gt = DummyAudioPort::Loopback;
843         }
844
845         const int a_ins = _n_inputs > 0 ? _n_inputs : 8;
846         const int a_out = _n_outputs > 0 ? _n_outputs : 8;
847         const int m_ins = _n_midi_inputs == UINT_MAX ? 0 : _n_midi_inputs;
848         const int m_out = _n_midi_outputs == UINT_MAX ? a_ins : _n_midi_outputs;
849
850
851         /* audio ports */
852         lr.min = lr.max = _systemic_input_latency;
853         for (int i = 1; i <= a_ins; ++i) {
854                 char tmp[64];
855                 snprintf(tmp, sizeof(tmp), "system:capture_%d", i);
856                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
857                 if (!p) return -1;
858                 set_latency_range (p, false, lr);
859                 _system_inputs.push_back (static_cast<DummyAudioPort*>(p));
860                 static_cast<DummyAudioPort*>(p)->setup_generator (gt, _samplerate);
861         }
862
863         lr.min = lr.max = _systemic_output_latency;
864         for (int i = 1; i <= a_out; ++i) {
865                 char tmp[64];
866                 snprintf(tmp, sizeof(tmp), "system:playback_%d", i);
867                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
868                 if (!p) return -1;
869                 set_latency_range (p, true, lr);
870                 _system_outputs.push_back (static_cast<DummyAudioPort*>(p));
871         }
872
873         /* midi ports */
874         lr.min = lr.max = _systemic_input_latency;
875         for (int i = 0; i < m_ins; ++i) {
876                 char tmp[64];
877                 snprintf(tmp, sizeof(tmp), "system:midi_capture_%d", i+1);
878                 PortHandle p = add_port(std::string(tmp), DataType::MIDI, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
879                 if (!p) return -1;
880                 set_latency_range (p, false, lr);
881                 _system_midi_in.push_back (static_cast<DummyMidiPort*>(p));
882                 if (_midi_mode == MidiGenerator) {
883                         static_cast<DummyMidiPort*>(p)->setup_generator (i % NUM_MIDI_EVENT_GENERATORS, _samplerate);
884                         static_cast<DummyMidiPort*>(p)->set_pretty_name (DummyMidiData::sequence_names[i % NUM_MIDI_EVENT_GENERATORS]);
885                 }
886         }
887
888         lr.min = lr.max = _systemic_output_latency;
889         for (int i = 1; i <= m_out; ++i) {
890                 char tmp[64];
891                 snprintf(tmp, sizeof(tmp), "system:midi_playback_%d", i);
892                 PortHandle p = add_port(std::string(tmp), DataType::MIDI, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
893                 if (!p) return -1;
894                 set_latency_range (p, true, lr);
895                 _system_midi_out.push_back (static_cast<DummyMidiPort*>(p));
896
897                 if (_device == _("Loopback") && _midi_mode == MidiToAudio) {
898                         std::stringstream ss;
899                         ss << "Midi2Audio";
900                         for (int apc = 0; apc < (int)_system_inputs.size(); ++apc) {
901                                 if ((apc % m_out) + 1 == i) {
902                                         ss << " >" << (apc + 1);
903                                 }
904                         }
905                         static_cast<DummyMidiPort*>(p)->set_pretty_name (ss.str());
906                 }
907         }
908         return 0;
909 }
910
911 void
912 DummyAudioBackend::unregister_ports (bool system_only)
913 {
914         _system_inputs.clear();
915         _system_outputs.clear();
916         _system_midi_in.clear();
917         _system_midi_out.clear();
918
919         for (PortIndex::iterator i = _ports.begin (); i != _ports.end ();) {
920                 PortIndex::iterator cur = i++;
921                 DummyPort* port = *cur;
922                 if (! system_only || (port->is_physical () && port->is_terminal ())) {
923                         port->disconnect_all ();
924                         PortMap::const_iterator it = _portmap.find (port->name());
925                         if (it != _portmap.end()) {
926                                 _portmap.erase (it);
927                         }
928                         delete port;
929                         _ports.erase (cur);
930                 }
931         }
932 }
933
934 int
935 DummyAudioBackend::connect (const std::string& src, const std::string& dst)
936 {
937         DummyPort* src_port = find_port (src);
938         DummyPort* dst_port = find_port (dst);
939
940         if (!src_port) {
941                 PBD::error << _("DummyBackend::connect: Invalid Source port:")
942                                 << " (" << src <<")" << endmsg;
943                 return -1;
944         }
945         if (!dst_port) {
946                 PBD::error << _("DummyBackend::connect: Invalid Destination port:")
947                         << " (" << dst <<")" << endmsg;
948                 return -1;
949         }
950         return src_port->connect (dst_port);
951 }
952
953 int
954 DummyAudioBackend::disconnect (const std::string& src, const std::string& dst)
955 {
956         DummyPort* src_port = find_port (src);
957         DummyPort* dst_port = find_port (dst);
958
959         if (!src_port || !dst_port) {
960                 PBD::error << _("DummyBackend::disconnect: Invalid Port(s)") << endmsg;
961                 return -1;
962         }
963         return src_port->disconnect (dst_port);
964 }
965
966 int
967 DummyAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
968 {
969         DummyPort* dst_port = find_port (dst);
970         if (!valid_port (src)) {
971                 PBD::error << _("DummyBackend::connect: Invalid Source Port Handle") << endmsg;
972                 return -1;
973         }
974         if (!dst_port) {
975                 PBD::error << _("DummyBackend::connect: Invalid Destination Port")
976                         << " (" << dst << ")" << endmsg;
977                 return -1;
978         }
979         return static_cast<DummyPort*>(src)->connect (dst_port);
980 }
981
982 int
983 DummyAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
984 {
985         DummyPort* dst_port = find_port (dst);
986         if (!valid_port (src) || !dst_port) {
987                 PBD::error << _("DummyBackend::disconnect: Invalid Port(s)") << endmsg;
988                 return -1;
989         }
990         return static_cast<DummyPort*>(src)->disconnect (dst_port);
991 }
992
993 int
994 DummyAudioBackend::disconnect_all (PortEngine::PortHandle port)
995 {
996         if (!valid_port (port)) {
997                 PBD::error << _("DummyBackend::disconnect_all: Invalid Port") << endmsg;
998                 return -1;
999         }
1000         static_cast<DummyPort*>(port)->disconnect_all ();
1001         return 0;
1002 }
1003
1004 bool
1005 DummyAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
1006 {
1007         if (!valid_port (port)) {
1008                 PBD::error << _("DummyBackend::disconnect_all: Invalid Port") << endmsg;
1009                 return false;
1010         }
1011         return static_cast<DummyPort*>(port)->is_connected ();
1012 }
1013
1014 bool
1015 DummyAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
1016 {
1017         DummyPort* dst_port = find_port (dst);
1018 #ifndef NDEBUG
1019         if (!valid_port (src) || !dst_port) {
1020                 PBD::error << _("DummyBackend::connected_to: Invalid Port") << endmsg;
1021                 return false;
1022         }
1023 #endif
1024         return static_cast<DummyPort*>(src)->is_connected (dst_port);
1025 }
1026
1027 bool
1028 DummyAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
1029 {
1030         if (!valid_port (port)) {
1031                 PBD::error << _("DummyBackend::physically_connected: Invalid Port") << endmsg;
1032                 return false;
1033         }
1034         return static_cast<DummyPort*>(port)->is_physically_connected ();
1035 }
1036
1037 int
1038 DummyAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
1039 {
1040         if (!valid_port (port)) {
1041                 PBD::error << _("DummyBackend::get_connections: Invalid Port") << endmsg;
1042                 return -1;
1043         }
1044
1045         assert (0 == names.size ());
1046
1047         const std::set<DummyPort*>& connected_ports = static_cast<DummyPort*>(port)->get_connections ();
1048
1049         for (std::set<DummyPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
1050                 names.push_back ((*i)->name ());
1051         }
1052
1053         return (int)names.size ();
1054 }
1055
1056 /* MIDI */
1057 int
1058 DummyAudioBackend::midi_event_get (
1059                 pframes_t& timestamp,
1060                 size_t& size, uint8_t** buf, void* port_buffer,
1061                 uint32_t event_index)
1062 {
1063         assert (buf && port_buffer);
1064         DummyMidiBuffer& source = * static_cast<DummyMidiBuffer*>(port_buffer);
1065         if (event_index >= source.size ()) {
1066                 return -1;
1067         }
1068         DummyMidiEvent * const event = source[event_index].get ();
1069
1070         timestamp = event->timestamp ();
1071         size = event->size ();
1072         *buf = event->data ();
1073         return 0;
1074 }
1075
1076 int
1077 DummyAudioBackend::midi_event_put (
1078                 void* port_buffer,
1079                 pframes_t timestamp,
1080                 const uint8_t* buffer, size_t size)
1081 {
1082         assert (buffer && port_buffer);
1083         DummyMidiBuffer& dst = * static_cast<DummyMidiBuffer*>(port_buffer);
1084         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
1085                 // nevermind, ::get_buffer() sorts events, but always print warning
1086                 fprintf (stderr, "DummyMidiBuffer: it's too late for this event %d > %d.\n", (pframes_t)dst.back ()->timestamp (), timestamp);
1087         }
1088         dst.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (timestamp, buffer, size)));
1089 #if 0 // DEBUG MIDI EVENTS
1090         printf("DummyAudioBackend::midi_event_put %d, %zu: ", timestamp, size);
1091         for (size_t xx = 0; xx < size; ++xx) {
1092                 printf(" %02x", buffer[xx]);
1093         }
1094         printf("\n");
1095 #endif
1096         return 0;
1097 }
1098
1099 uint32_t
1100 DummyAudioBackend::get_midi_event_count (void* port_buffer)
1101 {
1102         assert (port_buffer);
1103         return static_cast<DummyMidiBuffer*>(port_buffer)->size ();
1104 }
1105
1106 void
1107 DummyAudioBackend::midi_clear (void* port_buffer)
1108 {
1109         assert (port_buffer);
1110         DummyMidiBuffer * buf = static_cast<DummyMidiBuffer*>(port_buffer);
1111         assert (buf);
1112         buf->clear ();
1113 }
1114
1115 /* Monitoring */
1116
1117 bool
1118 DummyAudioBackend::can_monitor_input () const
1119 {
1120         return false;
1121 }
1122
1123 int
1124 DummyAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1125 {
1126         return -1;
1127 }
1128
1129 int
1130 DummyAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1131 {
1132         return -1;
1133 }
1134
1135 bool
1136 DummyAudioBackend::monitoring_input (PortEngine::PortHandle)
1137 {
1138         return false;
1139 }
1140
1141 /* Latency management */
1142
1143 void
1144 DummyAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1145 {
1146         if (!valid_port (port)) {
1147                 PBD::error << _("DummyPort::set_latency_range (): invalid port.") << endmsg;
1148         }
1149         static_cast<DummyPort*>(port)->set_latency_range (latency_range, for_playback);
1150 }
1151
1152 LatencyRange
1153 DummyAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1154 {
1155         LatencyRange r;
1156         if (!valid_port (port)) {
1157                 PBD::error << _("DummyPort::get_latency_range (): invalid port.") << endmsg;
1158                 r.min = 0;
1159                 r.max = 0;
1160                 return r;
1161         }
1162         DummyPort *p =  static_cast<DummyPort*>(port);
1163         assert(p);
1164
1165         r = p->latency_range (for_playback);
1166         if (p->is_physical() && p->is_terminal()) {
1167                 if (p->is_input() && for_playback) {
1168                         const size_t l_in = _samples_per_period * .25;
1169                         r.min += l_in;
1170                         r.max += l_in;
1171                 }
1172                 if (p->is_output() && !for_playback) {
1173                         /* with 'Loopback' there is exactly once cycle latency, divide it between In + Out; */
1174                         const size_t l_in = _samples_per_period * .25;
1175                         const size_t l_out = _samples_per_period - l_in;
1176                         r.min += l_out;
1177                         r.max += l_out;
1178                 }
1179         }
1180         return r;
1181 }
1182
1183 /* Discovering physical ports */
1184
1185 bool
1186 DummyAudioBackend::port_is_physical (PortEngine::PortHandle port) const
1187 {
1188         if (!valid_port (port)) {
1189                 PBD::error << _("DummyPort::port_is_physical (): invalid port.") << endmsg;
1190                 return false;
1191         }
1192         return static_cast<DummyPort*>(port)->is_physical ();
1193 }
1194
1195 void
1196 DummyAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1197 {
1198         for (PortIndex::iterator i = _ports.begin (); i != _ports.end (); ++i) {
1199                 DummyPort* port = *i;
1200                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1201                         port_names.push_back (port->name ());
1202                 }
1203         }
1204 }
1205
1206 void
1207 DummyAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1208 {
1209         for (PortIndex::iterator i = _ports.begin (); i != _ports.end (); ++i) {
1210                 DummyPort* port = *i;
1211                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1212                         port_names.push_back (port->name ());
1213                 }
1214         }
1215 }
1216
1217 ChanCount
1218 DummyAudioBackend::n_physical_outputs () const
1219 {
1220         int n_midi = 0;
1221         int n_audio = 0;
1222         for (PortIndex::iterator i = _ports.begin (); i != _ports.end (); ++i) {
1223                 DummyPort* port = *i;
1224                 if (port->is_output () && port->is_physical ()) {
1225                         switch (port->type ()) {
1226                                 case DataType::AUDIO: ++n_audio; break;
1227                                 case DataType::MIDI: ++n_midi; break;
1228                                 default: break;
1229                         }
1230                 }
1231         }
1232         ChanCount cc;
1233         cc.set (DataType::AUDIO, n_audio);
1234         cc.set (DataType::MIDI, n_midi);
1235         return cc;
1236 }
1237
1238 ChanCount
1239 DummyAudioBackend::n_physical_inputs () const
1240 {
1241         int n_midi = 0;
1242         int n_audio = 0;
1243         for (PortIndex::iterator i = _ports.begin (); i != _ports.end (); ++i) {
1244                 DummyPort* port = *i;
1245                 if (port->is_input () && port->is_physical ()) {
1246                         switch (port->type ()) {
1247                                 case DataType::AUDIO: ++n_audio; break;
1248                                 case DataType::MIDI: ++n_midi; break;
1249                                 default: break;
1250                         }
1251                 }
1252         }
1253         ChanCount cc;
1254         cc.set (DataType::AUDIO, n_audio);
1255         cc.set (DataType::MIDI, n_midi);
1256         return cc;
1257 }
1258
1259 /* Getting access to the data buffer for a port */
1260
1261 void*
1262 DummyAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1263 {
1264         assert (port);
1265         assert (valid_port (port));
1266         return static_cast<DummyPort*>(port)->get_buffer (nframes);
1267 }
1268
1269 /* Engine Process */
1270 void *
1271 DummyAudioBackend::main_process_thread ()
1272 {
1273         AudioEngine::thread_init_callback (this);
1274         _running = true;
1275         _processed_samples = 0;
1276
1277         manager.registration_callback();
1278         manager.graph_order_callback();
1279
1280         int64_t clock1;
1281         clock1 = -1;
1282         while (_running) {
1283
1284                 if (_freewheeling != _freewheel) {
1285                         _freewheel = _freewheeling;
1286                         engine.freewheel_callback (_freewheel);
1287                 }
1288
1289                 // re-set input buffers, generate on demand.
1290                 for (std::vector<DummyAudioPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
1291                         (*it)->next_period();
1292                 }
1293                 for (std::vector<DummyMidiPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it) {
1294                         (*it)->next_period();
1295                 }
1296
1297                 if (engine.process_callback (_samples_per_period)) {
1298                         return 0;
1299                 }
1300                 _processed_samples += _samples_per_period;
1301
1302                 if (_device == _("Loopback") && _midi_mode != MidiToAudio) {
1303                         int opn = 0;
1304                         int opc = _system_outputs.size();
1305                         for (std::vector<DummyAudioPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++opn) {
1306                                 DummyAudioPort* op = _system_outputs[(opn % opc)];
1307                                 (*it)->fill_wavetable ((const float*)op->get_buffer (_samples_per_period), _samples_per_period);
1308                         }
1309                 }
1310
1311                 if (_midi_mode == MidiLoopback) {
1312                         int opn = 0;
1313                         int opc = _system_midi_out.size();
1314                         for (std::vector<DummyMidiPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++opn) {
1315                                 DummyMidiPort* op = _system_midi_out[(opn % opc)];
1316                                 op->get_buffer(0); // mix-down
1317                                 (*it)->set_loopback (op->const_buffer());
1318                         }
1319                 }
1320                 else if (_midi_mode == MidiToAudio) {
1321                         int opn = 0;
1322                         int opc = _system_midi_out.size();
1323                         for (std::vector<DummyAudioPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++opn) {
1324                                 DummyMidiPort* op = _system_midi_out[(opn % opc)];
1325                                 op->get_buffer(0); // mix-down
1326                                 (*it)->midi_to_wavetable (op->const_buffer(), _samples_per_period);
1327                         }
1328                 }
1329
1330                 if (!_freewheel) {
1331                         _dsp_load_calc.set_start_timestamp_us (clock1);
1332                         _dsp_load_calc.set_stop_timestamp_us (_x_get_monotonic_usec());
1333                         _dsp_load = _dsp_load_calc.get_dsp_load_unbound ();
1334
1335                         const int64_t elapsed_time = _dsp_load_calc.elapsed_time_us ();
1336                         const int64_t nominal_time = _dsp_load_calc.get_max_time_us ();
1337                         if (elapsed_time < nominal_time) {
1338                                 const int64_t sleepy = _speedup * (nominal_time - elapsed_time);
1339                                 Glib::usleep (std::max ((int64_t) 100, sleepy));
1340                         } else {
1341                                 Glib::usleep (100); // don't hog cpu
1342                         }
1343                 } else {
1344                         _dsp_load = 1.0f;
1345                         Glib::usleep (100); // don't hog cpu
1346                 }
1347
1348                 /* beginning of next cycle */
1349                 clock1 = _x_get_monotonic_usec();
1350
1351                 bool connections_changed = false;
1352                 bool ports_changed = false;
1353                 if (!pthread_mutex_trylock (&_port_callback_mutex)) {
1354                         if (_port_change_flag) {
1355                                 ports_changed = true;
1356                                 _port_change_flag = false;
1357                         }
1358                         if (!_port_connection_queue.empty ()) {
1359                                 connections_changed = true;
1360                         }
1361                         while (!_port_connection_queue.empty ()) {
1362                                 PortConnectData *c = _port_connection_queue.back ();
1363                                 manager.connect_callback (c->a, c->b, c->c);
1364                                 _port_connection_queue.pop_back ();
1365                                 delete c;
1366                         }
1367                         pthread_mutex_unlock (&_port_callback_mutex);
1368                 }
1369                 if (ports_changed) {
1370                         manager.registration_callback();
1371                 }
1372                 if (connections_changed) {
1373                         manager.graph_order_callback();
1374                 }
1375                 if (connections_changed || ports_changed) {
1376                         engine.latency_callback(false);
1377                         engine.latency_callback(true);
1378                 }
1379
1380         }
1381         _running = false;
1382         return 0;
1383 }
1384
1385
1386 /******************************************************************************/
1387
1388 static boost::shared_ptr<DummyAudioBackend> _instance;
1389
1390 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
1391 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
1392 static int deinstantiate ();
1393 static bool already_configured ();
1394 static bool available ();
1395
1396 static ARDOUR::AudioBackendInfo _descriptor = {
1397         _("None (Dummy)"),
1398         instantiate,
1399         deinstantiate,
1400         backend_factory,
1401         already_configured,
1402         available
1403 };
1404
1405 static boost::shared_ptr<AudioBackend>
1406 backend_factory (AudioEngine& e)
1407 {
1408         if (!_instance) {
1409                 _instance.reset (new DummyAudioBackend (e, _descriptor));
1410         }
1411         return _instance;
1412 }
1413
1414 static int
1415 instantiate (const std::string& arg1, const std::string& /* arg2 */)
1416 {
1417         s_instance_name = arg1;
1418         return 0;
1419 }
1420
1421 static int
1422 deinstantiate ()
1423 {
1424         _instance.reset ();
1425         return 0;
1426 }
1427
1428 static bool
1429 already_configured ()
1430 {
1431         // special-case: unit-tests require backend to be pre-configured.
1432         if (s_instance_name == "Unit-Test") {
1433                 return true;
1434         }
1435         return false;
1436 }
1437
1438 static bool
1439 available ()
1440 {
1441         return true;
1442 }
1443
1444 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
1445 {
1446         return &_descriptor;
1447 }
1448
1449
1450 /******************************************************************************/
1451 DummyPort::DummyPort (DummyAudioBackend &b, const std::string& name, PortFlags flags)
1452         : _dummy_backend (b)
1453         , _name  (name)
1454         , _flags (flags)
1455         , _rseed (0)
1456         , _gen_cycle (false)
1457 {
1458         _capture_latency_range.min = 0;
1459         _capture_latency_range.max = 0;
1460         _playback_latency_range.min = 0;
1461         _playback_latency_range.max = 0;
1462         _dummy_backend.port_connect_add_remove_callback();
1463 }
1464
1465 DummyPort::~DummyPort () {
1466         disconnect_all ();
1467         _dummy_backend.port_connect_add_remove_callback();
1468 }
1469
1470
1471 int DummyPort::connect (DummyPort *port)
1472 {
1473         if (!port) {
1474                 PBD::error << _("DummyPort::connect (): invalid (null) port") << endmsg;
1475                 return -1;
1476         }
1477
1478         if (type () != port->type ()) {
1479                 PBD::error << _("DummyPort::connect (): wrong port-type") << endmsg;
1480                 return -1;
1481         }
1482
1483         if (is_output () && port->is_output ()) {
1484                 PBD::error << _("DummyPort::connect (): cannot inter-connect output ports.") << endmsg;
1485                 return -1;
1486         }
1487
1488         if (is_input () && port->is_input ()) {
1489                 PBD::error << _("DummyPort::connect (): cannot inter-connect input ports.") << endmsg;
1490                 return -1;
1491         }
1492
1493         if (this == port) {
1494                 PBD::error << _("DummyPort::connect (): cannot self-connect ports.") << endmsg;
1495                 return -1;
1496         }
1497
1498         if (is_connected (port)) {
1499 #if 0 // don't bother to warn about this for now. just ignore it
1500                 PBD::error << _("DummyPort::connect (): ports are already connected:")
1501                         << " (" << name () << ") -> (" << port->name () << ")"
1502                         << endmsg;
1503 #endif
1504                 return -1;
1505         }
1506
1507         _connect (port, true);
1508         return 0;
1509 }
1510
1511
1512 void DummyPort::_connect (DummyPort *port, bool callback)
1513 {
1514         _connections.insert (port);
1515         if (callback) {
1516                 port->_connect (this, false);
1517                 _dummy_backend.port_connect_callback (name(),  port->name(), true);
1518         }
1519 }
1520
1521 int DummyPort::disconnect (DummyPort *port)
1522 {
1523         if (!port) {
1524                 PBD::error << _("DummyPort::disconnect (): invalid (null) port") << endmsg;
1525                 return -1;
1526         }
1527
1528         if (!is_connected (port)) {
1529                 PBD::error << _("DummyPort::disconnect (): ports are not connected:")
1530                         << " (" << name () << ") -> (" << port->name () << ")"
1531                         << endmsg;
1532                 return -1;
1533         }
1534         _disconnect (port, true);
1535         return 0;
1536 }
1537
1538 void DummyPort::_disconnect (DummyPort *port, bool callback)
1539 {
1540         std::set<DummyPort*>::iterator it = _connections.find (port);
1541         assert (it != _connections.end ());
1542         _connections.erase (it);
1543         if (callback) {
1544                 port->_disconnect (this, false);
1545                 _dummy_backend.port_connect_callback (name(),  port->name(), false);
1546         }
1547 }
1548
1549
1550 void DummyPort::disconnect_all ()
1551 {
1552         while (!_connections.empty ()) {
1553                 std::set<DummyPort*>::iterator it = _connections.begin ();
1554                 (*it)->_disconnect (this, false);
1555                 _dummy_backend.port_connect_callback (name(), (*it)->name(), false);
1556                 _connections.erase (it);
1557         }
1558 }
1559
1560 bool
1561 DummyPort::is_connected (const DummyPort *port) const
1562 {
1563         return _connections.find (const_cast<DummyPort *>(port)) != _connections.end ();
1564 }
1565
1566 bool DummyPort::is_physically_connected () const
1567 {
1568         for (std::set<DummyPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
1569                 if ((*it)->is_physical ()) {
1570                         return true;
1571                 }
1572         }
1573         return false;
1574 }
1575
1576 void DummyPort::setup_random_number_generator ()
1577 {
1578 #ifdef PLATFORM_WINDOWS
1579         LARGE_INTEGER Count;
1580         if (QueryPerformanceCounter (&Count)) {
1581                 _rseed = Count.QuadPart % UINT_MAX;
1582         } else
1583 #endif
1584         {
1585         _rseed = g_get_monotonic_time() % UINT_MAX;
1586         }
1587         _rseed = (_rseed + (uint64_t)this) % UINT_MAX;
1588         if (_rseed == 0) _rseed = 1;
1589 }
1590
1591 inline uint32_t
1592 DummyPort::randi ()
1593 {
1594         // 31bit Park-Miller-Carta Pseudo-Random Number Generator
1595         // http://www.firstpr.com.au/dsp/rand31/
1596         uint32_t hi, lo;
1597         lo = 16807 * (_rseed & 0xffff);
1598         hi = 16807 * (_rseed >> 16);
1599
1600         lo += (hi & 0x7fff) << 16;
1601         lo += hi >> 15;
1602 #if 1
1603         lo = (lo & 0x7fffffff) + (lo >> 31);
1604 #else
1605         if (lo > 0x7fffffff) { lo -= 0x7fffffff; }
1606 #endif
1607         return (_rseed = lo);
1608 }
1609
1610 inline float
1611 DummyPort::randf ()
1612 {
1613         return (randi() / 1073741824.f) - 1.f;
1614 }
1615
1616 /******************************************************************************/
1617
1618 DummyAudioPort::DummyAudioPort (DummyAudioBackend &b, const std::string& name, PortFlags flags)
1619         : DummyPort (b, name, flags)
1620         , _gen_type (Silence)
1621         , _b0 (0)
1622         , _b1 (0)
1623         , _b2 (0)
1624         , _b3 (0)
1625         , _b4 (0)
1626         , _b5 (0)
1627         , _b6 (0)
1628         , _wavetable (0)
1629         , _gen_period (0)
1630         , _gen_offset (0)
1631         , _gen_perio2 (0)
1632         , _gen_count2 (0)
1633         , _pass (false)
1634         , _rn1 (0)
1635 {
1636         memset (_buffer, 0, sizeof (_buffer));
1637 }
1638
1639 DummyAudioPort::~DummyAudioPort () {
1640         free(_wavetable);
1641         _wavetable = 0;
1642 }
1643
1644 void DummyAudioPort::setup_generator (GeneratorType const g, float const samplerate)
1645 {
1646         DummyPort::setup_random_number_generator();
1647         _gen_type = g;
1648
1649         switch (_gen_type) {
1650                 case PinkNoise:
1651                 case PonyNoise:
1652                 case UniformWhiteNoise:
1653                 case GaussianWhiteNoise:
1654                 case Silence:
1655                         break;
1656                 case KronekerDelta:
1657                         _gen_period = (5 + randi() % (int)(samplerate / 20.f));
1658                         break;
1659                 case SquareWave:
1660                         _gen_period = (5 + randi() % (int)(samplerate / 20.f)) & ~1;
1661                         break;
1662                 case SineWave:
1663                         _gen_period = 5 + randi() % (int)(samplerate / 20.f);
1664                         _wavetable = (Sample*) malloc (_gen_period * sizeof(Sample));
1665                         for (uint32_t i = 0 ; i < _gen_period; ++i) {
1666                                 _wavetable[i] = .12589f * sinf(2.0f * M_PI * (float)i / (float)_gen_period); // -18dBFS
1667                         }
1668                         break;
1669                 case SquareSweep:
1670                 case SquareSweepSwell:
1671                 case SineSweep:
1672                 case SineSweepSwell:
1673                         {
1674                                 _gen_period = 5 * samplerate + randi() % (int)(samplerate * 10.f);
1675                                 _gen_period &= ~1;
1676                                 _gen_perio2 = 1 | (int)ceilf (_gen_period * .89f); // Volume Swell period
1677                                 const double f_min = 20.;
1678                                 const double f_max = samplerate * .5;
1679                                 const double g_p2 = _gen_period * .5;
1680 #ifdef LINEAR_SWEEP
1681                                 const double b = (f_max - f_min) / (2. * samplerate * g_p2);
1682                                 const double a = f_min / samplerate;
1683 #else
1684                                 const double b = log (f_max / f_min) / g_p2;
1685                                 const double a = f_min / (b * samplerate);
1686 #endif
1687                                 const uint32_t g_p2i = rint(g_p2);
1688                                 _wavetable = (Sample*) malloc (_gen_period * sizeof(Sample));
1689                                 for (uint32_t i = 0 ; i < g_p2i; ++i) {
1690 #ifdef LINEAR_SWEEP
1691                                         const double phase = i * (a + b * i);
1692 #else
1693                                         const double phase = a * exp (b * i) - a;
1694 #endif
1695                                         _wavetable[i] = (float)sin (2. * M_PI * (phase - floor (phase)));
1696                                 }
1697                                 for (uint32_t i = g_p2i; i < _gen_period; ++i) {
1698                                         const uint32_t j = _gen_period - i;
1699 #ifdef LINEAR_SWEEP
1700                                         const double phase = j * (a + b * j);
1701 #else
1702                                         const double phase = a * exp (b * j) - a;
1703 #endif
1704                                         _wavetable[i] = -(float)sin (2. * M_PI * (phase - floor (phase)));
1705                                 }
1706                                 if (_gen_type == SquareSweep) {
1707                                         for (uint32_t i = 0 ; i < _gen_period; ++i) {
1708                                                 _wavetable[i] = _wavetable[i] < 0 ? -.40709f : .40709f;
1709                                         }
1710                                 }
1711                                 else if (_gen_type == SquareSweepSwell) {
1712                                         for (uint32_t i = 0 ; i < _gen_period; ++i) {
1713                                                 _wavetable[i] = _wavetable[i] < 0 ? -1 : 1;
1714                                         }
1715                                 }
1716                         }
1717                         break;
1718                 case Loopback:
1719                         _wavetable = (Sample*) malloc (DummyAudioBackend::max_buffer_size() * sizeof(Sample));
1720                         break;
1721         }
1722 }
1723
1724 void DummyAudioPort::midi_to_wavetable (DummyMidiBuffer const * const src, size_t n_samples)
1725 {
1726         memset(_wavetable, 0, n_samples * sizeof(float));
1727         /* generate an audio spike for every midi message
1728          * to verify layency-compensation alignment
1729          * (here: midi-out playback-latency + audio-in capture-latency)
1730          */
1731         for (DummyMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
1732                 const pframes_t t = (*it)->timestamp();
1733                 assert(t < n_samples);
1734                 // somewhat arbitrary mapping for quick visual feedback
1735                 float v = -.5f;
1736                 if ((*it)->size() == 3) {
1737                         const unsigned char *d = (*it)->const_data();
1738                         if ((d[0] & 0xf0) == 0x90) { // note on
1739                                 v = .25f + d[2] / 512.f;
1740                         }
1741                         else if ((d[0] & 0xf0) == 0x80) { // note off
1742                                 v = .3f - d[2] / 640.f;
1743                         }
1744                         else if ((d[0] & 0xf0) == 0xb0) { // CC
1745                                 v = -.1f - d[2] / 256.f;
1746                         }
1747                 }
1748                 _wavetable[t] += v;
1749         }
1750 }
1751
1752 float DummyAudioPort::grandf ()
1753 {
1754         // Gaussian White Noise
1755         // http://www.musicdsp.org/archive.php?classid=0#109
1756         float x1, x2, r;
1757
1758         if (_pass) {
1759                 _pass = false;
1760                 return _rn1;
1761         }
1762
1763         do {
1764                 x1 = randf ();
1765                 x2 = randf ();
1766                 r = x1 * x1 + x2 * x2;
1767         } while ((r >= 1.0f) || (r < 1e-22f));
1768
1769         r = sqrtf (-2.f * logf (r) / r);
1770
1771         _pass = true;
1772         _rn1 = r * x2;
1773         return r * x1;
1774 }
1775
1776 void DummyAudioPort::generate (const pframes_t n_samples)
1777 {
1778         Glib::Threads::Mutex::Lock lm (generator_lock);
1779         if (_gen_cycle) {
1780                 return;
1781         }
1782
1783         switch (_gen_type) {
1784                 case Silence:
1785                         memset (_buffer, 0, n_samples * sizeof (Sample));
1786                         break;
1787                 case SquareWave:
1788                         assert(_gen_period > 0);
1789                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1790                                 if (_gen_offset < _gen_period * .5f) {
1791                                         _buffer[i] =  .40709f; // -6dBFS
1792                                 } else {
1793                                         _buffer[i] = -.40709f;
1794                                 }
1795                                 _gen_offset = (_gen_offset + 1) % _gen_period;
1796                         }
1797                         break;
1798                 case KronekerDelta:
1799                         assert(_gen_period > 0);
1800                         memset (_buffer, 0, n_samples * sizeof (Sample));
1801                         for (pframes_t i = 0; i < n_samples; ++i) {
1802                                 if (_gen_offset == 0) {
1803                                         _buffer[i] = 1.0f;
1804                                 }
1805                                 _gen_offset = (_gen_offset + 1) % _gen_period;
1806                         }
1807                         break;
1808                 case SineSweepSwell:
1809                 case SquareSweepSwell:
1810                         assert(_wavetable && _gen_period > 0);
1811                         {
1812                                 const float vols = 2.f / (float)_gen_perio2;
1813                                 for (pframes_t i = 0; i < n_samples; ++i) {
1814                                         const float g = fabsf (_gen_count2 * vols - 1.f);
1815                                         _buffer[i] = g * _wavetable[_gen_offset];
1816                                         _gen_offset = (_gen_offset + 1) % _gen_period;
1817                                         _gen_count2 = (_gen_count2 + 1) % _gen_perio2;
1818                                 }
1819                         }
1820                         break;
1821                 case Loopback:
1822                         _gen_period = n_samples; // XXX DummyBackend::_samples_per_period;
1823                 case SineWave:
1824                 case SineSweep:
1825                 case SquareSweep:
1826                         assert(_wavetable && _gen_period > 0);
1827                         {
1828                                 pframes_t written = 0;
1829                                 while (written < n_samples) {
1830                                         const uint32_t remain = n_samples - written;
1831                                         const uint32_t to_copy = std::min(remain, _gen_period - _gen_offset);
1832                                         memcpy((void*)&_buffer[written],
1833                                                         (void*)&_wavetable[_gen_offset],
1834                                                         to_copy * sizeof(Sample));
1835                                         written += to_copy;
1836                                         _gen_offset = (_gen_offset + to_copy) % _gen_period;
1837                                 }
1838                         }
1839                         break;
1840                 case UniformWhiteNoise:
1841                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1842                                 _buffer[i] = .158489f * randf();
1843                         }
1844                         break;
1845                 case GaussianWhiteNoise:
1846                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1847                                 _buffer[i] = .089125f * grandf();
1848                         }
1849                         break;
1850                 case PinkNoise:
1851                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1852                                 // Paul Kellet's refined method
1853                                 // http://www.musicdsp.org/files/pink.txt
1854                                 // NB. If 'white' consists of uniform random numbers,
1855                                 // the pink noise will have an almost gaussian distribution.
1856                                 const float white = .0498f * randf ();
1857                                 _b0 = .99886f * _b0 + white * .0555179f;
1858                                 _b1 = .99332f * _b1 + white * .0750759f;
1859                                 _b2 = .96900f * _b2 + white * .1538520f;
1860                                 _b3 = .86650f * _b3 + white * .3104856f;
1861                                 _b4 = .55000f * _b4 + white * .5329522f;
1862                                 _b5 = -.7616f * _b5 - white * .0168980f;
1863                                 _buffer[i] = _b0 + _b1 + _b2 + _b3 + _b4 + _b5 + _b6 + white * 0.5362f;
1864                                 _b6 = white * 0.115926f;
1865                         }
1866                         break;
1867                 case PonyNoise:
1868                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1869                                 const float white = 0.0498f * randf ();
1870                                 // Paul Kellet's economy method
1871                                 // http://www.musicdsp.org/files/pink.txt
1872                                 _b0 = 0.99765f * _b0 + white * 0.0990460f;
1873                                 _b1 = 0.96300f * _b1 + white * 0.2965164f;
1874                                 _b2 = 0.57000f * _b2 + white * 1.0526913f;
1875                                 _buffer[i] = _b0 + _b1 + _b2 + white * 0.1848f;
1876                         }
1877                         break;
1878         }
1879         _gen_cycle = true;
1880 }
1881
1882 void* DummyAudioPort::get_buffer (pframes_t n_samples)
1883 {
1884         if (is_input ()) {
1885                 const std::set<DummyPort *>& connections = get_connections ();
1886                 std::set<DummyPort*>::const_iterator it = connections.begin ();
1887                 if (it == connections.end ()) {
1888                         memset (_buffer, 0, n_samples * sizeof (Sample));
1889                 } else {
1890                         DummyAudioPort * source = static_cast<DummyAudioPort*>(*it);
1891                         assert (source && source->is_output ());
1892                         if (source->is_physical() && source->is_terminal()) {
1893                                 source->get_buffer(n_samples); // generate signal.
1894                         }
1895                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
1896                         while (++it != connections.end ()) {
1897                                 source = static_cast<DummyAudioPort*>(*it);
1898                                 assert (source && source->is_output ());
1899                                 Sample* dst = buffer ();
1900                                 if (source->is_physical() && source->is_terminal()) {
1901                                         source->get_buffer(n_samples); // generate signal.
1902                                 }
1903                                 const Sample* src = source->const_buffer ();
1904                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
1905                                         *dst += *src;
1906                                 }
1907                         }
1908                 }
1909         } else if (is_output () && is_physical () && is_terminal()) {
1910                 if (!_gen_cycle) {
1911                         generate(n_samples);
1912                 }
1913         }
1914         return _buffer;
1915 }
1916
1917
1918 DummyMidiPort::DummyMidiPort (DummyAudioBackend &b, const std::string& name, PortFlags flags)
1919         : DummyPort (b, name, flags)
1920         , _midi_seq_spb (0)
1921         , _midi_seq_time (0)
1922         , _midi_seq_pos (0)
1923 {
1924         _buffer.clear ();
1925         _loopback.clear ();
1926 }
1927
1928 DummyMidiPort::~DummyMidiPort () {
1929         _buffer.clear ();
1930         _loopback.clear ();
1931 }
1932
1933 struct MidiEventSorter {
1934         bool operator() (const boost::shared_ptr<DummyMidiEvent>& a, const boost::shared_ptr<DummyMidiEvent>& b) {
1935                 return *a < *b;
1936         }
1937 };
1938
1939 void DummyMidiPort::set_loopback (DummyMidiBuffer const * const src)
1940 {
1941         _loopback.clear ();
1942         for (DummyMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
1943                 _loopback.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (**it)));
1944         }
1945 }
1946
1947 void DummyMidiPort::setup_generator (int seq_id, const float sr)
1948 {
1949         DummyPort::setup_random_number_generator();
1950         _midi_seq_dat = DummyMidiData::sequences[seq_id % NUM_MIDI_EVENT_GENERATORS];
1951         _midi_seq_spb = sr * .5f; // 120 BPM, beat_time 1.0 per beat.
1952         _midi_seq_pos = 0;
1953         _midi_seq_time = 0;
1954 }
1955
1956 void DummyMidiPort::midi_generate (const pframes_t n_samples)
1957 {
1958         Glib::Threads::Mutex::Lock lm (generator_lock);
1959         if (_gen_cycle) {
1960                 return;
1961         }
1962
1963         _buffer.clear ();
1964         _gen_cycle = true;
1965
1966         if (_midi_seq_spb == 0 || !_midi_seq_dat) {
1967                 for (DummyMidiBuffer::const_iterator it = _loopback.begin (); it != _loopback.end (); ++it) {
1968                         _buffer.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (**it)));
1969                 }
1970                 return;
1971         }
1972
1973         while (1) {
1974                 const int32_t ev_beat_time = _midi_seq_dat[_midi_seq_pos].beat_time * _midi_seq_spb - _midi_seq_time;
1975                 if (ev_beat_time < 0) {
1976                         break;
1977                 }
1978                 if ((pframes_t) ev_beat_time >= n_samples) {
1979                         break;
1980                 }
1981                 _buffer.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (
1982                                                 ev_beat_time,
1983                                                 _midi_seq_dat[_midi_seq_pos].event,
1984                                                 _midi_seq_dat[_midi_seq_pos].size
1985                                                 )));
1986                 ++_midi_seq_pos;
1987
1988                 if (_midi_seq_dat[_midi_seq_pos].event[0] == 0xff && _midi_seq_dat[_midi_seq_pos].event[1] == 0xff) {
1989                         _midi_seq_time -= _midi_seq_dat[_midi_seq_pos].beat_time * _midi_seq_spb;
1990                         _midi_seq_pos = 0;
1991                 }
1992         }
1993         _midi_seq_time += n_samples;
1994 }
1995
1996
1997 void* DummyMidiPort::get_buffer (pframes_t n_samples)
1998 {
1999         if (is_input ()) {
2000                 _buffer.clear ();
2001                 const std::set<DummyPort*>& connections = get_connections ();
2002                 for (std::set<DummyPort*>::const_iterator i = connections.begin ();
2003                                 i != connections.end ();
2004                                 ++i) {
2005                         DummyMidiPort * source = static_cast<DummyMidiPort*>(*i);
2006                         if (source->is_physical() && source->is_terminal()) {
2007                                 source->get_buffer(n_samples); // generate signal.
2008                         }
2009                         const DummyMidiBuffer *src = source->const_buffer ();
2010                         for (DummyMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
2011                                 _buffer.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (**it)));
2012                         }
2013                 }
2014                 std::sort (_buffer.begin (), _buffer.end (), MidiEventSorter());
2015         } else if (is_output () && is_physical () && is_terminal()) {
2016                 if (!_gen_cycle) {
2017                         midi_generate(n_samples);
2018                 }
2019         }
2020         return &_buffer;
2021 }
2022
2023 DummyMidiEvent::DummyMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
2024         : _size (size)
2025         , _timestamp (timestamp)
2026         , _data (0)
2027 {
2028         if (size > 0) {
2029                 _data = (uint8_t*) malloc (size);
2030                 memcpy (_data, data, size);
2031         }
2032 }
2033
2034 DummyMidiEvent::DummyMidiEvent (const DummyMidiEvent& other)
2035         : _size (other.size ())
2036         , _timestamp (other.timestamp ())
2037         , _data (0)
2038 {
2039         if (other.size () && other.const_data ()) {
2040                 _data = (uint8_t*) malloc (other.size ());
2041                 memcpy (_data, other.const_data (), other.size ());
2042         }
2043 };
2044
2045 DummyMidiEvent::~DummyMidiEvent () {
2046         free (_data);
2047 };