some backends can handle incorrectly ordered midi events.
[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 (_("Square Sweep"), true));
116                 _device_status.push_back (DeviceStatus (_("Square Sweep Swell"), true));
117                 _device_status.push_back (DeviceStatus (_("Loopback"), true));
118         }
119         return _device_status;
120 }
121
122 std::vector<float>
123 DummyAudioBackend::available_sample_rates (const std::string&) const
124 {
125         std::vector<float> sr;
126         sr.push_back (8000.0);
127         sr.push_back (22050.0);
128         sr.push_back (24000.0);
129         sr.push_back (44100.0);
130         sr.push_back (48000.0);
131         sr.push_back (88200.0);
132         sr.push_back (96000.0);
133         sr.push_back (176400.0);
134         sr.push_back (192000.0);
135         return sr;
136 }
137
138 std::vector<uint32_t>
139 DummyAudioBackend::available_buffer_sizes (const std::string&) const
140 {
141         std::vector<uint32_t> bs;
142         bs.push_back (4);
143         bs.push_back (8);
144         bs.push_back (16);
145         bs.push_back (32);
146         bs.push_back (64);
147         bs.push_back (128);
148         bs.push_back (256);
149         bs.push_back (512);
150         bs.push_back (1024);
151         bs.push_back (2048);
152         bs.push_back (4096);
153         bs.push_back (8192);
154         return bs;
155 }
156
157 uint32_t
158 DummyAudioBackend::available_input_channel_count (const std::string&) const
159 {
160         return 128;
161 }
162
163 uint32_t
164 DummyAudioBackend::available_output_channel_count (const std::string&) const
165 {
166         return 128;
167 }
168
169 bool
170 DummyAudioBackend::can_change_sample_rate_when_running () const
171 {
172         return true;
173 }
174
175 bool
176 DummyAudioBackend::can_change_buffer_size_when_running () const
177 {
178         return true;
179 }
180
181 int
182 DummyAudioBackend::set_device_name (const std::string& d)
183 {
184         _device = d;
185         return 0;
186 }
187
188 int
189 DummyAudioBackend::set_sample_rate (float sr)
190 {
191         if (sr <= 0) { return -1; }
192         _samplerate = sr;
193         engine.sample_rate_change (sr);
194         return 0;
195 }
196
197 int
198 DummyAudioBackend::set_buffer_size (uint32_t bs)
199 {
200         if (bs <= 0 || bs >= _max_buffer_size) {
201                 return -1;
202         }
203         _samples_per_period = bs;
204
205         /* update port latencies
206          * with 'Loopback' there is exactly once cycle latency,
207          * divide it between In + Out;
208          */
209         LatencyRange lr;
210         lr.min = lr.max = _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 = _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 (_("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                 _midi_options.push_back (_("8 in, 8 out, Loopback"));
325                 _midi_options.push_back (_("MIDI to Audio, Loopback"));
326                 _midi_options.push_back (_("No MIDI I/O"));
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 == _("Square Sweep")) {
748                 gt = DummyAudioPort::SquareSweep;
749         } else if (_device == _("Square Sweep Swell")) {
750                 gt = DummyAudioPort::SquareSweepSwell;
751         } else if (_device == _("Loopback")) {
752                 gt = DummyAudioPort::Loopback;
753         } else {
754                 gt = DummyAudioPort::Silence;
755         }
756
757         if (_midi_mode == MidiToAudio) {
758                 gt = DummyAudioPort::Loopback;
759         }
760
761         const int a_ins = _n_inputs > 0 ? _n_inputs : 8;
762         const int a_out = _n_outputs > 0 ? _n_outputs : 8;
763         const int m_ins = _n_midi_inputs == UINT_MAX ? 0 : _n_midi_inputs;
764         const int m_out = _n_midi_outputs == UINT_MAX ? a_ins : _n_midi_outputs;
765
766
767         /* audio ports */
768         lr.min = lr.max = _systemic_input_latency;
769         for (int i = 1; i <= a_ins; ++i) {
770                 char tmp[64];
771                 snprintf(tmp, sizeof(tmp), "system:capture_%d", i);
772                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
773                 if (!p) return -1;
774                 set_latency_range (p, false, lr);
775                 _system_inputs.push_back (static_cast<DummyAudioPort*>(p));
776                 static_cast<DummyAudioPort*>(p)->setup_generator (gt, _samplerate);
777         }
778
779         lr.min = lr.max = _systemic_output_latency;
780         for (int i = 1; i <= a_out; ++i) {
781                 char tmp[64];
782                 snprintf(tmp, sizeof(tmp), "system:playback_%d", i);
783                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
784                 if (!p) return -1;
785                 set_latency_range (p, true, lr);
786                 _system_outputs.push_back (static_cast<DummyAudioPort*>(p));
787         }
788
789         /* midi ports */
790         lr.min = lr.max = _systemic_input_latency;
791         for (int i = 0; i < m_ins; ++i) {
792                 char tmp[64];
793                 snprintf(tmp, sizeof(tmp), "system:midi_capture_%d", i+1);
794                 PortHandle p = add_port(std::string(tmp), DataType::MIDI, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
795                 if (!p) return -1;
796                 set_latency_range (p, false, lr);
797                 _system_midi_in.push_back (static_cast<DummyMidiPort*>(p));
798                 if (_midi_mode == MidiGenerator) {
799                         static_cast<DummyMidiPort*>(p)->setup_generator (i % NUM_MIDI_EVENT_GENERATORS, _samplerate);
800                 }
801         }
802
803         lr.min = lr.max = _systemic_output_latency;
804         for (int i = 1; i <= m_out; ++i) {
805                 char tmp[64];
806                 snprintf(tmp, sizeof(tmp), "system:midi_playback_%d", i);
807                 PortHandle p = add_port(std::string(tmp), DataType::MIDI, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
808                 if (!p) return -1;
809                 set_latency_range (p, true, lr);
810                 _system_midi_out.push_back (static_cast<DummyMidiPort*>(p));
811         }
812         return 0;
813 }
814
815 void
816 DummyAudioBackend::unregister_ports (bool system_only)
817 {
818         size_t i = 0;
819         _system_inputs.clear();
820         _system_outputs.clear();
821         _system_midi_in.clear();
822         _system_midi_out.clear();
823         while (i <  _ports.size ()) {
824                 DummyPort* port = _ports[i];
825                 if (! system_only || (port->is_physical () && port->is_terminal ())) {
826                         port->disconnect_all ();
827                         delete port;
828                         _ports.erase (_ports.begin() + i);
829                 } else {
830                         ++i;
831                 }
832         }
833 }
834
835 int
836 DummyAudioBackend::connect (const std::string& src, const std::string& dst)
837 {
838         DummyPort* src_port = find_port (src);
839         DummyPort* dst_port = find_port (dst);
840
841         if (!src_port) {
842                 PBD::error << _("DummyBackend::connect: Invalid Source port:")
843                                 << " (" << src <<")" << endmsg;
844                 return -1;
845         }
846         if (!dst_port) {
847                 PBD::error << _("DummyBackend::connect: Invalid Destination port:")
848                         << " (" << dst <<")" << endmsg;
849                 return -1;
850         }
851         return src_port->connect (dst_port);
852 }
853
854 int
855 DummyAudioBackend::disconnect (const std::string& src, const std::string& dst)
856 {
857         DummyPort* src_port = find_port (src);
858         DummyPort* dst_port = find_port (dst);
859
860         if (!src_port || !dst_port) {
861                 PBD::error << _("DummyBackend::disconnect: Invalid Port(s)") << endmsg;
862                 return -1;
863         }
864         return src_port->disconnect (dst_port);
865 }
866
867 int
868 DummyAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
869 {
870         DummyPort* dst_port = find_port (dst);
871         if (!valid_port (src)) {
872                 PBD::error << _("DummyBackend::connect: Invalid Source Port Handle") << endmsg;
873                 return -1;
874         }
875         if (!dst_port) {
876                 PBD::error << _("DummyBackend::connect: Invalid Destination Port")
877                         << " (" << dst << ")" << endmsg;
878                 return -1;
879         }
880         return static_cast<DummyPort*>(src)->connect (dst_port);
881 }
882
883 int
884 DummyAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
885 {
886         DummyPort* dst_port = find_port (dst);
887         if (!valid_port (src) || !dst_port) {
888                 PBD::error << _("DummyBackend::disconnect: Invalid Port(s)") << endmsg;
889                 return -1;
890         }
891         return static_cast<DummyPort*>(src)->disconnect (dst_port);
892 }
893
894 int
895 DummyAudioBackend::disconnect_all (PortEngine::PortHandle port)
896 {
897         if (!valid_port (port)) {
898                 PBD::error << _("DummyBackend::disconnect_all: Invalid Port") << endmsg;
899                 return -1;
900         }
901         static_cast<DummyPort*>(port)->disconnect_all ();
902         return 0;
903 }
904
905 bool
906 DummyAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
907 {
908         if (!valid_port (port)) {
909                 PBD::error << _("DummyBackend::disconnect_all: Invalid Port") << endmsg;
910                 return false;
911         }
912         return static_cast<DummyPort*>(port)->is_connected ();
913 }
914
915 bool
916 DummyAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
917 {
918         DummyPort* dst_port = find_port (dst);
919         if (!valid_port (src) || !dst_port) {
920                 PBD::error << _("DummyBackend::connected_to: Invalid Port") << endmsg;
921                 return false;
922         }
923         return static_cast<DummyPort*>(src)->is_connected (dst_port);
924 }
925
926 bool
927 DummyAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
928 {
929         if (!valid_port (port)) {
930                 PBD::error << _("DummyBackend::physically_connected: Invalid Port") << endmsg;
931                 return false;
932         }
933         return static_cast<DummyPort*>(port)->is_physically_connected ();
934 }
935
936 int
937 DummyAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
938 {
939         if (!valid_port (port)) {
940                 PBD::error << _("DummyBackend::get_connections: Invalid Port") << endmsg;
941                 return -1;
942         }
943
944         assert (0 == names.size ());
945
946         const std::vector<DummyPort*>& connected_ports = static_cast<DummyPort*>(port)->get_connections ();
947
948         for (std::vector<DummyPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
949                 names.push_back ((*i)->name ());
950         }
951
952         return (int)names.size ();
953 }
954
955 /* MIDI */
956 int
957 DummyAudioBackend::midi_event_get (
958                 pframes_t& timestamp,
959                 size_t& size, uint8_t** buf, void* port_buffer,
960                 uint32_t event_index)
961 {
962         assert (buf && port_buffer);
963         DummyMidiBuffer& source = * static_cast<DummyMidiBuffer*>(port_buffer);
964         if (event_index >= source.size ()) {
965                 return -1;
966         }
967         DummyMidiEvent * const event = source[event_index].get ();
968
969         timestamp = event->timestamp ();
970         size = event->size ();
971         *buf = event->data ();
972         return 0;
973 }
974
975 int
976 DummyAudioBackend::midi_event_put (
977                 void* port_buffer,
978                 pframes_t timestamp,
979                 const uint8_t* buffer, size_t size)
980 {
981         assert (buffer && port_buffer);
982         DummyMidiBuffer& dst = * static_cast<DummyMidiBuffer*>(port_buffer);
983         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
984                 // nevermind, ::get_buffer() sorts events, but always print warning
985                 fprintf (stderr, "DummyMidiBuffer: it's too late for this event.\n");
986         }
987         dst.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (timestamp, buffer, size)));
988         return 0;
989 }
990
991 uint32_t
992 DummyAudioBackend::get_midi_event_count (void* port_buffer)
993 {
994         assert (port_buffer);
995         return static_cast<DummyMidiBuffer*>(port_buffer)->size ();
996 }
997
998 void
999 DummyAudioBackend::midi_clear (void* port_buffer)
1000 {
1001         assert (port_buffer);
1002         DummyMidiBuffer * buf = static_cast<DummyMidiBuffer*>(port_buffer);
1003         assert (buf);
1004         buf->clear ();
1005 }
1006
1007 /* Monitoring */
1008
1009 bool
1010 DummyAudioBackend::can_monitor_input () const
1011 {
1012         return false;
1013 }
1014
1015 int
1016 DummyAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1017 {
1018         return -1;
1019 }
1020
1021 int
1022 DummyAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1023 {
1024         return -1;
1025 }
1026
1027 bool
1028 DummyAudioBackend::monitoring_input (PortEngine::PortHandle)
1029 {
1030         return false;
1031 }
1032
1033 /* Latency management */
1034
1035 void
1036 DummyAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1037 {
1038         if (!valid_port (port)) {
1039                 PBD::error << _("DummyPort::set_latency_range (): invalid port.") << endmsg;
1040         }
1041         static_cast<DummyPort*>(port)->set_latency_range (latency_range, for_playback);
1042 }
1043
1044 LatencyRange
1045 DummyAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1046 {
1047         LatencyRange r;
1048         if (!valid_port (port)) {
1049                 PBD::error << _("DummyPort::get_latency_range (): invalid port.") << endmsg;
1050                 r.min = 0;
1051                 r.max = 0;
1052                 return r;
1053         }
1054         DummyPort *p =  static_cast<DummyPort*>(port);
1055         assert(p);
1056
1057         r = p->latency_range (for_playback);
1058         if (p->is_physical() && p->is_terminal()) {
1059                 if (p->is_input() && for_playback) {
1060                         const size_t l_in = _samples_per_period * .25;
1061                         r.min += l_in;
1062                         r.max += l_in;
1063                 }
1064                 if (p->is_output() && !for_playback) {
1065                         /* with 'Loopback' there is exactly once cycle latency, divide it between In + Out; */
1066                         const size_t l_in = _samples_per_period * .25;
1067                         const size_t l_out = _samples_per_period - l_in;
1068                         r.min += l_out;
1069                         r.max += l_out;
1070                 }
1071         }
1072         return r;
1073 }
1074
1075 /* Discovering physical ports */
1076
1077 bool
1078 DummyAudioBackend::port_is_physical (PortEngine::PortHandle port) const
1079 {
1080         if (!valid_port (port)) {
1081                 PBD::error << _("DummyPort::port_is_physical (): invalid port.") << endmsg;
1082                 return false;
1083         }
1084         return static_cast<DummyPort*>(port)->is_physical ();
1085 }
1086
1087 void
1088 DummyAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1089 {
1090         for (size_t i = 0; i < _ports.size (); ++i) {
1091                 DummyPort* port = _ports[i];
1092                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1093                         port_names.push_back (port->name ());
1094                 }
1095         }
1096 }
1097
1098 void
1099 DummyAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1100 {
1101         for (size_t i = 0; i < _ports.size (); ++i) {
1102                 DummyPort* port = _ports[i];
1103                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1104                         port_names.push_back (port->name ());
1105                 }
1106         }
1107 }
1108
1109 ChanCount
1110 DummyAudioBackend::n_physical_outputs () const
1111 {
1112         int n_midi = 0;
1113         int n_audio = 0;
1114         for (size_t i = 0; i < _ports.size (); ++i) {
1115                 DummyPort* port = _ports[i];
1116                 if (port->is_output () && port->is_physical ()) {
1117                         switch (port->type ()) {
1118                                 case DataType::AUDIO: ++n_audio; break;
1119                                 case DataType::MIDI: ++n_midi; break;
1120                                 default: break;
1121                         }
1122                 }
1123         }
1124         ChanCount cc;
1125         cc.set (DataType::AUDIO, n_audio);
1126         cc.set (DataType::MIDI, n_midi);
1127         return cc;
1128 }
1129
1130 ChanCount
1131 DummyAudioBackend::n_physical_inputs () const
1132 {
1133         int n_midi = 0;
1134         int n_audio = 0;
1135         for (size_t i = 0; i < _ports.size (); ++i) {
1136                 DummyPort* port = _ports[i];
1137                 if (port->is_input () && port->is_physical ()) {
1138                         switch (port->type ()) {
1139                                 case DataType::AUDIO: ++n_audio; break;
1140                                 case DataType::MIDI: ++n_midi; break;
1141                                 default: break;
1142                         }
1143                 }
1144         }
1145         ChanCount cc;
1146         cc.set (DataType::AUDIO, n_audio);
1147         cc.set (DataType::MIDI, n_midi);
1148         return cc;
1149 }
1150
1151 /* Getting access to the data buffer for a port */
1152
1153 void*
1154 DummyAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1155 {
1156         assert (port);
1157         assert (valid_port (port));
1158         return static_cast<DummyPort*>(port)->get_buffer (nframes);
1159 }
1160
1161 /* Engine Process */
1162 void *
1163 DummyAudioBackend::main_process_thread ()
1164 {
1165         AudioEngine::thread_init_callback (this);
1166         _running = true;
1167         _processed_samples = 0;
1168
1169         manager.registration_callback();
1170         manager.graph_order_callback();
1171
1172         int64_t clock1, clock2;
1173         clock1 = _x_get_monotonic_usec();
1174         while (_running) {
1175
1176                 if (_freewheeling != _freewheel) {
1177                         _freewheel = _freewheeling;
1178                         engine.freewheel_callback (_freewheel);
1179                 }
1180
1181                 // re-set input buffers, generate on demand.
1182                 for (std::vector<DummyAudioPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
1183                         (*it)->next_period();
1184                 }
1185                 for (std::vector<DummyMidiPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it) {
1186                         (*it)->next_period();
1187                 }
1188
1189                 if (engine.process_callback (_samples_per_period)) {
1190                         return 0;
1191                 }
1192                 _processed_samples += _samples_per_period;
1193
1194                 if (_device == _("Loopback") && _midi_mode != MidiToAudio) {
1195                         int opn = 0;
1196                         int opc = _system_outputs.size();
1197                         for (std::vector<DummyAudioPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++opn) {
1198                                 DummyAudioPort* op = _system_outputs[(opn % opc)];
1199                                 (*it)->fill_wavetable ((const float*)op->get_buffer (_samples_per_period), _samples_per_period);
1200                         }
1201                 }
1202
1203                 if (_midi_mode == MidiLoopback) {
1204                         int opn = 0;
1205                         int opc = _system_midi_out.size();
1206                         for (std::vector<DummyMidiPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++opn) {
1207                                 DummyMidiPort* op = _system_midi_out[(opn % opc)];
1208                                 op->get_buffer(0); // mix-down
1209                                 (*it)->set_loopback (op->const_buffer());
1210                         }
1211                 }
1212                 else if (_midi_mode == MidiToAudio) {
1213                         int opn = 0;
1214                         int opc = _system_midi_out.size();
1215                         for (std::vector<DummyAudioPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++opn) {
1216                                 DummyMidiPort* op = _system_midi_out[(opn % opc)];
1217                                 op->get_buffer(0); // mix-down
1218                                 (*it)->midi_to_wavetable (op->const_buffer(), _samples_per_period);
1219                         }
1220                 }
1221
1222                 if (!_freewheel) {
1223                         const int64_t nomial_time = 1e6 * _samples_per_period / _samplerate;
1224                         clock2 = _x_get_monotonic_usec();
1225 #ifdef PLATFORM_WINDOWS
1226                         bool win_timers_ok = true;
1227                         /* querying the performance counter can fail occasionally (-1).
1228                          * Also on some multi-core systems, timers are CPU specific and not
1229                          * synchronized. We assume they differ more than a few milliseconds
1230                          * (4 * nominal cycle time) and simply ignore cases where the
1231                          * execution switches cores.
1232                          */
1233                         if (clock1 < 0 || clock2 < 0 || (clock1 > clock2) || (clock2 - clock1) > 4 * nomial_time) {
1234                                 clock2 = clock1 = 0;
1235                                 win_timers_ok = false;
1236                         }
1237 #endif
1238                         const int64_t elapsed_time = clock2 - clock1;
1239 #ifdef PLATFORM_WINDOWS
1240                         if (win_timers_ok)
1241 #endif
1242                         { // low pass filter
1243                                 _dsp_load = _dsp_load + .05 * ((elapsed_time / (float) nomial_time) - _dsp_load) + 1e-12;
1244                         }
1245
1246                         if (elapsed_time < nomial_time) {
1247                                 Glib::usleep (nomial_time - elapsed_time);
1248                         } else {
1249                                 Glib::usleep (100); // don't hog cpu
1250                         }
1251                 } else {
1252                         _dsp_load = 1.0f;
1253                         Glib::usleep (100); // don't hog cpu
1254                 }
1255
1256                 /* beginning of netx cycle */
1257                 clock1 = _x_get_monotonic_usec();
1258
1259                 bool connections_changed = false;
1260                 bool ports_changed = false;
1261                 if (!pthread_mutex_trylock (&_port_callback_mutex)) {
1262                         if (_port_change_flag) {
1263                                 ports_changed = true;
1264                                 _port_change_flag = false;
1265                         }
1266                         if (!_port_connection_queue.empty ()) {
1267                                 connections_changed = true;
1268                         }
1269                         while (!_port_connection_queue.empty ()) {
1270                                 PortConnectData *c = _port_connection_queue.back ();
1271                                 manager.connect_callback (c->a, c->b, c->c);
1272                                 _port_connection_queue.pop_back ();
1273                                 delete c;
1274                         }
1275                         pthread_mutex_unlock (&_port_callback_mutex);
1276                 }
1277                 if (ports_changed) {
1278                         manager.registration_callback();
1279                 }
1280                 if (connections_changed) {
1281                         manager.graph_order_callback();
1282                 }
1283                 if (connections_changed || ports_changed) {
1284                         engine.latency_callback(false);
1285                         engine.latency_callback(true);
1286                 }
1287
1288         }
1289         _running = false;
1290         return 0;
1291 }
1292
1293
1294 /******************************************************************************/
1295
1296 static boost::shared_ptr<DummyAudioBackend> _instance;
1297
1298 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
1299 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
1300 static int deinstantiate ();
1301 static bool already_configured ();
1302 static bool available ();
1303
1304 static ARDOUR::AudioBackendInfo _descriptor = {
1305         "Dummy",
1306         instantiate,
1307         deinstantiate,
1308         backend_factory,
1309         already_configured,
1310         available
1311 };
1312
1313 static boost::shared_ptr<AudioBackend>
1314 backend_factory (AudioEngine& e)
1315 {
1316         if (!_instance) {
1317                 _instance.reset (new DummyAudioBackend (e, _descriptor));
1318         }
1319         return _instance;
1320 }
1321
1322 static int
1323 instantiate (const std::string& arg1, const std::string& /* arg2 */)
1324 {
1325         s_instance_name = arg1;
1326 #ifdef PLATFORM_WINDOWS
1327         LARGE_INTEGER Frequency;
1328         if (!QueryPerformanceFrequency(&Frequency) || Frequency.QuadPart < 1) {
1329                 _win_pc_rate = 0;
1330         } else {
1331                 _win_pc_rate = 1000000.0 / Frequency.QuadPart;
1332         }
1333 #endif
1334         return 0;
1335 }
1336
1337 static int
1338 deinstantiate ()
1339 {
1340         _instance.reset ();
1341         return 0;
1342 }
1343
1344 static bool
1345 already_configured ()
1346 {
1347         if (_instance) {
1348                 return _instance->is_running();
1349         }
1350         return false;
1351 }
1352
1353 static bool
1354 available ()
1355 {
1356         return true;
1357 }
1358
1359 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
1360 {
1361         return &_descriptor;
1362 }
1363
1364
1365 /******************************************************************************/
1366 DummyPort::DummyPort (DummyAudioBackend &b, const std::string& name, PortFlags flags)
1367         : _dummy_backend (b)
1368         , _name  (name)
1369         , _flags (flags)
1370         , _rseed (0)
1371         , _gen_cycle (false)
1372 {
1373         _capture_latency_range.min = 0;
1374         _capture_latency_range.max = 0;
1375         _playback_latency_range.min = 0;
1376         _playback_latency_range.max = 0;
1377         _dummy_backend.port_connect_add_remove_callback();
1378 }
1379
1380 DummyPort::~DummyPort () {
1381         disconnect_all ();
1382         _dummy_backend.port_connect_add_remove_callback();
1383 }
1384
1385
1386 int DummyPort::connect (DummyPort *port)
1387 {
1388         if (!port) {
1389                 PBD::error << _("DummyPort::connect (): invalid (null) port") << endmsg;
1390                 return -1;
1391         }
1392
1393         if (type () != port->type ()) {
1394                 PBD::error << _("DummyPort::connect (): wrong port-type") << endmsg;
1395                 return -1;
1396         }
1397
1398         if (is_output () && port->is_output ()) {
1399                 PBD::error << _("DummyPort::connect (): cannot inter-connect output ports.") << endmsg;
1400                 return -1;
1401         }
1402
1403         if (is_input () && port->is_input ()) {
1404                 PBD::error << _("DummyPort::connect (): cannot inter-connect input ports.") << endmsg;
1405                 return -1;
1406         }
1407
1408         if (this == port) {
1409                 PBD::error << _("DummyPort::connect (): cannot self-connect ports.") << endmsg;
1410                 return -1;
1411         }
1412
1413         if (is_connected (port)) {
1414 #if 0 // don't bother to warn about this for now. just ignore it
1415                 PBD::error << _("DummyPort::connect (): ports are already connected:")
1416                         << " (" << name () << ") -> (" << port->name () << ")"
1417                         << endmsg;
1418 #endif
1419                 return -1;
1420         }
1421
1422         _connect (port, true);
1423         return 0;
1424 }
1425
1426
1427 void DummyPort::_connect (DummyPort *port, bool callback)
1428 {
1429         _connections.push_back (port);
1430         if (callback) {
1431                 port->_connect (this, false);
1432                 _dummy_backend.port_connect_callback (name(),  port->name(), true);
1433         }
1434 }
1435
1436 int DummyPort::disconnect (DummyPort *port)
1437 {
1438         if (!port) {
1439                 PBD::error << _("DummyPort::disconnect (): invalid (null) port") << endmsg;
1440                 return -1;
1441         }
1442
1443         if (!is_connected (port)) {
1444                 PBD::error << _("DummyPort::disconnect (): ports are not connected:")
1445                         << " (" << name () << ") -> (" << port->name () << ")"
1446                         << endmsg;
1447                 return -1;
1448         }
1449         _disconnect (port, true);
1450         return 0;
1451 }
1452
1453 void DummyPort::_disconnect (DummyPort *port, bool callback)
1454 {
1455         std::vector<DummyPort*>::iterator it = std::find (_connections.begin (), _connections.end (), port);
1456
1457         assert (it != _connections.end ());
1458
1459         _connections.erase (it);
1460
1461         if (callback) {
1462                 port->_disconnect (this, false);
1463                 _dummy_backend.port_connect_callback (name(),  port->name(), false);
1464         }
1465 }
1466
1467
1468 void DummyPort::disconnect_all ()
1469 {
1470         while (!_connections.empty ()) {
1471                 _connections.back ()->_disconnect (this, false);
1472                 _dummy_backend.port_connect_callback (name(),  _connections.back ()->name(), false);
1473                 _connections.pop_back ();
1474         }
1475 }
1476
1477 bool
1478 DummyPort::is_connected (const DummyPort *port) const
1479 {
1480         return std::find (_connections.begin (), _connections.end (), port) != _connections.end ();
1481 }
1482
1483 bool DummyPort::is_physically_connected () const
1484 {
1485         for (std::vector<DummyPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
1486                 if ((*it)->is_physical ()) {
1487                         return true;
1488                 }
1489         }
1490         return false;
1491 }
1492
1493 void DummyPort::setup_random_number_generator ()
1494 {
1495 #ifdef PLATFORM_WINDOWS
1496         LARGE_INTEGER Count;
1497         if (QueryPerformanceCounter (&Count)) {
1498                 _rseed = Count.QuadPart % UINT_MAX;
1499         } else
1500 #endif
1501         {
1502         _rseed = g_get_monotonic_time() % UINT_MAX;
1503         }
1504         _rseed = (_rseed + (uint64_t)this) % UINT_MAX;
1505 }
1506
1507 inline uint32_t
1508 DummyPort::randi ()
1509 {
1510         // 31bit Park-Miller-Carta Pseudo-Random Number Generator
1511         // http://www.firstpr.com.au/dsp/rand31/
1512         uint32_t hi, lo;
1513         lo = 16807 * (_rseed & 0xffff);
1514         hi = 16807 * (_rseed >> 16);
1515
1516         lo += (hi & 0x7fff) << 16;
1517         lo += hi >> 15;
1518 #if 1
1519         lo = (lo & 0x7fffffff) + (lo >> 31);
1520 #else
1521         if (lo > 0x7fffffff) { lo -= 0x7fffffff; }
1522 #endif
1523         return (_rseed = lo);
1524 }
1525
1526 inline float
1527 DummyPort::randf ()
1528 {
1529         return (randi() / 1073741824.f) - 1.f;
1530 }
1531
1532 /******************************************************************************/
1533
1534 DummyAudioPort::DummyAudioPort (DummyAudioBackend &b, const std::string& name, PortFlags flags)
1535         : DummyPort (b, name, flags)
1536         , _gen_type (Silence)
1537         , _b0 (0)
1538         , _b1 (0)
1539         , _b2 (0)
1540         , _b3 (0)
1541         , _b4 (0)
1542         , _b5 (0)
1543         , _b6 (0)
1544         , _wavetable (0)
1545         , _gen_period (0)
1546         , _gen_offset (0)
1547         , _gen_perio2 (0)
1548         , _gen_count2 (0)
1549         , _pass (false)
1550         , _rn1 (0)
1551 {
1552         memset (_buffer, 0, sizeof (_buffer));
1553 }
1554
1555 DummyAudioPort::~DummyAudioPort () {
1556         free(_wavetable);
1557         _wavetable = 0;
1558 }
1559
1560 void DummyAudioPort::setup_generator (GeneratorType const g, float const samplerate)
1561 {
1562         DummyPort::setup_random_number_generator();
1563         _gen_type = g;
1564
1565         switch (_gen_type) {
1566                 case PinkNoise:
1567                 case PonyNoise:
1568                 case UniformWhiteNoise:
1569                 case GaussianWhiteNoise:
1570                 case Silence:
1571                         break;
1572                 case KronekerDelta:
1573                         _gen_period = (5 + randi() % (int)(samplerate / 20.f));
1574                         break;
1575                 case SquareWave:
1576                         _gen_period = (5 + randi() % (int)(samplerate / 20.f)) & ~1;
1577                         break;
1578                 case SineWave:
1579                         _gen_period = 5 + randi() % (int)(samplerate / 20.f);
1580                         _wavetable = (Sample*) malloc (_gen_period * sizeof(Sample));
1581                         for (uint32_t i = 0 ; i < _gen_period; ++i) {
1582                                 _wavetable[i] = .12589f * sinf(2.0f * M_PI * (float)i / (float)_gen_period); // -18dBFS
1583                         }
1584                         break;
1585                 case SquareSweep:
1586                 case SquareSweepSwell:
1587                 case SineSweep:
1588                 case SineSweepSwell:
1589                         {
1590                                 _gen_period = 5 * samplerate + randi() % (int)(samplerate * 10.f);
1591                                 _gen_period &= ~1;
1592                                 _gen_perio2 = 1 | (int)ceilf (_gen_period * .89f); // Volume Swell period
1593                                 const double f_min = 20.;
1594                                 const double f_max = samplerate * .5;
1595                                 const double g_p2 = _gen_period * .5;
1596 #ifdef LINEAR_SWEEP
1597                                 const double b = (f_max - f_min) / (2. * samplerate * g_p2);
1598                                 const double a = f_min / samplerate;
1599 #else
1600                                 const double b = log (f_max / f_min) / g_p2;
1601                                 const double a = f_min / (b * samplerate);
1602 #endif
1603                                 const uint32_t g_p2i = rint(g_p2);
1604                                 _wavetable = (Sample*) malloc (_gen_period * sizeof(Sample));
1605                                 for (uint32_t i = 0 ; i < g_p2i; ++i) {
1606 #ifdef LINEAR_SWEEP
1607                                         const double phase = i * (a + b * i);
1608 #else
1609                                         const double phase = a * exp (b * i) - a;
1610 #endif
1611                                         _wavetable[i] = (float)sin (2. * M_PI * (phase - floor (phase)));
1612                                 }
1613                                 for (uint32_t i = g_p2i; i < _gen_period; ++i) {
1614                                         const uint32_t j = _gen_period - i;
1615 #ifdef LINEAR_SWEEP
1616                                         const double phase = j * (a + b * j);
1617 #else
1618                                         const double phase = a * exp (b * j) - a;
1619 #endif
1620                                         _wavetable[i] = (float)sin (2. * M_PI * (phase - floor (phase)));
1621                                 }
1622                                 if (_gen_type == SquareSweep) {
1623                                         for (uint32_t i = 0 ; i < _gen_period; ++i) {
1624                                                 _wavetable[i] = _wavetable[i] < 0 ? -.40709f : .40709f;
1625                                         }
1626                                 }
1627                                 else if (_gen_type == SquareSweepSwell) {
1628                                         for (uint32_t i = 0 ; i < _gen_period; ++i) {
1629                                                 _wavetable[i] = _wavetable[i] < 0 ? -1 : 1;
1630                                         }
1631                                 }
1632                         }
1633                         break;
1634                 case Loopback:
1635                         _wavetable = (Sample*) malloc (DummyAudioBackend::max_buffer_size() * sizeof(Sample));
1636                         break;
1637         }
1638 }
1639
1640 void DummyAudioPort::midi_to_wavetable (DummyMidiBuffer const * const src, size_t n_samples)
1641 {
1642         memset(_wavetable, 0, n_samples * sizeof(float));
1643         /* generate an audio spike for every midi message
1644          * to verify layency-compensation alignment
1645          * (here: midi-out playback-latency + audio-in capture-latency)
1646          */
1647         for (DummyMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
1648                 const pframes_t t = (*it)->timestamp();
1649                 assert(t < n_samples);
1650                 // somewhat arbitrary mapping for quick visual feedback
1651                 float v = -.5f;
1652                 if ((*it)->size() == 3) {
1653                         const unsigned char *d = (*it)->const_data();
1654                         if ((d[0] & 0xf0) == 0x90) { // note on
1655                                 v = .25f + d[2] / 512.f;
1656                         }
1657                         else if ((d[0] & 0xf0) == 0x80) { // note off
1658                                 v = .3f - d[2] / 640.f;
1659                         }
1660                         else if ((d[0] & 0xf0) == 0xb0) { // CC
1661                                 v = -.1f - d[2] / 256.f;
1662                         }
1663                 }
1664                 _wavetable[t] += v;
1665         }
1666 }
1667
1668 float DummyAudioPort::grandf ()
1669 {
1670         // Gaussian White Noise
1671         // http://www.musicdsp.org/archive.php?classid=0#109
1672         float x1, x2, r;
1673
1674         if (_pass) {
1675                 _pass = false;
1676                 return _rn1;
1677         }
1678
1679         do {
1680                 x1 = randf ();
1681                 x2 = randf ();
1682                 r = x1 * x1 + x2 * x2;
1683         } while ((r >= 1.0f) || (r < 1e-22f));
1684
1685         r = sqrtf (-2.f * logf (r) / r);
1686
1687         _pass = true;
1688         _rn1 = r * x2;
1689         return r * x1;
1690 }
1691
1692 void DummyAudioPort::generate (const pframes_t n_samples)
1693 {
1694         Glib::Threads::Mutex::Lock lm (generator_lock);
1695         if (_gen_cycle) {
1696                 return;
1697         }
1698
1699         switch (_gen_type) {
1700                 case Silence:
1701                         memset (_buffer, 0, n_samples * sizeof (Sample));
1702                         break;
1703                 case SquareWave:
1704                         assert(_gen_period > 0);
1705                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1706                                 if (_gen_offset < _gen_period * .5f) {
1707                                         _buffer[i] =  .40709f; // -6dBFS
1708                                 } else {
1709                                         _buffer[i] = -.40709f;
1710                                 }
1711                                 _gen_offset = (_gen_offset + 1) % _gen_period;
1712                         }
1713                         break;
1714                 case KronekerDelta:
1715                         assert(_gen_period > 0);
1716                         memset (_buffer, 0, n_samples * sizeof (Sample));
1717                         for (pframes_t i = 0; i < n_samples; ++i) {
1718                                 if (_gen_offset == 0) {
1719                                         _buffer[i] = 1.0f;
1720                                 }
1721                                 _gen_offset = (_gen_offset + 1) % _gen_period;
1722                         }
1723                         break;
1724                 case SineSweepSwell:
1725                 case SquareSweepSwell:
1726                         assert(_wavetable && _gen_period > 0);
1727                         {
1728                                 const float vols = 2.f / (float)_gen_perio2;
1729                                 for (pframes_t i = 0; i < n_samples; ++i) {
1730                                         const float g = fabsf (_gen_count2 * vols - 1.0);
1731                                         _buffer[i] = g * _wavetable[_gen_offset];
1732                                         _gen_offset = (_gen_offset + 1) % _gen_period;
1733                                         _gen_count2 = (_gen_count2 + 1) % _gen_perio2;
1734                                 }
1735                         }
1736                         break;
1737                 case Loopback:
1738                         _gen_period = n_samples; // XXX DummyBackend::_samples_per_period;
1739                 case SineWave:
1740                 case SineSweep:
1741                 case SquareSweep:
1742                         assert(_wavetable && _gen_period > 0);
1743                         {
1744                                 pframes_t written = 0;
1745                                 while (written < n_samples) {
1746                                         const uint32_t remain = n_samples - written;
1747                                         const uint32_t to_copy = std::min(remain, _gen_period - _gen_offset);
1748                                         memcpy((void*)&_buffer[written],
1749                                                         (void*)&_wavetable[_gen_offset],
1750                                                         to_copy * sizeof(Sample));
1751                                         written += to_copy;
1752                                         _gen_offset = (_gen_offset + to_copy) % _gen_period;
1753                                 }
1754                         }
1755                         break;
1756                 case UniformWhiteNoise:
1757                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1758                                 _buffer[i] = .158489f * randf();
1759                         }
1760                         break;
1761                 case GaussianWhiteNoise:
1762                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1763                                 _buffer[i] = .089125f * grandf();
1764                         }
1765                         break;
1766                 case PinkNoise:
1767                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1768                                 // Paul Kellet's refined method
1769                                 // http://www.musicdsp.org/files/pink.txt
1770                                 // NB. If 'white' consists of uniform random numbers,
1771                                 // the pink noise will have an almost gaussian distribution.
1772                                 const float white = .0498f * randf ();
1773                                 _b0 = .99886f * _b0 + white * .0555179f;
1774                                 _b1 = .99332f * _b1 + white * .0750759f;
1775                                 _b2 = .96900f * _b2 + white * .1538520f;
1776                                 _b3 = .86650f * _b3 + white * .3104856f;
1777                                 _b4 = .55000f * _b4 + white * .5329522f;
1778                                 _b5 = -.7616f * _b5 - white * .0168980f;
1779                                 _buffer[i] = _b0 + _b1 + _b2 + _b3 + _b4 + _b5 + _b6 + white * 0.5362f;
1780                                 _b6 = white * 0.115926f;
1781                         }
1782                         break;
1783                 case PonyNoise:
1784                         for (pframes_t i = 0 ; i < n_samples; ++i) {
1785                                 const float white = 0.0498f * randf ();
1786                                 // Paul Kellet's economy method
1787                                 // http://www.musicdsp.org/files/pink.txt
1788                                 _b0 = 0.99765f * _b0 + white * 0.0990460f;
1789                                 _b1 = 0.96300f * _b1 + white * 0.2965164f;
1790                                 _b2 = 0.57000f * _b2 + white * 1.0526913f;
1791                                 _buffer[i] = _b0 + _b1 + _b2 + white * 0.1848f;
1792                         }
1793                         break;
1794         }
1795         _gen_cycle = true;
1796 }
1797
1798 void* DummyAudioPort::get_buffer (pframes_t n_samples)
1799 {
1800         if (is_input ()) {
1801                 std::vector<DummyPort*>::const_iterator it = get_connections ().begin ();
1802                 if (it == get_connections ().end ()) {
1803                         memset (_buffer, 0, n_samples * sizeof (Sample));
1804                 } else {
1805                         DummyAudioPort * source = static_cast<DummyAudioPort*>(*it);
1806                         assert (source && source->is_output ());
1807                         if (source->is_physical() && source->is_terminal()) {
1808                                 source->get_buffer(n_samples); // generate signal.
1809                         }
1810                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
1811                         while (++it != get_connections ().end ()) {
1812                                 source = static_cast<DummyAudioPort*>(*it);
1813                                 assert (source && source->is_output ());
1814                                 Sample* dst = buffer ();
1815                                 if (source->is_physical() && source->is_terminal()) {
1816                                         source->get_buffer(n_samples); // generate signal.
1817                                 }
1818                                 const Sample* src = source->const_buffer ();
1819                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
1820                                         *dst += *src;
1821                                 }
1822                         }
1823                 }
1824         } else if (is_output () && is_physical () && is_terminal()) {
1825                 if (!_gen_cycle) {
1826                         generate(n_samples);
1827                 }
1828         }
1829         return _buffer;
1830 }
1831
1832
1833 DummyMidiPort::DummyMidiPort (DummyAudioBackend &b, const std::string& name, PortFlags flags)
1834         : DummyPort (b, name, flags)
1835         , _midi_seq_spb (0)
1836         , _midi_seq_time (0)
1837         , _midi_seq_pos (0)
1838 {
1839         _buffer.clear ();
1840         _loopback.clear ();
1841 }
1842
1843 DummyMidiPort::~DummyMidiPort () {
1844         _buffer.clear ();
1845         _loopback.clear ();
1846 }
1847
1848 struct MidiEventSorter {
1849         bool operator() (const boost::shared_ptr<DummyMidiEvent>& a, const boost::shared_ptr<DummyMidiEvent>& b) {
1850                 return *a < *b;
1851         }
1852 };
1853
1854 void DummyMidiPort::set_loopback (DummyMidiBuffer const * const src)
1855 {
1856         _loopback.clear ();
1857         for (DummyMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
1858                 _loopback.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (**it)));
1859         }
1860 }
1861
1862 void DummyMidiPort::setup_generator (int seq_id, const float sr)
1863 {
1864         DummyPort::setup_random_number_generator();
1865         _midi_seq_dat = DummyMidiData::sequences[seq_id % NUM_MIDI_EVENT_GENERATORS];
1866         _midi_seq_spb = sr * .5f; // 120 BPM, beat_time 1.0 per beat.
1867         _midi_seq_pos = 0;
1868         _midi_seq_time = 0;
1869 }
1870
1871 void DummyMidiPort::midi_generate (const pframes_t n_samples)
1872 {
1873         Glib::Threads::Mutex::Lock lm (generator_lock);
1874         if (_gen_cycle) {
1875                 return;
1876         }
1877
1878         _buffer.clear ();
1879         _gen_cycle = true;
1880
1881         if (_midi_seq_spb == 0 || !_midi_seq_dat) {
1882                 for (DummyMidiBuffer::const_iterator it = _loopback.begin (); it != _loopback.end (); ++it) {
1883                         _buffer.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (**it)));
1884                 }
1885                 return;
1886         }
1887
1888         while (1) {
1889                 const int32_t ev_beat_time = _midi_seq_dat[_midi_seq_pos].beat_time * _midi_seq_spb - _midi_seq_time;
1890                 if (ev_beat_time < 0) {
1891                         break;
1892                 }
1893                 if ((pframes_t) ev_beat_time >= n_samples) {
1894                         break;
1895                 }
1896                 _buffer.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (
1897                                                 ev_beat_time,
1898                                                 _midi_seq_dat[_midi_seq_pos].event,
1899                                                 _midi_seq_dat[_midi_seq_pos].size
1900                                                 )));
1901                 ++_midi_seq_pos;
1902
1903                 if (_midi_seq_dat[_midi_seq_pos].event[0] == 0xff && _midi_seq_dat[_midi_seq_pos].event[1] == 0xff) {
1904                         _midi_seq_time -= _midi_seq_dat[_midi_seq_pos].beat_time * _midi_seq_spb;
1905                         _midi_seq_pos = 0;
1906                 }
1907         }
1908         _midi_seq_time += n_samples;
1909 }
1910
1911
1912 void* DummyMidiPort::get_buffer (pframes_t n_samples)
1913 {
1914         if (is_input ()) {
1915                 _buffer.clear ();
1916                 for (std::vector<DummyPort*>::const_iterator i = get_connections ().begin ();
1917                                 i != get_connections ().end ();
1918                                 ++i) {
1919                         DummyMidiPort * source = static_cast<DummyMidiPort*>(*i);
1920                         if (source->is_physical() && source->is_terminal()) {
1921                                 source->get_buffer(n_samples); // generate signal.
1922                         }
1923                         const DummyMidiBuffer *src = source->const_buffer ();
1924                         for (DummyMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
1925                                 _buffer.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (**it)));
1926                         }
1927                 }
1928                 std::sort (_buffer.begin (), _buffer.end (), MidiEventSorter());
1929         } else if (is_output () && is_physical () && is_terminal()) {
1930                 if (!_gen_cycle) {
1931                         midi_generate(n_samples);
1932                 }
1933         }
1934         return &_buffer;
1935 }
1936
1937 DummyMidiEvent::DummyMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
1938         : _size (size)
1939         , _timestamp (timestamp)
1940         , _data (0)
1941 {
1942         if (size > 0) {
1943                 _data = (uint8_t*) malloc (size);
1944                 memcpy (_data, data, size);
1945         }
1946 }
1947
1948 DummyMidiEvent::DummyMidiEvent (const DummyMidiEvent& other)
1949         : _size (other.size ())
1950         , _timestamp (other.timestamp ())
1951         , _data (0)
1952 {
1953         if (other.size () && other.const_data ()) {
1954                 _data = (uint8_t*) malloc (other.size ());
1955                 memcpy (_data, other.const_data (), other.size ());
1956         }
1957 };
1958
1959 DummyMidiEvent::~DummyMidiEvent () {
1960         free (_data);
1961 };