2 * Copyright (C) 2014 Robin Gareus <robin@gareus.org>
3 * Copyright (C) 2013 Paul Davis
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.
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.
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.
26 #include "asio_backend.h"
27 #include "rt_thread.h"
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"
36 using namespace ARDOUR;
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;
44 /* static class instance access */
45 static void hw_changed_callback_ptr (void *arg)
47 ASIOBackend *d = static_cast<ASIOBackend*> (arg);
48 d->hw_changed_callback();
51 static void error_callback_ptr (void *arg)
53 ASIOBackend *d = static_cast<ASIOBackend*> (arg);
57 static void xrun_callback_ptr (void *arg)
59 ASIOBackend *d = static_cast<ASIOBackend*> (arg);
63 static void buffer_size_callback_ptr (void *arg)
65 ASIOBackend *d = static_cast<ASIOBackend*> (arg);
66 d->buffer_size_callback();
69 static void sample_rate_callback_ptr (void *arg)
71 ASIOBackend *d = static_cast<ASIOBackend*> (arg);
72 d->sample_rate_callback();
76 ASIOBackend::ASIOBackend (AudioEngine& e, AudioBackendInfo& info)
77 : AudioBackend (e, info)
81 , _freewheeling (false)
83 , _freewheel_ack (false)
84 , _reinit_thread_callback (false)
85 , _measure_latency (false)
86 , _last_process_start (0)
88 , _midi_driver_option(_("None"))
90 , _samples_per_period (1024)
93 , _systemic_audio_input_latency (0)
94 , _systemic_audio_output_latency (0)
96 , _processed_samples (0)
97 , _port_change_flag (false)
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);
106 //_pcmio = new ASIOPCM ();
107 //_midiio = new WindowsMidiIo ();
109 _pcmio->set_hw_changed_callback (hw_changed_callback_ptr, this);
114 ASIOBackend::~ASIOBackend ()
117 delete _pcmio; _pcmio = 0; // TODO
118 delete _midiio; _midiio = 0; // TODO
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);
126 /* AUDIOBACKEND API */
129 ASIOBackend::name () const
135 ASIOBackend::is_realtime () const
140 std::vector<AudioBackend::DeviceStatus>
141 ASIOBackend::enumerate_devices () const
143 _audio_device_status.clear();
145 std::map<size_t, std::string> devices;
146 _pcmio->device_list(devices);
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));
153 return _audio_device_status;
157 ASIOBackend::available_sample_rates (const std::string&) const
159 std::vector<float> sr;
161 _pcmio->available_sample_rates(_audio_device, sr);
166 std::vector<uint32_t>
167 ASIOBackend::available_buffer_sizes (const std::string&) const
169 std::vector<uint32_t> bs;
171 _pcmio->available_buffer_sizes(_audio_device, bs);
177 ASIOBackend::available_input_channel_count (const std::string&) const
179 return 128; // TODO query current device
183 ASIOBackend::available_output_channel_count (const std::string&) const
185 return 128; // TODO query current device
189 ASIOBackend::can_change_sample_rate_when_running () const
195 ASIOBackend::can_change_buffer_size_when_running () const
201 ASIOBackend::set_device_name (const std::string& d)
205 const float sr = _pcmio->current_sample_rate(_audio_device);
207 //if (sr > 0) { set_sample_rate(sr); }
212 ASIOBackend::set_sample_rate (float sr)
214 if (sr <= 0) { return -1; }
215 // TODO check if it's in the list of valid SR
217 engine.sample_rate_change (sr);
222 ASIOBackend::set_buffer_size (uint32_t bs)
224 if (bs <= 0 || bs >= _max_buffer_size) {
227 _samples_per_period = bs;
229 _pcmio->set_samples_per_period(bs);
231 engine.buffer_size_change (bs);
236 ASIOBackend::set_interleaved (bool yn)
238 if (!yn) { return 0; }
243 ASIOBackend::set_input_channels (uint32_t cc)
250 ASIOBackend::set_output_channels (uint32_t cc)
257 ASIOBackend::set_systemic_input_latency (uint32_t sl)
259 _systemic_audio_input_latency = sl;
264 ASIOBackend::set_systemic_output_latency (uint32_t sl)
266 _systemic_audio_output_latency = sl;
270 /* Retrieving parameters */
272 ASIOBackend::device_name () const
274 return _audio_device;
278 ASIOBackend::sample_rate () const
284 ASIOBackend::buffer_size () const
286 return _samples_per_period;
290 ASIOBackend::interleaved () const
296 ASIOBackend::input_channels () const
302 ASIOBackend::output_channels () const
308 ASIOBackend::systemic_input_latency () const
310 return _systemic_audio_input_latency;
314 ASIOBackend::systemic_output_latency () const
316 return _systemic_audio_output_latency;
321 std::vector<std::string>
322 ASIOBackend::enumerate_midi_options () const
324 if (_midi_options.empty()) {
325 _midi_options.push_back (_("WindowsMidi"));
326 _midi_options.push_back (_("None"));
328 return _midi_options;
332 ASIOBackend::set_midi_option (const std::string& opt)
334 if (opt != _("None") && opt != _("WindowsMidi")) {
337 _midi_driver_option = opt;
342 ASIOBackend::midi_option () const
344 return _midi_driver_option;
348 ASIOBackend::launch_control_app ()
355 static void * pthread_freewheel (void *arg)
357 ASIOBackend *d = static_cast<ASIOBackend *>(arg);
358 d->freewheel_thread ();
363 static int process_callback_ptr (void *arg, const uint32_t n_samples, const uint64_t host_time)
365 ASIOBackend *d = static_cast<ASIOBackend*> (arg);
366 return d->process_callback(n_samples, host_time);
370 ASIOBackend::_start (bool for_latency_measurement)
372 if ((!_active_cb || !_active_fw) && _run) {
373 // recover from 'halted', reap threads
377 if (_active_cb || _active_fw || _run) {
378 PBD::error << _("ASIOBackend: already active.") << endmsg;
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();
391 assert(_active_cb == false);
392 assert(_active_fw == false);
394 _freewheel_ack = false;
395 _reinit_thread_callback = true;
396 _last_process_start = 0;
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);
403 _pcmio->pcm_start (device1, device2, _samplerate, _samples_per_period, process_callback_ptr, this);
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;
410 if (_pcmio->state ()) {
414 if (_n_outputs != _pcmio->n_playback_channels ()) {
415 if (_n_outputs == 0) {
416 _n_outputs = _pcmio->n_playback_channels ();
418 _n_outputs = std::min (_n_outputs, _pcmio->n_playback_channels ());
420 PBD::info << _("ASIOBackend: adjusted output channel count to match device.") << endmsg;
423 if (_n_inputs != _pcmio->n_capture_channels ()) {
424 if (_n_inputs == 0) {
425 _n_inputs = _pcmio->n_capture_channels ();
427 _n_inputs = std::min (_n_inputs, _pcmio->n_capture_channels ());
429 PBD::info << _("ASIOBackend: adjusted input channel count to match device.") << endmsg;
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;
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;
444 _measure_latency = for_latency_measurement;
448 _port_change_flag = false;
451 if (_midi_driver_option == _("WindowsMidi")) {
453 //_midiio->set_enabled(true);
454 //_midiio->set_port_changed_callback(midi_port_change, this);
455 //_midiio->start(); // triggers port discovery, callback coremidi_rediscover()
459 if (register_system_audio_ports()) {
460 PBD::error << _("ASIOBackend: failed to register system ports.") << endmsg;
465 engine.sample_rate_change (_samplerate);
466 engine.buffer_size_change (_samples_per_period);
468 if (engine.reestablish_ports ()) {
469 PBD::error << _("ASIOBackend: Could not re-establish ports.") << endmsg;
474 if (pthread_create (&_freeewheel_thread, NULL, pthread_freewheel, this))
476 PBD::error << _("ASIOBackend: failed to create process thread.") << endmsg;
478 delete _pcmio; _pcmio = 0;
485 while ((!_active_cb || !_active_fw) && --timeout > 0) { Glib::usleep (1000); }
488 PBD::error << _("ASIOBackend: failed to start.") << endmsg;
492 PBD::error << _("ASIOBackend: failed to start freewheeling thread.") << endmsg;
504 PBD::error << _("ASIOBackend: failed to start ASIO.") << endmsg;
510 engine.reconnect_ports ();
512 // force an initial registration_callback() & latency re-compute
513 _port_change_flag = true;
518 _pcmio->set_xrun_callback (xrun_callback_ptr, this);
536 _midiio->set_port_changed_callback(NULL, NULL);
539 pthread_mutex_lock (&_freewheel_mutex);
540 pthread_cond_signal (&_freewheel_signal);
541 pthread_mutex_unlock (&_freewheel_mutex);
543 if (pthread_join (_freeewheel_thread, &status)) {
544 PBD::error << _("ASIOBackend: failed to terminate.") << endmsg;
551 _active_fw = false; // ??
557 ASIOBackend::freewheel (bool onoff)
559 if (onoff == _freewheeling) {
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);
572 ASIOBackend::dsp_load () const
574 return 100.f * _dsp_load;
578 ASIOBackend::raw_buffer_size (DataType t)
581 case DataType::AUDIO:
582 return _samples_per_period * sizeof(Sample);
584 return _max_buffer_size; // XXX not really limited
591 ASIOBackend::sample_time ()
593 return _processed_samples;
597 ASIOBackend::sample_time_at_cycle_start ()
599 return _processed_samples;
603 ASIOBackend::samples_since_cycle_start ()
605 if (!_active_cb || !_run || _freewheeling || _freewheel) {
608 if (_last_process_start == 0) {
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));
622 ASIOBackend::asio_process_thread (void *arg)
624 ThreadData* td = reinterpret_cast<ThreadData*> (arg);
625 boost::function<void ()> f = td->f;
632 ASIOBackend::create_process_thread (boost::function<void()> func)
636 size_t stacksize = 100000;
638 ThreadData* td = new ThreadData (this, func, stacksize);
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);
649 pthread_attr_destroy (&attr);
652 _threads.push_back (thread_id);
657 ASIOBackend::join_process_threads ()
661 for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
664 if (pthread_join (*i, &status)) {
665 PBD::error << _("AudioEngine: cannot terminate process thread.") << endmsg;
674 ASIOBackend::in_process_thread ()
676 if (pthread_equal (_main_thread, pthread_self()) != 0) {
680 for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
682 if (pthread_equal (*i, pthread_self ()) != 0) {
690 ASIOBackend::process_thread_count ()
692 return _threads.size ();
696 ASIOBackend::update_latencies ()
698 // trigger latency callback in RT thread (locked graph)
699 port_connect_add_remove_callback();
705 ASIOBackend::private_handle () const
711 ASIOBackend::my_name () const
713 return _instance_name;
717 ASIOBackend::available () const
719 return _run && _active_fw && _active_cb;
723 ASIOBackend::port_name_size () const
729 ASIOBackend::set_port_name (PortEngine::PortHandle port, const std::string& name)
731 if (!valid_port (port)) {
732 PBD::error << _("ASIOBackend::set_port_name: Invalid Port(s)") << endmsg;
735 return static_cast<ASIOBackendPort*>(port)->set_name (_instance_name + ":" + name);
739 ASIOBackend::get_port_name (PortEngine::PortHandle port) const
741 if (!valid_port (port)) {
742 PBD::error << _("ASIOBackend::get_port_name: Invalid Port(s)") << endmsg;
743 return std::string ();
745 return static_cast<ASIOBackendPort*>(port)->name ();
749 ASIOBackend::get_port_property (PortHandle port, const std::string& key, std::string& value, std::string& type) const
751 if (!valid_port (port)) {
752 PBD::error << _("ASIOBackend::get_port_name: Invalid Port(s)") << endmsg;
755 if (key == "http://jackaudio.org/metadata/pretty-name") {
757 value = static_cast<ASIOBackendPort*>(port)->pretty_name ();
758 if (!value.empty()) {
765 PortEngine::PortHandle
766 ASIOBackend::get_port_by_name (const std::string& name) const
768 PortHandle port = (PortHandle) find_port (name);
773 ASIOBackend::get_ports (
774 const std::string& port_name_pattern,
775 DataType type, PortFlags flags,
776 std::vector<std::string>& port_names) const
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)) {
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 ());
796 regfree (&port_regex);
802 ASIOBackend::port_data_type (PortEngine::PortHandle port) const
804 if (!valid_port (port)) {
805 return DataType::NIL;
807 return static_cast<ASIOBackendPort*>(port)->type ();
810 PortEngine::PortHandle
811 ASIOBackend::register_port (
812 const std::string& name,
813 ARDOUR::DataType type,
814 ARDOUR::PortFlags flags)
816 if (name.size () == 0) { return 0; }
817 if (flags & IsPhysical) { return 0; }
818 return add_port (_instance_name + ":" + name, type, flags);
821 PortEngine::PortHandle
822 ASIOBackend::add_port (
823 const std::string& name,
824 ARDOUR::DataType type,
825 ARDOUR::PortFlags flags)
827 assert(name.size ());
828 if (find_port (name)) {
829 PBD::error << _("ASIOBackend::register_port: Port already exists:")
830 << " (" << name << ")" << endmsg;
833 ASIOBackendPort* port = NULL;
835 case DataType::AUDIO:
836 port = new ASIOPort (*this, name, flags);
839 port = new WindowsMidiPort (*this, name, flags);
842 PBD::error << _("ASIOBackend::register_port: Invalid Data Type.") << endmsg;
846 _ports.push_back (port);
852 ASIOBackend::unregister_port (PortEngine::PortHandle port_handle)
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;
863 disconnect_all(port_handle);
869 ASIOBackend::register_system_audio_ports()
873 const uint32_t a_ins = _n_inputs;
874 const uint32_t a_out = _n_outputs;
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);
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) {
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));
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);
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) {
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));
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);
907 ASIOBackend::unregister_ports (bool system_only)
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 ();
919 _ports.erase (_ports.begin() + i);
927 ASIOBackend::connect (const std::string& src, const std::string& dst)
929 ASIOBackendPort* src_port = find_port (src);
930 ASIOBackendPort* dst_port = find_port (dst);
933 PBD::error << _("ASIOBackend::connect: Invalid Source port:")
934 << " (" << src <<")" << endmsg;
938 PBD::error << _("ASIOBackend::connect: Invalid Destination port:")
939 << " (" << dst <<")" << endmsg;
942 return src_port->connect (dst_port);
946 ASIOBackend::disconnect (const std::string& src, const std::string& dst)
948 ASIOBackendPort* src_port = find_port (src);
949 ASIOBackendPort* dst_port = find_port (dst);
951 if (!src_port || !dst_port) {
952 PBD::error << _("ASIOBackend::disconnect: Invalid Port(s)") << endmsg;
955 return src_port->disconnect (dst_port);
959 ASIOBackend::connect (PortEngine::PortHandle src, const std::string& dst)
961 ASIOBackendPort* dst_port = find_port (dst);
962 if (!valid_port (src)) {
963 PBD::error << _("ASIOBackend::connect: Invalid Source Port Handle") << endmsg;
967 PBD::error << _("ASIOBackend::connect: Invalid Destination Port")
968 << " (" << dst << ")" << endmsg;
971 return static_cast<ASIOBackendPort*>(src)->connect (dst_port);
975 ASIOBackend::disconnect (PortEngine::PortHandle src, const std::string& dst)
977 ASIOBackendPort* dst_port = find_port (dst);
978 if (!valid_port (src) || !dst_port) {
979 PBD::error << _("ASIOBackend::disconnect: Invalid Port(s)") << endmsg;
982 return static_cast<ASIOBackendPort*>(src)->disconnect (dst_port);
986 ASIOBackend::disconnect_all (PortEngine::PortHandle port)
988 if (!valid_port (port)) {
989 PBD::error << _("ASIOBackend::disconnect_all: Invalid Port") << endmsg;
992 static_cast<ASIOBackendPort*>(port)->disconnect_all ();
997 ASIOBackend::connected (PortEngine::PortHandle port, bool /* process_callback_safe*/)
999 if (!valid_port (port)) {
1000 PBD::error << _("ASIOBackend::disconnect_all: Invalid Port") << endmsg;
1003 return static_cast<ASIOBackendPort*>(port)->is_connected ();
1007 ASIOBackend::connected_to (PortEngine::PortHandle src, const std::string& dst, bool /*process_callback_safe*/)
1009 ASIOBackendPort* dst_port = find_port (dst);
1010 if (!valid_port (src) || !dst_port) {
1011 PBD::error << _("ASIOBackend::connected_to: Invalid Port") << endmsg;
1014 return static_cast<ASIOBackendPort*>(src)->is_connected (dst_port);
1018 ASIOBackend::physically_connected (PortEngine::PortHandle port, bool /*process_callback_safe*/)
1020 if (!valid_port (port)) {
1021 PBD::error << _("ASIOBackend::physically_connected: Invalid Port") << endmsg;
1024 return static_cast<ASIOBackendPort*>(port)->is_physically_connected ();
1028 ASIOBackend::get_connections (PortEngine::PortHandle port, std::vector<std::string>& names, bool /*process_callback_safe*/)
1030 if (!valid_port (port)) {
1031 PBD::error << _("ASIOBackend::get_connections: Invalid Port") << endmsg;
1035 assert (0 == names.size ());
1037 const std::vector<ASIOBackendPort*>& connected_ports = static_cast<ASIOBackendPort*>(port)->get_connections ();
1039 for (std::vector<ASIOBackendPort*>::const_iterator i = connected_ports.begin (); i != connected_ports.end (); ++i) {
1040 names.push_back ((*i)->name ());
1043 return (int)names.size ();
1048 ASIOBackend::midi_event_get (
1049 pframes_t& timestamp,
1050 size_t& size, uint8_t** buf, void* port_buffer,
1051 uint32_t event_index)
1053 if (!buf || !port_buffer) return -1;
1054 WindowsMidiBuffer& source = * static_cast<WindowsMidiBuffer*>(port_buffer);
1055 if (event_index >= source.size ()) {
1058 WindowsMidiEvent * const event = source[event_index].get ();
1060 timestamp = event->timestamp ();
1061 size = event->size ();
1062 *buf = event->data ();
1067 ASIOBackend::midi_event_put (
1069 pframes_t timestamp,
1070 const uint8_t* buffer, size_t size)
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) {
1076 // nevermind, ::get_buffer() sorts events
1077 fprintf (stderr, "WindowsMidiBuffer: unordered event: %d > %d\n",
1078 (pframes_t)dst.back ()->timestamp (), timestamp);
1081 dst.push_back (boost::shared_ptr<WindowsMidiEvent>(new WindowsMidiEvent (timestamp, buffer, size)));
1086 ASIOBackend::get_midi_event_count (void* port_buffer)
1088 if (!port_buffer) return 0;
1089 return static_cast<WindowsMidiBuffer*>(port_buffer)->size ();
1093 ASIOBackend::midi_clear (void* port_buffer)
1095 if (!port_buffer) return;
1096 WindowsMidiBuffer * buf = static_cast<WindowsMidiBuffer*>(port_buffer);
1104 ASIOBackend::can_monitor_input () const
1110 ASIOBackend::request_input_monitoring (PortEngine::PortHandle, bool)
1116 ASIOBackend::ensure_input_monitoring (PortEngine::PortHandle, bool)
1122 ASIOBackend::monitoring_input (PortEngine::PortHandle)
1127 /* Latency management */
1130 ASIOBackend::set_latency_range (PortEngine::PortHandle port, bool for_playback, LatencyRange latency_range)
1132 if (!valid_port (port)) {
1133 PBD::error << _("ASIOBackendPort::set_latency_range (): invalid port.") << endmsg;
1135 static_cast<ASIOBackendPort*>(port)->set_latency_range (latency_range, for_playback);
1139 ASIOBackend::get_latency_range (PortEngine::PortHandle port, bool for_playback)
1142 if (!valid_port (port)) {
1143 PBD::error << _("ASIOBackendPort::get_latency_range (): invalid port.") << endmsg;
1148 ASIOBackendPort* p = static_cast<ASIOBackendPort*>(port);
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;
1157 if (p->is_output() && !for_playback) {
1158 r.min += _samples_per_period;
1159 r.max += _samples_per_period;
1165 /* Discovering physical ports */
1168 ASIOBackend::port_is_physical (PortEngine::PortHandle port) const
1170 if (!valid_port (port)) {
1171 PBD::error << _("ASIOBackendPort::port_is_physical (): invalid port.") << endmsg;
1174 return static_cast<ASIOBackendPort*>(port)->is_physical ();
1178 ASIOBackend::get_physical_outputs (DataType type, std::vector<std::string>& port_names)
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 ());
1189 ASIOBackend::get_physical_inputs (DataType type, std::vector<std::string>& port_names)
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 ());
1200 ASIOBackend::n_physical_outputs () const
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;
1215 cc.set (DataType::AUDIO, n_audio);
1216 cc.set (DataType::MIDI, n_midi);
1221 ASIOBackend::n_physical_inputs () const
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;
1236 cc.set (DataType::AUDIO, n_audio);
1237 cc.set (DataType::MIDI, n_midi);
1241 /* Getting access to the data buffer for a port */
1244 ASIOBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
1246 if (!port || !valid_port (port)) return NULL;
1247 return static_cast<ASIOBackendPort*>(port)->get_buffer (nframes);
1251 ASIOBackend::pre_process ()
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;
1260 if (!_port_connection_queue.empty ()) {
1261 connections_changed = true;
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 ();
1269 pthread_mutex_unlock (&_port_callback_mutex);
1271 if (ports_changed) {
1272 manager.registration_callback();
1274 if (connections_changed) {
1275 manager.graph_order_callback();
1277 if (connections_changed || ports_changed) {
1278 engine.latency_callback(false);
1279 engine.latency_callback(true);
1284 ASIOBackend::freewheel_thread ()
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.
1293 * Furthermore we need to make sure the registered process thread
1296 * _freewheeling = GUI thread state as set by ::freewheel()
1297 * _freewheel = in sync here (export thread)
1299 pthread_mutex_lock (&_freewheel_mutex);
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);
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
1322 gettimeofday (&tv, NULL);
1323 ts.tv_sec = tv.tv_sec + 3;
1325 pthread_cond_timedwait (&_freewheel_signal, &_freewheel_mutex, &ts);
1330 // tell the engine we're ready to GO.
1331 engine.freewheel_callback (_freewheeling);
1333 _main_thread = pthread_self();
1334 AudioEngine::thread_init_callback (this);
1336 _midiio->set_enabled(false);
1340 // process port updates first in every cycle.
1343 // prevent device changes
1344 pthread_mutex_lock (&_process_callback_mutex);
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));
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 ();
1356 _last_process_start = 0;
1357 if (engine.process_callback (_samples_per_period)) {
1358 pthread_mutex_unlock (&_process_callback_mutex);
1362 pthread_mutex_unlock (&_process_callback_mutex);
1364 Glib::usleep (100); // don't hog cpu
1367 pthread_mutex_unlock (&_freewheel_mutex);
1372 // engine.process_callback() returner error
1373 engine.halted_callback("ASIO Freehweeling aborted.");
1379 ASIOBackend::process_callback (const uint32_t n_samples, const uint64_t host_time)
1382 uint64_t clock1, clock2;
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);
1394 if (!_run || _freewheel || _preinit) {
1395 // NB if we return 1, the output is
1396 // zeroed by the asio callback
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);
1406 if (pthread_mutex_trylock (&_process_callback_mutex)) {
1407 // block while devices are added/removed
1409 printf("Xrun due to device change\n");
1414 /* port-connection change */
1417 // cycle-length in usec
1418 const double nominal_time = 1e6 * n_samples / _samplerate;
1420 clock1 = g_get_monotonic_time();
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));
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);
1442 for (std::vector<ASIOBackendPort*>::const_iterator it = _system_inputs.begin (); it != _system_inputs.end (); ++it, ++i) {
1444 _pcmio->get_capture_channel (i, (float*)((*it)->get_buffer(n_samples)), n_samples);
1446 memset ((*it)->get_buffer (n_samples), 0, n_samples * sizeof (Sample));
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));
1455 #if 0 // TODO; sync Audio + midi
1456 _midiio->start_cycle();
1458 _last_process_start = host_time;
1460 if (engine.process_callback (n_samples)) {
1461 fprintf(stderr, "ENGINE PROCESS ERROR\n");
1463 pthread_mutex_unlock (&_process_callback_mutex);
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);
1472 /* queue outgoing midi */
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);
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());
1488 /* write back audio */
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);
1496 _processed_samples += n_samples;
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;
1503 pthread_mutex_unlock (&_process_callback_mutex);
1508 ASIOBackend::error_callback ()
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);
1516 engine.halted_callback("ASIO Process aborted.");
1521 ASIOBackend::xrun_callback ()
1527 ASIOBackend::buffer_size_callback ()
1530 uint32_t bs = _pcmio->samples_per_period();
1531 if (bs == _samples_per_period) {
1534 _samples_per_period = bs;
1535 engine.buffer_size_change (_samples_per_period);
1540 ASIOBackend::sample_rate_callback ()
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.");
1553 ASIOBackend::hw_changed_callback ()
1556 _reinit_thread_callback = true;
1557 engine.request_device_list_update();
1561 /******************************************************************************/
1563 static boost::shared_ptr<ASIOBackend> _instance;
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 ();
1571 static ARDOUR::AudioBackendInfo _descriptor = {
1580 static boost::shared_ptr<AudioBackend>
1581 backend_factory (AudioEngine& e)
1584 _instance.reset (new ASIOBackend (e, _descriptor));
1590 instantiate (const std::string& arg1, const std::string& /* arg2 */)
1592 s_instance_name = arg1;
1604 already_configured ()
1615 extern "C" ARDOURBACKEND_API ARDOUR::AudioBackendInfo* descriptor ()
1617 return &_descriptor;
1621 /******************************************************************************/
1622 ASIOBackendPort::ASIOBackendPort (ASIOBackend &b, const std::string& name, PortFlags flags)
1627 _capture_latency_range.min = 0;
1628 _capture_latency_range.max = 0;
1629 _playback_latency_range.min = 0;
1630 _playback_latency_range.max = 0;
1633 ASIOBackendPort::~ASIOBackendPort () {
1638 int ASIOBackendPort::connect (ASIOBackendPort *port)
1641 PBD::error << _("ASIOBackendPort::connect (): invalid (null) port") << endmsg;
1645 if (type () != port->type ()) {
1646 PBD::error << _("ASIOBackendPort::connect (): wrong port-type") << endmsg;
1650 if (is_output () && port->is_output ()) {
1651 PBD::error << _("ASIOBackendPort::connect (): cannot inter-connect output ports.") << endmsg;
1655 if (is_input () && port->is_input ()) {
1656 PBD::error << _("ASIOBackendPort::connect (): cannot inter-connect input ports.") << endmsg;
1661 PBD::error << _("ASIOBackendPort::connect (): cannot self-connect ports.") << endmsg;
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 () << ")"
1674 _connect (port, true);
1679 void ASIOBackendPort::_connect (ASIOBackendPort *port, bool callback)
1681 _connections.push_back (port);
1683 port->_connect (this, false);
1684 _osx_backend.port_connect_callback (name(), port->name(), true);
1688 int ASIOBackendPort::disconnect (ASIOBackendPort *port)
1691 PBD::error << _("ASIOBackendPort::disconnect (): invalid (null) port") << endmsg;
1695 if (!is_connected (port)) {
1696 PBD::error << _("ASIOBackendPort::disconnect (): ports are not connected:")
1697 << " (" << name () << ") -> (" << port->name () << ")"
1701 _disconnect (port, true);
1705 void ASIOBackendPort::_disconnect (ASIOBackendPort *port, bool callback)
1707 std::vector<ASIOBackendPort*>::iterator it = std::find (_connections.begin (), _connections.end (), port);
1709 assert (it != _connections.end ());
1711 _connections.erase (it);
1714 port->_disconnect (this, false);
1715 _osx_backend.port_connect_callback (name(), port->name(), false);
1720 void ASIOBackendPort::disconnect_all ()
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 ();
1730 ASIOBackendPort::is_connected (const ASIOBackendPort *port) const
1732 return std::find (_connections.begin (), _connections.end (), port) != _connections.end ();
1735 bool ASIOBackendPort::is_physically_connected () const
1737 for (std::vector<ASIOBackendPort*>::const_iterator it = _connections.begin (); it != _connections.end (); ++it) {
1738 if ((*it)->is_physical ()) {
1745 /******************************************************************************/
1747 ASIOPort::ASIOPort (ASIOBackend &b, const std::string& name, PortFlags flags)
1748 : ASIOBackendPort (b, name, flags)
1750 memset (_buffer, 0, sizeof (_buffer));
1751 mlock(_buffer, sizeof (_buffer));
1754 ASIOPort::~ASIOPort () { }
1756 void* ASIOPort::get_buffer (pframes_t n_samples)
1759 std::vector<ASIOBackendPort*>::const_iterator it = get_connections ().begin ();
1760 if (it == get_connections ().end ()) {
1761 memset (_buffer, 0, n_samples * sizeof (Sample));
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) {
1781 WindowsMidiPort::WindowsMidiPort (ASIOBackend &b, const std::string& name, PortFlags flags)
1782 : ASIOBackendPort (b, name, flags)
1786 _buffer[0].clear ();
1787 _buffer[1].clear ();
1790 WindowsMidiPort::~WindowsMidiPort () { }
1792 struct MidiEventSorter {
1793 bool operator() (const boost::shared_ptr<WindowsMidiEvent>& a, const boost::shared_ptr<WindowsMidiEvent>& b) {
1798 void* WindowsMidiPort::get_buffer (pframes_t /* nframes */)
1801 (_buffer[_bufperiod]).clear ();
1802 for (std::vector<ASIOBackendPort*>::const_iterator i = get_connections ().begin ();
1803 i != get_connections ().end ();
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)));
1810 std::sort ((_buffer[_bufperiod]).begin (), (_buffer[_bufperiod]).end (), MidiEventSorter());
1812 return &(_buffer[_bufperiod]);
1815 WindowsMidiEvent::WindowsMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
1817 , _timestamp (timestamp)
1821 _data = (uint8_t*) malloc (size);
1822 memcpy (_data, data, size);
1826 WindowsMidiEvent::WindowsMidiEvent (const WindowsMidiEvent& other)
1827 : _size (other.size ())
1828 , _timestamp (other.timestamp ())
1831 if (other.size () && other.const_data ()) {
1832 _data = (uint8_t*) malloc (other.size ());
1833 memcpy (_data, other.const_data (), other.size ());
1837 WindowsMidiEvent::~WindowsMidiEvent () {