Fix non-buffered PA backend. Wait for backend to become active
[ardour.git] / libs / backends / portaudio / portaudio_backend.cc
index 0f816c991fb9f4814a5e1061c5507378dd08668c..5bb8ecb08dd22a82ae919c5e880fd1b057737526 100644 (file)
@@ -41,7 +41,7 @@
 
 #include "ardour/filesystem_paths.h"
 #include "ardour/port_manager.h"
-#include "i18n.h"
+#include "pbd/i18n.h"
 
 #include "audio_utils.h"
 
@@ -66,6 +66,7 @@ PortAudioBackend::PortAudioBackend (AudioEngine& e, AudioBackendInfo& info)
        , _pcmio (0)
        , _run (false)
        , _active (false)
+       , _use_blocking_api(false)
        , _freewheel (false)
        , _freewheeling (false)
        , _freewheel_ack (false)
@@ -92,6 +93,8 @@ PortAudioBackend::PortAudioBackend (AudioEngine& e, AudioBackendInfo& info)
        pthread_mutex_init (&_freewheel_mutex, 0);
        pthread_cond_init (&_freewheel_signal, 0);
 
+       _port_connection_queue.reserve (128);
+
        _pcmio = new PortAudioIO ();
        _midiio = new WinMMEMidiIO ();
 }
@@ -160,6 +163,18 @@ PortAudioBackend::update_devices ()
        return _pcmio->update_devices();
 }
 
+void
+PortAudioBackend::set_use_buffered_io (bool use_buffered_io)
+{
+       DEBUG_AUDIO (string_compose ("Portaudio: use_buffered_io %1 \n", use_buffered_io));
+
+       if (running()) {
+               return;
+       }
+
+       _use_blocking_api = use_buffered_io;
+}
+
 std::string
 PortAudioBackend::driver_name () const
 {
@@ -566,27 +581,29 @@ PortAudioBackend::_start (bool for_latency_measurement)
        }
 
        /* reset internal state */
+       assert (_run == false);
+       _run = false;
        _dsp_load = 0;
        _freewheeling = false;
        _freewheel = false;
 
        PaErrorCode err = paNoError;
 
-#ifdef USE_BLOCKING_API
-       err = _pcmio->open_blocking_stream(name_to_id(_input_audio_device),
-                                          name_to_id(_output_audio_device),
-                                          _samplerate,
-                                          _samples_per_period);
-
-#else
-       err = _pcmio->open_callback_stream(name_to_id(_input_audio_device),
-                                          name_to_id(_output_audio_device),
-                                          _samplerate,
-                                          _samples_per_period,
-                                          portaudio_callback,
-                                          this);
-
-#endif
+       if (_use_blocking_api) {
+               DEBUG_AUDIO("Opening blocking audio stream\n");
+               err = _pcmio->open_blocking_stream(name_to_id(_input_audio_device),
+                                                  name_to_id(_output_audio_device),
+                                                  _samplerate,
+                                                  _samples_per_period);
+       } else {
+               DEBUG_AUDIO("Opening callback audio stream\n");
+               err = _pcmio->open_callback_stream(name_to_id(_input_audio_device),
+                                                  name_to_id(_output_audio_device),
+                                                  _samplerate,
+                                                  _samples_per_period,
+                                                  portaudio_callback,
+                                                  this);
+       }
 
        // reintepret Portaudio error messages
        switch (err) {
@@ -626,7 +643,6 @@ PortAudioBackend::_start (bool for_latency_measurement)
 
        _measure_latency = for_latency_measurement;
 
-       _run = true;
        _port_change_flag = false;
 
        if (_midi_driver_option == winmme_driver_name) {
@@ -644,7 +660,6 @@ PortAudioBackend::_start (bool for_latency_measurement)
 
        if (register_system_midi_ports () != 0) {
                DEBUG_PORTS("Failed to register system midi ports.\n")
-               _run = false;
                return PortRegistrationError;
        }
 
@@ -652,7 +667,6 @@ PortAudioBackend::_start (bool for_latency_measurement)
 
        if (register_system_audio_ports()) {
                DEBUG_PORTS("Failed to register system audio ports.\n");
-               _run = false;
                return PortRegistrationError;
        }
 
@@ -661,30 +675,40 @@ PortAudioBackend::_start (bool for_latency_measurement)
 
        if (engine.reestablish_ports ()) {
                DEBUG_PORTS("Could not re-establish ports.\n");
-               _run = false;
                return PortReconnectError;
        }
 
-       engine.reconnect_ports ();
        _run = true;
+
+       engine.reconnect_ports ();
        _port_change_flag = false;
 
-#ifdef USE_BLOCKING_API
-       if (!start_blocking_process_thread()) {
-               return ProcessThreadStartError;
-       }
-#else
-       if (_pcmio->start_stream() != paNoError) {
-               DEBUG_AUDIO("Unable to start stream\n");
-               return AudioDeviceOpenError;
-       }
+       if (_use_blocking_api) {
+               if (!start_blocking_process_thread()) {
+                       return ProcessThreadStartError;
+               }
+       } else {
+               if (_pcmio->start_stream() != paNoError) {
+                       DEBUG_AUDIO("Unable to start stream\n");
+                       return AudioDeviceOpenError;
+               }
 
-       if (!start_freewheel_process_thread()) {
-               DEBUG_AUDIO("Unable to start freewheel thread\n");
-               stop();
-               return ProcessThreadStartError;
+               if (!start_freewheel_process_thread()) {
+                       DEBUG_AUDIO("Unable to start freewheel thread\n");
+                       stop();
+                       return ProcessThreadStartError;
+               }
+
+               /* wait for backend to become active */
+               int timeout = 5000;
+               while (!_active && --timeout > 0) { Glib::usleep (1000); }
+
+               if (timeout == 0 || !_active) {
+                       PBD::error << _("PortAudio:: failed to start device.") << endmsg;
+                       stop ();
+                       return ProcessThreadStartError;
+               }
        }
-#endif
 
        return NoError;
 }
@@ -814,20 +838,19 @@ PortAudioBackend::stop ()
 
        _run = false;
 
-#ifdef USE_BLOCKING_API
-       if (!stop_blocking_process_thread ()) {
-               return -1;
-       }
-#else
-       _pcmio->close_stream ();
-       _active = false;
+       if (_use_blocking_api) {
+               if (!stop_blocking_process_thread()) {
+                       return -1;
+               }
+       } else {
+               _pcmio->close_stream();
+               _active = false;
 
-       if (!stop_freewheel_process_thread ()) {
-               return -1;
+               if (!stop_freewheel_process_thread()) {
+                       return -1;
+               }
        }
 
-#endif
-
        unregister_ports();
 
        return (_active == false) ? 0 : -1;
@@ -900,6 +923,7 @@ PortAudioBackend::freewheel_process_thread()
                                _reinit_thread_callback = true; // hand over _main_thread
                                _freewheel_ack = false; // prepare next handshake
                                _midiio->set_enabled(true);
+                               engine.freewheel_callback (_freewheeling);
                        } else {
                                first_run = true;
                                _freewheel = true;
@@ -1091,7 +1115,7 @@ PortAudioBackend::create_process_thread (boost::function<void()> func)
 
        ThreadData* td = new ThreadData (this, func, stacksize);
 
-       if (_realtime_pthread_create (SCHED_FIFO, -21, stacksize,
+       if (_realtime_pthread_create (SCHED_FIFO, -22, stacksize,
                                &thread_id, portaudio_process_thread, td)) {
                pthread_attr_init (&attr);
                pthread_attr_setstacksize (&attr, stacksize);
@@ -1127,16 +1151,15 @@ PortAudioBackend::join_process_threads ()
 bool
 PortAudioBackend::in_process_thread ()
 {
-#ifdef USE_BLOCKING_API
-       if (pthread_equal (_main_blocking_thread, pthread_self()) != 0) {
-               return true;
-       }
-#else
-       if (pthread_equal (_main_thread, pthread_self()) != 0) {
-               return true;
+       if (_use_blocking_api) {
+               if (pthread_equal(_main_blocking_thread, pthread_self()) != 0) {
+                       return true;
+               }
+       } else {
+               if (pthread_equal(_main_thread, pthread_self()) != 0) {
+                       return true;
+               }
        }
-#endif
-
        for (std::vector<pthread_t>::const_iterator i = _threads.begin (); i != _threads.end (); ++i)
        {
                if (pthread_equal (*i, pthread_self ()) != 0) {
@@ -1226,6 +1249,24 @@ PortAudioBackend::get_port_property (PortHandle port,
        return -1;
 }
 
+int
+PortAudioBackend::set_port_property (PortHandle port,
+                                     const std::string& key,
+                                     const std::string& value,
+                                     const std::string& type)
+{
+       if (!valid_port (port)) {
+               DEBUG_PORTS("get_port_name: Invalid Port(s)\n");
+               return -1;
+       }
+
+       if (key == "http://jackaudio.org/metadata/pretty-name" && type.empty ()) {
+               static_cast<PamPort*>(port)->set_pretty_name (value);
+               return 0;
+       }
+       return -1;
+}
+
 PortEngine::PortHandle
 PortAudioBackend::get_port_by_name (const std::string& name) const
 {
@@ -1580,7 +1621,7 @@ PortAudioBackend::get_connections (PortEngine::PortHandle port, std::vector<std:
 int
 PortAudioBackend::midi_event_get (
                pframes_t& timestamp,
-               size_t& size, uint8_t** buf, void* port_buffer,
+               size_t& size, uint8_t const** buf, void* port_buffer,
                uint32_t event_index)
 {
        if (!buf || !port_buffer) return -1;
@@ -1588,11 +1629,11 @@ PortAudioBackend::midi_event_get (
        if (event_index >= source.size ()) {
                return -1;
        }
-       PortMidiEvent * const event = source[event_index].get ();
+       PortMidiEvent const& event = source[event_index];
 
-       timestamp = event->timestamp ();
-       size = event->size ();
-       *buf = event->data ();
+       timestamp = event.timestamp ();
+       size = event.size ();
+       *buf = event.data ();
        return 0;
 }
 
@@ -1604,13 +1645,15 @@ PortAudioBackend::midi_event_put (
 {
        if (!buffer || !port_buffer) return -1;
        PortMidiBuffer& dst = * static_cast<PortMidiBuffer*>(port_buffer);
-       if (dst.size () && (pframes_t)dst.back ()->timestamp () > timestamp) {
+#ifndef NDEBUG
+       if (dst.size () && (pframes_t)dst.back ().timestamp () > timestamp) {
                // nevermind, ::get_buffer() sorts events
                DEBUG_MIDI (string_compose ("PortMidiBuffer: unordered event: %1 > %2\n",
-                                           (pframes_t)dst.back ()->timestamp (),
+                                           (pframes_t)dst.back ().timestamp (),
                                            timestamp));
        }
-       dst.push_back (boost::shared_ptr<PortMidiEvent>(new PortMidiEvent (timestamp, buffer, size)));
+#endif
+       dst.push_back (PortMidiEvent (timestamp, buffer, size));
        return 0;
 }
 
@@ -1786,7 +1829,9 @@ PortAudioBackend::n_physical_inputs () const
 void*
 PortAudioBackend::get_buffer (PortEngine::PortHandle port, pframes_t nframes)
 {
-       if (!port || !valid_port (port)) return NULL;
+       assert (port);
+       assert (valid_port (port));
+       if (!port || !valid_port (port)) return NULL; // XXX remove me
        return static_cast<PamPort*>(port)->get_buffer (nframes);
 }
 
@@ -2006,7 +2051,7 @@ PortAudioBackend::process_incoming_midi ()
                mbuf->clear();
                uint64_t timestamp;
                pframes_t sample_offset;
-               uint8_t data[256];
+               uint8_t data[MaxWinMidiEventSize];
                size_t size = sizeof(data);
                while (_midiio->dequeue_input_event(i,
                                                    _cycle_timer.get_start(),
@@ -2047,14 +2092,14 @@ PortAudioBackend::process_outgoing_midi ()
                for (PortMidiBuffer::const_iterator mit = src->begin(); mit != src->end();
                     ++mit) {
                        uint64_t timestamp =
-                           _cycle_timer.timestamp_from_sample_offset((*mit)->timestamp());
+                           _cycle_timer.timestamp_from_sample_offset(mit->timestamp());
                        DEBUG_MIDI(string_compose("Queuing outgoing MIDI data for device: "
                                                  "%1 sample_offset: %2 timestamp: %3, size: %4\n",
                                                  _midiio->get_outputs()[i]->name(),
-                                                 (*mit)->timestamp(),
+                                                 mit->timestamp(),
                                                  timestamp,
-                                                 (*mit)->size()));
-                       _midiio->enqueue_output_event(i, timestamp, (*mit)->data(), (*mit)->size());
+                                                 mit->size()));
+                       _midiio->enqueue_output_event(i, timestamp, mit->data(), mit->size());
                }
        }
 }
@@ -2322,13 +2367,16 @@ PortMidiPort::PortMidiPort (PortAudioBackend &b, const std::string& name, PortFl
 {
        _buffer[0].clear ();
        _buffer[1].clear ();
+
+       _buffer[0].reserve (256);
+       _buffer[1].reserve (256);
 }
 
 PortMidiPort::~PortMidiPort () { }
 
 struct MidiEventSorter {
-       bool operator() (const boost::shared_ptr<PortMidiEvent>& a, const boost::shared_ptr<PortMidiEvent>& b) {
-               return *a < *b;
+       bool operator() (PortMidiEvent const& a, PortMidiEvent const& b) {
+               return a < b;
        }
 };
 
@@ -2341,10 +2389,10 @@ void* PortMidiPort::get_buffer (pframes_t /* nframes */)
                                ++i) {
                        const PortMidiBuffer * src = static_cast<const PortMidiPort*>(*i)->const_buffer ();
                        for (PortMidiBuffer::const_iterator it = src->begin (); it != src->end (); ++it) {
-                               (_buffer[_bufperiod]).push_back (boost::shared_ptr<PortMidiEvent>(new PortMidiEvent (**it)));
+                               (_buffer[_bufperiod]).push_back (*it);
                        }
                }
-               std::sort ((_buffer[_bufperiod]).begin (), (_buffer[_bufperiod]).end (), MidiEventSorter());
+               std::stable_sort ((_buffer[_bufperiod]).begin (), (_buffer[_bufperiod]).end (), MidiEventSorter());
        }
        return &(_buffer[_bufperiod]);
 }
@@ -2352,10 +2400,8 @@ void* PortMidiPort::get_buffer (pframes_t /* nframes */)
 PortMidiEvent::PortMidiEvent (const pframes_t timestamp, const uint8_t* data, size_t size)
        : _size (size)
        , _timestamp (timestamp)
-       , _data (0)
 {
-       if (size > 0) {
-               _data = (uint8_t*) malloc (size);
+       if (size > 0 && size < MaxWinMidiEventSize) {
                memcpy (_data, data, size);
        }
 }
@@ -2363,14 +2409,9 @@ PortMidiEvent::PortMidiEvent (const pframes_t timestamp, const uint8_t* data, si
 PortMidiEvent::PortMidiEvent (const PortMidiEvent& other)
        : _size (other.size ())
        , _timestamp (other.timestamp ())
-       , _data (0)
 {
-       if (other.size () && other.const_data ()) {
-               _data = (uint8_t*) malloc (other.size ());
-               memcpy (_data, other.const_data (), other.size ());
+       if (other._size > 0) {
+               assert (other._size < MaxWinMidiEventSize);
+               memcpy (_data, other._data, other._size);
        }
 };
-
-PortMidiEvent::~PortMidiEvent () {
-       free (_data);
-};