From 34dabe75b7985a42432a2c0f948a9c5a9404e57b Mon Sep 17 00:00:00 2001 From: "Steinar H. Gunderson" Date: Wed, 21 Sep 2016 19:19:10 +0200 Subject: [PATCH] Move ALSAPool into its own file; it is pretty large now. --- Makefile | 2 +- alsa_input.cpp | 527 ++++--------------------------------------------- alsa_input.h | 144 +------------- alsa_pool.cpp | 468 +++++++++++++++++++++++++++++++++++++++++++ alsa_pool.h | 154 +++++++++++++++ audio_mixer.h | 1 + 6 files changed, 672 insertions(+), 624 deletions(-) create mode 100644 alsa_pool.cpp create mode 100644 alsa_pool.h diff --git a/Makefile b/Makefile index 1b1f038..65956ac 100644 --- a/Makefile +++ b/Makefile @@ -18,7 +18,7 @@ OBJS=glwidget.o main.o mainwindow.o vumeter.o lrameter.o vu_common.o correlation OBJS += glwidget.moc.o mainwindow.moc.o vumeter.moc.o lrameter.moc.o correlation_meter.moc.o aboutdialog.moc.o ellipsis_label.moc.o input_mapping_dialog.moc.o nonlinear_fader.moc.o clickable_label.moc.o # Mixer objects -AUDIO_MIXER_OBJS = audio_mixer.o alsa_input.o ebu_r128_proc.o stereocompressor.o resampling_queue.o flags.o correlation_measurer.o filter.o input_mapping.o state.pb.o +AUDIO_MIXER_OBJS = audio_mixer.o alsa_input.o alsa_pool.o ebu_r128_proc.o stereocompressor.o resampling_queue.o flags.o correlation_measurer.o filter.o input_mapping.o state.pb.o OBJS += mixer.o pbo_frame_allocator.o context.o ref_counted_frame.o theme.o httpd.o flags.o image_input.o alsa_output.o disk_space_estimator.o $(AUDIO_MIXER_OBJS) # Streaming and encoding objects diff --git a/alsa_input.cpp b/alsa_input.cpp index 0f8e99c..ff726f0 100644 --- a/alsa_input.cpp +++ b/alsa_input.cpp @@ -1,52 +1,18 @@ #include "alsa_input.h" -#include "audio_mixer.h" -#include "defs.h" -#include "state.pb.h" -#include +#include +#include +#include +#include +#include -#include -#include -#include +#include "alsa_pool.h" +#include "bmusb/bmusb.h" +#include "timebase.h" using namespace std; using namespace std::placeholders; -namespace { - -bool set_base_params(const char *device_name, snd_pcm_t *pcm_handle, snd_pcm_hw_params_t *hw_params, unsigned *sample_rate) -{ - int err; - err = snd_pcm_hw_params_any(pcm_handle, hw_params); - if (err < 0) { - fprintf(stderr, "[%s] snd_pcm_hw_params_any(): %s\n", device_name, snd_strerror(err)); - return false; - } - err = snd_pcm_hw_params_set_access(pcm_handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED); - if (err < 0) { - fprintf(stderr, "[%s] snd_pcm_hw_params_set_access(): %s\n", device_name, snd_strerror(err)); - return false; - } - snd_pcm_format_mask_t *format_mask; - snd_pcm_format_mask_alloca(&format_mask); - snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S16_LE); - snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S24_LE); - snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S32_LE); - err = snd_pcm_hw_params_set_format_mask(pcm_handle, hw_params, format_mask); - if (err < 0) { - fprintf(stderr, "[%s] snd_pcm_hw_params_set_format_mask(): %s\n", device_name, snd_strerror(err)); - return false; - } - err = snd_pcm_hw_params_set_rate_near(pcm_handle, hw_params, sample_rate, 0); - if (err < 0) { - fprintf(stderr, "[%s] snd_pcm_hw_params_set_rate_near(): %s\n", device_name, snd_strerror(err)); - return false; - } - return true; -} - -} // namespace - #define RETURN_ON_ERROR(msg, expr) do { \ int err = (expr); \ if (err < 0) { \ @@ -149,6 +115,37 @@ bool ALSAInput::open_device() return true; } +bool ALSAInput::set_base_params(const char *device_name, snd_pcm_t *pcm_handle, snd_pcm_hw_params_t *hw_params, unsigned *sample_rate) +{ + int err; + err = snd_pcm_hw_params_any(pcm_handle, hw_params); + if (err < 0) { + fprintf(stderr, "[%s] snd_pcm_hw_params_any(): %s\n", device_name, snd_strerror(err)); + return false; + } + err = snd_pcm_hw_params_set_access(pcm_handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED); + if (err < 0) { + fprintf(stderr, "[%s] snd_pcm_hw_params_set_access(): %s\n", device_name, snd_strerror(err)); + return false; + } + snd_pcm_format_mask_t *format_mask; + snd_pcm_format_mask_alloca(&format_mask); + snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S16_LE); + snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S24_LE); + snd_pcm_format_mask_set(format_mask, SND_PCM_FORMAT_S32_LE); + err = snd_pcm_hw_params_set_format_mask(pcm_handle, hw_params, format_mask); + if (err < 0) { + fprintf(stderr, "[%s] snd_pcm_hw_params_set_format_mask(): %s\n", device_name, snd_strerror(err)); + return false; + } + err = snd_pcm_hw_params_set_rate_near(pcm_handle, hw_params, sample_rate, 0); + if (err < 0) { + fprintf(stderr, "[%s] snd_pcm_hw_params_set_rate_near(): %s\n", device_name, snd_strerror(err)); + return false; + } + return true; +} + ALSAInput::~ALSAInput() { if (pcm_handle) { @@ -260,449 +257,3 @@ int64_t ALSAInput::frames_to_pts(uint64_t n) const return (n * TIMEBASE) / sample_rate; } -ALSAPool::~ALSAPool() -{ - for (Device &device : devices) { - if (device.input != nullptr) { - device.input->stop_capture_thread(); - } - } -} - -std::vector ALSAPool::get_devices() -{ - lock_guard lock(mu); - for (Device &device : devices) { - device.held = true; - } - return devices; -} - -void ALSAPool::hold_device(unsigned index) -{ - lock_guard lock(mu); - assert(index < devices.size()); - devices[index].held = true; -} - -void ALSAPool::release_device(unsigned index) -{ - lock_guard lock(mu); - if (index < devices.size()) { - devices[index].held = false; - } -} - -void ALSAPool::enumerate_devices() -{ - // Enumerate all cards. - for (int card_index = -1; snd_card_next(&card_index) == 0 && card_index >= 0; ) { - char address[256]; - snprintf(address, sizeof(address), "hw:%d", card_index); - - snd_ctl_t *ctl; - int err = snd_ctl_open(&ctl, address, 0); - if (err < 0) { - printf("%s: %s\n", address, snd_strerror(err)); - continue; - } - unique_ptr ctl_closer(ctl, snd_ctl_close); - - // Enumerate all devices on this card. - for (int dev_index = -1; snd_ctl_pcm_next_device(ctl, &dev_index) == 0 && dev_index >= 0; ) { - probe_device_with_retry(card_index, 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 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 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); - snd_ctl_t *ctl; - int err = snd_ctl_open(&ctl, address, 0); - if (err < 0) { - printf("%s: %s\n", address, snd_strerror(err)); - return ALSAPool::ProbeResult::DEFER; - } - unique_ptr ctl_closer(ctl, snd_ctl_close); - - snd_pcm_info_t *pcm_info; - snd_pcm_info_alloca(&pcm_info); - snd_pcm_info_set_device(pcm_info, dev_index); - snd_pcm_info_set_subdevice(pcm_info, 0); - snd_pcm_info_set_stream(pcm_info, SND_PCM_STREAM_CAPTURE); - if (snd_ctl_pcm_info(ctl, pcm_info) < 0) { - // Not available for capture. - printf("%s: Not available for capture.\n", address); - return ALSAPool::ProbeResult::DEFER; - } - - snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index); - - unsigned num_channels = 0; - - // Find all channel maps for this device, and pick out the one - // with the most channels. - snd_pcm_chmap_query_t **cmaps = snd_pcm_query_chmaps_from_hw(card_index, dev_index, 0, SND_PCM_STREAM_CAPTURE); - if (cmaps != nullptr) { - for (snd_pcm_chmap_query_t **ptr = cmaps; *ptr; ++ptr) { - num_channels = max(num_channels, (*ptr)->map.channels); - } - snd_pcm_free_chmaps(cmaps); - } - if (num_channels == 0) { - // Device had no channel maps. We need to open it to query. - // TODO: Do this asynchronously. - snd_pcm_t *pcm_handle; - int err = snd_pcm_open(&pcm_handle, address, SND_PCM_STREAM_CAPTURE, 0); - if (err < 0) { - printf("%s: %s\n", address, snd_strerror(err)); - 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 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 ALSAPool::ProbeResult::DEFER; - } - snd_pcm_close(pcm_handle); - } - - if (num_channels == 0) { - printf("%s: No channel maps with channels\n", address); - 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); - - string name = snd_ctl_card_info_get_name(card_info); - string info = snd_pcm_info_get_name(pcm_info); - - unsigned internal_dev_index; - string display_name; - { - lock_guard lock(mu); - internal_dev_index = find_free_device_index(name, info, num_channels, address); - devices[internal_dev_index].address = address; - devices[internal_dev_index].name = name; - devices[internal_dev_index].info = info; - devices[internal_dev_index].num_channels = num_channels; - // Note: Purposefully does not overwrite held. - - display_name = devices[internal_dev_index].display_name(); - } - - fprintf(stderr, "%s: Probed successfully.\n", address); - - reset_device(internal_dev_index); // Restarts it if it is held (ie., we just replaced a dead card). - - DeviceSpec spec{InputSourceType::ALSA_INPUT, internal_dev_index}; - global_audio_mixer->set_display_name(spec, display_name); - global_audio_mixer->trigger_state_changed_callback(); - - return ALSAPool::ProbeResult::SUCCESS; -} - -void ALSAPool::unplug_device(unsigned card_index, unsigned dev_index) -{ - char address[256]; - snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index); - for (unsigned i = 0; i < devices.size(); ++i) { - if (devices[i].state != Device::State::EMPTY && - devices[i].state != Device::State::DEAD && - devices[i].address == address) { - free_card(i); - } - } -} - -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 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(&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); - unplug_device(card, device); - } - 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 lock(mu); - Device *device = &devices[index]; - if (inputs[index] != nullptr) { - inputs[index]->stop_capture_thread(); - } - if (!device->held) { - inputs[index].reset(); - } else { - // TODO: Put on a background thread instead of locking? - 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(); -} - -unsigned ALSAPool::get_capture_frequency(unsigned index) -{ - lock_guard lock(mu); - assert(devices[index].held); - if (devices[index].input) - return devices[index].input->get_sample_rate(); - else - return OUTPUT_FREQUENCY; -} - -ALSAPool::Device::State ALSAPool::get_card_state(unsigned index) -{ - lock_guard lock(mu); - assert(devices[index].held); - return devices[index].state; -} - -void ALSAPool::set_card_state(unsigned index, ALSAPool::Device::State state) -{ - { - lock_guard lock(mu); - devices[index].state = state; - } - - DeviceSpec spec{InputSourceType::ALSA_INPUT, index}; - bool silence = (state != ALSAPool::Device::State::RUNNING); - while (!global_audio_mixer->silence_card(spec, silence)) - ; - global_audio_mixer->trigger_state_changed_callback(); -} - -unsigned ALSAPool::find_free_device_index(const string &name, const string &info, unsigned num_channels, const string &address) -{ - // First try to find an exact match on a dead card. - for (unsigned i = 0; i < devices.size(); ++i) { - if (devices[i].state == Device::State::DEAD && - devices[i].address == address && - devices[i].name == name && - devices[i].info == info && - devices[i].num_channels == num_channels) { - devices[i].state = Device::State::READY; - return i; - } - } - - // Then try to find a match on everything but the address - // (probably that devices were plugged back in a different order). - // If we have two cards that are equal, this might get them mixed up, - // but we don't have anything better. - for (unsigned i = 0; i < devices.size(); ++i) { - if (devices[i].state == Device::State::DEAD && - devices[i].name == name && - devices[i].info == info && - devices[i].num_channels == num_channels) { - devices[i].state = Device::State::READY; - return i; - } - } - - // OK, so we didn't find a match; see if there are any empty slots. - for (unsigned i = 0; i < devices.size(); ++i) { - if (devices[i].state == Device::State::EMPTY) { - devices[i].state = Device::State::READY; - devices[i].held = false; - return i; - } - } - - // Failing that, we just insert the new device at the end. - Device new_dev; - new_dev.state = Device::State::READY; - new_dev.held = false; - devices.push_back(new_dev); - inputs.emplace_back(nullptr); - return devices.size() - 1; -} - -unsigned ALSAPool::create_dead_card(const string &name, const string &info, unsigned num_channels) -{ - lock_guard lock(mu); - - // See if there are any empty slots. If not, insert one at the end. - vector::iterator free_device = - find_if(devices.begin(), devices.end(), - [](const Device &device) { return device.state == Device::State::EMPTY; }); - if (free_device == devices.end()) { - devices.push_back(Device()); - inputs.emplace_back(nullptr); - free_device = devices.end() - 1; - } - - free_device->state = Device::State::DEAD; - free_device->name = name; - free_device->info = info; - free_device->num_channels = num_channels; - free_device->held = true; - - return distance(devices.begin(), free_device); -} - -void ALSAPool::serialize_device(unsigned index, DeviceSpecProto *serialized) -{ - lock_guard lock(mu); - assert(index < devices.size()); - assert(devices[index].held); - serialized->set_type(DeviceSpecProto::ALSA_INPUT); - serialized->set_index(index); - serialized->set_display_name(devices[index].display_name()); - serialized->set_alsa_name(devices[index].name); - serialized->set_alsa_info(devices[index].info); - serialized->set_num_channels(devices[index].num_channels); - serialized->set_address(devices[index].address); -} - -void ALSAPool::free_card(unsigned index) -{ - DeviceSpec spec{InputSourceType::ALSA_INPUT, index}; - while (!global_audio_mixer->silence_card(spec, true)) - ; - - { - lock_guard 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(); - } - } - - global_audio_mixer->trigger_state_changed_callback(); -} diff --git a/alsa_input.h b/alsa_input.h index 3b98885..b08d47a 100644 --- a/alsa_input.h +++ b/alsa_input.h @@ -10,7 +10,9 @@ // as a whole, since that's what AudioMixer::add_audio() wants. #include - +#include +#include +#include #include #include #include @@ -43,6 +45,12 @@ public: void start_capture_thread(); void stop_capture_thread(); + // Set access, sample rate and format parameters on the given ALSA PCM handle. + // Returns the computed parameter set and the chosen sample rate. Note that + // sample_rate is an in/out parameter; you send in the desired rate, + // and ALSA picks one as close to that as possible. + static bool set_base_params(const char *device_name, snd_pcm_t *pcm_handle, snd_pcm_hw_params_t *hw_params, unsigned *sample_rate); + private: void capture_thread_func(); int64_t frames_to_pts(uint64_t n) const; @@ -69,138 +77,4 @@ private: unsigned internal_dev_index; }; -// The class dealing with the collective of all ALSA cards in the system. -// In particular, it deals with enumeration of cards, and hotplug of new ones. -class ALSAPool { -public: - ~ALSAPool(); - - struct Device { - enum class State { - // There is no card here. (There probably used to be one, - // but it got removed.) We don't insert a card before - // we've actually probed it, ie., we know whether it - // can be captured from at all, and what its name is. - EMPTY, - - // This card is ready for capture, as far as we know. - // (It could still be used by someone else; we don't know - // until we try to open it.) - READY, - - // We are trying to start capture from this card, but we are not - // streaming yet. Note that this could in theory go on forever, - // if the card is in use by some other process; in the UI, - // we will show this state as “(busy)”. - STARTING, - - // The card is capturing and sending data. If there's a fatal error, - // it could go back to STARTING, or it could go to DEAD - // (depending on the error). - RUNNING, - - // The card is gone (e.g., unplugged). However, since there's - // still a bus using it, we can't just remove the entry. - // If the card comes back (ie., a new card is plugged in, - // and we believe it has the same configuration), it could be - // installed in place of this card, and then presumably be put - // back into STARTING or RUNNING. - DEAD - } state = State::EMPTY; - - std::string address; // E.g. “hw:0,0”. - std::string name, info; - unsigned num_channels; - ALSAInput *input = nullptr; // nullptr iff EMPTY or DEAD. - - // Whether the AudioMixer is interested in this card or not. - // “Interested” could mean either of two things: Either it is part of - // a bus mapping, or it is in the process of enumerating devices - // (to show to the user). A card that is _not_ held can disappear - // at any given time as a result of an error or hotplug event; - // a card that is held will go to the DEAD state instead. - bool held = false; - - std::string display_name() const { return name + " (" + info + ")"; } - }; - - void init(); - - // Get the list of all current devices. Note that this will implicitly mark - // all of the returned devices as held, since the input mapping UI needs - // some kind of stability when the user is to choose. Thus, when you are done - // with the list and have set a new mapping, you must go through all the devices - // you don't want and release them using release_device(). - std::vector get_devices(); - - void hold_device(unsigned index); - void release_device(unsigned index); // Note: index is allowed to go out of bounds. - - // If device is held, start or restart capture. If device is not held, - // stop capture if it isn't already. - void reset_device(unsigned index); - - // 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 and then moving the card to - // EMPTY or DEAD state. Only for ALSAInput and for internal use. - void free_card(unsigned index); - - // Create a new card, mark it immediately as DEAD and hold it. - // Returns the new index. - unsigned create_dead_card(const std::string &name, const std::string &info, unsigned num_channels); - - // Make a protobuf representation of the given card, so that it can be - // matched against at a later stage. For AudioMixer only. - // The given card must be held. - void serialize_device(unsigned index, DeviceSpecProto *serialized); - -private: - mutable std::mutex mu; - std::vector devices; // Under mu. - std::vector> 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 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(); - - // 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 - // 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); - - void unplug_device(unsigned card_index, unsigned dev_index); - - // Must be called with held. Will allocate a new entry if needed. - // The returned entry will be set to READY state. - unsigned find_free_device_index(const std::string &name, - const std::string &info, - unsigned num_channels, - const std::string &address); - - friend class ALSAInput; -}; - #endif // !defined(_ALSA_INPUT_H) diff --git a/alsa_pool.cpp b/alsa_pool.cpp new file mode 100644 index 0000000..28e7ee0 --- /dev/null +++ b/alsa_pool.cpp @@ -0,0 +1,468 @@ +#include "alsa_pool.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "alsa_input.h" +#include "audio_mixer.h" +#include "defs.h" +#include "input_mapping.h" +#include "state.pb.h" + +using namespace std; +using namespace std::placeholders; + +ALSAPool::~ALSAPool() +{ + for (Device &device : devices) { + if (device.input != nullptr) { + device.input->stop_capture_thread(); + } + } +} + +std::vector ALSAPool::get_devices() +{ + lock_guard lock(mu); + for (Device &device : devices) { + device.held = true; + } + return devices; +} + +void ALSAPool::hold_device(unsigned index) +{ + lock_guard lock(mu); + assert(index < devices.size()); + devices[index].held = true; +} + +void ALSAPool::release_device(unsigned index) +{ + lock_guard lock(mu); + if (index < devices.size()) { + devices[index].held = false; + } +} + +void ALSAPool::enumerate_devices() +{ + // Enumerate all cards. + for (int card_index = -1; snd_card_next(&card_index) == 0 && card_index >= 0; ) { + char address[256]; + snprintf(address, sizeof(address), "hw:%d", card_index); + + snd_ctl_t *ctl; + int err = snd_ctl_open(&ctl, address, 0); + if (err < 0) { + printf("%s: %s\n", address, snd_strerror(err)); + continue; + } + unique_ptr ctl_closer(ctl, snd_ctl_close); + + // Enumerate all devices on this card. + for (int dev_index = -1; snd_ctl_pcm_next_device(ctl, &dev_index) == 0 && dev_index >= 0; ) { + probe_device_with_retry(card_index, 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 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 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); + snd_ctl_t *ctl; + int err = snd_ctl_open(&ctl, address, 0); + if (err < 0) { + printf("%s: %s\n", address, snd_strerror(err)); + return ALSAPool::ProbeResult::DEFER; + } + unique_ptr ctl_closer(ctl, snd_ctl_close); + + snd_pcm_info_t *pcm_info; + snd_pcm_info_alloca(&pcm_info); + snd_pcm_info_set_device(pcm_info, dev_index); + snd_pcm_info_set_subdevice(pcm_info, 0); + snd_pcm_info_set_stream(pcm_info, SND_PCM_STREAM_CAPTURE); + if (snd_ctl_pcm_info(ctl, pcm_info) < 0) { + // Not available for capture. + printf("%s: Not available for capture.\n", address); + return ALSAPool::ProbeResult::DEFER; + } + + snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index); + + unsigned num_channels = 0; + + // Find all channel maps for this device, and pick out the one + // with the most channels. + snd_pcm_chmap_query_t **cmaps = snd_pcm_query_chmaps_from_hw(card_index, dev_index, 0, SND_PCM_STREAM_CAPTURE); + if (cmaps != nullptr) { + for (snd_pcm_chmap_query_t **ptr = cmaps; *ptr; ++ptr) { + num_channels = max(num_channels, (*ptr)->map.channels); + } + snd_pcm_free_chmaps(cmaps); + } + if (num_channels == 0) { + // Device had no channel maps. We need to open it to query. + // TODO: Do this asynchronously. + snd_pcm_t *pcm_handle; + int err = snd_pcm_open(&pcm_handle, address, SND_PCM_STREAM_CAPTURE, 0); + if (err < 0) { + printf("%s: %s\n", address, snd_strerror(err)); + return ALSAPool::ProbeResult::DEFER; + } + snd_pcm_hw_params_t *hw_params; + snd_pcm_hw_params_alloca(&hw_params); + unsigned sample_rate; + if (!ALSAInput::set_base_params(address, pcm_handle, hw_params, &sample_rate)) { + snd_pcm_close(pcm_handle); + 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 ALSAPool::ProbeResult::DEFER; + } + snd_pcm_close(pcm_handle); + } + + if (num_channels == 0) { + printf("%s: No channel maps with channels\n", address); + 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); + + string name = snd_ctl_card_info_get_name(card_info); + string info = snd_pcm_info_get_name(pcm_info); + + unsigned internal_dev_index; + string display_name; + { + lock_guard lock(mu); + internal_dev_index = find_free_device_index(name, info, num_channels, address); + devices[internal_dev_index].address = address; + devices[internal_dev_index].name = name; + devices[internal_dev_index].info = info; + devices[internal_dev_index].num_channels = num_channels; + // Note: Purposefully does not overwrite held. + + display_name = devices[internal_dev_index].display_name(); + } + + fprintf(stderr, "%s: Probed successfully.\n", address); + + reset_device(internal_dev_index); // Restarts it if it is held (ie., we just replaced a dead card). + + DeviceSpec spec{InputSourceType::ALSA_INPUT, internal_dev_index}; + global_audio_mixer->set_display_name(spec, display_name); + global_audio_mixer->trigger_state_changed_callback(); + + return ALSAPool::ProbeResult::SUCCESS; +} + +void ALSAPool::unplug_device(unsigned card_index, unsigned dev_index) +{ + char address[256]; + snprintf(address, sizeof(address), "hw:%d,%d", card_index, dev_index); + for (unsigned i = 0; i < devices.size(); ++i) { + if (devices[i].state != Device::State::EMPTY && + devices[i].state != Device::State::DEAD && + devices[i].address == address) { + free_card(i); + } + } +} + +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 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(&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); + unplug_device(card, device); + } + 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 lock(mu); + Device *device = &devices[index]; + if (inputs[index] != nullptr) { + inputs[index]->stop_capture_thread(); + } + if (!device->held) { + inputs[index].reset(); + } else { + // TODO: Put on a background thread instead of locking? + 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(); +} + +unsigned ALSAPool::get_capture_frequency(unsigned index) +{ + lock_guard lock(mu); + assert(devices[index].held); + if (devices[index].input) + return devices[index].input->get_sample_rate(); + else + return OUTPUT_FREQUENCY; +} + +ALSAPool::Device::State ALSAPool::get_card_state(unsigned index) +{ + lock_guard lock(mu); + assert(devices[index].held); + return devices[index].state; +} + +void ALSAPool::set_card_state(unsigned index, ALSAPool::Device::State state) +{ + { + lock_guard lock(mu); + devices[index].state = state; + } + + DeviceSpec spec{InputSourceType::ALSA_INPUT, index}; + bool silence = (state != ALSAPool::Device::State::RUNNING); + while (!global_audio_mixer->silence_card(spec, silence)) + ; + global_audio_mixer->trigger_state_changed_callback(); +} + +unsigned ALSAPool::find_free_device_index(const string &name, const string &info, unsigned num_channels, const string &address) +{ + // First try to find an exact match on a dead card. + for (unsigned i = 0; i < devices.size(); ++i) { + if (devices[i].state == Device::State::DEAD && + devices[i].address == address && + devices[i].name == name && + devices[i].info == info && + devices[i].num_channels == num_channels) { + devices[i].state = Device::State::READY; + return i; + } + } + + // Then try to find a match on everything but the address + // (probably that devices were plugged back in a different order). + // If we have two cards that are equal, this might get them mixed up, + // but we don't have anything better. + for (unsigned i = 0; i < devices.size(); ++i) { + if (devices[i].state == Device::State::DEAD && + devices[i].name == name && + devices[i].info == info && + devices[i].num_channels == num_channels) { + devices[i].state = Device::State::READY; + return i; + } + } + + // OK, so we didn't find a match; see if there are any empty slots. + for (unsigned i = 0; i < devices.size(); ++i) { + if (devices[i].state == Device::State::EMPTY) { + devices[i].state = Device::State::READY; + devices[i].held = false; + return i; + } + } + + // Failing that, we just insert the new device at the end. + Device new_dev; + new_dev.state = Device::State::READY; + new_dev.held = false; + devices.push_back(new_dev); + inputs.emplace_back(nullptr); + return devices.size() - 1; +} + +unsigned ALSAPool::create_dead_card(const string &name, const string &info, unsigned num_channels) +{ + lock_guard lock(mu); + + // See if there are any empty slots. If not, insert one at the end. + vector::iterator free_device = + find_if(devices.begin(), devices.end(), + [](const Device &device) { return device.state == Device::State::EMPTY; }); + if (free_device == devices.end()) { + devices.push_back(Device()); + inputs.emplace_back(nullptr); + free_device = devices.end() - 1; + } + + free_device->state = Device::State::DEAD; + free_device->name = name; + free_device->info = info; + free_device->num_channels = num_channels; + free_device->held = true; + + return distance(devices.begin(), free_device); +} + +void ALSAPool::serialize_device(unsigned index, DeviceSpecProto *serialized) +{ + lock_guard lock(mu); + assert(index < devices.size()); + assert(devices[index].held); + serialized->set_type(DeviceSpecProto::ALSA_INPUT); + serialized->set_index(index); + serialized->set_display_name(devices[index].display_name()); + serialized->set_alsa_name(devices[index].name); + serialized->set_alsa_info(devices[index].info); + serialized->set_num_channels(devices[index].num_channels); + serialized->set_address(devices[index].address); +} + +void ALSAPool::free_card(unsigned index) +{ + DeviceSpec spec{InputSourceType::ALSA_INPUT, index}; + while (!global_audio_mixer->silence_card(spec, true)) + ; + + { + lock_guard 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(); + } + } + + global_audio_mixer->trigger_state_changed_callback(); +} diff --git a/alsa_pool.h b/alsa_pool.h new file mode 100644 index 0000000..bc82201 --- /dev/null +++ b/alsa_pool.h @@ -0,0 +1,154 @@ +#ifndef _ALSA_POOL_H +#define _ALSA_POOL_H 1 + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "alsa_input.h" +#include "bmusb/bmusb.h" +#include "timebase.h" + +class ALSAInput; +class DeviceSpecProto; + +// The class dealing with the collective of all ALSA cards in the system. +// In particular, it deals with enumeration of cards, and hotplug of new ones. +class ALSAPool { +public: + ~ALSAPool(); + + struct Device { + enum class State { + // There is no card here. (There probably used to be one, + // but it got removed.) We don't insert a card before + // we've actually probed it, ie., we know whether it + // can be captured from at all, and what its name is. + EMPTY, + + // This card is ready for capture, as far as we know. + // (It could still be used by someone else; we don't know + // until we try to open it.) + READY, + + // We are trying to start capture from this card, but we are not + // streaming yet. Note that this could in theory go on forever, + // if the card is in use by some other process; in the UI, + // we will show this state as “(busy)”. + STARTING, + + // The card is capturing and sending data. If there's a fatal error, + // it could go back to STARTING, or it could go to DEAD + // (depending on the error). + RUNNING, + + // The card is gone (e.g., unplugged). However, since there's + // still a bus using it, we can't just remove the entry. + // If the card comes back (ie., a new card is plugged in, + // and we believe it has the same configuration), it could be + // installed in place of this card, and then presumably be put + // back into STARTING or RUNNING. + DEAD + } state = State::EMPTY; + + std::string address; // E.g. “hw:0,0”. + std::string name, info; + unsigned num_channels; + ALSAInput *input = nullptr; // nullptr iff EMPTY or DEAD. + + // Whether the AudioMixer is interested in this card or not. + // “Interested” could mean either of two things: Either it is part of + // a bus mapping, or it is in the process of enumerating devices + // (to show to the user). A card that is _not_ held can disappear + // at any given time as a result of an error or hotplug event; + // a card that is held will go to the DEAD state instead. + bool held = false; + + std::string display_name() const { return name + " (" + info + ")"; } + }; + + void init(); + + // Get the list of all current devices. Note that this will implicitly mark + // all of the returned devices as held, since the input mapping UI needs + // some kind of stability when the user is to choose. Thus, when you are done + // with the list and have set a new mapping, you must go through all the devices + // you don't want and release them using release_device(). + std::vector get_devices(); + + void hold_device(unsigned index); + void release_device(unsigned index); // Note: index is allowed to go out of bounds. + + // If device is held, start or restart capture. If device is not held, + // stop capture if it isn't already. + void reset_device(unsigned index); + + // 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 and then moving the card to + // EMPTY or DEAD state. Only for ALSAInput and for internal use. + void free_card(unsigned index); + + // Create a new card, mark it immediately as DEAD and hold it. + // Returns the new index. + unsigned create_dead_card(const std::string &name, const std::string &info, unsigned num_channels); + + // Make a protobuf representation of the given card, so that it can be + // matched against at a later stage. For AudioMixer only. + // The given card must be held. + void serialize_device(unsigned index, DeviceSpecProto *serialized); + +private: + mutable std::mutex mu; + std::vector devices; // Under mu. + std::vector> 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 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(); + + // 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 + // 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); + + void unplug_device(unsigned card_index, unsigned dev_index); + + // Must be called with held. Will allocate a new entry if needed. + // The returned entry will be set to READY state. + unsigned find_free_device_index(const std::string &name, + const std::string &info, + unsigned num_channels, + const std::string &address); + + friend class ALSAInput; +}; + +#endif // !defined(_ALSA_POOL_H) diff --git a/audio_mixer.h b/audio_mixer.h index 502a442..2794367 100644 --- a/audio_mixer.h +++ b/audio_mixer.h @@ -19,6 +19,7 @@ #include #include "alsa_input.h" +#include "alsa_pool.h" #include "bmusb/bmusb.h" #include "correlation_measurer.h" #include "db.h" -- 2.39.2