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