+
+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;
+ }
+
+ 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;
+}
+
+void ALSAPool::free_card(unsigned index)
+{
+ DeviceSpec spec{InputSourceType::ALSA_INPUT, index};
+ while (!global_audio_mixer->silence_card(spec, true))
+ ;
+
+ {
+ 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();
+ }
+ }
+
+ global_audio_mixer->trigger_state_changed_callback();
+}