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