Use Glib::usleep in DummyAudioBackend rather than ::usleep
[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
23 #include <glibmm.h>
24
25 #include "dummy_audiobackend.h"
26 #include "pbd/error.h"
27 #include "i18n.h"
28
29 using namespace ARDOUR;
30
31 static std::string s_instance_name;
32 size_t DummyAudioBackend::_max_buffer_size = 8192;
33
34 DummyAudioBackend::DummyAudioBackend (AudioEngine& e, AudioBackendInfo& info)
35         : AudioBackend (e, info)
36         , _running (false)
37         , _freewheeling (false)
38         , _samplerate (48000)
39         , _samples_per_period (1024)
40         , _dsp_load (0)
41         , _n_inputs (0)
42         , _n_outputs (0)
43         , _systemic_input_latency (0)
44         , _systemic_output_latency (0)
45         , _processed_samples (0)
46 {
47         _instance_name = s_instance_name;
48 }
49
50 DummyAudioBackend::~DummyAudioBackend ()
51 {
52 }
53
54 /* AUDIOBACKEND API */
55
56 std::string
57 DummyAudioBackend::name () const
58 {
59         return X_("Dummy");
60 }
61
62 bool
63 DummyAudioBackend::is_realtime () const
64 {
65         return false;
66 }
67
68 std::vector<AudioBackend::DeviceStatus>
69 DummyAudioBackend::enumerate_devices () const
70 {
71         std::vector<AudioBackend::DeviceStatus> s;
72         s.push_back (DeviceStatus (_("Dummy"), true));
73         return s;
74 }
75
76 std::vector<float>
77 DummyAudioBackend::available_sample_rates (const std::string&) const
78 {
79         std::vector<float> sr;
80         sr.push_back (8000.0);
81         sr.push_back (22050.0);
82         sr.push_back (24000.0);
83         sr.push_back (44100.0);
84         sr.push_back (48000.0);
85         sr.push_back (88200.0);
86         sr.push_back (96000.0);
87         sr.push_back (176400.0);
88         sr.push_back (192000.0);
89         return sr;
90 }
91
92 std::vector<uint32_t>
93 DummyAudioBackend::available_buffer_sizes (const std::string&) const
94 {
95         std::vector<uint32_t> bs;
96         bs.push_back (4);
97         bs.push_back (8);
98         bs.push_back (16);
99         bs.push_back (32);
100         bs.push_back (64);
101         bs.push_back (128);
102         bs.push_back (256);
103         bs.push_back (512);
104         bs.push_back (1024);
105         bs.push_back (2048);
106         bs.push_back (4096);
107         bs.push_back (8192);
108         return bs;
109 }
110
111 uint32_t
112 DummyAudioBackend::available_input_channel_count (const std::string&) const
113 {
114         return 128;
115 }
116
117 uint32_t
118 DummyAudioBackend::available_output_channel_count (const std::string&) const
119 {
120         return 128;
121 }
122
123 bool
124 DummyAudioBackend::can_change_sample_rate_when_running () const
125 {
126         return true;
127 }
128
129 bool
130 DummyAudioBackend::can_change_buffer_size_when_running () const
131 {
132         return true;
133 }
134
135 int
136 DummyAudioBackend::set_device_name (const std::string&)
137 {
138         return 0;
139 }
140
141 int
142 DummyAudioBackend::set_sample_rate (float sr)
143 {
144         if (sr <= 0) { return -1; }
145         _samplerate = sr;
146         engine.sample_rate_change (sr);
147         return 0;
148 }
149
150 int
151 DummyAudioBackend::set_buffer_size (uint32_t bs)
152 {
153         if (bs <= 0 || bs >= _max_buffer_size) {
154                 return -1;
155         }
156         _samples_per_period = bs;
157         engine.buffer_size_change (bs);
158         return 0;
159 }
160
161 int
162 DummyAudioBackend::set_interleaved (bool yn)
163 {
164         if (!yn) { return 0; }
165         return -1;
166 }
167
168 int
169 DummyAudioBackend::set_input_channels (uint32_t cc)
170 {
171         _n_inputs = cc;
172         return 0;
173 }
174
175 int
176 DummyAudioBackend::set_output_channels (uint32_t cc)
177 {
178         _n_outputs = cc;
179         return 0;
180 }
181
182 int
183 DummyAudioBackend::set_systemic_input_latency (uint32_t sl)
184 {
185         _systemic_input_latency = sl;
186         return 0;
187 }
188
189 int
190 DummyAudioBackend::set_systemic_output_latency (uint32_t sl)
191 {
192         _systemic_output_latency = sl;
193         return 0;
194 }
195
196 /* Retrieving parameters */
197 std::string
198 DummyAudioBackend::device_name () const
199 {
200         return _("Dummy Device");
201 }
202
203 float
204 DummyAudioBackend::sample_rate () const
205 {
206         return _samplerate;
207 }
208
209 uint32_t
210 DummyAudioBackend::buffer_size () const
211 {
212         return _samples_per_period;
213 }
214
215 bool
216 DummyAudioBackend::interleaved () const
217 {
218         return false;
219 }
220
221 uint32_t
222 DummyAudioBackend::input_channels () const
223 {
224         return _n_inputs;
225 }
226
227 uint32_t
228 DummyAudioBackend::output_channels () const
229 {
230         return _n_outputs;
231 }
232
233 uint32_t
234 DummyAudioBackend::systemic_input_latency () const
235 {
236         return _systemic_input_latency;
237 }
238
239 uint32_t
240 DummyAudioBackend::systemic_output_latency () const
241 {
242         return _systemic_output_latency;
243 }
244
245 /* MIDI */
246 std::vector<std::string>
247 DummyAudioBackend::enumerate_midi_options () const
248 {
249         std::vector<std::string> m;
250         m.push_back (_("None"));
251         return m;
252 }
253
254 int
255 DummyAudioBackend::set_midi_option (const std::string&)
256 {
257         return -1;
258 }
259
260 std::string
261 DummyAudioBackend::midi_option () const
262 {
263         return "";
264 }
265
266 /* State Control */
267
268 static void * pthread_process (void *arg)
269 {
270         DummyAudioBackend *d = static_cast<DummyAudioBackend *>(arg);
271         d->main_process_thread ();
272         pthread_exit (0);
273         return 0;
274 }
275
276 int
277 DummyAudioBackend::_start (bool /*for_latency_measurement*/)
278 {
279         if (_running) {
280                 PBD::error << _("DummyAudioBackend: already active.") << endmsg;
281                 return -1;
282         }
283
284         if (_ports.size()) {
285                 PBD::warning << _("DummyAudioBackend: recovering from unclean shutdown, port registry is not empty.") << endmsg;
286                 _ports.clear();
287         }
288
289         if (register_system_ports()) {
290                 PBD::error << _("DummyAudioBackend: failed to register system ports.") << endmsg;
291                 return -1;
292         }
293
294         if (engine.reestablish_ports ()) {
295                 PBD::error << _("DummyAudioBackend: Could not re-establish ports.") << endmsg;
296                 stop ();
297                 return -1;
298         }
299
300         engine.reconnect_ports ();
301
302         if (pthread_create (&_main_thread, NULL, pthread_process, this)) {
303                 PBD::error << _("DummyAudioBackend: cannot start.") << endmsg;
304         }
305
306         int timeout = 5000;
307         while (!_running && --timeout > 0) { Glib::usleep (1000); }
308
309         if (timeout == 0 || !_running) {
310                 PBD::error << _("DummyAudioBackend: failed to start process thread.") << endmsg;
311                 return -1;
312         }
313
314         return 0;
315 }
316
317 int
318 DummyAudioBackend::stop ()
319 {
320         void *status;
321         if (!_running) {
322                 return -1;
323         }
324
325         _running = false;
326         if (pthread_join (_main_thread, &status)) {
327                 PBD::error << _("DummyAudioBackend: failed to terminate.") << endmsg;
328                 return -1;
329         }
330         unregister_system_ports();
331         return 0;
332 }
333
334 int
335 DummyAudioBackend::freewheel (bool onoff)
336 {
337         if (onoff == _freewheeling) {
338                 return 0;
339         }
340         _freewheeling = onoff;
341         engine.freewheel_callback (onoff);
342         return 0;
343 }
344
345 float
346 DummyAudioBackend::dsp_load () const
347 {
348         return 100.f * _dsp_load;
349 }
350
351 size_t
352 DummyAudioBackend::raw_buffer_size (DataType t)
353 {
354         switch (t) {
355                 case DataType::AUDIO:
356                         return _max_buffer_size * sizeof(Sample);
357                 case DataType::MIDI:
358                         return _max_buffer_size; // XXX not really limited
359         }
360         return 0;
361 }
362
363 /* Process time */
364 pframes_t
365 DummyAudioBackend::sample_time ()
366 {
367         return _processed_samples;
368 }
369
370 pframes_t
371 DummyAudioBackend::sample_time_at_cycle_start ()
372 {
373         return _processed_samples;
374 }
375
376 pframes_t
377 DummyAudioBackend::samples_since_cycle_start ()
378 {
379         return 0;
380 }
381
382
383 void *
384 DummyAudioBackend::dummy_process_thread (void *arg)
385 {
386         ThreadData* td = reinterpret_cast<ThreadData*> (arg);
387         boost::function<void ()> f = td->f;
388         delete td;
389         f ();
390         return 0;
391 }
392
393 int
394 DummyAudioBackend::create_process_thread (boost::function<void()> func)
395 {
396         pthread_t thread_id;
397         pthread_attr_t attr;
398         size_t stacksize = 100000;
399
400         pthread_attr_init (&attr);
401         pthread_attr_setstacksize (&attr, stacksize);
402         ThreadData* td = new ThreadData (this, func, stacksize);
403
404         if (pthread_create (&thread_id, &attr, dummy_process_thread, td)) {
405                 PBD::error << _("AudioEngine: cannot create process thread.") << endmsg;
406                 return -1;
407         }
408
409         _threads.push_back (thread_id);
410         return 0;
411 }
412
413 int
414 DummyAudioBackend::join_process_threads ()
415 {
416         int rv = 0;
417
418         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
419         {
420                 void *status;
421                 if (pthread_join (*i, &status)) {
422                         PBD::error << _("AudioEngine: cannot terminate process thread.") << endmsg;
423                         rv -= 1;
424                 }
425         }
426         _threads.clear ();
427         return rv;
428 }
429
430 bool
431 DummyAudioBackend::in_process_thread ()
432 {
433         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
434         {
435                 if (pthread_equal (*i, pthread_self ()) != 0) {
436                         return true;
437                 }
438         }
439         return false;
440 }
441
442 uint32_t
443 DummyAudioBackend::process_thread_count ()
444 {
445         return _threads.size ();
446 }
447
448 void
449 DummyAudioBackend::update_latencies ()
450 {
451 }
452
453 /* PORTENGINE API */
454
455 void*
456 DummyAudioBackend::private_handle () const
457 {
458         return NULL;
459 }
460
461 const std::string&
462 DummyAudioBackend::my_name () const
463 {
464         return _instance_name;
465 }
466
467 bool
468 DummyAudioBackend::available () const
469 {
470         return true;
471 }
472
473 uint32_t
474 DummyAudioBackend::port_name_size () const
475 {
476         return 256;
477 }
478
479 int
480 DummyAudioBackend::set_port_name (PortEngine::PortHandle port, const std::string& name)
481 {
482         if (!valid_port (port)) {
483                 PBD::error << _("DummyBackend::set_port_name: Invalid Port(s)") << endmsg;
484                 return -1;
485         }
486         return static_cast<DummyPort*>(port)->set_name (_instance_name + ":" + name);
487 }
488
489 std::string
490 DummyAudioBackend::get_port_name (PortEngine::PortHandle port) const
491 {
492         if (!valid_port (port)) {
493                 PBD::error << _("DummyBackend::get_port_name: Invalid Port(s)") << endmsg;
494                 return std::string ();
495         }
496         return static_cast<DummyPort*>(port)->name ();
497 }
498
499 PortEngine::PortHandle
500 DummyAudioBackend::get_port_by_name (const std::string& name) const
501 {
502         PortHandle port = (PortHandle) find_port (name);
503         return port;
504 }
505
506 int
507 DummyAudioBackend::get_ports (
508                 const std::string& port_name_pattern,
509                 DataType type, PortFlags flags,
510                 std::vector<std::string>& port_names) const
511 {
512         int rv = 0;
513         regex_t port_regex;
514         bool use_regexp = false;
515         if (port_name_pattern.size () > 0) {
516                 if (!regcomp (&port_regex, port_name_pattern.c_str (), REG_EXTENDED|REG_NOSUB)) {
517                         use_regexp = true;
518                 }
519         }
520         for (size_t i = 0; i < _ports.size (); ++i) {
521                 DummyPort* port = _ports[i];
522                 if ((port->type () == type) && (port->flags () & flags)) {
523                         if (!use_regexp || !regexec (&port_regex, port->name ().c_str (), 0, NULL, 0)) {
524                                 port_names.push_back (port->name ());
525                                 ++rv;
526                         }
527                 }
528         }
529         if (use_regexp) {
530                 regfree (&port_regex);
531         }
532         return rv;
533 }
534
535 DataType
536 DummyAudioBackend::port_data_type (PortEngine::PortHandle port) const
537 {
538         if (!valid_port (port)) {
539                 return DataType::NIL;
540         }
541         return static_cast<DummyPort*>(port)->type ();
542 }
543
544 PortEngine::PortHandle
545 DummyAudioBackend::register_port (
546                 const std::string& name,
547                 ARDOUR::DataType type,
548                 ARDOUR::PortFlags flags)
549 {
550         if (name.size () == 0) { return 0; }
551         if (flags & IsPhysical) { return 0; }
552         return add_port (_instance_name + ":" + name, type, flags);
553 }
554
555 PortEngine::PortHandle
556 DummyAudioBackend::add_port (
557                 const std::string& name,
558                 ARDOUR::DataType type,
559                 ARDOUR::PortFlags flags)
560 {
561         assert(name.size ());
562         if (find_port (name)) {
563                 PBD::error << _("DummyBackend::register_port: Port already exists:")
564                                 << " (" << name << ")" << endmsg;
565                 return 0;
566         }
567         DummyPort* port = NULL;
568         switch (type) {
569                 case DataType::AUDIO:
570                         port = new DummyAudioPort (name, flags);
571                         break;
572                 case DataType::MIDI:
573                         port = new DummyMidiPort (name, flags);
574                         break;
575                 default:
576                         PBD::error << _("DummyBackend::register_port: Invalid Data Type.") << endmsg;
577                         return 0;
578         }
579
580         _ports.push_back (port);
581
582         return port;
583 }
584
585 void
586 DummyAudioBackend::unregister_port (PortEngine::PortHandle port_handle)
587 {
588         if (!valid_port (port_handle)) {
589                 PBD::error << _("DummyBackend::unregister_port: Invalid Port.") << endmsg;
590         }
591         DummyPort* port = static_cast<DummyPort*>(port_handle);
592         std::vector<DummyPort*>::iterator i = std::find (_ports.begin (), _ports.end (), static_cast<DummyPort*>(port_handle));
593         if (i == _ports.end ()) {
594                 PBD::error << _("DummyBackend::unregister_port: Failed to find port") << endmsg;
595                 return;
596         }
597         disconnect_all(port_handle);
598         _ports.erase (i);
599         delete port;
600 }
601
602 int
603 DummyAudioBackend::register_system_ports()
604 {
605         LatencyRange lr;
606
607         const int a_ins = _n_inputs > 0 ? _n_inputs : 8;
608         const int a_out = _n_outputs > 0 ? _n_outputs : 8;
609         const int m_ins = 2; // TODO
610         const int m_out = 2;
611
612         /* audio ports */
613         lr.min = lr.max = _samples_per_period + _systemic_input_latency;
614         for (int i = 1; i <= a_ins; ++i) {
615                 char tmp[64];
616                 snprintf(tmp, sizeof(tmp), "system:capture_%d", i);
617                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
618                 if (!p) return -1;
619                 set_latency_range (p, false, lr);
620         }
621
622         lr.min = lr.max = _samples_per_period + _systemic_output_latency;
623         for (int i = 1; i <= a_out; ++i) {
624                 char tmp[64];
625                 snprintf(tmp, sizeof(tmp), "system:playback_%d", i);
626                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
627                 if (!p) return -1;
628                 set_latency_range (p, false, lr);
629         }
630
631         /* midi ports */
632         lr.min = lr.max = _samples_per_period + _systemic_input_latency;
633         for (int i = 1; i <= m_ins; ++i) {
634                 char tmp[64];
635                 snprintf(tmp, sizeof(tmp), "system:midi_capture_%d", i);
636                 PortHandle p = add_port(std::string(tmp), DataType::MIDI, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
637                 if (!p) return -1;
638                 set_latency_range (p, false, lr);
639         }
640
641         lr.min = lr.max = _samples_per_period + _systemic_output_latency;
642         for (int i = 1; i <= m_out; ++i) {
643                 char tmp[64];
644                 snprintf(tmp, sizeof(tmp), "system:midi_playback_%d", i);
645                 PortHandle p = add_port(std::string(tmp), DataType::MIDI, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
646                 if (!p) return -1;
647                 set_latency_range (p, false, lr);
648         }
649
650         return 0;
651 }
652
653 void
654 DummyAudioBackend::unregister_system_ports()
655 {
656         size_t i = 0;
657         while (i <  _ports.size ()) {
658                 DummyPort* port = _ports[i];
659                 if (port->is_physical () && port->is_terminal ()) {
660                         port->disconnect_all ();
661                         _ports.erase (_ports.begin() + i);
662                 } else {
663                         ++i;
664                 }
665         }
666 }
667
668 int
669 DummyAudioBackend::connect (const std::string& src, const std::string& dst)
670 {
671         DummyPort* src_port = find_port (src);
672         DummyPort* dst_port = find_port (dst);
673
674         if (!src_port) {
675                 PBD::error << _("DummyBackend::connect: Invalid Source port:")
676                                 << " (" << src <<")" << endmsg;
677                 return -1;
678         }
679         if (!dst_port) {
680                 PBD::error << _("DummyBackend::connect: Invalid Destination port:")
681                         << " (" << dst <<")" << endmsg;
682                 return -1;
683         }
684         return src_port->connect (dst_port);
685 }
686
687 int
688 DummyAudioBackend::disconnect (const std::string& src, const std::string& dst)
689 {
690         DummyPort* src_port = find_port (src);
691         DummyPort* dst_port = find_port (dst);
692
693         if (!src_port || !dst_port) {
694                 PBD::error << _("DummyBackend::disconnect: Invalid Port(s)") << endmsg;
695                 return -1;
696         }
697         return src_port->disconnect (dst_port);
698 }
699
700 int
701 DummyAudioBackend::connect (PortEngine::PortHandle src, const std::string& dst)
702 {
703         DummyPort* dst_port = find_port (dst);
704         if (!valid_port (src)) {
705                 PBD::error << _("DummyBackend::connect: Invalid Source Port Handle") << endmsg;
706                 return -1;
707         }
708         if (!dst_port) {
709                 PBD::error << _("DummyBackend::connect: Invalid Destination Port")
710                         << " (" << dst << ")" << endmsg;
711                 return -1;
712         }
713         return static_cast<DummyPort*>(src)->connect (dst_port);
714 }
715
716 int
717 DummyAudioBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
718 {
719         DummyPort* dst_port = find_port (dst);
720         if (!valid_port (src) || !dst_port) {
721                 PBD::error << _("DummyBackend::disconnect: Invalid Port(s)") << endmsg;
722                 return -1;
723         }
724         return static_cast<DummyPort*>(src)->disconnect (dst_port);
725 }
726
727 int
728 DummyAudioBackend::disconnect_all (PortEngine::PortHandle port)
729 {
730         if (!valid_port (port)) {
731                 PBD::error << _("DummyBackend::disconnect_all: Invalid Port") << endmsg;
732                 return -1;
733         }
734         static_cast<DummyPort*>(port)->disconnect_all ();
735         return 0;
736 }
737
738 bool
739 DummyAudioBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
740 {
741         if (!valid_port (port)) {
742                 PBD::error << _("DummyBackend::disconnect_all: Invalid Port") << endmsg;
743                 return false;
744         }
745         return static_cast<DummyPort*>(port)->is_connected ();
746 }
747
748 bool
749 DummyAudioBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
750 {
751         DummyPort* dst_port = find_port (dst);
752         if (!valid_port (src) || !dst_port) {
753                 PBD::error << _("DummyBackend::connected_to: Invalid Port") << endmsg;
754                 return false;
755         }
756         return static_cast<DummyPort*>(src)->is_connected (dst_port);
757 }
758
759 bool
760 DummyAudioBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
761 {
762         if (!valid_port (port)) {
763                 PBD::error << _("DummyBackend::physically_connected: Invalid Port") << endmsg;
764                 return false;
765         }
766         return static_cast<DummyPort*>(port)->is_physically_connected ();
767 }
768
769 int
770 DummyAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
771 {
772         if (!valid_port (port)) {
773                 PBD::error << _("DummyBackend::get_connections: Invalid Port") << endmsg;
774                 return -1;
775         }
776
777         assert (0 == names.size ());
778
779         const std::vector<DummyPort*>& connected_ports = static_cast<DummyPort*>(port)->get_connections ();
780
781         for (std::vector<DummyPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
782                 names.push_back ((*i)->name ());
783         }
784
785         return (int)names.size ();
786 }
787
788 /* MIDI */
789 int
790 DummyAudioBackend::midi_event_get (
791                 pframes_t& timestamp,
792                 size_t& size, uint8_t** buf, void* port_buffer,
793                 uint32_t event_index)
794 {
795         assert (buf && port_buffer);
796         DummyMidiBuffer& source = * static_cast<DummyMidiBuffer*>(port_buffer);
797         if (event_index >= source.size ()) {
798                 return -1;
799         }
800         DummyMidiEvent * const event = source[event_index].get ();
801
802         timestamp = event->timestamp ();
803         size = event->size ();
804         *buf = event->data ();
805         return 0;
806 }
807
808 int
809 DummyAudioBackend::midi_event_put (
810                 void* port_buffer,
811                 pframes_t timestamp,
812                 const uint8_t* buffer, size_t size)
813 {
814         assert (buffer && port_buffer);
815         DummyMidiBuffer& dst = * static_cast<DummyMidiBuffer*>(port_buffer);
816         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
817                 fprintf (stderr, "DummyMidiBuffer: it's too late for this event.\n");
818                 return -1;
819         }
820         dst.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (timestamp, buffer, size)));
821         return 0;
822 }
823
824 uint32_t
825 DummyAudioBackend::get_midi_event_count (void* port_buffer)
826 {
827         assert (port_buffer && _running);
828         return static_cast<DummyMidiBuffer*>(port_buffer)->size ();
829 }
830
831 void
832 DummyAudioBackend::midi_clear (void* port_buffer)
833 {
834         assert (port_buffer && _running);
835         DummyMidiBuffer * buf = static_cast<DummyMidiBuffer*>(port_buffer);
836         assert (buf);
837         buf->clear ();
838 }
839
840 /* Monitoring */
841
842 bool
843 DummyAudioBackend::can_monitor_input () const
844 {
845         return false;
846 }
847
848 int
849 DummyAudioBackend::request_input_monitoring (PortEngine::PortHandle, bool)
850 {
851         return -1;
852 }
853
854 int
855 DummyAudioBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
856 {
857         return -1;
858 }
859
860 bool
861 DummyAudioBackend::monitoring_input (PortEngine::PortHandle)
862 {
863         return false;
864 }
865
866 /* Latency management */
867
868 void
869 DummyAudioBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
870 {
871         if (!valid_port (port)) {
872                 PBD::error << _("DummyPort::set_latency_range (): invalid port.") << endmsg;
873         }
874         static_cast<DummyPort*>(port)->set_latency_range (latency_range, for_playback);
875 }
876
877 LatencyRange
878 DummyAudioBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
879 {
880         if (!valid_port (port)) {
881                 PBD::error << _("DummyPort::get_latency_range (): invalid port.") << endmsg;
882                 LatencyRange r;
883                 r.min = 0;
884                 r.max = 0;
885                 return r;
886         }
887         return static_cast<DummyPort*>(port)->latency_range (for_playback);
888 }
889
890 /* Discovering physical ports */
891
892 bool
893 DummyAudioBackend::port_is_physical (PortEngine::PortHandle port) const
894 {
895         if (!valid_port (port)) {
896                 PBD::error << _("DummyPort::port_is_physical (): invalid port.") << endmsg;
897                 return false;
898         }
899         return static_cast<DummyPort*>(port)->is_physical ();
900 }
901
902 void
903 DummyAudioBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
904 {
905         for (size_t i = 0; i < _ports.size (); ++i) {
906                 DummyPort* port = _ports[i];
907                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
908                         port_names.push_back (port->name ());
909                 }
910         }
911 }
912
913 void
914 DummyAudioBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
915 {
916         for (size_t i = 0; i < _ports.size (); ++i) {
917                 DummyPort* port = _ports[i];
918                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
919                         port_names.push_back (port->name ());
920                 }
921         }
922 }
923
924 ChanCount
925 DummyAudioBackend::n_physical_outputs () const
926 {
927         int n_midi = 0;
928         int n_audio = 0;
929         for (size_t i = 0; i < _ports.size (); ++i) {
930                 DummyPort* port = _ports[i];
931                 if (port->is_output () && port->is_physical ()) {
932                         switch (port->type ()) {
933                                 case DataType::AUDIO: ++n_audio; break;
934                                 case DataType::MIDI: ++n_midi; break;
935                                 default: break;
936                         }
937                 }
938         }
939         ChanCount cc;
940         cc.set (DataType::AUDIO, n_audio);
941         cc.set (DataType::MIDI, n_midi);
942         return cc;
943 }
944
945 ChanCount
946 DummyAudioBackend::n_physical_inputs () const
947 {
948         int n_midi = 0;
949         int n_audio = 0;
950         for (size_t i = 0; i < _ports.size (); ++i) {
951                 DummyPort* port = _ports[i];
952                 if (port->is_input () && port->is_physical ()) {
953                         switch (port->type ()) {
954                                 case DataType::AUDIO: ++n_audio; break;
955                                 case DataType::MIDI: ++n_midi; break;
956                                 default: break;
957                         }
958                 }
959         }
960         ChanCount cc;
961         cc.set (DataType::AUDIO, n_audio);
962         cc.set (DataType::MIDI, n_midi);
963         return cc;
964 }
965
966 /* Getting access to the data buffer for a port */
967
968 void*
969 DummyAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
970 {
971         assert (port && _running);
972         assert (valid_port (port));
973         return static_cast<DummyPort*>(port)->get_buffer (nframes);
974 }
975
976 /* Engine Process */
977 void *
978 DummyAudioBackend::main_process_thread ()
979 {
980         AudioEngine::thread_init_callback (this);
981         _running = true;
982         _processed_samples = 0;
983
984         struct timeval clock1, clock2;
985         ::gettimeofday (&clock1, NULL);
986         while (_running) {
987                 if (engine.process_callback (_samples_per_period)) {
988                         return 0;
989                 }
990                 _processed_samples += _samples_per_period;
991                 if (!_freewheeling) {
992                         ::gettimeofday (&clock2, NULL);
993                         const int elapsed_time = (clock2.tv_sec - clock1.tv_sec) * 1000000 + (clock2.tv_usec - clock1.tv_usec);
994                         const int nomial_time = 1000000 * _samples_per_period / _samplerate;
995                         _dsp_load = elapsed_time / (float) nomial_time;
996                         if (elapsed_time < nomial_time) {
997                                 Glib::usleep (nomial_time - elapsed_time);
998                         } else {
999                                 Glib::usleep (100); // don't hog cpu
1000                         }
1001                 } else {
1002                         _dsp_load = 1.0;
1003                         Glib::usleep (100); // don't hog cpu
1004                 }
1005                 ::gettimeofday (&clock1, NULL);
1006         }
1007         _running = false;
1008         return 0;
1009 }
1010
1011
1012 /******************************************************************************/
1013
1014 static boost::shared_ptr<DummyAudioBackend> _instance;
1015
1016 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
1017 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
1018 static int deinstantiate ();
1019 static bool already_configured ();
1020
1021 static ARDOUR::AudioBackendInfo _descriptor = {
1022         "Dummy",
1023         instantiate,
1024         deinstantiate,
1025         backend_factory,
1026         already_configured,
1027 };
1028
1029 static boost::shared_ptr<AudioBackend>
1030 backend_factory (AudioEngine& e)
1031 {
1032         if (!_instance) {
1033                 _instance.reset (new DummyAudioBackend (e, _descriptor));
1034         }
1035         return _instance;
1036 }
1037
1038 static int
1039 instantiate (const std::string& arg1, const std::string& /* arg2 */)
1040 {
1041         s_instance_name = arg1;
1042         return 0;
1043 }
1044
1045 static int
1046 deinstantiate ()
1047 {
1048         _instance.reset ();
1049         return 0;
1050 }
1051
1052 static bool
1053 already_configured ()
1054 {
1055         return false;
1056 }
1057
1058 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
1059 {
1060         return &_descriptor;
1061 }
1062
1063
1064 /******************************************************************************/
1065 DummyPort::DummyPort (const std::string& name, PortFlags flags)
1066         : _name  (name)
1067         , _flags (flags)
1068 {
1069         _capture_latency_range.min = 0;
1070         _capture_latency_range.max = 0;
1071         _playback_latency_range.min = 0;
1072         _playback_latency_range.max = 0;
1073 }
1074
1075 DummyPort::~DummyPort () {
1076         disconnect_all ();
1077 }
1078
1079
1080 int DummyPort::connect (DummyPort *port)
1081 {
1082         if (!port) {
1083                 PBD::error << _("DummyPort::connect (): invalid (null) port") << endmsg;
1084                 return -1;
1085         }
1086
1087         if (type () != port->type ()) {
1088                 PBD::error << _("DummyPort::connect (): wrong port-type") << endmsg;
1089                 return -1;
1090         }
1091
1092         if (is_output () && port->is_output ()) {
1093                 PBD::error << _("DummyPort::connect (): cannot inter-connect output ports.") << endmsg;
1094                 return -1;
1095         }
1096
1097         if (is_input () && port->is_input ()) {
1098                 PBD::error << _("DummyPort::connect (): cannot inter-connect input ports.") << endmsg;
1099                 return -1;
1100         }
1101
1102         if (this == port) {
1103                 PBD::error << _("DummyPort::connect (): cannot self-connect ports.") << endmsg;
1104                 return -1;
1105         }
1106
1107         if (is_connected (port)) {
1108 #if 0 // don't bother to warn about this for now. just ignore it
1109                 PBD::error << _("DummyPort::connect (): ports are already connected:")
1110                         << " (" << name () << ") -> (" << port->name () << ")"
1111                         << endmsg;
1112 #endif
1113                 return -1;
1114         }
1115
1116         _connect (port, true);
1117         return 0;
1118 }
1119
1120
1121 void DummyPort::_connect (DummyPort *port, bool callback)
1122 {
1123         _connections.push_back (port);
1124         if (callback) {
1125                 port->_connect (this, false);
1126         }
1127 }
1128
1129 int DummyPort::disconnect (DummyPort *port)
1130 {
1131         if (!port) {
1132                 PBD::error << _("DummyPort::disconnect (): invalid (null) port") << endmsg;
1133                 return -1;
1134         }
1135
1136         if (!is_connected (port)) {
1137                 PBD::error << _("DummyPort::disconnect (): ports are not connected:")
1138                         << " (" << name () << ") -> (" << port->name () << ")"
1139                         << endmsg;
1140                 return -1;
1141         }
1142         _disconnect (port, true);
1143         return 0;
1144 }
1145
1146 void DummyPort::_disconnect (DummyPort *port, bool callback)
1147 {
1148         std::vector<DummyPort*>::iterator it = std::find (_connections.begin (), _connections.end (), port);
1149
1150         assert (it != _connections.end ());
1151
1152         _connections.erase (it);
1153
1154         if (callback) {
1155                 port->_disconnect (this, false);
1156         }
1157 }
1158
1159
1160 void DummyPort::disconnect_all ()
1161 {
1162         while (!_connections.empty ()) {
1163                 _connections.back ()->_disconnect (this, false);
1164                 _connections.pop_back ();
1165         }
1166 }
1167
1168 bool
1169 DummyPort::is_connected (const DummyPort *port) const
1170 {
1171         return std::find (_connections.begin (), _connections.end (), port) != _connections.end ();
1172 }
1173
1174 bool DummyPort::is_physically_connected () const
1175 {
1176         for (std::vector<DummyPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
1177                 if ((*it)->is_physical ()) {
1178                         return true;
1179                 }
1180         }
1181         return false;
1182 }
1183
1184 /******************************************************************************/
1185
1186 DummyAudioPort::DummyAudioPort (const std::string& name, PortFlags flags)
1187         : DummyPort (name, flags)
1188 {
1189         memset (_buffer, 0, sizeof (_buffer));
1190 }
1191
1192 DummyAudioPort::~DummyAudioPort () { }
1193
1194 void* DummyAudioPort::get_buffer (pframes_t n_samples)
1195 {
1196         if (is_input ()) {
1197                 std::vector<DummyPort*>::const_iterator it = get_connections ().begin ();
1198                 if (it == get_connections ().end ()) {
1199                         memset (_buffer, 0, n_samples * sizeof (Sample));
1200                 } else {
1201                         DummyAudioPort const * source = static_cast<const DummyAudioPort*>(*it);
1202                         assert (source && source->is_output ());
1203                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
1204                         while (++it != get_connections ().end ()) {
1205                                 source = static_cast<const DummyAudioPort*>(*it);
1206                                 assert (source && source->is_output ());
1207                                 Sample* dst = buffer ();
1208                                 const Sample* src = source->const_buffer ();
1209                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
1210                                         *dst += *src;
1211                                 }
1212                         }
1213                 }
1214         } else if (is_output () && is_physical () && is_terminal()) {
1215                 memset (_buffer, 0, n_samples * sizeof (Sample));
1216         }
1217         return _buffer;
1218 }
1219
1220
1221 DummyMidiPort::DummyMidiPort (const std::string& name, PortFlags flags)
1222         : DummyPort (name, flags)
1223 {
1224         _buffer.clear ();
1225 }
1226
1227 DummyMidiPort::~DummyMidiPort () { }
1228
1229 void* DummyMidiPort::get_buffer (pframes_t /* nframes */)
1230 {
1231         if (is_input ()) {
1232                 _buffer.clear ();
1233                 for (std::vector<DummyPort*>::const_iterator i = get_connections ().begin ();
1234                                 i != get_connections ().end ();
1235                                 ++i) {
1236                         const DummyMidiBuffer src = static_cast<const DummyMidiPort*>(*i)->const_buffer ();
1237                         for (DummyMidiBuffer::const_iterator it = src.begin (); it != src.end (); ++it) {
1238                                 _buffer.push_back (boost::shared_ptr<DummyMidiEvent>(new DummyMidiEvent (**it)));
1239                         }
1240                 }
1241                 std::sort (_buffer.begin (), _buffer.end ());
1242         } else if (is_output () && is_physical () && is_terminal()) {
1243                 _buffer.clear ();
1244         }
1245         return &_buffer;
1246 }
1247
1248 DummyMidiEvent::DummyMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
1249         : _size (size)
1250         , _timestamp (timestamp)
1251         , _data (0)
1252 {
1253         if (size > 0) {
1254                 _data = (uint8_t*) malloc (size);
1255          memcpy (_data, data, size);
1256         }
1257 }
1258
1259 DummyMidiEvent::DummyMidiEvent (const DummyMidiEvent& other)
1260         : _size (other.size ())
1261         , _timestamp (other.timestamp ())
1262         , _data (0)
1263 {
1264         if (other.size () && other.const_data ()) {
1265                 _data = (uint8_t*) malloc (other.size ());
1266                 memcpy (_data, other.const_data (), other.size ());
1267         }
1268 };
1269
1270 DummyMidiEvent::~DummyMidiEvent () {
1271         free (_data);
1272 };