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