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