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