Only show user-presets in favorite sidebar
[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 uint32_t
639 DummyAudioBackend::port_name_size () const
640 {
641         return 256;
642 }
643
644 int
645 DummyAudioBackend::set_port_name (PortEngine::PortHandle port, const std::string& name)
646 {
647         std::string newname (_instance_name + ":" + name);
648
649         if (!valid_port (port)) {
650                 PBD::error << _("DummyBackend::set_port_name: Invalid Port(s)") << endmsg;
651                 return -1;
652         }
653
654         if (find_port (newname)) {
655                 PBD::error << _("DummyBackend::set_port_name: Port with given name already exists") << endmsg;
656                 return -1;
657         }
658
659         DummyPort* p = static_cast<DummyPort*>(port);
660         _portmap.erase (p->name());
661         _portmap.insert (make_pair (newname, p));
662         return p->set_name (newname);
663 }
664
665 std::string
666 DummyAudioBackend::get_port_name (PortEngine::PortHandle port) const
667 {
668         if (!valid_port (port)) {
669                 PBD::error << _("DummyBackend::get_port_name: Invalid Port(s)") << endmsg;
670                 return std::string ();
671         }
672         return static_cast<DummyPort*>(port)->name ();
673 }
674
675 PortFlags
676 DummyAudioBackend::get_port_flags (PortEngine::PortHandle port) const
677 {
678         if (!valid_port (port)) {
679                 PBD::error << _("DummyBackend::get_port_flags: Invalid Port(s)") << endmsg;
680                 return PortFlags (0);
681         }
682         return static_cast<DummyPort*>(port)->flags ();
683 }
684
685 int
686 DummyAudioBackend::get_port_property (PortHandle port, const std::string& key, std::string& value, std::string& type) const
687 {
688         if (!valid_port (port)) {
689                 PBD::warning << _("DummyBackend::get_port_property: Invalid Port(s)") << endmsg;
690                 return -1;
691         }
692         if (key == "http://jackaudio.org/metadata/pretty-name") {
693                 type = "";
694                 value = static_cast<DummyPort*>(port)->pretty_name ();
695                 if (!value.empty()) {
696                         return 0;
697                 }
698         }
699         return -1;
700 }
701
702 int
703 DummyAudioBackend::set_port_property (PortHandle port, const std::string& key, const std::string& value, const std::string& type)
704 {
705         if (!valid_port (port)) {
706                 PBD::warning << _("DummyBackend::set_port_property: Invalid Port(s)") << endmsg;
707                 return -1;
708         }
709         if (key == "http://jackaudio.org/metadata/pretty-name" && type.empty ()) {
710                 static_cast<DummyPort*>(port)->set_pretty_name (value);
711                 return 0;
712         }
713         return -1;
714 }
715
716 PortEngine::PortHandle
717 DummyAudioBackend::get_port_by_name (const std::string& name) const
718 {
719         PortHandle port = (PortHandle) find_port (name);
720         return port;
721 }
722
723 int
724 DummyAudioBackend::get_ports (
725                 const std::string& port_name_pattern,
726                 DataType type, PortFlags flags,
727                 std::vector<std::string>& port_names) const
728 {
729         int rv = 0;
730         regex_t port_regex;
731         bool use_regexp = false;
732         if (port_name_pattern.size () > 0) {
733                 if (!regcomp (&port_regex, port_name_pattern.c_str (), REG_EXTENDED|REG_NOSUB)) {
734                         use_regexp = true;
735                 }
736         }
737
738         for (PortIndex::const_iterator i = _ports.begin (); i != _ports.end (); ++i) {
739                 DummyPort* port = *i;
740                 if ((port->type () == type) && flags == (port->flags () & flags)) {
741                         if (!use_regexp || !regexec (&port_regex, port->name ().c_str (), 0, NULL, 0)) {
742                                 port_names.push_back (port->name ());
743                                 ++rv;
744                         }
745                 }
746         }
747         if (use_regexp) {
748                 regfree (&port_regex);
749         }
750         return rv;
751 }
752
753 DataType
754 DummyAudioBackend::port_data_type (PortEngine::PortHandle port) const
755 {
756         if (!valid_port (port)) {
757                 return DataType::NIL;
758         }
759         return static_cast<DummyPort*>(port)->type ();
760 }
761
762 PortEngine::PortHandle
763 DummyAudioBackend::register_port (
764                 const std::string& name,
765                 ARDOUR::DataType type,
766                 ARDOUR::PortFlags flags)
767 {
768         if (name.size () == 0) { return 0; }
769         if (flags & IsPhysical) { return 0; }
770         if (!_running) {
771                 PBD::info << _("DummyBackend::register_port: Engine is not running.") << endmsg;
772         }
773         return add_port (_instance_name + ":" + name, type, flags);
774 }
775
776 PortEngine::PortHandle
777 DummyAudioBackend::add_port (
778                 const std::string& name,
779                 ARDOUR::DataType type,
780                 ARDOUR::PortFlags flags)
781 {
782         assert(name.size ());
783         if (find_port (name)) {
784                 PBD::error << _("DummyBackend::register_port: Port already exists:")
785                                 << " (" << name << ")" << endmsg;
786                 return 0;
787         }
788         DummyPort* port = NULL;
789         switch (type) {
790                 case DataType::AUDIO:
791                         port = new DummyAudioPort (*this, name, flags);
792                         break;
793                 case DataType::MIDI:
794                         port = new DummyMidiPort (*this, name, flags);
795                         break;
796                 default:
797                         PBD::error << _("DummyBackend::register_port: Invalid Data Type.") << endmsg;
798                         return 0;
799         }
800
801         _ports.insert (port);
802         _portmap.insert (make_pair (name, port));
803
804         return port;
805 }
806
807 void
808 DummyAudioBackend::unregister_port (PortEngine::PortHandle port_handle)
809 {
810         if (!_running) {
811                 PBD::info << _("DummyBackend::unregister_port: Engine is not running.") << endmsg;
812                 assert (!valid_port (port_handle));
813                 return;
814         }
815         DummyPort* port = static_cast<DummyPort*>(port_handle);
816         PortIndex::iterator i = std::find (_ports.begin(), _ports.end(), static_cast<DummyPort*>(port_handle));
817         if (i == _ports.end ()) {
818                 PBD::error << _("DummyBackend::unregister_port: Failed to find port") << endmsg;
819                 return;
820         }
821         disconnect_all(port_handle);
822         _portmap.erase (port->name());
823         _ports.erase (i);
824         delete port;
825 }
826
827 int
828 DummyAudioBackend::register_system_ports()
829 {
830         LatencyRange lr;
831         enum DummyAudioPort::GeneratorType gt;
832         if (_device == _("Uniform White Noise")) {
833                 gt = DummyAudioPort::UniformWhiteNoise;
834         } else if (_device == _("Gaussian White Noise")) {
835                 gt = DummyAudioPort::GaussianWhiteNoise;
836         } else if (_device == _("Pink Noise")) {
837                 gt = DummyAudioPort::PinkNoise;
838         } else if (_device == _("Pink Noise (low CPU)")) {
839                 gt = DummyAudioPort::PonyNoise;
840         } else if (_device == _("Sine Wave")) {
841                 gt = DummyAudioPort::SineWave;
842         } else if (_device == _("Sine Wave 1K, 1/3 Oct")) {
843                 gt = DummyAudioPort::SineWaveOctaves;
844         } else if (_device == _("Square Wave")) {
845                 gt = DummyAudioPort::SquareWave;
846         } else if (_device == _("Impulses")) {
847                 gt = DummyAudioPort::KronekerDelta;
848         } else if (_device == _("Sine Sweep")) {
849                 gt = DummyAudioPort::SineSweep;
850         } else if (_device == _("Sine Sweep Swell")) {
851                 gt = DummyAudioPort::SineSweepSwell;
852         } else if (_device == _("Square Sweep")) {
853                 gt = DummyAudioPort::SquareSweep;
854         } else if (_device == _("Square Sweep Swell")) {
855                 gt = DummyAudioPort::SquareSweepSwell;
856         } else if (_device == _("LTC")) {
857                 gt = DummyAudioPort::LTC;
858         } else if (_device == _("Loopback")) {
859                 gt = DummyAudioPort::Loopback;
860         } else if (_device == _("Demolition")) {
861                 gt = DummyAudioPort::Demolition;
862         } else if (_device == _("DC -6dBFS (+.5)")) {
863                 gt = DummyAudioPort::DC05;
864         } else {
865                 gt = DummyAudioPort::Silence;
866         }
867
868         if (_midi_mode == MidiToAudio) {
869                 gt = DummyAudioPort::Loopback;
870         }
871
872         const int a_ins = _n_inputs > 0 ? _n_inputs : 8;
873         const int a_out = _n_outputs > 0 ? _n_outputs : 8;
874         const int m_ins = _n_midi_inputs == UINT_MAX ? 0 : _n_midi_inputs;
875         const int m_out = _n_midi_outputs == UINT_MAX ? a_ins : _n_midi_outputs;
876
877
878         /* audio ports */
879         lr.min = lr.max = _systemic_input_latency;
880         for (int i = 1; i <= a_ins; ++i) {
881                 char tmp[64];
882                 snprintf(tmp, sizeof(tmp), "system:capture_%d", i);
883                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
884                 if (!p) return -1;
885                 set_latency_range (p, false, lr);
886                 _system_inputs.push_back (static_cast<DummyAudioPort*>(p));
887                 std::string name = static_cast<DummyAudioPort*>(p)->setup_generator (gt, _samplerate, i - 1, a_ins);
888                 if (!name.empty ()) {
889                         static_cast<DummyAudioPort*>(p)->set_pretty_name (name);
890                 }
891         }
892
893         lr.min = lr.max = _systemic_output_latency;
894         for (int i = 1; i <= a_out; ++i) {
895                 char tmp[64];
896                 snprintf(tmp, sizeof(tmp), "system:playback_%d", i);
897                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
898                 if (!p) return -1;
899                 set_latency_range (p, true, lr);
900                 _system_outputs.push_back (static_cast<DummyAudioPort*>(p));
901         }
902
903         /* midi ports */
904         lr.min = lr.max = _systemic_input_latency;
905         for (int i = 0; i < m_ins; ++i) {
906                 char tmp[64];
907                 snprintf(tmp, sizeof(tmp), "system:midi_capture_%d", i+1);
908                 PortHandle p = add_port(std::string(tmp), DataType::MIDI, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
909                 if (!p) return -1;
910                 set_latency_range (p, false, lr);
911                 _system_midi_in.push_back (static_cast<DummyMidiPort*>(p));
912                 if (_midi_mode == MidiGenerator) {
913                         std::string name = static_cast<DummyMidiPort*>(p)->setup_generator (i % NUM_MIDI_EVENT_GENERATORS, _samplerate);
914                         if (!name.empty ()) {
915                                 static_cast<DummyMidiPort*>(p)->set_pretty_name (name);
916                         }
917                 }
918         }
919
920         lr.min = lr.max = _systemic_output_latency;
921         for (int i = 1; i <= m_out; ++i) {
922                 char tmp[64];
923                 snprintf(tmp, sizeof(tmp), "system:midi_playback_%d", i);
924                 PortHandle p = add_port(std::string(tmp), DataType::MIDI, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
925                 if (!p) return -1;
926                 set_latency_range (p, true, lr);
927                 _system_midi_out.push_back (static_cast<DummyMidiPort*>(p));
928
929                 if (_device == _("Loopback") && _midi_mode == MidiToAudio) {
930                         std::stringstream ss;
931                         ss << "Midi2Audio";
932                         for (int apc = 0; apc < (int)_system_inputs.size(); ++apc) {
933                                 if ((apc % m_out) + 1 == i) {
934                                         ss << " >" << (apc + 1);
935                                 }
936                         }
937                         static_cast<DummyMidiPort*>(p)->set_pretty_name (ss.str());
938                 }
939         }
940         return 0;
941 }
942
943 void
944 DummyAudioBackend::unregister_ports (bool system_only)
945 {
946         _system_inputs.clear();
947         _system_outputs.clear();
948         _system_midi_in.clear();
949         _system_midi_out.clear();
950
951         for (PortIndex::iterator i = _ports.begin (); i != _ports.end ();) {
952                 PortIndex::iterator cur = i++;
953                 DummyPort* port = *cur;
954                 if (! system_only || (port->is_physical () && port->is_terminal ())) {
955                         port->disconnect_all ();
956                         _portmap.erase (port->name());
957                         delete port;
958                         _ports.erase (cur);
959                 }
960         }
961 }
962
963 void
964 DummyAudioBackend::update_system_port_latecies ()
965 {
966         for (std::vector<DummyAudioPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
967                 (*it)->update_connected_latency (true);
968         }
969         for (std::vector<DummyAudioPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it) {
970                 (*it)->update_connected_latency (false);
971         }
972
973         for (std::vector<DummyMidiPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it) {
974                 (*it)->update_connected_latency (true);
975         }
976         for (std::vector<DummyMidiPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it) {
977                 (*it)->update_connected_latency (false);
978         }
979 }
980
981 int
982 DummyAudioBackend::connect (const std::string& src, const std::string& dst)
983 {
984         DummyPort* src_port = find_port (src);
985         DummyPort* dst_port = find_port (dst);
986
987         if (!src_port) {
988                 PBD::error << _("DummyBackend::connect: Invalid Source port:")
989                                 << " (" << src <<")" << endmsg;
990                 return -1;
991         }
992         if (!dst_port) {
993                 PBD::error << _("DummyBackend::connect: Invalid Destination port:")
994                         << " (" << dst <<")" << endmsg;
995                 return -1;
996         }
997         return src_port->connect (dst_port);
998 }
999
1000 int
1001 DummyAudioBackend::disconnect (const std::string& src, const std::string& dst)
1002 {
1003         DummyPort* src_port = find_port (src);
1004         DummyPort* dst_port = find_port (dst);
1005
1006         if (!src_port || !dst_port) {
1007                 PBD::error << _("DummyBackend::disconnect: Invalid Port(s)") << endmsg;
1008                 return -1;
1009         }
1010         return src_port->disconnect (dst_port);
1011 }
1012
1013 int
1014 DummyAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
1015 {
1016         DummyPort* dst_port = find_port (dst);
1017         if (!valid_port (src)) {
1018                 PBD::error << _("DummyBackend::connect: Invalid Source Port Handle") << endmsg;
1019                 return -1;
1020         }
1021         if (!dst_port) {
1022                 PBD::error << _("DummyBackend::connect: Invalid Destination Port")
1023                         << " (" << dst << ")" << endmsg;
1024                 return -1;
1025         }
1026         return static_cast<DummyPort*>(src)->connect (dst_port);
1027 }
1028
1029 int
1030 DummyAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
1031 {
1032         DummyPort* dst_port = find_port (dst);
1033         if (!valid_port (src) || !dst_port) {
1034                 PBD::error << _("DummyBackend::disconnect: Invalid Port(s)") << endmsg;
1035                 return -1;
1036         }
1037         return static_cast<DummyPort*>(src)->disconnect (dst_port);
1038 }
1039
1040 int
1041 DummyAudioBackend::disconnect_all (PortEngine::PortHandle port)
1042 {
1043         if (!valid_port (port)) {
1044                 PBD::error << _("DummyBackend::disconnect_all: Invalid Port") << endmsg;
1045                 return -1;
1046         }
1047         static_cast<DummyPort*>(port)->disconnect_all ();
1048         return 0;
1049 }
1050
1051 bool
1052 DummyAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
1053 {
1054         if (!valid_port (port)) {
1055                 PBD::error << _("DummyBackend::disconnect_all: Invalid Port") << endmsg;
1056                 return false;
1057         }
1058         return static_cast<DummyPort*>(port)->is_connected ();
1059 }
1060
1061 bool
1062 DummyAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
1063 {
1064         DummyPort* dst_port = find_port (dst);
1065 #ifndef NDEBUG
1066         if (!valid_port (src) || !dst_port) {
1067                 PBD::error << _("DummyBackend::connected_to: Invalid Port") << endmsg;
1068                 return false;
1069         }
1070 #endif
1071         return static_cast<DummyPort*>(src)->is_connected (dst_port);
1072 }
1073
1074 bool
1075 DummyAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
1076 {
1077         if (!valid_port (port)) {
1078                 PBD::error << _("DummyBackend::physically_connected: Invalid Port") << endmsg;
1079                 return false;
1080         }
1081         return static_cast<DummyPort*>(port)->is_physically_connected ();
1082 }
1083
1084 int
1085 DummyAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
1086 {
1087         if (!valid_port (port)) {
1088                 PBD::error << _("DummyBackend::get_connections: Invalid Port") << endmsg;
1089                 return -1;
1090         }
1091
1092         assert (0 == names.size ());
1093
1094         const std::set<DummyPort*>& connected_ports = static_cast<DummyPort*>(port)->get_connections ();
1095
1096         for (std::set<DummyPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
1097                 names.push_back ((*i)->name ());
1098         }
1099
1100         return (int)names.size ();
1101 }
1102
1103 /* MIDI */
1104 int
1105 DummyAudioBackend::midi_event_get (
1106                 pframes_t& timestamp,
1107                 size_t& size, uint8_t const** buf, void* port_buffer,
1108                 uint32_t event_index)
1109 {
1110         assert (buf && port_buffer);
1111         DummyMidiBuffer& source = * static_cast<DummyMidiBuffer*>(port_buffer);
1112         if (event_index >= source.size ()) {
1113                 return -1;
1114         }
1115         DummyMidiEvent * const event = source[event_index].get ();
1116
1117         timestamp = event->timestamp ();
1118         size = event->size ();
1119         *buf = event->data ();
1120         return 0;
1121 }
1122
1123 int
1124 DummyAudioBackend::midi_event_put (
1125                 void* port_buffer,
1126                 pframes_t timestamp,
1127                 const uint8_t* buffer, size_t size)
1128 {
1129         assert (buffer && port_buffer);
1130         DummyMidiBuffer& dst = * static_cast<DummyMidiBuffer*>(port_buffer);
1131         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
1132                 // nevermind, ::get_buffer() sorts events, but always print warning
1133                 fprintf (stderr, "DummyMidiBuffer: it's too late for this event %d > %d.\n", (pframes_t)dst.back ()->timestamp (), timestamp);
1134         }
1135         dst.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (timestamp, buffer, size)));
1136 #if 0 // DEBUG MIDI EVENTS
1137         printf("DummyAudioBackend::midi_event_put %d, %zu: ", timestamp, size);
1138         for (size_t xx = 0; xx < size; ++xx) {
1139                 printf(" %02x", buffer[xx]);
1140         }
1141         printf("\n");
1142 #endif
1143         return 0;
1144 }
1145
1146 uint32_t
1147 DummyAudioBackend::get_midi_event_count (void* port_buffer)
1148 {
1149         assert (port_buffer);
1150         return static_cast<DummyMidiBuffer*>(port_buffer)->size ();
1151 }
1152
1153 void
1154 DummyAudioBackend::midi_clear (void* port_buffer)
1155 {
1156         assert (port_buffer);
1157         DummyMidiBuffer * buf = static_cast<DummyMidiBuffer*>(port_buffer);
1158         assert (buf);
1159         buf->clear ();
1160 }
1161
1162 /* Monitoring */
1163
1164 bool
1165 DummyAudioBackend::can_monitor_input () const
1166 {
1167         return false;
1168 }
1169
1170 int
1171 DummyAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1172 {
1173         return -1;
1174 }
1175
1176 int
1177 DummyAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1178 {
1179         return -1;
1180 }
1181
1182 bool
1183 DummyAudioBackend::monitoring_input (PortEngine::PortHandle)
1184 {
1185         return false;
1186 }
1187
1188 /* Latency management */
1189
1190 void
1191 DummyAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1192 {
1193         if (!valid_port (port)) {
1194                 PBD::error << _("DummyPort::set_latency_range (): invalid port.") << endmsg;
1195         }
1196         static_cast<DummyPort*>(port)->set_latency_range (latency_range, for_playback);
1197 }
1198
1199 LatencyRange
1200 DummyAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1201 {
1202         LatencyRange r;
1203         if (!valid_port (port)) {
1204                 PBD::error << _("DummyPort::get_latency_range (): invalid port.") << endmsg;
1205                 r.min = 0;
1206                 r.max = 0;
1207                 return r;
1208         }
1209         DummyPort *p =  static_cast<DummyPort*>(port);
1210         assert(p);
1211
1212         r = p->latency_range (for_playback);
1213         if (p->is_physical() && p->is_terminal()) {
1214                 if (p->is_input() && for_playback) {
1215                         const size_t l_in = _samples_per_period * .25;
1216                         r.min += l_in;
1217                         r.max += l_in;
1218                 }
1219                 if (p->is_output() && !for_playback) {
1220                         /* with 'Loopback' there is exactly once cycle latency, divide it between In + Out; */
1221                         const size_t l_in = _samples_per_period * .25;
1222                         const size_t l_out = _samples_per_period - l_in;
1223                         r.min += l_out;
1224                         r.max += l_out;
1225                 }
1226         }
1227         return r;
1228 }
1229
1230 /* Discovering physical ports */
1231
1232 bool
1233 DummyAudioBackend::port_is_physical (PortEngine::PortHandle port) const
1234 {
1235         if (!valid_port (port)) {
1236                 PBD::error << _("DummyPort::port_is_physical (): invalid port.") << endmsg;
1237                 return false;
1238         }
1239         return static_cast<DummyPort*>(port)->is_physical ();
1240 }
1241
1242 void
1243 DummyAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1244 {
1245         for (PortIndex::iterator i = _ports.begin (); i != _ports.end (); ++i) {
1246                 DummyPort* port = *i;
1247                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1248                         port_names.push_back (port->name ());
1249                 }
1250         }
1251 }
1252
1253 void
1254 DummyAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1255 {
1256         for (PortIndex::iterator i = _ports.begin (); i != _ports.end (); ++i) {
1257                 DummyPort* port = *i;
1258                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1259                         port_names.push_back (port->name ());
1260                 }
1261         }
1262 }
1263
1264 ChanCount
1265 DummyAudioBackend::n_physical_outputs () const
1266 {
1267         int n_midi = 0;
1268         int n_audio = 0;
1269         for (PortIndex::const_iterator i = _ports.begin (); i != _ports.end (); ++i) {
1270                 DummyPort* port = *i;
1271                 if (port->is_output () && port->is_physical ()) {
1272                         switch (port->type ()) {
1273                                 case DataType::AUDIO: ++n_audio; break;
1274                                 case DataType::MIDI: ++n_midi; break;
1275                                 default: break;
1276                         }
1277                 }
1278         }
1279         ChanCount cc;
1280         cc.set (DataType::AUDIO, n_audio);
1281         cc.set (DataType::MIDI, n_midi);
1282         return cc;
1283 }
1284
1285 ChanCount
1286 DummyAudioBackend::n_physical_inputs () const
1287 {
1288         int n_midi = 0;
1289         int n_audio = 0;
1290         for (PortIndex::const_iterator i = _ports.begin (); i != _ports.end (); ++i) {
1291                 DummyPort* port = *i;
1292                 if (port->is_input () && port->is_physical ()) {
1293                         switch (port->type ()) {
1294                                 case DataType::AUDIO: ++n_audio; break;
1295                                 case DataType::MIDI: ++n_midi; break;
1296                                 default: break;
1297                         }
1298                 }
1299         }
1300         ChanCount cc;
1301         cc.set (DataType::AUDIO, n_audio);
1302         cc.set (DataType::MIDI, n_midi);
1303         return cc;
1304 }
1305
1306 /* Getting access to the data buffer for a port */
1307
1308 void*
1309 DummyAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1310 {
1311         assert (port);
1312         assert (valid_port (port));
1313         return static_cast<DummyPort*>(port)->get_buffer (nframes);
1314 }
1315
1316 /* Engine Process */
1317 void *
1318 DummyAudioBackend::main_process_thread ()
1319 {
1320         AudioEngine::thread_init_callback (this);
1321         _running = true;
1322         _processed_samples = 0;
1323
1324         manager.registration_callback();
1325         manager.graph_order_callback();
1326
1327         int64_t clock1;
1328         clock1 = -1;
1329         while (_running) {
1330                 const size_t samples_per_period = _samples_per_period;
1331
1332                 if (_freewheeling != _freewheel) {
1333                         _freewheel = _freewheeling;
1334                         engine.freewheel_callback (_freewheel);
1335                 }
1336
1337                 // re-set input buffers, generate on demand.
1338                 for (std::vector<DummyAudioPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
1339                         (*it)->next_period();
1340                 }
1341                 for (std::vector<DummyMidiPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it) {
1342                         (*it)->next_period();
1343                 }
1344
1345                 if (engine.process_callback (samples_per_period)) {
1346                         return 0;
1347                 }
1348                 _processed_samples += samples_per_period;
1349
1350                 if (_device == _("Loopback") && _midi_mode != MidiToAudio) {
1351                         int opn = 0;
1352                         int opc = _system_outputs.size();
1353                         for (std::vector<DummyAudioPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++opn) {
1354                                 DummyAudioPort* op = _system_outputs[(opn % opc)];
1355                                 (*it)->fill_wavetable ((const float*)op->get_buffer (samples_per_period), samples_per_period);
1356                         }
1357                 }
1358
1359                 if (_midi_mode == MidiLoopback) {
1360                         int opn = 0;
1361                         int opc = _system_midi_out.size();
1362                         for (std::vector<DummyMidiPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++opn) {
1363                                 DummyMidiPort* op = _system_midi_out[(opn % opc)];
1364                                 op->get_buffer(0); // mix-down
1365                                 (*it)->set_loopback (op->const_buffer());
1366                         }
1367                 }
1368                 else if (_midi_mode == MidiToAudio) {
1369                         int opn = 0;
1370                         int opc = _system_midi_out.size();
1371                         for (std::vector<DummyAudioPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++opn) {
1372                                 DummyMidiPort* op = _system_midi_out[(opn % opc)];
1373                                 op->get_buffer(0); // mix-down
1374                                 (*it)->midi_to_wavetable (op->const_buffer(), samples_per_period);
1375                         }
1376                 }
1377
1378                 if (!_freewheel) {
1379                         _dsp_load_calc.set_max_time (_samplerate, samples_per_period);
1380                         _dsp_load_calc.set_start_timestamp_us (clock1);
1381                         _dsp_load_calc.set_stop_timestamp_us (_x_get_monotonic_usec());
1382                         _dsp_load = _dsp_load_calc.get_dsp_load_unbound ();
1383
1384                         const int64_t elapsed_time = _dsp_load_calc.elapsed_time_us ();
1385                         const int64_t nominal_time = _dsp_load_calc.get_max_time_us ();
1386                         if (elapsed_time < nominal_time) {
1387                                 const int64_t sleepy = _speedup * (nominal_time - elapsed_time);
1388                                 Glib::usleep (std::max ((int64_t) 100, sleepy));
1389                         } else {
1390                                 Glib::usleep (100); // don't hog cpu
1391                         }
1392                 } else {
1393                         _dsp_load = 1.0f;
1394                         Glib::usleep (100); // don't hog cpu
1395                 }
1396
1397                 /* beginning of next cycle */
1398                 clock1 = _x_get_monotonic_usec();
1399
1400                 bool connections_changed = false;
1401                 bool ports_changed = false;
1402                 if (!pthread_mutex_trylock (&_port_callback_mutex)) {
1403                         if (_port_change_flag) {
1404                                 ports_changed = true;
1405                                 _port_change_flag = false;
1406                         }
1407                         if (!_port_connection_queue.empty ()) {
1408                                 connections_changed = true;
1409                         }
1410                         while (!_port_connection_queue.empty ()) {
1411                                 PortConnectData *c = _port_connection_queue.back ();
1412                                 manager.connect_callback (c->a, c->b, c->c);
1413                                 _port_connection_queue.pop_back ();
1414                                 delete c;
1415                         }
1416                         pthread_mutex_unlock (&_port_callback_mutex);
1417                 }
1418                 if (ports_changed) {
1419                         manager.registration_callback();
1420                 }
1421                 if (connections_changed) {
1422                         manager.graph_order_callback();
1423                 }
1424                 if (connections_changed || ports_changed) {
1425                         update_system_port_latecies ();
1426                         engine.latency_callback(false);
1427                         engine.latency_callback(true);
1428                 }
1429
1430         }
1431         _running = false;
1432         return 0;
1433 }
1434
1435
1436 /******************************************************************************/
1437
1438 static boost::shared_ptr<DummyAudioBackend> _instance;
1439
1440 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
1441 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
1442 static int deinstantiate ();
1443 static bool already_configured ();
1444 static bool available ();
1445
1446 static ARDOUR::AudioBackendInfo _descriptor = {
1447         _("None (Dummy)"),
1448         instantiate,
1449         deinstantiate,
1450         backend_factory,
1451         already_configured,
1452         available
1453 };
1454
1455 static boost::shared_ptr<AudioBackend>
1456 backend_factory (AudioEngine& e)
1457 {
1458         if (!_instance) {
1459                 _instance.reset (new DummyAudioBackend (e, _descriptor));
1460         }
1461         return _instance;
1462 }
1463
1464 static int
1465 instantiate (const std::string& arg1, const std::string& /* arg2 */)
1466 {
1467         s_instance_name = arg1;
1468         return 0;
1469 }
1470
1471 static int
1472 deinstantiate ()
1473 {
1474         _instance.reset ();
1475         return 0;
1476 }
1477
1478 static bool
1479 already_configured ()
1480 {
1481         // special-case: unit-tests require backend to be pre-configured.
1482         if (s_instance_name == "Unit-Test") {
1483                 return true;
1484         }
1485         return false;
1486 }
1487
1488 static bool
1489 available ()
1490 {
1491         return true;
1492 }
1493
1494 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
1495 {
1496         return &_descriptor;
1497 }
1498
1499
1500 /******************************************************************************/
1501 DummyPort::DummyPort (DummyAudioBackend &b, const std::string& name, PortFlags flags)
1502         : _dummy_backend (b)
1503         , _name  (name)
1504         , _flags (flags)
1505         , _rseed (0)
1506         , _gen_cycle (false)
1507 {
1508         _capture_latency_range.min = 0;
1509         _capture_latency_range.max = 0;
1510         _playback_latency_range.min = 0;
1511         _playback_latency_range.max = 0;
1512         _dummy_backend.port_connect_add_remove_callback();
1513 }
1514
1515 DummyPort::~DummyPort () {
1516         disconnect_all ();
1517         _dummy_backend.port_connect_add_remove_callback();
1518 }
1519
1520
1521 int DummyPort::connect (DummyPort *port)
1522 {
1523         if (!port) {
1524                 PBD::error << _("DummyPort::connect (): invalid (null) port") << endmsg;
1525                 return -1;
1526         }
1527
1528         if (type () != port->type ()) {
1529                 PBD::error << _("DummyPort::connect (): wrong port-type") << endmsg;
1530                 return -1;
1531         }
1532
1533         if (is_output () && port->is_output ()) {
1534                 PBD::error << _("DummyPort::connect (): cannot inter-connect output ports.") << endmsg;
1535                 return -1;
1536         }
1537
1538         if (is_input () && port->is_input ()) {
1539                 PBD::error << _("DummyPort::connect (): cannot inter-connect input ports.") << endmsg;
1540                 return -1;
1541         }
1542
1543         if (this == port) {
1544                 PBD::error << _("DummyPort::connect (): cannot self-connect ports.") << endmsg;
1545                 return -1;
1546         }
1547
1548         if (is_connected (port)) {
1549 #if 0 // don't bother to warn about this for now. just ignore it
1550                 PBD::error << _("DummyPort::connect (): ports are already connected:")
1551                         << " (" << name () << ") -> (" << port->name () << ")"
1552                         << endmsg;
1553 #endif
1554                 return -1;
1555         }
1556
1557         _connect (port, true);
1558         return 0;
1559 }
1560
1561
1562 void DummyPort::_connect (DummyPort *port, bool callback)
1563 {
1564         _connections.insert (port);
1565         if (callback) {
1566                 port->_connect (this, false);
1567                 _dummy_backend.port_connect_callback (name(),  port->name(), true);
1568         }
1569 }
1570
1571 int DummyPort::disconnect (DummyPort *port)
1572 {
1573         if (!port) {
1574                 PBD::error << _("DummyPort::disconnect (): invalid (null) port") << endmsg;
1575                 return -1;
1576         }
1577
1578         if (!is_connected (port)) {
1579                 PBD::error << _("DummyPort::disconnect (): ports are not connected:")
1580                         << " (" << name () << ") -> (" << port->name () << ")"
1581                         << endmsg;
1582                 return -1;
1583         }
1584         _disconnect (port, true);
1585         return 0;
1586 }
1587
1588 void DummyPort::_disconnect (DummyPort *port, bool callback)
1589 {
1590         std::set<DummyPort*>::iterator it = _connections.find (port);
1591         assert (it != _connections.end ());
1592         _connections.erase (it);
1593         if (callback) {
1594                 port->_disconnect (this, false);
1595                 _dummy_backend.port_connect_callback (name(),  port->name(), false);
1596         }
1597 }
1598
1599
1600 void DummyPort::disconnect_all ()
1601 {
1602         while (!_connections.empty ()) {
1603                 std::set<DummyPort*>::iterator it = _connections.begin ();
1604                 (*it)->_disconnect (this, false);
1605                 _dummy_backend.port_connect_callback (name(), (*it)->name(), false);
1606                 _connections.erase (it);
1607         }
1608 }
1609
1610 bool
1611 DummyPort::is_connected (const DummyPort *port) const
1612 {
1613         return _connections.find (const_cast<DummyPort *>(port)) != _connections.end ();
1614 }
1615
1616 bool DummyPort::is_physically_connected () const
1617 {
1618         for (std::set<DummyPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
1619                 if ((*it)->is_physical ()) {
1620                         return true;
1621                 }
1622         }
1623         return false;
1624 }
1625
1626 void
1627 DummyPort::set_latency_range (const LatencyRange &latency_range, bool for_playback)
1628 {
1629         if (for_playback) {
1630                 _playback_latency_range = latency_range;
1631         } else {
1632                 _capture_latency_range = latency_range;
1633         }
1634
1635         for (std::set<DummyPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
1636                 if ((*it)->is_physical ()) {
1637                         (*it)->update_connected_latency (is_input ());
1638                 }
1639         }
1640 }
1641
1642 void
1643 DummyPort::update_connected_latency (bool for_playback)
1644 {
1645         LatencyRange lr;
1646         lr.min = lr.max = 0;
1647         for (std::set<DummyPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
1648                 LatencyRange l;
1649                 l = (*it)->latency_range (for_playback);
1650                 lr.min = std::max (lr.min, l.min);
1651                 lr.max = std::max (lr.max, l.max);
1652         }
1653         set_latency_range (lr, for_playback);
1654 }
1655
1656 void DummyPort::setup_random_number_generator ()
1657 {
1658 #ifdef PLATFORM_WINDOWS
1659         LARGE_INTEGER Count;
1660         if (QueryPerformanceCounter (&Count)) {
1661                 _rseed = Count.QuadPart;
1662         } else
1663 #endif
1664         {
1665         _rseed = g_get_monotonic_time();
1666         }
1667         _rseed = (_rseed + (uint64_t)this) % INT_MAX;
1668         if (_rseed == 0) _rseed = 1;
1669 }
1670
1671 inline uint32_t
1672 DummyPort::randi ()
1673 {
1674         // 31bit Park-Miller-Carta Pseudo-Random Number Generator
1675         // http://www.firstpr.com.au/dsp/rand31/
1676         uint32_t hi, lo;
1677         lo = 16807 * (_rseed & 0xffff);
1678         hi = 16807 * (_rseed >> 16);
1679
1680         lo += (hi & 0x7fff) << 16;
1681         lo += hi >> 15;
1682 #if 1
1683         lo = (lo & 0x7fffffff) + (lo >> 31);
1684 #else
1685         if (lo > 0x7fffffff) { lo -= 0x7fffffff; }
1686 #endif
1687         return (_rseed = lo);
1688 }
1689
1690 inline float
1691 DummyPort::randf ()
1692 {
1693         return (randi() / 1073741824.f) - 1.f;
1694 }
1695
1696 /******************************************************************************/
1697
1698 DummyAudioPort::DummyAudioPort (DummyAudioBackend &b, const std::string& name, PortFlags flags)
1699         : DummyPort (b, name, flags)
1700         , _gen_type (Silence)
1701         , _b0 (0)
1702         , _b1 (0)
1703         , _b2 (0)
1704         , _b3 (0)
1705         , _b4 (0)
1706         , _b5 (0)
1707         , _b6 (0)
1708         , _wavetable (0)
1709         , _gen_period (0)
1710         , _gen_offset (0)
1711         , _gen_perio2 (0)
1712         , _gen_count2 (0)
1713         , _pass (false)
1714         , _rn1 (0)
1715         , _ltc (0)
1716         , _ltcbuf (0)
1717 {
1718         memset (_buffer, 0, sizeof (_buffer));
1719 }
1720
1721 DummyAudioPort::~DummyAudioPort () {
1722         free(_wavetable);
1723         ltc_encoder_free (_ltc);
1724         delete _ltcbuf;
1725         _wavetable = 0;
1726         _ltc = 0;
1727         _ltcbuf = 0;
1728 }
1729
1730 static std::string format_hz (float freq) {
1731         std::stringstream ss;
1732         if (freq >= 10000) {
1733                 ss <<  std::setprecision (1) << std::fixed << freq / 1000 << "kHz";
1734         } else if (freq >= 1000) {
1735                 ss <<  std::setprecision (2) << std::fixed << freq / 1000 << "kHz";
1736         } else {
1737                 ss <<  std::setprecision (1) << std::fixed << freq << "Hz";
1738         }
1739         return ss.str ();
1740 }
1741
1742 static size_t fit_wave (float freq, float rate, float precision = 0.001) {
1743         const size_t max_mult = floor (freq * rate);
1744         float minErr = 2;
1745         size_t fact = 1;
1746         for (size_t i = 1; i < max_mult; ++i) {
1747                 const float isc = rate * (float)i / freq; // ideal sample count
1748                 const float rsc = rintf (isc); // rounded sample count
1749                 const float err = fabsf (isc - rsc);
1750                 if (err < minErr) {
1751                         minErr = err;
1752                         fact = i;
1753                 }
1754                 if (err < precision) {
1755                         break;
1756                 }
1757         }
1758         //printf(" FIT %8.1f Hz / %8.1f Hz * %ld = %.0f (err: %e)\n", freq, rate, fact, fact * rate / freq, minErr);
1759         return fact;
1760 }
1761
1762 std::string
1763 DummyAudioPort::setup_generator (GeneratorType const g, float const samplerate, int c, int total)
1764 {
1765         std::string name;
1766         DummyPort::setup_random_number_generator();
1767         _gen_type = g;
1768
1769         switch (_gen_type) {
1770                 case PinkNoise:
1771                 case PonyNoise:
1772                 case UniformWhiteNoise:
1773                 case GaussianWhiteNoise:
1774                 case DC05:
1775                 case Silence:
1776                         break;
1777                 case Demolition:
1778                         _gen_period = 3 * samplerate;
1779                         break;
1780                 case KronekerDelta:
1781                         _gen_period = (5 + randi() % (int)(samplerate / 20.f));
1782                         name = "Delta " + format_hz (samplerate / _gen_period);
1783                         break;
1784                 case SquareWave:
1785                         _gen_period = (5 + randi() % (int)(samplerate / 20.f)) & ~1;
1786                         name = "Square " + format_hz (samplerate / _gen_period);
1787                         break;
1788                 case SineWaveOctaves:
1789                         {
1790                                 const int x = c - floor (((float)total / 2));
1791                                 float f = powf (2.f, x / 3.f) * 1000.f;
1792                                 f = std::max (10.f, std::min (samplerate *.5f, f));
1793                                 const size_t mult = fit_wave (f, samplerate);
1794                                 _gen_period = rintf ((float)mult * samplerate / f);
1795                                 name = "Sine " + format_hz (samplerate * mult / (float)_gen_period);
1796                                 _wavetable = (Sample*) malloc (_gen_period * sizeof(Sample));
1797                                 for (uint32_t i = 0 ; i < _gen_period; ++i) {
1798                                         _wavetable[i] = .12589f * sinf(2.0f * M_PI * (float)mult * (float)i / (float)(_gen_period)); // -18dBFS
1799                                 }
1800                         }
1801                         break;
1802                 case SineWave:
1803                         _gen_period = 5 + randi() % (int)(samplerate / 20.f);
1804                         name = "Sine " + format_hz (samplerate / _gen_period);
1805                         _wavetable = (Sample*) malloc (_gen_period * sizeof(Sample));
1806                         for (uint32_t i = 0 ; i < _gen_period; ++i) {
1807                                 _wavetable[i] = .12589f * sinf(2.0f * M_PI * (float)i / (float)_gen_period); // -18dBFS
1808                         }
1809                         break;
1810                 case SquareSweep:
1811                 case SquareSweepSwell:
1812                 case SineSweep:
1813                 case SineSweepSwell:
1814                         {
1815                                 _gen_period = 5 * samplerate + randi() % (int)(samplerate * 10.f);
1816                                 _gen_period &= ~1;
1817                                 _gen_perio2 = 1 | (int)ceilf (_gen_period * .89f); // Volume Swell period
1818                                 const double f_min = 20.;
1819                                 const double f_max = samplerate * .5;
1820                                 const double g_p2 = _gen_period * .5;
1821 #ifdef LINEAR_SWEEP
1822                                 const double b = (f_max - f_min) / (2. * samplerate * g_p2);
1823                                 const double a = f_min / samplerate;
1824 #else
1825                                 const double b = log (f_max / f_min) / g_p2;
1826                                 const double a = f_min / (b * samplerate);
1827 #endif
1828                                 const uint32_t g_p2i = rint(g_p2);
1829                                 _wavetable = (Sample*) malloc (_gen_period * sizeof(Sample));
1830                                 for (uint32_t i = 0 ; i < g_p2i; ++i) {
1831 #ifdef LINEAR_SWEEP
1832                                         const double phase = i * (a + b * i);
1833 #else
1834                                         const double phase = a * exp (b * i) - a;
1835 #endif
1836                                         _wavetable[i] = (float)sin (2. * M_PI * (phase - floor (phase)));
1837                                 }
1838                                 for (uint32_t i = g_p2i; i < _gen_period; ++i) {
1839                                         const uint32_t j = _gen_period - i;
1840 #ifdef LINEAR_SWEEP
1841                                         const double phase = j * (a + b * j);
1842 #else
1843                                         const double phase = a * exp (b * j) - a;
1844 #endif
1845                                         _wavetable[i] = -(float)sin (2. * M_PI * (phase - floor (phase)));
1846                                 }
1847                                 if (_gen_type == SquareSweep) {
1848                                         for (uint32_t i = 0 ; i < _gen_period; ++i) {
1849                                                 _wavetable[i] = _wavetable[i] < 0 ? -.40709f : .40709f;
1850                                         }
1851                                 }
1852                                 else if (_gen_type == SquareSweepSwell) {
1853                                         for (uint32_t i = 0 ; i < _gen_period; ++i) {
1854                                                 _wavetable[i] = _wavetable[i] < 0 ? -1 : 1;
1855                                         }
1856                                 }
1857                         }
1858                         break;
1859                 case LTC:
1860                         switch (c % 4) {
1861                                 case 0:
1862                                         _ltc = ltc_encoder_create (samplerate, 25, LTC_TV_625_50, 0);
1863                                         name = "LTC25";
1864                                         break;
1865                                 case 1:
1866                                         _ltc = ltc_encoder_create (samplerate, 30, LTC_TV_1125_60, 0);
1867                                         name = "LTC30";
1868                                         break;
1869                                 case 2:
1870                                         _ltc = ltc_encoder_create (samplerate, 30001.f / 1001.f, LTC_TV_525_60, 0);
1871                                         name = "LTC29df";
1872                                         break;
1873                                 case 3:
1874                                         _ltc = ltc_encoder_create (samplerate, 24, LTC_TV_FILM_24, 0);
1875                                         name = "LTC24";
1876                                         break;
1877                         }
1878                         _ltc_spd = 1.0;
1879                         _ltc_rand = floor((float)c / 4) * .001f;
1880                         if (c < 4) {
1881                                         name += " (locked)";
1882                         } else {
1883                                         name += " (varspd)";
1884                         }
1885                         SMPTETimecode tc;
1886                         tc.years = 0;
1887                         tc.months = 0;
1888                         tc.days = 0;
1889                         tc.hours = (3 * (c / 4)) % 24; // XXX
1890                         tc.mins = 0;
1891                         tc.secs = 0;
1892                         tc.frame = 0;
1893                         ltc_encoder_set_timecode (_ltc, &tc);
1894                                         name += string_compose ("@%1h", (int)tc.hours);
1895                         _ltcbuf = new PBD::RingBuffer<Sample> (std::max (DummyAudioBackend::max_buffer_size() * 2.f, samplerate));
1896                         break;
1897                 case Loopback:
1898                         _wavetable = (Sample*) calloc (DummyAudioBackend::max_buffer_size(), sizeof(Sample));
1899                         break;
1900         }
1901         return name;
1902 }
1903
1904 void DummyAudioPort::midi_to_wavetable (DummyMidiBuffer const * const src, size_t n_samples)
1905 {
1906         memset(_wavetable, 0, n_samples * sizeof(float));
1907         /* generate an audio spike for every midi message
1908          * to verify layency-compensation alignment
1909          * (here: midi-out playback-latency + audio-in capture-latency)
1910          */
1911         for (DummyMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
1912                 const pframes_t t = (*it)->timestamp();
1913                 assert(t < n_samples);
1914                 // somewhat arbitrary mapping for quick visual feedback
1915                 float v = -.5f;
1916                 if ((*it)->size() == 3) {
1917                         const unsigned char *d = (*it)->const_data();
1918                         if ((d[0] & 0xf0) == 0x90) { // note on
1919                                 v = .25f + d[2] / 512.f;
1920                         }
1921                         else if ((d[0] & 0xf0) == 0x80) { // note off
1922                                 v = .3f - d[2] / 640.f;
1923                         }
1924                         else if ((d[0] & 0xf0) == 0xb0) { // CC
1925                                 v = -.1f - d[2] / 256.f;
1926                         }
1927                 }
1928                 _wavetable[t] += v;
1929         }
1930 }
1931
1932 float DummyAudioPort::grandf ()
1933 {
1934         // Gaussian White Noise
1935         // http://www.musicdsp.org/archive.php?classid=0#109
1936         float x1, x2, r;
1937
1938         if (_pass) {
1939                 _pass = false;
1940                 return _rn1;
1941         }
1942
1943         do {
1944                 x1 = randf ();
1945                 x2 = randf ();
1946                 r = x1 * x1 + x2 * x2;
1947         } while ((r >= 1.0f) || (r < 1e-22f));
1948
1949         r = sqrtf (-2.f * logf (r) / r);
1950
1951         _pass = true;
1952         _rn1 = r * x2;
1953         return r * x1;
1954 }
1955
1956 /* inspired by jack-demolition by Steve Harris */
1957 static const float _demolition[] = {
1958          0.0f,             /* special case - 0dbFS white noise */
1959          0.0f,             /* zero, may cause denomrals following a signal */
1960          0.73 / 1e45,      /* very small - should be denormal when floated */
1961          3.7f,             /* arbitrary number > 0dBFS */
1962         -4.3f,             /* arbitrary negative number > 0dBFS */
1963          4294967395.0f,    /* 2^16 + 100 */
1964         -4294967395.0f,
1965          3.402823466e+38F, /* HUGE, HUGEVALF, non-inf number */
1966          INFINITY,         /* +inf */
1967         -INFINITY,         /* -inf */
1968         -NAN,              /* -nan */
1969          NAN,              /*  nan */
1970          0.0f,             /* some silence to check for recovery */
1971 };
1972
1973 void DummyAudioPort::generate (const pframes_t n_samples)
1974 {
1975         Glib::Threads::Mutex::Lock lm (generator_lock);
1976         if (_gen_cycle) {
1977                 return;
1978         }
1979
1980         switch (_gen_type) {
1981                 case Silence:
1982                         memset (_buffer, 0, n_samples * sizeof (Sample));
1983                         break;
1984                 case DC05:
1985                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1986                                 _buffer[i] = 0.5f;
1987                         }
1988                         break;
1989                 case Demolition:
1990                         switch (_gen_count2) {
1991                                 case 0: // noise
1992                                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1993                                                 _buffer[i] = randf();
1994                                         }
1995                                         break;
1996                                 default:
1997                                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1998                                                 _buffer[i] = _demolition [_gen_count2];
1999                                         }
2000                                         break;
2001                         }
2002                         _gen_offset += n_samples;
2003                         if (_gen_offset > _gen_period) {
2004                                 _gen_offset = 0;
2005                                 _gen_count2 = (_gen_count2 + 1) % (sizeof (_demolition) / sizeof (float));
2006                         }
2007                         break;
2008                 case SquareWave:
2009                         assert(_gen_period > 0);
2010                         for (pframes_t i = 0 ; i < n_samples; ++i) {
2011                                 if (_gen_offset < _gen_period * .5f) {
2012                                         _buffer[i] =  .40709f; // -6dBFS
2013                                 } else {
2014                                         _buffer[i] = -.40709f;
2015                                 }
2016                                 _gen_offset = (_gen_offset + 1) % _gen_period;
2017                         }
2018                         break;
2019                 case KronekerDelta:
2020                         assert(_gen_period > 0);
2021                         memset (_buffer, 0, n_samples * sizeof (Sample));
2022                         for (pframes_t i = 0; i < n_samples; ++i) {
2023                                 if (_gen_offset == 0) {
2024                                         _buffer[i] = 1.0f;
2025                                 }
2026                                 _gen_offset = (_gen_offset + 1) % _gen_period;
2027                         }
2028                         break;
2029                 case SineSweepSwell:
2030                 case SquareSweepSwell:
2031                         assert(_wavetable && _gen_period > 0);
2032                         {
2033                                 const float vols = 2.f / (float)_gen_perio2;
2034                                 for (pframes_t i = 0; i < n_samples; ++i) {
2035                                         const float g = fabsf (_gen_count2 * vols - 1.f);
2036                                         _buffer[i] = g * _wavetable[_gen_offset];
2037                                         _gen_offset = (_gen_offset + 1) % _gen_period;
2038                                         _gen_count2 = (_gen_count2 + 1) % _gen_perio2;
2039                                 }
2040                         }
2041                         break;
2042                 case Loopback:
2043                         memcpy((void*)_buffer, (void*)_wavetable, n_samples * sizeof(Sample));
2044                         break;
2045                 case SineWave:
2046                 case SineWaveOctaves:
2047                 case SineSweep:
2048                 case SquareSweep:
2049                         assert(_wavetable && _gen_period > 0);
2050                         {
2051                                 pframes_t written = 0;
2052                                 while (written < n_samples) {
2053                                         const uint32_t remain = n_samples - written;
2054                                         const uint32_t to_copy = std::min(remain, _gen_period - _gen_offset);
2055                                         memcpy((void*)&_buffer[written],
2056                                                         (void*)&_wavetable[_gen_offset],
2057                                                         to_copy * sizeof(Sample));
2058                                         written += to_copy;
2059                                         _gen_offset = (_gen_offset + to_copy) % _gen_period;
2060                                 }
2061                         }
2062                         break;
2063                 case UniformWhiteNoise:
2064                         for (pframes_t i = 0 ; i < n_samples; ++i) {
2065                                 _buffer[i] = .158489f * randf();
2066                         }
2067                         break;
2068                 case GaussianWhiteNoise:
2069                         for (pframes_t i = 0 ; i < n_samples; ++i) {
2070                                 _buffer[i] = .089125f * grandf();
2071                         }
2072                         break;
2073                 case PinkNoise:
2074                         for (pframes_t i = 0 ; i < n_samples; ++i) {
2075                                 // Paul Kellet's refined method
2076                                 // http://www.musicdsp.org/files/pink.txt
2077                                 // NB. If 'white' consists of uniform random numbers,
2078                                 // the pink noise will have an almost gaussian distribution.
2079                                 const float white = .0498f * randf ();
2080                                 _b0 = .99886f * _b0 + white * .0555179f;
2081                                 _b1 = .99332f * _b1 + white * .0750759f;
2082                                 _b2 = .96900f * _b2 + white * .1538520f;
2083                                 _b3 = .86650f * _b3 + white * .3104856f;
2084                                 _b4 = .55000f * _b4 + white * .5329522f;
2085                                 _b5 = -.7616f * _b5 - white * .0168980f;
2086                                 _buffer[i] = _b0 + _b1 + _b2 + _b3 + _b4 + _b5 + _b6 + white * 0.5362f;
2087                                 _b6 = white * 0.115926f;
2088                         }
2089                         break;
2090                 case PonyNoise:
2091                         for (pframes_t i = 0 ; i < n_samples; ++i) {
2092                                 const float white = 0.0498f * randf ();
2093                                 // Paul Kellet's economy method
2094                                 // http://www.musicdsp.org/files/pink.txt
2095                                 _b0 = 0.99765f * _b0 + white * 0.0990460f;
2096                                 _b1 = 0.96300f * _b1 + white * 0.2965164f;
2097                                 _b2 = 0.57000f * _b2 + white * 1.0526913f;
2098                                 _buffer[i] = _b0 + _b1 + _b2 + white * 0.1848f;
2099                         }
2100                         break;
2101                 case LTC:
2102                         while (_ltcbuf->read_space () < n_samples) {
2103                                 // we should pre-allocate (or add a zero-copy libltc API), whatever.
2104                                 ltcsnd_sample_t* enc_buf = (ltcsnd_sample_t*) malloc (ltc_encoder_get_buffersize (_ltc) * sizeof (ltcsnd_sample_t));
2105                                 for (int byteCnt = 0; byteCnt < 10; byteCnt++) {
2106                                         if (_ltc_rand != 0.f) {
2107                                                 _ltc_spd += randf () * _ltc_rand;
2108                                                 _ltc_spd = std::min (1.5f, std::max (0.5f, _ltc_spd));
2109                                         }
2110                                         ltc_encoder_encode_byte (_ltc, byteCnt, _ltc_spd);
2111                                         const int len = ltc_encoder_get_buffer (_ltc, enc_buf);
2112                                         for (int i = 0; i < len; ++i) {
2113                                                 const float v1 = enc_buf[i] - 128;
2114                                                 Sample v = v1 * 0.002;
2115                                                 _ltcbuf->write (&v, 1);
2116                                         }
2117                                 }
2118                                 ltc_encoder_inc_timecode (_ltc);
2119                                 free (enc_buf);
2120                         }
2121                         _ltcbuf->read (_buffer, n_samples);
2122                         break;
2123         }
2124         _gen_cycle = true;
2125 }
2126
2127 void* DummyAudioPort::get_buffer (pframes_t n_samples)
2128 {
2129         if (is_input ()) {
2130                 const std::set<DummyPort *>& connections = get_connections ();
2131                 std::set<DummyPort*>::const_iterator it = connections.begin ();
2132                 if (it == connections.end ()) {
2133                         memset (_buffer, 0, n_samples * sizeof (Sample));
2134                 } else {
2135                         DummyAudioPort * source = static_cast<DummyAudioPort*>(*it);
2136                         assert (source && source->is_output ());
2137                         if (source->is_physical() && source->is_terminal()) {
2138                                 source->get_buffer(n_samples); // generate signal.
2139                         }
2140                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
2141                         while (++it != connections.end ()) {
2142                                 source = static_cast<DummyAudioPort*>(*it);
2143                                 assert (source && source->is_output ());
2144                                 Sample* dst = buffer ();
2145                                 if (source->is_physical() && source->is_terminal()) {
2146                                         source->get_buffer(n_samples); // generate signal.
2147                                 }
2148                                 const Sample* src = source->const_buffer ();
2149                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
2150                                         *dst += *src;
2151                                 }
2152                         }
2153                 }
2154         } else if (is_output () && is_physical () && is_terminal()) {
2155                 if (!_gen_cycle) {
2156                         generate(n_samples);
2157                 }
2158         }
2159         return _buffer;
2160 }
2161
2162
2163 DummyMidiPort::DummyMidiPort (DummyAudioBackend &b, const std::string& name, PortFlags flags)
2164         : DummyPort (b, name, flags)
2165         , _midi_seq_spb (0)
2166         , _midi_seq_time (0)
2167         , _midi_seq_pos (0)
2168 {
2169         _buffer.clear ();
2170         _loopback.clear ();
2171 }
2172
2173 DummyMidiPort::~DummyMidiPort () {
2174         _buffer.clear ();
2175         _loopback.clear ();
2176 }
2177
2178 struct MidiEventSorter {
2179         bool operator() (const boost::shared_ptr<DummyMidiEvent>& a, const boost::shared_ptr<DummyMidiEvent>& b) {
2180                 return *a < *b;
2181         }
2182 };
2183
2184 void DummyMidiPort::set_loopback (DummyMidiBuffer const * const src)
2185 {
2186         _loopback.clear ();
2187         for (DummyMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
2188                 _loopback.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (**it)));
2189         }
2190 }
2191
2192 std::string
2193 DummyMidiPort::setup_generator (int seq_id, const float sr)
2194 {
2195         DummyPort::setup_random_number_generator();
2196         _midi_seq_dat = DummyMidiData::sequences[seq_id % NUM_MIDI_EVENT_GENERATORS];
2197         _midi_seq_spb = sr * .5f; // 120 BPM, beat_time 1.0 per beat.
2198         _midi_seq_pos = 0;
2199         _midi_seq_time = 0;
2200         return DummyMidiData::sequence_names[seq_id];
2201 }
2202
2203 void DummyMidiPort::midi_generate (const pframes_t n_samples)
2204 {
2205         Glib::Threads::Mutex::Lock lm (generator_lock);
2206         if (_gen_cycle) {
2207                 return;
2208         }
2209
2210         _buffer.clear ();
2211         _gen_cycle = true;
2212
2213         if (_midi_seq_spb == 0 || !_midi_seq_dat) {
2214                 for (DummyMidiBuffer::const_iterator it = _loopback.begin (); it != _loopback.end (); ++it) {
2215                         _buffer.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (**it)));
2216                 }
2217                 return;
2218         }
2219
2220         while (1) {
2221                 const int32_t ev_beat_time = _midi_seq_dat[_midi_seq_pos].beat_time * _midi_seq_spb - _midi_seq_time;
2222                 if (ev_beat_time < 0) {
2223                         break;
2224                 }
2225                 if ((pframes_t) ev_beat_time >= n_samples) {
2226                         break;
2227                 }
2228                 _buffer.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (
2229                                                 ev_beat_time,
2230                                                 _midi_seq_dat[_midi_seq_pos].event,
2231                                                 _midi_seq_dat[_midi_seq_pos].size
2232                                                 )));
2233                 ++_midi_seq_pos;
2234
2235                 if (_midi_seq_dat[_midi_seq_pos].event[0] == 0xff && _midi_seq_dat[_midi_seq_pos].event[1] == 0xff) {
2236                         _midi_seq_time -= _midi_seq_dat[_midi_seq_pos].beat_time * _midi_seq_spb;
2237                         _midi_seq_pos = 0;
2238                 }
2239         }
2240         _midi_seq_time += n_samples;
2241 }
2242
2243
2244 void* DummyMidiPort::get_buffer (pframes_t n_samples)
2245 {
2246         if (is_input ()) {
2247                 _buffer.clear ();
2248                 const std::set<DummyPort*>& connections = get_connections ();
2249                 for (std::set<DummyPort*>::const_iterator i = connections.begin ();
2250                                 i != connections.end ();
2251                                 ++i) {
2252                         DummyMidiPort * source = static_cast<DummyMidiPort*>(*i);
2253                         if (source->is_physical() && source->is_terminal()) {
2254                                 source->get_buffer(n_samples); // generate signal.
2255                         }
2256                         const DummyMidiBuffer *src = source->const_buffer ();
2257                         for (DummyMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
2258                                 _buffer.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (**it)));
2259                         }
2260                 }
2261                 std::stable_sort (_buffer.begin (), _buffer.end (), MidiEventSorter());
2262         } else if (is_output () && is_physical () && is_terminal()) {
2263                 if (!_gen_cycle) {
2264                         midi_generate(n_samples);
2265                 }
2266         }
2267         return &_buffer;
2268 }
2269
2270 DummyMidiEvent::DummyMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
2271         : _size (size)
2272         , _timestamp (timestamp)
2273         , _data (0)
2274 {
2275         if (size > 0) {
2276                 _data = (uint8_t*) malloc (size);
2277                 memcpy (_data, data, size);
2278         }
2279 }
2280
2281 DummyMidiEvent::DummyMidiEvent (const DummyMidiEvent& other)
2282         : _size (other.size ())
2283         , _timestamp (other.timestamp ())
2284         , _data (0)
2285 {
2286         if (other.size () && other.const_data ()) {
2287                 _data = (uint8_t*) malloc (other.size ());
2288                 memcpy (_data, other.const_data (), other.size ());
2289         }
2290 };
2291
2292 DummyMidiEvent::~DummyMidiEvent () {
2293         free (_data);
2294 };