now with C++98 compat
[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.erase (port->name());
801         _ports.erase (i);
802         delete port;
803 }
804
805 int
806 DummyAudioBackend::register_system_ports()
807 {
808         LatencyRange lr;
809         enum DummyAudioPort::GeneratorType gt;
810         if (_device == _("Uniform White Noise")) {
811                 gt = DummyAudioPort::UniformWhiteNoise;
812         } else if (_device == _("Gaussian White Noise")) {
813                 gt = DummyAudioPort::GaussianWhiteNoise;
814         } else if (_device == _("Pink Noise")) {
815                 gt = DummyAudioPort::PinkNoise;
816         } else if (_device == _("Pink Noise (low CPU)")) {
817                 gt = DummyAudioPort::PonyNoise;
818         } else if (_device == _("Sine Wave")) {
819                 gt = DummyAudioPort::SineWave;
820         } else if (_device == _("Square Wave")) {
821                 gt = DummyAudioPort::SquareWave;
822         } else if (_device == _("Impulses")) {
823                 gt = DummyAudioPort::KronekerDelta;
824         } else if (_device == _("Sine Sweep")) {
825                 gt = DummyAudioPort::SineSweep;
826         } else if (_device == _("Sine Sweep Swell")) {
827                 gt = DummyAudioPort::SineSweepSwell;
828         } else if (_device == _("Square Sweep")) {
829                 gt = DummyAudioPort::SquareSweep;
830         } else if (_device == _("Square Sweep Swell")) {
831                 gt = DummyAudioPort::SquareSweepSwell;
832         } else if (_device == _("Loopback")) {
833                 gt = DummyAudioPort::Loopback;
834         } else {
835                 gt = DummyAudioPort::Silence;
836         }
837
838         if (_midi_mode == MidiToAudio) {
839                 gt = DummyAudioPort::Loopback;
840         }
841
842         const int a_ins = _n_inputs > 0 ? _n_inputs : 8;
843         const int a_out = _n_outputs > 0 ? _n_outputs : 8;
844         const int m_ins = _n_midi_inputs == UINT_MAX ? 0 : _n_midi_inputs;
845         const int m_out = _n_midi_outputs == UINT_MAX ? a_ins : _n_midi_outputs;
846
847
848         /* audio ports */
849         lr.min = lr.max = _systemic_input_latency;
850         for (int i = 1; i <= a_ins; ++i) {
851                 char tmp[64];
852                 snprintf(tmp, sizeof(tmp), "system:capture_%d", i);
853                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
854                 if (!p) return -1;
855                 set_latency_range (p, false, lr);
856                 _system_inputs.push_back (static_cast<DummyAudioPort*>(p));
857                 static_cast<DummyAudioPort*>(p)->setup_generator (gt, _samplerate);
858         }
859
860         lr.min = lr.max = _systemic_output_latency;
861         for (int i = 1; i <= a_out; ++i) {
862                 char tmp[64];
863                 snprintf(tmp, sizeof(tmp), "system:playback_%d", i);
864                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
865                 if (!p) return -1;
866                 set_latency_range (p, true, lr);
867                 _system_outputs.push_back (static_cast<DummyAudioPort*>(p));
868         }
869
870         /* midi ports */
871         lr.min = lr.max = _systemic_input_latency;
872         for (int i = 0; i < m_ins; ++i) {
873                 char tmp[64];
874                 snprintf(tmp, sizeof(tmp), "system:midi_capture_%d", i+1);
875                 PortHandle p = add_port(std::string(tmp), DataType::MIDI, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
876                 if (!p) return -1;
877                 set_latency_range (p, false, lr);
878                 _system_midi_in.push_back (static_cast<DummyMidiPort*>(p));
879                 if (_midi_mode == MidiGenerator) {
880                         static_cast<DummyMidiPort*>(p)->setup_generator (i % NUM_MIDI_EVENT_GENERATORS, _samplerate);
881                         static_cast<DummyMidiPort*>(p)->set_pretty_name (DummyMidiData::sequence_names[i % NUM_MIDI_EVENT_GENERATORS]);
882                 }
883         }
884
885         lr.min = lr.max = _systemic_output_latency;
886         for (int i = 1; i <= m_out; ++i) {
887                 char tmp[64];
888                 snprintf(tmp, sizeof(tmp), "system:midi_playback_%d", i);
889                 PortHandle p = add_port(std::string(tmp), DataType::MIDI, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
890                 if (!p) return -1;
891                 set_latency_range (p, true, lr);
892                 _system_midi_out.push_back (static_cast<DummyMidiPort*>(p));
893
894                 if (_device == _("Loopback") && _midi_mode == MidiToAudio) {
895                         std::stringstream ss;
896                         ss << "Midi2Audio";
897                         for (int apc = 0; apc < (int)_system_inputs.size(); ++apc) {
898                                 if ((apc % m_out) + 1 == i) {
899                                         ss << " >" << (apc + 1);
900                                 }
901                         }
902                         static_cast<DummyMidiPort*>(p)->set_pretty_name (ss.str());
903                 }
904         }
905         return 0;
906 }
907
908 void
909 DummyAudioBackend::unregister_ports (bool system_only)
910 {
911         _system_inputs.clear();
912         _system_outputs.clear();
913         _system_midi_in.clear();
914         _system_midi_out.clear();
915
916         for (PortIndex::iterator i = _ports.begin (); i != _ports.end ();) {
917                 PortIndex::iterator cur = i++;
918                 DummyPort* port = *cur;
919                 if (! system_only || (port->is_physical () && port->is_terminal ())) {
920                         port->disconnect_all ();
921                         _portmap.erase (port->name());
922                         delete port;
923                         _ports.erase (cur);
924                 }
925         }
926 }
927
928 int
929 DummyAudioBackend::connect (const std::string& src, const std::string& dst)
930 {
931         DummyPort* src_port = find_port (src);
932         DummyPort* dst_port = find_port (dst);
933
934         if (!src_port) {
935                 PBD::error << _("DummyBackend::connect: Invalid Source port:")
936                                 << " (" << src <<")" << endmsg;
937                 return -1;
938         }
939         if (!dst_port) {
940                 PBD::error << _("DummyBackend::connect: Invalid Destination port:")
941                         << " (" << dst <<")" << endmsg;
942                 return -1;
943         }
944         return src_port->connect (dst_port);
945 }
946
947 int
948 DummyAudioBackend::disconnect (const std::string& src, const std::string& dst)
949 {
950         DummyPort* src_port = find_port (src);
951         DummyPort* dst_port = find_port (dst);
952
953         if (!src_port || !dst_port) {
954                 PBD::error << _("DummyBackend::disconnect: Invalid Port(s)") << endmsg;
955                 return -1;
956         }
957         return src_port->disconnect (dst_port);
958 }
959
960 int
961 DummyAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
962 {
963         DummyPort* dst_port = find_port (dst);
964         if (!valid_port (src)) {
965                 PBD::error << _("DummyBackend::connect: Invalid Source Port Handle") << endmsg;
966                 return -1;
967         }
968         if (!dst_port) {
969                 PBD::error << _("DummyBackend::connect: Invalid Destination Port")
970                         << " (" << dst << ")" << endmsg;
971                 return -1;
972         }
973         return static_cast<DummyPort*>(src)->connect (dst_port);
974 }
975
976 int
977 DummyAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
978 {
979         DummyPort* dst_port = find_port (dst);
980         if (!valid_port (src) || !dst_port) {
981                 PBD::error << _("DummyBackend::disconnect: Invalid Port(s)") << endmsg;
982                 return -1;
983         }
984         return static_cast<DummyPort*>(src)->disconnect (dst_port);
985 }
986
987 int
988 DummyAudioBackend::disconnect_all (PortEngine::PortHandle port)
989 {
990         if (!valid_port (port)) {
991                 PBD::error << _("DummyBackend::disconnect_all: Invalid Port") << endmsg;
992                 return -1;
993         }
994         static_cast<DummyPort*>(port)->disconnect_all ();
995         return 0;
996 }
997
998 bool
999 DummyAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
1000 {
1001         if (!valid_port (port)) {
1002                 PBD::error << _("DummyBackend::disconnect_all: Invalid Port") << endmsg;
1003                 return false;
1004         }
1005         return static_cast<DummyPort*>(port)->is_connected ();
1006 }
1007
1008 bool
1009 DummyAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
1010 {
1011         DummyPort* dst_port = find_port (dst);
1012 #ifndef NDEBUG
1013         if (!valid_port (src) || !dst_port) {
1014                 PBD::error << _("DummyBackend::connected_to: Invalid Port") << endmsg;
1015                 return false;
1016         }
1017 #endif
1018         return static_cast<DummyPort*>(src)->is_connected (dst_port);
1019 }
1020
1021 bool
1022 DummyAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
1023 {
1024         if (!valid_port (port)) {
1025                 PBD::error << _("DummyBackend::physically_connected: Invalid Port") << endmsg;
1026                 return false;
1027         }
1028         return static_cast<DummyPort*>(port)->is_physically_connected ();
1029 }
1030
1031 int
1032 DummyAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
1033 {
1034         if (!valid_port (port)) {
1035                 PBD::error << _("DummyBackend::get_connections: Invalid Port") << endmsg;
1036                 return -1;
1037         }
1038
1039         assert (0 == names.size ());
1040
1041         const std::set<DummyPort*>& connected_ports = static_cast<DummyPort*>(port)->get_connections ();
1042
1043         for (std::set<DummyPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
1044                 names.push_back ((*i)->name ());
1045         }
1046
1047         return (int)names.size ();
1048 }
1049
1050 /* MIDI */
1051 int
1052 DummyAudioBackend::midi_event_get (
1053                 pframes_t& timestamp,
1054                 size_t& size, uint8_t** buf, void* port_buffer,
1055                 uint32_t event_index)
1056 {
1057         assert (buf && port_buffer);
1058         DummyMidiBuffer& source = * static_cast<DummyMidiBuffer*>(port_buffer);
1059         if (event_index >= source.size ()) {
1060                 return -1;
1061         }
1062         DummyMidiEvent * const event = source[event_index].get ();
1063
1064         timestamp = event->timestamp ();
1065         size = event->size ();
1066         *buf = event->data ();
1067         return 0;
1068 }
1069
1070 int
1071 DummyAudioBackend::midi_event_put (
1072                 void* port_buffer,
1073                 pframes_t timestamp,
1074                 const uint8_t* buffer, size_t size)
1075 {
1076         assert (buffer && port_buffer);
1077         DummyMidiBuffer& dst = * static_cast<DummyMidiBuffer*>(port_buffer);
1078         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
1079                 // nevermind, ::get_buffer() sorts events, but always print warning
1080                 fprintf (stderr, "DummyMidiBuffer: it's too late for this event %d > %d.\n", (pframes_t)dst.back ()->timestamp (), timestamp);
1081         }
1082         dst.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (timestamp, buffer, size)));
1083 #if 0 // DEBUG MIDI EVENTS
1084         printf("DummyAudioBackend::midi_event_put %d, %zu: ", timestamp, size);
1085         for (size_t xx = 0; xx < size; ++xx) {
1086                 printf(" %02x", buffer[xx]);
1087         }
1088         printf("\n");
1089 #endif
1090         return 0;
1091 }
1092
1093 uint32_t
1094 DummyAudioBackend::get_midi_event_count (void* port_buffer)
1095 {
1096         assert (port_buffer);
1097         return static_cast<DummyMidiBuffer*>(port_buffer)->size ();
1098 }
1099
1100 void
1101 DummyAudioBackend::midi_clear (void* port_buffer)
1102 {
1103         assert (port_buffer);
1104         DummyMidiBuffer * buf = static_cast<DummyMidiBuffer*>(port_buffer);
1105         assert (buf);
1106         buf->clear ();
1107 }
1108
1109 /* Monitoring */
1110
1111 bool
1112 DummyAudioBackend::can_monitor_input () const
1113 {
1114         return false;
1115 }
1116
1117 int
1118 DummyAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1119 {
1120         return -1;
1121 }
1122
1123 int
1124 DummyAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1125 {
1126         return -1;
1127 }
1128
1129 bool
1130 DummyAudioBackend::monitoring_input (PortEngine::PortHandle)
1131 {
1132         return false;
1133 }
1134
1135 /* Latency management */
1136
1137 void
1138 DummyAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1139 {
1140         if (!valid_port (port)) {
1141                 PBD::error << _("DummyPort::set_latency_range (): invalid port.") << endmsg;
1142         }
1143         static_cast<DummyPort*>(port)->set_latency_range (latency_range, for_playback);
1144 }
1145
1146 LatencyRange
1147 DummyAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1148 {
1149         LatencyRange r;
1150         if (!valid_port (port)) {
1151                 PBD::error << _("DummyPort::get_latency_range (): invalid port.") << endmsg;
1152                 r.min = 0;
1153                 r.max = 0;
1154                 return r;
1155         }
1156         DummyPort *p =  static_cast<DummyPort*>(port);
1157         assert(p);
1158
1159         r = p->latency_range (for_playback);
1160         if (p->is_physical() && p->is_terminal()) {
1161                 if (p->is_input() && for_playback) {
1162                         const size_t l_in = _samples_per_period * .25;
1163                         r.min += l_in;
1164                         r.max += l_in;
1165                 }
1166                 if (p->is_output() && !for_playback) {
1167                         /* with 'Loopback' there is exactly once cycle latency, divide it between In + Out; */
1168                         const size_t l_in = _samples_per_period * .25;
1169                         const size_t l_out = _samples_per_period - l_in;
1170                         r.min += l_out;
1171                         r.max += l_out;
1172                 }
1173         }
1174         return r;
1175 }
1176
1177 /* Discovering physical ports */
1178
1179 bool
1180 DummyAudioBackend::port_is_physical (PortEngine::PortHandle port) const
1181 {
1182         if (!valid_port (port)) {
1183                 PBD::error << _("DummyPort::port_is_physical (): invalid port.") << endmsg;
1184                 return false;
1185         }
1186         return static_cast<DummyPort*>(port)->is_physical ();
1187 }
1188
1189 void
1190 DummyAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1191 {
1192         for (PortIndex::iterator i = _ports.begin (); i != _ports.end (); ++i) {
1193                 DummyPort* port = *i;
1194                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1195                         port_names.push_back (port->name ());
1196                 }
1197         }
1198 }
1199
1200 void
1201 DummyAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1202 {
1203         for (PortIndex::iterator i = _ports.begin (); i != _ports.end (); ++i) {
1204                 DummyPort* port = *i;
1205                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1206                         port_names.push_back (port->name ());
1207                 }
1208         }
1209 }
1210
1211 ChanCount
1212 DummyAudioBackend::n_physical_outputs () const
1213 {
1214         int n_midi = 0;
1215         int n_audio = 0;
1216         for (PortIndex::iterator i = _ports.begin (); i != _ports.end (); ++i) {
1217                 DummyPort* port = *i;
1218                 if (port->is_output () && port->is_physical ()) {
1219                         switch (port->type ()) {
1220                                 case DataType::AUDIO: ++n_audio; break;
1221                                 case DataType::MIDI: ++n_midi; break;
1222                                 default: break;
1223                         }
1224                 }
1225         }
1226         ChanCount cc;
1227         cc.set (DataType::AUDIO, n_audio);
1228         cc.set (DataType::MIDI, n_midi);
1229         return cc;
1230 }
1231
1232 ChanCount
1233 DummyAudioBackend::n_physical_inputs () const
1234 {
1235         int n_midi = 0;
1236         int n_audio = 0;
1237         for (PortIndex::iterator i = _ports.begin (); i != _ports.end (); ++i) {
1238                 DummyPort* port = *i;
1239                 if (port->is_input () && port->is_physical ()) {
1240                         switch (port->type ()) {
1241                                 case DataType::AUDIO: ++n_audio; break;
1242                                 case DataType::MIDI: ++n_midi; break;
1243                                 default: break;
1244                         }
1245                 }
1246         }
1247         ChanCount cc;
1248         cc.set (DataType::AUDIO, n_audio);
1249         cc.set (DataType::MIDI, n_midi);
1250         return cc;
1251 }
1252
1253 /* Getting access to the data buffer for a port */
1254
1255 void*
1256 DummyAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1257 {
1258         assert (port);
1259         assert (valid_port (port));
1260         return static_cast<DummyPort*>(port)->get_buffer (nframes);
1261 }
1262
1263 /* Engine Process */
1264 void *
1265 DummyAudioBackend::main_process_thread ()
1266 {
1267         AudioEngine::thread_init_callback (this);
1268         _running = true;
1269         _processed_samples = 0;
1270
1271         manager.registration_callback();
1272         manager.graph_order_callback();
1273
1274         int64_t clock1;
1275         clock1 = -1;
1276         while (_running) {
1277
1278                 if (_freewheeling != _freewheel) {
1279                         _freewheel = _freewheeling;
1280                         engine.freewheel_callback (_freewheel);
1281                 }
1282
1283                 // re-set input buffers, generate on demand.
1284                 for (std::vector<DummyAudioPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
1285                         (*it)->next_period();
1286                 }
1287                 for (std::vector<DummyMidiPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it) {
1288                         (*it)->next_period();
1289                 }
1290
1291                 if (engine.process_callback (_samples_per_period)) {
1292                         return 0;
1293                 }
1294                 _processed_samples += _samples_per_period;
1295
1296                 if (_device == _("Loopback") && _midi_mode != MidiToAudio) {
1297                         int opn = 0;
1298                         int opc = _system_outputs.size();
1299                         for (std::vector<DummyAudioPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++opn) {
1300                                 DummyAudioPort* op = _system_outputs[(opn % opc)];
1301                                 (*it)->fill_wavetable ((const float*)op->get_buffer (_samples_per_period), _samples_per_period);
1302                         }
1303                 }
1304
1305                 if (_midi_mode == MidiLoopback) {
1306                         int opn = 0;
1307                         int opc = _system_midi_out.size();
1308                         for (std::vector<DummyMidiPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++opn) {
1309                                 DummyMidiPort* op = _system_midi_out[(opn % opc)];
1310                                 op->get_buffer(0); // mix-down
1311                                 (*it)->set_loopback (op->const_buffer());
1312                         }
1313                 }
1314                 else if (_midi_mode == MidiToAudio) {
1315                         int opn = 0;
1316                         int opc = _system_midi_out.size();
1317                         for (std::vector<DummyAudioPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++opn) {
1318                                 DummyMidiPort* op = _system_midi_out[(opn % opc)];
1319                                 op->get_buffer(0); // mix-down
1320                                 (*it)->midi_to_wavetable (op->const_buffer(), _samples_per_period);
1321                         }
1322                 }
1323
1324                 if (!_freewheel) {
1325                         _dsp_load_calc.set_start_timestamp_us (clock1);
1326                         _dsp_load_calc.set_stop_timestamp_us (_x_get_monotonic_usec());
1327                         _dsp_load = _dsp_load_calc.get_dsp_load_unbound ();
1328
1329                         const int64_t elapsed_time = _dsp_load_calc.elapsed_time_us ();
1330                         const int64_t nominal_time = _dsp_load_calc.get_max_time_us ();
1331                         if (elapsed_time < nominal_time) {
1332                                 const int64_t sleepy = _speedup * (nominal_time - elapsed_time);
1333                                 Glib::usleep (std::max ((int64_t) 100, sleepy));
1334                         } else {
1335                                 Glib::usleep (100); // don't hog cpu
1336                         }
1337                 } else {
1338                         _dsp_load = 1.0f;
1339                         Glib::usleep (100); // don't hog cpu
1340                 }
1341
1342                 /* beginning of next cycle */
1343                 clock1 = _x_get_monotonic_usec();
1344
1345                 bool connections_changed = false;
1346                 bool ports_changed = false;
1347                 if (!pthread_mutex_trylock (&_port_callback_mutex)) {
1348                         if (_port_change_flag) {
1349                                 ports_changed = true;
1350                                 _port_change_flag = false;
1351                         }
1352                         if (!_port_connection_queue.empty ()) {
1353                                 connections_changed = true;
1354                         }
1355                         while (!_port_connection_queue.empty ()) {
1356                                 PortConnectData *c = _port_connection_queue.back ();
1357                                 manager.connect_callback (c->a, c->b, c->c);
1358                                 _port_connection_queue.pop_back ();
1359                                 delete c;
1360                         }
1361                         pthread_mutex_unlock (&_port_callback_mutex);
1362                 }
1363                 if (ports_changed) {
1364                         manager.registration_callback();
1365                 }
1366                 if (connections_changed) {
1367                         manager.graph_order_callback();
1368                 }
1369                 if (connections_changed || ports_changed) {
1370                         engine.latency_callback(false);
1371                         engine.latency_callback(true);
1372                 }
1373
1374         }
1375         _running = false;
1376         return 0;
1377 }
1378
1379
1380 /******************************************************************************/
1381
1382 static boost::shared_ptr<DummyAudioBackend> _instance;
1383
1384 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
1385 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
1386 static int deinstantiate ();
1387 static bool already_configured ();
1388 static bool available ();
1389
1390 static ARDOUR::AudioBackendInfo _descriptor = {
1391         _("None (Dummy)"),
1392         instantiate,
1393         deinstantiate,
1394         backend_factory,
1395         already_configured,
1396         available
1397 };
1398
1399 static boost::shared_ptr<AudioBackend>
1400 backend_factory (AudioEngine& e)
1401 {
1402         if (!_instance) {
1403                 _instance.reset (new DummyAudioBackend (e, _descriptor));
1404         }
1405         return _instance;
1406 }
1407
1408 static int
1409 instantiate (const std::string& arg1, const std::string& /* arg2 */)
1410 {
1411         s_instance_name = arg1;
1412         return 0;
1413 }
1414
1415 static int
1416 deinstantiate ()
1417 {
1418         _instance.reset ();
1419         return 0;
1420 }
1421
1422 static bool
1423 already_configured ()
1424 {
1425         // special-case: unit-tests require backend to be pre-configured.
1426         if (s_instance_name == "Unit-Test") {
1427                 return true;
1428         }
1429         return false;
1430 }
1431
1432 static bool
1433 available ()
1434 {
1435         return true;
1436 }
1437
1438 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
1439 {
1440         return &_descriptor;
1441 }
1442
1443
1444 /******************************************************************************/
1445 DummyPort::DummyPort (DummyAudioBackend &b, const std::string& name, PortFlags flags)
1446         : _dummy_backend (b)
1447         , _name  (name)
1448         , _flags (flags)
1449         , _rseed (0)
1450         , _gen_cycle (false)
1451 {
1452         _capture_latency_range.min = 0;
1453         _capture_latency_range.max = 0;
1454         _playback_latency_range.min = 0;
1455         _playback_latency_range.max = 0;
1456         _dummy_backend.port_connect_add_remove_callback();
1457 }
1458
1459 DummyPort::~DummyPort () {
1460         disconnect_all ();
1461         _dummy_backend.port_connect_add_remove_callback();
1462 }
1463
1464
1465 int DummyPort::connect (DummyPort *port)
1466 {
1467         if (!port) {
1468                 PBD::error << _("DummyPort::connect (): invalid (null) port") << endmsg;
1469                 return -1;
1470         }
1471
1472         if (type () != port->type ()) {
1473                 PBD::error << _("DummyPort::connect (): wrong port-type") << endmsg;
1474                 return -1;
1475         }
1476
1477         if (is_output () && port->is_output ()) {
1478                 PBD::error << _("DummyPort::connect (): cannot inter-connect output ports.") << endmsg;
1479                 return -1;
1480         }
1481
1482         if (is_input () && port->is_input ()) {
1483                 PBD::error << _("DummyPort::connect (): cannot inter-connect input ports.") << endmsg;
1484                 return -1;
1485         }
1486
1487         if (this == port) {
1488                 PBD::error << _("DummyPort::connect (): cannot self-connect ports.") << endmsg;
1489                 return -1;
1490         }
1491
1492         if (is_connected (port)) {
1493 #if 0 // don't bother to warn about this for now. just ignore it
1494                 PBD::error << _("DummyPort::connect (): ports are already connected:")
1495                         << " (" << name () << ") -> (" << port->name () << ")"
1496                         << endmsg;
1497 #endif
1498                 return -1;
1499         }
1500
1501         _connect (port, true);
1502         return 0;
1503 }
1504
1505
1506 void DummyPort::_connect (DummyPort *port, bool callback)
1507 {
1508         _connections.insert (port);
1509         if (callback) {
1510                 port->_connect (this, false);
1511                 _dummy_backend.port_connect_callback (name(),  port->name(), true);
1512         }
1513 }
1514
1515 int DummyPort::disconnect (DummyPort *port)
1516 {
1517         if (!port) {
1518                 PBD::error << _("DummyPort::disconnect (): invalid (null) port") << endmsg;
1519                 return -1;
1520         }
1521
1522         if (!is_connected (port)) {
1523                 PBD::error << _("DummyPort::disconnect (): ports are not connected:")
1524                         << " (" << name () << ") -> (" << port->name () << ")"
1525                         << endmsg;
1526                 return -1;
1527         }
1528         _disconnect (port, true);
1529         return 0;
1530 }
1531
1532 void DummyPort::_disconnect (DummyPort *port, bool callback)
1533 {
1534         std::set<DummyPort*>::iterator it = _connections.find (port);
1535         assert (it != _connections.end ());
1536         _connections.erase (it);
1537         if (callback) {
1538                 port->_disconnect (this, false);
1539                 _dummy_backend.port_connect_callback (name(),  port->name(), false);
1540         }
1541 }
1542
1543
1544 void DummyPort::disconnect_all ()
1545 {
1546         while (!_connections.empty ()) {
1547                 std::set<DummyPort*>::iterator it = _connections.begin ();
1548                 (*it)->_disconnect (this, false);
1549                 _dummy_backend.port_connect_callback (name(), (*it)->name(), false);
1550                 _connections.erase (it);
1551         }
1552 }
1553
1554 bool
1555 DummyPort::is_connected (const DummyPort *port) const
1556 {
1557         return _connections.find (const_cast<DummyPort *>(port)) != _connections.end ();
1558 }
1559
1560 bool DummyPort::is_physically_connected () const
1561 {
1562         for (std::set<DummyPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
1563                 if ((*it)->is_physical ()) {
1564                         return true;
1565                 }
1566         }
1567         return false;
1568 }
1569
1570 void DummyPort::setup_random_number_generator ()
1571 {
1572 #ifdef PLATFORM_WINDOWS
1573         LARGE_INTEGER Count;
1574         if (QueryPerformanceCounter (&Count)) {
1575                 _rseed = Count.QuadPart % UINT_MAX;
1576         } else
1577 #endif
1578         {
1579         _rseed = g_get_monotonic_time() % UINT_MAX;
1580         }
1581         _rseed = (_rseed + (uint64_t)this) % UINT_MAX;
1582         if (_rseed == 0) _rseed = 1;
1583 }
1584
1585 inline uint32_t
1586 DummyPort::randi ()
1587 {
1588         // 31bit Park-Miller-Carta Pseudo-Random Number Generator
1589         // http://www.firstpr.com.au/dsp/rand31/
1590         uint32_t hi, lo;
1591         lo = 16807 * (_rseed & 0xffff);
1592         hi = 16807 * (_rseed >> 16);
1593
1594         lo += (hi & 0x7fff) << 16;
1595         lo += hi >> 15;
1596 #if 1
1597         lo = (lo & 0x7fffffff) + (lo >> 31);
1598 #else
1599         if (lo > 0x7fffffff) { lo -= 0x7fffffff; }
1600 #endif
1601         return (_rseed = lo);
1602 }
1603
1604 inline float
1605 DummyPort::randf ()
1606 {
1607         return (randi() / 1073741824.f) - 1.f;
1608 }
1609
1610 /******************************************************************************/
1611
1612 DummyAudioPort::DummyAudioPort (DummyAudioBackend &b, const std::string& name, PortFlags flags)
1613         : DummyPort (b, name, flags)
1614         , _gen_type (Silence)
1615         , _b0 (0)
1616         , _b1 (0)
1617         , _b2 (0)
1618         , _b3 (0)
1619         , _b4 (0)
1620         , _b5 (0)
1621         , _b6 (0)
1622         , _wavetable (0)
1623         , _gen_period (0)
1624         , _gen_offset (0)
1625         , _gen_perio2 (0)
1626         , _gen_count2 (0)
1627         , _pass (false)
1628         , _rn1 (0)
1629 {
1630         memset (_buffer, 0, sizeof (_buffer));
1631 }
1632
1633 DummyAudioPort::~DummyAudioPort () {
1634         free(_wavetable);
1635         _wavetable = 0;
1636 }
1637
1638 void DummyAudioPort::setup_generator (GeneratorType const g, float const samplerate)
1639 {
1640         DummyPort::setup_random_number_generator();
1641         _gen_type = g;
1642
1643         switch (_gen_type) {
1644                 case PinkNoise:
1645                 case PonyNoise:
1646                 case UniformWhiteNoise:
1647                 case GaussianWhiteNoise:
1648                 case Silence:
1649                         break;
1650                 case KronekerDelta:
1651                         _gen_period = (5 + randi() % (int)(samplerate / 20.f));
1652                         break;
1653                 case SquareWave:
1654                         _gen_period = (5 + randi() % (int)(samplerate / 20.f)) & ~1;
1655                         break;
1656                 case SineWave:
1657                         _gen_period = 5 + randi() % (int)(samplerate / 20.f);
1658                         _wavetable = (Sample*) malloc (_gen_period * sizeof(Sample));
1659                         for (uint32_t i = 0 ; i < _gen_period; ++i) {
1660                                 _wavetable[i] = .12589f * sinf(2.0f * M_PI * (float)i / (float)_gen_period); // -18dBFS
1661                         }
1662                         break;
1663                 case SquareSweep:
1664                 case SquareSweepSwell:
1665                 case SineSweep:
1666                 case SineSweepSwell:
1667                         {
1668                                 _gen_period = 5 * samplerate + randi() % (int)(samplerate * 10.f);
1669                                 _gen_period &= ~1;
1670                                 _gen_perio2 = 1 | (int)ceilf (_gen_period * .89f); // Volume Swell period
1671                                 const double f_min = 20.;
1672                                 const double f_max = samplerate * .5;
1673                                 const double g_p2 = _gen_period * .5;
1674 #ifdef LINEAR_SWEEP
1675                                 const double b = (f_max - f_min) / (2. * samplerate * g_p2);
1676                                 const double a = f_min / samplerate;
1677 #else
1678                                 const double b = log (f_max / f_min) / g_p2;
1679                                 const double a = f_min / (b * samplerate);
1680 #endif
1681                                 const uint32_t g_p2i = rint(g_p2);
1682                                 _wavetable = (Sample*) malloc (_gen_period * sizeof(Sample));
1683                                 for (uint32_t i = 0 ; i < g_p2i; ++i) {
1684 #ifdef LINEAR_SWEEP
1685                                         const double phase = i * (a + b * i);
1686 #else
1687                                         const double phase = a * exp (b * i) - a;
1688 #endif
1689                                         _wavetable[i] = (float)sin (2. * M_PI * (phase - floor (phase)));
1690                                 }
1691                                 for (uint32_t i = g_p2i; i < _gen_period; ++i) {
1692                                         const uint32_t j = _gen_period - i;
1693 #ifdef LINEAR_SWEEP
1694                                         const double phase = j * (a + b * j);
1695 #else
1696                                         const double phase = a * exp (b * j) - a;
1697 #endif
1698                                         _wavetable[i] = -(float)sin (2. * M_PI * (phase - floor (phase)));
1699                                 }
1700                                 if (_gen_type == SquareSweep) {
1701                                         for (uint32_t i = 0 ; i < _gen_period; ++i) {
1702                                                 _wavetable[i] = _wavetable[i] < 0 ? -.40709f : .40709f;
1703                                         }
1704                                 }
1705                                 else if (_gen_type == SquareSweepSwell) {
1706                                         for (uint32_t i = 0 ; i < _gen_period; ++i) {
1707                                                 _wavetable[i] = _wavetable[i] < 0 ? -1 : 1;
1708                                         }
1709                                 }
1710                         }
1711                         break;
1712                 case Loopback:
1713                         _wavetable = (Sample*) malloc (DummyAudioBackend::max_buffer_size() * sizeof(Sample));
1714                         break;
1715         }
1716 }
1717
1718 void DummyAudioPort::midi_to_wavetable (DummyMidiBuffer const * const src, size_t n_samples)
1719 {
1720         memset(_wavetable, 0, n_samples * sizeof(float));
1721         /* generate an audio spike for every midi message
1722          * to verify layency-compensation alignment
1723          * (here: midi-out playback-latency + audio-in capture-latency)
1724          */
1725         for (DummyMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
1726                 const pframes_t t = (*it)->timestamp();
1727                 assert(t < n_samples);
1728                 // somewhat arbitrary mapping for quick visual feedback
1729                 float v = -.5f;
1730                 if ((*it)->size() == 3) {
1731                         const unsigned char *d = (*it)->const_data();
1732                         if ((d[0] & 0xf0) == 0x90) { // note on
1733                                 v = .25f + d[2] / 512.f;
1734                         }
1735                         else if ((d[0] & 0xf0) == 0x80) { // note off
1736                                 v = .3f - d[2] / 640.f;
1737                         }
1738                         else if ((d[0] & 0xf0) == 0xb0) { // CC
1739                                 v = -.1f - d[2] / 256.f;
1740                         }
1741                 }
1742                 _wavetable[t] += v;
1743         }
1744 }
1745
1746 float DummyAudioPort::grandf ()
1747 {
1748         // Gaussian White Noise
1749         // http://www.musicdsp.org/archive.php?classid=0#109
1750         float x1, x2, r;
1751
1752         if (_pass) {
1753                 _pass = false;
1754                 return _rn1;
1755         }
1756
1757         do {
1758                 x1 = randf ();
1759                 x2 = randf ();
1760                 r = x1 * x1 + x2 * x2;
1761         } while ((r >= 1.0f) || (r < 1e-22f));
1762
1763         r = sqrtf (-2.f * logf (r) / r);
1764
1765         _pass = true;
1766         _rn1 = r * x2;
1767         return r * x1;
1768 }
1769
1770 void DummyAudioPort::generate (const pframes_t n_samples)
1771 {
1772         Glib::Threads::Mutex::Lock lm (generator_lock);
1773         if (_gen_cycle) {
1774                 return;
1775         }
1776
1777         switch (_gen_type) {
1778                 case Silence:
1779                         memset (_buffer, 0, n_samples * sizeof (Sample));
1780                         break;
1781                 case SquareWave:
1782                         assert(_gen_period > 0);
1783                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1784                                 if (_gen_offset < _gen_period * .5f) {
1785                                         _buffer[i] =  .40709f; // -6dBFS
1786                                 } else {
1787                                         _buffer[i] = -.40709f;
1788                                 }
1789                                 _gen_offset = (_gen_offset + 1) % _gen_period;
1790                         }
1791                         break;
1792                 case KronekerDelta:
1793                         assert(_gen_period > 0);
1794                         memset (_buffer, 0, n_samples * sizeof (Sample));
1795                         for (pframes_t i = 0; i < n_samples; ++i) {
1796                                 if (_gen_offset == 0) {
1797                                         _buffer[i] = 1.0f;
1798                                 }
1799                                 _gen_offset = (_gen_offset + 1) % _gen_period;
1800                         }
1801                         break;
1802                 case SineSweepSwell:
1803                 case SquareSweepSwell:
1804                         assert(_wavetable && _gen_period > 0);
1805                         {
1806                                 const float vols = 2.f / (float)_gen_perio2;
1807                                 for (pframes_t i = 0; i < n_samples; ++i) {
1808                                         const float g = fabsf (_gen_count2 * vols - 1.f);
1809                                         _buffer[i] = g * _wavetable[_gen_offset];
1810                                         _gen_offset = (_gen_offset + 1) % _gen_period;
1811                                         _gen_count2 = (_gen_count2 + 1) % _gen_perio2;
1812                                 }
1813                         }
1814                         break;
1815                 case Loopback:
1816                         _gen_period = n_samples; // XXX DummyBackend::_samples_per_period;
1817                 case SineWave:
1818                 case SineSweep:
1819                 case SquareSweep:
1820                         assert(_wavetable && _gen_period > 0);
1821                         {
1822                                 pframes_t written = 0;
1823                                 while (written < n_samples) {
1824                                         const uint32_t remain = n_samples - written;
1825                                         const uint32_t to_copy = std::min(remain, _gen_period - _gen_offset);
1826                                         memcpy((void*)&_buffer[written],
1827                                                         (void*)&_wavetable[_gen_offset],
1828                                                         to_copy * sizeof(Sample));
1829                                         written += to_copy;
1830                                         _gen_offset = (_gen_offset + to_copy) % _gen_period;
1831                                 }
1832                         }
1833                         break;
1834                 case UniformWhiteNoise:
1835                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1836                                 _buffer[i] = .158489f * randf();
1837                         }
1838                         break;
1839                 case GaussianWhiteNoise:
1840                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1841                                 _buffer[i] = .089125f * grandf();
1842                         }
1843                         break;
1844                 case PinkNoise:
1845                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1846                                 // Paul Kellet's refined method
1847                                 // http://www.musicdsp.org/files/pink.txt
1848                                 // NB. If 'white' consists of uniform random numbers,
1849                                 // the pink noise will have an almost gaussian distribution.
1850                                 const float white = .0498f * randf ();
1851                                 _b0 = .99886f * _b0 + white * .0555179f;
1852                                 _b1 = .99332f * _b1 + white * .0750759f;
1853                                 _b2 = .96900f * _b2 + white * .1538520f;
1854                                 _b3 = .86650f * _b3 + white * .3104856f;
1855                                 _b4 = .55000f * _b4 + white * .5329522f;
1856                                 _b5 = -.7616f * _b5 - white * .0168980f;
1857                                 _buffer[i] = _b0 + _b1 + _b2 + _b3 + _b4 + _b5 + _b6 + white * 0.5362f;
1858                                 _b6 = white * 0.115926f;
1859                         }
1860                         break;
1861                 case PonyNoise:
1862                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1863                                 const float white = 0.0498f * randf ();
1864                                 // Paul Kellet's economy method
1865                                 // http://www.musicdsp.org/files/pink.txt
1866                                 _b0 = 0.99765f * _b0 + white * 0.0990460f;
1867                                 _b1 = 0.96300f * _b1 + white * 0.2965164f;
1868                                 _b2 = 0.57000f * _b2 + white * 1.0526913f;
1869                                 _buffer[i] = _b0 + _b1 + _b2 + white * 0.1848f;
1870                         }
1871                         break;
1872         }
1873         _gen_cycle = true;
1874 }
1875
1876 void* DummyAudioPort::get_buffer (pframes_t n_samples)
1877 {
1878         if (is_input ()) {
1879                 const std::set<DummyPort *>& connections = get_connections ();
1880                 std::set<DummyPort*>::const_iterator it = connections.begin ();
1881                 if (it == connections.end ()) {
1882                         memset (_buffer, 0, n_samples * sizeof (Sample));
1883                 } else {
1884                         DummyAudioPort * source = static_cast<DummyAudioPort*>(*it);
1885                         assert (source && source->is_output ());
1886                         if (source->is_physical() && source->is_terminal()) {
1887                                 source->get_buffer(n_samples); // generate signal.
1888                         }
1889                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
1890                         while (++it != connections.end ()) {
1891                                 source = static_cast<DummyAudioPort*>(*it);
1892                                 assert (source && source->is_output ());
1893                                 Sample* dst = buffer ();
1894                                 if (source->is_physical() && source->is_terminal()) {
1895                                         source->get_buffer(n_samples); // generate signal.
1896                                 }
1897                                 const Sample* src = source->const_buffer ();
1898                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
1899                                         *dst += *src;
1900                                 }
1901                         }
1902                 }
1903         } else if (is_output () && is_physical () && is_terminal()) {
1904                 if (!_gen_cycle) {
1905                         generate(n_samples);
1906                 }
1907         }
1908         return _buffer;
1909 }
1910
1911
1912 DummyMidiPort::DummyMidiPort (DummyAudioBackend &b, const std::string& name, PortFlags flags)
1913         : DummyPort (b, name, flags)
1914         , _midi_seq_spb (0)
1915         , _midi_seq_time (0)
1916         , _midi_seq_pos (0)
1917 {
1918         _buffer.clear ();
1919         _loopback.clear ();
1920 }
1921
1922 DummyMidiPort::~DummyMidiPort () {
1923         _buffer.clear ();
1924         _loopback.clear ();
1925 }
1926
1927 struct MidiEventSorter {
1928         bool operator() (const boost::shared_ptr<DummyMidiEvent>& a, const boost::shared_ptr<DummyMidiEvent>& b) {
1929                 return *a < *b;
1930         }
1931 };
1932
1933 void DummyMidiPort::set_loopback (DummyMidiBuffer const * const src)
1934 {
1935         _loopback.clear ();
1936         for (DummyMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
1937                 _loopback.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (**it)));
1938         }
1939 }
1940
1941 void DummyMidiPort::setup_generator (int seq_id, const float sr)
1942 {
1943         DummyPort::setup_random_number_generator();
1944         _midi_seq_dat = DummyMidiData::sequences[seq_id % NUM_MIDI_EVENT_GENERATORS];
1945         _midi_seq_spb = sr * .5f; // 120 BPM, beat_time 1.0 per beat.
1946         _midi_seq_pos = 0;
1947         _midi_seq_time = 0;
1948 }
1949
1950 void DummyMidiPort::midi_generate (const pframes_t n_samples)
1951 {
1952         Glib::Threads::Mutex::Lock lm (generator_lock);
1953         if (_gen_cycle) {
1954                 return;
1955         }
1956
1957         _buffer.clear ();
1958         _gen_cycle = true;
1959
1960         if (_midi_seq_spb == 0 || !_midi_seq_dat) {
1961                 for (DummyMidiBuffer::const_iterator it = _loopback.begin (); it != _loopback.end (); ++it) {
1962                         _buffer.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (**it)));
1963                 }
1964                 return;
1965         }
1966
1967         while (1) {
1968                 const int32_t ev_beat_time = _midi_seq_dat[_midi_seq_pos].beat_time * _midi_seq_spb - _midi_seq_time;
1969                 if (ev_beat_time < 0) {
1970                         break;
1971                 }
1972                 if ((pframes_t) ev_beat_time >= n_samples) {
1973                         break;
1974                 }
1975                 _buffer.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (
1976                                                 ev_beat_time,
1977                                                 _midi_seq_dat[_midi_seq_pos].event,
1978                                                 _midi_seq_dat[_midi_seq_pos].size
1979                                                 )));
1980                 ++_midi_seq_pos;
1981
1982                 if (_midi_seq_dat[_midi_seq_pos].event[0] == 0xff && _midi_seq_dat[_midi_seq_pos].event[1] == 0xff) {
1983                         _midi_seq_time -= _midi_seq_dat[_midi_seq_pos].beat_time * _midi_seq_spb;
1984                         _midi_seq_pos = 0;
1985                 }
1986         }
1987         _midi_seq_time += n_samples;
1988 }
1989
1990
1991 void* DummyMidiPort::get_buffer (pframes_t n_samples)
1992 {
1993         if (is_input ()) {
1994                 _buffer.clear ();
1995                 const std::set<DummyPort*>& connections = get_connections ();
1996                 for (std::set<DummyPort*>::const_iterator i = connections.begin ();
1997                                 i != connections.end ();
1998                                 ++i) {
1999                         DummyMidiPort * source = static_cast<DummyMidiPort*>(*i);
2000                         if (source->is_physical() && source->is_terminal()) {
2001                                 source->get_buffer(n_samples); // generate signal.
2002                         }
2003                         const DummyMidiBuffer *src = source->const_buffer ();
2004                         for (DummyMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
2005                                 _buffer.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (**it)));
2006                         }
2007                 }
2008                 std::sort (_buffer.begin (), _buffer.end (), MidiEventSorter());
2009         } else if (is_output () && is_physical () && is_terminal()) {
2010                 if (!_gen_cycle) {
2011                         midi_generate(n_samples);
2012                 }
2013         }
2014         return &_buffer;
2015 }
2016
2017 DummyMidiEvent::DummyMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
2018         : _size (size)
2019         , _timestamp (timestamp)
2020         , _data (0)
2021 {
2022         if (size > 0) {
2023                 _data = (uint8_t*) malloc (size);
2024                 memcpy (_data, data, size);
2025         }
2026 }
2027
2028 DummyMidiEvent::DummyMidiEvent (const DummyMidiEvent& other)
2029         : _size (other.size ())
2030         , _timestamp (other.timestamp ())
2031         , _data (0)
2032 {
2033         if (other.size () && other.const_data ()) {
2034                 _data = (uint8_t*) malloc (other.size ());
2035                 memcpy (_data, other.const_data (), other.size ());
2036         }
2037 };
2038
2039 DummyMidiEvent::~DummyMidiEvent () {
2040         free (_data);
2041 };