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