I wanna be nasty, I wanna be cruel,..
[ardour.git] / libs / backends / asio / asio_backend.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 <regex.h>
21 #include <sys/mman.h>
22 #include <sys/time.h>
23
24 #include <glibmm.h>
25
26 #include "asio_backend.h"
27 #include "rt_thread.h"
28
29 #include "pbd/compose.h"
30 #include "pbd/error.h"
31 #include "pbd/file_utils.h"
32 #include "ardour/filesystem_paths.h"
33 #include "ardour/port_manager.h"
34 #include "i18n.h"
35
36 using namespace ARDOUR;
37
38 static std::string s_instance_name;
39 size_t ASIOBackend::_max_buffer_size = 8192;
40 std::vector<std::string> ASIOBackend::_midi_options;
41 std::vector<AudioBackend::DeviceStatus> ASIOBackend::_audio_device_status;
42
43
44 /* static class instance access */
45 static void hw_changed_callback_ptr (void *arg)
46 {
47         ASIOBackend *d = static_cast<ASIOBackend*> (arg);
48         d->hw_changed_callback();
49 }
50
51 static void error_callback_ptr (void *arg)
52 {
53         ASIOBackend *d = static_cast<ASIOBackend*> (arg);
54         d->error_callback();
55 }
56
57 static void xrun_callback_ptr (void *arg)
58 {
59         ASIOBackend *d = static_cast<ASIOBackend*> (arg);
60         d->xrun_callback();
61 }
62
63 static void buffer_size_callback_ptr (void *arg)
64 {
65         ASIOBackend *d = static_cast<ASIOBackend*> (arg);
66         d->buffer_size_callback();
67 }
68
69 static void sample_rate_callback_ptr (void *arg)
70 {
71         ASIOBackend *d = static_cast<ASIOBackend*> (arg);
72         d->sample_rate_callback();
73 }
74
75
76 ASIOBackend::ASIOBackend (AudioEngine& e, AudioBackendInfo& info)
77         : AudioBackend (e, info)
78         , _run (false)
79         , _active_cb (false)
80         , _active_fw (false)
81         , _freewheeling (false)
82         , _freewheel (false)
83         , _freewheel_ack (false)
84         , _reinit_thread_callback (false)
85         , _measure_latency (false)
86         , _last_process_start (0)
87         , _audio_device("")
88         , _midi_driver_option(_("None"))
89         , _samplerate (48000)
90         , _samples_per_period (1024)
91         , _n_inputs (0)
92         , _n_outputs (0)
93         , _systemic_audio_input_latency (0)
94         , _systemic_audio_output_latency (0)
95         , _dsp_load (0)
96         , _processed_samples (0)
97         , _port_change_flag (false)
98 {
99         _instance_name = s_instance_name;
100         pthread_mutex_init (&_port_callback_mutex, 0);
101         pthread_mutex_init (&_process_callback_mutex, 0);
102         pthread_mutex_init (&_freewheel_mutex, 0);
103         pthread_cond_init  (&_freewheel_signal, 0);
104
105 #if 0 // TODO
106         //_pcmio = new ASIOPCM ();
107         //_midiio = new WindowsMidiIo ();
108
109         _pcmio->set_hw_changed_callback (hw_changed_callback_ptr, this);
110         _pcmio->discover();
111 #endif
112 }
113
114 ASIOBackend::~ASIOBackend ()
115 {
116 #if 0
117         delete _pcmio; _pcmio = 0; // TODO
118         delete _midiio; _midiio = 0; // TODO
119 #endif
120         pthread_mutex_destroy (&_port_callback_mutex);
121         pthread_mutex_destroy (&_process_callback_mutex);
122         pthread_mutex_destroy (&_freewheel_mutex);
123         pthread_cond_destroy  (&_freewheel_signal);
124 }
125
126 /* AUDIOBACKEND API */
127
128 std::string
129 ASIOBackend::name () const
130 {
131         return X_("ASIO");
132 }
133
134 bool
135 ASIOBackend::is_realtime () const
136 {
137         return true;
138 }
139
140 std::vector<AudioBackend::DeviceStatus>
141 ASIOBackend::enumerate_devices () const
142 {
143         _audio_device_status.clear();
144 #if 0 // TODO
145         std::map<size_t, std::string> devices;
146         _pcmio->device_list(devices);
147
148         for (std::map<size_t, std::string>::const_iterator i = devices.begin (); i != devices.end(); ++i) {
149                 if (_audio_device == "") _audio_device = i->second;
150                 _audio_device_status.push_back (DeviceStatus (i->second, true));
151         }
152 #endif
153         return _audio_device_status;
154 }
155
156 std::vector<float>
157 ASIOBackend::available_sample_rates (const std::string&) const
158 {
159         std::vector<float> sr;
160 #if 0 // TODO
161         _pcmio->available_sample_rates(_audio_device, sr);
162 #endif
163         return sr;
164 }
165
166 std::vector<uint32_t>
167 ASIOBackend::available_buffer_sizes (const std::string&) const
168 {
169         std::vector<uint32_t> bs;
170 #if 0 // TODO
171         _pcmio->available_buffer_sizes(_audio_device, bs);
172 #endif
173         return bs;
174 }
175
176 uint32_t
177 ASIOBackend::available_input_channel_count (const std::string&) const
178 {
179         return 128; // TODO query current device
180 }
181
182 uint32_t
183 ASIOBackend::available_output_channel_count (const std::string&) const
184 {
185         return 128; // TODO query current device
186 }
187
188 bool
189 ASIOBackend::can_change_sample_rate_when_running () const
190 {
191         return false;
192 }
193
194 bool
195 ASIOBackend::can_change_buffer_size_when_running () const
196 {
197         return true;
198 }
199
200 int
201 ASIOBackend::set_device_name (const std::string& d)
202 {
203         _audio_device = d;
204 #if 0 // TODO
205         const float sr = _pcmio->current_sample_rate(_audio_device);
206 #endif
207         //if (sr > 0) { set_sample_rate(sr); }
208         return 0;
209 }
210
211 int
212 ASIOBackend::set_sample_rate (float sr)
213 {
214         if (sr <= 0) { return -1; }
215         // TODO check if it's in the list of valid SR
216         _samplerate = sr;
217         engine.sample_rate_change (sr);
218         return 0;
219 }
220
221 int
222 ASIOBackend::set_buffer_size (uint32_t bs)
223 {
224         if (bs <= 0 || bs >= _max_buffer_size) {
225                 return -1;
226         }
227         _samples_per_period = bs;
228 #if 0 // TODO
229         _pcmio->set_samples_per_period(bs);
230 #endif
231         engine.buffer_size_change (bs);
232         return 0;
233 }
234
235 int
236 ASIOBackend::set_interleaved (bool yn)
237 {
238         if (!yn) { return 0; }
239         return -1;
240 }
241
242 int
243 ASIOBackend::set_input_channels (uint32_t cc)
244 {
245         _n_inputs = cc;
246         return 0;
247 }
248
249 int
250 ASIOBackend::set_output_channels (uint32_t cc)
251 {
252         _n_outputs = cc;
253         return 0;
254 }
255
256 int
257 ASIOBackend::set_systemic_input_latency (uint32_t sl)
258 {
259         _systemic_audio_input_latency = sl;
260         return 0;
261 }
262
263 int
264 ASIOBackend::set_systemic_output_latency (uint32_t sl)
265 {
266         _systemic_audio_output_latency = sl;
267         return 0;
268 }
269
270 /* Retrieving parameters */
271 std::string
272 ASIOBackend::device_name () const
273 {
274         return _audio_device;
275 }
276
277 float
278 ASIOBackend::sample_rate () const
279 {
280         return _samplerate;
281 }
282
283 uint32_t
284 ASIOBackend::buffer_size () const
285 {
286         return _samples_per_period;
287 }
288
289 bool
290 ASIOBackend::interleaved () const
291 {
292         return false;
293 }
294
295 uint32_t
296 ASIOBackend::input_channels () const
297 {
298         return _n_inputs;
299 }
300
301 uint32_t
302 ASIOBackend::output_channels () const
303 {
304         return _n_outputs;
305 }
306
307 uint32_t
308 ASIOBackend::systemic_input_latency () const
309 {
310         return _systemic_audio_input_latency;
311 }
312
313 uint32_t
314 ASIOBackend::systemic_output_latency () const
315 {
316         return _systemic_audio_output_latency;
317 }
318
319 /* MIDI */
320
321 std::vector<std::string>
322 ASIOBackend::enumerate_midi_options () const
323 {
324         if (_midi_options.empty()) {
325                 _midi_options.push_back (_("WindowsMidi"));
326                 _midi_options.push_back (_("None"));
327         }
328         return _midi_options;
329 }
330
331 int
332 ASIOBackend::set_midi_option (const std::string& opt)
333 {
334         if (opt != _("None") && opt != _("WindowsMidi")) {
335                 return -1;
336         }
337         _midi_driver_option = opt;
338         return 0;
339 }
340
341 std::string
342 ASIOBackend::midi_option () const
343 {
344         return _midi_driver_option;
345 }
346
347 void
348 ASIOBackend::launch_control_app ()
349 {
350         // TODO
351 }
352
353 /* State Control */
354
355 static void * pthread_freewheel (void *arg)
356 {
357         ASIOBackend *d = static_cast<ASIOBackend *>(arg);
358         d->freewheel_thread ();
359         pthread_exit (0);
360         return 0;
361 }
362
363 static int process_callback_ptr (void *arg, const uint32_t n_samples, const uint64_t host_time)
364 {
365         ASIOBackend *d = static_cast<ASIOBackend*> (arg);
366         return d->process_callback(n_samples, host_time);
367 }
368
369 int
370 ASIOBackend::_start (bool for_latency_measurement)
371 {
372         if ((!_active_cb || !_active_fw)  && _run) {
373                 // recover from 'halted', reap threads
374                 stop();
375         }
376
377         if (_active_cb || _active_fw || _run) {
378                 PBD::error << _("ASIOBackend: already active.") << endmsg;
379                 return -1;
380         }
381
382         if (_ports.size()) {
383                 PBD::warning << _("ASIOBackend: recovering from unclean shutdown, port registry is not empty.") << endmsg;
384                 _system_inputs.clear();
385                 _system_outputs.clear();
386                 _system_midi_in.clear();
387                 _system_midi_out.clear();
388                 _ports.clear();
389         }
390
391         assert(_active_cb == false);
392         assert(_active_fw == false);
393
394         _freewheel_ack = false;
395         _reinit_thread_callback = true;
396         _last_process_start = 0;
397
398 #if 0 // TODO
399         _pcmio->set_error_callback (error_callback_ptr, this);
400         _pcmio->set_buffer_size_callback (buffer_size_callback_ptr, this);
401         _pcmio->set_sample_rate_callback (sample_rate_callback_ptr, this);
402
403         _pcmio->pcm_start (device1, device2, _samplerate, _samples_per_period, process_callback_ptr, this);
404
405         switch (_pcmio->state ()) {
406                 case 0: /* OK */ break;
407                 case -1: PBD::error << _("ASIOBackend: failed to open device.") << endmsg; break;
408                 default: PBD::error << _("ASIOBackend: initialization failed.") << endmsg; break;
409         }
410         if (_pcmio->state ()) {
411                 return -1;
412         }
413
414         if (_n_outputs != _pcmio->n_playback_channels ()) {
415                 if (_n_outputs == 0) {
416                  _n_outputs = _pcmio->n_playback_channels ();
417                 } else {
418                  _n_outputs = std::min (_n_outputs, _pcmio->n_playback_channels ());
419                 }
420                 PBD::info << _("ASIOBackend: adjusted output channel count to match device.") << endmsg;
421         }
422
423         if (_n_inputs != _pcmio->n_capture_channels ()) {
424                 if (_n_inputs == 0) {
425                  _n_inputs = _pcmio->n_capture_channels ();
426                 } else {
427                  _n_inputs = std::min (_n_inputs, _pcmio->n_capture_channels ());
428                 }
429                 PBD::info << _("ASIOBackend: adjusted input channel count to match device.") << endmsg;
430         }
431
432         if (_pcmio->samples_per_period() != _samples_per_period) {
433                 _samples_per_period = _pcmio->samples_per_period();
434                 PBD::warning << _("ASIOBackend: samples per period does not match.") << endmsg;
435         }
436
437         if (_pcmio->sample_rate() != _samplerate) {
438                 _samplerate = _pcmio->sample_rate();
439                 engine.sample_rate_change (_samplerate);
440                 PBD::warning << _("ASIOBackend: sample rate does not match.") << endmsg;
441         }
442 #endif
443
444         _measure_latency = for_latency_measurement;
445
446         _preinit = true;
447         _run = true;
448         _port_change_flag = false;
449
450 #if 0 // TODO
451         if (_midi_driver_option == _("WindowsMidi")) {
452                 // TODO
453                 //_midiio->set_enabled(true);
454                 //_midiio->set_port_changed_callback(midi_port_change, this);
455                 //_midiio->start(); // triggers port discovery, callback coremidi_rediscover()
456         }
457 #endif
458
459         if (register_system_audio_ports()) {
460                 PBD::error << _("ASIOBackend: failed to register system ports.") << endmsg;
461                 _run = false;
462                 return -1;
463         }
464
465         engine.sample_rate_change (_samplerate);
466         engine.buffer_size_change (_samples_per_period);
467
468         if (engine.reestablish_ports ()) {
469                 PBD::error << _("ASIOBackend: Could not re-establish ports.") << endmsg;
470                 _run = false;
471                 return -1;
472         }
473
474         if (pthread_create (&_freeewheel_thread, NULL, pthread_freewheel, this))
475         {
476                 PBD::error << _("ASIOBackend: failed to create process thread.") << endmsg;
477 #if 0 // TODO
478                 delete _pcmio; _pcmio = 0;
479 #endif
480                 _run = false;
481                 return -1;
482         }
483
484         int timeout = 5000;
485         while ((!_active_cb || !_active_fw) && --timeout > 0) { Glib::usleep (1000); }
486
487         if (timeout == 0) {
488                 PBD::error << _("ASIOBackend: failed to start.") << endmsg;
489         }
490
491         if (!_active_fw) {
492                 PBD::error << _("ASIOBackend: failed to start freewheeling thread.") << endmsg;
493                 _run = false;
494 #if 0 // TODO
495                 _pcmio->pcm_stop();
496 #endif
497                 unregister_ports();
498                 _active_cb = false;
499                 _active_fw = false;
500                 return -1;
501         }
502
503         if (!_active_cb) {
504                 PBD::error << _("ASIOBackend: failed to start ASIO.") << endmsg;
505                 stop();
506                 _run = false;
507                 return -1;
508         }
509
510         engine.reconnect_ports ();
511
512         // force  an initial registration_callback() & latency re-compute
513         _port_change_flag = true;
514         pre_process ();
515
516         // all systems go.
517 #if 0 // TODO
518         _pcmio->set_xrun_callback (xrun_callback_ptr, this);
519 #endif
520         _preinit = false;
521
522         return 0;
523 }
524
525 int
526 ASIOBackend::stop ()
527 {
528         void *status;
529         if (!_run) {
530                 return 0;
531         }
532
533         _run = false;
534 #if 0 // TODO
535         _pcmio->pcm_stop();
536         _midiio->set_port_changed_callback(NULL, NULL);
537         _midiio->stop();
538 #endif
539         pthread_mutex_lock (&_freewheel_mutex);
540         pthread_cond_signal (&_freewheel_signal);
541         pthread_mutex_unlock (&_freewheel_mutex);
542
543         if (pthread_join (_freeewheel_thread, &status)) {
544                 PBD::error << _("ASIOBackend: failed to terminate.") << endmsg;
545                 return -1;
546         }
547
548         unregister_ports();
549
550         _active_cb = false;
551         _active_fw = false; // ??
552
553         return 0;
554 }
555
556 int
557 ASIOBackend::freewheel (bool onoff)
558 {
559         if (onoff == _freewheeling) {
560                 return 0;
561         }
562         _freewheeling = onoff;
563         // wake up freewheeling thread
564         if (0 == pthread_mutex_trylock (&_freewheel_mutex)) {
565                 pthread_cond_signal (&_freewheel_signal);
566                 pthread_mutex_unlock (&_freewheel_mutex);
567         }
568         return 0;
569 }
570
571 float
572 ASIOBackend::dsp_load () const
573 {
574         return 100.f * _dsp_load;
575 }
576
577 size_t
578 ASIOBackend::raw_buffer_size (DataType t)
579 {
580         switch (t) {
581                 case DataType::AUDIO:
582                         return _samples_per_period * sizeof(Sample);
583                 case DataType::MIDI:
584                         return _max_buffer_size; // XXX not really limited
585         }
586         return 0;
587 }
588
589 /* Process time */
590 framepos_t
591 ASIOBackend::sample_time ()
592 {
593         return _processed_samples;
594 }
595
596 framepos_t
597 ASIOBackend::sample_time_at_cycle_start ()
598 {
599         return _processed_samples;
600 }
601
602 pframes_t
603 ASIOBackend::samples_since_cycle_start ()
604 {
605         if (!_active_cb || !_run || _freewheeling || _freewheel) {
606                 return 0;
607         }
608         if (_last_process_start == 0) {
609                 return 0;
610         }
611
612 #if 0 // TODO
613         const uint64_t now = AudioGetCurrentHostTime ();
614         const int64_t elapsed_time_ns = AudioConvertHostTimeToNanos(now - _last_process_start);
615         return std::max((pframes_t)0, (pframes_t)rint(1e-9 * elapsed_time_ns * _samplerate));
616 #else
617         return 0;
618 #endif
619 }
620
621 void *
622 ASIOBackend::asio_process_thread (void *arg)
623 {
624         ThreadData* td = reinterpret_cast<ThreadData*> (arg);
625         boost::function<void ()> f = td->f;
626         delete td;
627         f ();
628         return 0;
629 }
630
631 int
632 ASIOBackend::create_process_thread (boost::function<void()> func)
633 {
634         pthread_t thread_id;
635         pthread_attr_t attr;
636         size_t stacksize = 100000;
637
638         ThreadData* td = new ThreadData (this, func, stacksize);
639
640         if (_realtime_pthread_create (SCHED_FIFO, -21, stacksize,
641                                 &thread_id, asio_process_thread, td)) {
642                 pthread_attr_init (&attr);
643                 pthread_attr_setstacksize (&attr, stacksize);
644                 if (pthread_create (&thread_id, &attr, asio_process_thread, td)) {
645                         PBD::error << _("AudioEngine: cannot create process thread.") << endmsg;
646                         pthread_attr_destroy (&attr);
647                         return -1;
648                 }
649                 pthread_attr_destroy (&attr);
650         }
651
652         _threads.push_back (thread_id);
653         return 0;
654 }
655
656 int
657 ASIOBackend::join_process_threads ()
658 {
659         int rv = 0;
660
661         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
662         {
663                 void *status;
664                 if (pthread_join (*i, &status)) {
665                         PBD::error << _("AudioEngine: cannot terminate process thread.") << endmsg;
666                         rv -= 1;
667                 }
668         }
669         _threads.clear ();
670         return rv;
671 }
672
673 bool
674 ASIOBackend::in_process_thread ()
675 {
676         if (pthread_equal (_main_thread, pthread_self()) != 0) {
677                 return true;
678         }
679
680         for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
681         {
682                 if (pthread_equal (*i, pthread_self ()) != 0) {
683                         return true;
684                 }
685         }
686         return false;
687 }
688
689 uint32_t
690 ASIOBackend::process_thread_count ()
691 {
692         return _threads.size ();
693 }
694
695 void
696 ASIOBackend::update_latencies ()
697 {
698         // trigger latency callback in RT thread (locked graph)
699         port_connect_add_remove_callback();
700 }
701
702 /* PORTENGINE API */
703
704 void*
705 ASIOBackend::private_handle () const
706 {
707         return NULL;
708 }
709
710 const std::string&
711 ASIOBackend::my_name () const
712 {
713         return _instance_name;
714 }
715
716 bool
717 ASIOBackend::available () const
718 {
719         return _run && _active_fw && _active_cb;
720 }
721
722 uint32_t
723 ASIOBackend::port_name_size () const
724 {
725         return 256;
726 }
727
728 int
729 ASIOBackend::set_port_name (PortEngine::PortHandle port, const std::string& name)
730 {
731         if (!valid_port (port)) {
732                 PBD::error << _("ASIOBackend::set_port_name: Invalid Port(s)") << endmsg;
733                 return -1;
734         }
735         return static_cast<ASIOBackendPort*>(port)->set_name (_instance_name + ":" + name);
736 }
737
738 std::string
739 ASIOBackend::get_port_name (PortEngine::PortHandle port) const
740 {
741         if (!valid_port (port)) {
742                 PBD::error << _("ASIOBackend::get_port_name: Invalid Port(s)") << endmsg;
743                 return std::string ();
744         }
745         return static_cast<ASIOBackendPort*>(port)->name ();
746 }
747
748 int
749 ASIOBackend::get_port_property (PortHandle port, const std::string& key, std::string& value, std::string& type) const
750 {
751         if (!valid_port (port)) {
752                 PBD::error << _("ASIOBackend::get_port_name: Invalid Port(s)") << endmsg;
753                 return -1;
754         }
755         if (key == "http://jackaudio.org/metadata/pretty-name") {
756                 type = "";
757                 value = static_cast<ASIOBackendPort*>(port)->pretty_name ();
758                 if (!value.empty()) {
759                         return 0;
760                 }
761         }
762         return -1;
763 }
764
765 PortEngine::PortHandle
766 ASIOBackend::get_port_by_name (const std::string& name) const
767 {
768         PortHandle port = (PortHandle) find_port (name);
769         return port;
770 }
771
772 int
773 ASIOBackend::get_ports (
774                 const std::string& port_name_pattern,
775                 DataType type, PortFlags flags,
776                 std::vector<std::string>& port_names) const
777 {
778         int rv = 0;
779         regex_t port_regex;
780         bool use_regexp = false;
781         if (port_name_pattern.size () > 0) {
782                 if (!regcomp (&port_regex, port_name_pattern.c_str (), REG_EXTENDED|REG_NOSUB)) {
783                         use_regexp = true;
784                 }
785         }
786         for (size_t i = 0; i < _ports.size (); ++i) {
787                 ASIOBackendPort* port = _ports[i];
788                 if ((port->type () == type) && (port->flags () & flags)) {
789                         if (!use_regexp || !regexec (&port_regex, port->name ().c_str (), 0, NULL, 0)) {
790                                 port_names.push_back (port->name ());
791                                 ++rv;
792                         }
793                 }
794         }
795         if (use_regexp) {
796                 regfree (&port_regex);
797         }
798         return rv;
799 }
800
801 DataType
802 ASIOBackend::port_data_type (PortEngine::PortHandle port) const
803 {
804         if (!valid_port (port)) {
805                 return DataType::NIL;
806         }
807         return static_cast<ASIOBackendPort*>(port)->type ();
808 }
809
810 PortEngine::PortHandle
811 ASIOBackend::register_port (
812                 const std::string& name,
813                 ARDOUR::DataType type,
814                 ARDOUR::PortFlags flags)
815 {
816         if (name.size () == 0) { return 0; }
817         if (flags & IsPhysical) { return 0; }
818         return add_port (_instance_name + ":" + name, type, flags);
819 }
820
821 PortEngine::PortHandle
822 ASIOBackend::add_port (
823                 const std::string& name,
824                 ARDOUR::DataType type,
825                 ARDOUR::PortFlags flags)
826 {
827         assert(name.size ());
828         if (find_port (name)) {
829                 PBD::error << _("ASIOBackend::register_port: Port already exists:")
830                                 << " (" << name << ")" << endmsg;
831                 return 0;
832         }
833         ASIOBackendPort* port = NULL;
834         switch (type) {
835                 case DataType::AUDIO:
836                         port = new ASIOPort (*this, name, flags);
837                         break;
838                 case DataType::MIDI:
839                         port = new WindowsMidiPort (*this, name, flags);
840                         break;
841                 default:
842                         PBD::error << _("ASIOBackend::register_port: Invalid Data Type.") << endmsg;
843                         return 0;
844         }
845
846         _ports.push_back (port);
847
848         return port;
849 }
850
851 void
852 ASIOBackend::unregister_port (PortEngine::PortHandle port_handle)
853 {
854         if (!_run) {
855                 return;
856         }
857         ASIOBackendPort* port = static_cast<ASIOBackendPort*>(port_handle);
858         std::vector<ASIOBackendPort*>::iterator i = std::find (_ports.begin (), _ports.end (), static_cast<ASIOBackendPort*>(port_handle));
859         if (i == _ports.end ()) {
860                 PBD::error << _("ASIOBackend::unregister_port: Failed to find port") << endmsg;
861                 return;
862         }
863         disconnect_all(port_handle);
864         _ports.erase (i);
865         delete port;
866 }
867
868 int
869 ASIOBackend::register_system_audio_ports()
870 {
871         LatencyRange lr;
872
873         const uint32_t a_ins = _n_inputs;
874         const uint32_t a_out = _n_outputs;
875
876         const uint32_t asio_reported_input_latency =  0; // TODO _pcmio->get_latency(_audio_device, true);
877         const uint32_t asio_reported_output_latency = 0; // TODO _pcmio->get_latency(_audio_device, false);
878
879         /* audio ports */
880         lr.min = lr.max = asio_reported_input_latency + (_measure_latency ? 0 : _systemic_audio_input_latency);
881         for (uint32_t i = 0; i < a_ins; ++i) {
882                 char tmp[64];
883                 snprintf(tmp, sizeof(tmp), "system:capture_%d", i+1);
884                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsOutput | IsPhysical | IsTerminal));
885                 if (!p) return -1;
886                 set_latency_range (p, false, lr);
887                 ASIOBackendPort *cp = static_cast<ASIOBackendPort*>(p);
888                 //cp->set_pretty_name (_pcmio->cached_port_name(i, true)); // TODO
889                 _system_inputs.push_back(cp);
890         }
891
892         lr.min = lr.max = asio_reported_output_latency + (_measure_latency ? 0 : _systemic_audio_output_latency);
893         for (uint32_t i = 0; i < a_out; ++i) {
894                 char tmp[64];
895                 snprintf(tmp, sizeof(tmp), "system:playback_%d", i+1);
896                 PortHandle p = add_port(std::string(tmp), DataType::AUDIO, static_cast<PortFlags>(IsInput | IsPhysical | IsTerminal));
897                 if (!p) return -1;
898                 set_latency_range (p, true, lr);
899                 ASIOBackendPort *cp = static_cast<ASIOBackendPort*>(p);
900                 //cp->set_pretty_name (_pcmio->cached_port_name(i, false)); // TODO
901                 _system_outputs.push_back(cp);
902         }
903         return 0;
904 }
905
906 void
907 ASIOBackend::unregister_ports (bool system_only)
908 {
909         size_t i = 0;
910         _system_inputs.clear();
911         _system_outputs.clear();
912         _system_midi_in.clear();
913         _system_midi_out.clear();
914         while (i <  _ports.size ()) {
915                 ASIOBackendPort* port = _ports[i];
916                 if (! system_only || (port->is_physical () && port->is_terminal ())) {
917                         port->disconnect_all ();
918                         delete port;
919                         _ports.erase (_ports.begin() + i);
920                 } else {
921                         ++i;
922                 }
923         }
924 }
925
926 int
927 ASIOBackend::connect (const std::string& src, const std::string& dst)
928 {
929         ASIOBackendPort* src_port = find_port (src);
930         ASIOBackendPort* dst_port = find_port (dst);
931
932         if (!src_port) {
933                 PBD::error << _("ASIOBackend::connect: Invalid Source port:")
934                                 << " (" << src <<")" << endmsg;
935                 return -1;
936         }
937         if (!dst_port) {
938                 PBD::error << _("ASIOBackend::connect: Invalid Destination port:")
939                         << " (" << dst <<")" << endmsg;
940                 return -1;
941         }
942         return src_port->connect (dst_port);
943 }
944
945 int
946 ASIOBackend::disconnect (const std::string& src, const std::string& dst)
947 {
948         ASIOBackendPort* src_port = find_port (src);
949         ASIOBackendPort* dst_port = find_port (dst);
950
951         if (!src_port || !dst_port) {
952                 PBD::error << _("ASIOBackend::disconnect: Invalid Port(s)") << endmsg;
953                 return -1;
954         }
955         return src_port->disconnect (dst_port);
956 }
957
958 int
959 ASIOBackend::connect (PortEngine::PortHandle src, const std::string& dst)
960 {
961         ASIOBackendPort* dst_port = find_port (dst);
962         if (!valid_port (src)) {
963                 PBD::error << _("ASIOBackend::connect: Invalid Source Port Handle") << endmsg;
964                 return -1;
965         }
966         if (!dst_port) {
967                 PBD::error << _("ASIOBackend::connect: Invalid Destination Port")
968                         << " (" << dst << ")" << endmsg;
969                 return -1;
970         }
971         return static_cast<ASIOBackendPort*>(src)->connect (dst_port);
972 }
973
974 int
975 ASIOBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
976 {
977         ASIOBackendPort* dst_port = find_port (dst);
978         if (!valid_port (src) || !dst_port) {
979                 PBD::error << _("ASIOBackend::disconnect: Invalid Port(s)") << endmsg;
980                 return -1;
981         }
982         return static_cast<ASIOBackendPort*>(src)->disconnect (dst_port);
983 }
984
985 int
986 ASIOBackend::disconnect_all (PortEngine::PortHandle port)
987 {
988         if (!valid_port (port)) {
989                 PBD::error << _("ASIOBackend::disconnect_all: Invalid Port") << endmsg;
990                 return -1;
991         }
992         static_cast<ASIOBackendPort*>(port)->disconnect_all ();
993         return 0;
994 }
995
996 bool
997 ASIOBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
998 {
999         if (!valid_port (port)) {
1000                 PBD::error << _("ASIOBackend::disconnect_all: Invalid Port") << endmsg;
1001                 return false;
1002         }
1003         return static_cast<ASIOBackendPort*>(port)->is_connected ();
1004 }
1005
1006 bool
1007 ASIOBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
1008 {
1009         ASIOBackendPort* dst_port = find_port (dst);
1010         if (!valid_port (src) || !dst_port) {
1011                 PBD::error << _("ASIOBackend::connected_to: Invalid Port") << endmsg;
1012                 return false;
1013         }
1014         return static_cast<ASIOBackendPort*>(src)->is_connected (dst_port);
1015 }
1016
1017 bool
1018 ASIOBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
1019 {
1020         if (!valid_port (port)) {
1021                 PBD::error << _("ASIOBackend::physically_connected: Invalid Port") << endmsg;
1022                 return false;
1023         }
1024         return static_cast<ASIOBackendPort*>(port)->is_physically_connected ();
1025 }
1026
1027 int
1028 ASIOBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
1029 {
1030         if (!valid_port (port)) {
1031                 PBD::error << _("ASIOBackend::get_connections: Invalid Port") << endmsg;
1032                 return -1;
1033         }
1034
1035         assert (0 == names.size ());
1036
1037         const std::vector<ASIOBackendPort*>& connected_ports = static_cast<ASIOBackendPort*>(port)->get_connections ();
1038
1039         for (std::vector<ASIOBackendPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
1040                 names.push_back ((*i)->name ());
1041         }
1042
1043         return (int)names.size ();
1044 }
1045
1046 /* MIDI */
1047 int
1048 ASIOBackend::midi_event_get (
1049                 pframes_t& timestamp,
1050                 size_t& size, uint8_t** buf, void* port_buffer,
1051                 uint32_t event_index)
1052 {
1053         if (!buf || !port_buffer) return -1;
1054         WindowsMidiBuffer& source = * static_cast<WindowsMidiBuffer*>(port_buffer);
1055         if (event_index >= source.size ()) {
1056                 return -1;
1057         }
1058         WindowsMidiEvent * const event = source[event_index].get ();
1059
1060         timestamp = event->timestamp ();
1061         size = event->size ();
1062         *buf = event->data ();
1063         return 0;
1064 }
1065
1066 int
1067 ASIOBackend::midi_event_put (
1068                 void* port_buffer,
1069                 pframes_t timestamp,
1070                 const uint8_t* buffer, size_t size)
1071 {
1072         if (!buffer || !port_buffer) return -1;
1073         WindowsMidiBuffer& dst = * static_cast<WindowsMidiBuffer*>(port_buffer);
1074         if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
1075 #ifndef NDEBUG
1076                 // nevermind, ::get_buffer() sorts events
1077                 fprintf (stderr, "WindowsMidiBuffer: unordered event: %d > %d\n",
1078                                 (pframes_t)dst.back ()->timestamp (), timestamp);
1079 #endif
1080         }
1081         dst.push_back (boost::shared_ptr<WindowsMidiEvent>(new WindowsMidiEvent (timestamp, buffer, size)));
1082         return 0;
1083 }
1084
1085 uint32_t
1086 ASIOBackend::get_midi_event_count (void* port_buffer)
1087 {
1088         if (!port_buffer) return 0;
1089         return static_cast<WindowsMidiBuffer*>(port_buffer)->size ();
1090 }
1091
1092 void
1093 ASIOBackend::midi_clear (void* port_buffer)
1094 {
1095         if (!port_buffer) return;
1096         WindowsMidiBuffer * buf = static_cast<WindowsMidiBuffer*>(port_buffer);
1097         assert (buf);
1098         buf->clear ();
1099 }
1100
1101 /* Monitoring */
1102
1103 bool
1104 ASIOBackend::can_monitor_input () const
1105 {
1106         return false;
1107 }
1108
1109 int
1110 ASIOBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1111 {
1112         return -1;
1113 }
1114
1115 int
1116 ASIOBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1117 {
1118         return -1;
1119 }
1120
1121 bool
1122 ASIOBackend::monitoring_input (PortEngine::PortHandle)
1123 {
1124         return false;
1125 }
1126
1127 /* Latency management */
1128
1129 void
1130 ASIOBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1131 {
1132         if (!valid_port (port)) {
1133                 PBD::error << _("ASIOBackendPort::set_latency_range (): invalid port.") << endmsg;
1134         }
1135         static_cast<ASIOBackendPort*>(port)->set_latency_range (latency_range, for_playback);
1136 }
1137
1138 LatencyRange
1139 ASIOBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1140 {
1141         LatencyRange r;
1142         if (!valid_port (port)) {
1143                 PBD::error << _("ASIOBackendPort::get_latency_range (): invalid port.") << endmsg;
1144                 r.min = 0;
1145                 r.max = 0;
1146                 return r;
1147         }
1148         ASIOBackendPort* p = static_cast<ASIOBackendPort*>(port);
1149         assert(p);
1150
1151         r = p->latency_range (for_playback);
1152         if (p->is_physical() && p->is_terminal() && p->type() == DataType::AUDIO) {
1153                 if (p->is_input() && for_playback) {
1154                         r.min += _samples_per_period;
1155                         r.max += _samples_per_period;
1156                 }
1157                 if (p->is_output() && !for_playback) {
1158                         r.min += _samples_per_period;
1159                         r.max += _samples_per_period;
1160                 }
1161         }
1162         return r;
1163 }
1164
1165 /* Discovering physical ports */
1166
1167 bool
1168 ASIOBackend::port_is_physical (PortEngine::PortHandle port) const
1169 {
1170         if (!valid_port (port)) {
1171                 PBD::error << _("ASIOBackendPort::port_is_physical (): invalid port.") << endmsg;
1172                 return false;
1173         }
1174         return static_cast<ASIOBackendPort*>(port)->is_physical ();
1175 }
1176
1177 void
1178 ASIOBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
1179 {
1180         for (size_t i = 0; i < _ports.size (); ++i) {
1181                 ASIOBackendPort* port = _ports[i];
1182                 if ((port->type () == type) && port->is_input () && port->is_physical ()) {
1183                         port_names.push_back (port->name ());
1184                 }
1185         }
1186 }
1187
1188 void
1189 ASIOBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
1190 {
1191         for (size_t i = 0; i < _ports.size (); ++i) {
1192                 ASIOBackendPort* port = _ports[i];
1193                 if ((port->type () == type) && port->is_output () && port->is_physical ()) {
1194                         port_names.push_back (port->name ());
1195                 }
1196         }
1197 }
1198
1199 ChanCount
1200 ASIOBackend::n_physical_outputs () const
1201 {
1202         int n_midi = 0;
1203         int n_audio = 0;
1204         for (size_t i = 0; i < _ports.size (); ++i) {
1205                 ASIOBackendPort* port = _ports[i];
1206                 if (port->is_output () && port->is_physical ()) {
1207                         switch (port->type ()) {
1208                                 case DataType::AUDIO: ++n_audio; break;
1209                                 case DataType::MIDI: ++n_midi; break;
1210                                 default: break;
1211                         }
1212                 }
1213         }
1214         ChanCount cc;
1215         cc.set (DataType::AUDIO, n_audio);
1216         cc.set (DataType::MIDI, n_midi);
1217         return cc;
1218 }
1219
1220 ChanCount
1221 ASIOBackend::n_physical_inputs () const
1222 {
1223         int n_midi = 0;
1224         int n_audio = 0;
1225         for (size_t i = 0; i < _ports.size (); ++i) {
1226                 ASIOBackendPort* port = _ports[i];
1227                 if (port->is_input () && port->is_physical ()) {
1228                         switch (port->type ()) {
1229                                 case DataType::AUDIO: ++n_audio; break;
1230                                 case DataType::MIDI: ++n_midi; break;
1231                                 default: break;
1232                         }
1233                 }
1234         }
1235         ChanCount cc;
1236         cc.set (DataType::AUDIO, n_audio);
1237         cc.set (DataType::MIDI, n_midi);
1238         return cc;
1239 }
1240
1241 /* Getting access to the data buffer for a port */
1242
1243 void*
1244 ASIOBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1245 {
1246         if (!port || !valid_port (port)) return NULL;
1247         return static_cast<ASIOBackendPort*>(port)->get_buffer (nframes);
1248 }
1249
1250 void
1251 ASIOBackend::pre_process ()
1252 {
1253         bool connections_changed = false;
1254         bool ports_changed = false;
1255         if (!pthread_mutex_trylock (&_port_callback_mutex)) {
1256                 if (_port_change_flag) {
1257                         ports_changed = true;
1258                         _port_change_flag = false;
1259                 }
1260                 if (!_port_connection_queue.empty ()) {
1261                         connections_changed = true;
1262                 }
1263                 while (!_port_connection_queue.empty ()) {
1264                         PortConnectData *c = _port_connection_queue.back ();
1265                         manager.connect_callback (c->a, c->b, c->c);
1266                         _port_connection_queue.pop_back ();
1267                         delete c;
1268                 }
1269                 pthread_mutex_unlock (&_port_callback_mutex);
1270         }
1271         if (ports_changed) {
1272                 manager.registration_callback();
1273         }
1274         if (connections_changed) {
1275                 manager.graph_order_callback();
1276         }
1277         if (connections_changed || ports_changed) {
1278                 engine.latency_callback(false);
1279                 engine.latency_callback(true);
1280         }
1281 }
1282
1283 void *
1284 ASIOBackend::freewheel_thread ()
1285 {
1286         _active_fw = true;
1287         bool first_run = false;
1288         /* Freewheeling - use for export.   The first call to
1289          * engine.process_callback() after engine.freewheel_callback will
1290          * if the first export cycle.
1291          * For reliable precise export timing, the calls need to be in sync.
1292          *
1293          * Furthermore we need to make sure the registered process thread
1294          * is correct.
1295          *
1296          * _freewheeling = GUI thread state as set by ::freewheel()
1297          * _freewheel = in sync here (export thread)
1298          */
1299         pthread_mutex_lock (&_freewheel_mutex);
1300         while (_run) {
1301                 // check if we should run,
1302                 if (_freewheeling != _freewheel) {
1303                         if (!_freewheeling) {
1304                                 // prepare leaving freewheeling mode
1305                                 _freewheel = false; // first mark as disabled
1306                                 _reinit_thread_callback = true; // hand over _main_thread
1307                                 _freewheel_ack = false; // prepare next handshake
1308 #if 0 // TODO disable hadrware MIDI threads during freewheeling
1309                                 _midiio->set_enabled(true);
1310 #endif
1311                         } else {
1312                                 first_run = true;
1313                                 _freewheel = true;
1314                         }
1315                 }
1316
1317                 if (!_freewheel || !_freewheel_ack) {
1318                         // wait for a change, we use a timed wait to
1319                         // terminate early in case some error sets _run = 0
1320                         struct timeval tv;
1321                         struct timespec ts;
1322                         gettimeofday (&tv, NULL);
1323                         ts.tv_sec = tv.tv_sec + 3;
1324                         ts.tv_nsec = 0;
1325                         pthread_cond_timedwait (&_freewheel_signal, &_freewheel_mutex, &ts);
1326                         continue;
1327                 }
1328
1329                 if (first_run) {
1330                         // tell the engine we're ready to GO.
1331                         engine.freewheel_callback (_freewheeling);
1332                         first_run = false;
1333                         _main_thread = pthread_self();
1334                         AudioEngine::thread_init_callback (this);
1335 #if 0 // TODO
1336                         _midiio->set_enabled(false);
1337 #endif
1338                 }
1339
1340                 // process port updates first in every cycle.
1341                 pre_process();
1342
1343                 // prevent device changes
1344                 pthread_mutex_lock (&_process_callback_mutex);
1345
1346                 /* Freewheelin' */
1347
1348                 // clear input buffers
1349                 for (std::vector<ASIOBackendPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it) {
1350                         memset ((*it)->get_buffer (_samples_per_period), 0, _samples_per_period * sizeof (Sample));
1351                 }
1352                 for (std::vector<ASIOBackendPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it) {
1353                         static_cast<WindowsMidiBuffer*>((*it)->get_buffer(0))->clear ();
1354                 }
1355
1356                 _last_process_start = 0;
1357                 if (engine.process_callback (_samples_per_period)) {
1358                         pthread_mutex_unlock (&_process_callback_mutex);
1359                         break;
1360                 }
1361
1362                 pthread_mutex_unlock (&_process_callback_mutex);
1363                 _dsp_load = 1.0;
1364                 Glib::usleep (100); // don't hog cpu
1365         }
1366
1367         pthread_mutex_unlock (&_freewheel_mutex);
1368
1369         _active_fw = false;
1370
1371         if (_run) {
1372                 // engine.process_callback() returner error
1373                 engine.halted_callback("ASIO Freehweeling aborted.");
1374         }
1375         return 0;
1376 }
1377
1378 int
1379 ASIOBackend::process_callback (const uint32_t n_samples, const uint64_t host_time)
1380 {
1381         uint32_t i = 0;
1382         uint64_t clock1, clock2;
1383
1384         _active_cb = true;
1385
1386         if (_run && _freewheel && !_freewheel_ack) {
1387                 // acknowledge freewheeling; hand-over thread ID
1388                 pthread_mutex_lock (&_freewheel_mutex);
1389                 if (_freewheel) _freewheel_ack = true;
1390                 pthread_cond_signal (&_freewheel_signal);
1391                 pthread_mutex_unlock (&_freewheel_mutex);
1392         }
1393
1394         if (!_run || _freewheel || _preinit) {
1395                 // NB if we return 1, the output is
1396                 // zeroed by the asio callback
1397                 return 1;
1398         }
1399
1400         if (_reinit_thread_callback || _main_thread != pthread_self()) {
1401                 _reinit_thread_callback = false;
1402                 _main_thread = pthread_self();
1403                 AudioEngine::thread_init_callback (this);
1404         }
1405
1406         if (pthread_mutex_trylock (&_process_callback_mutex)) {
1407                 // block while devices are added/removed
1408 #ifndef NDEBUG
1409                 printf("Xrun due to device change\n");
1410 #endif
1411                 engine.Xrun();
1412                 return 1;
1413         }
1414         /* port-connection change */
1415         pre_process();
1416
1417         // cycle-length in usec
1418         const double nominal_time = 1e6 * n_samples / _samplerate;
1419
1420         clock1 = g_get_monotonic_time();
1421
1422         /* get midi */
1423         i=0;
1424         for (std::vector<ASIOBackendPort*>::const_iterator it = _system_midi_in.begin (); it != _system_midi_in.end (); ++it, ++i) {
1425                 WindowsMidiBuffer* mbuf = static_cast<WindowsMidiBuffer*>((*it)->get_buffer(0));
1426                 mbuf->clear();
1427 #if 0 // TODO
1428                 uint64_t time_ns;
1429                 uint8_t data[128];
1430                 size_t size = sizeof(data);
1431                 while (_midiio->recv_event (i, nominal_time, time_ns, data, size)) {
1432                         pframes_t time = floor((float) time_ns * _samplerate * 1e-9);
1433                         assert (time < n_samples);
1434                         midi_event_put((void*)mbuf, time, data, size);
1435                         size = sizeof(data);
1436                 }
1437 #endif
1438         }
1439
1440         /* get audio */
1441         i = 0;
1442         for (std::vector<ASIOBackendPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++i) {
1443 #if 0 // TODO
1444                 _pcmio->get_capture_channel (i, (float*)((*it)->get_buffer(n_samples)), n_samples);
1445 #else
1446                 memset ((*it)->get_buffer (n_samples), 0, n_samples * sizeof (Sample));
1447 #endif
1448         }
1449
1450         /* clear output buffers */
1451         for (std::vector<ASIOBackendPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it) {
1452                 memset ((*it)->get_buffer (n_samples), 0, n_samples * sizeof (Sample));
1453         }
1454
1455 #if 0 // TODO; sync Audio + midi
1456         _midiio->start_cycle();
1457 #endif
1458         _last_process_start = host_time;
1459
1460         if (engine.process_callback (n_samples)) {
1461                 fprintf(stderr, "ENGINE PROCESS ERROR\n");
1462                 _active_cb = false;
1463                 pthread_mutex_unlock (&_process_callback_mutex);
1464                 return -1;
1465         }
1466
1467         /* mixdown midi */
1468         for (std::vector<ASIOBackendPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it) {
1469                 static_cast<WindowsMidiPort*>(*it)->get_buffer(0);
1470         }
1471
1472         /* queue outgoing midi */
1473 #if 0 // TODO
1474         i = 0;
1475         for (std::vector<ASIOBackendPort*>::const_iterator it = _system_midi_out.begin (); it != _system_midi_out.end (); ++it, ++i) {
1476 #if 0 // something's still b0rked with WindowsMidiIo::send_events()
1477                 const WindowsMidiBuffer *src = static_cast<const WindowsMidiPort*>(*it)->const_buffer();
1478                 _midiio->send_events (i, nominal_time, (void*)src);
1479 #else // works..
1480                 const WindowsMidiBuffer *src = static_cast<const WindowsMidiPort*>(*it)->const_buffer();
1481                 for (WindowsMidiBuffer::const_iterator mit = src->begin (); mit != src->end (); ++mit) {
1482                         _midiio->send_event (i, (*mit)->timestamp() / nominal_time, (*mit)->data(), (*mit)->size());
1483                 }
1484 #endif
1485         }
1486 #endif
1487
1488         /* write back audio */
1489 #if 0 // TODO
1490         i = 0;
1491         for (std::vector<ASIOBackendPort*>::const_iterator it = _system_outputs.begin (); it != _system_outputs.end (); ++it, ++i) {
1492                 _pcmio->set_playback_channel (i, (float const*)(*it)->get_buffer (n_samples), n_samples);
1493         }
1494 #endif
1495
1496         _processed_samples += n_samples;
1497
1498         /* calc DSP load. */
1499         clock2 = g_get_monotonic_time();
1500         const int64_t elapsed_time = clock2 - clock1;
1501         _dsp_load = elapsed_time / nominal_time;
1502
1503         pthread_mutex_unlock (&_process_callback_mutex);
1504         return 0;
1505 }
1506
1507 void
1508 ASIOBackend::error_callback ()
1509 {
1510 #if 0 // TODO
1511         _pcmio->set_error_callback (NULL, NULL);
1512         _pcmio->set_sample_rate_callback (NULL, NULL);
1513         _pcmio->set_xrun_callback (NULL, NULL);
1514         _midiio->set_port_changed_callback(NULL, NULL);
1515 #endif
1516         engine.halted_callback("ASIO Process aborted.");
1517         _active_cb = false;
1518 }
1519
1520 void
1521 ASIOBackend::xrun_callback ()
1522 {
1523         engine.Xrun ();
1524 }
1525
1526 void
1527 ASIOBackend::buffer_size_callback ()
1528 {
1529 #if 0 // TODO
1530         uint32_t bs = _pcmio->samples_per_period();
1531         if (bs == _samples_per_period) {
1532                 return;
1533         }
1534         _samples_per_period = bs;
1535         engine.buffer_size_change (_samples_per_period);
1536 #endif
1537 }
1538
1539 void
1540 ASIOBackend::sample_rate_callback ()
1541 {
1542 #if 0  // TODO
1543         _pcmio->set_error_callback (NULL, NULL);
1544         _pcmio->set_sample_rate_callback (NULL, NULL);
1545         _pcmio->set_xrun_callback (NULL, NULL);
1546         _midiio->set_port_changed_callback(NULL, NULL);
1547         engine.halted_callback("Sample Rate Changed.");
1548         stop();
1549 #endif
1550 }
1551
1552 void
1553 ASIOBackend::hw_changed_callback ()
1554 {
1555 #if 0 // TODO
1556         _reinit_thread_callback = true;
1557         engine.request_device_list_update();
1558 #endif
1559 }
1560
1561 /******************************************************************************/
1562
1563 static boost::shared_ptr<ASIOBackend> _instance;
1564
1565 static boost::shared_ptr<AudioBackend> backend_factory (AudioEngine& e);
1566 static int instantiate (const std::string& arg1, const std::string& /* arg2 */);
1567 static int deinstantiate ();
1568 static bool already_configured ();
1569 static bool available ();
1570
1571 static ARDOUR::AudioBackendInfo _descriptor = {
1572         "ASIO",
1573         instantiate,
1574         deinstantiate,
1575         backend_factory,
1576         already_configured,
1577         available
1578 };
1579
1580 static boost::shared_ptr<AudioBackend>
1581 backend_factory (AudioEngine& e)
1582 {
1583         if (!_instance) {
1584                 _instance.reset (new ASIOBackend (e, _descriptor));
1585         }
1586         return _instance;
1587 }
1588
1589 static int
1590 instantiate (const std::string& arg1, const std::string& /* arg2 */)
1591 {
1592         s_instance_name = arg1;
1593         return 0;
1594 }
1595
1596 static int
1597 deinstantiate ()
1598 {
1599         _instance.reset ();
1600         return 0;
1601 }
1602
1603 static bool
1604 already_configured ()
1605 {
1606         return false;
1607 }
1608
1609 static bool
1610 available ()
1611 {
1612         return true;
1613 }
1614
1615 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
1616 {
1617         return &_descriptor;
1618 }
1619
1620
1621 /******************************************************************************/
1622 ASIOBackendPort::ASIOBackendPort (ASIOBackend &b, const std::string& name, PortFlags flags)
1623         : _osx_backend (b)
1624         , _name  (name)
1625         , _flags (flags)
1626 {
1627         _capture_latency_range.min = 0;
1628         _capture_latency_range.max = 0;
1629         _playback_latency_range.min = 0;
1630         _playback_latency_range.max = 0;
1631 }
1632
1633 ASIOBackendPort::~ASIOBackendPort () {
1634         disconnect_all ();
1635 }
1636
1637
1638 int ASIOBackendPort::connect (ASIOBackendPort *port)
1639 {
1640         if (!port) {
1641                 PBD::error << _("ASIOBackendPort::connect (): invalid (null) port") << endmsg;
1642                 return -1;
1643         }
1644
1645         if (type () != port->type ()) {
1646                 PBD::error << _("ASIOBackendPort::connect (): wrong port-type") << endmsg;
1647                 return -1;
1648         }
1649
1650         if (is_output () && port->is_output ()) {
1651                 PBD::error << _("ASIOBackendPort::connect (): cannot inter-connect output ports.") << endmsg;
1652                 return -1;
1653         }
1654
1655         if (is_input () && port->is_input ()) {
1656                 PBD::error << _("ASIOBackendPort::connect (): cannot inter-connect input ports.") << endmsg;
1657                 return -1;
1658         }
1659
1660         if (this == port) {
1661                 PBD::error << _("ASIOBackendPort::connect (): cannot self-connect ports.") << endmsg;
1662                 return -1;
1663         }
1664
1665         if (is_connected (port)) {
1666 #if 0 // don't bother to warn about this for now. just ignore it
1667                 PBD::error << _("ASIOBackendPort::connect (): ports are already connected:")
1668                         << " (" << name () << ") -> (" << port->name () << ")"
1669                         << endmsg;
1670 #endif
1671                 return -1;
1672         }
1673
1674         _connect (port, true);
1675         return 0;
1676 }
1677
1678
1679 void ASIOBackendPort::_connect (ASIOBackendPort *port, bool callback)
1680 {
1681         _connections.push_back (port);
1682         if (callback) {
1683                 port->_connect (this, false);
1684                 _osx_backend.port_connect_callback (name(),  port->name(), true);
1685         }
1686 }
1687
1688 int ASIOBackendPort::disconnect (ASIOBackendPort *port)
1689 {
1690         if (!port) {
1691                 PBD::error << _("ASIOBackendPort::disconnect (): invalid (null) port") << endmsg;
1692                 return -1;
1693         }
1694
1695         if (!is_connected (port)) {
1696                 PBD::error << _("ASIOBackendPort::disconnect (): ports are not connected:")
1697                         << " (" << name () << ") -> (" << port->name () << ")"
1698                         << endmsg;
1699                 return -1;
1700         }
1701         _disconnect (port, true);
1702         return 0;
1703 }
1704
1705 void ASIOBackendPort::_disconnect (ASIOBackendPort *port, bool callback)
1706 {
1707         std::vector<ASIOBackendPort*>::iterator it = std::find (_connections.begin (), _connections.end (), port);
1708
1709         assert (it != _connections.end ());
1710
1711         _connections.erase (it);
1712
1713         if (callback) {
1714                 port->_disconnect (this, false);
1715                 _osx_backend.port_connect_callback (name(),  port->name(), false);
1716         }
1717 }
1718
1719
1720 void ASIOBackendPort::disconnect_all ()
1721 {
1722         while (!_connections.empty ()) {
1723                 _connections.back ()->_disconnect (this, false);
1724                 _osx_backend.port_connect_callback (name(),  _connections.back ()->name(), false);
1725                 _connections.pop_back ();
1726         }
1727 }
1728
1729 bool
1730 ASIOBackendPort::is_connected (const ASIOBackendPort *port) const
1731 {
1732         return std::find (_connections.begin (), _connections.end (), port) != _connections.end ();
1733 }
1734
1735 bool ASIOBackendPort::is_physically_connected () const
1736 {
1737         for (std::vector<ASIOBackendPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
1738                 if ((*it)->is_physical ()) {
1739                         return true;
1740                 }
1741         }
1742         return false;
1743 }
1744
1745 /******************************************************************************/
1746
1747 ASIOPort::ASIOPort (ASIOBackend &b, const std::string& name, PortFlags flags)
1748         : ASIOBackendPort (b, name, flags)
1749 {
1750         memset (_buffer, 0, sizeof (_buffer));
1751         mlock(_buffer, sizeof (_buffer));
1752 }
1753
1754 ASIOPort::~ASIOPort () { }
1755
1756 void* ASIOPort::get_buffer (pframes_t n_samples)
1757 {
1758         if (is_input ()) {
1759                 std::vector<ASIOBackendPort*>::const_iterator it = get_connections ().begin ();
1760                 if (it == get_connections ().end ()) {
1761                         memset (_buffer, 0, n_samples * sizeof (Sample));
1762                 } else {
1763                         ASIOPort const * source = static_cast<const ASIOPort*>(*it);
1764                         assert (source && source->is_output ());
1765                         memcpy (_buffer, source->const_buffer (), n_samples * sizeof (Sample));
1766                         while (++it != get_connections ().end ()) {
1767                                 source = static_cast<const ASIOPort*>(*it);
1768                                 assert (source && source->is_output ());
1769                                 Sample* dst = buffer ();
1770                                 const Sample* src = source->const_buffer ();
1771                                 for (uint32_t s = 0; s < n_samples; ++s, ++dst, ++src) {
1772                                         *dst += *src;
1773                                 }
1774                         }
1775                 }
1776         }
1777         return _buffer;
1778 }
1779
1780
1781 WindowsMidiPort::WindowsMidiPort (ASIOBackend &b, const std::string& name, PortFlags flags)
1782         : ASIOBackendPort (b, name, flags)
1783         , _n_periods (1)
1784         , _bufperiod (0)
1785 {
1786         _buffer[0].clear ();
1787         _buffer[1].clear ();
1788 }
1789
1790 WindowsMidiPort::~WindowsMidiPort () { }
1791
1792 struct MidiEventSorter {
1793         bool operator() (const boost::shared_ptr<WindowsMidiEvent>& a, const boost::shared_ptr<WindowsMidiEvent>& b) {
1794                 return *a < *b;
1795         }
1796 };
1797
1798 void* WindowsMidiPort::get_buffer (pframes_t /* nframes */)
1799 {
1800         if (is_input ()) {
1801                 (_buffer[_bufperiod]).clear ();
1802                 for (std::vector<ASIOBackendPort*>::const_iterator i = get_connections ().begin ();
1803                                 i != get_connections ().end ();
1804                                 ++i) {
1805                         const WindowsMidiBuffer * src = static_cast<const WindowsMidiPort*>(*i)->const_buffer ();
1806                         for (WindowsMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
1807                                 (_buffer[_bufperiod]).push_back (boost::shared_ptr<WindowsMidiEvent>(new WindowsMidiEvent (**it)));
1808                         }
1809                 }
1810                 std::sort ((_buffer[_bufperiod]).begin (), (_buffer[_bufperiod]).end (), MidiEventSorter());
1811         }
1812         return &(_buffer[_bufperiod]);
1813 }
1814
1815 WindowsMidiEvent::WindowsMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
1816         : _size (size)
1817         , _timestamp (timestamp)
1818         , _data (0)
1819 {
1820         if (size > 0) {
1821                 _data = (uint8_t*) malloc (size);
1822                 memcpy (_data, data, size);
1823         }
1824 }
1825
1826 WindowsMidiEvent::WindowsMidiEvent (const WindowsMidiEvent& other)
1827         : _size (other.size ())
1828         , _timestamp (other.timestamp ())
1829         , _data (0)
1830 {
1831         if (other.size () && other.const_data ()) {
1832                 _data = (uint8_t*) malloc (other.size ());
1833                 memcpy (_data, other.const_data (), other.size ());
1834         }
1835 };
1836
1837 WindowsMidiEvent::~WindowsMidiEvent () {
1838         free (_data);
1839 };