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