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