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