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