Fix an ambiguous call to 'floor()'
[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 true;
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         _dsp_load_calc.set_max_time (_samplerate, _samples_per_period);
461
462         if (engine.reestablish_ports ()) {
463                 PBD::error << _("DummyAudioBackend: Could not re-establish ports.") << endmsg;
464                 stop ();
465                 return PortReconnectError;
466         }
467
468         engine.reconnect_ports ();
469         _port_change_flag = false;
470
471         if (pthread_create (&_main_thread, NULL, pthread_process, this)) {
472                 PBD::error << _("DummyAudioBackend: cannot start.") << endmsg;
473         }
474
475         int timeout = 5000;
476         while (!_running && --timeout > 0) { Glib::usleep (1000); }
477
478         if (timeout == 0 || !_running) {
479                 PBD::error << _("DummyAudioBackend: failed to start process thread.") << endmsg;
480                 return ProcessThreadStartError;
481         }
482
483         return NoError;
484 }
485
486 int
487 DummyAudioBackend::stop ()
488 {
489         void *status;
490         if (!_running) {
491                 return 0;
492         }
493
494         _running = false;
495         if (pthread_join (_main_thread, &status)) {
496                 PBD::error << _("DummyAudioBackend: failed to terminate.") << endmsg;
497                 return -1;
498         }
499         unregister_ports();
500         return 0;
501 }
502
503 int
504 DummyAudioBackend::freewheel (bool onoff)
505 {
506         _freewheeling = onoff;
507         return 0;
508 }
509
510 float
511 DummyAudioBackend::dsp_load () const
512 {
513         return 100.f * _dsp_load;
514 }
515
516 size_t
517 DummyAudioBackend::raw_buffer_size (DataType t)
518 {
519         switch (t) {
520                 case DataType::AUDIO:
521                         return _samples_per_period * sizeof(Sample);
522                 case DataType::MIDI:
523                         return _max_buffer_size; // XXX not really limited
524         }
525         return 0;
526 }
527
528 /* Process time */
529 framepos_t
530 DummyAudioBackend::sample_time ()
531 {
532         return _processed_samples;
533 }
534
535 framepos_t
536 DummyAudioBackend::sample_time_at_cycle_start ()
537 {
538         return _processed_samples;
539 }
540
541 pframes_t
542 DummyAudioBackend::samples_since_cycle_start ()
543 {
544         return 0;
545 }
546
547
548 void *
549 DummyAudioBackend::dummy_process_thread (void *arg)
550 {
551         ThreadData* td = reinterpret_cast<ThreadData*> (arg);
552         boost::function<void ()> f = td->f;
553         delete td;
554         f ();
555         return 0;
556 }
557
558 int
559 DummyAudioBackend::create_process_thread (boost::function<void()> func)
560 {
561         pthread_t thread_id;
562         pthread_attr_t attr;
563         size_t stacksize = 100000;
564
565         pthread_attr_init (&attr);
566         pthread_attr_setstacksize (&attr, stacksize);
567         ThreadData* td = new ThreadData (this, func, stacksize);
568
569         if (pthread_create (&thread_id, &attr, dummy_process_thread, td)) {
570                 PBD::error << _("AudioEngine: cannot create process thread.") << endmsg;
571                 pthread_attr_destroy (&attr);
572                 return -1;
573         }
574         pthread_attr_destroy (&attr);
575
576         _threads.push_back (thread_id);
577         return 0;
578 }
579
580 int
581 DummyAudioBackend::join_process_threads ()
582 {
583         int rv = 0;
584
585         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
586         {
587                 void *status;
588                 if (pthread_join (*i, &status)) {
589                         PBD::error << _("AudioEngine: cannot terminate process thread.") << endmsg;
590                         rv -= 1;
591                 }
592         }
593         _threads.clear ();
594         return rv;
595 }
596
597 bool
598 DummyAudioBackend::in_process_thread ()
599 {
600         if (pthread_equal (_main_thread, pthread_self()) != 0) {
601                 return true;
602         }
603
604         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
605         {
606                 if (pthread_equal (*i, pthread_self ()) != 0) {
607                         return true;
608                 }
609         }
610         return false;
611 }
612
613 uint32_t
614 DummyAudioBackend::process_thread_count ()
615 {
616         return _threads.size ();
617 }
618
619 void
620 DummyAudioBackend::update_latencies ()
621 {
622         // trigger latency callback in RT thread (locked graph)
623         port_connect_add_remove_callback();
624 }
625
626 /* PORTENGINE API */
627
628 void*
629 DummyAudioBackend::private_handle () const
630 {
631         return NULL;
632 }
633
634 const std::string&
635 DummyAudioBackend::my_name () const
636 {
637         return _instance_name;
638 }
639
640 bool
641 DummyAudioBackend::available () const
642 {
643         return _running;
644 }
645
646 uint32_t
647 DummyAudioBackend::port_name_size () const
648 {
649         return 256;
650 }
651
652 int
653 DummyAudioBackend::set_port_name (PortEngine::PortHandle port, const std::string& name)
654 {
655         std::string newname (_instance_name + ":" + name);
656
657         if (!valid_port (port)) {
658                 PBD::error << _("DummyBackend::set_port_name: Invalid Port(s)") << endmsg;
659                 return -1;
660         }
661
662         if (find_port (newname)) {
663                 PBD::error << _("DummyBackend::set_port_name: Port with given name already exists") << endmsg;
664                 return -1;
665         }
666
667         DummyPort* p = static_cast<DummyPort*>(port);
668         _portmap.erase (p->name());
669         _portmap.insert (make_pair (newname, p));
670         return p->set_name (newname);
671 }
672
673 std::string
674 DummyAudioBackend::get_port_name (PortEngine::PortHandle port) const
675 {
676         if (!valid_port (port)) {
677                 PBD::error << _("DummyBackend::get_port_name: Invalid Port(s)") << endmsg;
678                 return std::string ();
679         }
680         return static_cast<DummyPort*>(port)->name ();
681 }
682
683 int
684 DummyAudioBackend::get_port_property (PortHandle port, const std::string& key, std::string& value, std::string& type) const
685 {
686         if (!valid_port (port)) {
687                 PBD::warning << _("DummyBackend::get_port_property: Invalid Port(s)") << endmsg;
688                 return -1;
689         }
690         if (key == "http://jackaudio.org/metadata/pretty-name") {
691                 type = "";
692                 value = static_cast<DummyPort*>(port)->pretty_name ();
693                 if (!value.empty()) {
694                         return 0;
695                 }
696         }
697         return -1;
698 }
699
700 int
701 DummyAudioBackend::set_port_property (PortHandle port, const std::string& key, const std::string& value, const std::string& type)
702 {
703         if (!valid_port (port)) {
704                 PBD::warning << _("DummyBackend::set_port_property: Invalid Port(s)") << endmsg;
705                 return -1;
706         }
707         if (key == "http://jackaudio.org/metadata/pretty-name" && type.empty ()) {
708                 static_cast<DummyPort*>(port)->set_pretty_name (value);
709                 return 0;
710         }
711         return -1;
712 }
713
714 PortEngine::PortHandle
715 DummyAudioBackend::get_port_by_name (const std::string& name) const
716 {
717         PortHandle port = (PortHandle) find_port (name);
718         return port;
719 }
720
721 int
722 DummyAudioBackend::get_ports (
723                 const std::string& port_name_pattern,
724                 DataType type, PortFlags flags,
725                 std::vector<std::string>& port_names) const
726 {
727         int rv = 0;
728         regex_t port_regex;
729         bool use_regexp = false;
730         if (port_name_pattern.size () > 0) {
731                 if (!regcomp (&port_regex, port_name_pattern.c_str (), REG_EXTENDED|REG_NOSUB)) {
732                         use_regexp = true;
733                 }
734         }
735
736         for (PortIndex::const_iterator i = _ports.begin (); i != _ports.end (); ++i) {
737                 DummyPort* port = *i;
738                 if ((port->type () == type) && flags == (port->flags () & flags)) {
739                         if (!use_regexp || !regexec (&port_regex, port->name ().c_str (), 0, NULL, 0)) {
740                                 port_names.push_back (port->name ());
741                                 ++rv;
742                         }
743                 }
744         }
745         if (use_regexp) {
746                 regfree (&port_regex);
747         }
748         return rv;
749 }
750
751 DataType
752 DummyAudioBackend::port_data_type (PortEngine::PortHandle port) const
753 {
754         if (!valid_port (port)) {
755                 return DataType::NIL;
756         }
757         return static_cast<DummyPort*>(port)->type ();
758 }
759
760 PortEngine::PortHandle
761 DummyAudioBackend::register_port (
762                 const std::string& name,
763                 ARDOUR::DataType type,
764                 ARDOUR::PortFlags flags)
765 {
766         if (name.size () == 0) { return 0; }
767         if (flags & IsPhysical) { return 0; }
768         if (!_running) {
769                 PBD::info << _("DummyBackend::register_port: Engine is not running.") << endmsg;
770         }
771         return add_port (_instance_name + ":" + name, type, flags);
772 }
773
774 PortEngine::PortHandle
775 DummyAudioBackend::add_port (
776                 const std::string& name,
777                 ARDOUR::DataType type,
778                 ARDOUR::PortFlags flags)
779 {
780         assert(name.size ());
781         if (find_port (name)) {
782                 PBD::error << _("DummyBackend::register_port: Port already exists:")
783                                 << " (" << name << ")" << endmsg;
784                 return 0;
785         }
786         DummyPort* port = NULL;
787         switch (type) {
788                 case DataType::AUDIO:
789                         port = new DummyAudioPort (*this, name, flags);
790                         break;
791                 case DataType::MIDI:
792                         port = new DummyMidiPort (*this, name, flags);
793                         break;
794                 default:
795                         PBD::error << _("DummyBackend::register_port: Invalid Data Type.") << endmsg;
796                         return 0;
797         }
798
799         _ports.insert (port);
800         _portmap.insert (make_pair (name, port));
801
802         return port;
803 }
804
805 void
806 DummyAudioBackend::unregister_port (PortEngine::PortHandle port_handle)
807 {
808         if (!_running) {
809                 PBD::info << _("DummyBackend::unregister_port: Engine is not running.") << endmsg;
810                 assert (!valid_port (port_handle));
811                 return;
812         }
813         DummyPort* port = static_cast<DummyPort*>(port_handle);
814         PortIndex::iterator i = std::find (_ports.begin(), _ports.end(), static_cast<DummyPort*>(port_handle));
815         if (i == _ports.end ()) {
816                 PBD::error << _("DummyBackend::unregister_port: Failed to find port") << endmsg;
817                 return;
818         }
819         disconnect_all(port_handle);
820         _portmap.erase (port->name());
821         _ports.erase (i);
822         delete port;
823 }
824
825 int
826 DummyAudioBackend::register_system_ports()
827 {
828         LatencyRange lr;
829         enum DummyAudioPort::GeneratorType gt;
830         if (_device == _("Uniform White Noise")) {
831                 gt = DummyAudioPort::UniformWhiteNoise;
832         } else if (_device == _("Gaussian White Noise")) {
833                 gt = DummyAudioPort::GaussianWhiteNoise;
834         } else if (_device == _("Pink Noise")) {
835                 gt = DummyAudioPort::PinkNoise;
836         } else if (_device == _("Pink Noise (low CPU)")) {
837                 gt = DummyAudioPort::PonyNoise;
838         } else if (_device == _("Sine Wave")) {
839                 gt = DummyAudioPort::SineWave;
840         } else if (_device == _("Sine Wave 1K, 1/3 Oct")) {
841                 gt = DummyAudioPort::SineWaveOctaves;
842         } else if (_device == _("Square Wave")) {
843                 gt = DummyAudioPort::SquareWave;
844         } else if (_device == _("Impulses")) {
845                 gt = DummyAudioPort::KronekerDelta;
846         } else if (_device == _("Sine Sweep")) {
847                 gt = DummyAudioPort::SineSweep;
848         } else if (_device == _("Sine Sweep Swell")) {
849                 gt = DummyAudioPort::SineSweepSwell;
850         } else if (_device == _("Square Sweep")) {
851                 gt = DummyAudioPort::SquareSweep;
852         } else if (_device == _("Square Sweep Swell")) {
853                 gt = DummyAudioPort::SquareSweepSwell;
854         } else if (_device == _("LTC")) {
855                 gt = DummyAudioPort::LTC;
856         } else if (_device == _("Loopback")) {
857                 gt = DummyAudioPort::Loopback;
858         } else if (_device == _("Demolition")) {
859                 gt = DummyAudioPort::Demolition;
860         } else if (_device == _("DC -6dBFS (+.5)")) {
861                 gt = DummyAudioPort::DC05;
862         } else {
863                 gt = DummyAudioPort::Silence;
864         }
865
866         if (_midi_mode == MidiToAudio) {
867                 gt = DummyAudioPort::Loopback;
868         }
869
870         const int a_ins = _n_inputs > 0 ? _n_inputs : 8;
871         const int a_out = _n_outputs > 0 ? _n_outputs : 8;
872         const int m_ins = _n_midi_inputs == UINT_MAX ? 0 : _n_midi_inputs;
873         const int m_out = _n_midi_outputs == UINT_MAX ? a_ins : _n_midi_outputs;
874
875
876         /* audio ports */
877         lr.min = lr.max = _systemic_input_latency;
878         for (int i = 1; i <= a_ins; ++i) {
879                 char tmp[64];
880                 snprintf(tmp, sizeof(tmp), "system:capture_%d", i);
881                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
882                 if (!p) return -1;
883                 set_latency_range (p, false, lr);
884                 _system_inputs.push_back (static_cast<DummyAudioPort*>(p));
885                 std::string name = static_cast<DummyAudioPort*>(p)->setup_generator (gt, _samplerate, i - 1, a_ins);
886                 if (!name.empty ()) {
887                         static_cast<DummyAudioPort*>(p)->set_pretty_name (name);
888                 }
889         }
890
891         lr.min = lr.max = _systemic_output_latency;
892         for (int i = 1; i <= a_out; ++i) {
893                 char tmp[64];
894                 snprintf(tmp, sizeof(tmp), "system:playback_%d", i);
895                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
896                 if (!p) return -1;
897                 set_latency_range (p, true, lr);
898                 _system_outputs.push_back (static_cast<DummyAudioPort*>(p));
899         }
900
901         /* midi ports */
902         lr.min = lr.max = _systemic_input_latency;
903         for (int i = 0; i < m_ins; ++i) {
904                 char tmp[64];
905                 snprintf(tmp, sizeof(tmp), "system:midi_capture_%d", i+1);
906                 PortHandle p = add_port(std::string(tmp), DataType::MIDI, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
907                 if (!p) return -1;
908                 set_latency_range (p, false, lr);
909                 _system_midi_in.push_back (static_cast<DummyMidiPort*>(p));
910                 if (_midi_mode == MidiGenerator) {
911                         std::string name = static_cast<DummyMidiPort*>(p)->setup_generator (i % NUM_MIDI_EVENT_GENERATORS, _samplerate);
912                         if (!name.empty ()) {
913                                 static_cast<DummyMidiPort*>(p)->set_pretty_name (name);
914                         }
915                 }
916         }
917
918         lr.min = lr.max = _systemic_output_latency;
919         for (int i = 1; i <= m_out; ++i) {
920                 char tmp[64];
921                 snprintf(tmp, sizeof(tmp), "system:midi_playback_%d", i);
922                 PortHandle p = add_port(std::string(tmp), DataType::MIDI, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
923                 if (!p) return -1;
924                 set_latency_range (p, true, lr);
925                 _system_midi_out.push_back (static_cast<DummyMidiPort*>(p));
926
927                 if (_device == _("Loopback") && _midi_mode == MidiToAudio) {
928                         std::stringstream ss;
929                         ss << "Midi2Audio";
930                         for (int apc = 0; apc < (int)_system_inputs.size(); ++apc) {
931                                 if ((apc % m_out) + 1 == i) {
932                                         ss << " >" << (apc + 1);
933                                 }
934                         }
935                         static_cast<DummyMidiPort*>(p)->set_pretty_name (ss.str());
936                 }
937         }
938         return 0;
939 }
940
941 void
942 DummyAudioBackend::unregister_ports (bool system_only)
943 {
944         _system_inputs.clear();
945         _system_outputs.clear();
946         _system_midi_in.clear();
947         _system_midi_out.clear();
948
949         for (PortIndex::iterator i = _ports.begin (); i != _ports.end ();) {
950                 PortIndex::iterator cur = i++;
951                 DummyPort* port = *cur;
952                 if (! system_only || (port->is_physical () && port->is_terminal ())) {
953                         port->disconnect_all ();
954                         _portmap.erase (port->name());
955                         delete port;
956                         _ports.erase (cur);
957                 }
958         }
959 }
960
961 int
962 DummyAudioBackend::connect (const std::string& src, const std::string& dst)
963 {
964         DummyPort* src_port = find_port (src);
965         DummyPort* dst_port = find_port (dst);
966
967         if (!src_port) {
968                 PBD::error << _("DummyBackend::connect: Invalid Source port:")
969                                 << " (" << src <<")" << endmsg;
970                 return -1;
971         }
972         if (!dst_port) {
973                 PBD::error << _("DummyBackend::connect: Invalid Destination port:")
974                         << " (" << dst <<")" << endmsg;
975                 return -1;
976         }
977         return src_port->connect (dst_port);
978 }
979
980 int
981 DummyAudioBackend::disconnect (const std::string& src, const std::string& dst)
982 {
983         DummyPort* src_port = find_port (src);
984         DummyPort* dst_port = find_port (dst);
985
986         if (!src_port || !dst_port) {
987                 PBD::error << _("DummyBackend::disconnect: Invalid Port(s)") << endmsg;
988                 return -1;
989         }
990         return src_port->disconnect (dst_port);
991 }
992
993 int
994 DummyAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
995 {
996         DummyPort* dst_port = find_port (dst);
997         if (!valid_port (src)) {
998                 PBD::error << _("DummyBackend::connect: Invalid Source Port Handle") << endmsg;
999                 return -1;
1000         }
1001         if (!dst_port) {
1002                 PBD::error << _("DummyBackend::connect: Invalid Destination Port")
1003                         << " (" << dst << ")" << endmsg;
1004                 return -1;
1005         }
1006         return static_cast<DummyPort*>(src)->connect (dst_port);
1007 }
1008
1009 int
1010 DummyAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
1011 {
1012         DummyPort* dst_port = find_port (dst);
1013         if (!valid_port (src) || !dst_port) {
1014                 PBD::error << _("DummyBackend::disconnect: Invalid Port(s)") << endmsg;
1015                 return -1;
1016         }
1017         return static_cast<DummyPort*>(src)->disconnect (dst_port);
1018 }
1019
1020 int
1021 DummyAudioBackend::disconnect_all (PortEngine::PortHandle port)
1022 {
1023         if (!valid_port (port)) {
1024                 PBD::error << _("DummyBackend::disconnect_all: Invalid Port") << endmsg;
1025                 return -1;
1026         }
1027         static_cast<DummyPort*>(port)->disconnect_all ();
1028         return 0;
1029 }
1030
1031 bool
1032 DummyAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
1033 {
1034         if (!valid_port (port)) {
1035                 PBD::error << _("DummyBackend::disconnect_all: Invalid Port") << endmsg;
1036                 return false;
1037         }
1038         return static_cast<DummyPort*>(port)->is_connected ();
1039 }
1040
1041 bool
1042 DummyAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
1043 {
1044         DummyPort* dst_port = find_port (dst);
1045 #ifndef NDEBUG
1046         if (!valid_port (src) || !dst_port) {
1047                 PBD::error << _("DummyBackend::connected_to: Invalid Port") << endmsg;
1048                 return false;
1049         }
1050 #endif
1051         return static_cast<DummyPort*>(src)->is_connected (dst_port);
1052 }
1053
1054 bool
1055 DummyAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
1056 {
1057         if (!valid_port (port)) {
1058                 PBD::error << _("DummyBackend::physically_connected: Invalid Port") << endmsg;
1059                 return false;
1060         }
1061         return static_cast<DummyPort*>(port)->is_physically_connected ();
1062 }
1063
1064 int
1065 DummyAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
1066 {
1067         if (!valid_port (port)) {
1068                 PBD::error << _("DummyBackend::get_connections: Invalid Port") << endmsg;
1069                 return -1;
1070         }
1071
1072         assert (0 == names.size ());
1073
1074         const std::set<DummyPort*>& connected_ports = static_cast<DummyPort*>(port)->get_connections ();
1075
1076         for (std::set<DummyPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
1077                 names.push_back ((*i)->name ());
1078         }
1079
1080         return (int)names.size ();
1081 }
1082
1083 /* MIDI */
1084 int
1085 DummyAudioBackend::midi_event_get (
1086                 pframes_t& timestamp,
1087                 size_t& size, uint8_t** buf, void* port_buffer,
1088                 uint32_t event_index)
1089 {
1090         assert (buf && port_buffer);
1091         DummyMidiBuffer& source = * static_cast<DummyMidiBuffer*>(port_buffer);
1092         if (event_index >= source.size ()) {
1093                 return -1;
1094         }
1095         DummyMidiEvent * const event = source[event_index].get ();
1096
1097         timestamp = event->timestamp ();
1098         size = event->size ();
1099         *buf = event->data ();
1100         return 0;
1101 }
1102
1103 int
1104 DummyAudioBackend::midi_event_put (
1105                 void* port_buffer,
1106                 pframes_t timestamp,
1107                 const uint8_t* buffer, size_t size)
1108 {
1109         assert (buffer && port_buffer);
1110         DummyMidiBuffer& dst = * static_cast<DummyMidiBuffer*>(port_buffer);
1111         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
1112                 // nevermind, ::get_buffer() sorts events, but always print warning
1113                 fprintf (stderr, "DummyMidiBuffer: it's too late for this event %d > %d.\n", (pframes_t)dst.back ()->timestamp (), timestamp);
1114         }
1115         dst.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (timestamp, buffer, size)));
1116 #if 0 // DEBUG MIDI EVENTS
1117         printf("DummyAudioBackend::midi_event_put %d, %zu: ", timestamp, size);
1118         for (size_t xx = 0; xx < size; ++xx) {
1119                 printf(" %02x", buffer[xx]);
1120         }
1121         printf("\n");
1122 #endif
1123         return 0;
1124 }
1125
1126 uint32_t
1127 DummyAudioBackend::get_midi_event_count (void* port_buffer)
1128 {
1129         assert (port_buffer);
1130         return static_cast<DummyMidiBuffer*>(port_buffer)->size ();
1131 }
1132
1133 void
1134 DummyAudioBackend::midi_clear (void* port_buffer)
1135 {
1136         assert (port_buffer);
1137         DummyMidiBuffer * buf = static_cast<DummyMidiBuffer*>(port_buffer);
1138         assert (buf);
1139         buf->clear ();
1140 }
1141
1142 /* Monitoring */
1143
1144 bool
1145 DummyAudioBackend::can_monitor_input () const
1146 {
1147         return false;
1148 }
1149
1150 int
1151 DummyAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1152 {
1153         return -1;
1154 }
1155
1156 int
1157 DummyAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1158 {
1159         return -1;
1160 }
1161
1162 bool
1163 DummyAudioBackend::monitoring_input (PortEngine::PortHandle)
1164 {
1165         return false;
1166 }
1167
1168 /* Latency management */
1169
1170 void
1171 DummyAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1172 {
1173         if (!valid_port (port)) {
1174                 PBD::error << _("DummyPort::set_latency_range (): invalid port.") << endmsg;
1175         }
1176         static_cast<DummyPort*>(port)->set_latency_range (latency_range, for_playback);
1177 }
1178
1179 LatencyRange
1180 DummyAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1181 {
1182         LatencyRange r;
1183         if (!valid_port (port)) {
1184                 PBD::error << _("DummyPort::get_latency_range (): invalid port.") << endmsg;
1185                 r.min = 0;
1186                 r.max = 0;
1187                 return r;
1188         }
1189         DummyPort *p =  static_cast<DummyPort*>(port);
1190         assert(p);
1191
1192         r = p->latency_range (for_playback);
1193         if (p->is_physical() && p->is_terminal()) {
1194                 if (p->is_input() && for_playback) {
1195                         const size_t l_in = _samples_per_period * .25;
1196                         r.min += l_in;
1197                         r.max += l_in;
1198                 }
1199                 if (p->is_output() && !for_playback) {
1200                         /* with 'Loopback' there is exactly once cycle latency, divide it between In + Out; */
1201                         const size_t l_in = _samples_per_period * .25;
1202                         const size_t l_out = _samples_per_period - l_in;
1203                         r.min += l_out;
1204                         r.max += l_out;
1205                 }
1206         }
1207         return r;
1208 }
1209
1210 /* Discovering physical ports */
1211
1212 bool
1213 DummyAudioBackend::port_is_physical (PortEngine::PortHandle port) const
1214 {
1215         if (!valid_port (port)) {
1216                 PBD::error << _("DummyPort::port_is_physical (): invalid port.") << endmsg;
1217                 return false;
1218         }
1219         return static_cast<DummyPort*>(port)->is_physical ();
1220 }
1221
1222 void
1223 DummyAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1224 {
1225         for (PortIndex::iterator i = _ports.begin (); i != _ports.end (); ++i) {
1226                 DummyPort* port = *i;
1227                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1228                         port_names.push_back (port->name ());
1229                 }
1230         }
1231 }
1232
1233 void
1234 DummyAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1235 {
1236         for (PortIndex::iterator i = _ports.begin (); i != _ports.end (); ++i) {
1237                 DummyPort* port = *i;
1238                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1239                         port_names.push_back (port->name ());
1240                 }
1241         }
1242 }
1243
1244 ChanCount
1245 DummyAudioBackend::n_physical_outputs () const
1246 {
1247         int n_midi = 0;
1248         int n_audio = 0;
1249         for (PortIndex::const_iterator i = _ports.begin (); i != _ports.end (); ++i) {
1250                 DummyPort* port = *i;
1251                 if (port->is_output () && port->is_physical ()) {
1252                         switch (port->type ()) {
1253                                 case DataType::AUDIO: ++n_audio; break;
1254                                 case DataType::MIDI: ++n_midi; break;
1255                                 default: break;
1256                         }
1257                 }
1258         }
1259         ChanCount cc;
1260         cc.set (DataType::AUDIO, n_audio);
1261         cc.set (DataType::MIDI, n_midi);
1262         return cc;
1263 }
1264
1265 ChanCount
1266 DummyAudioBackend::n_physical_inputs () const
1267 {
1268         int n_midi = 0;
1269         int n_audio = 0;
1270         for (PortIndex::const_iterator i = _ports.begin (); i != _ports.end (); ++i) {
1271                 DummyPort* port = *i;
1272                 if (port->is_input () && port->is_physical ()) {
1273                         switch (port->type ()) {
1274                                 case DataType::AUDIO: ++n_audio; break;
1275                                 case DataType::MIDI: ++n_midi; break;
1276                                 default: break;
1277                         }
1278                 }
1279         }
1280         ChanCount cc;
1281         cc.set (DataType::AUDIO, n_audio);
1282         cc.set (DataType::MIDI, n_midi);
1283         return cc;
1284 }
1285
1286 /* Getting access to the data buffer for a port */
1287
1288 void*
1289 DummyAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1290 {
1291         assert (port);
1292         assert (valid_port (port));
1293         return static_cast<DummyPort*>(port)->get_buffer (nframes);
1294 }
1295
1296 /* Engine Process */
1297 void *
1298 DummyAudioBackend::main_process_thread ()
1299 {
1300         AudioEngine::thread_init_callback (this);
1301         _running = true;
1302         _processed_samples = 0;
1303
1304         manager.registration_callback();
1305         manager.graph_order_callback();
1306
1307         int64_t clock1;
1308         clock1 = -1;
1309         while (_running) {
1310
1311                 if (_freewheeling != _freewheel) {
1312                         _freewheel = _freewheeling;
1313                         engine.freewheel_callback (_freewheel);
1314                 }
1315
1316                 // re-set input buffers, generate on demand.
1317                 for (std::vector<DummyAudioPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
1318                         (*it)->next_period();
1319                 }
1320                 for (std::vector<DummyMidiPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it) {
1321                         (*it)->next_period();
1322                 }
1323
1324                 if (engine.process_callback (_samples_per_period)) {
1325                         return 0;
1326                 }
1327                 _processed_samples += _samples_per_period;
1328
1329                 if (_device == _("Loopback") && _midi_mode != MidiToAudio) {
1330                         int opn = 0;
1331                         int opc = _system_outputs.size();
1332                         for (std::vector<DummyAudioPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++opn) {
1333                                 DummyAudioPort* op = _system_outputs[(opn % opc)];
1334                                 (*it)->fill_wavetable ((const float*)op->get_buffer (_samples_per_period), _samples_per_period);
1335                         }
1336                 }
1337
1338                 if (_midi_mode == MidiLoopback) {
1339                         int opn = 0;
1340                         int opc = _system_midi_out.size();
1341                         for (std::vector<DummyMidiPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++opn) {
1342                                 DummyMidiPort* op = _system_midi_out[(opn % opc)];
1343                                 op->get_buffer(0); // mix-down
1344                                 (*it)->set_loopback (op->const_buffer());
1345                         }
1346                 }
1347                 else if (_midi_mode == MidiToAudio) {
1348                         int opn = 0;
1349                         int opc = _system_midi_out.size();
1350                         for (std::vector<DummyAudioPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++opn) {
1351                                 DummyMidiPort* op = _system_midi_out[(opn % opc)];
1352                                 op->get_buffer(0); // mix-down
1353                                 (*it)->midi_to_wavetable (op->const_buffer(), _samples_per_period);
1354                         }
1355                 }
1356
1357                 if (!_freewheel) {
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 = "LTC30";
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          HUGE,           /* Big, 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                         _gen_period = n_samples; // XXX DummyBackend::_samples_per_period;
1991                 case SineWave:
1992                 case SineWaveOctaves:
1993                 case SineSweep:
1994                 case SquareSweep:
1995                         assert(_wavetable && _gen_period > 0);
1996                         {
1997                                 pframes_t written = 0;
1998                                 while (written < n_samples) {
1999                                         const uint32_t remain = n_samples - written;
2000                                         const uint32_t to_copy = std::min(remain, _gen_period - _gen_offset);
2001                                         memcpy((void*)&_buffer[written],
2002                                                         (void*)&_wavetable[_gen_offset],
2003                                                         to_copy * sizeof(Sample));
2004                                         written += to_copy;
2005                                         _gen_offset = (_gen_offset + to_copy) % _gen_period;
2006                                 }
2007                         }
2008                         break;
2009                 case UniformWhiteNoise:
2010                         for (pframes_t i = 0 ; i < n_samples; ++i) {
2011                                 _buffer[i] = .158489f * randf();
2012                         }
2013                         break;
2014                 case GaussianWhiteNoise:
2015                         for (pframes_t i = 0 ; i < n_samples; ++i) {
2016                                 _buffer[i] = .089125f * grandf();
2017                         }
2018                         break;
2019                 case PinkNoise:
2020                         for (pframes_t i = 0 ; i < n_samples; ++i) {
2021                                 // Paul Kellet's refined method
2022                                 // http://www.musicdsp.org/files/pink.txt
2023                                 // NB. If 'white' consists of uniform random numbers,
2024                                 // the pink noise will have an almost gaussian distribution.
2025                                 const float white = .0498f * randf ();
2026                                 _b0 = .99886f * _b0 + white * .0555179f;
2027                                 _b1 = .99332f * _b1 + white * .0750759f;
2028                                 _b2 = .96900f * _b2 + white * .1538520f;
2029                                 _b3 = .86650f * _b3 + white * .3104856f;
2030                                 _b4 = .55000f * _b4 + white * .5329522f;
2031                                 _b5 = -.7616f * _b5 - white * .0168980f;
2032                                 _buffer[i] = _b0 + _b1 + _b2 + _b3 + _b4 + _b5 + _b6 + white * 0.5362f;
2033                                 _b6 = white * 0.115926f;
2034                         }
2035                         break;
2036                 case PonyNoise:
2037                         for (pframes_t i = 0 ; i < n_samples; ++i) {
2038                                 const float white = 0.0498f * randf ();
2039                                 // Paul Kellet's economy method
2040                                 // http://www.musicdsp.org/files/pink.txt
2041                                 _b0 = 0.99765f * _b0 + white * 0.0990460f;
2042                                 _b1 = 0.96300f * _b1 + white * 0.2965164f;
2043                                 _b2 = 0.57000f * _b2 + white * 1.0526913f;
2044                                 _buffer[i] = _b0 + _b1 + _b2 + white * 0.1848f;
2045                         }
2046                         break;
2047                 case LTC:
2048                         while (_ltcbuf->read_space () < n_samples) {
2049                                 // we should pre-allocate (or add a zero-copy libltc API), whatever.
2050                                 ltcsnd_sample_t* enc_buf = (ltcsnd_sample_t*) malloc (ltc_encoder_get_buffersize (_ltc) * sizeof (ltcsnd_sample_t));
2051                                 for (int byteCnt = 0; byteCnt < 10; byteCnt++) {
2052                                         if (_ltc_rand != 0.f) {
2053                                                 _ltc_spd += randf () * _ltc_rand;
2054                                                 _ltc_spd = std::min (1.5f, std::max (0.5f, _ltc_spd));
2055                                         }
2056                                         ltc_encoder_encode_byte (_ltc, byteCnt, _ltc_spd);
2057                                         const int len = ltc_encoder_get_buffer (_ltc, enc_buf);
2058                                         for (int i = 0; i < len; ++i) {
2059                                                 const float v1 = enc_buf[i] - 128;
2060                                                 Sample v = v1 * 0.002;
2061                                                 _ltcbuf->write (&v, 1);
2062                                         }
2063                                 }
2064                                 ltc_encoder_inc_timecode (_ltc);
2065                                 free (enc_buf);
2066                         }
2067                         _ltcbuf->read (_buffer, n_samples);
2068                         break;
2069         }
2070         _gen_cycle = true;
2071 }
2072
2073 void* DummyAudioPort::get_buffer (pframes_t n_samples)
2074 {
2075         if (is_input ()) {
2076                 const std::set<DummyPort *>& connections = get_connections ();
2077                 std::set<DummyPort*>::const_iterator it = connections.begin ();
2078                 if (it == connections.end ()) {
2079                         memset (_buffer, 0, n_samples * sizeof (Sample));
2080                 } else {
2081                         DummyAudioPort * source = static_cast<DummyAudioPort*>(*it);
2082                         assert (source && source->is_output ());
2083                         if (source->is_physical() && source->is_terminal()) {
2084                                 source->get_buffer(n_samples); // generate signal.
2085                         }
2086                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
2087                         while (++it != connections.end ()) {
2088                                 source = static_cast<DummyAudioPort*>(*it);
2089                                 assert (source && source->is_output ());
2090                                 Sample* dst = buffer ();
2091                                 if (source->is_physical() && source->is_terminal()) {
2092                                         source->get_buffer(n_samples); // generate signal.
2093                                 }
2094                                 const Sample* src = source->const_buffer ();
2095                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
2096                                         *dst += *src;
2097                                 }
2098                         }
2099                 }
2100         } else if (is_output () && is_physical () && is_terminal()) {
2101                 if (!_gen_cycle) {
2102                         generate(n_samples);
2103                 }
2104         }
2105         return _buffer;
2106 }
2107
2108
2109 DummyMidiPort::DummyMidiPort (DummyAudioBackend &b, const std::string& name, PortFlags flags)
2110         : DummyPort (b, name, flags)
2111         , _midi_seq_spb (0)
2112         , _midi_seq_time (0)
2113         , _midi_seq_pos (0)
2114 {
2115         _buffer.clear ();
2116         _loopback.clear ();
2117 }
2118
2119 DummyMidiPort::~DummyMidiPort () {
2120         _buffer.clear ();
2121         _loopback.clear ();
2122 }
2123
2124 struct MidiEventSorter {
2125         bool operator() (const boost::shared_ptr<DummyMidiEvent>& a, const boost::shared_ptr<DummyMidiEvent>& b) {
2126                 return *a < *b;
2127         }
2128 };
2129
2130 void DummyMidiPort::set_loopback (DummyMidiBuffer const * const src)
2131 {
2132         _loopback.clear ();
2133         for (DummyMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
2134                 _loopback.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (**it)));
2135         }
2136 }
2137
2138 std::string
2139 DummyMidiPort::setup_generator (int seq_id, const float sr)
2140 {
2141         DummyPort::setup_random_number_generator();
2142         _midi_seq_dat = DummyMidiData::sequences[seq_id % NUM_MIDI_EVENT_GENERATORS];
2143         _midi_seq_spb = sr * .5f; // 120 BPM, beat_time 1.0 per beat.
2144         _midi_seq_pos = 0;
2145         _midi_seq_time = 0;
2146         return DummyMidiData::sequence_names[seq_id];
2147 }
2148
2149 void DummyMidiPort::midi_generate (const pframes_t n_samples)
2150 {
2151         Glib::Threads::Mutex::Lock lm (generator_lock);
2152         if (_gen_cycle) {
2153                 return;
2154         }
2155
2156         _buffer.clear ();
2157         _gen_cycle = true;
2158
2159         if (_midi_seq_spb == 0 || !_midi_seq_dat) {
2160                 for (DummyMidiBuffer::const_iterator it = _loopback.begin (); it != _loopback.end (); ++it) {
2161                         _buffer.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (**it)));
2162                 }
2163                 return;
2164         }
2165
2166         while (1) {
2167                 const int32_t ev_beat_time = _midi_seq_dat[_midi_seq_pos].beat_time * _midi_seq_spb - _midi_seq_time;
2168                 if (ev_beat_time < 0) {
2169                         break;
2170                 }
2171                 if ((pframes_t) ev_beat_time >= n_samples) {
2172                         break;
2173                 }
2174                 _buffer.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (
2175                                                 ev_beat_time,
2176                                                 _midi_seq_dat[_midi_seq_pos].event,
2177                                                 _midi_seq_dat[_midi_seq_pos].size
2178                                                 )));
2179                 ++_midi_seq_pos;
2180
2181                 if (_midi_seq_dat[_midi_seq_pos].event[0] == 0xff && _midi_seq_dat[_midi_seq_pos].event[1] == 0xff) {
2182                         _midi_seq_time -= _midi_seq_dat[_midi_seq_pos].beat_time * _midi_seq_spb;
2183                         _midi_seq_pos = 0;
2184                 }
2185         }
2186         _midi_seq_time += n_samples;
2187 }
2188
2189
2190 void* DummyMidiPort::get_buffer (pframes_t n_samples)
2191 {
2192         if (is_input ()) {
2193                 _buffer.clear ();
2194                 const std::set<DummyPort*>& connections = get_connections ();
2195                 for (std::set<DummyPort*>::const_iterator i = connections.begin ();
2196                                 i != connections.end ();
2197                                 ++i) {
2198                         DummyMidiPort * source = static_cast<DummyMidiPort*>(*i);
2199                         if (source->is_physical() && source->is_terminal()) {
2200                                 source->get_buffer(n_samples); // generate signal.
2201                         }
2202                         const DummyMidiBuffer *src = source->const_buffer ();
2203                         for (DummyMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
2204                                 _buffer.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (**it)));
2205                         }
2206                 }
2207                 std::stable_sort (_buffer.begin (), _buffer.end (), MidiEventSorter());
2208         } else if (is_output () && is_physical () && is_terminal()) {
2209                 if (!_gen_cycle) {
2210                         midi_generate(n_samples);
2211                 }
2212         }
2213         return &_buffer;
2214 }
2215
2216 DummyMidiEvent::DummyMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
2217         : _size (size)
2218         , _timestamp (timestamp)
2219         , _data (0)
2220 {
2221         if (size > 0) {
2222                 _data = (uint8_t*) malloc (size);
2223                 memcpy (_data, data, size);
2224         }
2225 }
2226
2227 DummyMidiEvent::DummyMidiEvent (const DummyMidiEvent& other)
2228         : _size (other.size ())
2229         , _timestamp (other.timestamp ())
2230         , _data (0)
2231 {
2232         if (other.size () && other.const_data ()) {
2233                 _data = (uint8_t*) malloc (other.size ());
2234                 memcpy (_data, other.const_data (), other.size ());
2235         }
2236 };
2237
2238 DummyMidiEvent::~DummyMidiEvent () {
2239         free (_data);
2240 };