2245f17e6cd92cea3474f9f521a36cd6c45d0538
[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 -1;
428         }
429
430         if (_ports.size()) {
431                 PBD::warning << _("DummyAudioBackend: recovering from unclean shutdown, port registry is not empty.") << endmsg;
432                 for (std::vector<DummyPort*>::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         }
441
442         if (register_system_ports()) {
443                 PBD::error << _("DummyAudioBackend: failed to register system ports.") << endmsg;
444                 return -1;
445         }
446
447         engine.sample_rate_change (_samplerate);
448         engine.buffer_size_change (_samples_per_period);
449
450         _dsp_load_calc.set_max_time (_samplerate, _samples_per_period);
451
452         if (engine.reestablish_ports ()) {
453                 PBD::error << _("DummyAudioBackend: Could not re-establish ports.") << endmsg;
454                 stop ();
455                 return -1;
456         }
457
458         engine.reconnect_ports ();
459         _port_change_flag = false;
460
461         if (pthread_create (&_main_thread, NULL, pthread_process, this)) {
462                 PBD::error << _("DummyAudioBackend: cannot start.") << endmsg;
463         }
464
465         int timeout = 5000;
466         while (!_running && --timeout > 0) { Glib::usleep (1000); }
467
468         if (timeout == 0 || !_running) {
469                 PBD::error << _("DummyAudioBackend: failed to start process thread.") << endmsg;
470                 return -1;
471         }
472
473         return 0;
474 }
475
476 int
477 DummyAudioBackend::stop ()
478 {
479         void *status;
480         if (!_running) {
481                 return 0;
482         }
483
484         _running = false;
485         if (pthread_join (_main_thread, &status)) {
486                 PBD::error << _("DummyAudioBackend: failed to terminate.") << endmsg;
487                 return -1;
488         }
489         unregister_ports();
490         return 0;
491 }
492
493 int
494 DummyAudioBackend::freewheel (bool onoff)
495 {
496         _freewheeling = onoff;
497         return 0;
498 }
499
500 float
501 DummyAudioBackend::dsp_load () const
502 {
503         return 100.f * _dsp_load;
504 }
505
506 size_t
507 DummyAudioBackend::raw_buffer_size (DataType t)
508 {
509         switch (t) {
510                 case DataType::AUDIO:
511                         return _samples_per_period * sizeof(Sample);
512                 case DataType::MIDI:
513                         return _max_buffer_size; // XXX not really limited
514         }
515         return 0;
516 }
517
518 /* Process time */
519 framepos_t
520 DummyAudioBackend::sample_time ()
521 {
522         return _processed_samples;
523 }
524
525 framepos_t
526 DummyAudioBackend::sample_time_at_cycle_start ()
527 {
528         return _processed_samples;
529 }
530
531 pframes_t
532 DummyAudioBackend::samples_since_cycle_start ()
533 {
534         return 0;
535 }
536
537
538 void *
539 DummyAudioBackend::dummy_process_thread (void *arg)
540 {
541         ThreadData* td = reinterpret_cast<ThreadData*> (arg);
542         boost::function<void ()> f = td->f;
543         delete td;
544         f ();
545         return 0;
546 }
547
548 int
549 DummyAudioBackend::create_process_thread (boost::function<void()> func)
550 {
551         pthread_t thread_id;
552         pthread_attr_t attr;
553         size_t stacksize = 100000;
554
555         pthread_attr_init (&attr);
556         pthread_attr_setstacksize (&attr, stacksize);
557         ThreadData* td = new ThreadData (this, func, stacksize);
558
559         if (pthread_create (&thread_id, &attr, dummy_process_thread, td)) {
560                 PBD::error << _("AudioEngine: cannot create process thread.") << endmsg;
561                 pthread_attr_destroy (&attr);
562                 return -1;
563         }
564         pthread_attr_destroy (&attr);
565
566         _threads.push_back (thread_id);
567         return 0;
568 }
569
570 int
571 DummyAudioBackend::join_process_threads ()
572 {
573         int rv = 0;
574
575         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
576         {
577                 void *status;
578                 if (pthread_join (*i, &status)) {
579                         PBD::error << _("AudioEngine: cannot terminate process thread.") << endmsg;
580                         rv -= 1;
581                 }
582         }
583         _threads.clear ();
584         return rv;
585 }
586
587 bool
588 DummyAudioBackend::in_process_thread ()
589 {
590         if (pthread_equal (_main_thread, pthread_self()) != 0) {
591                 return true;
592         }
593
594         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
595         {
596                 if (pthread_equal (*i, pthread_self ()) != 0) {
597                         return true;
598                 }
599         }
600         return false;
601 }
602
603 uint32_t
604 DummyAudioBackend::process_thread_count ()
605 {
606         return _threads.size ();
607 }
608
609 void
610 DummyAudioBackend::update_latencies ()
611 {
612         // trigger latency callback in RT thread (locked graph)
613         port_connect_add_remove_callback();
614 }
615
616 /* PORTENGINE API */
617
618 void*
619 DummyAudioBackend::private_handle () const
620 {
621         return NULL;
622 }
623
624 const std::string&
625 DummyAudioBackend::my_name () const
626 {
627         return _instance_name;
628 }
629
630 bool
631 DummyAudioBackend::available () const
632 {
633         return true;
634 }
635
636 uint32_t
637 DummyAudioBackend::port_name_size () const
638 {
639         return 256;
640 }
641
642 int
643 DummyAudioBackend::set_port_name (PortEngine::PortHandle port, const std::string& name)
644 {
645         if (!valid_port (port)) {
646                 PBD::error << _("DummyBackend::set_port_name: Invalid Port(s)") << endmsg;
647                 return -1;
648         }
649         return static_cast<DummyPort*>(port)->set_name (_instance_name + ":" + name);
650 }
651
652 std::string
653 DummyAudioBackend::get_port_name (PortEngine::PortHandle port) const
654 {
655         if (!valid_port (port)) {
656                 PBD::error << _("DummyBackend::get_port_name: Invalid Port(s)") << endmsg;
657                 return std::string ();
658         }
659         return static_cast<DummyPort*>(port)->name ();
660 }
661
662 PortEngine::PortHandle
663 DummyAudioBackend::get_port_by_name (const std::string& name) const
664 {
665         PortHandle port = (PortHandle) find_port (name);
666         return port;
667 }
668
669 int
670 DummyAudioBackend::get_ports (
671                 const std::string& port_name_pattern,
672                 DataType type, PortFlags flags,
673                 std::vector<std::string>& port_names) const
674 {
675         int rv = 0;
676         regex_t port_regex;
677         bool use_regexp = false;
678         if (port_name_pattern.size () > 0) {
679                 if (!regcomp (&port_regex, port_name_pattern.c_str (), REG_EXTENDED|REG_NOSUB)) {
680                         use_regexp = true;
681                 }
682         }
683         for (size_t i = 0; i < _ports.size (); ++i) {
684                 DummyPort* port = _ports[i];
685                 if ((port->type () == type) && flags == (port->flags () & flags)) {
686                         if (!use_regexp || !regexec (&port_regex, port->name ().c_str (), 0, NULL, 0)) {
687                                 port_names.push_back (port->name ());
688                                 ++rv;
689                         }
690                 }
691         }
692         if (use_regexp) {
693                 regfree (&port_regex);
694         }
695         return rv;
696 }
697
698 DataType
699 DummyAudioBackend::port_data_type (PortEngine::PortHandle port) const
700 {
701         if (!valid_port (port)) {
702                 return DataType::NIL;
703         }
704         return static_cast<DummyPort*>(port)->type ();
705 }
706
707 PortEngine::PortHandle
708 DummyAudioBackend::register_port (
709                 const std::string& name,
710                 ARDOUR::DataType type,
711                 ARDOUR::PortFlags flags)
712 {
713         if (name.size () == 0) { return 0; }
714         if (flags & IsPhysical) { return 0; }
715         if (!_running) {
716                 PBD::info << _("DummyBackend::register_port: Engine is not running.") << endmsg;
717         }
718         return add_port (_instance_name + ":" + name, type, flags);
719 }
720
721 PortEngine::PortHandle
722 DummyAudioBackend::add_port (
723                 const std::string& name,
724                 ARDOUR::DataType type,
725                 ARDOUR::PortFlags flags)
726 {
727         assert(name.size ());
728         if (find_port (name)) {
729                 PBD::error << _("DummyBackend::register_port: Port already exists:")
730                                 << " (" << name << ")" << endmsg;
731                 return 0;
732         }
733         DummyPort* port = NULL;
734         switch (type) {
735                 case DataType::AUDIO:
736                         port = new DummyAudioPort (*this, name, flags);
737                         break;
738                 case DataType::MIDI:
739                         port = new DummyMidiPort (*this, name, flags);
740                         break;
741                 default:
742                         PBD::error << _("DummyBackend::register_port: Invalid Data Type.") << endmsg;
743                         return 0;
744         }
745
746         _ports.push_back (port);
747
748         return port;
749 }
750
751 void
752 DummyAudioBackend::unregister_port (PortEngine::PortHandle port_handle)
753 {
754         if (!_running) {
755                 PBD::info << _("DummyBackend::unregister_port: Engine is not running.") << endmsg;
756                 assert (!valid_port (port_handle));
757                 return;
758         }
759         DummyPort* port = static_cast<DummyPort*>(port_handle);
760         std::vector<DummyPort*>::iterator i = std::find (_ports.begin (), _ports.end (), static_cast<DummyPort*>(port_handle));
761         if (i == _ports.end ()) {
762                 PBD::error << _("DummyBackend::unregister_port: Failed to find port") << endmsg;
763                 return;
764         }
765         disconnect_all(port_handle);
766         _ports.erase (i);
767         delete port;
768 }
769
770 int
771 DummyAudioBackend::register_system_ports()
772 {
773         LatencyRange lr;
774         enum DummyAudioPort::GeneratorType gt;
775         if (_device == _("Uniform White Noise")) {
776                 gt = DummyAudioPort::UniformWhiteNoise;
777         } else if (_device == _("Gaussian White Noise")) {
778                 gt = DummyAudioPort::GaussianWhiteNoise;
779         } else if (_device == _("Pink Noise")) {
780                 gt = DummyAudioPort::PinkNoise;
781         } else if (_device == _("Pink Noise (low CPU)")) {
782                 gt = DummyAudioPort::PonyNoise;
783         } else if (_device == _("Sine Wave")) {
784                 gt = DummyAudioPort::SineWave;
785         } else if (_device == _("Square Wave")) {
786                 gt = DummyAudioPort::SquareWave;
787         } else if (_device == _("Impulses")) {
788                 gt = DummyAudioPort::KronekerDelta;
789         } else if (_device == _("Sine Sweep")) {
790                 gt = DummyAudioPort::SineSweep;
791         } else if (_device == _("Sine Sweep Swell")) {
792                 gt = DummyAudioPort::SineSweepSwell;
793         } else if (_device == _("Square Sweep")) {
794                 gt = DummyAudioPort::SquareSweep;
795         } else if (_device == _("Square Sweep Swell")) {
796                 gt = DummyAudioPort::SquareSweepSwell;
797         } else if (_device == _("Loopback")) {
798                 gt = DummyAudioPort::Loopback;
799         } else {
800                 gt = DummyAudioPort::Silence;
801         }
802
803         if (_midi_mode == MidiToAudio) {
804                 gt = DummyAudioPort::Loopback;
805         }
806
807         const int a_ins = _n_inputs > 0 ? _n_inputs : 8;
808         const int a_out = _n_outputs > 0 ? _n_outputs : 8;
809         const int m_ins = _n_midi_inputs == UINT_MAX ? 0 : _n_midi_inputs;
810         const int m_out = _n_midi_outputs == UINT_MAX ? a_ins : _n_midi_outputs;
811
812
813         /* audio ports */
814         lr.min = lr.max = _systemic_input_latency;
815         for (int i = 1; i <= a_ins; ++i) {
816                 char tmp[64];
817                 snprintf(tmp, sizeof(tmp), "system:capture_%d", i);
818                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
819                 if (!p) return -1;
820                 set_latency_range (p, false, lr);
821                 _system_inputs.push_back (static_cast<DummyAudioPort*>(p));
822                 static_cast<DummyAudioPort*>(p)->setup_generator (gt, _samplerate);
823         }
824
825         lr.min = lr.max = _systemic_output_latency;
826         for (int i = 1; i <= a_out; ++i) {
827                 char tmp[64];
828                 snprintf(tmp, sizeof(tmp), "system:playback_%d", i);
829                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
830                 if (!p) return -1;
831                 set_latency_range (p, true, lr);
832                 _system_outputs.push_back (static_cast<DummyAudioPort*>(p));
833         }
834
835         /* midi ports */
836         lr.min = lr.max = _systemic_input_latency;
837         for (int i = 0; i < m_ins; ++i) {
838                 char tmp[64];
839                 snprintf(tmp, sizeof(tmp), "system:midi_capture_%d", i+1);
840                 PortHandle p = add_port(std::string(tmp), DataType::MIDI, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
841                 if (!p) return -1;
842                 set_latency_range (p, false, lr);
843                 _system_midi_in.push_back (static_cast<DummyMidiPort*>(p));
844                 if (_midi_mode == MidiGenerator) {
845                         static_cast<DummyMidiPort*>(p)->setup_generator (i % NUM_MIDI_EVENT_GENERATORS, _samplerate);
846                 }
847         }
848
849         lr.min = lr.max = _systemic_output_latency;
850         for (int i = 1; i <= m_out; ++i) {
851                 char tmp[64];
852                 snprintf(tmp, sizeof(tmp), "system:midi_playback_%d", i);
853                 PortHandle p = add_port(std::string(tmp), DataType::MIDI, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
854                 if (!p) return -1;
855                 set_latency_range (p, true, lr);
856                 _system_midi_out.push_back (static_cast<DummyMidiPort*>(p));
857         }
858         return 0;
859 }
860
861 void
862 DummyAudioBackend::unregister_ports (bool system_only)
863 {
864         _system_inputs.clear();
865         _system_outputs.clear();
866         _system_midi_in.clear();
867         _system_midi_out.clear();
868
869         for (std::vector<DummyPort*>::iterator i = _ports.begin (); i != _ports.end ();) {
870                 DummyPort* port = *i;
871                 if (! system_only || (port->is_physical () && port->is_terminal ())) {
872                         port->disconnect_all ();
873                         delete port;
874                         i = _ports.erase (i);
875                 } else {
876                         ++i;
877                 }
878         }
879 }
880
881 int
882 DummyAudioBackend::connect (const std::string& src, const std::string& dst)
883 {
884         DummyPort* src_port = find_port (src);
885         DummyPort* dst_port = find_port (dst);
886
887         if (!src_port) {
888                 PBD::error << _("DummyBackend::connect: Invalid Source port:")
889                                 << " (" << src <<")" << endmsg;
890                 return -1;
891         }
892         if (!dst_port) {
893                 PBD::error << _("DummyBackend::connect: Invalid Destination port:")
894                         << " (" << dst <<")" << endmsg;
895                 return -1;
896         }
897         return src_port->connect (dst_port);
898 }
899
900 int
901 DummyAudioBackend::disconnect (const std::string& src, const std::string& dst)
902 {
903         DummyPort* src_port = find_port (src);
904         DummyPort* dst_port = find_port (dst);
905
906         if (!src_port || !dst_port) {
907                 PBD::error << _("DummyBackend::disconnect: Invalid Port(s)") << endmsg;
908                 return -1;
909         }
910         return src_port->disconnect (dst_port);
911 }
912
913 int
914 DummyAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
915 {
916         DummyPort* dst_port = find_port (dst);
917         if (!valid_port (src)) {
918                 PBD::error << _("DummyBackend::connect: Invalid Source Port Handle") << endmsg;
919                 return -1;
920         }
921         if (!dst_port) {
922                 PBD::error << _("DummyBackend::connect: Invalid Destination Port")
923                         << " (" << dst << ")" << endmsg;
924                 return -1;
925         }
926         return static_cast<DummyPort*>(src)->connect (dst_port);
927 }
928
929 int
930 DummyAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
931 {
932         DummyPort* dst_port = find_port (dst);
933         if (!valid_port (src) || !dst_port) {
934                 PBD::error << _("DummyBackend::disconnect: Invalid Port(s)") << endmsg;
935                 return -1;
936         }
937         return static_cast<DummyPort*>(src)->disconnect (dst_port);
938 }
939
940 int
941 DummyAudioBackend::disconnect_all (PortEngine::PortHandle port)
942 {
943         if (!valid_port (port)) {
944                 PBD::error << _("DummyBackend::disconnect_all: Invalid Port") << endmsg;
945                 return -1;
946         }
947         static_cast<DummyPort*>(port)->disconnect_all ();
948         return 0;
949 }
950
951 bool
952 DummyAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
953 {
954         if (!valid_port (port)) {
955                 PBD::error << _("DummyBackend::disconnect_all: Invalid Port") << endmsg;
956                 return false;
957         }
958         return static_cast<DummyPort*>(port)->is_connected ();
959 }
960
961 bool
962 DummyAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
963 {
964         DummyPort* dst_port = find_port (dst);
965         if (!valid_port (src) || !dst_port) {
966                 PBD::error << _("DummyBackend::connected_to: Invalid Port") << endmsg;
967                 return false;
968         }
969         return static_cast<DummyPort*>(src)->is_connected (dst_port);
970 }
971
972 bool
973 DummyAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
974 {
975         if (!valid_port (port)) {
976                 PBD::error << _("DummyBackend::physically_connected: Invalid Port") << endmsg;
977                 return false;
978         }
979         return static_cast<DummyPort*>(port)->is_physically_connected ();
980 }
981
982 int
983 DummyAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
984 {
985         if (!valid_port (port)) {
986                 PBD::error << _("DummyBackend::get_connections: Invalid Port") << endmsg;
987                 return -1;
988         }
989
990         assert (0 == names.size ());
991
992         const std::vector<DummyPort*>& connected_ports = static_cast<DummyPort*>(port)->get_connections ();
993
994         for (std::vector<DummyPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
995                 names.push_back ((*i)->name ());
996         }
997
998         return (int)names.size ();
999 }
1000
1001 /* MIDI */
1002 int
1003 DummyAudioBackend::midi_event_get (
1004                 pframes_t& timestamp,
1005                 size_t& size, uint8_t** buf, void* port_buffer,
1006                 uint32_t event_index)
1007 {
1008         assert (buf && port_buffer);
1009         DummyMidiBuffer& source = * static_cast<DummyMidiBuffer*>(port_buffer);
1010         if (event_index >= source.size ()) {
1011                 return -1;
1012         }
1013         DummyMidiEvent * const event = source[event_index].get ();
1014
1015         timestamp = event->timestamp ();
1016         size = event->size ();
1017         *buf = event->data ();
1018         return 0;
1019 }
1020
1021 int
1022 DummyAudioBackend::midi_event_put (
1023                 void* port_buffer,
1024                 pframes_t timestamp,
1025                 const uint8_t* buffer, size_t size)
1026 {
1027         assert (buffer && port_buffer);
1028         DummyMidiBuffer& dst = * static_cast<DummyMidiBuffer*>(port_buffer);
1029         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
1030                 // nevermind, ::get_buffer() sorts events, but always print warning
1031                 fprintf (stderr, "DummyMidiBuffer: it's too late for this event.\n");
1032         }
1033         dst.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (timestamp, buffer, size)));
1034         return 0;
1035 }
1036
1037 uint32_t
1038 DummyAudioBackend::get_midi_event_count (void* port_buffer)
1039 {
1040         assert (port_buffer);
1041         return static_cast<DummyMidiBuffer*>(port_buffer)->size ();
1042 }
1043
1044 void
1045 DummyAudioBackend::midi_clear (void* port_buffer)
1046 {
1047         assert (port_buffer);
1048         DummyMidiBuffer * buf = static_cast<DummyMidiBuffer*>(port_buffer);
1049         assert (buf);
1050         buf->clear ();
1051 }
1052
1053 /* Monitoring */
1054
1055 bool
1056 DummyAudioBackend::can_monitor_input () const
1057 {
1058         return false;
1059 }
1060
1061 int
1062 DummyAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1063 {
1064         return -1;
1065 }
1066
1067 int
1068 DummyAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1069 {
1070         return -1;
1071 }
1072
1073 bool
1074 DummyAudioBackend::monitoring_input (PortEngine::PortHandle)
1075 {
1076         return false;
1077 }
1078
1079 /* Latency management */
1080
1081 void
1082 DummyAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1083 {
1084         if (!valid_port (port)) {
1085                 PBD::error << _("DummyPort::set_latency_range (): invalid port.") << endmsg;
1086         }
1087         static_cast<DummyPort*>(port)->set_latency_range (latency_range, for_playback);
1088 }
1089
1090 LatencyRange
1091 DummyAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1092 {
1093         LatencyRange r;
1094         if (!valid_port (port)) {
1095                 PBD::error << _("DummyPort::get_latency_range (): invalid port.") << endmsg;
1096                 r.min = 0;
1097                 r.max = 0;
1098                 return r;
1099         }
1100         DummyPort *p =  static_cast<DummyPort*>(port);
1101         assert(p);
1102
1103         r = p->latency_range (for_playback);
1104         if (p->is_physical() && p->is_terminal()) {
1105                 if (p->is_input() && for_playback) {
1106                         const size_t l_in = _samples_per_period * .25;
1107                         r.min += l_in;
1108                         r.max += l_in;
1109                 }
1110                 if (p->is_output() && !for_playback) {
1111                         /* with 'Loopback' there is exactly once cycle latency, divide it between In + Out; */
1112                         const size_t l_in = _samples_per_period * .25;
1113                         const size_t l_out = _samples_per_period - l_in;
1114                         r.min += l_out;
1115                         r.max += l_out;
1116                 }
1117         }
1118         return r;
1119 }
1120
1121 /* Discovering physical ports */
1122
1123 bool
1124 DummyAudioBackend::port_is_physical (PortEngine::PortHandle port) const
1125 {
1126         if (!valid_port (port)) {
1127                 PBD::error << _("DummyPort::port_is_physical (): invalid port.") << endmsg;
1128                 return false;
1129         }
1130         return static_cast<DummyPort*>(port)->is_physical ();
1131 }
1132
1133 void
1134 DummyAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1135 {
1136         for (size_t i = 0; i < _ports.size (); ++i) {
1137                 DummyPort* port = _ports[i];
1138                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1139                         port_names.push_back (port->name ());
1140                 }
1141         }
1142 }
1143
1144 void
1145 DummyAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1146 {
1147         for (size_t i = 0; i < _ports.size (); ++i) {
1148                 DummyPort* port = _ports[i];
1149                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1150                         port_names.push_back (port->name ());
1151                 }
1152         }
1153 }
1154
1155 ChanCount
1156 DummyAudioBackend::n_physical_outputs () const
1157 {
1158         int n_midi = 0;
1159         int n_audio = 0;
1160         for (size_t i = 0; i < _ports.size (); ++i) {
1161                 DummyPort* port = _ports[i];
1162                 if (port->is_output () && port->is_physical ()) {
1163                         switch (port->type ()) {
1164                                 case DataType::AUDIO: ++n_audio; break;
1165                                 case DataType::MIDI: ++n_midi; break;
1166                                 default: break;
1167                         }
1168                 }
1169         }
1170         ChanCount cc;
1171         cc.set (DataType::AUDIO, n_audio);
1172         cc.set (DataType::MIDI, n_midi);
1173         return cc;
1174 }
1175
1176 ChanCount
1177 DummyAudioBackend::n_physical_inputs () const
1178 {
1179         int n_midi = 0;
1180         int n_audio = 0;
1181         for (size_t i = 0; i < _ports.size (); ++i) {
1182                 DummyPort* port = _ports[i];
1183                 if (port->is_input () && port->is_physical ()) {
1184                         switch (port->type ()) {
1185                                 case DataType::AUDIO: ++n_audio; break;
1186                                 case DataType::MIDI: ++n_midi; break;
1187                                 default: break;
1188                         }
1189                 }
1190         }
1191         ChanCount cc;
1192         cc.set (DataType::AUDIO, n_audio);
1193         cc.set (DataType::MIDI, n_midi);
1194         return cc;
1195 }
1196
1197 /* Getting access to the data buffer for a port */
1198
1199 void*
1200 DummyAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1201 {
1202         assert (port);
1203         assert (valid_port (port));
1204         return static_cast<DummyPort*>(port)->get_buffer (nframes);
1205 }
1206
1207 /* Engine Process */
1208 void *
1209 DummyAudioBackend::main_process_thread ()
1210 {
1211         AudioEngine::thread_init_callback (this);
1212         _running = true;
1213         _processed_samples = 0;
1214
1215         manager.registration_callback();
1216         manager.graph_order_callback();
1217
1218         int64_t clock1;
1219         clock1 = -1;
1220         while (_running) {
1221
1222                 if (_freewheeling != _freewheel) {
1223                         _freewheel = _freewheeling;
1224                         engine.freewheel_callback (_freewheel);
1225                 }
1226
1227                 // re-set input buffers, generate on demand.
1228                 for (std::vector<DummyAudioPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
1229                         (*it)->next_period();
1230                 }
1231                 for (std::vector<DummyMidiPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it) {
1232                         (*it)->next_period();
1233                 }
1234
1235                 if (engine.process_callback (_samples_per_period)) {
1236                         return 0;
1237                 }
1238                 _processed_samples += _samples_per_period;
1239
1240                 if (_device == _("Loopback") && _midi_mode != MidiToAudio) {
1241                         int opn = 0;
1242                         int opc = _system_outputs.size();
1243                         for (std::vector<DummyAudioPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++opn) {
1244                                 DummyAudioPort* op = _system_outputs[(opn % opc)];
1245                                 (*it)->fill_wavetable ((const float*)op->get_buffer (_samples_per_period), _samples_per_period);
1246                         }
1247                 }
1248
1249                 if (_midi_mode == MidiLoopback) {
1250                         int opn = 0;
1251                         int opc = _system_midi_out.size();
1252                         for (std::vector<DummyMidiPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++opn) {
1253                                 DummyMidiPort* op = _system_midi_out[(opn % opc)];
1254                                 op->get_buffer(0); // mix-down
1255                                 (*it)->set_loopback (op->const_buffer());
1256                         }
1257                 }
1258                 else if (_midi_mode == MidiToAudio) {
1259                         int opn = 0;
1260                         int opc = _system_midi_out.size();
1261                         for (std::vector<DummyAudioPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++opn) {
1262                                 DummyMidiPort* op = _system_midi_out[(opn % opc)];
1263                                 op->get_buffer(0); // mix-down
1264                                 (*it)->midi_to_wavetable (op->const_buffer(), _samples_per_period);
1265                         }
1266                 }
1267
1268                 if (!_freewheel) {
1269                         _dsp_load_calc.set_start_timestamp_us (clock1);
1270                         _dsp_load_calc.set_stop_timestamp_us (_x_get_monotonic_usec());
1271                         _dsp_load = _dsp_load_calc.get_dsp_load_unbound ();
1272
1273                         const int64_t elapsed_time = _dsp_load_calc.elapsed_time_us ();
1274                         const int64_t nominal_time = _dsp_load_calc.get_max_time_us ();
1275                         if (elapsed_time < nominal_time) {
1276                                 const int64_t sleepy = _speedup * (nominal_time - elapsed_time);
1277                                 Glib::usleep (std::max ((int64_t) 100, sleepy));
1278                         } else {
1279                                 Glib::usleep (100); // don't hog cpu
1280                         }
1281                 } else {
1282                         _dsp_load = 1.0f;
1283                         Glib::usleep (100); // don't hog cpu
1284                 }
1285
1286                 /* beginning of next cycle */
1287                 clock1 = _x_get_monotonic_usec();
1288
1289                 bool connections_changed = false;
1290                 bool ports_changed = false;
1291                 if (!pthread_mutex_trylock (&_port_callback_mutex)) {
1292                         if (_port_change_flag) {
1293                                 ports_changed = true;
1294                                 _port_change_flag = false;
1295                         }
1296                         if (!_port_connection_queue.empty ()) {
1297                                 connections_changed = true;
1298                         }
1299                         while (!_port_connection_queue.empty ()) {
1300                                 PortConnectData *c = _port_connection_queue.back ();
1301                                 manager.connect_callback (c->a, c->b, c->c);
1302                                 _port_connection_queue.pop_back ();
1303                                 delete c;
1304                         }
1305                         pthread_mutex_unlock (&_port_callback_mutex);
1306                 }
1307                 if (ports_changed) {
1308                         manager.registration_callback();
1309                 }
1310                 if (connections_changed) {
1311                         manager.graph_order_callback();
1312                 }
1313                 if (connections_changed || ports_changed) {
1314                         engine.latency_callback(false);
1315                         engine.latency_callback(true);
1316                 }
1317
1318         }
1319         _running = false;
1320         return 0;
1321 }
1322
1323
1324 /******************************************************************************/
1325
1326 static boost::shared_ptr<DummyAudioBackend> _instance;
1327
1328 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
1329 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
1330 static int deinstantiate ();
1331 static bool already_configured ();
1332 static bool available ();
1333
1334 static ARDOUR::AudioBackendInfo _descriptor = {
1335         _("None (Dummy)"),
1336         instantiate,
1337         deinstantiate,
1338         backend_factory,
1339         already_configured,
1340         available
1341 };
1342
1343 static boost::shared_ptr<AudioBackend>
1344 backend_factory (AudioEngine& e)
1345 {
1346         if (!_instance) {
1347                 _instance.reset (new DummyAudioBackend (e, _descriptor));
1348         }
1349         return _instance;
1350 }
1351
1352 static int
1353 instantiate (const std::string& arg1, const std::string& /* arg2 */)
1354 {
1355         s_instance_name = arg1;
1356         return 0;
1357 }
1358
1359 static int
1360 deinstantiate ()
1361 {
1362         _instance.reset ();
1363         return 0;
1364 }
1365
1366 static bool
1367 already_configured ()
1368 {
1369         // special-case: unit-tests require backend to be pre-configured.
1370         if (s_instance_name == "Unit-Test") {
1371                 return true;
1372         }
1373         return false;
1374 }
1375
1376 static bool
1377 available ()
1378 {
1379         return true;
1380 }
1381
1382 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
1383 {
1384         return &_descriptor;
1385 }
1386
1387
1388 /******************************************************************************/
1389 DummyPort::DummyPort (DummyAudioBackend &b, const std::string& name, PortFlags flags)
1390         : _dummy_backend (b)
1391         , _name  (name)
1392         , _flags (flags)
1393         , _rseed (0)
1394         , _gen_cycle (false)
1395 {
1396         _capture_latency_range.min = 0;
1397         _capture_latency_range.max = 0;
1398         _playback_latency_range.min = 0;
1399         _playback_latency_range.max = 0;
1400         _dummy_backend.port_connect_add_remove_callback();
1401 }
1402
1403 DummyPort::~DummyPort () {
1404         disconnect_all ();
1405         _dummy_backend.port_connect_add_remove_callback();
1406 }
1407
1408
1409 int DummyPort::connect (DummyPort *port)
1410 {
1411         if (!port) {
1412                 PBD::error << _("DummyPort::connect (): invalid (null) port") << endmsg;
1413                 return -1;
1414         }
1415
1416         if (type () != port->type ()) {
1417                 PBD::error << _("DummyPort::connect (): wrong port-type") << endmsg;
1418                 return -1;
1419         }
1420
1421         if (is_output () && port->is_output ()) {
1422                 PBD::error << _("DummyPort::connect (): cannot inter-connect output ports.") << endmsg;
1423                 return -1;
1424         }
1425
1426         if (is_input () && port->is_input ()) {
1427                 PBD::error << _("DummyPort::connect (): cannot inter-connect input ports.") << endmsg;
1428                 return -1;
1429         }
1430
1431         if (this == port) {
1432                 PBD::error << _("DummyPort::connect (): cannot self-connect ports.") << endmsg;
1433                 return -1;
1434         }
1435
1436         if (is_connected (port)) {
1437 #if 0 // don't bother to warn about this for now. just ignore it
1438                 PBD::error << _("DummyPort::connect (): ports are already connected:")
1439                         << " (" << name () << ") -> (" << port->name () << ")"
1440                         << endmsg;
1441 #endif
1442                 return -1;
1443         }
1444
1445         _connect (port, true);
1446         return 0;
1447 }
1448
1449
1450 void DummyPort::_connect (DummyPort *port, bool callback)
1451 {
1452         _connections.push_back (port);
1453         if (callback) {
1454                 port->_connect (this, false);
1455                 _dummy_backend.port_connect_callback (name(),  port->name(), true);
1456         }
1457 }
1458
1459 int DummyPort::disconnect (DummyPort *port)
1460 {
1461         if (!port) {
1462                 PBD::error << _("DummyPort::disconnect (): invalid (null) port") << endmsg;
1463                 return -1;
1464         }
1465
1466         if (!is_connected (port)) {
1467                 PBD::error << _("DummyPort::disconnect (): ports are not connected:")
1468                         << " (" << name () << ") -> (" << port->name () << ")"
1469                         << endmsg;
1470                 return -1;
1471         }
1472         _disconnect (port, true);
1473         return 0;
1474 }
1475
1476 void DummyPort::_disconnect (DummyPort *port, bool callback)
1477 {
1478         std::vector<DummyPort*>::iterator it = std::find (_connections.begin (), _connections.end (), port);
1479
1480         assert (it != _connections.end ());
1481
1482         _connections.erase (it);
1483
1484         if (callback) {
1485                 port->_disconnect (this, false);
1486                 _dummy_backend.port_connect_callback (name(),  port->name(), false);
1487         }
1488 }
1489
1490
1491 void DummyPort::disconnect_all ()
1492 {
1493         while (!_connections.empty ()) {
1494                 _connections.back ()->_disconnect (this, false);
1495                 _dummy_backend.port_connect_callback (name(),  _connections.back ()->name(), false);
1496                 _connections.pop_back ();
1497         }
1498 }
1499
1500 bool
1501 DummyPort::is_connected (const DummyPort *port) const
1502 {
1503         return std::find (_connections.begin (), _connections.end (), port) != _connections.end ();
1504 }
1505
1506 bool DummyPort::is_physically_connected () const
1507 {
1508         for (std::vector<DummyPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
1509                 if ((*it)->is_physical ()) {
1510                         return true;
1511                 }
1512         }
1513         return false;
1514 }
1515
1516 void DummyPort::setup_random_number_generator ()
1517 {
1518 #ifdef PLATFORM_WINDOWS
1519         LARGE_INTEGER Count;
1520         if (QueryPerformanceCounter (&Count)) {
1521                 _rseed = Count.QuadPart % UINT_MAX;
1522         } else
1523 #endif
1524         {
1525         _rseed = g_get_monotonic_time() % UINT_MAX;
1526         }
1527         _rseed = (_rseed + (uint64_t)this) % UINT_MAX;
1528 }
1529
1530 inline uint32_t
1531 DummyPort::randi ()
1532 {
1533         // 31bit Park-Miller-Carta Pseudo-Random Number Generator
1534         // http://www.firstpr.com.au/dsp/rand31/
1535         uint32_t hi, lo;
1536         lo = 16807 * (_rseed & 0xffff);
1537         hi = 16807 * (_rseed >> 16);
1538
1539         lo += (hi & 0x7fff) << 16;
1540         lo += hi >> 15;
1541 #if 1
1542         lo = (lo & 0x7fffffff) + (lo >> 31);
1543 #else
1544         if (lo > 0x7fffffff) { lo -= 0x7fffffff; }
1545 #endif
1546         return (_rseed = lo);
1547 }
1548
1549 inline float
1550 DummyPort::randf ()
1551 {
1552         return (randi() / 1073741824.f) - 1.f;
1553 }
1554
1555 /******************************************************************************/
1556
1557 DummyAudioPort::DummyAudioPort (DummyAudioBackend &b, const std::string& name, PortFlags flags)
1558         : DummyPort (b, name, flags)
1559         , _gen_type (Silence)
1560         , _b0 (0)
1561         , _b1 (0)
1562         , _b2 (0)
1563         , _b3 (0)
1564         , _b4 (0)
1565         , _b5 (0)
1566         , _b6 (0)
1567         , _wavetable (0)
1568         , _gen_period (0)
1569         , _gen_offset (0)
1570         , _gen_perio2 (0)
1571         , _gen_count2 (0)
1572         , _pass (false)
1573         , _rn1 (0)
1574 {
1575         memset (_buffer, 0, sizeof (_buffer));
1576 }
1577
1578 DummyAudioPort::~DummyAudioPort () {
1579         free(_wavetable);
1580         _wavetable = 0;
1581 }
1582
1583 void DummyAudioPort::setup_generator (GeneratorType const g, float const samplerate)
1584 {
1585         DummyPort::setup_random_number_generator();
1586         _gen_type = g;
1587
1588         switch (_gen_type) {
1589                 case PinkNoise:
1590                 case PonyNoise:
1591                 case UniformWhiteNoise:
1592                 case GaussianWhiteNoise:
1593                 case Silence:
1594                         break;
1595                 case KronekerDelta:
1596                         _gen_period = (5 + randi() % (int)(samplerate / 20.f));
1597                         break;
1598                 case SquareWave:
1599                         _gen_period = (5 + randi() % (int)(samplerate / 20.f)) & ~1;
1600                         break;
1601                 case SineWave:
1602                         _gen_period = 5 + randi() % (int)(samplerate / 20.f);
1603                         _wavetable = (Sample*) malloc (_gen_period * sizeof(Sample));
1604                         for (uint32_t i = 0 ; i < _gen_period; ++i) {
1605                                 _wavetable[i] = .12589f * sinf(2.0f * M_PI * (float)i / (float)_gen_period); // -18dBFS
1606                         }
1607                         break;
1608                 case SquareSweep:
1609                 case SquareSweepSwell:
1610                 case SineSweep:
1611                 case SineSweepSwell:
1612                         {
1613                                 _gen_period = 5 * samplerate + randi() % (int)(samplerate * 10.f);
1614                                 _gen_period &= ~1;
1615                                 _gen_perio2 = 1 | (int)ceilf (_gen_period * .89f); // Volume Swell period
1616                                 const double f_min = 20.;
1617                                 const double f_max = samplerate * .5;
1618                                 const double g_p2 = _gen_period * .5;
1619 #ifdef LINEAR_SWEEP
1620                                 const double b = (f_max - f_min) / (2. * samplerate * g_p2);
1621                                 const double a = f_min / samplerate;
1622 #else
1623                                 const double b = log (f_max / f_min) / g_p2;
1624                                 const double a = f_min / (b * samplerate);
1625 #endif
1626                                 const uint32_t g_p2i = rint(g_p2);
1627                                 _wavetable = (Sample*) malloc (_gen_period * sizeof(Sample));
1628                                 for (uint32_t i = 0 ; i < g_p2i; ++i) {
1629 #ifdef LINEAR_SWEEP
1630                                         const double phase = i * (a + b * i);
1631 #else
1632                                         const double phase = a * exp (b * i) - a;
1633 #endif
1634                                         _wavetable[i] = (float)sin (2. * M_PI * (phase - floor (phase)));
1635                                 }
1636                                 for (uint32_t i = g_p2i; i < _gen_period; ++i) {
1637                                         const uint32_t j = _gen_period - i;
1638 #ifdef LINEAR_SWEEP
1639                                         const double phase = j * (a + b * j);
1640 #else
1641                                         const double phase = a * exp (b * j) - a;
1642 #endif
1643                                         _wavetable[i] = -(float)sin (2. * M_PI * (phase - floor (phase)));
1644                                 }
1645                                 if (_gen_type == SquareSweep) {
1646                                         for (uint32_t i = 0 ; i < _gen_period; ++i) {
1647                                                 _wavetable[i] = _wavetable[i] < 0 ? -.40709f : .40709f;
1648                                         }
1649                                 }
1650                                 else if (_gen_type == SquareSweepSwell) {
1651                                         for (uint32_t i = 0 ; i < _gen_period; ++i) {
1652                                                 _wavetable[i] = _wavetable[i] < 0 ? -1 : 1;
1653                                         }
1654                                 }
1655                         }
1656                         break;
1657                 case Loopback:
1658                         _wavetable = (Sample*) malloc (DummyAudioBackend::max_buffer_size() * sizeof(Sample));
1659                         break;
1660         }
1661 }
1662
1663 void DummyAudioPort::midi_to_wavetable (DummyMidiBuffer const * const src, size_t n_samples)
1664 {
1665         memset(_wavetable, 0, n_samples * sizeof(float));
1666         /* generate an audio spike for every midi message
1667          * to verify layency-compensation alignment
1668          * (here: midi-out playback-latency + audio-in capture-latency)
1669          */
1670         for (DummyMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
1671                 const pframes_t t = (*it)->timestamp();
1672                 assert(t < n_samples);
1673                 // somewhat arbitrary mapping for quick visual feedback
1674                 float v = -.5f;
1675                 if ((*it)->size() == 3) {
1676                         const unsigned char *d = (*it)->const_data();
1677                         if ((d[0] & 0xf0) == 0x90) { // note on
1678                                 v = .25f + d[2] / 512.f;
1679                         }
1680                         else if ((d[0] & 0xf0) == 0x80) { // note off
1681                                 v = .3f - d[2] / 640.f;
1682                         }
1683                         else if ((d[0] & 0xf0) == 0xb0) { // CC
1684                                 v = -.1f - d[2] / 256.f;
1685                         }
1686                 }
1687                 _wavetable[t] += v;
1688         }
1689 }
1690
1691 float DummyAudioPort::grandf ()
1692 {
1693         // Gaussian White Noise
1694         // http://www.musicdsp.org/archive.php?classid=0#109
1695         float x1, x2, r;
1696
1697         if (_pass) {
1698                 _pass = false;
1699                 return _rn1;
1700         }
1701
1702         do {
1703                 x1 = randf ();
1704                 x2 = randf ();
1705                 r = x1 * x1 + x2 * x2;
1706         } while ((r >= 1.0f) || (r < 1e-22f));
1707
1708         r = sqrtf (-2.f * logf (r) / r);
1709
1710         _pass = true;
1711         _rn1 = r * x2;
1712         return r * x1;
1713 }
1714
1715 void DummyAudioPort::generate (const pframes_t n_samples)
1716 {
1717         Glib::Threads::Mutex::Lock lm (generator_lock);
1718         if (_gen_cycle) {
1719                 return;
1720         }
1721
1722         switch (_gen_type) {
1723                 case Silence:
1724                         memset (_buffer, 0, n_samples * sizeof (Sample));
1725                         break;
1726                 case SquareWave:
1727                         assert(_gen_period > 0);
1728                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1729                                 if (_gen_offset < _gen_period * .5f) {
1730                                         _buffer[i] =  .40709f; // -6dBFS
1731                                 } else {
1732                                         _buffer[i] = -.40709f;
1733                                 }
1734                                 _gen_offset = (_gen_offset + 1) % _gen_period;
1735                         }
1736                         break;
1737                 case KronekerDelta:
1738                         assert(_gen_period > 0);
1739                         memset (_buffer, 0, n_samples * sizeof (Sample));
1740                         for (pframes_t i = 0; i < n_samples; ++i) {
1741                                 if (_gen_offset == 0) {
1742                                         _buffer[i] = 1.0f;
1743                                 }
1744                                 _gen_offset = (_gen_offset + 1) % _gen_period;
1745                         }
1746                         break;
1747                 case SineSweepSwell:
1748                 case SquareSweepSwell:
1749                         assert(_wavetable && _gen_period > 0);
1750                         {
1751                                 const float vols = 2.f / (float)_gen_perio2;
1752                                 for (pframes_t i = 0; i < n_samples; ++i) {
1753                                         const float g = fabsf (_gen_count2 * vols - 1.f);
1754                                         _buffer[i] = g * _wavetable[_gen_offset];
1755                                         _gen_offset = (_gen_offset + 1) % _gen_period;
1756                                         _gen_count2 = (_gen_count2 + 1) % _gen_perio2;
1757                                 }
1758                         }
1759                         break;
1760                 case Loopback:
1761                         _gen_period = n_samples; // XXX DummyBackend::_samples_per_period;
1762                 case SineWave:
1763                 case SineSweep:
1764                 case SquareSweep:
1765                         assert(_wavetable && _gen_period > 0);
1766                         {
1767                                 pframes_t written = 0;
1768                                 while (written < n_samples) {
1769                                         const uint32_t remain = n_samples - written;
1770                                         const uint32_t to_copy = std::min(remain, _gen_period - _gen_offset);
1771                                         memcpy((void*)&_buffer[written],
1772                                                         (void*)&_wavetable[_gen_offset],
1773                                                         to_copy * sizeof(Sample));
1774                                         written += to_copy;
1775                                         _gen_offset = (_gen_offset + to_copy) % _gen_period;
1776                                 }
1777                         }
1778                         break;
1779                 case UniformWhiteNoise:
1780                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1781                                 _buffer[i] = .158489f * randf();
1782                         }
1783                         break;
1784                 case GaussianWhiteNoise:
1785                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1786                                 _buffer[i] = .089125f * grandf();
1787                         }
1788                         break;
1789                 case PinkNoise:
1790                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1791                                 // Paul Kellet's refined method
1792                                 // http://www.musicdsp.org/files/pink.txt
1793                                 // NB. If 'white' consists of uniform random numbers,
1794                                 // the pink noise will have an almost gaussian distribution.
1795                                 const float white = .0498f * randf ();
1796                                 _b0 = .99886f * _b0 + white * .0555179f;
1797                                 _b1 = .99332f * _b1 + white * .0750759f;
1798                                 _b2 = .96900f * _b2 + white * .1538520f;
1799                                 _b3 = .86650f * _b3 + white * .3104856f;
1800                                 _b4 = .55000f * _b4 + white * .5329522f;
1801                                 _b5 = -.7616f * _b5 - white * .0168980f;
1802                                 _buffer[i] = _b0 + _b1 + _b2 + _b3 + _b4 + _b5 + _b6 + white * 0.5362f;
1803                                 _b6 = white * 0.115926f;
1804                         }
1805                         break;
1806                 case PonyNoise:
1807                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1808                                 const float white = 0.0498f * randf ();
1809                                 // Paul Kellet's economy method
1810                                 // http://www.musicdsp.org/files/pink.txt
1811                                 _b0 = 0.99765f * _b0 + white * 0.0990460f;
1812                                 _b1 = 0.96300f * _b1 + white * 0.2965164f;
1813                                 _b2 = 0.57000f * _b2 + white * 1.0526913f;
1814                                 _buffer[i] = _b0 + _b1 + _b2 + white * 0.1848f;
1815                         }
1816                         break;
1817         }
1818         _gen_cycle = true;
1819 }
1820
1821 void* DummyAudioPort::get_buffer (pframes_t n_samples)
1822 {
1823         if (is_input ()) {
1824                 std::vector<DummyPort*>::const_iterator it = get_connections ().begin ();
1825                 if (it == get_connections ().end ()) {
1826                         memset (_buffer, 0, n_samples * sizeof (Sample));
1827                 } else {
1828                         DummyAudioPort * source = static_cast<DummyAudioPort*>(*it);
1829                         assert (source && source->is_output ());
1830                         if (source->is_physical() && source->is_terminal()) {
1831                                 source->get_buffer(n_samples); // generate signal.
1832                         }
1833                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
1834                         while (++it != get_connections ().end ()) {
1835                                 source = static_cast<DummyAudioPort*>(*it);
1836                                 assert (source && source->is_output ());
1837                                 Sample* dst = buffer ();
1838                                 if (source->is_physical() && source->is_terminal()) {
1839                                         source->get_buffer(n_samples); // generate signal.
1840                                 }
1841                                 const Sample* src = source->const_buffer ();
1842                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
1843                                         *dst += *src;
1844                                 }
1845                         }
1846                 }
1847         } else if (is_output () && is_physical () && is_terminal()) {
1848                 if (!_gen_cycle) {
1849                         generate(n_samples);
1850                 }
1851         }
1852         return _buffer;
1853 }
1854
1855
1856 DummyMidiPort::DummyMidiPort (DummyAudioBackend &b, const std::string& name, PortFlags flags)
1857         : DummyPort (b, name, flags)
1858         , _midi_seq_spb (0)
1859         , _midi_seq_time (0)
1860         , _midi_seq_pos (0)
1861 {
1862         _buffer.clear ();
1863         _loopback.clear ();
1864 }
1865
1866 DummyMidiPort::~DummyMidiPort () {
1867         _buffer.clear ();
1868         _loopback.clear ();
1869 }
1870
1871 struct MidiEventSorter {
1872         bool operator() (const boost::shared_ptr<DummyMidiEvent>& a, const boost::shared_ptr<DummyMidiEvent>& b) {
1873                 return *a < *b;
1874         }
1875 };
1876
1877 void DummyMidiPort::set_loopback (DummyMidiBuffer const * const src)
1878 {
1879         _loopback.clear ();
1880         for (DummyMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
1881                 _loopback.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (**it)));
1882         }
1883 }
1884
1885 void DummyMidiPort::setup_generator (int seq_id, const float sr)
1886 {
1887         DummyPort::setup_random_number_generator();
1888         _midi_seq_dat = DummyMidiData::sequences[seq_id % NUM_MIDI_EVENT_GENERATORS];
1889         _midi_seq_spb = sr * .5f; // 120 BPM, beat_time 1.0 per beat.
1890         _midi_seq_pos = 0;
1891         _midi_seq_time = 0;
1892 }
1893
1894 void DummyMidiPort::midi_generate (const pframes_t n_samples)
1895 {
1896         Glib::Threads::Mutex::Lock lm (generator_lock);
1897         if (_gen_cycle) {
1898                 return;
1899         }
1900
1901         _buffer.clear ();
1902         _gen_cycle = true;
1903
1904         if (_midi_seq_spb == 0 || !_midi_seq_dat) {
1905                 for (DummyMidiBuffer::const_iterator it = _loopback.begin (); it != _loopback.end (); ++it) {
1906                         _buffer.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (**it)));
1907                 }
1908                 return;
1909         }
1910
1911         while (1) {
1912                 const int32_t ev_beat_time = _midi_seq_dat[_midi_seq_pos].beat_time * _midi_seq_spb - _midi_seq_time;
1913                 if (ev_beat_time < 0) {
1914                         break;
1915                 }
1916                 if ((pframes_t) ev_beat_time >= n_samples) {
1917                         break;
1918                 }
1919                 _buffer.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (
1920                                                 ev_beat_time,
1921                                                 _midi_seq_dat[_midi_seq_pos].event,
1922                                                 _midi_seq_dat[_midi_seq_pos].size
1923                                                 )));
1924                 ++_midi_seq_pos;
1925
1926                 if (_midi_seq_dat[_midi_seq_pos].event[0] == 0xff && _midi_seq_dat[_midi_seq_pos].event[1] == 0xff) {
1927                         _midi_seq_time -= _midi_seq_dat[_midi_seq_pos].beat_time * _midi_seq_spb;
1928                         _midi_seq_pos = 0;
1929                 }
1930         }
1931         _midi_seq_time += n_samples;
1932 }
1933
1934
1935 void* DummyMidiPort::get_buffer (pframes_t n_samples)
1936 {
1937         if (is_input ()) {
1938                 _buffer.clear ();
1939                 for (std::vector<DummyPort*>::const_iterator i = get_connections ().begin ();
1940                                 i != get_connections ().end ();
1941                                 ++i) {
1942                         DummyMidiPort * source = static_cast<DummyMidiPort*>(*i);
1943                         if (source->is_physical() && source->is_terminal()) {
1944                                 source->get_buffer(n_samples); // generate signal.
1945                         }
1946                         const DummyMidiBuffer *src = source->const_buffer ();
1947                         for (DummyMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
1948                                 _buffer.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (**it)));
1949                         }
1950                 }
1951                 std::sort (_buffer.begin (), _buffer.end (), MidiEventSorter());
1952         } else if (is_output () && is_physical () && is_terminal()) {
1953                 if (!_gen_cycle) {
1954                         midi_generate(n_samples);
1955                 }
1956         }
1957         return &_buffer;
1958 }
1959
1960 DummyMidiEvent::DummyMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
1961         : _size (size)
1962         , _timestamp (timestamp)
1963         , _data (0)
1964 {
1965         if (size > 0) {
1966                 _data = (uint8_t*) malloc (size);
1967                 memcpy (_data, data, size);
1968         }
1969 }
1970
1971 DummyMidiEvent::DummyMidiEvent (const DummyMidiEvent& other)
1972         : _size (other.size ())
1973         , _timestamp (other.timestamp ())
1974         , _data (0)
1975 {
1976         if (other.size () && other.const_data ()) {
1977                 _data = (uint8_t*) malloc (other.size ());
1978                 memcpy (_data, other.const_data (), other.size ());
1979         }
1980 };
1981
1982 DummyMidiEvent::~DummyMidiEvent () {
1983         free (_data);
1984 };