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