]> git.sesse.net Git - nageru/commitdiff
Support limited ALSA hotplug.
authorSteinar H. Gunderson <sgunderson@bigfoot.com>
Thu, 8 Sep 2016 21:43:50 +0000 (23:43 +0200)
committerSteinar H. Gunderson <sgunderson@bigfoot.com>
Wed, 19 Oct 2016 22:55:44 +0000 (00:55 +0200)
We don't support removing cards yet (we still just exit on error),
and thus also not replacing dead cards with re-plugged ones.
We also don't communicate changed state to the UI yet, and retry
could still be improved.

alsa_input.cpp
alsa_input.h
audio_mixer.h
input_mapping_dialog.cpp

index 4e507f39cb374de0360d1beb6eeb5a06345b98e9..e96366b3a693074930154788b8da49671445bb5a 100644 (file)
@@ -45,8 +45,13 @@ bool set_base_params(const char *device_name, snd_pcm_t *pcm_handle, snd_pcm_hw_
 
 }  // namespace
 
-ALSAInput::ALSAInput(const char *device, unsigned sample_rate, unsigned num_channels, audio_callback_t audio_callback)
-       : device(device), sample_rate(sample_rate), num_channels(num_channels), audio_callback(audio_callback)
+ALSAInput::ALSAInput(const char *device, unsigned sample_rate, unsigned num_channels, audio_callback_t audio_callback, ALSAPool *parent_pool, unsigned internal_dev_index)
+       : device(device),
+         sample_rate(sample_rate),
+         num_channels(num_channels),
+         audio_callback(audio_callback),
+         parent_pool(parent_pool),
+         internal_dev_index(internal_dev_index)
 {
        die_on_error(device, snd_pcm_open(&pcm_handle, device, SND_PCM_STREAM_CAPTURE, 0));
 
@@ -132,7 +137,10 @@ void ALSAInput::stop_capture_thread()
 
 void ALSAInput::capture_thread_func()
 {
+       parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::STARTING);
        die_on_error("snd_pcm_start()", snd_pcm_start(pcm_handle));
+       parent_pool->set_card_state(internal_dev_index, ALSAPool::Device::State::RUNNING);
+
        uint64_t num_frames_output = 0;
        while (!should_quit) {
                int ret = snd_pcm_wait(pcm_handle, /*timeout=*/100);
@@ -167,6 +175,7 @@ void ALSAInput::capture_thread_func()
                } while (!success);
                num_frames_output += frames;
        }
+       parent_pool->free_card(internal_dev_index);
 }
 
 int64_t ALSAInput::frames_to_pts(uint64_t n) const
@@ -187,7 +196,6 @@ ALSAPool::~ALSAPool()
        for (Device &device : devices) {
                if (device.input != nullptr) {
                        device.input->stop_capture_thread();
-                       delete device.input;
                }
        }
 }
@@ -233,12 +241,78 @@ void ALSAPool::enumerate_devices()
 
                // Enumerate all devices on this card.
                for (int dev_index = -1; snd_ctl_pcm_next_device(ctl, &dev_index) == 0 && dev_index >= 0; ) {
-                       add_device(card_index, dev_index);
+                       probe_device_with_retry(card_index, dev_index);
                }
        }
 }
 
-bool ALSAPool::add_device(unsigned card_index, unsigned dev_index)
+void ALSAPool::probe_device_with_retry(unsigned card_index, unsigned dev_index)
+{
+       char address[256];
+       snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
+
+       lock_guard<mutex> lock(add_device_mutex);
+       if (add_device_tries_left.count(address)) {
+               // Some thread is already busy retrying this,
+               // so just reset its count.
+               add_device_tries_left[address] = num_retries;
+               return;
+       }
+
+       // Try (while still holding the lock) to add the device synchronously.
+       ProbeResult result = probe_device_once(card_index, dev_index);
+       if (result == ProbeResult::SUCCESS) {
+               return;
+       } else if (result == ProbeResult::FAILURE) {
+               return;
+       }
+       assert(result == ProbeResult::DEFER);
+
+       // Add failed for whatever reason (probably just that the device
+       // isn't up yet. Set up a count so that nobody else starts a thread,
+       // then start it ourselves.
+       fprintf(stderr, "Trying %s again in one second...\n", address);
+       add_device_tries_left[address] = num_retries;
+       thread(&ALSAPool::probe_device_retry_thread_func, this, card_index, dev_index).detach();
+}
+
+void ALSAPool::probe_device_retry_thread_func(unsigned card_index, unsigned dev_index)
+{
+       char address[256];
+       snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
+
+       for ( ;; ) {  // Termination condition within the loop.
+               sleep(1);
+
+               // See if there are any retries left.
+               lock_guard<mutex> lock(add_device_mutex);
+               if (!add_device_tries_left.count(address) ||
+                   add_device_tries_left[address] == 0) {
+                       add_device_tries_left.erase(address);
+                       fprintf(stderr, "Giving up probe of %s.\n", address);
+                       return;
+               }
+
+               // Seemingly there were. Give it a try (we still hold the mutex).
+               ProbeResult result = probe_device_once(card_index, dev_index);
+               if (result == ProbeResult::SUCCESS) {
+                       add_device_tries_left.erase(address);
+                       fprintf(stderr, "Probe of %s succeeded.\n", address);
+                       return;
+               } else if (result == ProbeResult::FAILURE || --add_device_tries_left[address] == 0) {
+                       add_device_tries_left.erase(address);
+                       fprintf(stderr, "Giving up probe of %s.\n", address);
+                       return;
+               }
+
+               // Failed again.
+               assert(result == ProbeResult::DEFER);
+               fprintf(stderr, "Trying %s again in one second (%d tries left)...\n",
+                       address, add_device_tries_left[address]);
+       }
+}
+
+ALSAPool::ProbeResult ALSAPool::probe_device_once(unsigned card_index, unsigned dev_index)
 {
        char address[256];
        snprintf(address, sizeof(address), "hw:%d", card_index);
@@ -246,7 +320,7 @@ bool ALSAPool::add_device(unsigned card_index, unsigned dev_index)
        int err = snd_ctl_open(&ctl, address, 0);
        if (err < 0) {
                printf("%s: %s\n", address, snd_strerror(err));
-               return false;
+               return ALSAPool::ProbeResult::DEFER;
        }
        unique_ptr<snd_ctl_t, decltype(snd_ctl_close)*> ctl_closer(ctl, snd_ctl_close);
 
@@ -257,7 +331,8 @@ bool ALSAPool::add_device(unsigned card_index, unsigned dev_index)
        snd_pcm_info_set_stream(pcm_info, SND_PCM_STREAM_CAPTURE);
        if (snd_ctl_pcm_info(ctl, pcm_info) < 0) {
                // Not available for capture.
-               return false;
+               printf("%s: Not available for capture.\n", address);
+               return ALSAPool::ProbeResult::DEFER;
        }
 
        snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index);
@@ -279,54 +354,107 @@ bool ALSAPool::add_device(unsigned card_index, unsigned dev_index)
                snd_pcm_t *pcm_handle;
                int err = snd_pcm_open(&pcm_handle, address, SND_PCM_STREAM_CAPTURE, 0);
                if (err < 0) {
-                       // TODO: When we go to hotplug support, we should support some
-                       // retry here, as the device could legitimately be busy.
                        printf("%s: %s\n", address, snd_strerror(err));
-                       return false;
+                       return ALSAPool::ProbeResult::DEFER;
                }
                snd_pcm_hw_params_t *hw_params;
                snd_pcm_hw_params_alloca(&hw_params);
                unsigned sample_rate;
                if (!set_base_params(address, pcm_handle, hw_params, &sample_rate)) {
                        snd_pcm_close(pcm_handle);
-                       return false;
+                       return ALSAPool::ProbeResult::DEFER;
                }
                err = snd_pcm_hw_params_get_channels_max(hw_params, &num_channels);
                if (err < 0) {
                        fprintf(stderr, "[%s] snd_pcm_hw_params_get_channels_max(): %s\n",
                                address, snd_strerror(err));
                        snd_pcm_close(pcm_handle);
-                       return false;
+                       return ALSAPool::ProbeResult::DEFER;
                }
                snd_pcm_close(pcm_handle);
        }
 
        if (num_channels == 0) {
                printf("%s: No channel maps with channels\n", address);
-               return true;
+               return ALSAPool::ProbeResult::FAILURE;
        }
 
        snd_ctl_card_info_t *card_info;
        snd_ctl_card_info_alloca(&card_info);
        snd_ctl_card_info(ctl, card_info);
 
-       Device dev;
-       dev.address = address;
-       dev.name = snd_ctl_card_info_get_name(card_info);
-       dev.info = snd_pcm_info_get_name(pcm_info);
-       dev.num_channels = num_channels;
-       dev.state = Device::State::RUNNING;
-
        lock_guard<mutex> lock(mu);
-       devices.push_back(std::move(dev));
-       return true;
+       unsigned internal_dev_index = find_free_device_index();
+       devices[internal_dev_index].address = address;
+       devices[internal_dev_index].name = snd_ctl_card_info_get_name(card_info);
+       devices[internal_dev_index].info = snd_pcm_info_get_name(pcm_info);
+       devices[internal_dev_index].num_channels = num_channels;
+       devices[internal_dev_index].state = Device::State::READY;
+
+       fprintf(stderr, "%s: Probed successfully.\n", address);
+
+       return ALSAPool::ProbeResult::SUCCESS;
 }
 
 void ALSAPool::init()
 {
+       thread(&ALSAPool::inotify_thread_func, this).detach();
        enumerate_devices();
 }
 
+void ALSAPool::inotify_thread_func()
+{
+       int inotify_fd = inotify_init();
+       if (inotify_fd == -1) {
+               perror("inotify_init()");
+               fprintf(stderr, "No hotplug of ALSA devices available.\n");
+               return;
+       }
+
+       int watch_fd = inotify_add_watch(inotify_fd, "/dev/snd", IN_MOVE | IN_CREATE | IN_DELETE);
+       if (watch_fd == -1) {
+               perror("inotify_add_watch()");
+               fprintf(stderr, "No hotplug of ALSA devices available.\n");
+               close(inotify_fd);
+               return;
+       }
+
+       int size = sizeof(inotify_event) + NAME_MAX + 1;
+       unique_ptr<char[]> buf(new char[size]);
+       for ( ;; ) {
+               int ret = read(inotify_fd, buf.get(), size);
+               if (ret < int(sizeof(inotify_event))) {
+                       fprintf(stderr, "inotify read unexpectedly returned %d, giving up hotplug of ALSA devices.\n",
+                               int(ret));
+                       close(watch_fd);
+                       close(inotify_fd);
+                       return;
+               }
+
+               for (int i = 0; i < ret; ) {
+                       const inotify_event *event = reinterpret_cast<const inotify_event *>(&buf[i]);
+                       i += sizeof(inotify_event) + event->len;
+
+                       if (event->mask & IN_Q_OVERFLOW) {
+                               fprintf(stderr, "WARNING: inotify overflowed, may lose ALSA hotplug events.\n");
+                               continue;
+                       }
+                       unsigned card, device;
+                       char type;
+                       if (sscanf(event->name, "pcmC%uD%u%c", &card, &device, &type) == 3 && type == 'c') {
+                               if (event->mask & (IN_MOVED_FROM | IN_DELETE)) {
+                                       printf("Deleted capture device: Card %u, device %u\n", card, device);
+                                       // TODO: Unplug.
+                               }
+                               if (event->mask & (IN_MOVED_TO | IN_CREATE)) {
+                                       printf("Adding capture device: Card %u, device %u\n", card, device);
+                                       probe_device_with_retry(card, device);
+                               }
+                       }
+               }
+       }
+}
+
 void ALSAPool::reset_device(unsigned index)
 {
        lock_guard<mutex> lock(mu);
@@ -338,7 +466,8 @@ void ALSAPool::reset_device(unsigned index)
                inputs[index].reset();
        } else {
                // TODO: Put on a background thread instead of locking?
-               inputs[index].reset(new ALSAInput(device->address.c_str(), OUTPUT_FREQUENCY, device->num_channels, bind(&AudioMixer::add_audio, global_audio_mixer, DeviceSpec{InputSourceType::ALSA_INPUT, index}, _1, _2, _3, _4)));
+               auto callback = bind(&AudioMixer::add_audio, global_audio_mixer, DeviceSpec{InputSourceType::ALSA_INPUT, index}, _1, _2, _3, _4);
+               inputs[index].reset(new ALSAInput(device->address.c_str(), OUTPUT_FREQUENCY, device->num_channels, callback, this, index));
                inputs[index]->start_capture_thread();
        }
        device->input = inputs[index].get();
@@ -353,3 +482,46 @@ unsigned ALSAPool::get_capture_frequency(unsigned index)
        else
                return OUTPUT_FREQUENCY;
 }
+
+ALSAPool::Device::State ALSAPool::get_card_state(unsigned index)
+{
+       lock_guard<mutex> lock(mu);
+       assert(devices[index].held);
+       return devices[index].state;
+}
+
+void ALSAPool::set_card_state(unsigned index, ALSAPool::Device::State state)
+{
+       lock_guard<mutex> lock(mu);
+       devices[index].state = state;
+}
+
+unsigned ALSAPool::find_free_device_index()
+{
+       for (unsigned i = 0; i < devices.size(); ++i) {
+               if (devices[i].state == Device::State::EMPTY) {
+                       devices[i].state = Device::State::READY;
+                       return i;
+               }
+       }
+       Device new_dev;
+       new_dev.state = Device::State::READY;
+       devices.push_back(new_dev);
+       inputs.emplace_back(nullptr);
+       return devices.size() - 1;
+}
+
+void ALSAPool::free_card(unsigned index)
+{
+       lock_guard<mutex> lock(mu);
+       if (devices[index].held) {
+               devices[index].state = Device::State::DEAD;
+       } else {
+               devices[index].state = Device::State::EMPTY;
+               inputs[index].reset();
+       }
+       while (!devices.empty() && devices.back().state == Device::State::EMPTY) {
+               devices.pop_back();
+               inputs.pop_back();
+       }
+}
index d3768c5d109ed3921452641b2d75df09ba7633c4..07e8fe52e18dac164cdc6d967e92e3cf48fe1042 100644 (file)
 #include <functional>
 #include <string>
 #include <thread>
+#include <unordered_map>
 #include <vector>
 
 #include "bmusb/bmusb.h"
 #include "timebase.h"
 
+class ALSAPool;
+
 class ALSAInput {
 public:
        typedef std::function<bool(const uint8_t *data, unsigned num_samples, bmusb::AudioFormat audio_format, int64_t frame_length)> audio_callback_t;
 
-       ALSAInput(const char *device, unsigned sample_rate, unsigned num_channels, audio_callback_t audio_callback);
+       ALSAInput(const char *device, unsigned sample_rate, unsigned num_channels, audio_callback_t audio_callback, ALSAPool *parent_pool, unsigned internal_dev_index);
        ~ALSAInput();
 
        // NOTE: Might very well be different from the sample rate given to the
@@ -50,6 +53,8 @@ private:
        std::thread capture_thread;
        std::atomic<bool> should_quit{false};
        std::unique_ptr<uint8_t[]> buffer;
+       ALSAPool *parent_pool;
+       unsigned internal_dev_index;
 };
 
 // The class dealing with the collective of all ALSA cards in the system.
@@ -89,7 +94,7 @@ public:
                        // installed in place of this card, and then presumably be put
                        // back into STARTING or RUNNING.
                        DEAD
-               } state;
+               } state = State::EMPTY;
 
                std::string address;  // E.g. “hw:0,0”.
                std::string name, info;
@@ -124,6 +129,16 @@ public:
        // Note: The card must be held. Returns OUTPUT_FREQUENCY if the card is in EMPTY or DEAD.
        unsigned get_capture_frequency(unsigned index);
 
+       // Note: The card must be held.
+       Device::State get_card_state(unsigned index);
+
+       // Only for ALSAInput.
+       void set_card_state(unsigned index, Device::State state);
+
+       // Just a short form for taking <mu> and then moving the card to
+       // EMPTY or DEAD state. Only for ALSAInput and for internal use.
+       void free_card(unsigned index);
+
        // TODO: Add accessors and/or callbacks about changed state, so that
        // the UI actually stands a chance in using that information.
 
@@ -132,8 +147,35 @@ private:
        std::vector<Device> devices;  // Under mu.
        std::vector<std::unique_ptr<ALSAInput>> inputs;  // Under mu, corresponds 1:1 to devices.
 
+       // Keyed on device address (e.g. “hw:0,0”). If there's an entry here,
+       // it means we already have a thread doing retries, so we shouldn't
+       // start a new one.
+       std::unordered_map<std::string, unsigned> add_device_tries_left;  // Under add_device_mutex.
+       std::mutex add_device_mutex;
+
+       static constexpr int num_retries = 10;
+
+       void inotify_thread_func();
        void enumerate_devices();
-       bool add_device(unsigned card_index, unsigned dev_index);
+
+       // Try to add an input at the given card/device. If it succeeds, return
+       // synchronously. If not, fire off a background thread to try up to
+       // <num_retries> times.
+       void probe_device_with_retry(unsigned card_index, unsigned dev_index);
+       void probe_device_retry_thread_func(unsigned card_index, unsigned dev_index);
+
+       enum class ProbeResult {
+               SUCCESS,
+               DEFER,
+               FAILURE
+       };
+       ProbeResult probe_device_once(unsigned card_index, unsigned dev_index);
+
+       // Must be called with <mu> held. Will allocate a new entry if needed.
+       // The returned entry will be set to READY state.
+       unsigned find_free_device_index();
+
+       friend class ALSAInput;
 };
 
 #endif  // !defined(_ALSA_INPUT_H)
index e5922674f1245382b2a0dd872ca6291b437d6def..c845a26608aec82a3534826aacb86fd418d2ded1 100644 (file)
@@ -102,6 +102,12 @@ public:
        // or every card will be held forever.
        std::map<DeviceSpec, DeviceInfo> get_devices();
 
+       // See comments on ALSAPool::get_card_state().
+       ALSAPool::Device::State get_alsa_card_state(unsigned index)
+       {
+               return alsa_pool.get_card_state(index);
+       }
+
        void set_name(DeviceSpec device_spec, const std::string &name);
 
        void set_input_mapping(const InputMapping &input_mapping);
index 0a301d77cd749d244e1256d08eab69c312adcd32..08d68dcbc05ed783f1dacb2bf3aa30c2a8ab3790 100644 (file)
@@ -54,9 +54,20 @@ void InputMappingDialog::fill_row_from_bus(unsigned row, const InputMapping::Bus
        unsigned current_index = 0;
        card_combo->addItem(QString("(none)   "));
        for (const auto &spec_and_info : devices) {
+               QString label(QString::fromStdString(spec_and_info.second.name));
+               if (spec_and_info.first.type == InputSourceType::ALSA_INPUT) {
+                       ALSAPool::Device::State state = global_audio_mixer->get_alsa_card_state(spec_and_info.first.index);
+                       if (state == ALSAPool::Device::State::EMPTY) {
+                               continue;
+                       } else if (state == ALSAPool::Device::State::STARTING) {
+                               label += " (busy)";
+                       } else if (state == ALSAPool::Device::State::DEAD) {
+                               label += " (dead)";
+                       }
+               }
                ++current_index;
                card_combo->addItem(
-                       QString::fromStdString(spec_and_info.second.name + "   "),
+                       label + "   ",
                        qulonglong(DeviceSpec_to_key(spec_and_info.first)));
                if (bus.device == spec_and_info.first) {
                        card_combo->setCurrentIndex(current_index);