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