summaryrefslogtreecommitdiffstats
path: root/src/modules/alsa
diff options
context:
space:
mode:
Diffstat (limited to 'src/modules/alsa')
-rw-r--r--src/modules/alsa/90-pulseaudio.rules170
-rw-r--r--src/modules/alsa/alsa-mixer.c5386
-rw-r--r--src/modules/alsa/alsa-mixer.h411
-rw-r--r--src/modules/alsa/alsa-sink.c2832
-rw-r--r--src/modules/alsa/alsa-sink.h34
-rw-r--r--src/modules/alsa/alsa-source.c2473
-rw-r--r--src/modules/alsa/alsa-source.h34
-rw-r--r--src/modules/alsa/alsa-ucm.c2396
-rw-r--r--src/modules/alsa/alsa-ucm.h294
-rw-r--r--src/modules/alsa/alsa-util.c1891
-rw-r--r--src/modules/alsa/alsa-util.h167
-rw-r--r--src/modules/alsa/meson.build51
-rw-r--r--src/modules/alsa/mixer/meson.build7
-rw-r--r--src/modules/alsa/mixer/paths/analog-input-aux.conf65
-rw-r--r--src/modules/alsa/mixer/paths/analog-input-dock-mic.conf104
-rw-r--r--src/modules/alsa/mixer/paths/analog-input-fm.conf65
-rw-r--r--src/modules/alsa/mixer/paths/analog-input-front-mic.conf104
-rw-r--r--src/modules/alsa/mixer/paths/analog-input-headphone-mic.conf102
-rw-r--r--src/modules/alsa/mixer/paths/analog-input-headset-mic.conf114
-rw-r--r--src/modules/alsa/mixer/paths/analog-input-internal-mic-always.conf133
-rw-r--r--src/modules/alsa/mixer/paths/analog-input-internal-mic.conf154
-rw-r--r--src/modules/alsa/mixer/paths/analog-input-linein.conf144
-rw-r--r--src/modules/alsa/mixer/paths/analog-input-mic-line.conf66
-rw-r--r--src/modules/alsa/mixer/paths/analog-input-mic.conf141
-rw-r--r--src/modules/alsa/mixer/paths/analog-input-mic.conf.common60
-rw-r--r--src/modules/alsa/mixer/paths/analog-input-rear-mic.conf104
-rw-r--r--src/modules/alsa/mixer/paths/analog-input-tvtuner.conf65
-rw-r--r--src/modules/alsa/mixer/paths/analog-input-video.conf64
-rw-r--r--src/modules/alsa/mixer/paths/analog-input.conf102
-rw-r--r--src/modules/alsa/mixer/paths/analog-input.conf.common289
-rw-r--r--src/modules/alsa/mixer/paths/analog-output-headphones-2.conf116
-rw-r--r--src/modules/alsa/mixer/paths/analog-output-headphones.conf174
-rw-r--r--src/modules/alsa/mixer/paths/analog-output-lineout.conf208
-rw-r--r--src/modules/alsa/mixer/paths/analog-output-mono.conf99
-rw-r--r--src/modules/alsa/mixer/paths/analog-output-speaker-always.conf181
-rw-r--r--src/modules/alsa/mixer/paths/analog-output-speaker.conf233
-rw-r--r--src/modules/alsa/mixer/paths/analog-output.conf82
-rw-r--r--src/modules/alsa/mixer/paths/analog-output.conf.common186
-rw-r--r--src/modules/alsa/mixer/paths/hdmi-output-0.conf12
-rw-r--r--src/modules/alsa/mixer/paths/hdmi-output-1.conf12
-rw-r--r--src/modules/alsa/mixer/paths/hdmi-output-2.conf12
-rw-r--r--src/modules/alsa/mixer/paths/hdmi-output-3.conf12
-rw-r--r--src/modules/alsa/mixer/paths/hdmi-output-4.conf12
-rw-r--r--src/modules/alsa/mixer/paths/hdmi-output-5.conf12
-rw-r--r--src/modules/alsa/mixer/paths/hdmi-output-6.conf12
-rw-r--r--src/modules/alsa/mixer/paths/hdmi-output-7.conf12
-rw-r--r--src/modules/alsa/mixer/paths/iec958-stereo-input.conf20
-rw-r--r--src/modules/alsa/mixer/paths/iec958-stereo-output.conf18
-rw-r--r--src/modules/alsa/mixer/paths/steelseries-arctis-output-chat-common.conf27
-rw-r--r--src/modules/alsa/mixer/paths/steelseries-arctis-output-game-common.conf27
-rw-r--r--src/modules/alsa/mixer/paths/usb-gaming-headset-input.conf34
-rw-r--r--src/modules/alsa/mixer/paths/usb-gaming-headset-output-mono.conf34
-rw-r--r--src/modules/alsa/mixer/paths/usb-gaming-headset-output-stereo.conf32
-rw-r--r--src/modules/alsa/mixer/profile-sets/audigy.conf94
-rw-r--r--src/modules/alsa/mixer/profile-sets/cmedia-high-speed-true-hdaudio.conf66
-rw-r--r--src/modules/alsa/mixer/profile-sets/default.conf484
-rw-r--r--src/modules/alsa/mixer/profile-sets/dell-dock-tb16-usb-audio.conf55
-rw-r--r--src/modules/alsa/mixer/profile-sets/force-speaker-and-int-mic.conf153
-rw-r--r--src/modules/alsa/mixer/profile-sets/force-speaker.conf152
-rw-r--r--src/modules/alsa/mixer/profile-sets/kinect-audio.conf38
-rw-r--r--src/modules/alsa/mixer/profile-sets/maudio-fasttrack-pro.conf86
-rw-r--r--src/modules/alsa/mixer/profile-sets/native-instruments-audio4dj.conf90
-rw-r--r--src/modules/alsa/mixer/profile-sets/native-instruments-audio8dj.conf161
-rw-r--r--src/modules/alsa/mixer/profile-sets/native-instruments-korecontroller.conf84
-rw-r--r--src/modules/alsa/mixer/profile-sets/native-instruments-traktor-audio10.conf130
-rw-r--r--src/modules/alsa/mixer/profile-sets/native-instruments-traktor-audio2.conf53
-rw-r--r--src/modules/alsa/mixer/profile-sets/native-instruments-traktor-audio6.conf91
-rw-r--r--src/modules/alsa/mixer/profile-sets/native-instruments-traktorkontrol-s4.conf80
-rw-r--r--src/modules/alsa/mixer/profile-sets/sb-omni-surround-5.1.conf112
-rw-r--r--src/modules/alsa/mixer/profile-sets/steelseries-arctis-common-usb-audio.conf23
-rw-r--r--src/modules/alsa/mixer/profile-sets/usb-gaming-headset.conf64
-rw-r--r--src/modules/alsa/module-alsa-card.c1115
-rw-r--r--src/modules/alsa/module-alsa-sink.c137
-rw-r--r--src/modules/alsa/module-alsa-source.c144
74 files changed, 23001 insertions, 0 deletions
diff --git a/src/modules/alsa/90-pulseaudio.rules b/src/modules/alsa/90-pulseaudio.rules
new file mode 100644
index 0000000..7bfacda
--- /dev/null
+++ b/src/modules/alsa/90-pulseaudio.rules
@@ -0,0 +1,170 @@
+# do not edit this file, it will be overwritten on update
+
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+SUBSYSTEM!="sound", GOTO="pulseaudio_end"
+ACTION!="change", GOTO="pulseaudio_end"
+KERNEL!="card*", GOTO="pulseaudio_end"
+SUBSYSTEMS=="usb", GOTO="pulseaudio_check_usb"
+SUBSYSTEMS=="pci", GOTO="pulseaudio_check_pci"
+SUBSYSTEMS=="firewire", GOTO="pulseaudio_firewire_quirk"
+
+SUBSYSTEMS=="platform", DRIVERS=="thinkpad_acpi", ENV{PULSE_IGNORE}="1"
+
+# Force enable speaker and internal mic for some laptops
+# This should only be necessary for kernels 3.3, 3.4 and 3.5 (as they are lacking the phantom jack kctls).
+# Acer AOA150
+ATTRS{subsystem_vendor}=="0x1025", ATTRS{subsystem_device}=="0x015b", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Acer Aspire 4810TZ
+ATTRS{subsystem_vendor}=="0x1025", ATTRS{subsystem_device}=="0x022a", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Packard bell dot m/a
+ATTRS{subsystem_vendor}=="0x1025", ATTRS{subsystem_device}=="0x028c", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Acer Aspire 1810TZ
+ATTRS{subsystem_vendor}=="0x1025", ATTRS{subsystem_device}=="0x029b", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Acer AOD260 and AO532h
+ATTRS{subsystem_vendor}=="0x1025", ATTRS{subsystem_device}=="0x0349", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Dell MXC051
+ATTRS{subsystem_vendor}=="0x1028", ATTRS{subsystem_device}=="0x01b5", ENV{PULSE_PROFILE_SET}="force-speaker.conf"
+# Dell Inspiron 6400 and E1505
+ATTRS{subsystem_vendor}=="0x1028", ATTRS{subsystem_device}=="0x01bd", ENV{PULSE_PROFILE_SET}="force-speaker.conf"
+# Dell Latitude D620
+ATTRS{subsystem_vendor}=="0x1028", ATTRS{subsystem_device}=="0x01c2", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Dell Latitude D820
+ATTRS{subsystem_vendor}=="0x1028", ATTRS{subsystem_device}=="0x01cc", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Dell Latitude D520
+ATTRS{subsystem_vendor}=="0x1028", ATTRS{subsystem_device}=="0x01d4", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Dell Latitude D420
+ATTRS{subsystem_vendor}=="0x1028", ATTRS{subsystem_device}=="0x01d6", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Dell Inspiron 1525
+ATTRS{subsystem_vendor}=="0x1028", ATTRS{subsystem_device}=="0x022f", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Dell Inspiron 1011
+ATTRS{subsystem_vendor}=="0x1028", ATTRS{subsystem_device}=="0x02f4", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Dell XPS 14 (L401X)
+ATTRS{subsystem_vendor}=="0x1028", ATTRS{subsystem_device}=="0x0468", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Dell XPS 15 (L501X)
+ATTRS{subsystem_vendor}=="0x1028", ATTRS{subsystem_device}=="0x046e", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Dell XPS 15 (L502X)
+ATTRS{subsystem_vendor}=="0x1028", ATTRS{subsystem_device}=="0x050e", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Dell Inspiron 3420
+ATTRS{subsystem_vendor}=="0x1028", ATTRS{subsystem_device}=="0x0553", ENV{PULSE_PROFILE_SET}="force-speaker.conf"
+# Dell Inspiron 3520
+ATTRS{subsystem_vendor}=="0x1028", ATTRS{subsystem_device}=="0x0555", ENV{PULSE_PROFILE_SET}="force-speaker.conf"
+# Dell Vostro 2420
+ATTRS{subsystem_vendor}=="0x1028", ATTRS{subsystem_device}=="0x0556", ENV{PULSE_PROFILE_SET}="force-speaker.conf"
+# Dell Vostro 2520
+ATTRS{subsystem_vendor}=="0x1028", ATTRS{subsystem_device}=="0x0558", ENV{PULSE_PROFILE_SET}="force-speaker.conf"
+# Dell Inspiron One 2020
+ATTRS{subsystem_vendor}=="0x1028", ATTRS{subsystem_device}=="0x0579", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Asus 904HA (1000H)
+ATTRS{subsystem_vendor}=="0x1043", ATTRS{subsystem_device}=="0x831a", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Asus T101MT
+ATTRS{subsystem_vendor}=="0x1043", ATTRS{subsystem_device}=="0x83ce", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Sony Vaio VGN-SR21M
+ATTRS{subsystem_vendor}=="0x104d", ATTRS{subsystem_device}=="0x9033", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Sony Vaio VPC-W115XG
+ATTRS{subsystem_vendor}=="0x104d", ATTRS{subsystem_device}=="0x9064", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Fujitsu Lifebook S7110
+ATTRS{subsystem_vendor}=="0x10cf", ATTRS{subsystem_device}=="0x1397", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Fujitsu Lifebook A530
+ATTRS{subsystem_vendor}=="0x10cf", ATTRS{subsystem_device}=="0x1531", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Toshiba A200
+ATTRS{subsystem_vendor}=="0x1179", ATTRS{subsystem_device}=="0xff00", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# MSI X360
+ATTRS{subsystem_vendor}=="0x1462", ATTRS{subsystem_device}=="0x1053", ENV{PULSE_PROFILE_SET}="force-speaker-and-int-mic.conf"
+# Lenovo 3000 Y410
+ATTRS{subsystem_vendor}=="0x17aa", ATTRS{subsystem_device}=="0x384e", ENV{PULSE_PROFILE_SET}="force-speaker.conf"
+
+GOTO="pulseaudio_end"
+
+LABEL="pulseaudio_check_usb"
+ATTRS{idVendor}=="17cc", ATTRS{idProduct}=="1978", ENV{PULSE_PROFILE_SET}="native-instruments-audio8dj.conf"
+ATTRS{idVendor}=="17cc", ATTRS{idProduct}=="0839", ENV{PULSE_PROFILE_SET}="native-instruments-audio4dj.conf"
+ATTRS{idVendor}=="17cc", ATTRS{idProduct}=="baff", ENV{PULSE_PROFILE_SET}="native-instruments-traktorkontrol-s4.conf"
+ATTRS{idVendor}=="17cc", ATTRS{idProduct}=="4711", ENV{PULSE_PROFILE_SET}="native-instruments-korecontroller.conf"
+
+# This ID 17cc:041c is verified for the older Audio 2 DJ model (pre-2014 ish).
+ATTRS{idVendor}=="17cc", ATTRS{idProduct}=="041c", ENV{PULSE_PROFILE_SET}="native-instruments-traktor-audio2.conf"
+ATTRS{idVendor}=="17cc", ATTRS{idProduct}=="041d", ENV{PULSE_PROFILE_SET}="native-instruments-traktor-audio2.conf"
+
+# There appear to be two IDs in use for Traktor Audio 6 (or maybe 17cc:1011
+# is just incorrect - 17cc:1010 has been verified to be correct at least
+# for some hardware).
+ATTRS{idVendor}=="17cc", ATTRS{idProduct}=="1010", ENV{PULSE_PROFILE_SET}="native-instruments-traktor-audio6.conf"
+ATTRS{idVendor}=="17cc", ATTRS{idProduct}=="1011", ENV{PULSE_PROFILE_SET}="native-instruments-traktor-audio6.conf"
+
+ATTRS{idVendor}=="17cc", ATTRS{idProduct}=="1021", ENV{PULSE_PROFILE_SET}="native-instruments-traktor-audio10.conf"
+ATTRS{idVendor}=="0763", ATTRS{idProduct}=="2012", ENV{PULSE_PROFILE_SET}="maudio-fasttrack-pro.conf"
+ATTRS{idVendor}=="045e", ATTRS{idProduct}=="02bb", ENV{PULSE_PROFILE_SET}="kinect-audio.conf"
+ATTRS{idVendor}=="041e", ATTRS{idProduct}=="322c", ENV{PULSE_PROFILE_SET}="sb-omni-surround-5.1.conf"
+ATTRS{idVendor}=="0bda", ATTRS{idProduct}=="4014", ENV{PULSE_PROFILE_SET}="dell-dock-tb16-usb-audio.conf"
+
+# ID 1038:12ad is for the 2018 refresh of the Arctis 7.
+# ID 1038:1294 is for Arctis Pro Wireless (which works with the Arctis 7 configuration).
+ATTRS{idVendor}=="1038", ATTRS{idProduct}=="1260", ENV{PULSE_PROFILE_SET}="usb-gaming-headset.conf"
+ATTRS{idVendor}=="1038", ATTRS{idProduct}=="12ad", ENV{PULSE_PROFILE_SET}="usb-gaming-headset.conf"
+ATTRS{idVendor}=="1038", ATTRS{idProduct}=="1294", ENV{PULSE_PROFILE_SET}="usb-gaming-headset.conf"
+ATTRS{idVendor}=="1038", ATTRS{idProduct}=="1730", ENV{PULSE_PROFILE_SET}="usb-gaming-headset.conf"
+# Lucidsound LS31
+ATTRS{idVendor}=="2f12", ATTRS{idProduct}=="0109", ENV{PULSE_PROFILE_SET}="usb-gaming-headset.conf"
+# ID 9886:002c is for the Astro A50 Gen4
+ATTRS{idVendor}=="9886", ATTRS{idProduct}=="002c", ENV{PULSE_PROFILE_SET}="usb-gaming-headset.conf"
+# ID 1532:0520 is for the Razer Kraken Tournament Edition
+ATTRS{idVendor}=="1532", ATTRS{idProduct}=="0520", ENV{PULSE_PROFILE_SET}="usb-gaming-headset.conf"
+
+
+# ID 1038:1250 is for the Arctis 5
+# ID 1037:12aa is for the Arctis 5 2019
+# ID 1038:1252 is for the Arctis Pro 2019 edition
+ATTRS{idVendor}=="1038", ATTRS{idProduct}=="1250", ENV{PULSE_PROFILE_SET}="steelseries-arctis-common-usb-audio.conf"
+ATTRS{idVendor}=="1038", ATTRS{idProduct}=="12aa", ENV{PULSE_PROFILE_SET}="steelseries-arctis-common-usb-audio.conf"
+ATTRS{idVendor}=="1038", ATTRS{idProduct}=="1252", ENV{PULSE_PROFILE_SET}="steelseries-arctis-common-usb-audio.conf"
+
+ATTRS{idVendor}=="147a", ATTRS{idProduct}=="e055", ENV{PULSE_PROFILE_SET}="cmedia-high-speed-true-hdaudio.conf"
+
+# HyperX Cloud Orbit S has three modes. Each mode has a separate product ID.
+# ID_SERIAL for this device is the device name + mode repeated three times.
+# ID_SERIAL is used for the ID_ID property, and the ID_ID property is used in
+# the card name in PulseAudio. The resulting card name is too long for the name
+# length limit, so we set a more sensible ID_ID here (the same as the default
+# ID_ID, but without repetition in the serial part).
+ATTRS{idVendor}=="0951", ATTRS{idProduct}=="16ff", ENV{ID_ID}="usb-HyperX_Cloud_Orbit_S_2Ch-$env{ID_USB_INTERFACE_NUM}"
+ATTRS{idVendor}=="0951", ATTRS{idProduct}=="1702", ENV{ID_ID}="usb-HyperX_Cloud_Orbit_S_Hi-Res_2Ch-$env{ID_USB_INTERFACE_NUM}"
+ATTRS{idVendor}=="0951", ATTRS{idProduct}=="1703", ENV{ID_ID}="usb-HyperX_Cloud_Orbit_S_3D_8Ch-$env{ID_USB_INTERFACE_NUM}"
+
+GOTO="pulseaudio_end"
+
+LABEL="pulseaudio_check_pci"
+
+# Creative SoundBlaster Audigy-based cards
+# EMU10k2/CA0100/CA0102/CA10200
+ATTRS{vendor}=="0x1102", ATTRS{device}=="0x0004", ENV{PULSE_PROFILE_SET}="audigy.conf"
+# CA0108/CA10300
+ATTRS{vendor}=="0x1102", ATTRS{device}=="0x0008", ENV{PULSE_PROFILE_SET}="audigy.conf"
+
+GOTO="pulseaudio_end"
+
+LABEL="pulseaudio_firewire_quirk"
+
+# Focusrite Saffire Pro 10/26 i/o has a quirk to disappear from IEEE 1394 bus when losing connections.
+# https://bugzilla.kernel.org/show_bug.cgi?id=199365
+ENV{ID_VENDOR_ID}=="0x00130e", ENV{ID_MODEL_ID}=="0x000003", ENV{PULSE_IGNORE}="1"
+# Both of Saffire Pro 10 i/o and Liquid Saffire 56 have the same ID_MODEL_ID
+# (0x000006), but Liquid Saffire 56 doesn't suffer from the problem, so we
+# can't use ID_MODEL_ID to identify the problematic card. ID_MODEL works
+# better here.
+ENV{ID_VENDOR_ID}=="0x00130e", ENV{ID_MODEL}=="Pro10IO" ENV{PULSE_IGNORE}="1"
+
+LABEL="pulseaudio_end"
diff --git a/src/modules/alsa/alsa-mixer.c b/src/modules/alsa/alsa-mixer.c
new file mode 100644
index 0000000..e494a12
--- /dev/null
+++ b/src/modules/alsa/alsa-mixer.c
@@ -0,0 +1,5386 @@
+/***
+ This file is part of PulseAudio.
+
+ Copyright 2004-2009 Lennart Poettering
+ Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
+
+ PulseAudio is free software; you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License,
+ or (at your option) any later version.
+
+ PulseAudio is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+***/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <sys/types.h>
+#include <alsa/asoundlib.h>
+#include <math.h>
+
+#ifdef HAVE_VALGRIND_MEMCHECK_H
+#include <valgrind/memcheck.h>
+#endif
+
+#include <pulse/mainloop-api.h>
+#include <pulse/sample.h>
+#include <pulse/timeval.h>
+#include <pulse/util.h>
+#include <pulse/volume.h>
+#include <pulse/xmalloc.h>
+#include <pulse/utf8.h>
+
+#include <pulsecore/i18n.h>
+#include <pulsecore/log.h>
+#include <pulsecore/macro.h>
+#include <pulsecore/core-util.h>
+#include <pulsecore/conf-parser.h>
+#include <pulsecore/strbuf.h>
+
+#include "alsa-mixer.h"
+#include "alsa-util.h"
+
+#ifdef HAVE_VALGRIND_MEMCHECK_H
+/* These macros are workarounds for a bug in valgrind, which is not handling the
+ * ALSA TLV syscalls correctly. See
+ * http://valgrind.10908.n7.nabble.com/Missing-ioctl-for-SNDRV-CTL-IOCTL-TLV-READ-td42711.html */
+
+static inline int vgfix_get_capture_dB(snd_mixer_elem_t *a, snd_mixer_selem_channel_id_t b, long *c) {
+ int r = snd_mixer_selem_get_capture_dB(a, b, c);
+ VALGRIND_MAKE_MEM_DEFINED(c, sizeof(*c));
+ return r;
+}
+
+static inline int vgfix_get_playback_dB(snd_mixer_elem_t *a, snd_mixer_selem_channel_id_t b, long *c) {
+ int r = snd_mixer_selem_get_playback_dB(a, b, c);
+ VALGRIND_MAKE_MEM_DEFINED(c, sizeof(*c));
+ return r;
+}
+
+static inline int vgfix_ask_capture_vol_dB(snd_mixer_elem_t *a, long b, long *c) {
+ int r = snd_mixer_selem_ask_capture_vol_dB(a, b, c);
+ VALGRIND_MAKE_MEM_DEFINED(c, sizeof(*c));
+ return r;
+}
+
+static inline int vgfix_ask_playback_vol_dB(snd_mixer_elem_t *a, long b, long *c) {
+ int r = snd_mixer_selem_ask_playback_vol_dB(a, b, c);
+ VALGRIND_MAKE_MEM_DEFINED(c, sizeof(*c));
+ return r;
+}
+
+static inline int vgfix_get_capture_dB_range(snd_mixer_elem_t *a, long *b, long *c) {
+ int r = snd_mixer_selem_get_capture_dB_range(a, b, c);
+ VALGRIND_MAKE_MEM_DEFINED(b, sizeof(*b));
+ VALGRIND_MAKE_MEM_DEFINED(c, sizeof(*c));
+ return r;
+}
+
+static inline int vgfix_get_playback_dB_range(snd_mixer_elem_t *a, long *b, long *c) {
+ int r = snd_mixer_selem_get_playback_dB_range(a, b, c);
+ VALGRIND_MAKE_MEM_DEFINED(b, sizeof(*b));
+ VALGRIND_MAKE_MEM_DEFINED(c, sizeof(*c));
+ return r;
+}
+
+#define snd_mixer_selem_get_capture_dB(a, b, c) vgfix_get_capture_dB(a, b, c)
+#define snd_mixer_selem_get_playback_dB(a, b, c) vgfix_get_playback_dB(a, b, c)
+#define snd_mixer_selem_ask_capture_vol_dB(a, b, c) vgfix_ask_capture_vol_dB(a, b, c)
+#define snd_mixer_selem_ask_playback_vol_dB(a, b, c) vgfix_ask_playback_vol_dB(a, b, c)
+#define snd_mixer_selem_get_capture_dB_range(a, b, c) vgfix_get_capture_dB_range(a, b, c)
+#define snd_mixer_selem_get_playback_dB_range(a, b, c) vgfix_get_playback_dB_range(a, b, c)
+
+#endif
+
+static int setting_select(pa_alsa_setting *s, snd_mixer_t *m);
+
+struct description_map {
+ const char *key;
+ const char *description;
+};
+
+struct description2_map {
+ const char *key;
+ const char *description;
+ pa_device_port_type_t type;
+};
+
+char *pa_alsa_mixer_id_to_string(char *dst, size_t dst_len, pa_alsa_mixer_id *id) {
+ if (id->index > 0) {
+ snprintf(dst, dst_len, "'%s',%d", id->name, id->index);
+ } else {
+ snprintf(dst, dst_len, "'%s'", id->name);
+ }
+ return dst;
+}
+
+static int alsa_id_decode(const char *src, char *name, int *index) {
+ char *idx, c;
+ int i;
+
+ *index = 0;
+ c = src[0];
+ /* Strip quotes in entries such as 'Speaker',1 or "Speaker",1 */
+ if (c == '\'' || c == '"') {
+ strcpy(name, src + 1);
+ for (i = 0; name[i] != '\0' && name[i] != c; i++);
+ idx = NULL;
+ if (name[i]) {
+ name[i] = '\0';
+ idx = strchr(name + i + 1, ',');
+ }
+ } else {
+ strcpy(name, src);
+ idx = strchr(name, ',');
+ }
+ if (idx == NULL)
+ return 0;
+ *idx = '\0';
+ idx++;
+ if (*idx < '0' || *idx > '9') {
+ pa_log("Element %s: index value is invalid", src);
+ return 1;
+ }
+ *index = atoi(idx);
+ return 0;
+}
+
+pa_alsa_jack *pa_alsa_jack_new(pa_alsa_path *path, const char *mixer_device_name, const char *name, int index) {
+ pa_alsa_jack *jack;
+
+ pa_assert(name);
+
+ jack = pa_xnew0(pa_alsa_jack, 1);
+ jack->path = path;
+ jack->mixer_device_name = pa_xstrdup(mixer_device_name);
+ jack->name = pa_xstrdup(name);
+ jack->alsa_id.name = pa_sprintf_malloc("%s Jack", name);
+ jack->alsa_id.index = index;
+ jack->state_unplugged = PA_AVAILABLE_NO;
+ jack->state_plugged = PA_AVAILABLE_YES;
+ jack->ucm_devices = pa_dynarray_new(NULL);
+ jack->ucm_hw_mute_devices = pa_dynarray_new(NULL);
+
+ return jack;
+}
+
+void pa_alsa_jack_free(pa_alsa_jack *jack) {
+ pa_assert(jack);
+
+ pa_dynarray_free(jack->ucm_hw_mute_devices);
+ pa_dynarray_free(jack->ucm_devices);
+
+ pa_xfree(jack->alsa_id.name);
+ pa_xfree(jack->name);
+ pa_xfree(jack->mixer_device_name);
+ pa_xfree(jack);
+}
+
+void pa_alsa_jack_set_has_control(pa_alsa_jack *jack, bool has_control) {
+ pa_alsa_ucm_device *device;
+ unsigned idx;
+
+ pa_assert(jack);
+
+ if (has_control == jack->has_control)
+ return;
+
+ jack->has_control = has_control;
+
+ PA_DYNARRAY_FOREACH(device, jack->ucm_hw_mute_devices, idx)
+ pa_alsa_ucm_device_update_available(device);
+
+ PA_DYNARRAY_FOREACH(device, jack->ucm_devices, idx)
+ pa_alsa_ucm_device_update_available(device);
+}
+
+void pa_alsa_jack_set_plugged_in(pa_alsa_jack *jack, bool plugged_in) {
+ pa_alsa_ucm_device *device;
+ unsigned idx;
+
+ pa_assert(jack);
+
+ if (plugged_in == jack->plugged_in)
+ return;
+
+ jack->plugged_in = plugged_in;
+
+ /* XXX: If this is a headphone jack that mutes speakers when plugged in,
+ * and the headphones get unplugged, then the headphone device must be set
+ * to unavailable and the speaker device must be set to unknown. So far so
+ * good. But there's an ugly detail: we must first set the availability of
+ * the speakers and then the headphones. We shouldn't need to care about
+ * the order, but we have to, because module-switch-on-port-available gets
+ * separate events for the two devices, and the intermediate state between
+ * the two events is such that the second event doesn't trigger the desired
+ * port switch, if the event order is "wrong".
+ *
+ * These are the transitions when the event order is "right":
+ *
+ * speakers: 1) unavailable -> 2) unknown -> 3) unknown
+ * headphones: 1) available -> 2) available -> 3) unavailable
+ *
+ * In the 2 -> 3 transition, headphones become unavailable, and
+ * module-switch-on-port-available sees that speakers can be used, so the
+ * port gets changed as it should.
+ *
+ * These are the transitions when the event order is "wrong":
+ *
+ * speakers: 1) unavailable -> 2) unavailable -> 3) unknown
+ * headphones: 1) available -> 2) unavailable -> 3) unavailable
+ *
+ * In the 1 -> 2 transition, headphones become unavailable, and there are
+ * no available ports to use, so no port change happens. In the 2 -> 3
+ * transition, speaker availability becomes unknown, but that's not
+ * a strong enough signal for module-switch-on-port-available, so it still
+ * doesn't do the port switch.
+ *
+ * We should somehow merge the two events so that
+ * module-switch-on-port-available would handle both transitions in one go.
+ * If module-switch-on-port-available used a defer event to delay
+ * the port availability processing, that would probably do the trick. */
+
+ PA_DYNARRAY_FOREACH(device, jack->ucm_hw_mute_devices, idx)
+ pa_alsa_ucm_device_update_available(device);
+
+ PA_DYNARRAY_FOREACH(device, jack->ucm_devices, idx)
+ pa_alsa_ucm_device_update_available(device);
+}
+
+void pa_alsa_jack_add_ucm_device(pa_alsa_jack *jack, pa_alsa_ucm_device *device) {
+ pa_alsa_ucm_device *idevice;
+ unsigned idx, prio, iprio;
+
+ pa_assert(jack);
+ pa_assert(device);
+
+ /* store the ucm device with the sequence of priority from low to high. this
+ * could guarantee when the jack state is changed, the device with highest
+ * priority will send to the module-switch-on-port-available last */
+ prio = device->playback_priority ? device->playback_priority : device->capture_priority;
+
+ PA_DYNARRAY_FOREACH(idevice, jack->ucm_devices, idx) {
+ iprio = idevice->playback_priority ? idevice->playback_priority : idevice->capture_priority;
+ if (iprio > prio)
+ break;
+ }
+ pa_dynarray_insert_by_index(jack->ucm_devices, device, idx);
+}
+
+void pa_alsa_jack_add_ucm_hw_mute_device(pa_alsa_jack *jack, pa_alsa_ucm_device *device) {
+ pa_assert(jack);
+ pa_assert(device);
+
+ pa_dynarray_append(jack->ucm_hw_mute_devices, device);
+}
+
+static const char *lookup_description(const char *key, const struct description_map dm[], unsigned n) {
+ unsigned i;
+
+ if (!key)
+ return NULL;
+
+ for (i = 0; i < n; i++)
+ if (pa_streq(dm[i].key, key))
+ return _(dm[i].description);
+
+ return NULL;
+}
+
+static const struct description2_map *lookup_description2(const char *key, const struct description2_map dm[], unsigned n) {
+ unsigned i;
+
+ if (!key)
+ return NULL;
+
+ for (i = 0; i < n; i++)
+ if (pa_streq(dm[i].key, key))
+ return &dm[i];
+
+ return NULL;
+}
+
+struct pa_alsa_fdlist {
+ unsigned num_fds;
+ struct pollfd *fds;
+ /* This is a temporary buffer used to avoid lots of mallocs */
+ struct pollfd *work_fds;
+
+ snd_mixer_t *mixer;
+ snd_hctl_t *hctl;
+
+ pa_mainloop_api *m;
+ pa_defer_event *defer;
+ pa_io_event **ios;
+
+ bool polled;
+
+ void (*cb)(void *userdata);
+ void *userdata;
+};
+
+static void io_cb(pa_mainloop_api *a, pa_io_event *e, int fd, pa_io_event_flags_t events, void *userdata) {
+
+ struct pa_alsa_fdlist *fdl = userdata;
+ int err;
+ unsigned i;
+ unsigned short revents;
+
+ pa_assert(a);
+ pa_assert(fdl);
+ pa_assert(fdl->mixer || fdl->hctl);
+ pa_assert(fdl->fds);
+ pa_assert(fdl->work_fds);
+
+ if (fdl->polled)
+ return;
+
+ fdl->polled = true;
+
+ memcpy(fdl->work_fds, fdl->fds, sizeof(struct pollfd) * fdl->num_fds);
+
+ for (i = 0; i < fdl->num_fds; i++) {
+ if (e == fdl->ios[i]) {
+ if (events & PA_IO_EVENT_INPUT)
+ fdl->work_fds[i].revents |= POLLIN;
+ if (events & PA_IO_EVENT_OUTPUT)
+ fdl->work_fds[i].revents |= POLLOUT;
+ if (events & PA_IO_EVENT_ERROR)
+ fdl->work_fds[i].revents |= POLLERR;
+ if (events & PA_IO_EVENT_HANGUP)
+ fdl->work_fds[i].revents |= POLLHUP;
+ break;
+ }
+ }
+
+ pa_assert(i != fdl->num_fds);
+
+ if (fdl->hctl)
+ err = snd_hctl_poll_descriptors_revents(fdl->hctl, fdl->work_fds, fdl->num_fds, &revents);
+ else
+ err = snd_mixer_poll_descriptors_revents(fdl->mixer, fdl->work_fds, fdl->num_fds, &revents);
+
+ if (err < 0) {
+ pa_log_error("Unable to get poll revent: %s", pa_alsa_strerror(err));
+ return;
+ }
+
+ a->defer_enable(fdl->defer, 1);
+
+ if (revents) {
+ if (fdl->hctl)
+ snd_hctl_handle_events(fdl->hctl);
+ else
+ snd_mixer_handle_events(fdl->mixer);
+ }
+}
+
+static void defer_cb(pa_mainloop_api *a, pa_defer_event *e, void *userdata) {
+ struct pa_alsa_fdlist *fdl = userdata;
+ unsigned num_fds, i;
+ int err, n;
+ struct pollfd *temp;
+
+ pa_assert(a);
+ pa_assert(fdl);
+ pa_assert(fdl->mixer || fdl->hctl);
+
+ a->defer_enable(fdl->defer, 0);
+
+ if (fdl->hctl)
+ n = snd_hctl_poll_descriptors_count(fdl->hctl);
+ else
+ n = snd_mixer_poll_descriptors_count(fdl->mixer);
+
+ if (n < 0) {
+ pa_log("snd_mixer_poll_descriptors_count() failed: %s", pa_alsa_strerror(n));
+ return;
+ }
+ else if (n == 0) {
+ pa_log_warn("Mixer has no poll descriptors. Please control mixer from PulseAudio only.");
+ return;
+ }
+ num_fds = (unsigned) n;
+
+ if (num_fds != fdl->num_fds) {
+ if (fdl->fds)
+ pa_xfree(fdl->fds);
+ if (fdl->work_fds)
+ pa_xfree(fdl->work_fds);
+ fdl->fds = pa_xnew0(struct pollfd, num_fds);
+ fdl->work_fds = pa_xnew(struct pollfd, num_fds);
+ }
+
+ memset(fdl->work_fds, 0, sizeof(struct pollfd) * num_fds);
+
+ if (fdl->hctl)
+ err = snd_hctl_poll_descriptors(fdl->hctl, fdl->work_fds, num_fds);
+ else
+ err = snd_mixer_poll_descriptors(fdl->mixer, fdl->work_fds, num_fds);
+
+ if (err < 0) {
+ pa_log_error("Unable to get poll descriptors: %s", pa_alsa_strerror(err));
+ return;
+ }
+
+ fdl->polled = false;
+
+ if (memcmp(fdl->fds, fdl->work_fds, sizeof(struct pollfd) * num_fds) == 0)
+ return;
+
+ if (fdl->ios) {
+ for (i = 0; i < fdl->num_fds; i++)
+ a->io_free(fdl->ios[i]);
+
+ if (num_fds != fdl->num_fds) {
+ pa_xfree(fdl->ios);
+ fdl->ios = NULL;
+ }
+ }
+
+ if (!fdl->ios)
+ fdl->ios = pa_xnew(pa_io_event*, num_fds);
+
+ /* Swap pointers */
+ temp = fdl->work_fds;
+ fdl->work_fds = fdl->fds;
+ fdl->fds = temp;
+
+ fdl->num_fds = num_fds;
+
+ for (i = 0;i < num_fds;i++)
+ fdl->ios[i] = a->io_new(a, fdl->fds[i].fd,
+ ((fdl->fds[i].events & POLLIN) ? PA_IO_EVENT_INPUT : 0) |
+ ((fdl->fds[i].events & POLLOUT) ? PA_IO_EVENT_OUTPUT : 0),
+ io_cb, fdl);
+}
+
+struct pa_alsa_fdlist *pa_alsa_fdlist_new(void) {
+ struct pa_alsa_fdlist *fdl;
+
+ fdl = pa_xnew0(struct pa_alsa_fdlist, 1);
+
+ return fdl;
+}
+
+void pa_alsa_fdlist_free(struct pa_alsa_fdlist *fdl) {
+ pa_assert(fdl);
+
+ if (fdl->defer) {
+ pa_assert(fdl->m);
+ fdl->m->defer_free(fdl->defer);
+ }
+
+ if (fdl->ios) {
+ unsigned i;
+ pa_assert(fdl->m);
+ for (i = 0; i < fdl->num_fds; i++)
+ fdl->m->io_free(fdl->ios[i]);
+ pa_xfree(fdl->ios);
+ }
+
+ if (fdl->fds)
+ pa_xfree(fdl->fds);
+ if (fdl->work_fds)
+ pa_xfree(fdl->work_fds);
+
+ pa_xfree(fdl);
+}
+
+/* We can listen to either a snd_hctl_t or a snd_mixer_t, but not both */
+int pa_alsa_fdlist_set_handle(struct pa_alsa_fdlist *fdl, snd_mixer_t *mixer_handle, snd_hctl_t *hctl_handle, pa_mainloop_api *m) {
+ pa_assert(fdl);
+ pa_assert(hctl_handle || mixer_handle);
+ pa_assert(!(hctl_handle && mixer_handle));
+ pa_assert(m);
+ pa_assert(!fdl->m);
+
+ fdl->hctl = hctl_handle;
+ fdl->mixer = mixer_handle;
+ fdl->m = m;
+ fdl->defer = m->defer_new(m, defer_cb, fdl);
+
+ return 0;
+}
+
+struct pa_alsa_mixer_pdata {
+ pa_rtpoll *rtpoll;
+ pa_rtpoll_item *poll_item;
+ snd_mixer_t *mixer;
+};
+
+struct pa_alsa_mixer_pdata *pa_alsa_mixer_pdata_new(void) {
+ struct pa_alsa_mixer_pdata *pd;
+
+ pd = pa_xnew0(struct pa_alsa_mixer_pdata, 1);
+
+ return pd;
+}
+
+void pa_alsa_mixer_pdata_free(struct pa_alsa_mixer_pdata *pd) {
+ pa_assert(pd);
+
+ if (pd->poll_item) {
+ pa_rtpoll_item_free(pd->poll_item);
+ }
+
+ pa_xfree(pd);
+}
+
+static int rtpoll_work_cb(pa_rtpoll_item *i) {
+ struct pa_alsa_mixer_pdata *pd;
+ struct pollfd *p;
+ unsigned n_fds;
+ unsigned short revents = 0;
+ int err, ret = 0;
+
+ pd = pa_rtpoll_item_get_work_userdata(i);
+ pa_assert_fp(pd);
+ pa_assert_fp(i == pd->poll_item);
+
+ p = pa_rtpoll_item_get_pollfd(i, &n_fds);
+
+ if ((err = snd_mixer_poll_descriptors_revents(pd->mixer, p, n_fds, &revents)) < 0) {
+ pa_log_error("Unable to get poll revent: %s", pa_alsa_strerror(err));
+ ret = -1;
+ goto fail;
+ }
+
+ if (revents) {
+ if (revents & (POLLNVAL | POLLERR)) {
+ pa_log_debug("Device disconnected, stopping poll on mixer");
+ goto fail;
+ } else if (revents & POLLERR) {
+ /* This shouldn't happen. */
+ pa_log_error("Got a POLLERR (revents = %04x), stopping poll on mixer", revents);
+ goto fail;
+ }
+
+ err = snd_mixer_handle_events(pd->mixer);
+
+ if (PA_LIKELY(err >= 0)) {
+ pa_rtpoll_item_free(i);
+ pa_alsa_set_mixer_rtpoll(pd, pd->mixer, pd->rtpoll);
+ } else {
+ pa_log_error("Error handling mixer event: %s", pa_alsa_strerror(err));
+ ret = -1;
+ goto fail;
+ }
+ }
+
+ return ret;
+
+fail:
+ pa_rtpoll_item_free(i);
+
+ pd->poll_item = NULL;
+ pd->rtpoll = NULL;
+ pd->mixer = NULL;
+
+ return ret;
+}
+
+int pa_alsa_set_mixer_rtpoll(struct pa_alsa_mixer_pdata *pd, snd_mixer_t *mixer, pa_rtpoll *rtp) {
+ pa_rtpoll_item *i;
+ struct pollfd *p;
+ int err, n;
+
+ pa_assert(pd);
+ pa_assert(mixer);
+ pa_assert(rtp);
+
+ if ((n = snd_mixer_poll_descriptors_count(mixer)) < 0) {
+ pa_log("snd_mixer_poll_descriptors_count() failed: %s", pa_alsa_strerror(n));
+ return -1;
+ }
+ else if (n == 0) {
+ pa_log_warn("Mixer has no poll descriptors. Please control mixer from PulseAudio only.");
+ return 0;
+ }
+
+ i = pa_rtpoll_item_new(rtp, PA_RTPOLL_LATE, (unsigned) n);
+
+ p = pa_rtpoll_item_get_pollfd(i, NULL);
+
+ memset(p, 0, sizeof(struct pollfd) * n);
+
+ if ((err = snd_mixer_poll_descriptors(mixer, p, (unsigned) n)) < 0) {
+ pa_log_error("Unable to get poll descriptors: %s", pa_alsa_strerror(err));
+ pa_rtpoll_item_free(i);
+ return -1;
+ }
+
+ pd->rtpoll = rtp;
+ pd->poll_item = i;
+ pd->mixer = mixer;
+
+ pa_rtpoll_item_set_work_callback(i, rtpoll_work_cb, pd);
+
+ return 0;
+}
+
+static const snd_mixer_selem_channel_id_t alsa_channel_ids[PA_CHANNEL_POSITION_MAX] = {
+ [PA_CHANNEL_POSITION_MONO] = SND_MIXER_SCHN_MONO, /* The ALSA name is just an alias! */
+
+ [PA_CHANNEL_POSITION_FRONT_CENTER] = SND_MIXER_SCHN_FRONT_CENTER,
+ [PA_CHANNEL_POSITION_FRONT_LEFT] = SND_MIXER_SCHN_FRONT_LEFT,
+ [PA_CHANNEL_POSITION_FRONT_RIGHT] = SND_MIXER_SCHN_FRONT_RIGHT,
+
+ [PA_CHANNEL_POSITION_REAR_CENTER] = SND_MIXER_SCHN_REAR_CENTER,
+ [PA_CHANNEL_POSITION_REAR_LEFT] = SND_MIXER_SCHN_REAR_LEFT,
+ [PA_CHANNEL_POSITION_REAR_RIGHT] = SND_MIXER_SCHN_REAR_RIGHT,
+
+ [PA_CHANNEL_POSITION_LFE] = SND_MIXER_SCHN_WOOFER,
+
+ [PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER] = SND_MIXER_SCHN_UNKNOWN,
+
+ [PA_CHANNEL_POSITION_SIDE_LEFT] = SND_MIXER_SCHN_SIDE_LEFT,
+ [PA_CHANNEL_POSITION_SIDE_RIGHT] = SND_MIXER_SCHN_SIDE_RIGHT,
+
+ [PA_CHANNEL_POSITION_AUX0] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX1] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX2] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX3] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX4] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX5] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX6] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX7] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX8] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX9] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX10] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX11] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX12] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX13] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX14] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX15] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX16] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX17] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX18] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX19] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX20] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX21] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX22] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX23] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX24] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX25] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX26] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX27] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX28] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX29] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX30] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_AUX31] = SND_MIXER_SCHN_UNKNOWN,
+
+ [PA_CHANNEL_POSITION_TOP_CENTER] = SND_MIXER_SCHN_UNKNOWN,
+
+ [PA_CHANNEL_POSITION_TOP_FRONT_CENTER] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_TOP_FRONT_LEFT] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_TOP_FRONT_RIGHT] = SND_MIXER_SCHN_UNKNOWN,
+
+ [PA_CHANNEL_POSITION_TOP_REAR_CENTER] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_TOP_REAR_LEFT] = SND_MIXER_SCHN_UNKNOWN,
+ [PA_CHANNEL_POSITION_TOP_REAR_RIGHT] = SND_MIXER_SCHN_UNKNOWN
+};
+
+static snd_mixer_selem_channel_id_t alsa_channel_positions[POSITION_MASK_CHANNELS] = {
+ SND_MIXER_SCHN_FRONT_LEFT,
+ SND_MIXER_SCHN_FRONT_RIGHT,
+ SND_MIXER_SCHN_REAR_LEFT,
+ SND_MIXER_SCHN_REAR_RIGHT,
+ SND_MIXER_SCHN_FRONT_CENTER,
+ SND_MIXER_SCHN_WOOFER,
+ SND_MIXER_SCHN_SIDE_LEFT,
+ SND_MIXER_SCHN_SIDE_RIGHT,
+#if POSITION_MASK_CHANNELS > 8
+#error "Extend alsa_channel_positions[] array (9+)"
+#endif
+};
+
+static void setting_free(pa_alsa_setting *s) {
+ pa_assert(s);
+
+ if (s->options)
+ pa_idxset_free(s->options, NULL);
+
+ pa_xfree(s->name);
+ pa_xfree(s->description);
+ pa_xfree(s);
+}
+
+static void option_free(pa_alsa_option *o) {
+ pa_assert(o);
+
+ pa_xfree(o->alsa_name);
+ pa_xfree(o->name);
+ pa_xfree(o->description);
+ pa_xfree(o);
+}
+
+static void decibel_fix_free(pa_alsa_decibel_fix *db_fix) {
+ pa_assert(db_fix);
+
+ pa_xfree(db_fix->name);
+ pa_xfree(db_fix->db_values);
+
+ pa_xfree(db_fix->key);
+ pa_xfree(db_fix);
+}
+
+static void element_free(pa_alsa_element *e) {
+ pa_alsa_option *o;
+ pa_assert(e);
+
+ while ((o = e->options)) {
+ PA_LLIST_REMOVE(pa_alsa_option, e->options, o);
+ option_free(o);
+ }
+
+ if (e->db_fix)
+ decibel_fix_free(e->db_fix);
+
+ pa_xfree(e->alsa_id.name);
+ pa_xfree(e);
+}
+
+void pa_alsa_path_free(pa_alsa_path *p) {
+ pa_alsa_jack *j;
+ pa_alsa_element *e;
+ pa_alsa_setting *s;
+
+ pa_assert(p);
+
+ while ((j = p->jacks)) {
+ PA_LLIST_REMOVE(pa_alsa_jack, p->jacks, j);
+ pa_alsa_jack_free(j);
+ }
+
+ while ((e = p->elements)) {
+ PA_LLIST_REMOVE(pa_alsa_element, p->elements, e);
+ element_free(e);
+ }
+
+ while ((s = p->settings)) {
+ PA_LLIST_REMOVE(pa_alsa_setting, p->settings, s);
+ setting_free(s);
+ }
+
+ pa_proplist_free(p->proplist);
+ pa_xfree(p->availability_group);
+ pa_xfree(p->name);
+ pa_xfree(p->description);
+ pa_xfree(p->description_key);
+ pa_xfree(p);
+}
+
+void pa_alsa_path_set_free(pa_alsa_path_set *ps) {
+ pa_assert(ps);
+
+ if (ps->paths)
+ pa_hashmap_free(ps->paths);
+
+ pa_xfree(ps);
+}
+
+int pa_alsa_path_set_is_empty(pa_alsa_path_set *ps) {
+ if (ps && !pa_hashmap_isempty(ps->paths))
+ return 0;
+ return 1;
+}
+
+static long to_alsa_dB(pa_volume_t v) {
+ return lround(pa_sw_volume_to_dB(v) * 100.0);
+}
+
+static pa_volume_t from_alsa_dB(long v) {
+ return pa_sw_volume_from_dB((double) v / 100.0);
+}
+
+static long to_alsa_volume(pa_volume_t v, long min, long max) {
+ long w;
+
+ w = (long) round(((double) v * (double) (max - min)) / PA_VOLUME_NORM) + min;
+ return PA_CLAMP_UNLIKELY(w, min, max);
+}
+
+static pa_volume_t from_alsa_volume(long v, long min, long max) {
+ return (pa_volume_t) round(((double) (v - min) * PA_VOLUME_NORM) / (double) (max - min));
+}
+
+#define SELEM_INIT(sid, aid) \
+ do { \
+ snd_mixer_selem_id_alloca(&(sid)); \
+ snd_mixer_selem_id_set_name((sid), (aid)->name); \
+ snd_mixer_selem_id_set_index((sid), (aid)->index); \
+ } while(false)
+
+static int element_get_volume(pa_alsa_element *e, snd_mixer_t *m, const pa_channel_map *cm, pa_cvolume *v) {
+ snd_mixer_selem_id_t *sid;
+ snd_mixer_elem_t *me;
+ snd_mixer_selem_channel_id_t c;
+ pa_channel_position_mask_t mask = 0;
+ char buf[64];
+ unsigned k;
+
+ pa_assert(m);
+ pa_assert(e);
+ pa_assert(cm);
+ pa_assert(v);
+
+ SELEM_INIT(sid, &e->alsa_id);
+ if (!(me = snd_mixer_find_selem(m, sid))) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("Element %s seems to have disappeared.", buf);
+ return -1;
+ }
+
+ pa_cvolume_mute(v, cm->channels);
+
+ /* We take the highest volume of all channels that match */
+
+ for (c = 0; c <= SND_MIXER_SCHN_LAST; c++) {
+ int r;
+ pa_volume_t f;
+
+ if (e->has_dB) {
+ long value = 0;
+
+ if (e->direction == PA_ALSA_DIRECTION_OUTPUT) {
+ if (snd_mixer_selem_has_playback_channel(me, c)) {
+ if (e->db_fix) {
+ if ((r = snd_mixer_selem_get_playback_volume(me, c, &value)) >= 0) {
+ /* If the channel volume is outside the limits set
+ * by the dB fix, we clamp the hw volume to be
+ * within the limits. */
+ if (value < e->db_fix->min_step) {
+ value = e->db_fix->min_step;
+ snd_mixer_selem_set_playback_volume(me, c, value);
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_debug("Playback volume for element %s channel %i was below the dB fix limit. "
+ "Volume reset to %0.2f dB.", buf, c,
+ e->db_fix->db_values[value - e->db_fix->min_step] / 100.0);
+ } else if (value > e->db_fix->max_step) {
+ value = e->db_fix->max_step;
+ snd_mixer_selem_set_playback_volume(me, c, value);
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_debug("Playback volume for element %s channel %i was over the dB fix limit. "
+ "Volume reset to %0.2f dB.", buf, c,
+ e->db_fix->db_values[value - e->db_fix->min_step] / 100.0);
+ }
+
+ /* Volume step -> dB value conversion. */
+ value = e->db_fix->db_values[value - e->db_fix->min_step];
+ }
+ } else
+ r = snd_mixer_selem_get_playback_dB(me, c, &value);
+ } else
+ r = -1;
+ } else {
+ if (snd_mixer_selem_has_capture_channel(me, c)) {
+ if (e->db_fix) {
+ if ((r = snd_mixer_selem_get_capture_volume(me, c, &value)) >= 0) {
+ /* If the channel volume is outside the limits set
+ * by the dB fix, we clamp the hw volume to be
+ * within the limits. */
+ if (value < e->db_fix->min_step) {
+ value = e->db_fix->min_step;
+ snd_mixer_selem_set_capture_volume(me, c, value);
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_debug("Capture volume for element %s channel %i was below the dB fix limit. "
+ "Volume reset to %0.2f dB.", buf, c,
+ e->db_fix->db_values[value - e->db_fix->min_step] / 100.0);
+ } else if (value > e->db_fix->max_step) {
+ value = e->db_fix->max_step;
+ snd_mixer_selem_set_capture_volume(me, c, value);
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_debug("Capture volume for element %s channel %i was over the dB fix limit. "
+ "Volume reset to %0.2f dB.", buf, c,
+ e->db_fix->db_values[value - e->db_fix->min_step] / 100.0);
+ }
+
+ /* Volume step -> dB value conversion. */
+ value = e->db_fix->db_values[value - e->db_fix->min_step];
+ }
+ } else
+ r = snd_mixer_selem_get_capture_dB(me, c, &value);
+ } else
+ r = -1;
+ }
+
+ if (r < 0)
+ continue;
+
+#ifdef HAVE_VALGRIND_MEMCHECK_H
+ VALGRIND_MAKE_MEM_DEFINED(&value, sizeof(value));
+#endif
+
+ f = from_alsa_dB(value);
+
+ } else {
+ long value = 0;
+
+ if (e->direction == PA_ALSA_DIRECTION_OUTPUT) {
+ if (snd_mixer_selem_has_playback_channel(me, c))
+ r = snd_mixer_selem_get_playback_volume(me, c, &value);
+ else
+ r = -1;
+ } else {
+ if (snd_mixer_selem_has_capture_channel(me, c))
+ r = snd_mixer_selem_get_capture_volume(me, c, &value);
+ else
+ r = -1;
+ }
+
+ if (r < 0)
+ continue;
+
+ f = from_alsa_volume(value, e->min_volume, e->max_volume);
+ }
+
+ for (k = 0; k < cm->channels; k++)
+ if (e->masks[c][e->n_channels-1] & PA_CHANNEL_POSITION_MASK(cm->map[k]))
+ if (v->values[k] < f)
+ v->values[k] = f;
+
+ mask |= e->masks[c][e->n_channels-1];
+ }
+
+ for (k = 0; k < cm->channels; k++)
+ if (!(mask & PA_CHANNEL_POSITION_MASK(cm->map[k])))
+ v->values[k] = PA_VOLUME_NORM;
+
+ return 0;
+}
+
+int pa_alsa_path_get_volume(pa_alsa_path *p, snd_mixer_t *m, const pa_channel_map *cm, pa_cvolume *v) {
+ pa_alsa_element *e;
+
+ pa_assert(m);
+ pa_assert(p);
+ pa_assert(cm);
+ pa_assert(v);
+
+ if (!p->has_volume)
+ return -1;
+
+ pa_cvolume_reset(v, cm->channels);
+
+ PA_LLIST_FOREACH(e, p->elements) {
+ pa_cvolume ev;
+
+ if (e->volume_use != PA_ALSA_VOLUME_MERGE)
+ continue;
+
+ pa_assert(!p->has_dB || e->has_dB);
+
+ if (element_get_volume(e, m, cm, &ev) < 0)
+ return -1;
+
+ /* If we have no dB information all we can do is take the first element and leave */
+ if (!p->has_dB) {
+ *v = ev;
+ return 0;
+ }
+
+ pa_sw_cvolume_multiply(v, v, &ev);
+ }
+
+ return 0;
+}
+
+static int element_get_switch(pa_alsa_element *e, snd_mixer_t *m, bool *b) {
+ snd_mixer_selem_id_t *sid;
+ snd_mixer_elem_t *me;
+ snd_mixer_selem_channel_id_t c;
+ char buf[64];
+
+ pa_assert(m);
+ pa_assert(e);
+ pa_assert(b);
+
+ SELEM_INIT(sid, &e->alsa_id);
+ if (!(me = snd_mixer_find_selem(m, sid))) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("Element %s seems to have disappeared.", buf);
+ return -1;
+ }
+
+ /* We return muted if at least one channel is muted */
+
+ for (c = 0; c <= SND_MIXER_SCHN_LAST; c++) {
+ int r;
+ int value = 0;
+
+ if (e->direction == PA_ALSA_DIRECTION_OUTPUT) {
+ if (snd_mixer_selem_has_playback_channel(me, c))
+ r = snd_mixer_selem_get_playback_switch(me, c, &value);
+ else
+ r = -1;
+ } else {
+ if (snd_mixer_selem_has_capture_channel(me, c))
+ r = snd_mixer_selem_get_capture_switch(me, c, &value);
+ else
+ r = -1;
+ }
+
+ if (r < 0)
+ continue;
+
+ if (!value) {
+ *b = false;
+ return 0;
+ }
+ }
+
+ *b = true;
+ return 0;
+}
+
+int pa_alsa_path_get_mute(pa_alsa_path *p, snd_mixer_t *m, bool *muted) {
+ pa_alsa_element *e;
+
+ pa_assert(m);
+ pa_assert(p);
+ pa_assert(muted);
+
+ if (!p->has_mute)
+ return -1;
+
+ PA_LLIST_FOREACH(e, p->elements) {
+ bool b;
+
+ if (e->switch_use != PA_ALSA_SWITCH_MUTE)
+ continue;
+
+ if (element_get_switch(e, m, &b) < 0)
+ return -1;
+
+ if (!b) {
+ *muted = true;
+ return 0;
+ }
+ }
+
+ *muted = false;
+ return 0;
+}
+
+/* Finds the closest item in db_fix->db_values and returns the corresponding
+ * step. *db_value is replaced with the value from the db_values table.
+ * Rounding is done based on the rounding parameter: -1 means rounding down and
+ * +1 means rounding up. */
+static long decibel_fix_get_step(pa_alsa_decibel_fix *db_fix, long *db_value, int rounding) {
+ unsigned i = 0;
+ unsigned max_i = 0;
+
+ pa_assert(db_fix);
+ pa_assert(db_value);
+ pa_assert(rounding != 0);
+
+ max_i = db_fix->max_step - db_fix->min_step;
+
+ if (rounding > 0) {
+ for (i = 0; i < max_i; i++) {
+ if (db_fix->db_values[i] >= *db_value)
+ break;
+ }
+ } else {
+ for (i = 0; i < max_i; i++) {
+ if (db_fix->db_values[i + 1] > *db_value)
+ break;
+ }
+ }
+
+ *db_value = db_fix->db_values[i];
+
+ return i + db_fix->min_step;
+}
+
+/* Alsa lib documentation says for snd_mixer_selem_set_playback_dB() direction argument,
+ * that "-1 = accurate or first below, 0 = accurate, 1 = accurate or first above".
+ * But even with accurate nearest dB volume step is not selected, so that is why we need
+ * this function. Returns 0 and nearest selectable volume in *value_dB on success or
+ * negative error code if fails. */
+static int element_get_nearest_alsa_dB(snd_mixer_elem_t *me, snd_mixer_selem_channel_id_t c, pa_alsa_direction_t d, long *value_dB) {
+
+ long alsa_val;
+ long value_high;
+ long value_low;
+ int r = -1;
+
+ pa_assert(me);
+ pa_assert(value_dB);
+
+ if (d == PA_ALSA_DIRECTION_OUTPUT) {
+ if ((r = snd_mixer_selem_ask_playback_dB_vol(me, *value_dB, +1, &alsa_val)) >= 0)
+ r = snd_mixer_selem_ask_playback_vol_dB(me, alsa_val, &value_high);
+
+ if (r < 0)
+ return r;
+
+ if (value_high == *value_dB)
+ return r;
+
+ if ((r = snd_mixer_selem_ask_playback_dB_vol(me, *value_dB, -1, &alsa_val)) >= 0)
+ r = snd_mixer_selem_ask_playback_vol_dB(me, alsa_val, &value_low);
+ } else {
+ if ((r = snd_mixer_selem_ask_capture_dB_vol(me, *value_dB, +1, &alsa_val)) >= 0)
+ r = snd_mixer_selem_ask_capture_vol_dB(me, alsa_val, &value_high);
+
+ if (r < 0)
+ return r;
+
+ if (value_high == *value_dB)
+ return r;
+
+ if ((r = snd_mixer_selem_ask_capture_dB_vol(me, *value_dB, -1, &alsa_val)) >= 0)
+ r = snd_mixer_selem_ask_capture_vol_dB(me, alsa_val, &value_low);
+ }
+
+ if (r < 0)
+ return r;
+
+ if (labs(value_high - *value_dB) < labs(value_low - *value_dB))
+ *value_dB = value_high;
+ else
+ *value_dB = value_low;
+
+ return r;
+}
+
+static int element_set_volume(pa_alsa_element *e, snd_mixer_t *m, const pa_channel_map *cm, pa_cvolume *v, bool deferred_volume, bool write_to_hw) {
+
+ snd_mixer_selem_id_t *sid;
+ pa_cvolume rv;
+ snd_mixer_elem_t *me;
+ snd_mixer_selem_channel_id_t c;
+ pa_channel_position_mask_t mask = 0;
+ char buf[64];
+ unsigned k;
+
+ pa_assert(m);
+ pa_assert(e);
+ pa_assert(cm);
+ pa_assert(v);
+ pa_assert(pa_cvolume_compatible_with_channel_map(v, cm));
+
+ SELEM_INIT(sid, &e->alsa_id);
+ if (!(me = snd_mixer_find_selem(m, sid))) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("Element %s seems to have disappeared.", buf);
+ return -1;
+ }
+
+ pa_cvolume_mute(&rv, cm->channels);
+
+ for (c = 0; c <= SND_MIXER_SCHN_LAST; c++) {
+ int r;
+ pa_volume_t f = PA_VOLUME_MUTED;
+ bool found = false;
+
+ for (k = 0; k < cm->channels; k++)
+ if (e->masks[c][e->n_channels-1] & PA_CHANNEL_POSITION_MASK(cm->map[k])) {
+ found = true;
+ if (v->values[k] > f)
+ f = v->values[k];
+ }
+
+ if (!found) {
+ /* Hmm, so this channel does not exist in the volume
+ * struct, so let's bind it to the overall max of the
+ * volume. */
+ f = pa_cvolume_max(v);
+ }
+
+ if (e->has_dB) {
+ long value = to_alsa_dB(f);
+ int rounding;
+
+ if (e->volume_limit >= 0 && value > (e->max_dB * 100))
+ value = e->max_dB * 100;
+
+ if (e->direction == PA_ALSA_DIRECTION_OUTPUT) {
+ /* If we call set_playback_volume() without checking first
+ * if the channel is available, ALSA behaves very
+ * strangely and doesn't fail the call */
+ if (snd_mixer_selem_has_playback_channel(me, c)) {
+ rounding = +1;
+ if (e->db_fix) {
+ if (write_to_hw)
+ r = snd_mixer_selem_set_playback_volume(me, c, decibel_fix_get_step(e->db_fix, &value, rounding));
+ else {
+ decibel_fix_get_step(e->db_fix, &value, rounding);
+ r = 0;
+ }
+
+ } else {
+ if (write_to_hw) {
+ if (deferred_volume) {
+ if ((r = element_get_nearest_alsa_dB(me, c, PA_ALSA_DIRECTION_OUTPUT, &value)) >= 0)
+ r = snd_mixer_selem_set_playback_dB(me, c, value, 0);
+ } else {
+ if ((r = snd_mixer_selem_set_playback_dB(me, c, value, rounding)) >= 0)
+ r = snd_mixer_selem_get_playback_dB(me, c, &value);
+ }
+ } else {
+ long alsa_val;
+ if ((r = snd_mixer_selem_ask_playback_dB_vol(me, value, rounding, &alsa_val)) >= 0)
+ r = snd_mixer_selem_ask_playback_vol_dB(me, alsa_val, &value);
+ }
+ }
+ } else
+ r = -1;
+ } else {
+ if (snd_mixer_selem_has_capture_channel(me, c)) {
+ rounding = -1;
+ if (e->db_fix) {
+ if (write_to_hw)
+ r = snd_mixer_selem_set_capture_volume(me, c, decibel_fix_get_step(e->db_fix, &value, rounding));
+ else {
+ decibel_fix_get_step(e->db_fix, &value, rounding);
+ r = 0;
+ }
+
+ } else {
+ if (write_to_hw) {
+ if (deferred_volume) {
+ if ((r = element_get_nearest_alsa_dB(me, c, PA_ALSA_DIRECTION_INPUT, &value)) >= 0)
+ r = snd_mixer_selem_set_capture_dB(me, c, value, 0);
+ } else {
+ if ((r = snd_mixer_selem_set_capture_dB(me, c, value, rounding)) >= 0)
+ r = snd_mixer_selem_get_capture_dB(me, c, &value);
+ }
+ } else {
+ long alsa_val;
+ if ((r = snd_mixer_selem_ask_capture_dB_vol(me, value, rounding, &alsa_val)) >= 0)
+ r = snd_mixer_selem_ask_capture_vol_dB(me, alsa_val, &value);
+ }
+ }
+ } else
+ r = -1;
+ }
+
+ if (r < 0)
+ continue;
+
+ f = from_alsa_dB(value);
+
+ } else {
+ long value;
+
+ value = to_alsa_volume(f, e->min_volume, e->max_volume);
+
+ if (e->direction == PA_ALSA_DIRECTION_OUTPUT) {
+ if (snd_mixer_selem_has_playback_channel(me, c)) {
+ if ((r = snd_mixer_selem_set_playback_volume(me, c, value)) >= 0)
+ r = snd_mixer_selem_get_playback_volume(me, c, &value);
+ } else
+ r = -1;
+ } else {
+ if (snd_mixer_selem_has_capture_channel(me, c)) {
+ if ((r = snd_mixer_selem_set_capture_volume(me, c, value)) >= 0)
+ r = snd_mixer_selem_get_capture_volume(me, c, &value);
+ } else
+ r = -1;
+ }
+
+ if (r < 0)
+ continue;
+
+ f = from_alsa_volume(value, e->min_volume, e->max_volume);
+ }
+
+ for (k = 0; k < cm->channels; k++)
+ if (e->masks[c][e->n_channels-1] & PA_CHANNEL_POSITION_MASK(cm->map[k]))
+ if (rv.values[k] < f)
+ rv.values[k] = f;
+
+ mask |= e->masks[c][e->n_channels-1];
+ }
+
+ for (k = 0; k < cm->channels; k++)
+ if (!(mask & PA_CHANNEL_POSITION_MASK(cm->map[k])))
+ rv.values[k] = PA_VOLUME_NORM;
+
+ *v = rv;
+ return 0;
+}
+
+int pa_alsa_path_set_volume(pa_alsa_path *p, snd_mixer_t *m, const pa_channel_map *cm, pa_cvolume *v, bool deferred_volume, bool write_to_hw) {
+
+ pa_alsa_element *e;
+ pa_cvolume rv;
+
+ pa_assert(m);
+ pa_assert(p);
+ pa_assert(cm);
+ pa_assert(v);
+ pa_assert(pa_cvolume_compatible_with_channel_map(v, cm));
+
+ if (!p->has_volume)
+ return -1;
+
+ rv = *v; /* Remaining adjustment */
+ pa_cvolume_reset(v, cm->channels); /* Adjustment done */
+
+ PA_LLIST_FOREACH(e, p->elements) {
+ pa_cvolume ev;
+
+ if (e->volume_use != PA_ALSA_VOLUME_MERGE)
+ continue;
+
+ pa_assert(!p->has_dB || e->has_dB);
+
+ ev = rv;
+ if (element_set_volume(e, m, cm, &ev, deferred_volume, write_to_hw) < 0)
+ return -1;
+
+ if (!p->has_dB) {
+ *v = ev;
+ return 0;
+ }
+
+ pa_sw_cvolume_multiply(v, v, &ev);
+ pa_sw_cvolume_divide(&rv, &rv, &ev);
+ }
+
+ return 0;
+}
+
+static int element_set_switch(pa_alsa_element *e, snd_mixer_t *m, bool b) {
+ snd_mixer_elem_t *me;
+ snd_mixer_selem_id_t *sid;
+ char buf[64];
+ int r;
+
+ pa_assert(m);
+ pa_assert(e);
+
+ SELEM_INIT(sid, &e->alsa_id);
+ if (!(me = snd_mixer_find_selem(m, sid))) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("Element %s seems to have disappeared.", buf);
+ return -1;
+ }
+
+ if (e->direction == PA_ALSA_DIRECTION_OUTPUT)
+ r = snd_mixer_selem_set_playback_switch_all(me, b);
+ else
+ r = snd_mixer_selem_set_capture_switch_all(me, b);
+
+ if (r < 0) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("Failed to set switch of %s: %s", buf, pa_alsa_strerror(errno));
+ }
+
+ return r;
+}
+
+int pa_alsa_path_set_mute(pa_alsa_path *p, snd_mixer_t *m, bool muted) {
+ pa_alsa_element *e;
+
+ pa_assert(m);
+ pa_assert(p);
+
+ if (!p->has_mute)
+ return -1;
+
+ PA_LLIST_FOREACH(e, p->elements) {
+
+ if (e->switch_use != PA_ALSA_SWITCH_MUTE)
+ continue;
+
+ if (element_set_switch(e, m, !muted) < 0)
+ return -1;
+ }
+
+ return 0;
+}
+
+/* Depending on whether e->volume_use is _OFF, _ZERO or _CONSTANT, this
+ * function sets all channels of the volume element to e->min_volume, 0 dB or
+ * e->constant_volume. */
+static int element_set_constant_volume(pa_alsa_element *e, snd_mixer_t *m) {
+ snd_mixer_elem_t *me = NULL;
+ snd_mixer_selem_id_t *sid = NULL;
+ int r = 0;
+ long volume = -1;
+ bool volume_set = false;
+ char buf[64];
+
+ pa_assert(m);
+ pa_assert(e);
+
+ SELEM_INIT(sid, &e->alsa_id);
+ if (!(me = snd_mixer_find_selem(m, sid))) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("Element %s seems to have disappeared.", buf);
+ return -1;
+ }
+
+ switch (e->volume_use) {
+ case PA_ALSA_VOLUME_OFF:
+ volume = e->min_volume;
+ volume_set = true;
+ break;
+
+ case PA_ALSA_VOLUME_ZERO:
+ if (e->db_fix) {
+ long dB = 0;
+
+ volume = decibel_fix_get_step(e->db_fix, &dB, (e->direction == PA_ALSA_DIRECTION_OUTPUT ? +1 : -1));
+ volume_set = true;
+ }
+ break;
+
+ case PA_ALSA_VOLUME_CONSTANT:
+ volume = e->constant_volume;
+ volume_set = true;
+ break;
+
+ default:
+ pa_assert_not_reached();
+ }
+
+ if (volume_set) {
+ if (e->direction == PA_ALSA_DIRECTION_OUTPUT)
+ r = snd_mixer_selem_set_playback_volume_all(me, volume);
+ else
+ r = snd_mixer_selem_set_capture_volume_all(me, volume);
+ } else {
+ pa_assert(e->volume_use == PA_ALSA_VOLUME_ZERO);
+ pa_assert(!e->db_fix);
+
+ if (e->direction == PA_ALSA_DIRECTION_OUTPUT)
+ r = snd_mixer_selem_set_playback_dB_all(me, 0, +1);
+ else
+ r = snd_mixer_selem_set_capture_dB_all(me, 0, -1);
+ }
+
+ if (r < 0) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("Failed to set volume of %s: %s", buf, pa_alsa_strerror(errno));
+ }
+
+ return r;
+}
+
+int pa_alsa_path_select(pa_alsa_path *p, pa_alsa_setting *s, snd_mixer_t *m, bool device_is_muted) {
+ pa_alsa_element *e;
+ int r = 0;
+
+ pa_assert(m);
+ pa_assert(p);
+
+ pa_log_debug("Activating path %s", p->name);
+ pa_alsa_path_dump(p);
+
+ /* First turn on hw mute if available, to avoid noise
+ * when setting the mixer controls. */
+ if (p->mute_during_activation) {
+ PA_LLIST_FOREACH(e, p->elements) {
+ if (e->switch_use == PA_ALSA_SWITCH_MUTE)
+ /* If the muting fails here, that's not a critical problem for
+ * selecting a path, so we ignore the return value.
+ * element_set_switch() will print a warning anyway, so this
+ * won't be a silent failure either. */
+ (void) element_set_switch(e, m, false);
+ }
+ }
+
+ PA_LLIST_FOREACH(e, p->elements) {
+
+ switch (e->switch_use) {
+ case PA_ALSA_SWITCH_OFF:
+ r = element_set_switch(e, m, false);
+ break;
+
+ case PA_ALSA_SWITCH_ON:
+ r = element_set_switch(e, m, true);
+ break;
+
+ case PA_ALSA_SWITCH_MUTE:
+ case PA_ALSA_SWITCH_IGNORE:
+ case PA_ALSA_SWITCH_SELECT:
+ r = 0;
+ break;
+ }
+
+ if (r < 0)
+ return -1;
+
+ switch (e->volume_use) {
+ case PA_ALSA_VOLUME_OFF:
+ case PA_ALSA_VOLUME_ZERO:
+ case PA_ALSA_VOLUME_CONSTANT:
+ r = element_set_constant_volume(e, m);
+ break;
+
+ case PA_ALSA_VOLUME_MERGE:
+ case PA_ALSA_VOLUME_IGNORE:
+ r = 0;
+ break;
+ }
+
+ if (r < 0)
+ return -1;
+ }
+
+ if (s)
+ setting_select(s, m);
+
+ /* Finally restore hw mute to the device mute status. */
+ if (p->mute_during_activation) {
+ PA_LLIST_FOREACH(e, p->elements) {
+ if (e->switch_use == PA_ALSA_SWITCH_MUTE) {
+ if (element_set_switch(e, m, !device_is_muted) < 0)
+ return -1;
+ }
+ }
+ }
+
+ return 0;
+}
+
+static int check_required(pa_alsa_element *e, snd_mixer_elem_t *me) {
+ bool has_switch;
+ bool has_enumeration;
+ bool has_volume;
+
+ pa_assert(e);
+ pa_assert(me);
+
+ if (e->direction == PA_ALSA_DIRECTION_OUTPUT) {
+ has_switch =
+ snd_mixer_selem_has_playback_switch(me) ||
+ (e->direction_try_other && snd_mixer_selem_has_capture_switch(me));
+ } else {
+ has_switch =
+ snd_mixer_selem_has_capture_switch(me) ||
+ (e->direction_try_other && snd_mixer_selem_has_playback_switch(me));
+ }
+
+ if (e->direction == PA_ALSA_DIRECTION_OUTPUT) {
+ has_volume =
+ snd_mixer_selem_has_playback_volume(me) ||
+ (e->direction_try_other && snd_mixer_selem_has_capture_volume(me));
+ } else {
+ has_volume =
+ snd_mixer_selem_has_capture_volume(me) ||
+ (e->direction_try_other && snd_mixer_selem_has_playback_volume(me));
+ }
+
+ has_enumeration = snd_mixer_selem_is_enumerated(me);
+
+ if ((e->required == PA_ALSA_REQUIRED_SWITCH && !has_switch) ||
+ (e->required == PA_ALSA_REQUIRED_VOLUME && !has_volume) ||
+ (e->required == PA_ALSA_REQUIRED_ENUMERATION && !has_enumeration))
+ return -1;
+
+ if (e->required == PA_ALSA_REQUIRED_ANY && !(has_switch || has_volume || has_enumeration))
+ return -1;
+
+ if ((e->required_absent == PA_ALSA_REQUIRED_SWITCH && has_switch) ||
+ (e->required_absent == PA_ALSA_REQUIRED_VOLUME && has_volume) ||
+ (e->required_absent == PA_ALSA_REQUIRED_ENUMERATION && has_enumeration))
+ return -1;
+
+ if (e->required_absent == PA_ALSA_REQUIRED_ANY && (has_switch || has_volume || has_enumeration))
+ return -1;
+
+ if (e->required_any != PA_ALSA_REQUIRED_IGNORE) {
+ switch (e->required_any) {
+ case PA_ALSA_REQUIRED_VOLUME:
+ e->path->req_any_present |= (e->volume_use != PA_ALSA_VOLUME_IGNORE);
+ break;
+ case PA_ALSA_REQUIRED_SWITCH:
+ e->path->req_any_present |= (e->switch_use != PA_ALSA_SWITCH_IGNORE);
+ break;
+ case PA_ALSA_REQUIRED_ENUMERATION:
+ e->path->req_any_present |= (e->enumeration_use != PA_ALSA_ENUMERATION_IGNORE);
+ break;
+ case PA_ALSA_REQUIRED_ANY:
+ e->path->req_any_present |=
+ (e->volume_use != PA_ALSA_VOLUME_IGNORE) ||
+ (e->switch_use != PA_ALSA_SWITCH_IGNORE) ||
+ (e->enumeration_use != PA_ALSA_ENUMERATION_IGNORE);
+ break;
+ default:
+ pa_assert_not_reached();
+ }
+ }
+
+ if (e->enumeration_use == PA_ALSA_ENUMERATION_SELECT) {
+ pa_alsa_option *o;
+ PA_LLIST_FOREACH(o, e->options) {
+ e->path->req_any_present |= (o->required_any != PA_ALSA_REQUIRED_IGNORE) &&
+ (o->alsa_idx >= 0);
+ if (o->required != PA_ALSA_REQUIRED_IGNORE && o->alsa_idx < 0)
+ return -1;
+ if (o->required_absent != PA_ALSA_REQUIRED_IGNORE && o->alsa_idx >= 0)
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+static int element_ask_vol_dB(snd_mixer_elem_t *me, pa_alsa_direction_t dir, long value, long *dBvalue) {
+ if (dir == PA_ALSA_DIRECTION_OUTPUT)
+ return snd_mixer_selem_ask_playback_vol_dB(me, value, dBvalue);
+ else
+ return snd_mixer_selem_ask_capture_vol_dB(me, value, dBvalue);
+}
+
+static bool element_probe_volume(pa_alsa_element *e, snd_mixer_elem_t *me) {
+
+ long min_dB = 0, max_dB = 0;
+ int r;
+ bool is_mono;
+ pa_channel_position_t p;
+ char buf[64];
+
+ if (e->direction == PA_ALSA_DIRECTION_OUTPUT) {
+ if (!snd_mixer_selem_has_playback_volume(me)) {
+ if (e->direction_try_other && snd_mixer_selem_has_capture_volume(me))
+ e->direction = PA_ALSA_DIRECTION_INPUT;
+ else
+ return false;
+ }
+ } else {
+ if (!snd_mixer_selem_has_capture_volume(me)) {
+ if (e->direction_try_other && snd_mixer_selem_has_playback_volume(me))
+ e->direction = PA_ALSA_DIRECTION_OUTPUT;
+ else
+ return false;
+ }
+ }
+
+ e->direction_try_other = false;
+
+ if (e->direction == PA_ALSA_DIRECTION_OUTPUT)
+ r = snd_mixer_selem_get_playback_volume_range(me, &e->min_volume, &e->max_volume);
+ else
+ r = snd_mixer_selem_get_capture_volume_range(me, &e->min_volume, &e->max_volume);
+
+ if (r < 0) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("Failed to get volume range of %s: %s", buf, pa_alsa_strerror(r));
+ return false;
+ }
+
+ if (e->min_volume >= e->max_volume) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("Your kernel driver is broken for element %s: it reports a volume range from %li to %li which makes no sense.",
+ buf, e->min_volume, e->max_volume);
+ return false;
+ }
+ if (e->volume_use == PA_ALSA_VOLUME_CONSTANT && (e->min_volume > e->constant_volume || e->max_volume < e->constant_volume)) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("Constant volume %li configured for element %s, but the available range is from %li to %li.",
+ e->constant_volume, buf, e->min_volume, e->max_volume);
+ return false;
+ }
+
+
+ if (e->db_fix && ((e->min_volume > e->db_fix->min_step) || (e->max_volume < e->db_fix->max_step))) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("The step range of the decibel fix for element %s (%li-%li) doesn't fit to the "
+ "real hardware range (%li-%li). Disabling the decibel fix.", buf,
+ e->db_fix->min_step, e->db_fix->max_step, e->min_volume, e->max_volume);
+
+ decibel_fix_free(e->db_fix);
+ e->db_fix = NULL;
+ }
+
+ if (e->db_fix) {
+ e->has_dB = true;
+ e->min_volume = e->db_fix->min_step;
+ e->max_volume = e->db_fix->max_step;
+ min_dB = e->db_fix->db_values[0];
+ max_dB = e->db_fix->db_values[e->db_fix->max_step - e->db_fix->min_step];
+ } else if (e->direction == PA_ALSA_DIRECTION_OUTPUT)
+ e->has_dB = snd_mixer_selem_get_playback_dB_range(me, &min_dB, &max_dB) >= 0;
+ else
+ e->has_dB = snd_mixer_selem_get_capture_dB_range(me, &min_dB, &max_dB) >= 0;
+
+ /* Check that the kernel driver returns consistent limits with
+ * both _get_*_dB_range() and _ask_*_vol_dB(). */
+ if (e->has_dB && !e->db_fix) {
+ long min_dB_checked = 0;
+ long max_dB_checked = 0;
+
+ if (element_ask_vol_dB(me, e->direction, e->min_volume, &min_dB_checked) < 0) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("Failed to query the dB value for %s at volume level %li", buf, e->min_volume);
+ return false;
+ }
+
+ if (element_ask_vol_dB(me, e->direction, e->max_volume, &max_dB_checked) < 0) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("Failed to query the dB value for %s at volume level %li", buf, e->max_volume);
+ return false;
+ }
+
+ if (min_dB != min_dB_checked || max_dB != max_dB_checked) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("Your kernel driver is broken: the reported dB range for %s (from %0.2f dB to %0.2f dB) "
+ "doesn't match the dB values at minimum and maximum volume levels: %0.2f dB at level %li, "
+ "%0.2f dB at level %li.", buf, min_dB / 100.0, max_dB / 100.0,
+ min_dB_checked / 100.0, e->min_volume, max_dB_checked / 100.0, e->max_volume);
+ return false;
+ }
+ }
+
+ if (e->has_dB) {
+ e->min_dB = ((double) min_dB) / 100.0;
+ e->max_dB = ((double) max_dB) / 100.0;
+
+ if (min_dB >= max_dB) {
+ pa_assert(!e->db_fix);
+ pa_log_warn("Your kernel driver is broken: it reports a volume range from %0.2f dB to %0.2f dB which makes no sense.",
+ e->min_dB, e->max_dB);
+ e->has_dB = false;
+ }
+ }
+
+ if (e->volume_limit >= 0) {
+ if (e->volume_limit <= e->min_volume || e->volume_limit > e->max_volume) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("Volume limit for element %s of path %s is invalid: %li isn't within the valid range "
+ "%li-%li. The volume limit is ignored.",
+ buf, e->path->name, e->volume_limit, e->min_volume + 1, e->max_volume);
+ } else {
+ e->max_volume = e->volume_limit;
+
+ if (e->has_dB) {
+ if (e->db_fix) {
+ e->db_fix->max_step = e->max_volume;
+ e->max_dB = ((double) e->db_fix->db_values[e->db_fix->max_step - e->db_fix->min_step]) / 100.0;
+ } else if (element_ask_vol_dB(me, e->direction, e->max_volume, &max_dB) < 0) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("Failed to get dB value of %s: %s", buf, pa_alsa_strerror(r));
+ e->has_dB = false;
+ } else
+ e->max_dB = ((double) max_dB) / 100.0;
+ }
+ }
+ }
+
+ if (e->direction == PA_ALSA_DIRECTION_OUTPUT)
+ is_mono = snd_mixer_selem_is_playback_mono(me) > 0;
+ else
+ is_mono = snd_mixer_selem_is_capture_mono(me) > 0;
+
+ if (is_mono) {
+ e->n_channels = 1;
+
+ if ((e->override_map & (1 << (e->n_channels-1))) && e->masks[SND_MIXER_SCHN_MONO][e->n_channels-1] == 0) {
+ pa_log_warn("Override map for mono element %s is invalid, ignoring override map", e->path->name);
+ e->override_map &= ~(1 << (e->n_channels-1));
+ }
+ if (!(e->override_map & (1 << (e->n_channels-1)))) {
+ for (p = PA_CHANNEL_POSITION_FRONT_LEFT; p < PA_CHANNEL_POSITION_MAX; p++) {
+ if (alsa_channel_ids[p] == SND_MIXER_SCHN_UNKNOWN)
+ continue;
+ e->masks[alsa_channel_ids[p]][e->n_channels-1] = 0;
+ }
+ e->masks[SND_MIXER_SCHN_MONO][e->n_channels-1] = PA_CHANNEL_POSITION_MASK_ALL;
+ }
+ e->merged_mask = e->masks[SND_MIXER_SCHN_MONO][e->n_channels-1];
+ return true;
+ }
+
+ e->n_channels = 0;
+ for (p = PA_CHANNEL_POSITION_FRONT_LEFT; p < PA_CHANNEL_POSITION_MAX; p++) {
+ if (alsa_channel_ids[p] == SND_MIXER_SCHN_UNKNOWN)
+ continue;
+
+ if (e->direction == PA_ALSA_DIRECTION_OUTPUT)
+ e->n_channels += snd_mixer_selem_has_playback_channel(me, alsa_channel_ids[p]) > 0;
+ else
+ e->n_channels += snd_mixer_selem_has_capture_channel(me, alsa_channel_ids[p]) > 0;
+ }
+
+ if (e->n_channels <= 0) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("Volume element %s with no channels?", buf);
+ return false;
+ } else if (e->n_channels > POSITION_MASK_CHANNELS) {
+ /* FIXME: In some places code like this is used:
+ *
+ * e->masks[alsa_channel_ids[p]][e->n_channels-1]
+ *
+ * The definition of e->masks is
+ *
+ * pa_channel_position_mask_t masks[SND_MIXER_SCHN_LAST + 1][POSITION_MASK_CHANNELS];
+ *
+ * Since the array size is fixed at POSITION_MASK_CHANNELS, we obviously
+ * don't support elements with more than POSITION_MASK_CHANNELS
+ * channels... */
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("Volume element %s has %u channels. That's too much! I can't handle that!", buf, e->n_channels);
+ return false;
+ }
+
+retry:
+ if (!(e->override_map & (1 << (e->n_channels-1)))) {
+ for (p = PA_CHANNEL_POSITION_FRONT_LEFT; p < PA_CHANNEL_POSITION_MAX; p++) {
+ bool has_channel;
+
+ if (alsa_channel_ids[p] == SND_MIXER_SCHN_UNKNOWN)
+ continue;
+
+ if (e->direction == PA_ALSA_DIRECTION_OUTPUT)
+ has_channel = snd_mixer_selem_has_playback_channel(me, alsa_channel_ids[p]) > 0;
+ else
+ has_channel = snd_mixer_selem_has_capture_channel(me, alsa_channel_ids[p]) > 0;
+
+ e->masks[alsa_channel_ids[p]][e->n_channels-1] = has_channel ? PA_CHANNEL_POSITION_MASK(p) : 0;
+ }
+ }
+
+ e->merged_mask = 0;
+ for (p = PA_CHANNEL_POSITION_FRONT_LEFT; p < PA_CHANNEL_POSITION_MAX; p++) {
+ if (alsa_channel_ids[p] == SND_MIXER_SCHN_UNKNOWN)
+ continue;
+
+ e->merged_mask |= e->masks[alsa_channel_ids[p]][e->n_channels-1];
+ }
+
+ if (e->merged_mask == 0) {
+ if (!(e->override_map & (1 << (e->n_channels-1)))) {
+ pa_log_warn("Channel map for element %s is invalid", e->path->name);
+ return false;
+ }
+ pa_log_warn("Override map for element %s has empty result, ignoring override map", e->path->name);
+ e->override_map &= ~(1 << (e->n_channels-1));
+ goto retry;
+ }
+
+ return true;
+}
+
+static int element_probe(pa_alsa_element *e, snd_mixer_t *m) {
+ snd_mixer_selem_id_t *sid;
+ snd_mixer_elem_t *me;
+
+ pa_assert(m);
+ pa_assert(e);
+ pa_assert(e->path);
+
+ SELEM_INIT(sid, &e->alsa_id);
+
+ if (!(me = snd_mixer_find_selem(m, sid))) {
+
+ if (e->required != PA_ALSA_REQUIRED_IGNORE)
+ return -1;
+
+ e->switch_use = PA_ALSA_SWITCH_IGNORE;
+ e->volume_use = PA_ALSA_VOLUME_IGNORE;
+ e->enumeration_use = PA_ALSA_ENUMERATION_IGNORE;
+
+ return 0;
+ }
+
+ if (e->switch_use != PA_ALSA_SWITCH_IGNORE) {
+ if (e->direction == PA_ALSA_DIRECTION_OUTPUT) {
+
+ if (!snd_mixer_selem_has_playback_switch(me)) {
+ if (e->direction_try_other && snd_mixer_selem_has_capture_switch(me))
+ e->direction = PA_ALSA_DIRECTION_INPUT;
+ else
+ e->switch_use = PA_ALSA_SWITCH_IGNORE;
+ }
+
+ } else {
+
+ if (!snd_mixer_selem_has_capture_switch(me)) {
+ if (e->direction_try_other && snd_mixer_selem_has_playback_switch(me))
+ e->direction = PA_ALSA_DIRECTION_OUTPUT;
+ else
+ e->switch_use = PA_ALSA_SWITCH_IGNORE;
+ }
+ }
+
+ if (e->switch_use != PA_ALSA_SWITCH_IGNORE)
+ e->direction_try_other = false;
+ }
+
+ if (!element_probe_volume(e, me))
+ e->volume_use = PA_ALSA_VOLUME_IGNORE;
+
+ if (e->switch_use == PA_ALSA_SWITCH_SELECT) {
+ pa_alsa_option *o;
+
+ PA_LLIST_FOREACH(o, e->options)
+ o->alsa_idx = pa_streq(o->alsa_name, "on") ? 1 : 0;
+ } else if (e->enumeration_use == PA_ALSA_ENUMERATION_SELECT) {
+ int n;
+ pa_alsa_option *o;
+
+ if ((n = snd_mixer_selem_get_enum_items(me)) < 0) {
+ pa_log("snd_mixer_selem_get_enum_items() failed: %s", pa_alsa_strerror(n));
+ return -1;
+ }
+
+ PA_LLIST_FOREACH(o, e->options) {
+ int i;
+
+ for (i = 0; i < n; i++) {
+ char buf[128];
+
+ if (snd_mixer_selem_get_enum_item_name(me, i, sizeof(buf), buf) < 0)
+ continue;
+
+ if (!pa_streq(buf, o->alsa_name))
+ continue;
+
+ o->alsa_idx = i;
+ }
+ }
+ }
+
+ if (check_required(e, me) < 0)
+ return -1;
+
+ return 0;
+}
+
+static int jack_probe(pa_alsa_jack *j, pa_alsa_mapping *mapping, snd_mixer_t *m) {
+ bool has_control;
+
+ pa_assert(j);
+ pa_assert(j->path);
+
+ if (j->append_pcm_to_name) {
+ char *new_name;
+
+ if (!mapping) {
+ /* This could also be an assertion, because this should never
+ * happen. At the time of writing, mapping can only be NULL when
+ * module-alsa-sink/source synthesizes a path, and those
+ * synthesized paths never have any jacks, so jack_probe() should
+ * never be called with a NULL mapping. */
+ pa_log("Jack %s: append_pcm_to_name is set, but mapping is NULL. Can't use this jack.", j->name);
+ return -1;
+ }
+
+ new_name = pa_sprintf_malloc("%s,pcm=%i Jack", j->name, mapping->hw_device_index);
+ pa_xfree(j->alsa_id.name);
+ j->alsa_id.name = new_name;
+ j->append_pcm_to_name = false;
+ }
+
+ has_control = pa_alsa_mixer_find_card(m, &j->alsa_id, 0) != NULL;
+ pa_alsa_jack_set_has_control(j, has_control);
+
+ if (j->has_control) {
+ if (j->required_absent != PA_ALSA_REQUIRED_IGNORE)
+ return -1;
+ if (j->required_any != PA_ALSA_REQUIRED_IGNORE)
+ j->path->req_any_present = true;
+ } else {
+ if (j->required != PA_ALSA_REQUIRED_IGNORE)
+ return -1;
+ }
+
+ return 0;
+}
+
+pa_alsa_element * pa_alsa_element_get(pa_alsa_path *p, const char *section, bool prefixed) {
+ pa_alsa_element *e;
+ char *name;
+ int index;
+
+ pa_assert(p);
+ pa_assert(section);
+
+ if (prefixed) {
+ if (!pa_startswith(section, "Element "))
+ return NULL;
+
+ section += 8;
+ }
+
+ /* This is not an element section, but an enum section? */
+ if (strchr(section, ':'))
+ return NULL;
+
+ name = alloca(strlen(section) + 1);
+ if (alsa_id_decode(section, name, &index))
+ return NULL;
+
+ if (p->last_element && pa_streq(p->last_element->alsa_id.name, name) &&
+ p->last_element->alsa_id.index == index)
+ return p->last_element;
+
+ PA_LLIST_FOREACH(e, p->elements)
+ if (pa_streq(e->alsa_id.name, name) && e->alsa_id.index == index)
+ goto finish;
+
+ e = pa_xnew0(pa_alsa_element, 1);
+ e->path = p;
+ e->alsa_id.name = pa_xstrdup(name);
+ e->alsa_id.index = index;
+ e->direction = p->direction;
+ e->volume_limit = -1;
+
+ PA_LLIST_INSERT_AFTER(pa_alsa_element, p->elements, p->last_element, e);
+
+finish:
+ p->last_element = e;
+ return e;
+}
+
+static pa_alsa_jack* jack_get(pa_alsa_path *p, const char *section) {
+ pa_alsa_jack *j;
+ char *name;
+ int index;
+
+ if (!pa_startswith(section, "Jack "))
+ return NULL;
+ section += 5;
+
+ name = alloca(strlen(section) + 1);
+ if (alsa_id_decode(section, name, &index))
+ return NULL;
+
+ if (p->last_jack && pa_streq(p->last_jack->name, name) &&
+ p->last_jack->alsa_id.index == index)
+ return p->last_jack;
+
+ PA_LLIST_FOREACH(j, p->jacks)
+ if (pa_streq(j->name, name) && j->alsa_id.index == index)
+ goto finish;
+
+ j = pa_alsa_jack_new(p, NULL, name, index);
+ PA_LLIST_INSERT_AFTER(pa_alsa_jack, p->jacks, p->last_jack, j);
+
+finish:
+ p->last_jack = j;
+ return j;
+}
+
+static pa_alsa_option* option_get(pa_alsa_path *p, const char *section) {
+ char *en, *name;
+ const char *on;
+ pa_alsa_option *o;
+ pa_alsa_element *e;
+ size_t len;
+ int index;
+
+ if (!pa_startswith(section, "Option "))
+ return NULL;
+
+ section += 7;
+
+ /* This is not an enum section, but an element section? */
+ if (!(on = strchr(section, ':')))
+ return NULL;
+
+ len = on - section;
+ en = alloca(len + 1);
+ strncpy(en, section, len);
+ en[len] = '\0';
+
+ name = alloca(strlen(en) + 1);
+ if (alsa_id_decode(en, name, &index))
+ return NULL;
+
+ on++;
+
+ if (p->last_option &&
+ pa_streq(p->last_option->element->alsa_id.name, name) &&
+ p->last_option->element->alsa_id.index == index &&
+ pa_streq(p->last_option->alsa_name, on)) {
+ return p->last_option;
+ }
+
+ pa_assert_se(e = pa_alsa_element_get(p, en, false));
+
+ PA_LLIST_FOREACH(o, e->options)
+ if (pa_streq(o->alsa_name, on))
+ goto finish;
+
+ o = pa_xnew0(pa_alsa_option, 1);
+ o->element = e;
+ o->alsa_name = pa_xstrdup(on);
+ o->alsa_idx = -1;
+
+ if (p->last_option && p->last_option->element == e)
+ PA_LLIST_INSERT_AFTER(pa_alsa_option, e->options, p->last_option, o);
+ else
+ PA_LLIST_PREPEND(pa_alsa_option, e->options, o);
+
+finish:
+ p->last_option = o;
+ return o;
+}
+
+static int element_parse_switch(pa_config_parser_state *state) {
+ pa_alsa_path *p;
+ pa_alsa_element *e;
+
+ pa_assert(state);
+
+ p = state->userdata;
+
+ if (!(e = pa_alsa_element_get(p, state->section, true))) {
+ pa_log("[%s:%u] Switch makes no sense in '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ if (pa_streq(state->rvalue, "ignore"))
+ e->switch_use = PA_ALSA_SWITCH_IGNORE;
+ else if (pa_streq(state->rvalue, "mute"))
+ e->switch_use = PA_ALSA_SWITCH_MUTE;
+ else if (pa_streq(state->rvalue, "off"))
+ e->switch_use = PA_ALSA_SWITCH_OFF;
+ else if (pa_streq(state->rvalue, "on"))
+ e->switch_use = PA_ALSA_SWITCH_ON;
+ else if (pa_streq(state->rvalue, "select"))
+ e->switch_use = PA_ALSA_SWITCH_SELECT;
+ else {
+ pa_log("[%s:%u] Switch invalid of '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ return 0;
+}
+
+static int element_parse_volume(pa_config_parser_state *state) {
+ pa_alsa_path *p;
+ pa_alsa_element *e;
+
+ pa_assert(state);
+
+ p = state->userdata;
+
+ if (!(e = pa_alsa_element_get(p, state->section, true))) {
+ pa_log("[%s:%u] Volume makes no sense in '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ if (pa_streq(state->rvalue, "ignore"))
+ e->volume_use = PA_ALSA_VOLUME_IGNORE;
+ else if (pa_streq(state->rvalue, "merge"))
+ e->volume_use = PA_ALSA_VOLUME_MERGE;
+ else if (pa_streq(state->rvalue, "off"))
+ e->volume_use = PA_ALSA_VOLUME_OFF;
+ else if (pa_streq(state->rvalue, "zero"))
+ e->volume_use = PA_ALSA_VOLUME_ZERO;
+ else {
+ uint32_t constant;
+
+ if (pa_atou(state->rvalue, &constant) >= 0) {
+ e->volume_use = PA_ALSA_VOLUME_CONSTANT;
+ e->constant_volume = constant;
+ } else {
+ pa_log("[%s:%u] Volume invalid of '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+static int element_parse_enumeration(pa_config_parser_state *state) {
+ pa_alsa_path *p;
+ pa_alsa_element *e;
+
+ pa_assert(state);
+
+ p = state->userdata;
+
+ if (!(e = pa_alsa_element_get(p, state->section, true))) {
+ pa_log("[%s:%u] Enumeration makes no sense in '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ if (pa_streq(state->rvalue, "ignore"))
+ e->enumeration_use = PA_ALSA_ENUMERATION_IGNORE;
+ else if (pa_streq(state->rvalue, "select"))
+ e->enumeration_use = PA_ALSA_ENUMERATION_SELECT;
+ else {
+ pa_log("[%s:%u] Enumeration invalid of '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ return 0;
+}
+
+static int parse_type(pa_config_parser_state *state) {
+ struct device_port_types {
+ const char *name;
+ pa_device_port_type_t type;
+ } device_port_types[] = {
+ { "unknown", PA_DEVICE_PORT_TYPE_UNKNOWN },
+ { "aux", PA_DEVICE_PORT_TYPE_AUX },
+ { "speaker", PA_DEVICE_PORT_TYPE_SPEAKER },
+ { "headphones", PA_DEVICE_PORT_TYPE_HEADPHONES },
+ { "line", PA_DEVICE_PORT_TYPE_LINE },
+ { "mic", PA_DEVICE_PORT_TYPE_MIC },
+ { "headset", PA_DEVICE_PORT_TYPE_HEADSET },
+ { "handset", PA_DEVICE_PORT_TYPE_HANDSET },
+ { "earpiece", PA_DEVICE_PORT_TYPE_EARPIECE },
+ { "spdif", PA_DEVICE_PORT_TYPE_SPDIF },
+ { "hdmi", PA_DEVICE_PORT_TYPE_HDMI },
+ { "tv", PA_DEVICE_PORT_TYPE_TV },
+ { "radio", PA_DEVICE_PORT_TYPE_RADIO },
+ { "video", PA_DEVICE_PORT_TYPE_VIDEO },
+ { "usb", PA_DEVICE_PORT_TYPE_USB },
+ { "bluetooth", PA_DEVICE_PORT_TYPE_BLUETOOTH },
+ { "portable", PA_DEVICE_PORT_TYPE_PORTABLE },
+ { "handsfree", PA_DEVICE_PORT_TYPE_HANDSFREE },
+ { "car", PA_DEVICE_PORT_TYPE_CAR },
+ { "hifi", PA_DEVICE_PORT_TYPE_HIFI },
+ { "phone", PA_DEVICE_PORT_TYPE_PHONE },
+ { "network", PA_DEVICE_PORT_TYPE_NETWORK },
+ { "analog", PA_DEVICE_PORT_TYPE_ANALOG },
+ };
+ pa_alsa_path *path;
+ unsigned int idx;
+
+ path = state->userdata;
+
+ for (idx = 0; idx < PA_ELEMENTSOF(device_port_types); idx++)
+ if (pa_streq(state->rvalue, device_port_types[idx].name)) {
+ path->device_port_type = device_port_types[idx].type;
+ return 0;
+ }
+
+ pa_log("[%s:%u] Invalid value for option 'type': %s", state->filename, state->lineno, state->rvalue);
+ return -1;
+}
+
+static int parse_eld_device(pa_config_parser_state *state) {
+ pa_alsa_path *path;
+ uint32_t eld_device;
+
+ path = state->userdata;
+
+ if (pa_atou(state->rvalue, &eld_device) >= 0) {
+ path->autodetect_eld_device = false;
+ path->eld_device = eld_device;
+ return 0;
+ }
+
+ if (pa_streq(state->rvalue, "auto")) {
+ path->autodetect_eld_device = true;
+ path->eld_device = -1;
+ return 0;
+ }
+
+ pa_log("[%s:%u] Invalid value for option 'eld-device': %s", state->filename, state->lineno, state->rvalue);
+ return -1;
+}
+
+static int option_parse_priority(pa_config_parser_state *state) {
+ pa_alsa_path *p;
+ pa_alsa_option *o;
+ uint32_t prio;
+
+ pa_assert(state);
+
+ p = state->userdata;
+
+ if (!(o = option_get(p, state->section))) {
+ pa_log("[%s:%u] Priority makes no sense in '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ if (pa_atou(state->rvalue, &prio) < 0) {
+ pa_log("[%s:%u] Priority invalid of '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ o->priority = prio;
+ return 0;
+}
+
+static int option_parse_name(pa_config_parser_state *state) {
+ pa_alsa_path *p;
+ pa_alsa_option *o;
+
+ pa_assert(state);
+
+ p = state->userdata;
+
+ if (!(o = option_get(p, state->section))) {
+ pa_log("[%s:%u] Name makes no sense in '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ pa_xfree(o->name);
+ o->name = pa_xstrdup(state->rvalue);
+
+ return 0;
+}
+
+static int element_parse_required(pa_config_parser_state *state) {
+ pa_alsa_path *p;
+ pa_alsa_element *e;
+ pa_alsa_option *o;
+ pa_alsa_jack *j;
+ pa_alsa_required_t req;
+
+ pa_assert(state);
+
+ p = state->userdata;
+
+ e = pa_alsa_element_get(p, state->section, true);
+ o = option_get(p, state->section);
+ j = jack_get(p, state->section);
+ if (!e && !o && !j) {
+ pa_log("[%s:%u] Required makes no sense in '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ if (pa_streq(state->rvalue, "ignore"))
+ req = PA_ALSA_REQUIRED_IGNORE;
+ else if (pa_streq(state->rvalue, "switch") && e)
+ req = PA_ALSA_REQUIRED_SWITCH;
+ else if (pa_streq(state->rvalue, "volume") && e)
+ req = PA_ALSA_REQUIRED_VOLUME;
+ else if (pa_streq(state->rvalue, "enumeration"))
+ req = PA_ALSA_REQUIRED_ENUMERATION;
+ else if (pa_streq(state->rvalue, "any"))
+ req = PA_ALSA_REQUIRED_ANY;
+ else {
+ pa_log("[%s:%u] Required invalid of '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ if (pa_streq(state->lvalue, "required-absent")) {
+ if (e)
+ e->required_absent = req;
+ if (o)
+ o->required_absent = req;
+ if (j)
+ j->required_absent = req;
+ }
+ else if (pa_streq(state->lvalue, "required-any")) {
+ if (e) {
+ e->required_any = req;
+ e->path->has_req_any |= (req != PA_ALSA_REQUIRED_IGNORE);
+ }
+ if (o) {
+ o->required_any = req;
+ o->element->path->has_req_any |= (req != PA_ALSA_REQUIRED_IGNORE);
+ }
+ if (j) {
+ j->required_any = req;
+ j->path->has_req_any |= (req != PA_ALSA_REQUIRED_IGNORE);
+ }
+
+ }
+ else {
+ if (e)
+ e->required = req;
+ if (o)
+ o->required = req;
+ if (j)
+ j->required = req;
+ }
+
+ return 0;
+}
+
+static int element_parse_direction(pa_config_parser_state *state) {
+ pa_alsa_path *p;
+ pa_alsa_element *e;
+
+ pa_assert(state);
+
+ p = state->userdata;
+
+ if (!(e = pa_alsa_element_get(p, state->section, true))) {
+ pa_log("[%s:%u] Direction makes no sense in '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ if (pa_streq(state->rvalue, "playback"))
+ e->direction = PA_ALSA_DIRECTION_OUTPUT;
+ else if (pa_streq(state->rvalue, "capture"))
+ e->direction = PA_ALSA_DIRECTION_INPUT;
+ else {
+ pa_log("[%s:%u] Direction invalid of '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ return 0;
+}
+
+static int element_parse_direction_try_other(pa_config_parser_state *state) {
+ pa_alsa_path *p;
+ pa_alsa_element *e;
+ int yes;
+
+ pa_assert(state);
+
+ p = state->userdata;
+
+ if (!(e = pa_alsa_element_get(p, state->section, true))) {
+ pa_log("[%s:%u] Direction makes no sense in '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ if ((yes = pa_parse_boolean(state->rvalue)) < 0) {
+ pa_log("[%s:%u] Direction invalid of '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ e->direction_try_other = !!yes;
+ return 0;
+}
+
+static int element_parse_volume_limit(pa_config_parser_state *state) {
+ pa_alsa_path *p;
+ pa_alsa_element *e;
+ long volume_limit;
+
+ pa_assert(state);
+
+ p = state->userdata;
+
+ if (!(e = pa_alsa_element_get(p, state->section, true))) {
+ pa_log("[%s:%u] volume-limit makes no sense in '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ if (pa_atol(state->rvalue, &volume_limit) < 0 || volume_limit < 0) {
+ pa_log("[%s:%u] Invalid value for volume-limit", state->filename, state->lineno);
+ return -1;
+ }
+
+ e->volume_limit = volume_limit;
+ return 0;
+}
+
+static unsigned int parse_channel_position(const char *m)
+{
+ pa_channel_position_t p;
+
+ if ((p = pa_channel_position_from_string(m)) == PA_CHANNEL_POSITION_INVALID)
+ return SND_MIXER_SCHN_UNKNOWN;
+
+ return alsa_channel_ids[p];
+}
+
+static pa_channel_position_mask_t parse_mask(const char *m) {
+ pa_channel_position_mask_t v;
+
+ if (pa_streq(m, "all-left"))
+ v = PA_CHANNEL_POSITION_MASK_LEFT;
+ else if (pa_streq(m, "all-right"))
+ v = PA_CHANNEL_POSITION_MASK_RIGHT;
+ else if (pa_streq(m, "all-center"))
+ v = PA_CHANNEL_POSITION_MASK_CENTER;
+ else if (pa_streq(m, "all-front"))
+ v = PA_CHANNEL_POSITION_MASK_FRONT;
+ else if (pa_streq(m, "all-rear"))
+ v = PA_CHANNEL_POSITION_MASK_REAR;
+ else if (pa_streq(m, "all-side"))
+ v = PA_CHANNEL_POSITION_MASK_SIDE_OR_TOP_CENTER;
+ else if (pa_streq(m, "all-top"))
+ v = PA_CHANNEL_POSITION_MASK_TOP;
+ else if (pa_streq(m, "all-no-lfe"))
+ v = PA_CHANNEL_POSITION_MASK_ALL ^ PA_CHANNEL_POSITION_MASK(PA_CHANNEL_POSITION_LFE);
+ else if (pa_streq(m, "all"))
+ v = PA_CHANNEL_POSITION_MASK_ALL;
+ else {
+ pa_channel_position_t p;
+
+ if ((p = pa_channel_position_from_string(m)) == PA_CHANNEL_POSITION_INVALID)
+ return 0;
+
+ v = PA_CHANNEL_POSITION_MASK(p);
+ }
+
+ return v;
+}
+
+static int element_parse_override_map(pa_config_parser_state *state) {
+ pa_alsa_path *p;
+ pa_alsa_element *e;
+ const char *split_state = NULL;
+ char *s;
+ unsigned i = 0;
+ int channel_count = 0;
+ char *n;
+
+ pa_assert(state);
+
+ p = state->userdata;
+
+ if (!(e = pa_alsa_element_get(p, state->section, true))) {
+ pa_log("[%s:%u] Override map makes no sense in '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ s = strstr(state->lvalue, ".");
+ if (s) {
+ pa_atoi(s + 1, &channel_count);
+ if (channel_count < 1 || channel_count > POSITION_MASK_CHANNELS) {
+ pa_log("[%s:%u] Override map index '%s' invalid in '%s'", state->filename, state->lineno, state->lvalue, state->section);
+ return 0;
+ }
+ } else {
+ pa_log("[%s:%u] Invalid override map syntax '%s' in '%s'", state->filename, state->lineno, state->lvalue, state->section);
+ return -1;
+ }
+
+ while ((n = pa_split(state->rvalue, ",", &split_state))) {
+ pa_channel_position_mask_t m;
+ snd_mixer_selem_channel_id_t channel_position;
+
+ if (i >= (unsigned)channel_count) {
+ pa_log("[%s:%u] Invalid override map size (>%d) in '%s'", state->filename, state->lineno, channel_count, state->section);
+ return -1;
+ }
+ channel_position = alsa_channel_positions[i];
+
+ if (!*n)
+ m = 0;
+ else {
+ s = strstr(n, ":");
+ if (s) {
+ *s = '\0';
+ s++;
+ channel_position = parse_channel_position(n);
+ if (channel_position == SND_MIXER_SCHN_UNKNOWN) {
+ pa_log("[%s:%u] Override map position '%s' invalid in '%s'", state->filename, state->lineno, n, state->section);
+ pa_xfree(n);
+ return -1;
+ }
+ }
+ if ((m = parse_mask(s ? s : n)) == 0) {
+ pa_log("[%s:%u] Override map '%s' invalid in '%s'", state->filename, state->lineno, s ? s : n, state->section);
+ pa_xfree(n);
+ return -1;
+ }
+ }
+
+ if (e->masks[channel_position][channel_count-1]) {
+ pa_log("[%s:%u] Override map '%s' duplicate position '%s' in '%s'", state->filename, state->lineno, s ? s : n, snd_mixer_selem_channel_name(channel_position), state->section);
+ pa_xfree(n);
+ return -1;
+ }
+ e->override_map |= (1 << (channel_count - 1));
+ e->masks[channel_position][channel_count-1] = m;
+ pa_xfree(n);
+ i++;
+ }
+
+ return 0;
+}
+
+static int jack_parse_state(pa_config_parser_state *state) {
+ pa_alsa_path *p;
+ pa_alsa_jack *j;
+ pa_available_t pa;
+
+ pa_assert(state);
+
+ p = state->userdata;
+
+ if (!(j = jack_get(p, state->section))) {
+ pa_log("[%s:%u] state makes no sense in '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ if (pa_streq(state->rvalue, "yes"))
+ pa = PA_AVAILABLE_YES;
+ else if (pa_streq(state->rvalue, "no"))
+ pa = PA_AVAILABLE_NO;
+ else if (pa_streq(state->rvalue, "unknown"))
+ pa = PA_AVAILABLE_UNKNOWN;
+ else {
+ pa_log("[%s:%u] state must be 'yes', 'no' or 'unknown' in '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ if (pa_streq(state->lvalue, "state.unplugged"))
+ j->state_unplugged = pa;
+ else {
+ j->state_plugged = pa;
+ pa_assert(pa_streq(state->lvalue, "state.plugged"));
+ }
+
+ return 0;
+}
+
+static int jack_parse_append_pcm_to_name(pa_config_parser_state *state) {
+ pa_alsa_path *path;
+ pa_alsa_jack *jack;
+ int b;
+
+ pa_assert(state);
+
+ path = state->userdata;
+ if (!(jack = jack_get(path, state->section))) {
+ pa_log("[%s:%u] Option 'append_pcm_to_name' not expected in section '%s'",
+ state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ b = pa_parse_boolean(state->rvalue);
+ if (b < 0) {
+ pa_log("[%s:%u] Invalid value for 'append_pcm_to_name': %s", state->filename, state->lineno, state->rvalue);
+ return -1;
+ }
+
+ jack->append_pcm_to_name = b;
+ return 0;
+}
+
+static int element_set_option(pa_alsa_element *e, snd_mixer_t *m, int alsa_idx) {
+ snd_mixer_selem_id_t *sid;
+ snd_mixer_elem_t *me;
+ char buf[64];
+ int r;
+
+ pa_assert(e);
+ pa_assert(m);
+
+ SELEM_INIT(sid, &e->alsa_id);
+ if (!(me = snd_mixer_find_selem(m, sid))) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("Element %s seems to have disappeared.", buf);
+ return -1;
+ }
+
+ if (e->switch_use == PA_ALSA_SWITCH_SELECT) {
+
+ if (e->direction == PA_ALSA_DIRECTION_OUTPUT)
+ r = snd_mixer_selem_set_playback_switch_all(me, alsa_idx);
+ else
+ r = snd_mixer_selem_set_capture_switch_all(me, alsa_idx);
+
+ if (r < 0) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("Failed to set switch of %s: %s", buf, pa_alsa_strerror(errno));
+ }
+
+ } else {
+ pa_assert(e->enumeration_use == PA_ALSA_ENUMERATION_SELECT);
+
+ if ((r = snd_mixer_selem_set_enum_item(me, 0, alsa_idx)) < 0) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("Failed to set enumeration of %s: %s", buf, pa_alsa_strerror(errno));
+ }
+ }
+
+ return r;
+}
+
+static int setting_select(pa_alsa_setting *s, snd_mixer_t *m) {
+ pa_alsa_option *o;
+ uint32_t idx;
+
+ pa_assert(s);
+ pa_assert(m);
+
+ PA_IDXSET_FOREACH(o, s->options, idx)
+ element_set_option(o->element, m, o->alsa_idx);
+
+ return 0;
+}
+
+static int option_verify(pa_alsa_option *o) {
+ static const struct description_map well_known_descriptions[] = {
+ { "input", N_("Input") },
+ { "input-docking", N_("Docking Station Input") },
+ { "input-docking-microphone", N_("Docking Station Microphone") },
+ { "input-docking-linein", N_("Docking Station Line In") },
+ { "input-linein", N_("Line In") },
+ { "input-microphone", N_("Microphone") },
+ { "input-microphone-front", N_("Front Microphone") },
+ { "input-microphone-rear", N_("Rear Microphone") },
+ { "input-microphone-external", N_("External Microphone") },
+ { "input-microphone-internal", N_("Internal Microphone") },
+ { "input-radio", N_("Radio") },
+ { "input-video", N_("Video") },
+ { "input-agc-on", N_("Automatic Gain Control") },
+ { "input-agc-off", N_("No Automatic Gain Control") },
+ { "input-boost-on", N_("Boost") },
+ { "input-boost-off", N_("No Boost") },
+ { "output-amplifier-on", N_("Amplifier") },
+ { "output-amplifier-off", N_("No Amplifier") },
+ { "output-bass-boost-on", N_("Bass Boost") },
+ { "output-bass-boost-off", N_("No Bass Boost") },
+ { "output-speaker", N_("Speaker") },
+ { "output-headphones", N_("Headphones") }
+ };
+ char buf[64];
+
+ pa_assert(o);
+
+ if (!o->name) {
+ pa_log("No name set for option %s", o->alsa_name);
+ return -1;
+ }
+
+ if (o->element->enumeration_use != PA_ALSA_ENUMERATION_SELECT &&
+ o->element->switch_use != PA_ALSA_SWITCH_SELECT) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &o->element->alsa_id);
+ pa_log("Element %s of option %s not set for select.", buf, o->name);
+ return -1;
+ }
+
+ if (o->element->switch_use == PA_ALSA_SWITCH_SELECT &&
+ !pa_streq(o->alsa_name, "on") &&
+ !pa_streq(o->alsa_name, "off")) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &o->element->alsa_id);
+ pa_log("Switch %s options need be named off or on ", buf);
+ return -1;
+ }
+
+ if (!o->description)
+ o->description = pa_xstrdup(lookup_description(o->name,
+ well_known_descriptions,
+ PA_ELEMENTSOF(well_known_descriptions)));
+ if (!o->description)
+ o->description = pa_xstrdup(o->name);
+
+ return 0;
+}
+
+static int element_verify(pa_alsa_element *e) {
+ pa_alsa_option *o;
+ char buf[64];
+
+ pa_assert(e);
+
+// pa_log_debug("Element %s, path %s: r=%d, r-any=%d, r-abs=%d", e->alsa_name, e->path->name, e->required, e->required_any, e->required_absent);
+ if ((e->required != PA_ALSA_REQUIRED_IGNORE && e->required == e->required_absent) ||
+ (e->required_any != PA_ALSA_REQUIRED_IGNORE && e->required_any == e->required_absent) ||
+ (e->required_absent == PA_ALSA_REQUIRED_ANY && e->required_any != PA_ALSA_REQUIRED_IGNORE) ||
+ (e->required_absent == PA_ALSA_REQUIRED_ANY && e->required != PA_ALSA_REQUIRED_IGNORE)) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log("Element %s cannot be required and absent at the same time.", buf);
+ return -1;
+ }
+
+ if (e->switch_use == PA_ALSA_SWITCH_SELECT && e->enumeration_use == PA_ALSA_ENUMERATION_SELECT) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log("Element %s cannot set select for both switch and enumeration.", buf);
+ return -1;
+ }
+
+ PA_LLIST_FOREACH(o, e->options)
+ if (option_verify(o) < 0)
+ return -1;
+
+ return 0;
+}
+
+static int path_verify(pa_alsa_path *p) {
+ static const struct description2_map well_known_descriptions[] = {
+ { "analog-input", N_("Analog Input"), PA_DEVICE_PORT_TYPE_ANALOG },
+ { "analog-input-microphone", N_("Microphone"), PA_DEVICE_PORT_TYPE_MIC },
+ { "analog-input-microphone-front", N_("Front Microphone"), PA_DEVICE_PORT_TYPE_MIC },
+ { "analog-input-microphone-rear", N_("Rear Microphone"), PA_DEVICE_PORT_TYPE_MIC },
+ { "analog-input-microphone-dock", N_("Dock Microphone"), PA_DEVICE_PORT_TYPE_MIC },
+ { "analog-input-microphone-internal", N_("Internal Microphone"), PA_DEVICE_PORT_TYPE_MIC },
+ { "analog-input-microphone-headset", N_("Headset Microphone"), PA_DEVICE_PORT_TYPE_HEADSET },
+ { "analog-input-linein", N_("Line In"), PA_DEVICE_PORT_TYPE_LINE },
+ { "analog-input-radio", N_("Radio"), PA_DEVICE_PORT_TYPE_RADIO },
+ { "analog-input-video", N_("Video"), PA_DEVICE_PORT_TYPE_VIDEO },
+ { "analog-output", N_("Analog Output"), PA_DEVICE_PORT_TYPE_ANALOG },
+ { "analog-output-headphones", N_("Headphones"), PA_DEVICE_PORT_TYPE_HEADPHONES },
+ { "analog-output-headphones-2", N_("Headphones 2"), PA_DEVICE_PORT_TYPE_HEADPHONES },
+ { "analog-output-headphones-mono", N_("Headphones Mono Output"), PA_DEVICE_PORT_TYPE_HEADPHONES },
+ { "analog-output-lineout", N_("Line Out"), PA_DEVICE_PORT_TYPE_LINE },
+ { "analog-output-mono", N_("Analog Mono Output"), PA_DEVICE_PORT_TYPE_ANALOG },
+ { "analog-output-speaker", N_("Speakers"), PA_DEVICE_PORT_TYPE_SPEAKER },
+ { "hdmi-output", N_("HDMI / DisplayPort"), PA_DEVICE_PORT_TYPE_HDMI },
+ { "iec958-stereo-output", N_("Digital Output (S/PDIF)"), PA_DEVICE_PORT_TYPE_SPDIF },
+ { "iec958-stereo-input", N_("Digital Input (S/PDIF)"), PA_DEVICE_PORT_TYPE_SPDIF },
+ { "multichannel-input", N_("Multichannel Input"), PA_DEVICE_PORT_TYPE_LINE },
+ { "multichannel-output", N_("Multichannel Output"), PA_DEVICE_PORT_TYPE_LINE },
+ { "steelseries-arctis-output-game-common", N_("Game Output"), PA_DEVICE_PORT_TYPE_HEADSET },
+ { "steelseries-arctis-output-chat-common", N_("Chat Output"), PA_DEVICE_PORT_TYPE_HEADSET },
+ };
+
+ pa_alsa_element *e;
+ const char *key = p->description_key ? p->description_key : p->name;
+ const struct description2_map *map = lookup_description2(key,
+ well_known_descriptions,
+ PA_ELEMENTSOF(well_known_descriptions));
+
+ pa_assert(p);
+
+ PA_LLIST_FOREACH(e, p->elements)
+ if (element_verify(e) < 0)
+ return -1;
+
+ if (map) {
+ if (p->device_port_type == PA_DEVICE_PORT_TYPE_UNKNOWN)
+ p->device_port_type = map->type;
+ if (!p->description)
+ p->description = pa_xstrdup(map->description);
+ }
+
+ if (!p->description) {
+ if (p->description_key)
+ pa_log_warn("Path %s: Unrecognized description key: %s", p->name, p->description_key);
+
+ p->description = pa_xstrdup(p->name);
+ }
+
+ return 0;
+}
+
+static const char *get_default_paths_dir(void) {
+#ifdef HAVE_RUNNING_FROM_BUILD_TREE
+ if (pa_run_from_build_tree())
+ return PA_SRCDIR "/modules/alsa/mixer/paths/";
+ else
+#endif
+ return PA_ALSA_PATHS_DIR;
+}
+
+pa_alsa_path* pa_alsa_path_new(const char *paths_dir, const char *fname, pa_alsa_direction_t direction) {
+ pa_alsa_path *p;
+ char *fn;
+ int r;
+ const char *n;
+ bool mute_during_activation = false;
+
+ pa_config_item items[] = {
+ /* [General] */
+ { "priority", pa_config_parse_unsigned, NULL, "General" },
+ { "description-key", pa_config_parse_string, NULL, "General" },
+ { "description", pa_config_parse_string, NULL, "General" },
+ { "mute-during-activation", pa_config_parse_bool, NULL, "General" },
+ { "type", parse_type, NULL, "General" },
+ { "eld-device", parse_eld_device, NULL, "General" },
+
+ /* [Option ...] */
+ { "priority", option_parse_priority, NULL, NULL },
+ { "name", option_parse_name, NULL, NULL },
+
+ /* [Jack ...] */
+ { "state.plugged", jack_parse_state, NULL, NULL },
+ { "state.unplugged", jack_parse_state, NULL, NULL },
+ { "append-pcm-to-name", jack_parse_append_pcm_to_name, NULL, NULL },
+
+ /* [Element ...] */
+ { "switch", element_parse_switch, NULL, NULL },
+ { "volume", element_parse_volume, NULL, NULL },
+ { "enumeration", element_parse_enumeration, NULL, NULL },
+ { "override-map.1", element_parse_override_map, NULL, NULL },
+ { "override-map.2", element_parse_override_map, NULL, NULL },
+ { "override-map.3", element_parse_override_map, NULL, NULL },
+ { "override-map.4", element_parse_override_map, NULL, NULL },
+ { "override-map.5", element_parse_override_map, NULL, NULL },
+ { "override-map.6", element_parse_override_map, NULL, NULL },
+ { "override-map.7", element_parse_override_map, NULL, NULL },
+ { "override-map.8", element_parse_override_map, NULL, NULL },
+#if POSITION_MASK_CHANNELS > 8
+#error "Add override-map.9+ definitions"
+#endif
+ /* ... later on we might add override-map.3 and so on here ... */
+ { "required", element_parse_required, NULL, NULL },
+ { "required-any", element_parse_required, NULL, NULL },
+ { "required-absent", element_parse_required, NULL, NULL },
+ { "direction", element_parse_direction, NULL, NULL },
+ { "direction-try-other", element_parse_direction_try_other, NULL, NULL },
+ { "volume-limit", element_parse_volume_limit, NULL, NULL },
+ { NULL, NULL, NULL, NULL }
+ };
+
+ pa_assert(fname);
+
+ p = pa_xnew0(pa_alsa_path, 1);
+ n = pa_path_get_filename(fname);
+ p->name = pa_xstrndup(n, strcspn(n, "."));
+ p->proplist = pa_proplist_new();
+ p->direction = direction;
+ p->eld_device = -1;
+
+ items[0].data = &p->priority;
+ items[1].data = &p->description_key;
+ items[2].data = &p->description;
+ items[3].data = &mute_during_activation;
+
+ if (!paths_dir)
+ paths_dir = get_default_paths_dir();
+
+ fn = pa_maybe_prefix_path(fname, paths_dir);
+
+ r = pa_config_parse(fn, NULL, items, p->proplist, false, p);
+ pa_xfree(fn);
+
+ if (r < 0)
+ goto fail;
+
+ p->mute_during_activation = mute_during_activation;
+
+ if (path_verify(p) < 0)
+ goto fail;
+
+ return p;
+
+fail:
+ pa_alsa_path_free(p);
+ return NULL;
+}
+
+pa_alsa_path *pa_alsa_path_synthesize(const char *element, pa_alsa_direction_t direction) {
+ pa_alsa_path *p;
+ pa_alsa_element *e;
+ char *name;
+ int index;
+
+ pa_assert(element);
+
+ name = alloca(strlen(element) + 1);
+ if (alsa_id_decode(element, name, &index))
+ return NULL;
+
+ p = pa_xnew0(pa_alsa_path, 1);
+ p->name = pa_xstrdup(element);
+ p->direction = direction;
+ p->proplist = pa_proplist_new();
+
+ e = pa_xnew0(pa_alsa_element, 1);
+ e->path = p;
+ e->alsa_id.name = pa_xstrdup(name);
+ e->alsa_id.index = index;
+ e->direction = direction;
+ e->volume_limit = -1;
+
+ e->switch_use = PA_ALSA_SWITCH_MUTE;
+ e->volume_use = PA_ALSA_VOLUME_MERGE;
+
+ PA_LLIST_PREPEND(pa_alsa_element, p->elements, e);
+ p->last_element = e;
+ return p;
+}
+
+static bool element_drop_unsupported(pa_alsa_element *e) {
+ pa_alsa_option *o, *n;
+
+ pa_assert(e);
+
+ for (o = e->options; o; o = n) {
+ n = o->next;
+
+ if (o->alsa_idx < 0) {
+ PA_LLIST_REMOVE(pa_alsa_option, e->options, o);
+ option_free(o);
+ }
+ }
+
+ return
+ e->switch_use != PA_ALSA_SWITCH_IGNORE ||
+ e->volume_use != PA_ALSA_VOLUME_IGNORE ||
+ e->enumeration_use != PA_ALSA_ENUMERATION_IGNORE;
+}
+
+static void path_drop_unsupported(pa_alsa_path *p) {
+ pa_alsa_element *e, *n;
+
+ pa_assert(p);
+
+ for (e = p->elements; e; e = n) {
+ n = e->next;
+
+ if (!element_drop_unsupported(e)) {
+ PA_LLIST_REMOVE(pa_alsa_element, p->elements, e);
+ element_free(e);
+ }
+ }
+}
+
+static void path_make_options_unique(pa_alsa_path *p) {
+ pa_alsa_element *e;
+ pa_alsa_option *o, *u;
+
+ PA_LLIST_FOREACH(e, p->elements) {
+ PA_LLIST_FOREACH(o, e->options) {
+ unsigned i;
+ char *m;
+
+ for (u = o->next; u; u = u->next)
+ if (pa_streq(u->name, o->name))
+ break;
+
+ if (!u)
+ continue;
+
+ m = pa_xstrdup(o->name);
+
+ /* OK, this name is not unique, hence let's rename */
+ for (i = 1, u = o; u; u = u->next) {
+ char *nn, *nd;
+
+ if (!pa_streq(u->name, m))
+ continue;
+
+ nn = pa_sprintf_malloc("%s-%u", m, i);
+ pa_xfree(u->name);
+ u->name = nn;
+
+ nd = pa_sprintf_malloc("%s %u", u->description, i);
+ pa_xfree(u->description);
+ u->description = nd;
+
+ i++;
+ }
+
+ pa_xfree(m);
+ }
+ }
+}
+
+static bool element_create_settings(pa_alsa_element *e, pa_alsa_setting *template) {
+ pa_alsa_option *o;
+
+ for (; e; e = e->next)
+ if (e->switch_use == PA_ALSA_SWITCH_SELECT ||
+ e->enumeration_use == PA_ALSA_ENUMERATION_SELECT)
+ break;
+
+ if (!e)
+ return false;
+
+ for (o = e->options; o; o = o->next) {
+ pa_alsa_setting *s;
+
+ if (template) {
+ s = pa_xnewdup(pa_alsa_setting, template, 1);
+ s->options = pa_idxset_copy(template->options, NULL);
+ s->name = pa_sprintf_malloc("%s+%s", template->name, o->name);
+ s->description =
+ (template->description[0] && o->description[0])
+ ? pa_sprintf_malloc("%s / %s", template->description, o->description)
+ : (template->description[0]
+ ? pa_xstrdup(template->description)
+ : pa_xstrdup(o->description));
+
+ s->priority = PA_MAX(template->priority, o->priority);
+ } else {
+ s = pa_xnew0(pa_alsa_setting, 1);
+ s->options = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
+ s->name = pa_xstrdup(o->name);
+ s->description = pa_xstrdup(o->description);
+ s->priority = o->priority;
+ }
+
+ pa_idxset_put(s->options, o, NULL);
+
+ if (element_create_settings(e->next, s))
+ /* This is not a leaf, so let's get rid of it */
+ setting_free(s);
+ else {
+ /* This is a leaf, so let's add it */
+ PA_LLIST_INSERT_AFTER(pa_alsa_setting, e->path->settings, e->path->last_setting, s);
+
+ e->path->last_setting = s;
+ }
+ }
+
+ return true;
+}
+
+static void path_create_settings(pa_alsa_path *p) {
+ pa_assert(p);
+
+ element_create_settings(p->elements, NULL);
+}
+
+int pa_alsa_path_probe(pa_alsa_path *p, pa_alsa_mapping *mapping, snd_mixer_t *m, bool ignore_dB) {
+ pa_alsa_element *e;
+ pa_alsa_jack *j;
+ double min_dB[PA_CHANNEL_POSITION_MAX], max_dB[PA_CHANNEL_POSITION_MAX];
+ pa_channel_position_t t;
+ pa_channel_position_mask_t path_volume_channels = 0;
+ bool min_dB_set, max_dB_set;
+ char buf[64];
+
+ pa_assert(p);
+ pa_assert(m);
+
+ if (p->probed)
+ return p->supported ? 0 : -1;
+ p->probed = true;
+
+ pa_zero(min_dB);
+ pa_zero(max_dB);
+
+ pa_log_debug("Probing path '%s'", p->name);
+
+ PA_LLIST_FOREACH(j, p->jacks) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &j->alsa_id);
+ if (jack_probe(j, mapping, m) < 0) {
+ p->supported = false;
+ pa_log_debug("Probe of jack %s failed.", buf);
+ return -1;
+ }
+ pa_log_debug("Probe of jack %s succeeded (%s)", buf, j->has_control ? "found!" : "not found");
+ }
+
+ PA_LLIST_FOREACH(e, p->elements) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ if (element_probe(e, m) < 0) {
+ p->supported = false;
+ pa_log_debug("Probe of element %s failed.", buf);
+ return -1;
+ }
+ pa_log_debug("Probe of element %s succeeded (volume=%d, switch=%d, enumeration=%d, has_dB=%d).", buf, e->volume_use, e->switch_use, e->enumeration_use, e->has_dB);
+
+ if (ignore_dB)
+ e->has_dB = false;
+
+ if (e->volume_use == PA_ALSA_VOLUME_MERGE) {
+
+ if (!p->has_volume) {
+ p->min_volume = e->min_volume;
+ p->max_volume = e->max_volume;
+ }
+
+ if (e->has_dB) {
+ if (!p->has_volume) {
+ for (t = 0; t < PA_CHANNEL_POSITION_MAX; t++)
+ if (PA_CHANNEL_POSITION_MASK(t) & e->merged_mask) {
+ min_dB[t] = e->min_dB;
+ max_dB[t] = e->max_dB;
+ path_volume_channels |= PA_CHANNEL_POSITION_MASK(t);
+ }
+
+ p->has_dB = true;
+ } else {
+
+ if (p->has_dB) {
+ for (t = 0; t < PA_CHANNEL_POSITION_MAX; t++)
+ if (PA_CHANNEL_POSITION_MASK(t) & e->merged_mask) {
+ min_dB[t] += e->min_dB;
+ max_dB[t] += e->max_dB;
+ path_volume_channels |= PA_CHANNEL_POSITION_MASK(t);
+ }
+ } else {
+ /* Hmm, there's another element before us
+ * which cannot do dB volumes, so we we need
+ * to 'neutralize' this slider */
+ e->volume_use = PA_ALSA_VOLUME_ZERO;
+ pa_log_info("Zeroing volume of %s on path '%s'", buf, p->name);
+ }
+ }
+ } else if (p->has_volume) {
+ /* We can't use this volume, so let's ignore it */
+ e->volume_use = PA_ALSA_VOLUME_IGNORE;
+ pa_log_info("Ignoring volume of %s on path '%s' (missing dB info)", buf, p->name);
+ }
+ p->has_volume = true;
+ }
+
+ if (e->switch_use == PA_ALSA_SWITCH_MUTE)
+ p->has_mute = true;
+ }
+
+ if (p->has_req_any && !p->req_any_present) {
+ p->supported = false;
+ pa_log_debug("Skipping path '%s', none of required-any elements preset.", p->name);
+ return -1;
+ }
+
+ path_drop_unsupported(p);
+ path_make_options_unique(p);
+ path_create_settings(p);
+
+ p->supported = true;
+
+ p->min_dB = INFINITY;
+ min_dB_set = false;
+ p->max_dB = -INFINITY;
+ max_dB_set = false;
+
+ for (t = 0; t < PA_CHANNEL_POSITION_MAX; t++) {
+ if (path_volume_channels & PA_CHANNEL_POSITION_MASK(t)) {
+ if (p->min_dB > min_dB[t]) {
+ p->min_dB = min_dB[t];
+ min_dB_set = true;
+ }
+
+ if (p->max_dB < max_dB[t]) {
+ p->max_dB = max_dB[t];
+ max_dB_set = true;
+ }
+ }
+ }
+
+ /* this is probably a wrong prediction, but it should be safe */
+ if (!min_dB_set)
+ p->min_dB = -INFINITY;
+ if (!max_dB_set)
+ p->max_dB = 0;
+
+ return 0;
+}
+
+void pa_alsa_setting_dump(pa_alsa_setting *s) {
+ pa_assert(s);
+
+ pa_log_debug("Setting %s (%s) priority=%u",
+ s->name,
+ pa_strnull(s->description),
+ s->priority);
+}
+
+void pa_alsa_jack_dump(pa_alsa_jack *j) {
+ pa_assert(j);
+
+ pa_log_debug("Jack %s, alsa_name='%s', index='%d', detection %s", j->name, j->alsa_id.name, j->alsa_id.index, j->has_control ? "possible" : "unavailable");
+}
+
+void pa_alsa_option_dump(pa_alsa_option *o) {
+ pa_assert(o);
+
+ pa_log_debug("Option %s (%s/%s) index=%i, priority=%u",
+ o->alsa_name,
+ pa_strnull(o->name),
+ pa_strnull(o->description),
+ o->alsa_idx,
+ o->priority);
+}
+
+void pa_alsa_element_dump(pa_alsa_element *e) {
+ char buf[64];
+
+ pa_alsa_option *o;
+ pa_assert(e);
+
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_debug("Element %s, direction=%i, switch=%i, volume=%i, volume_limit=%li, enumeration=%i, required=%i, required_any=%i, required_absent=%i, mask=0x%llx, n_channels=%u, override_map=%02x",
+ buf,
+ e->direction,
+ e->switch_use,
+ e->volume_use,
+ e->volume_limit,
+ e->enumeration_use,
+ e->required,
+ e->required_any,
+ e->required_absent,
+ (long long unsigned) e->merged_mask,
+ e->n_channels,
+ e->override_map);
+
+ PA_LLIST_FOREACH(o, e->options)
+ pa_alsa_option_dump(o);
+}
+
+void pa_alsa_path_dump(pa_alsa_path *p) {
+ pa_alsa_element *e;
+ pa_alsa_jack *j;
+ pa_alsa_setting *s;
+ pa_assert(p);
+
+ pa_log_debug("Path %s (%s), direction=%i, priority=%u, probed=%s, supported=%s, has_mute=%s, has_volume=%s, "
+ "has_dB=%s, min_volume=%li, max_volume=%li, min_dB=%g, max_dB=%g",
+ p->name,
+ pa_strnull(p->description),
+ p->direction,
+ p->priority,
+ pa_yes_no(p->probed),
+ pa_yes_no(p->supported),
+ pa_yes_no(p->has_mute),
+ pa_yes_no(p->has_volume),
+ pa_yes_no(p->has_dB),
+ p->min_volume, p->max_volume,
+ p->min_dB, p->max_dB);
+
+ PA_LLIST_FOREACH(e, p->elements)
+ pa_alsa_element_dump(e);
+
+ PA_LLIST_FOREACH(j, p->jacks)
+ pa_alsa_jack_dump(j);
+
+ PA_LLIST_FOREACH(s, p->settings)
+ pa_alsa_setting_dump(s);
+}
+
+static void element_set_callback(pa_alsa_element *e, snd_mixer_t *m, snd_mixer_elem_callback_t cb, void *userdata) {
+ snd_mixer_selem_id_t *sid;
+ snd_mixer_elem_t *me;
+ char buf[64];
+
+ pa_assert(e);
+ pa_assert(m);
+ pa_assert(cb);
+
+ SELEM_INIT(sid, &e->alsa_id);
+ if (!(me = snd_mixer_find_selem(m, sid))) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &e->alsa_id);
+ pa_log_warn("Element %s seems to have disappeared.", buf);
+ return;
+ }
+
+ snd_mixer_elem_set_callback(me, cb);
+ snd_mixer_elem_set_callback_private(me, userdata);
+}
+
+void pa_alsa_path_set_callback(pa_alsa_path *p, snd_mixer_t *m, snd_mixer_elem_callback_t cb, void *userdata) {
+ pa_alsa_element *e;
+
+ pa_assert(p);
+ pa_assert(m);
+ pa_assert(cb);
+
+ PA_LLIST_FOREACH(e, p->elements)
+ element_set_callback(e, m, cb, userdata);
+}
+
+void pa_alsa_path_set_set_callback(pa_alsa_path_set *ps, snd_mixer_t *m, snd_mixer_elem_callback_t cb, void *userdata) {
+ pa_alsa_path *p;
+ void *state;
+
+ pa_assert(ps);
+ pa_assert(m);
+ pa_assert(cb);
+
+ PA_HASHMAP_FOREACH(p, ps->paths, state)
+ pa_alsa_path_set_callback(p, m, cb, userdata);
+}
+
+static pa_alsa_path *profile_set_get_path(pa_alsa_profile_set *ps, const char *path_name) {
+ pa_alsa_path *path;
+
+ pa_assert(ps);
+ pa_assert(path_name);
+
+ if ((path = pa_hashmap_get(ps->output_paths, path_name)))
+ return path;
+
+ return pa_hashmap_get(ps->input_paths, path_name);
+}
+
+static void profile_set_add_path(pa_alsa_profile_set *ps, pa_alsa_path *path) {
+ pa_assert(ps);
+ pa_assert(path);
+
+ switch (path->direction) {
+ case PA_ALSA_DIRECTION_OUTPUT:
+ pa_assert_se(pa_hashmap_put(ps->output_paths, path->name, path) >= 0);
+ break;
+
+ case PA_ALSA_DIRECTION_INPUT:
+ pa_assert_se(pa_hashmap_put(ps->input_paths, path->name, path) >= 0);
+ break;
+
+ default:
+ pa_assert_not_reached();
+ }
+}
+
+pa_alsa_path_set *pa_alsa_path_set_new(pa_alsa_mapping *m, pa_alsa_direction_t direction, const char *paths_dir) {
+ pa_alsa_path_set *ps;
+ char **pn = NULL, **en = NULL, **ie;
+ pa_alsa_decibel_fix *db_fix;
+ void *state, *state2;
+ char name[64];
+ int index;
+
+ pa_assert(m);
+ pa_assert(m->profile_set);
+ pa_assert(m->profile_set->decibel_fixes);
+ pa_assert(direction == PA_ALSA_DIRECTION_OUTPUT || direction == PA_ALSA_DIRECTION_INPUT);
+
+ if (m->direction != PA_ALSA_DIRECTION_ANY && m->direction != direction)
+ return NULL;
+
+ ps = pa_xnew0(pa_alsa_path_set, 1);
+ ps->direction = direction;
+ ps->paths = pa_hashmap_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
+
+ if (direction == PA_ALSA_DIRECTION_OUTPUT)
+ pn = m->output_path_names;
+ else
+ pn = m->input_path_names;
+
+ if (pn) {
+ char **in;
+
+ for (in = pn; *in; in++) {
+ pa_alsa_path *p = NULL;
+ bool duplicate = false;
+ char **kn;
+
+ for (kn = pn; kn < in; kn++)
+ if (pa_streq(*kn, *in)) {
+ duplicate = true;
+ break;
+ }
+
+ if (duplicate)
+ continue;
+
+ p = profile_set_get_path(m->profile_set, *in);
+
+ if (p && p->direction != direction) {
+ pa_log("Configuration error: Path %s is used both as an input and as an output path.", p->name);
+ goto fail;
+ }
+
+ if (!p) {
+ char *fn = pa_sprintf_malloc("%s.conf", *in);
+ p = pa_alsa_path_new(paths_dir, fn, direction);
+ pa_xfree(fn);
+ if (p)
+ profile_set_add_path(m->profile_set, p);
+ }
+
+ if (p)
+ pa_hashmap_put(ps->paths, p, p);
+
+ }
+
+ goto finish;
+ }
+
+ if (direction == PA_ALSA_DIRECTION_OUTPUT)
+ en = m->output_element;
+ else
+ en = m->input_element;
+
+ if (!en)
+ goto fail;
+
+ for (ie = en; *ie; ie++) {
+ char **je;
+ pa_alsa_path *p;
+
+ p = pa_alsa_path_synthesize(*ie, direction);
+
+ /* Mark all other passed elements for require-absent */
+ for (je = en; *je; je++) {
+ pa_alsa_element *e;
+
+ if (je == ie)
+ continue;
+
+ if (strlen(*je) + 1 >= sizeof(name)) {
+ pa_log("Element identifier %s is too long!", *je);
+ continue;
+ }
+
+ if (alsa_id_decode(*je, name, &index))
+ continue;
+
+ e = pa_xnew0(pa_alsa_element, 1);
+ e->path = p;
+ e->alsa_id.name = pa_xstrdup(name);
+ e->alsa_id.index = index;
+ e->direction = direction;
+ e->required_absent = PA_ALSA_REQUIRED_ANY;
+ e->volume_limit = -1;
+
+ PA_LLIST_INSERT_AFTER(pa_alsa_element, p->elements, p->last_element, e);
+ p->last_element = e;
+ }
+
+ pa_hashmap_put(ps->paths, *ie, p);
+ }
+
+finish:
+ /* Assign decibel fixes to elements. */
+ PA_HASHMAP_FOREACH(db_fix, m->profile_set->decibel_fixes, state) {
+ pa_alsa_path *p;
+
+ PA_HASHMAP_FOREACH(p, ps->paths, state2) {
+ pa_alsa_element *e;
+
+ PA_LLIST_FOREACH(e, p->elements) {
+ if (e->volume_use != PA_ALSA_VOLUME_IGNORE && pa_streq(db_fix->name, e->alsa_id.name) &&
+ db_fix->index == e->alsa_id.index) {
+ /* The profile set that contains the dB fix may be freed
+ * before the element, so we have to copy the dB fix
+ * object. */
+ e->db_fix = pa_xnewdup(pa_alsa_decibel_fix, db_fix, 1);
+ e->db_fix->profile_set = NULL;
+ e->db_fix->name = pa_xstrdup(db_fix->name);
+ e->db_fix->db_values = pa_xmemdup(db_fix->db_values, (db_fix->max_step - db_fix->min_step + 1) * sizeof(long));
+ }
+ }
+ }
+ }
+
+ return ps;
+
+fail:
+ if (ps)
+ pa_alsa_path_set_free(ps);
+
+ return NULL;
+}
+
+void pa_alsa_path_set_dump(pa_alsa_path_set *ps) {
+ pa_alsa_path *p;
+ void *state;
+ pa_assert(ps);
+
+ pa_log_debug("Path Set %p, direction=%i",
+ (void*) ps,
+ ps->direction);
+
+ PA_HASHMAP_FOREACH(p, ps->paths, state)
+ pa_alsa_path_dump(p);
+}
+
+static bool options_have_option(pa_alsa_option *options, const char *alsa_name) {
+ pa_alsa_option *o;
+
+ pa_assert(options);
+ pa_assert(alsa_name);
+
+ PA_LLIST_FOREACH(o, options) {
+ if (pa_streq(o->alsa_name, alsa_name))
+ return true;
+ }
+ return false;
+}
+
+static bool enumeration_is_subset(pa_alsa_option *a_options, pa_alsa_option *b_options) {
+ pa_alsa_option *oa, *ob;
+
+ if (!a_options) return true;
+ if (!b_options) return false;
+
+ /* If there is an option A offers that B does not, then A is not a subset of B. */
+ PA_LLIST_FOREACH(oa, a_options) {
+ bool found = false;
+ PA_LLIST_FOREACH(ob, b_options) {
+ if (pa_streq(oa->alsa_name, ob->alsa_name)) {
+ found = true;
+ break;
+ }
+ }
+ if (!found)
+ return false;
+ }
+ return true;
+}
+
+/**
+ * Compares two elements to see if a is a subset of b
+ */
+static bool element_is_subset(pa_alsa_element *a, pa_alsa_element *b, snd_mixer_t *m) {
+ char buf[64];
+
+ pa_assert(a);
+ pa_assert(b);
+ pa_assert(m);
+
+ /* General rules:
+ * Every state is a subset of itself (with caveats for volume_limits and options)
+ * IGNORE is a subset of every other state */
+
+ /* Check the volume_use */
+ if (a->volume_use != PA_ALSA_VOLUME_IGNORE) {
+
+ /* "Constant" is subset of "Constant" only when their constant values are equal */
+ if (a->volume_use == PA_ALSA_VOLUME_CONSTANT && b->volume_use == PA_ALSA_VOLUME_CONSTANT && a->constant_volume != b->constant_volume)
+ return false;
+
+ /* Different volume uses when b is not "Merge" means we are definitely not a subset */
+ if (a->volume_use != b->volume_use && b->volume_use != PA_ALSA_VOLUME_MERGE)
+ return false;
+
+ /* "Constant" is a subset of "Merge", if there is not a "volume-limit" in "Merge" below the actual constant.
+ * "Zero" and "Off" are just special cases of "Constant" when comparing to "Merge"
+ * "Merge" with a "volume-limit" is a subset of "Merge" without a "volume-limit" or with a higher "volume-limit" */
+ if (b->volume_use == PA_ALSA_VOLUME_MERGE && b->volume_limit >= 0) {
+ long a_limit;
+
+ if (a->volume_use == PA_ALSA_VOLUME_CONSTANT)
+ a_limit = a->constant_volume;
+ else if (a->volume_use == PA_ALSA_VOLUME_ZERO) {
+ long dB = 0;
+
+ if (a->db_fix) {
+ int rounding = (a->direction == PA_ALSA_DIRECTION_OUTPUT ? +1 : -1);
+ a_limit = decibel_fix_get_step(a->db_fix, &dB, rounding);
+ } else {
+ snd_mixer_selem_id_t *sid;
+ snd_mixer_elem_t *me;
+
+ SELEM_INIT(sid, &a->alsa_id);
+ if (!(me = snd_mixer_find_selem(m, sid))) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &a->alsa_id);
+ pa_log_warn("Element %s seems to have disappeared.", buf);
+ return false;
+ }
+
+ if (a->direction == PA_ALSA_DIRECTION_OUTPUT) {
+ if (snd_mixer_selem_ask_playback_dB_vol(me, dB, +1, &a_limit) < 0)
+ return false;
+ } else {
+ if (snd_mixer_selem_ask_capture_dB_vol(me, dB, -1, &a_limit) < 0)
+ return false;
+ }
+ }
+ } else if (a->volume_use == PA_ALSA_VOLUME_OFF)
+ a_limit = a->min_volume;
+ else if (a->volume_use == PA_ALSA_VOLUME_MERGE)
+ a_limit = a->volume_limit;
+ else
+ pa_assert_not_reached();
+
+ if (a_limit > b->volume_limit)
+ return false;
+ }
+
+ if (a->volume_use == PA_ALSA_VOLUME_MERGE) {
+ int s;
+ /* If override-maps are different, they're not subsets */
+ if (a->n_channels != b->n_channels)
+ return false;
+ for (s = 0; s <= SND_MIXER_SCHN_LAST; s++)
+ if (a->masks[s][a->n_channels-1] != b->masks[s][b->n_channels-1]) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &a->alsa_id);
+ pa_log_debug("Element %s is not a subset - mask a: 0x%" PRIx64 ", mask b: 0x%" PRIx64 ", at channel %d",
+ buf, a->masks[s][a->n_channels-1], b->masks[s][b->n_channels-1], s);
+ return false;
+ }
+ }
+ }
+
+ if (a->switch_use != PA_ALSA_SWITCH_IGNORE) {
+ /* "On" is a subset of "Mute".
+ * "Off" is a subset of "Mute".
+ * "On" is a subset of "Select", if there is an "Option:On" in B.
+ * "Off" is a subset of "Select", if there is an "Option:Off" in B.
+ * "Select" is a subset of "Select", if they have the same options (is this always true?). */
+
+ if (a->switch_use != b->switch_use) {
+
+ if (a->switch_use == PA_ALSA_SWITCH_SELECT || a->switch_use == PA_ALSA_SWITCH_MUTE
+ || b->switch_use == PA_ALSA_SWITCH_OFF || b->switch_use == PA_ALSA_SWITCH_ON)
+ return false;
+
+ if (b->switch_use == PA_ALSA_SWITCH_SELECT) {
+ if (a->switch_use == PA_ALSA_SWITCH_ON) {
+ if (!options_have_option(b->options, "on"))
+ return false;
+ } else if (a->switch_use == PA_ALSA_SWITCH_OFF) {
+ if (!options_have_option(b->options, "off"))
+ return false;
+ }
+ }
+ } else if (a->switch_use == PA_ALSA_SWITCH_SELECT) {
+ if (!enumeration_is_subset(a->options, b->options))
+ return false;
+ }
+ }
+
+ if (a->enumeration_use != PA_ALSA_ENUMERATION_IGNORE) {
+ if (b->enumeration_use == PA_ALSA_ENUMERATION_IGNORE)
+ return false;
+ if (!enumeration_is_subset(a->options, b->options))
+ return false;
+ }
+
+ return true;
+}
+
+static void path_set_condense(pa_alsa_path_set *ps, snd_mixer_t *m) {
+ pa_alsa_path *p;
+ void *state;
+
+ pa_assert(ps);
+ pa_assert(m);
+
+ /* If we only have one path, then don't bother */
+ if (pa_hashmap_size(ps->paths) < 2)
+ return;
+
+ PA_HASHMAP_FOREACH(p, ps->paths, state) {
+ pa_alsa_path *p2;
+ void *state2;
+
+ PA_HASHMAP_FOREACH(p2, ps->paths, state2) {
+ pa_alsa_element *ea, *eb;
+ pa_alsa_jack *ja, *jb;
+ bool is_subset = true;
+
+ if (p == p2)
+ continue;
+
+ /* If a has a jack that b does not have, a is not a subset */
+ PA_LLIST_FOREACH(ja, p->jacks) {
+ bool exists = false;
+
+ if (!ja->has_control)
+ continue;
+
+ PA_LLIST_FOREACH(jb, p2->jacks) {
+ if (jb->has_control && pa_streq(ja->alsa_id.name, jb->alsa_id.name) &&
+ (ja->alsa_id.index == jb->alsa_id.index) &&
+ (ja->state_plugged == jb->state_plugged) &&
+ (ja->state_unplugged == jb->state_unplugged)) {
+ exists = true;
+ break;
+ }
+ }
+
+ if (!exists) {
+ is_subset = false;
+ break;
+ }
+ }
+
+ /* Compare the elements of each set... */
+ PA_LLIST_FOREACH(ea, p->elements) {
+ bool found_matching_element = false;
+
+ if (!is_subset)
+ break;
+
+ PA_LLIST_FOREACH(eb, p2->elements) {
+ if (pa_streq(ea->alsa_id.name, eb->alsa_id.name) &&
+ ea->alsa_id.index == eb->alsa_id.index) {
+ found_matching_element = true;
+ is_subset = element_is_subset(ea, eb, m);
+ break;
+ }
+ }
+
+ if (!found_matching_element)
+ is_subset = false;
+ }
+
+ if (is_subset) {
+ pa_log_debug("Removing path '%s' as it is a subset of '%s'.", p->name, p2->name);
+ pa_hashmap_remove(ps->paths, p);
+ break;
+ }
+ }
+ }
+}
+
+static pa_alsa_path* path_set_find_path_by_description(pa_alsa_path_set *ps, const char* description, pa_alsa_path *ignore) {
+ pa_alsa_path* p;
+ void *state;
+
+ PA_HASHMAP_FOREACH(p, ps->paths, state)
+ if (p != ignore && pa_streq(p->description, description))
+ return p;
+
+ return NULL;
+}
+
+static void path_set_make_path_descriptions_unique(pa_alsa_path_set *ps) {
+ pa_alsa_path *p, *q;
+ void *state, *state2;
+
+ PA_HASHMAP_FOREACH(p, ps->paths, state) {
+ unsigned i;
+ char *old_description;
+
+ q = path_set_find_path_by_description(ps, p->description, p);
+
+ if (!q)
+ continue;
+
+ old_description = pa_xstrdup(p->description);
+
+ /* OK, this description is not unique, hence let's rename */
+ i = 1;
+ PA_HASHMAP_FOREACH(q, ps->paths, state2) {
+ char *new_description;
+
+ if (!pa_streq(q->description, old_description))
+ continue;
+
+ new_description = pa_sprintf_malloc("%s %u", q->description, i);
+ pa_xfree(q->description);
+ q->description = new_description;
+
+ i++;
+ }
+
+ pa_xfree(old_description);
+ }
+}
+
+static void mapping_free(pa_alsa_mapping *m) {
+ pa_assert(m);
+
+ pa_xfree(m->name);
+ pa_xfree(m->description);
+ pa_xfree(m->description_key);
+
+ pa_proplist_free(m->proplist);
+
+ pa_xstrfreev(m->device_strings);
+ pa_xstrfreev(m->input_path_names);
+ pa_xstrfreev(m->output_path_names);
+ pa_xstrfreev(m->input_element);
+ pa_xstrfreev(m->output_element);
+ if (m->input_path_set)
+ pa_alsa_path_set_free(m->input_path_set);
+ if (m->output_path_set)
+ pa_alsa_path_set_free(m->output_path_set);
+
+ pa_assert(!m->input_pcm);
+ pa_assert(!m->output_pcm);
+
+ pa_alsa_ucm_mapping_context_free(&m->ucm_context);
+
+ pa_xfree(m);
+}
+
+static void profile_free(pa_alsa_profile *p) {
+ pa_assert(p);
+
+ pa_xfree(p->name);
+ pa_xfree(p->description);
+ pa_xfree(p->description_key);
+ pa_xfree(p->input_name);
+ pa_xfree(p->output_name);
+
+ pa_xstrfreev(p->input_mapping_names);
+ pa_xstrfreev(p->output_mapping_names);
+
+ if (p->input_mappings)
+ pa_idxset_free(p->input_mappings, NULL);
+
+ if (p->output_mappings)
+ pa_idxset_free(p->output_mappings, NULL);
+
+ pa_xfree(p);
+}
+
+void pa_alsa_profile_set_free(pa_alsa_profile_set *ps) {
+ pa_assert(ps);
+
+ if (ps->input_paths)
+ pa_hashmap_free(ps->input_paths);
+
+ if (ps->output_paths)
+ pa_hashmap_free(ps->output_paths);
+
+ if (ps->profiles)
+ pa_hashmap_free(ps->profiles);
+
+ if (ps->mappings)
+ pa_hashmap_free(ps->mappings);
+
+ if (ps->decibel_fixes)
+ pa_hashmap_free(ps->decibel_fixes);
+
+ pa_xfree(ps);
+}
+
+pa_alsa_mapping *pa_alsa_mapping_get(pa_alsa_profile_set *ps, const char *name) {
+ pa_alsa_mapping *m;
+
+ if (!pa_startswith(name, "Mapping "))
+ return NULL;
+
+ name += 8;
+
+ if ((m = pa_hashmap_get(ps->mappings, name)))
+ return m;
+
+ m = pa_xnew0(pa_alsa_mapping, 1);
+ m->profile_set = ps;
+ m->exact_channels = true;
+ m->name = pa_xstrdup(name);
+ pa_sample_spec_init(&m->sample_spec);
+ pa_channel_map_init(&m->channel_map);
+ m->proplist = pa_proplist_new();
+ m->hw_device_index = -1;
+
+ pa_hashmap_put(ps->mappings, m->name, m);
+
+ return m;
+}
+
+static pa_alsa_profile *profile_get(pa_alsa_profile_set *ps, const char *name) {
+ pa_alsa_profile *p;
+
+ if (!pa_startswith(name, "Profile "))
+ return NULL;
+
+ name += 8;
+
+ if ((p = pa_hashmap_get(ps->profiles, name)))
+ return p;
+
+ p = pa_xnew0(pa_alsa_profile, 1);
+ p->profile_set = ps;
+ p->name = pa_xstrdup(name);
+
+ pa_hashmap_put(ps->profiles, p->name, p);
+
+ return p;
+}
+
+static pa_alsa_decibel_fix *decibel_fix_get(pa_alsa_profile_set *ps, const char *alsa_id) {
+ pa_alsa_decibel_fix *db_fix;
+ char *name;
+ int index;
+
+ if (!pa_startswith(alsa_id, "DecibelFix "))
+ return NULL;
+
+ alsa_id += 11;
+
+ if ((db_fix = pa_hashmap_get(ps->decibel_fixes, alsa_id)))
+ return db_fix;
+
+ name = alloca(strlen(alsa_id) + 1);
+ if (alsa_id_decode(alsa_id, name, &index))
+ return NULL;
+
+ db_fix = pa_xnew0(pa_alsa_decibel_fix, 1);
+ db_fix->profile_set = ps;
+ db_fix->name = pa_xstrdup(name);
+ db_fix->index = index;
+ db_fix->key = pa_xstrdup(alsa_id);
+
+ pa_hashmap_put(ps->decibel_fixes, db_fix->key, db_fix);
+
+ return db_fix;
+}
+
+static int mapping_parse_device_strings(pa_config_parser_state *state) {
+ pa_alsa_profile_set *ps;
+ pa_alsa_mapping *m;
+
+ pa_assert(state);
+
+ ps = state->userdata;
+
+ if (!(m = pa_alsa_mapping_get(ps, state->section))) {
+ pa_log("[%s:%u] %s invalid in section %s", state->filename, state->lineno, state->lvalue, state->section);
+ return -1;
+ }
+
+ pa_xstrfreev(m->device_strings);
+ if (!(m->device_strings = pa_split_spaces_strv(state->rvalue))) {
+ pa_log("[%s:%u] Device string list empty of '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ return 0;
+}
+
+static int mapping_parse_channel_map(pa_config_parser_state *state) {
+ pa_alsa_profile_set *ps;
+ pa_alsa_mapping *m;
+
+ pa_assert(state);
+
+ ps = state->userdata;
+
+ if (!(m = pa_alsa_mapping_get(ps, state->section))) {
+ pa_log("[%s:%u] %s invalid in section %s", state->filename, state->lineno, state->lvalue, state->section);
+ return -1;
+ }
+
+ if (!(pa_channel_map_parse(&m->channel_map, state->rvalue))) {
+ pa_log("[%s:%u] Channel map invalid of '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ return 0;
+}
+
+static int mapping_parse_paths(pa_config_parser_state *state) {
+ pa_alsa_profile_set *ps;
+ pa_alsa_mapping *m;
+
+ pa_assert(state);
+
+ ps = state->userdata;
+
+ if (!(m = pa_alsa_mapping_get(ps, state->section))) {
+ pa_log("[%s:%u] %s invalid in section %s", state->filename, state->lineno, state->lvalue, state->section);
+ return -1;
+ }
+
+ if (pa_streq(state->lvalue, "paths-input")) {
+ pa_xstrfreev(m->input_path_names);
+ m->input_path_names = pa_split_spaces_strv(state->rvalue);
+ } else {
+ pa_xstrfreev(m->output_path_names);
+ m->output_path_names = pa_split_spaces_strv(state->rvalue);
+ }
+
+ return 0;
+}
+
+static int mapping_parse_exact_channels(pa_config_parser_state *state) {
+ pa_alsa_profile_set *ps;
+ pa_alsa_mapping *m;
+ int b;
+
+ pa_assert(state);
+
+ ps = state->userdata;
+
+ if (!(m = pa_alsa_mapping_get(ps, state->section))) {
+ pa_log("[%s:%u] %s invalid in section %s", state->filename, state->lineno, state->lvalue, state->section);
+ return -1;
+ }
+
+ if ((b = pa_parse_boolean(state->rvalue)) < 0) {
+ pa_log("[%s:%u] %s has invalid value '%s'", state->filename, state->lineno, state->lvalue, state->section);
+ return -1;
+ }
+
+ m->exact_channels = b;
+
+ return 0;
+}
+
+static int mapping_parse_element(pa_config_parser_state *state) {
+ pa_alsa_profile_set *ps;
+ pa_alsa_mapping *m;
+
+ pa_assert(state);
+
+ ps = state->userdata;
+
+ if (!(m = pa_alsa_mapping_get(ps, state->section))) {
+ pa_log("[%s:%u] %s invalid in section %s", state->filename, state->lineno, state->lvalue, state->section);
+ return -1;
+ }
+
+ if (pa_streq(state->lvalue, "element-input")) {
+ pa_xstrfreev(m->input_element);
+ m->input_element = pa_split_spaces_strv(state->rvalue);
+ } else {
+ pa_xstrfreev(m->output_element);
+ m->output_element = pa_split_spaces_strv(state->rvalue);
+ }
+
+ return 0;
+}
+
+static int mapping_parse_direction(pa_config_parser_state *state) {
+ pa_alsa_profile_set *ps;
+ pa_alsa_mapping *m;
+
+ pa_assert(state);
+
+ ps = state->userdata;
+
+ if (!(m = pa_alsa_mapping_get(ps, state->section))) {
+ pa_log("[%s:%u] Section name %s invalid.", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ if (pa_streq(state->rvalue, "input"))
+ m->direction = PA_ALSA_DIRECTION_INPUT;
+ else if (pa_streq(state->rvalue, "output"))
+ m->direction = PA_ALSA_DIRECTION_OUTPUT;
+ else if (pa_streq(state->rvalue, "any"))
+ m->direction = PA_ALSA_DIRECTION_ANY;
+ else {
+ pa_log("[%s:%u] Direction %s invalid.", state->filename, state->lineno, state->rvalue);
+ return -1;
+ }
+
+ return 0;
+}
+
+static int mapping_parse_description(pa_config_parser_state *state) {
+ pa_alsa_profile_set *ps;
+ pa_alsa_profile *p;
+ pa_alsa_mapping *m;
+
+ pa_assert(state);
+
+ ps = state->userdata;
+
+ if ((m = pa_alsa_mapping_get(ps, state->section))) {
+ pa_xfree(m->description);
+ m->description = pa_xstrdup(state->rvalue);
+ } else if ((p = profile_get(ps, state->section))) {
+ pa_xfree(p->description);
+ p->description = pa_xstrdup(state->rvalue);
+ } else {
+ pa_log("[%s:%u] Section name %s invalid.", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ return 0;
+}
+
+static int mapping_parse_description_key(pa_config_parser_state *state) {
+ pa_alsa_profile_set *ps;
+ pa_alsa_profile *p;
+ pa_alsa_mapping *m;
+
+ pa_assert(state);
+
+ ps = state->userdata;
+
+ if ((m = pa_alsa_mapping_get(ps, state->section))) {
+ pa_xfree(m->description_key);
+ m->description_key = pa_xstrdup(state->rvalue);
+ } else if ((p = profile_get(ps, state->section))) {
+ pa_xfree(p->description_key);
+ p->description_key = pa_xstrdup(state->rvalue);
+ } else {
+ pa_log("[%s:%u] Section name %s invalid.", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ return 0;
+}
+
+
+static int mapping_parse_priority(pa_config_parser_state *state) {
+ pa_alsa_profile_set *ps;
+ pa_alsa_profile *p;
+ pa_alsa_mapping *m;
+ uint32_t prio;
+
+ pa_assert(state);
+
+ ps = state->userdata;
+
+ if (pa_atou(state->rvalue, &prio) < 0) {
+ pa_log("[%s:%u] Priority invalid of '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ if ((m = pa_alsa_mapping_get(ps, state->section)))
+ m->priority = prio;
+ else if ((p = profile_get(ps, state->section)))
+ p->priority = prio;
+ else {
+ pa_log("[%s:%u] Section name %s invalid.", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ return 0;
+}
+
+static int mapping_parse_fallback(pa_config_parser_state *state) {
+ pa_alsa_profile_set *ps;
+ pa_alsa_profile *p;
+ pa_alsa_mapping *m;
+ int k;
+
+ pa_assert(state);
+
+ ps = state->userdata;
+
+ if ((k = pa_parse_boolean(state->rvalue)) < 0) {
+ pa_log("[%s:%u] Fallback invalid of '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ if ((m = pa_alsa_mapping_get(ps, state->section)))
+ m->fallback = k;
+ else if ((p = profile_get(ps, state->section)))
+ p->fallback_input = p->fallback_output = k;
+ else {
+ pa_log("[%s:%u] Section name %s invalid.", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ return 0;
+}
+
+static int mapping_parse_intended_roles(pa_config_parser_state *state) {
+ pa_alsa_profile_set *ps;
+ pa_alsa_mapping *m;
+
+ pa_assert(state);
+
+ ps = state->userdata;
+
+ if (!(m = pa_alsa_mapping_get(ps, state->section))) {
+ pa_log("[%s:%u] %s invalid in section %s", state->filename, state->lineno, state->lvalue, state->section);
+ return -1;
+ }
+
+ pa_proplist_sets(m->proplist, PA_PROP_DEVICE_INTENDED_ROLES, state->rvalue);
+
+ return 0;
+}
+
+
+static int profile_parse_mappings(pa_config_parser_state *state) {
+ pa_alsa_profile_set *ps;
+ pa_alsa_profile *p;
+
+ pa_assert(state);
+
+ ps = state->userdata;
+
+ if (!(p = profile_get(ps, state->section))) {
+ pa_log("[%s:%u] %s invalid in section %s", state->filename, state->lineno, state->lvalue, state->section);
+ return -1;
+ }
+
+ if (pa_streq(state->lvalue, "input-mappings")) {
+ pa_xstrfreev(p->input_mapping_names);
+ p->input_mapping_names = pa_split_spaces_strv(state->rvalue);
+ } else {
+ pa_xstrfreev(p->output_mapping_names);
+ p->output_mapping_names = pa_split_spaces_strv(state->rvalue);
+ }
+
+ return 0;
+}
+
+static int profile_parse_skip_probe(pa_config_parser_state *state) {
+ pa_alsa_profile_set *ps;
+ pa_alsa_profile *p;
+ int b;
+
+ pa_assert(state);
+
+ ps = state->userdata;
+
+ if (!(p = profile_get(ps, state->section))) {
+ pa_log("[%s:%u] %s invalid in section %s", state->filename, state->lineno, state->lvalue, state->section);
+ return -1;
+ }
+
+ if ((b = pa_parse_boolean(state->rvalue)) < 0) {
+ pa_log("[%s:%u] Skip probe invalid of '%s'", state->filename, state->lineno, state->section);
+ return -1;
+ }
+
+ p->supported = b;
+
+ return 0;
+}
+
+static int decibel_fix_parse_db_values(pa_config_parser_state *state) {
+ pa_alsa_profile_set *ps;
+ pa_alsa_decibel_fix *db_fix;
+ char **items;
+ char *item;
+ long *db_values;
+ unsigned n = 8; /* Current size of the db_values table. */
+ unsigned min_step = 0;
+ unsigned max_step = 0;
+ unsigned i = 0; /* Index to the items table. */
+ unsigned prev_step = 0;
+ double prev_db = 0;
+
+ pa_assert(state);
+
+ ps = state->userdata;
+
+ if (!(db_fix = decibel_fix_get(ps, state->section))) {
+ pa_log("[%s:%u] %s invalid in section %s", state->filename, state->lineno, state->lvalue, state->section);
+ return -1;
+ }
+
+ if (!(items = pa_split_spaces_strv(state->rvalue))) {
+ pa_log("[%s:%u] Value missing", state->filename, state->lineno);
+ return -1;
+ }
+
+ db_values = pa_xnew(long, n);
+
+ while ((item = items[i++])) {
+ char *s = item; /* Step value string. */
+ char *d = item; /* dB value string. */
+ uint32_t step;
+ double db;
+
+ /* Move d forward until it points to a colon or to the end of the item. */
+ for (; *d && *d != ':'; ++d);
+
+ if (d == s) {
+ /* item started with colon. */
+ pa_log("[%s:%u] No step value found in %s", state->filename, state->lineno, item);
+ goto fail;
+ }
+
+ if (!*d || !*(d + 1)) {
+ /* No colon found, or it was the last character in item. */
+ pa_log("[%s:%u] No dB value found in %s", state->filename, state->lineno, item);
+ goto fail;
+ }
+
+ /* pa_atou() needs a null-terminating string. Let's replace the colon
+ * with a zero byte. */
+ *d++ = '\0';
+
+ if (pa_atou(s, &step) < 0) {
+ pa_log("[%s:%u] Invalid step value: %s", state->filename, state->lineno, s);
+ goto fail;
+ }
+
+ if (pa_atod(d, &db) < 0) {
+ pa_log("[%s:%u] Invalid dB value: %s", state->filename, state->lineno, d);
+ goto fail;
+ }
+
+ if (step <= prev_step && i != 1) {
+ pa_log("[%s:%u] Step value %u not greater than the previous value %u", state->filename, state->lineno, step, prev_step);
+ goto fail;
+ }
+
+ if (db < prev_db && i != 1) {
+ pa_log("[%s:%u] Decibel value %0.2f less than the previous value %0.2f", state->filename, state->lineno, db, prev_db);
+ goto fail;
+ }
+
+ if (i == 1) {
+ min_step = step;
+ db_values[0] = (long) (db * 100.0);
+ prev_step = step;
+ prev_db = db;
+ } else {
+ /* Interpolate linearly. */
+ double db_increment = (db - prev_db) / (step - prev_step);
+
+ for (; prev_step < step; ++prev_step, prev_db += db_increment) {
+
+ /* Reallocate the db_values table if it's about to overflow. */
+ if (prev_step + 1 - min_step == n) {
+ n *= 2;
+ db_values = pa_xrenew(long, db_values, n);
+ }
+
+ db_values[prev_step + 1 - min_step] = (long) ((prev_db + db_increment) * 100.0);
+ }
+ }
+
+ max_step = step;
+ }
+
+ db_fix->min_step = min_step;
+ db_fix->max_step = max_step;
+ pa_xfree(db_fix->db_values);
+ db_fix->db_values = db_values;
+
+ pa_xstrfreev(items);
+
+ return 0;
+
+fail:
+ pa_xstrfreev(items);
+ pa_xfree(db_values);
+
+ return -1;
+}
+
+/* the logic is simple: if we see the jack in multiple paths */
+/* assign all those paths to one availability_group */
+static void profile_set_set_availability_groups(pa_alsa_profile_set *ps) {
+ pa_dynarray *paths;
+ pa_alsa_path *p;
+ void *state;
+ unsigned idx1;
+ uint32_t num = 1;
+
+ /* Merge ps->input_paths and ps->output_paths into one dynarray. */
+ paths = pa_dynarray_new(NULL);
+ PA_HASHMAP_FOREACH(p, ps->input_paths, state)
+ pa_dynarray_append(paths, p);
+ PA_HASHMAP_FOREACH(p, ps->output_paths, state)
+ pa_dynarray_append(paths, p);
+
+ PA_DYNARRAY_FOREACH(p, paths, idx1) {
+ pa_alsa_jack *j;
+ const char *found = NULL;
+ bool has_control = false;
+
+ PA_LLIST_FOREACH(j, p->jacks) {
+ pa_alsa_path *p2;
+ unsigned idx2;
+
+ if (!j->has_control || j->state_plugged == PA_AVAILABLE_NO)
+ continue;
+ has_control = true;
+ PA_DYNARRAY_FOREACH(p2, paths, idx2) {
+ pa_alsa_jack *j2;
+
+ if (p2 == p)
+ break;
+ PA_LLIST_FOREACH(j2, p2->jacks) {
+ if (!j2->has_control || j2->state_plugged == PA_AVAILABLE_NO)
+ continue;
+ if (pa_streq(j->alsa_id.name, j2->alsa_id.name) &&
+ j->alsa_id.index == j2->alsa_id.index) {
+ j->state_plugged = PA_AVAILABLE_UNKNOWN;
+ j2->state_plugged = PA_AVAILABLE_UNKNOWN;
+ found = p2->availability_group;
+ break;
+ }
+ }
+ }
+ if (found)
+ break;
+ }
+ if (!has_control)
+ continue;
+ if (!found) {
+ p->availability_group = pa_sprintf_malloc("Legacy %d", num);
+ } else {
+ p->availability_group = pa_xstrdup(found);
+ }
+ if (!found)
+ num++;
+ }
+
+ pa_dynarray_free(paths);
+}
+
+static void mapping_paths_probe(pa_alsa_mapping *m, pa_alsa_profile *profile,
+ pa_alsa_direction_t direction, pa_hashmap *used_paths,
+ pa_hashmap *mixers) {
+
+ pa_alsa_path *p;
+ void *state;
+ snd_pcm_t *pcm_handle;
+ pa_alsa_path_set *ps;
+ snd_mixer_t *mixer_handle;
+
+ if (direction == PA_ALSA_DIRECTION_OUTPUT) {
+ if (m->output_path_set)
+ return; /* Already probed */
+ m->output_path_set = ps = pa_alsa_path_set_new(m, direction, NULL); /* FIXME: Handle paths_dir */
+ pcm_handle = m->output_pcm;
+ } else {
+ if (m->input_path_set)
+ return; /* Already probed */
+ m->input_path_set = ps = pa_alsa_path_set_new(m, direction, NULL); /* FIXME: Handle paths_dir */
+ pcm_handle = m->input_pcm;
+ }
+
+ if (!ps)
+ return; /* No paths */
+
+ pa_assert(pcm_handle);
+
+ mixer_handle = pa_alsa_open_mixer_for_pcm(mixers, pcm_handle, true);
+ if (!mixer_handle) {
+ /* Cannot open mixer, remove all entries */
+ pa_hashmap_remove_all(ps->paths);
+ return;
+ }
+
+ PA_HASHMAP_FOREACH(p, ps->paths, state) {
+ if (p->autodetect_eld_device)
+ p->eld_device = m->hw_device_index;
+
+ if (pa_alsa_path_probe(p, m, mixer_handle, m->profile_set->ignore_dB) < 0)
+ pa_hashmap_remove(ps->paths, p);
+ }
+
+ path_set_condense(ps, mixer_handle);
+ path_set_make_path_descriptions_unique(ps);
+
+ PA_HASHMAP_FOREACH(p, ps->paths, state)
+ pa_hashmap_put(used_paths, p, p);
+
+ pa_log_debug("Available mixer paths (after tidying):");
+ pa_alsa_path_set_dump(ps);
+}
+
+static int mapping_verify(pa_alsa_mapping *m, const pa_channel_map *bonus) {
+
+ static const struct description_map well_known_descriptions[] = {
+ { "analog-mono", N_("Analog Mono") },
+ { "analog-stereo", N_("Analog Stereo") },
+ { "mono-fallback", N_("Mono") },
+ { "stereo-fallback", N_("Stereo") },
+ /* Note: Not translated to "Analog Stereo Input", because the source
+ * name gets "Input" appended to it automatically, so adding "Input"
+ * here would lead to the source name to become "Analog Stereo Input
+ * Input". The same logic applies to analog-stereo-output,
+ * multichannel-input and multichannel-output. */
+ { "analog-stereo-input", N_("Analog Stereo") },
+ { "analog-stereo-output", N_("Analog Stereo") },
+ { "multichannel-input", N_("Multichannel") },
+ { "multichannel-output", N_("Multichannel") },
+ { "analog-surround-21", N_("Analog Surround 2.1") },
+ { "analog-surround-30", N_("Analog Surround 3.0") },
+ { "analog-surround-31", N_("Analog Surround 3.1") },
+ { "analog-surround-40", N_("Analog Surround 4.0") },
+ { "analog-surround-41", N_("Analog Surround 4.1") },
+ { "analog-surround-50", N_("Analog Surround 5.0") },
+ { "analog-surround-51", N_("Analog Surround 5.1") },
+ { "analog-surround-61", N_("Analog Surround 6.0") },
+ { "analog-surround-61", N_("Analog Surround 6.1") },
+ { "analog-surround-70", N_("Analog Surround 7.0") },
+ { "analog-surround-71", N_("Analog Surround 7.1") },
+ { "iec958-stereo", N_("Digital Stereo (IEC958)") },
+ { "iec958-ac3-surround-40", N_("Digital Surround 4.0 (IEC958/AC3)") },
+ { "iec958-ac3-surround-51", N_("Digital Surround 5.1 (IEC958/AC3)") },
+ { "iec958-dts-surround-51", N_("Digital Surround 5.1 (IEC958/DTS)") },
+ { "hdmi-stereo", N_("Digital Stereo (HDMI)") },
+ { "hdmi-surround-51", N_("Digital Surround 5.1 (HDMI)") },
+ { "gaming-headset-chat", N_("Chat") },
+ { "gaming-headset-game", N_("Game") },
+ };
+ const char *description_key = m->description_key ? m->description_key : m->name;
+
+ pa_assert(m);
+
+ if (!pa_channel_map_valid(&m->channel_map)) {
+ pa_log("Mapping %s is missing channel map.", m->name);
+ return -1;
+ }
+
+ if (!m->device_strings) {
+ pa_log("Mapping %s is missing device strings.", m->name);
+ return -1;
+ }
+
+ if ((m->input_path_names && m->input_element) ||
+ (m->output_path_names && m->output_element)) {
+ pa_log("Mapping %s must have either mixer path or mixer element, not both.", m->name);
+ return -1;
+ }
+
+ if (!m->description)
+ m->description = pa_xstrdup(lookup_description(description_key,
+ well_known_descriptions,
+ PA_ELEMENTSOF(well_known_descriptions)));
+
+ if (!m->description)
+ m->description = pa_xstrdup(m->name);
+
+ if (bonus) {
+ if (pa_channel_map_equal(&m->channel_map, bonus))
+ m->priority += 50;
+ else if (m->channel_map.channels == bonus->channels)
+ m->priority += 30;
+ }
+
+ return 0;
+}
+
+void pa_alsa_mapping_dump(pa_alsa_mapping *m) {
+ char cm[PA_CHANNEL_MAP_SNPRINT_MAX];
+
+ pa_assert(m);
+
+ pa_log_debug("Mapping %s (%s), priority=%u, channel_map=%s, supported=%s, direction=%i",
+ m->name,
+ pa_strnull(m->description),
+ m->priority,
+ pa_channel_map_snprint(cm, sizeof(cm), &m->channel_map),
+ pa_yes_no(m->supported),
+ m->direction);
+}
+
+static void profile_set_add_auto_pair(
+ pa_alsa_profile_set *ps,
+ pa_alsa_mapping *m, /* output */
+ pa_alsa_mapping *n /* input */) {
+
+ char *name;
+ pa_alsa_profile *p;
+
+ pa_assert(ps);
+ pa_assert(m || n);
+
+ if (m && m->direction == PA_ALSA_DIRECTION_INPUT)
+ return;
+
+ if (n && n->direction == PA_ALSA_DIRECTION_OUTPUT)
+ return;
+
+ if (m && n)
+ name = pa_sprintf_malloc("output:%s+input:%s", m->name, n->name);
+ else if (m)
+ name = pa_sprintf_malloc("output:%s", m->name);
+ else
+ name = pa_sprintf_malloc("input:%s", n->name);
+
+ if (pa_hashmap_get(ps->profiles, name)) {
+ pa_xfree(name);
+ return;
+ }
+
+ p = pa_xnew0(pa_alsa_profile, 1);
+ p->profile_set = ps;
+ p->name = name;
+
+ if (m) {
+ p->output_name = pa_xstrdup(m->name);
+ p->output_mappings = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
+ pa_idxset_put(p->output_mappings, m, NULL);
+ p->priority += m->priority * 100;
+ p->fallback_output = m->fallback;
+ }
+
+ if (n) {
+ p->input_name = pa_xstrdup(n->name);
+ p->input_mappings = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
+ pa_idxset_put(p->input_mappings, n, NULL);
+ p->priority += n->priority;
+ p->fallback_input = n->fallback;
+ }
+
+ pa_hashmap_put(ps->profiles, p->name, p);
+}
+
+static void profile_set_add_auto(pa_alsa_profile_set *ps) {
+ pa_alsa_mapping *m, *n;
+ void *m_state, *n_state;
+
+ pa_assert(ps);
+
+ /* The order is important here:
+ 1) try single inputs and outputs before trying their
+ combination, because if the half-duplex test failed, we don't have
+ to try full duplex.
+ 2) try the output right before the input combinations with
+ that output, because then the output_pcm is not closed between tests.
+ */
+ PA_HASHMAP_FOREACH(n, ps->mappings, n_state)
+ profile_set_add_auto_pair(ps, NULL, n);
+
+ PA_HASHMAP_FOREACH(m, ps->mappings, m_state) {
+ profile_set_add_auto_pair(ps, m, NULL);
+
+ PA_HASHMAP_FOREACH(n, ps->mappings, n_state)
+ profile_set_add_auto_pair(ps, m, n);
+ }
+
+}
+
+static int profile_verify(pa_alsa_profile *p) {
+
+ static const struct description_map well_known_descriptions[] = {
+ { "output:analog-mono+input:analog-mono", N_("Analog Mono Duplex") },
+ { "output:analog-stereo+input:analog-stereo", N_("Analog Stereo Duplex") },
+ { "output:iec958-stereo+input:iec958-stereo", N_("Digital Stereo Duplex (IEC958)") },
+ { "output:multichannel-output+input:multichannel-input", N_("Multichannel Duplex") },
+ { "output:unknown-stereo+input:unknown-stereo", N_("Stereo Duplex") },
+ { "off", N_("Off") }
+ };
+ const char *description_key = p->description_key ? p->description_key : p->name;
+
+ pa_assert(p);
+
+ /* Replace the output mapping names by the actual mappings */
+ if (p->output_mapping_names) {
+ char **name;
+
+ pa_assert(!p->output_mappings);
+ p->output_mappings = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
+
+ for (name = p->output_mapping_names; *name; name++) {
+ pa_alsa_mapping *m;
+ char **in;
+ bool duplicate = false;
+
+ for (in = name + 1; *in; in++)
+ if (pa_streq(*name, *in)) {
+ duplicate = true;
+ break;
+ }
+
+ if (duplicate)
+ continue;
+
+ if (!(m = pa_hashmap_get(p->profile_set->mappings, *name)) || m->direction == PA_ALSA_DIRECTION_INPUT) {
+ pa_log("Profile '%s' refers to nonexistent mapping '%s'.", p->name, *name);
+ return -1;
+ }
+
+ pa_idxset_put(p->output_mappings, m, NULL);
+
+ if (p->supported)
+ m->supported++;
+ }
+
+ pa_xstrfreev(p->output_mapping_names);
+ p->output_mapping_names = NULL;
+ }
+
+ /* Replace the input mapping names by the actual mappings */
+ if (p->input_mapping_names) {
+ char **name;
+
+ pa_assert(!p->input_mappings);
+ p->input_mappings = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
+
+ for (name = p->input_mapping_names; *name; name++) {
+ pa_alsa_mapping *m;
+ char **in;
+ bool duplicate = false;
+
+ for (in = name + 1; *in; in++)
+ if (pa_streq(*name, *in)) {
+ duplicate = true;
+ break;
+ }
+
+ if (duplicate)
+ continue;
+
+ if (!(m = pa_hashmap_get(p->profile_set->mappings, *name)) || m->direction == PA_ALSA_DIRECTION_OUTPUT) {
+ pa_log("Profile '%s' refers to nonexistent mapping '%s'.", p->name, *name);
+ return -1;
+ }
+
+ pa_idxset_put(p->input_mappings, m, NULL);
+
+ if (p->supported)
+ m->supported++;
+ }
+
+ pa_xstrfreev(p->input_mapping_names);
+ p->input_mapping_names = NULL;
+ }
+
+ if (!p->input_mappings && !p->output_mappings) {
+ pa_log("Profile '%s' lacks mappings.", p->name);
+ return -1;
+ }
+
+ if (!p->description)
+ p->description = pa_xstrdup(lookup_description(description_key,
+ well_known_descriptions,
+ PA_ELEMENTSOF(well_known_descriptions)));
+
+ if (!p->description) {
+ pa_strbuf *sb;
+ uint32_t idx;
+ pa_alsa_mapping *m;
+
+ sb = pa_strbuf_new();
+
+ if (p->output_mappings)
+ PA_IDXSET_FOREACH(m, p->output_mappings, idx) {
+ if (!pa_strbuf_isempty(sb))
+ pa_strbuf_puts(sb, " + ");
+
+ pa_strbuf_printf(sb, _("%s Output"), m->description);
+ }
+
+ if (p->input_mappings)
+ PA_IDXSET_FOREACH(m, p->input_mappings, idx) {
+ if (!pa_strbuf_isempty(sb))
+ pa_strbuf_puts(sb, " + ");
+
+ pa_strbuf_printf(sb, _("%s Input"), m->description);
+ }
+
+ p->description = pa_strbuf_to_string_free(sb);
+ }
+
+ return 0;
+}
+
+void pa_alsa_profile_dump(pa_alsa_profile *p) {
+ uint32_t idx;
+ pa_alsa_mapping *m;
+ pa_assert(p);
+
+ pa_log_debug("Profile %s (%s), input=%s, output=%s priority=%u, supported=%s n_input_mappings=%u, n_output_mappings=%u",
+ p->name,
+ pa_strnull(p->description),
+ pa_strnull(p->input_name),
+ pa_strnull(p->output_name),
+ p->priority,
+ pa_yes_no(p->supported),
+ p->input_mappings ? pa_idxset_size(p->input_mappings) : 0,
+ p->output_mappings ? pa_idxset_size(p->output_mappings) : 0);
+
+ if (p->input_mappings)
+ PA_IDXSET_FOREACH(m, p->input_mappings, idx)
+ pa_log_debug("Input %s", m->name);
+
+ if (p->output_mappings)
+ PA_IDXSET_FOREACH(m, p->output_mappings, idx)
+ pa_log_debug("Output %s", m->name);
+}
+
+static int decibel_fix_verify(pa_alsa_decibel_fix *db_fix) {
+ pa_assert(db_fix);
+
+ /* Check that the dB mapping has been configured. Since "db-values" is
+ * currently the only option in the DecibelFix section, and decibel fix
+ * objects don't get created if a DecibelFix section is empty, this is
+ * actually a redundant check. Having this may prevent future bugs,
+ * however. */
+ if (!db_fix->db_values) {
+ pa_log("Decibel fix for element %s lacks the dB values.", db_fix->name);
+ return -1;
+ }
+
+ return 0;
+}
+
+void pa_alsa_decibel_fix_dump(pa_alsa_decibel_fix *db_fix) {
+ char *db_values = NULL;
+
+ pa_assert(db_fix);
+
+ if (db_fix->db_values) {
+ pa_strbuf *buf;
+ unsigned long i, nsteps;
+
+ pa_assert(db_fix->min_step <= db_fix->max_step);
+ nsteps = db_fix->max_step - db_fix->min_step + 1;
+
+ buf = pa_strbuf_new();
+ for (i = 0; i < nsteps; ++i)
+ pa_strbuf_printf(buf, "[%li]:%0.2f ", i + db_fix->min_step, db_fix->db_values[i] / 100.0);
+
+ db_values = pa_strbuf_to_string_free(buf);
+ }
+
+ pa_log_debug("Decibel fix %s, min_step=%li, max_step=%li, db_values=%s",
+ db_fix->name, db_fix->min_step, db_fix->max_step, pa_strnull(db_values));
+
+ pa_xfree(db_values);
+}
+
+pa_alsa_profile_set* pa_alsa_profile_set_new(const char *fname, const pa_channel_map *bonus) {
+ pa_alsa_profile_set *ps;
+ pa_alsa_profile *p;
+ pa_alsa_mapping *m;
+ pa_alsa_decibel_fix *db_fix;
+ char *fn;
+ int r;
+ void *state;
+
+ static pa_config_item items[] = {
+ /* [General] */
+ { "auto-profiles", pa_config_parse_bool, NULL, "General" },
+
+ /* [Mapping ...] */
+ { "device-strings", mapping_parse_device_strings, NULL, NULL },
+ { "channel-map", mapping_parse_channel_map, NULL, NULL },
+ { "paths-input", mapping_parse_paths, NULL, NULL },
+ { "paths-output", mapping_parse_paths, NULL, NULL },
+ { "element-input", mapping_parse_element, NULL, NULL },
+ { "element-output", mapping_parse_element, NULL, NULL },
+ { "direction", mapping_parse_direction, NULL, NULL },
+ { "exact-channels", mapping_parse_exact_channels, NULL, NULL },
+ { "intended-roles", mapping_parse_intended_roles, NULL, NULL },
+
+ /* Shared by [Mapping ...] and [Profile ...] */
+ { "description", mapping_parse_description, NULL, NULL },
+ { "description-key", mapping_parse_description_key,NULL, NULL },
+ { "priority", mapping_parse_priority, NULL, NULL },
+ { "fallback", mapping_parse_fallback, NULL, NULL },
+
+ /* [Profile ...] */
+ { "input-mappings", profile_parse_mappings, NULL, NULL },
+ { "output-mappings", profile_parse_mappings, NULL, NULL },
+ { "skip-probe", profile_parse_skip_probe, NULL, NULL },
+
+ /* [DecibelFix ...] */
+ { "db-values", decibel_fix_parse_db_values, NULL, NULL },
+ { NULL, NULL, NULL, NULL }
+ };
+
+ ps = pa_xnew0(pa_alsa_profile_set, 1);
+ ps->mappings = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func, NULL, (pa_free_cb_t) mapping_free);
+ ps->profiles = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func, NULL, (pa_free_cb_t) profile_free);
+ ps->decibel_fixes = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func, NULL, (pa_free_cb_t) decibel_fix_free);
+ ps->input_paths = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func, NULL, (pa_free_cb_t) pa_alsa_path_free);
+ ps->output_paths = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func, NULL, (pa_free_cb_t) pa_alsa_path_free);
+
+ items[0].data = &ps->auto_profiles;
+
+ if (!fname)
+ fname = "default.conf";
+
+ fn = pa_maybe_prefix_path(fname,
+#ifdef HAVE_RUNNING_FROM_BUILD_TREE
+ pa_run_from_build_tree() ? PA_SRCDIR "/modules/alsa/mixer/profile-sets/" :
+#endif
+ PA_ALSA_PROFILE_SETS_DIR);
+
+ r = pa_config_parse(fn, NULL, items, NULL, false, ps);
+ pa_xfree(fn);
+
+ if (r < 0)
+ goto fail;
+
+ PA_HASHMAP_FOREACH(m, ps->mappings, state)
+ if (mapping_verify(m, bonus) < 0)
+ goto fail;
+
+ if (ps->auto_profiles)
+ profile_set_add_auto(ps);
+
+ PA_HASHMAP_FOREACH(p, ps->profiles, state)
+ if (profile_verify(p) < 0)
+ goto fail;
+
+ PA_HASHMAP_FOREACH(db_fix, ps->decibel_fixes, state)
+ if (decibel_fix_verify(db_fix) < 0)
+ goto fail;
+
+ return ps;
+
+fail:
+ pa_alsa_profile_set_free(ps);
+ return NULL;
+}
+
+static void profile_finalize_probing(pa_alsa_profile *to_be_finalized, pa_alsa_profile *next) {
+ pa_alsa_mapping *m;
+ uint32_t idx;
+
+ if (!to_be_finalized)
+ return;
+
+ if (to_be_finalized->output_mappings)
+ PA_IDXSET_FOREACH(m, to_be_finalized->output_mappings, idx) {
+
+ if (!m->output_pcm)
+ continue;
+
+ if (to_be_finalized->supported)
+ m->supported++;
+
+ /* If this mapping is also in the next profile, we won't close the
+ * pcm handle here, because it would get immediately reopened
+ * anyway. */
+ if (next && next->output_mappings && pa_idxset_get_by_data(next->output_mappings, m, NULL))
+ continue;
+
+ snd_pcm_close(m->output_pcm);
+ m->output_pcm = NULL;
+ }
+
+ if (to_be_finalized->input_mappings)
+ PA_IDXSET_FOREACH(m, to_be_finalized->input_mappings, idx) {
+
+ if (!m->input_pcm)
+ continue;
+
+ if (to_be_finalized->supported)
+ m->supported++;
+
+ /* If this mapping is also in the next profile, we won't close the
+ * pcm handle here, because it would get immediately reopened
+ * anyway. */
+ if (next && next->input_mappings && pa_idxset_get_by_data(next->input_mappings, m, NULL))
+ continue;
+
+ snd_pcm_close(m->input_pcm);
+ m->input_pcm = NULL;
+ }
+}
+
+static snd_pcm_t* mapping_open_pcm(pa_alsa_mapping *m,
+ const pa_sample_spec *ss,
+ const char *dev_id,
+ bool exact_channels,
+ int mode,
+ unsigned default_n_fragments,
+ unsigned default_fragment_size_msec) {
+
+ snd_pcm_t* handle;
+ pa_sample_spec try_ss = *ss;
+ pa_channel_map try_map = m->channel_map;
+ snd_pcm_uframes_t try_period_size, try_buffer_size;
+
+ try_ss.channels = try_map.channels;
+
+ try_period_size =
+ pa_usec_to_bytes(default_fragment_size_msec * PA_USEC_PER_MSEC, &try_ss) /
+ pa_frame_size(&try_ss);
+ try_buffer_size = default_n_fragments * try_period_size;
+
+ handle = pa_alsa_open_by_template(
+ m->device_strings, dev_id, NULL, &try_ss,
+ &try_map, mode, &try_period_size,
+ &try_buffer_size, 0, NULL, NULL, exact_channels);
+ if (handle && !exact_channels && m->channel_map.channels != try_map.channels) {
+ char buf[PA_CHANNEL_MAP_SNPRINT_MAX];
+ pa_log_debug("Channel map for mapping '%s' permanently changed to '%s'", m->name,
+ pa_channel_map_snprint(buf, sizeof(buf), &try_map));
+ m->channel_map = try_map;
+ }
+ return handle;
+}
+
+static void paths_drop_unused(pa_hashmap* h, pa_hashmap *keep) {
+
+ void* state = NULL;
+ const void* key;
+ pa_alsa_path* p;
+
+ pa_assert(h);
+ pa_assert(keep);
+
+ p = pa_hashmap_iterate(h, &state, &key);
+ while (p) {
+ if (pa_hashmap_get(keep, p) == NULL)
+ pa_hashmap_remove_and_free(h, key);
+ p = pa_hashmap_iterate(h, &state, &key);
+ }
+}
+
+static int add_profiles_to_probe(
+ pa_alsa_profile **list,
+ pa_hashmap *profiles,
+ bool fallback_output,
+ bool fallback_input) {
+
+ int i = 0;
+ void *state;
+ pa_alsa_profile *p;
+ PA_HASHMAP_FOREACH(p, profiles, state)
+ if (p->fallback_input == fallback_input && p->fallback_output == fallback_output) {
+ *list = p;
+ list++;
+ i++;
+ }
+ return i;
+}
+
+static void mapping_query_hw_device(pa_alsa_mapping *mapping, snd_pcm_t *pcm) {
+ int r;
+ snd_pcm_info_t* pcm_info;
+ snd_pcm_info_alloca(&pcm_info);
+
+ r = snd_pcm_info(pcm, pcm_info);
+ if (r < 0) {
+ pa_log("Mapping %s: snd_pcm_info() failed %s: ", mapping->name, pa_alsa_strerror(r));
+ return;
+ }
+
+ /* XXX: It's not clear what snd_pcm_info_get_device() does if the device is
+ * not backed by a hw device or if it's backed by multiple hw devices. We
+ * only use hw_device_index for HDMI devices, however, and for those the
+ * return value is expected to be always valid, so this shouldn't be a
+ * significant problem. */
+ mapping->hw_device_index = snd_pcm_info_get_device(pcm_info);
+}
+
+void pa_alsa_profile_set_probe(
+ pa_alsa_profile_set *ps,
+ pa_hashmap *mixers,
+ const char *dev_id,
+ const pa_sample_spec *ss,
+ unsigned default_n_fragments,
+ unsigned default_fragment_size_msec) {
+
+ bool found_output = false, found_input = false;
+
+ pa_alsa_profile *p, *last = NULL;
+ pa_alsa_profile **pp, **probe_order;
+ pa_alsa_mapping *m;
+ pa_hashmap *broken_inputs, *broken_outputs, *used_paths;
+
+ pa_assert(ps);
+ pa_assert(dev_id);
+ pa_assert(ss);
+
+ if (ps->probed)
+ return;
+
+ broken_inputs = pa_hashmap_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
+ broken_outputs = pa_hashmap_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
+ used_paths = pa_hashmap_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
+ pp = probe_order = pa_xnew0(pa_alsa_profile *, pa_hashmap_size(ps->profiles) + 1);
+
+ pp += add_profiles_to_probe(pp, ps->profiles, false, false);
+ pp += add_profiles_to_probe(pp, ps->profiles, false, true);
+ pp += add_profiles_to_probe(pp, ps->profiles, true, false);
+ pp += add_profiles_to_probe(pp, ps->profiles, true, true);
+
+ for (pp = probe_order; *pp; pp++) {
+ uint32_t idx;
+ p = *pp;
+
+ /* Skip if fallback and already found something */
+ if (found_input && p->fallback_input)
+ continue;
+ if (found_output && p->fallback_output)
+ continue;
+
+ /* Skip if this is already marked that it is supported (i.e. from the config file) */
+ if (!p->supported) {
+
+ profile_finalize_probing(last, p);
+ p->supported = true;
+
+ if (p->output_mappings) {
+ PA_IDXSET_FOREACH(m, p->output_mappings, idx) {
+ if (pa_hashmap_get(broken_outputs, m) == m) {
+ pa_log_debug("Skipping profile %s - will not be able to open output:%s", p->name, m->name);
+ p->supported = false;
+ break;
+ }
+ }
+ }
+
+ if (p->input_mappings && p->supported) {
+ PA_IDXSET_FOREACH(m, p->input_mappings, idx) {
+ if (pa_hashmap_get(broken_inputs, m) == m) {
+ pa_log_debug("Skipping profile %s - will not be able to open input:%s", p->name, m->name);
+ p->supported = false;
+ break;
+ }
+ }
+ }
+
+ if (p->supported)
+ pa_log_debug("Looking at profile %s", p->name);
+
+ /* Check if we can open all new ones */
+ if (p->output_mappings && p->supported)
+ PA_IDXSET_FOREACH(m, p->output_mappings, idx) {
+
+ if (m->output_pcm)
+ continue;
+
+ pa_log_debug("Checking for playback on %s (%s)", m->description, m->name);
+ if (!(m->output_pcm = mapping_open_pcm(m, ss, dev_id, m->exact_channels,
+ SND_PCM_STREAM_PLAYBACK,
+ default_n_fragments,
+ default_fragment_size_msec))) {
+ p->supported = false;
+ if (pa_idxset_size(p->output_mappings) == 1 &&
+ ((!p->input_mappings) || pa_idxset_size(p->input_mappings) == 0)) {
+ pa_log_debug("Caching failure to open output:%s", m->name);
+ pa_hashmap_put(broken_outputs, m, m);
+ }
+ break;
+ }
+
+ if (m->hw_device_index < 0)
+ mapping_query_hw_device(m, m->output_pcm);
+ }
+
+ if (p->input_mappings && p->supported)
+ PA_IDXSET_FOREACH(m, p->input_mappings, idx) {
+
+ if (m->input_pcm)
+ continue;
+
+ pa_log_debug("Checking for recording on %s (%s)", m->description, m->name);
+ if (!(m->input_pcm = mapping_open_pcm(m, ss, dev_id, m->exact_channels,
+ SND_PCM_STREAM_CAPTURE,
+ default_n_fragments,
+ default_fragment_size_msec))) {
+ p->supported = false;
+ if (pa_idxset_size(p->input_mappings) == 1 &&
+ ((!p->output_mappings) || pa_idxset_size(p->output_mappings) == 0)) {
+ pa_log_debug("Caching failure to open input:%s", m->name);
+ pa_hashmap_put(broken_inputs, m, m);
+ }
+ break;
+ }
+
+ if (m->hw_device_index < 0)
+ mapping_query_hw_device(m, m->input_pcm);
+ }
+
+ last = p;
+
+ if (!p->supported)
+ continue;
+ }
+
+ pa_log_debug("Profile %s supported.", p->name);
+
+ if (p->output_mappings)
+ PA_IDXSET_FOREACH(m, p->output_mappings, idx)
+ if (m->output_pcm) {
+ found_output |= !p->fallback_output;
+ mapping_paths_probe(m, p, PA_ALSA_DIRECTION_OUTPUT, used_paths, mixers);
+ }
+
+ if (p->input_mappings)
+ PA_IDXSET_FOREACH(m, p->input_mappings, idx)
+ if (m->input_pcm) {
+ found_input |= !p->fallback_input;
+ mapping_paths_probe(m, p, PA_ALSA_DIRECTION_INPUT, used_paths, mixers);
+ }
+ }
+
+ /* Clean up */
+ profile_finalize_probing(last, NULL);
+
+ pa_alsa_profile_set_drop_unsupported(ps);
+
+ paths_drop_unused(ps->input_paths, used_paths);
+ paths_drop_unused(ps->output_paths, used_paths);
+ pa_hashmap_free(broken_inputs);
+ pa_hashmap_free(broken_outputs);
+ pa_hashmap_free(used_paths);
+ pa_xfree(probe_order);
+
+ profile_set_set_availability_groups(ps);
+
+ ps->probed = true;
+}
+
+void pa_alsa_profile_set_dump(pa_alsa_profile_set *ps) {
+ pa_alsa_profile *p;
+ pa_alsa_mapping *m;
+ pa_alsa_decibel_fix *db_fix;
+ void *state;
+
+ pa_assert(ps);
+
+ pa_log_debug("Profile set %p, auto_profiles=%s, probed=%s, n_mappings=%u, n_profiles=%u, n_decibel_fixes=%u",
+ (void*)
+ ps,
+ pa_yes_no(ps->auto_profiles),
+ pa_yes_no(ps->probed),
+ pa_hashmap_size(ps->mappings),
+ pa_hashmap_size(ps->profiles),
+ pa_hashmap_size(ps->decibel_fixes));
+
+ PA_HASHMAP_FOREACH(m, ps->mappings, state)
+ pa_alsa_mapping_dump(m);
+
+ PA_HASHMAP_FOREACH(p, ps->profiles, state)
+ pa_alsa_profile_dump(p);
+
+ PA_HASHMAP_FOREACH(db_fix, ps->decibel_fixes, state)
+ pa_alsa_decibel_fix_dump(db_fix);
+}
+
+void pa_alsa_profile_set_drop_unsupported(pa_alsa_profile_set *ps) {
+ pa_alsa_profile *p;
+ pa_alsa_mapping *m;
+ void *state;
+
+ PA_HASHMAP_FOREACH(p, ps->profiles, state) {
+ if (!p->supported)
+ pa_hashmap_remove_and_free(ps->profiles, p->name);
+ }
+
+ PA_HASHMAP_FOREACH(m, ps->mappings, state) {
+ if (m->supported <= 0)
+ pa_hashmap_remove_and_free(ps->mappings, m->name);
+ }
+}
+
+static pa_device_port* device_port_alsa_init(pa_hashmap *ports, /* card ports */
+ const char* name,
+ const char* description,
+ pa_alsa_path *path,
+ pa_alsa_setting *setting,
+ pa_card_profile *cp,
+ pa_hashmap *extra, /* sink/source ports */
+ pa_core *core) {
+
+ pa_device_port *p;
+
+ pa_assert(path);
+
+ p = pa_hashmap_get(ports, name);
+
+ if (!p) {
+ pa_alsa_port_data *data;
+ pa_device_port_new_data port_data;
+
+ pa_device_port_new_data_init(&port_data);
+ pa_device_port_new_data_set_name(&port_data, name);
+ pa_device_port_new_data_set_description(&port_data, description);
+ pa_device_port_new_data_set_direction(&port_data, path->direction == PA_ALSA_DIRECTION_OUTPUT ? PA_DIRECTION_OUTPUT : PA_DIRECTION_INPUT);
+ pa_device_port_new_data_set_type(&port_data, path->device_port_type);
+ pa_device_port_new_data_set_availability_group(&port_data, path->availability_group);
+
+ p = pa_device_port_new(core, &port_data, sizeof(pa_alsa_port_data));
+ pa_device_port_new_data_done(&port_data);
+ pa_assert(p);
+ pa_hashmap_put(ports, p->name, p);
+ pa_proplist_update(p->proplist, PA_UPDATE_REPLACE, path->proplist);
+
+ data = PA_DEVICE_PORT_DATA(p);
+ /* Ownership of the path and setting is not transferred to the port data, so we don't deal with freeing them */
+ data->path = path;
+ data->setting = setting;
+ path->port = p;
+ }
+
+ if (cp)
+ pa_hashmap_put(p->profiles, cp->name, cp);
+
+ if (extra) {
+ pa_hashmap_put(extra, p->name, p);
+ pa_device_port_ref(p);
+ }
+
+ return p;
+}
+
+void pa_alsa_path_set_add_ports(
+ pa_alsa_path_set *ps,
+ pa_card_profile *cp,
+ pa_hashmap *ports, /* card ports */
+ pa_hashmap *extra, /* sink/source ports */
+ pa_core *core) {
+
+ pa_alsa_path *path;
+ void *state;
+
+ pa_assert(ports);
+
+ if (!ps)
+ return;
+
+ PA_HASHMAP_FOREACH(path, ps->paths, state) {
+ if (!path->settings || !path->settings->next) {
+ /* If there is no or just one setting we only need a
+ * single entry */
+ pa_device_port *port = device_port_alsa_init(ports, path->name,
+ path->description, path, path->settings, cp, extra, core);
+ port->priority = path->priority * 100;
+
+ } else {
+ pa_alsa_setting *s;
+ PA_LLIST_FOREACH(s, path->settings) {
+ pa_device_port *port;
+ char *n, *d;
+
+ n = pa_sprintf_malloc("%s;%s", path->name, s->name);
+
+ if (s->description[0])
+ d = pa_sprintf_malloc("%s / %s", path->description, s->description);
+ else
+ d = pa_xstrdup(path->description);
+
+ port = device_port_alsa_init(ports, n, d, path, s, cp, extra, core);
+ port->priority = path->priority * 100 + s->priority;
+
+ pa_xfree(n);
+ pa_xfree(d);
+ }
+ }
+ }
+}
+
+void pa_alsa_add_ports(void *sink_or_source_new_data, pa_alsa_path_set *ps, pa_card *card) {
+ pa_hashmap *ports;
+
+ pa_assert(sink_or_source_new_data);
+ pa_assert(ps);
+
+ if (ps->direction == PA_ALSA_DIRECTION_OUTPUT)
+ ports = ((pa_sink_new_data *) sink_or_source_new_data)->ports;
+ else
+ ports = ((pa_source_new_data *) sink_or_source_new_data)->ports;
+
+ if (ps->paths && pa_hashmap_size(ps->paths) > 0) {
+ pa_assert(card);
+ pa_alsa_path_set_add_ports(ps, NULL, card->ports, ports, card->core);
+ }
+
+ pa_log_debug("Added %u ports", pa_hashmap_size(ports));
+}
diff --git a/src/modules/alsa/alsa-mixer.h b/src/modules/alsa/alsa-mixer.h
new file mode 100644
index 0000000..db83102
--- /dev/null
+++ b/src/modules/alsa/alsa-mixer.h
@@ -0,0 +1,411 @@
+#ifndef fooalsamixerhfoo
+#define fooalsamixerhfoo
+
+/***
+ This file is part of PulseAudio.
+
+ Copyright 2004-2006 Lennart Poettering
+ Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
+
+ PulseAudio is free software; you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License,
+ or (at your option) any later version.
+
+ PulseAudio is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <alsa/asoundlib.h>
+
+#include <pulse/sample.h>
+#include <pulse/mainloop-api.h>
+#include <pulse/channelmap.h>
+#include <pulse/volume.h>
+
+#include <pulsecore/llist.h>
+#include <pulsecore/rtpoll.h>
+
+typedef struct pa_alsa_fdlist pa_alsa_fdlist;
+typedef struct pa_alsa_mixer pa_alsa_mixer;
+typedef struct pa_alsa_mixer_pdata pa_alsa_mixer_pdata;
+typedef struct pa_alsa_setting pa_alsa_setting;
+typedef struct pa_alsa_mixer_id pa_alsa_mixer_id;
+typedef struct pa_alsa_option pa_alsa_option;
+typedef struct pa_alsa_element pa_alsa_element;
+typedef struct pa_alsa_jack pa_alsa_jack;
+typedef struct pa_alsa_path pa_alsa_path;
+typedef struct pa_alsa_path_set pa_alsa_path_set;
+typedef struct pa_alsa_mapping pa_alsa_mapping;
+typedef struct pa_alsa_profile pa_alsa_profile;
+typedef struct pa_alsa_decibel_fix pa_alsa_decibel_fix;
+typedef struct pa_alsa_profile_set pa_alsa_profile_set;
+typedef struct pa_alsa_port_data pa_alsa_port_data;
+
+#include "alsa-util.h"
+#include "alsa-ucm.h"
+
+#define POSITION_MASK_CHANNELS 8
+
+typedef enum pa_alsa_switch_use {
+ PA_ALSA_SWITCH_IGNORE,
+ PA_ALSA_SWITCH_MUTE, /* make this switch follow mute status */
+ PA_ALSA_SWITCH_OFF, /* set this switch to 'off' unconditionally */
+ PA_ALSA_SWITCH_ON, /* set this switch to 'on' unconditionally */
+ PA_ALSA_SWITCH_SELECT /* allow the user to select switch status through a setting */
+} pa_alsa_switch_use_t;
+
+typedef enum pa_alsa_volume_use {
+ PA_ALSA_VOLUME_IGNORE,
+ PA_ALSA_VOLUME_MERGE, /* merge this volume slider into the global volume slider */
+ PA_ALSA_VOLUME_OFF, /* set this volume to minimal unconditionally */
+ PA_ALSA_VOLUME_ZERO, /* set this volume to 0dB unconditionally */
+ PA_ALSA_VOLUME_CONSTANT /* set this volume to a constant value unconditionally */
+} pa_alsa_volume_use_t;
+
+typedef enum pa_alsa_enumeration_use {
+ PA_ALSA_ENUMERATION_IGNORE,
+ PA_ALSA_ENUMERATION_SELECT
+} pa_alsa_enumeration_use_t;
+
+typedef enum pa_alsa_required {
+ PA_ALSA_REQUIRED_IGNORE,
+ PA_ALSA_REQUIRED_SWITCH,
+ PA_ALSA_REQUIRED_VOLUME,
+ PA_ALSA_REQUIRED_ENUMERATION,
+ PA_ALSA_REQUIRED_ANY
+} pa_alsa_required_t;
+
+typedef enum pa_alsa_direction {
+ PA_ALSA_DIRECTION_ANY,
+ PA_ALSA_DIRECTION_OUTPUT,
+ PA_ALSA_DIRECTION_INPUT
+} pa_alsa_direction_t;
+
+/* A setting combines a couple of options into a single entity that
+ * may be selected. Only one setting can be active at the same
+ * time. */
+struct pa_alsa_setting {
+ pa_alsa_path *path;
+ PA_LLIST_FIELDS(pa_alsa_setting);
+
+ pa_idxset *options;
+
+ char *name;
+ char *description;
+ unsigned priority;
+};
+
+/* An entry for one ALSA mixer */
+struct pa_alsa_mixer {
+ snd_mixer_t *mixer_handle;
+ int card_index;
+ pa_alsa_fdlist *fdl;
+ bool used_for_probe_only:1;
+};
+
+/* ALSA mixer element identifier */
+struct pa_alsa_mixer_id {
+ char *name;
+ int index;
+};
+
+char *pa_alsa_mixer_id_to_string(char *dst, size_t dst_len, pa_alsa_mixer_id *id);
+
+/* An option belongs to an element and refers to one enumeration item
+ * of the element is an enumeration item, or a switch status if the
+ * element is a switch item. */
+struct pa_alsa_option {
+ pa_alsa_element *element;
+ PA_LLIST_FIELDS(pa_alsa_option);
+
+ char *alsa_name;
+ int alsa_idx;
+
+ char *name;
+ char *description;
+ unsigned priority;
+
+ pa_alsa_required_t required;
+ pa_alsa_required_t required_any;
+ pa_alsa_required_t required_absent;
+};
+
+/* An element wraps one specific ALSA element. A series of elements
+ * make up a path (see below). If the element is an enumeration or switch
+ * element it may include a list of options. */
+struct pa_alsa_element {
+ pa_alsa_path *path;
+ PA_LLIST_FIELDS(pa_alsa_element);
+
+ struct pa_alsa_mixer_id alsa_id;
+ pa_alsa_direction_t direction;
+
+ pa_alsa_switch_use_t switch_use;
+ pa_alsa_volume_use_t volume_use;
+ pa_alsa_enumeration_use_t enumeration_use;
+
+ pa_alsa_required_t required;
+ pa_alsa_required_t required_any;
+ pa_alsa_required_t required_absent;
+
+ long constant_volume;
+
+ unsigned int override_map;
+ bool direction_try_other:1;
+
+ bool has_dB:1;
+ long min_volume, max_volume;
+ long volume_limit; /* -1 for no configured limit */
+ double min_dB, max_dB;
+
+ pa_channel_position_mask_t masks[SND_MIXER_SCHN_LAST + 1][POSITION_MASK_CHANNELS];
+ unsigned n_channels;
+
+ pa_channel_position_mask_t merged_mask;
+
+ PA_LLIST_HEAD(pa_alsa_option, options);
+
+ pa_alsa_decibel_fix *db_fix;
+};
+
+struct pa_alsa_jack {
+ pa_alsa_path *path;
+ PA_LLIST_FIELDS(pa_alsa_jack);
+
+ snd_mixer_t *mixer_handle;
+ char *mixer_device_name;
+
+ struct pa_alsa_mixer_id alsa_id;
+ char *name; /* E g "Headphone" */
+ bool has_control; /* is the jack itself present? */
+ bool plugged_in; /* is this jack currently plugged in? */
+ snd_mixer_elem_t *melem; /* Jack detection handle */
+ pa_available_t state_unplugged, state_plugged;
+
+ pa_alsa_required_t required;
+ pa_alsa_required_t required_any;
+ pa_alsa_required_t required_absent;
+
+ pa_dynarray *ucm_devices; /* pa_alsa_ucm_device */
+ pa_dynarray *ucm_hw_mute_devices; /* pa_alsa_ucm_device */
+
+ bool append_pcm_to_name;
+};
+
+pa_alsa_jack *pa_alsa_jack_new(pa_alsa_path *path, const char *mixer_device_name, const char *name, int index);
+void pa_alsa_jack_free(pa_alsa_jack *jack);
+void pa_alsa_jack_set_has_control(pa_alsa_jack *jack, bool has_control);
+void pa_alsa_jack_set_plugged_in(pa_alsa_jack *jack, bool plugged_in);
+void pa_alsa_jack_add_ucm_device(pa_alsa_jack *jack, pa_alsa_ucm_device *device);
+void pa_alsa_jack_add_ucm_hw_mute_device(pa_alsa_jack *jack, pa_alsa_ucm_device *device);
+
+/* A path wraps a series of elements into a single entity which can be
+ * used to control it as if it had a single volume slider, a single
+ * mute switch and a single list of selectable options. */
+struct pa_alsa_path {
+ pa_alsa_direction_t direction;
+ pa_device_port* port;
+
+ char *name;
+ char *description_key;
+ char *description;
+ char *availability_group;
+ pa_device_port_type_t device_port_type;
+ unsigned priority;
+ bool autodetect_eld_device;
+ pa_alsa_mixer *eld_mixer_handle;
+ int eld_device;
+ pa_proplist *proplist;
+
+ bool probed:1;
+ bool supported:1;
+ bool has_mute:1;
+ bool has_volume:1;
+ bool has_dB:1;
+ bool mute_during_activation:1;
+ /* These two are used during probing only */
+ bool has_req_any:1;
+ bool req_any_present:1;
+
+ long min_volume, max_volume;
+ double min_dB, max_dB;
+
+ /* This is used during parsing only, as a shortcut so that we
+ * don't have to iterate the list all the time */
+ pa_alsa_element *last_element;
+ pa_alsa_option *last_option;
+ pa_alsa_setting *last_setting;
+ pa_alsa_jack *last_jack;
+
+ PA_LLIST_HEAD(pa_alsa_element, elements);
+ PA_LLIST_HEAD(pa_alsa_setting, settings);
+ PA_LLIST_HEAD(pa_alsa_jack, jacks);
+};
+
+/* A path set is simply a set of paths that are applicable to a
+ * device */
+struct pa_alsa_path_set {
+ pa_hashmap *paths;
+ pa_alsa_direction_t direction;
+};
+
+void pa_alsa_setting_dump(pa_alsa_setting *s);
+
+void pa_alsa_option_dump(pa_alsa_option *o);
+void pa_alsa_jack_dump(pa_alsa_jack *j);
+void pa_alsa_element_dump(pa_alsa_element *e);
+
+pa_alsa_path *pa_alsa_path_new(const char *paths_dir, const char *fname, pa_alsa_direction_t direction);
+pa_alsa_path *pa_alsa_path_synthesize(const char *element, pa_alsa_direction_t direction);
+pa_alsa_element *pa_alsa_element_get(pa_alsa_path *p, const char *section, bool prefixed);
+int pa_alsa_path_probe(pa_alsa_path *p, pa_alsa_mapping *mapping, snd_mixer_t *m, bool ignore_dB);
+void pa_alsa_path_dump(pa_alsa_path *p);
+int pa_alsa_path_get_volume(pa_alsa_path *p, snd_mixer_t *m, const pa_channel_map *cm, pa_cvolume *v);
+int pa_alsa_path_get_mute(pa_alsa_path *path, snd_mixer_t *m, bool *muted);
+int pa_alsa_path_set_volume(pa_alsa_path *path, snd_mixer_t *m, const pa_channel_map *cm, pa_cvolume *v, bool deferred_volume, bool write_to_hw);
+int pa_alsa_path_set_mute(pa_alsa_path *path, snd_mixer_t *m, bool muted);
+int pa_alsa_path_select(pa_alsa_path *p, pa_alsa_setting *s, snd_mixer_t *m, bool device_is_muted);
+void pa_alsa_path_set_callback(pa_alsa_path *p, snd_mixer_t *m, snd_mixer_elem_callback_t cb, void *userdata);
+void pa_alsa_path_free(pa_alsa_path *p);
+
+pa_alsa_path_set *pa_alsa_path_set_new(pa_alsa_mapping *m, pa_alsa_direction_t direction, const char *paths_dir);
+void pa_alsa_path_set_dump(pa_alsa_path_set *s);
+void pa_alsa_path_set_set_callback(pa_alsa_path_set *ps, snd_mixer_t *m, snd_mixer_elem_callback_t cb, void *userdata);
+void pa_alsa_path_set_free(pa_alsa_path_set *s);
+int pa_alsa_path_set_is_empty(pa_alsa_path_set *s);
+
+struct pa_alsa_mapping {
+ pa_alsa_profile_set *profile_set;
+
+ char *name;
+ char *description;
+ char *description_key;
+ unsigned priority;
+ pa_alsa_direction_t direction;
+ /* These are copied over to the resultant sink/source */
+ pa_proplist *proplist;
+
+ pa_sample_spec sample_spec;
+ pa_channel_map channel_map;
+
+ char **device_strings;
+
+ char **input_path_names;
+ char **output_path_names;
+ char **input_element; /* list of fallbacks */
+ char **output_element;
+ pa_alsa_path_set *input_path_set;
+ pa_alsa_path_set *output_path_set;
+
+ unsigned supported;
+ bool exact_channels:1;
+ bool fallback:1;
+
+ /* The "y" in "hw:x,y". This is set to -1 before the device index has been
+ * queried, or if the query failed. */
+ int hw_device_index;
+
+ /* Temporarily used during probing */
+ snd_pcm_t *input_pcm;
+ snd_pcm_t *output_pcm;
+
+ pa_sink *sink;
+ pa_source *source;
+
+ /* ucm device context*/
+ pa_alsa_ucm_mapping_context ucm_context;
+};
+
+struct pa_alsa_profile {
+ pa_alsa_profile_set *profile_set;
+
+ char *name;
+ char *description;
+ char *description_key;
+ unsigned priority;
+
+ char *input_name;
+ char *output_name;
+
+ bool supported:1;
+ bool fallback_input:1;
+ bool fallback_output:1;
+
+ char **input_mapping_names;
+ char **output_mapping_names;
+
+ pa_idxset *input_mappings;
+ pa_idxset *output_mappings;
+};
+
+struct pa_alsa_decibel_fix {
+ char *key;
+
+ pa_alsa_profile_set *profile_set;
+
+ char *name; /* Alsa volume element name. */
+ int index; /* Alsa volume element index. */
+ long min_step;
+ long max_step;
+
+ /* An array that maps alsa volume element steps to decibels. The steps can
+ * be used as indices to this array, after subtracting min_step from the
+ * real value.
+ *
+ * The values are actually stored as integers representing millibels,
+ * because that's the format the alsa API uses. */
+ long *db_values;
+};
+
+struct pa_alsa_profile_set {
+ pa_hashmap *mappings;
+ pa_hashmap *profiles;
+ pa_hashmap *decibel_fixes;
+ pa_hashmap *input_paths;
+ pa_hashmap *output_paths;
+
+ bool auto_profiles;
+ bool ignore_dB:1;
+ bool probed:1;
+};
+
+void pa_alsa_mapping_dump(pa_alsa_mapping *m);
+void pa_alsa_profile_dump(pa_alsa_profile *p);
+void pa_alsa_decibel_fix_dump(pa_alsa_decibel_fix *db_fix);
+pa_alsa_mapping *pa_alsa_mapping_get(pa_alsa_profile_set *ps, const char *name);
+
+pa_alsa_profile_set* pa_alsa_profile_set_new(const char *fname, const pa_channel_map *bonus);
+void pa_alsa_profile_set_probe(pa_alsa_profile_set *ps, pa_hashmap *mixers, const char *dev_id, const pa_sample_spec *ss, unsigned default_n_fragments, unsigned default_fragment_size_msec);
+void pa_alsa_profile_set_free(pa_alsa_profile_set *s);
+void pa_alsa_profile_set_dump(pa_alsa_profile_set *s);
+void pa_alsa_profile_set_drop_unsupported(pa_alsa_profile_set *s);
+
+pa_alsa_fdlist *pa_alsa_fdlist_new(void);
+void pa_alsa_fdlist_free(pa_alsa_fdlist *fdl);
+int pa_alsa_fdlist_set_handle(pa_alsa_fdlist *fdl, snd_mixer_t *mixer_handle, snd_hctl_t *hctl_handle, pa_mainloop_api* m);
+
+/* Alternative for handling alsa mixer events in io-thread. */
+
+pa_alsa_mixer_pdata *pa_alsa_mixer_pdata_new(void);
+void pa_alsa_mixer_pdata_free(pa_alsa_mixer_pdata *pd);
+int pa_alsa_set_mixer_rtpoll(struct pa_alsa_mixer_pdata *pd, snd_mixer_t *mixer, pa_rtpoll *rtp);
+
+/* Data structure for inclusion in pa_device_port for alsa
+ * sinks/sources. This contains nothing that needs to be freed
+ * individually */
+struct pa_alsa_port_data {
+ pa_alsa_path *path;
+ pa_alsa_setting *setting;
+ bool suspend_when_unavailable;
+};
+
+void pa_alsa_add_ports(void *sink_or_source_new_data, pa_alsa_path_set *ps, pa_card *card);
+void pa_alsa_path_set_add_ports(pa_alsa_path_set *ps, pa_card_profile *cp, pa_hashmap *ports, pa_hashmap *extra, pa_core *core);
+
+#endif
diff --git a/src/modules/alsa/alsa-sink.c b/src/modules/alsa/alsa-sink.c
new file mode 100644
index 0000000..f7fef8a
--- /dev/null
+++ b/src/modules/alsa/alsa-sink.c
@@ -0,0 +1,2832 @@
+/***
+ This file is part of PulseAudio.
+
+ Copyright 2004-2008 Lennart Poettering
+ Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
+
+ PulseAudio is free software; you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License,
+ or (at your option) any later version.
+
+ PulseAudio is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+***/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <signal.h>
+#include <stdio.h>
+
+#include <alsa/asoundlib.h>
+
+#ifdef HAVE_VALGRIND_MEMCHECK_H
+#include <valgrind/memcheck.h>
+#endif
+
+#include <pulse/rtclock.h>
+#include <pulse/timeval.h>
+#include <pulse/util.h>
+#include <pulse/volume.h>
+#include <pulse/xmalloc.h>
+#include <pulse/internal.h>
+
+#include <pulsecore/core.h>
+#include <pulsecore/i18n.h>
+#include <pulsecore/module.h>
+#include <pulsecore/memchunk.h>
+#include <pulsecore/sink.h>
+#include <pulsecore/modargs.h>
+#include <pulsecore/core-rtclock.h>
+#include <pulsecore/core-util.h>
+#include <pulsecore/sample-util.h>
+#include <pulsecore/log.h>
+#include <pulsecore/macro.h>
+#include <pulsecore/thread.h>
+#include <pulsecore/thread-mq.h>
+#include <pulsecore/rtpoll.h>
+#include <pulsecore/time-smoother.h>
+
+#include <modules/reserve-wrap.h>
+
+#include "alsa-util.h"
+#include "alsa-sink.h"
+
+/* #define DEBUG_TIMING */
+
+#define DEFAULT_DEVICE "default"
+
+#define DEFAULT_TSCHED_BUFFER_USEC (2*PA_USEC_PER_SEC) /* 2s -- Overall buffer size */
+#define DEFAULT_TSCHED_WATERMARK_USEC (20*PA_USEC_PER_MSEC) /* 20ms -- Fill up when only this much is left in the buffer */
+
+#define TSCHED_WATERMARK_INC_STEP_USEC (10*PA_USEC_PER_MSEC) /* 10ms -- On underrun, increase watermark by this */
+#define TSCHED_WATERMARK_DEC_STEP_USEC (5*PA_USEC_PER_MSEC) /* 5ms -- When everything's great, decrease watermark by this */
+#define TSCHED_WATERMARK_VERIFY_AFTER_USEC (20*PA_USEC_PER_SEC) /* 20s -- How long after a drop out recheck if things are good now */
+#define TSCHED_WATERMARK_INC_THRESHOLD_USEC (0*PA_USEC_PER_MSEC) /* 0ms -- If the buffer level ever below this threshold, increase the watermark */
+#define TSCHED_WATERMARK_DEC_THRESHOLD_USEC (100*PA_USEC_PER_MSEC) /* 100ms -- If the buffer level didn't drop below this threshold in the verification time, decrease the watermark */
+
+/* Note that TSCHED_WATERMARK_INC_THRESHOLD_USEC == 0 means that we
+ * will increase the watermark only if we hit a real underrun. */
+
+#define TSCHED_MIN_SLEEP_USEC (10*PA_USEC_PER_MSEC) /* 10ms -- Sleep at least 10ms on each iteration */
+#define TSCHED_MIN_WAKEUP_USEC (4*PA_USEC_PER_MSEC) /* 4ms -- Wakeup at least this long before the buffer runs empty*/
+
+#define SMOOTHER_WINDOW_USEC (10*PA_USEC_PER_SEC) /* 10s -- smoother windows size */
+#define SMOOTHER_ADJUST_USEC (1*PA_USEC_PER_SEC) /* 1s -- smoother adjust time */
+
+#define SMOOTHER_MIN_INTERVAL (2*PA_USEC_PER_MSEC) /* 2ms -- min smoother update interval */
+#define SMOOTHER_MAX_INTERVAL (200*PA_USEC_PER_MSEC) /* 200ms -- max smoother update interval */
+
+#define VOLUME_ACCURACY (PA_VOLUME_NORM/100) /* don't require volume adjustments to be perfectly correct. don't necessarily extend granularity in software unless the differences get greater than this level */
+
+#define DEFAULT_REWIND_SAFEGUARD_BYTES (256U) /* 1.33ms @48kHz, we'll never rewind less than this */
+#define DEFAULT_REWIND_SAFEGUARD_USEC (1330) /* 1.33ms, depending on channels/rate/sample we may rewind more than 256 above */
+
+#define DEFAULT_WRITE_ITERATION_THRESHOLD 0.03 /* don't iterate write if < 3% of the buffer is available */
+
+struct userdata {
+ pa_core *core;
+ pa_module *module;
+ pa_sink *sink;
+
+ pa_thread *thread;
+ pa_thread_mq thread_mq;
+ pa_rtpoll *rtpoll;
+
+ snd_pcm_t *pcm_handle;
+
+ char *paths_dir;
+ pa_alsa_fdlist *mixer_fdl;
+ pa_alsa_mixer_pdata *mixer_pd;
+ pa_hashmap *mixers;
+ snd_mixer_t *mixer_handle;
+ pa_alsa_path_set *mixer_path_set;
+ pa_alsa_path *mixer_path;
+
+ pa_cvolume hardware_volume;
+
+ pa_sample_spec verified_sample_spec;
+ pa_sample_format_t *supported_formats;
+ unsigned int *supported_rates;
+ struct {
+ size_t fragment_size;
+ size_t nfrags;
+ size_t tsched_size;
+ size_t tsched_watermark;
+ size_t rewind_safeguard;
+ } initial_info;
+
+ size_t
+ frame_size,
+ fragment_size,
+ hwbuf_size,
+ tsched_size,
+ tsched_watermark,
+ tsched_watermark_ref,
+ hwbuf_unused,
+ min_sleep,
+ min_wakeup,
+ watermark_inc_step,
+ watermark_dec_step,
+ watermark_inc_threshold,
+ watermark_dec_threshold,
+ rewind_safeguard;
+
+ snd_pcm_uframes_t frames_per_block;
+
+ pa_usec_t watermark_dec_not_before;
+ pa_usec_t min_latency_ref;
+ pa_usec_t tsched_watermark_usec;
+
+ pa_memchunk memchunk;
+
+ char *device_name; /* name of the PCM device */
+ char *control_device; /* name of the control device */
+
+ bool use_mmap:1, use_tsched:1, deferred_volume:1, fixed_latency_range:1;
+
+ bool first, after_rewind;
+
+ pa_rtpoll_item *alsa_rtpoll_item;
+
+ pa_smoother *smoother;
+ uint64_t write_count;
+ uint64_t since_start;
+ pa_usec_t smoother_interval;
+ pa_usec_t last_smoother_update;
+
+ pa_idxset *formats;
+
+ pa_reserve_wrapper *reserve;
+ pa_hook_slot *reserve_slot;
+ pa_reserve_monitor_wrapper *monitor;
+ pa_hook_slot *monitor_slot;
+
+ /* ucm context */
+ pa_alsa_ucm_mapping_context *ucm_context;
+};
+
+enum {
+ SINK_MESSAGE_SYNC_MIXER = PA_SINK_MESSAGE_MAX
+};
+
+static void userdata_free(struct userdata *u);
+static int unsuspend(struct userdata *u, bool recovering);
+
+/* FIXME: Is there a better way to do this than device names? */
+static bool is_iec958(struct userdata *u) {
+ return (strncmp("iec958", u->device_name, 6) == 0);
+}
+
+static bool is_hdmi(struct userdata *u) {
+ return (strncmp("hdmi", u->device_name, 4) == 0);
+}
+
+static pa_hook_result_t reserve_cb(pa_reserve_wrapper *r, void *forced, struct userdata *u) {
+ pa_assert(r);
+ pa_assert(u);
+
+ pa_log_debug("Suspending sink %s, because another application requested us to release the device.", u->sink->name);
+
+ if (pa_sink_suspend(u->sink, true, PA_SUSPEND_APPLICATION) < 0)
+ return PA_HOOK_CANCEL;
+
+ return PA_HOOK_OK;
+}
+
+static void reserve_done(struct userdata *u) {
+ pa_assert(u);
+
+ if (u->reserve_slot) {
+ pa_hook_slot_free(u->reserve_slot);
+ u->reserve_slot = NULL;
+ }
+
+ if (u->reserve) {
+ pa_reserve_wrapper_unref(u->reserve);
+ u->reserve = NULL;
+ }
+}
+
+static void reserve_update(struct userdata *u) {
+ const char *description;
+ pa_assert(u);
+
+ if (!u->sink || !u->reserve)
+ return;
+
+ if ((description = pa_proplist_gets(u->sink->proplist, PA_PROP_DEVICE_DESCRIPTION)))
+ pa_reserve_wrapper_set_application_device_name(u->reserve, description);
+}
+
+static int reserve_init(struct userdata *u, const char *dname) {
+ char *rname;
+
+ pa_assert(u);
+ pa_assert(dname);
+
+ if (u->reserve)
+ return 0;
+
+ if (pa_in_system_mode())
+ return 0;
+
+ if (!(rname = pa_alsa_get_reserve_name(dname)))
+ return 0;
+
+ /* We are resuming, try to lock the device */
+ u->reserve = pa_reserve_wrapper_get(u->core, rname);
+ pa_xfree(rname);
+
+ if (!(u->reserve))
+ return -1;
+
+ reserve_update(u);
+
+ pa_assert(!u->reserve_slot);
+ u->reserve_slot = pa_hook_connect(pa_reserve_wrapper_hook(u->reserve), PA_HOOK_NORMAL, (pa_hook_cb_t) reserve_cb, u);
+
+ return 0;
+}
+
+static pa_hook_result_t monitor_cb(pa_reserve_monitor_wrapper *w, void* busy, struct userdata *u) {
+ pa_assert(w);
+ pa_assert(u);
+
+ if (PA_PTR_TO_UINT(busy) && !u->reserve) {
+ pa_log_debug("Suspending sink %s, because another application is blocking the access to the device.", u->sink->name);
+ pa_sink_suspend(u->sink, true, PA_SUSPEND_APPLICATION);
+ } else {
+ pa_log_debug("Resuming sink %s, because other applications aren't blocking access to the device any more.", u->sink->name);
+ pa_sink_suspend(u->sink, false, PA_SUSPEND_APPLICATION);
+ }
+
+ return PA_HOOK_OK;
+}
+
+static void monitor_done(struct userdata *u) {
+ pa_assert(u);
+
+ if (u->monitor_slot) {
+ pa_hook_slot_free(u->monitor_slot);
+ u->monitor_slot = NULL;
+ }
+
+ if (u->monitor) {
+ pa_reserve_monitor_wrapper_unref(u->monitor);
+ u->monitor = NULL;
+ }
+}
+
+static int reserve_monitor_init(struct userdata *u, const char *dname) {
+ char *rname;
+
+ pa_assert(u);
+ pa_assert(dname);
+
+ if (pa_in_system_mode())
+ return 0;
+
+ if (!(rname = pa_alsa_get_reserve_name(dname)))
+ return 0;
+
+ /* We are resuming, try to lock the device */
+ u->monitor = pa_reserve_monitor_wrapper_get(u->core, rname);
+ pa_xfree(rname);
+
+ if (!(u->monitor))
+ return -1;
+
+ pa_assert(!u->monitor_slot);
+ u->monitor_slot = pa_hook_connect(pa_reserve_monitor_wrapper_hook(u->monitor), PA_HOOK_NORMAL, (pa_hook_cb_t) monitor_cb, u);
+
+ return 0;
+}
+
+static void fix_min_sleep_wakeup(struct userdata *u) {
+ size_t max_use, max_use_2;
+
+ pa_assert(u);
+ pa_assert(u->use_tsched);
+
+ max_use = u->hwbuf_size - u->hwbuf_unused;
+ max_use_2 = pa_frame_align(max_use/2, &u->sink->sample_spec);
+
+ u->min_sleep = pa_usec_to_bytes(TSCHED_MIN_SLEEP_USEC, &u->sink->sample_spec);
+ u->min_sleep = PA_CLAMP(u->min_sleep, u->frame_size, max_use_2);
+
+ u->min_wakeup = pa_usec_to_bytes(TSCHED_MIN_WAKEUP_USEC, &u->sink->sample_spec);
+ u->min_wakeup = PA_CLAMP(u->min_wakeup, u->frame_size, max_use_2);
+}
+
+static void fix_tsched_watermark(struct userdata *u) {
+ size_t max_use;
+ pa_assert(u);
+ pa_assert(u->use_tsched);
+
+ max_use = u->hwbuf_size - u->hwbuf_unused;
+
+ if (u->tsched_watermark > max_use - u->min_sleep)
+ u->tsched_watermark = max_use - u->min_sleep;
+
+ if (u->tsched_watermark < u->min_wakeup)
+ u->tsched_watermark = u->min_wakeup;
+
+ u->tsched_watermark_usec = pa_bytes_to_usec(u->tsched_watermark, &u->sink->sample_spec);
+}
+
+static void increase_watermark(struct userdata *u) {
+ size_t old_watermark;
+ pa_usec_t old_min_latency, new_min_latency;
+
+ pa_assert(u);
+ pa_assert(u->use_tsched);
+
+ /* First, just try to increase the watermark */
+ old_watermark = u->tsched_watermark;
+ u->tsched_watermark = PA_MIN(u->tsched_watermark * 2, u->tsched_watermark + u->watermark_inc_step);
+ fix_tsched_watermark(u);
+
+ if (old_watermark != u->tsched_watermark) {
+ pa_log_info("Increasing wakeup watermark to %0.2f ms",
+ (double) u->tsched_watermark_usec / PA_USEC_PER_MSEC);
+ return;
+ }
+
+ /* Hmm, we cannot increase the watermark any further, hence let's
+ raise the latency, unless doing so was disabled in
+ configuration */
+ if (u->fixed_latency_range)
+ return;
+
+ old_min_latency = u->sink->thread_info.min_latency;
+ new_min_latency = PA_MIN(old_min_latency * 2, old_min_latency + TSCHED_WATERMARK_INC_STEP_USEC);
+ new_min_latency = PA_MIN(new_min_latency, u->sink->thread_info.max_latency);
+
+ if (old_min_latency != new_min_latency) {
+ pa_log_info("Increasing minimal latency to %0.2f ms",
+ (double) new_min_latency / PA_USEC_PER_MSEC);
+
+ pa_sink_set_latency_range_within_thread(u->sink, new_min_latency, u->sink->thread_info.max_latency);
+ }
+
+ /* When we reach this we're officially fucked! */
+}
+
+static void decrease_watermark(struct userdata *u) {
+ size_t old_watermark;
+ pa_usec_t now;
+
+ pa_assert(u);
+ pa_assert(u->use_tsched);
+
+ now = pa_rtclock_now();
+
+ if (u->watermark_dec_not_before <= 0)
+ goto restart;
+
+ if (u->watermark_dec_not_before > now)
+ return;
+
+ old_watermark = u->tsched_watermark;
+
+ if (u->tsched_watermark < u->watermark_dec_step)
+ u->tsched_watermark = u->tsched_watermark / 2;
+ else
+ u->tsched_watermark = PA_MAX(u->tsched_watermark / 2, u->tsched_watermark - u->watermark_dec_step);
+
+ fix_tsched_watermark(u);
+
+ if (old_watermark != u->tsched_watermark)
+ pa_log_info("Decreasing wakeup watermark to %0.2f ms",
+ (double) u->tsched_watermark_usec / PA_USEC_PER_MSEC);
+
+ /* We don't change the latency range*/
+
+restart:
+ u->watermark_dec_not_before = now + TSCHED_WATERMARK_VERIFY_AFTER_USEC;
+}
+
+/* Called from IO Context on unsuspend or from main thread when creating sink */
+static void reset_watermark(struct userdata *u, size_t tsched_watermark, pa_sample_spec *ss,
+ bool in_thread) {
+ u->tsched_watermark = pa_convert_size(tsched_watermark, ss, &u->sink->sample_spec);
+
+ u->watermark_inc_step = pa_usec_to_bytes(TSCHED_WATERMARK_INC_STEP_USEC, &u->sink->sample_spec);
+ u->watermark_dec_step = pa_usec_to_bytes(TSCHED_WATERMARK_DEC_STEP_USEC, &u->sink->sample_spec);
+
+ u->watermark_inc_threshold = pa_usec_to_bytes_round_up(TSCHED_WATERMARK_INC_THRESHOLD_USEC, &u->sink->sample_spec);
+ u->watermark_dec_threshold = pa_usec_to_bytes_round_up(TSCHED_WATERMARK_DEC_THRESHOLD_USEC, &u->sink->sample_spec);
+
+ fix_min_sleep_wakeup(u);
+ fix_tsched_watermark(u);
+
+ if (in_thread)
+ pa_sink_set_latency_range_within_thread(u->sink,
+ u->min_latency_ref,
+ pa_bytes_to_usec(u->hwbuf_size, ss));
+ else {
+ pa_sink_set_latency_range(u->sink,
+ 0,
+ pa_bytes_to_usec(u->hwbuf_size, ss));
+
+ /* work-around assert in pa_sink_set_latency_within_thead,
+ keep track of min_latency and reuse it when
+ this routine is called from IO context */
+ u->min_latency_ref = u->sink->thread_info.min_latency;
+ }
+
+ pa_log_info("Time scheduling watermark is %0.2fms",
+ (double) u->tsched_watermark_usec / PA_USEC_PER_MSEC);
+}
+
+static void hw_sleep_time(struct userdata *u, pa_usec_t *sleep_usec, pa_usec_t*process_usec) {
+ pa_usec_t usec, wm;
+
+ pa_assert(sleep_usec);
+ pa_assert(process_usec);
+
+ pa_assert(u);
+ pa_assert(u->use_tsched);
+
+ usec = pa_sink_get_requested_latency_within_thread(u->sink);
+
+ if (usec == (pa_usec_t) -1)
+ usec = pa_bytes_to_usec(u->hwbuf_size, &u->sink->sample_spec);
+
+ wm = u->tsched_watermark_usec;
+
+ if (wm > usec)
+ wm = usec/2;
+
+ *sleep_usec = usec - wm;
+ *process_usec = wm;
+
+#ifdef DEBUG_TIMING
+ pa_log_debug("Buffer time: %lu ms; Sleep time: %lu ms; Process time: %lu ms",
+ (unsigned long) (usec / PA_USEC_PER_MSEC),
+ (unsigned long) (*sleep_usec / PA_USEC_PER_MSEC),
+ (unsigned long) (*process_usec / PA_USEC_PER_MSEC));
+#endif
+}
+
+/* Reset smoother and counters */
+static void reset_vars(struct userdata *u) {
+
+ pa_smoother_reset(u->smoother, pa_rtclock_now(), true);
+ u->smoother_interval = SMOOTHER_MIN_INTERVAL;
+ u->last_smoother_update = 0;
+
+ u->first = true;
+ u->since_start = 0;
+ u->write_count = 0;
+}
+
+/* Called from IO context */
+static void close_pcm(struct userdata *u) {
+ /* Let's suspend -- we don't call snd_pcm_drain() here since that might
+ * take awfully long with our long buffer sizes today. */
+ snd_pcm_close(u->pcm_handle);
+ u->pcm_handle = NULL;
+
+ if (u->alsa_rtpoll_item) {
+ pa_rtpoll_item_free(u->alsa_rtpoll_item);
+ u->alsa_rtpoll_item = NULL;
+ }
+}
+
+static int try_recover(struct userdata *u, const char *call, int err) {
+ pa_assert(u);
+ pa_assert(call);
+ pa_assert(err < 0);
+
+ pa_log_debug("%s: %s", call, pa_alsa_strerror(err));
+
+ pa_assert(err != -EAGAIN);
+
+ if (err == -EPIPE)
+ pa_log_debug("%s: Buffer underrun!", call);
+
+ if (err == -ESTRPIPE)
+ pa_log_debug("%s: System suspended!", call);
+
+ if ((err = snd_pcm_recover(u->pcm_handle, err, 1)) < 0) {
+ pa_log("%s: %s, trying to restart PCM", call, pa_alsa_strerror(err));
+
+ /* As a last measure, restart the PCM and inform the caller about it. */
+ close_pcm(u);
+ if (unsuspend(u, true) < 0)
+ return -1;
+
+ return 1;
+ }
+
+ reset_vars(u);
+ return 0;
+}
+
+static size_t check_left_to_play(struct userdata *u, size_t n_bytes, bool on_timeout) {
+ size_t left_to_play;
+ bool underrun = false;
+
+ /* We use <= instead of < for this check here because an underrun
+ * only happens after the last sample was processed, not already when
+ * it is removed from the buffer. This is particularly important
+ * when block transfer is used. */
+
+ if (n_bytes <= u->hwbuf_size)
+ left_to_play = u->hwbuf_size - n_bytes;
+ else {
+
+ /* We got a dropout. What a mess! */
+ left_to_play = 0;
+ underrun = true;
+
+#if 0
+ PA_DEBUG_TRAP;
+#endif
+
+ if (!u->first && !u->after_rewind)
+ if (pa_log_ratelimit(PA_LOG_INFO))
+ pa_log_info("Underrun!");
+ }
+
+#ifdef DEBUG_TIMING
+ pa_log_debug("%0.2f ms left to play; inc threshold = %0.2f ms; dec threshold = %0.2f ms",
+ (double) pa_bytes_to_usec(left_to_play, &u->sink->sample_spec) / PA_USEC_PER_MSEC,
+ (double) pa_bytes_to_usec(u->watermark_inc_threshold, &u->sink->sample_spec) / PA_USEC_PER_MSEC,
+ (double) pa_bytes_to_usec(u->watermark_dec_threshold, &u->sink->sample_spec) / PA_USEC_PER_MSEC);
+#endif
+
+ if (u->use_tsched) {
+ bool reset_not_before = true;
+
+ if (!u->first && !u->after_rewind) {
+ if (underrun || left_to_play < u->watermark_inc_threshold)
+ increase_watermark(u);
+ else if (left_to_play > u->watermark_dec_threshold) {
+ reset_not_before = false;
+
+ /* We decrease the watermark only if have actually
+ * been woken up by a timeout. If something else woke
+ * us up it's too easy to fulfill the deadlines... */
+
+ if (on_timeout)
+ decrease_watermark(u);
+ }
+ }
+
+ if (reset_not_before)
+ u->watermark_dec_not_before = 0;
+ }
+
+ return left_to_play;
+}
+
+static int mmap_write(struct userdata *u, pa_usec_t *sleep_usec, bool polled, bool on_timeout) {
+ bool work_done = false;
+ pa_usec_t max_sleep_usec = 0, process_usec = 0;
+ size_t left_to_play, input_underrun;
+ unsigned j = 0;
+
+ pa_assert(u);
+ pa_sink_assert_ref(u->sink);
+
+ if (u->use_tsched)
+ hw_sleep_time(u, &max_sleep_usec, &process_usec);
+
+ for (;;) {
+ snd_pcm_sframes_t n;
+ size_t n_bytes;
+ int r;
+ bool after_avail = true;
+
+ /* First we determine how many samples are missing to fill the
+ * buffer up to 100% */
+
+ if (PA_UNLIKELY((n = pa_alsa_safe_avail(u->pcm_handle, u->hwbuf_size, &u->sink->sample_spec)) < 0)) {
+
+ if ((r = try_recover(u, "snd_pcm_avail", (int) n)) >= 0)
+ continue;
+
+ return r;
+ }
+
+ n_bytes = (size_t) n * u->frame_size;
+
+#ifdef DEBUG_TIMING
+ pa_log_debug("avail: %lu", (unsigned long) n_bytes);
+#endif
+
+ left_to_play = check_left_to_play(u, n_bytes, on_timeout);
+ on_timeout = false;
+
+ if (u->use_tsched)
+
+ /* We won't fill up the playback buffer before at least
+ * half the sleep time is over because otherwise we might
+ * ask for more data from the clients then they expect. We
+ * need to guarantee that clients only have to keep around
+ * a single hw buffer length. */
+
+ if (!polled &&
+ pa_bytes_to_usec(left_to_play, &u->sink->sample_spec) > process_usec+max_sleep_usec/2) {
+#ifdef DEBUG_TIMING
+ pa_log_debug("Not filling up, because too early.");
+#endif
+ break;
+ }
+
+ if (PA_UNLIKELY(n_bytes <= u->hwbuf_unused)) {
+
+ if (polled)
+ PA_ONCE_BEGIN {
+ char *dn = pa_alsa_get_driver_name_by_pcm(u->pcm_handle);
+ pa_log(_("ALSA woke us up to write new data to the device, but there was actually nothing to write.\n"
+ "Most likely this is a bug in the ALSA driver '%s'. Please report this issue to the ALSA developers.\n"
+ "We were woken up with POLLOUT set -- however a subsequent snd_pcm_avail() returned 0 or another value < min_avail."),
+ pa_strnull(dn));
+ pa_xfree(dn);
+ } PA_ONCE_END;
+
+#ifdef DEBUG_TIMING
+ pa_log_debug("Not filling up, because not necessary.");
+#endif
+ break;
+ }
+
+ j++;
+
+ if (j > 10) {
+#ifdef DEBUG_TIMING
+ pa_log_debug("Not filling up, because already too many iterations.");
+#endif
+
+ break;
+ } else if (j >= 2 && (n_bytes < (DEFAULT_WRITE_ITERATION_THRESHOLD * (u->hwbuf_size - u->hwbuf_unused)))) {
+#ifdef DEBUG_TIMING
+ pa_log_debug("Not filling up, because <%g%% available.", DEFAULT_WRITE_ITERATION_THRESHOLD * 100);
+#endif
+ break;
+ }
+
+ n_bytes -= u->hwbuf_unused;
+ polled = false;
+
+#ifdef DEBUG_TIMING
+ pa_log_debug("Filling up");
+#endif
+
+ for (;;) {
+ pa_memchunk chunk;
+ void *p;
+ int err;
+ const snd_pcm_channel_area_t *areas;
+ snd_pcm_uframes_t offset, frames;
+ snd_pcm_sframes_t sframes;
+ size_t written;
+
+ frames = (snd_pcm_uframes_t) (n_bytes / u->frame_size);
+/* pa_log_debug("%lu frames to write", (unsigned long) frames); */
+
+ if (PA_UNLIKELY((err = pa_alsa_safe_mmap_begin(u->pcm_handle, &areas, &offset, &frames, u->hwbuf_size, &u->sink->sample_spec)) < 0)) {
+
+ if (!after_avail && err == -EAGAIN)
+ break;
+
+ if ((r = try_recover(u, "snd_pcm_mmap_begin", err)) == 0)
+ continue;
+
+ if (r == 1)
+ break;
+
+ return r;
+ }
+
+ /* Make sure that if these memblocks need to be copied they will fit into one slot */
+ frames = PA_MIN(frames, u->frames_per_block);
+
+ if (!after_avail && frames == 0)
+ break;
+
+ pa_assert(frames > 0);
+ after_avail = false;
+
+ /* Check these are multiples of 8 bit */
+ pa_assert((areas[0].first & 7) == 0);
+ pa_assert((areas[0].step & 7) == 0);
+
+ /* We assume a single interleaved memory buffer */
+ pa_assert((areas[0].first >> 3) == 0);
+ pa_assert((areas[0].step >> 3) == u->frame_size);
+
+ p = (uint8_t*) areas[0].addr + (offset * u->frame_size);
+
+ written = frames * u->frame_size;
+ chunk.memblock = pa_memblock_new_fixed(u->core->mempool, p, written, true);
+ chunk.length = pa_memblock_get_length(chunk.memblock);
+ chunk.index = 0;
+
+ pa_sink_render_into_full(u->sink, &chunk);
+ pa_memblock_unref_fixed(chunk.memblock);
+
+ if (PA_UNLIKELY((sframes = snd_pcm_mmap_commit(u->pcm_handle, offset, frames)) < 0)) {
+
+ if ((int) sframes == -EAGAIN)
+ break;
+
+ if ((r = try_recover(u, "snd_pcm_mmap_commit", (int) sframes)) == 0)
+ continue;
+
+ if (r == 1)
+ break;
+
+ return r;
+ }
+
+ work_done = true;
+
+ u->write_count += written;
+ u->since_start += written;
+
+#ifdef DEBUG_TIMING
+ pa_log_debug("Wrote %lu bytes (of possible %lu bytes)", (unsigned long) written, (unsigned long) n_bytes);
+#endif
+
+ if (written >= n_bytes)
+ break;
+
+ n_bytes -= written;
+ }
+ }
+
+ input_underrun = pa_sink_process_input_underruns(u->sink, left_to_play);
+
+ if (u->use_tsched) {
+ pa_usec_t underrun_sleep = pa_bytes_to_usec_round_up(input_underrun, &u->sink->sample_spec);
+
+ *sleep_usec = pa_bytes_to_usec(left_to_play, &u->sink->sample_spec);
+ process_usec = u->tsched_watermark_usec;
+
+ if (*sleep_usec > process_usec)
+ *sleep_usec -= process_usec;
+ else
+ *sleep_usec = 0;
+
+ *sleep_usec = PA_MIN(*sleep_usec, underrun_sleep);
+ } else
+ *sleep_usec = 0;
+
+ return work_done ? 1 : 0;
+}
+
+static int unix_write(struct userdata *u, pa_usec_t *sleep_usec, bool polled, bool on_timeout) {
+ bool work_done = false;
+ pa_usec_t max_sleep_usec = 0, process_usec = 0;
+ size_t left_to_play, input_underrun;
+ unsigned j = 0;
+
+ pa_assert(u);
+ pa_sink_assert_ref(u->sink);
+
+ if (u->use_tsched)
+ hw_sleep_time(u, &max_sleep_usec, &process_usec);
+
+ for (;;) {
+ snd_pcm_sframes_t n;
+ size_t n_bytes;
+ int r;
+ bool after_avail = true;
+
+ if (PA_UNLIKELY((n = pa_alsa_safe_avail(u->pcm_handle, u->hwbuf_size, &u->sink->sample_spec)) < 0)) {
+
+ if ((r = try_recover(u, "snd_pcm_avail", (int) n)) >= 0)
+ continue;
+
+ return r;
+ }
+
+ n_bytes = (size_t) n * u->frame_size;
+
+#ifdef DEBUG_TIMING
+ pa_log_debug("avail: %lu", (unsigned long) n_bytes);
+#endif
+
+ left_to_play = check_left_to_play(u, n_bytes, on_timeout);
+ on_timeout = false;
+
+ if (u->use_tsched)
+
+ /* We won't fill up the playback buffer before at least
+ * half the sleep time is over because otherwise we might
+ * ask for more data from the clients then they expect. We
+ * need to guarantee that clients only have to keep around
+ * a single hw buffer length. */
+
+ if (!polled &&
+ pa_bytes_to_usec(left_to_play, &u->sink->sample_spec) > process_usec+max_sleep_usec/2)
+ break;
+
+ if (PA_UNLIKELY(n_bytes <= u->hwbuf_unused)) {
+
+ if (polled)
+ PA_ONCE_BEGIN {
+ char *dn = pa_alsa_get_driver_name_by_pcm(u->pcm_handle);
+ pa_log(_("ALSA woke us up to write new data to the device, but there was actually nothing to write.\n"
+ "Most likely this is a bug in the ALSA driver '%s'. Please report this issue to the ALSA developers.\n"
+ "We were woken up with POLLOUT set -- however a subsequent snd_pcm_avail() returned 0 or another value < min_avail."),
+ pa_strnull(dn));
+ pa_xfree(dn);
+ } PA_ONCE_END;
+
+ break;
+ }
+
+ j++;
+
+ if (j > 10) {
+#ifdef DEBUG_TIMING
+ pa_log_debug("Not filling up, because already too many iterations.");
+#endif
+
+ break;
+ } else if (j >= 2 && (n_bytes < (DEFAULT_WRITE_ITERATION_THRESHOLD * (u->hwbuf_size - u->hwbuf_unused)))) {
+#ifdef DEBUG_TIMING
+ pa_log_debug("Not filling up, because <%g%% available.", DEFAULT_WRITE_ITERATION_THRESHOLD * 100);
+#endif
+ break;
+ }
+
+ n_bytes -= u->hwbuf_unused;
+ polled = false;
+
+ for (;;) {
+ snd_pcm_sframes_t frames;
+ void *p;
+ size_t written;
+
+/* pa_log_debug("%lu frames to write", (unsigned long) frames); */
+
+ if (u->memchunk.length <= 0)
+ pa_sink_render(u->sink, n_bytes, &u->memchunk);
+
+ pa_assert(u->memchunk.length > 0);
+
+ frames = (snd_pcm_sframes_t) (u->memchunk.length / u->frame_size);
+
+ if (frames > (snd_pcm_sframes_t) (n_bytes/u->frame_size))
+ frames = (snd_pcm_sframes_t) (n_bytes/u->frame_size);
+
+ p = pa_memblock_acquire(u->memchunk.memblock);
+ frames = snd_pcm_writei(u->pcm_handle, (const uint8_t*) p + u->memchunk.index, (snd_pcm_uframes_t) frames);
+ pa_memblock_release(u->memchunk.memblock);
+
+ if (PA_UNLIKELY(frames < 0)) {
+
+ if (!after_avail && (int) frames == -EAGAIN)
+ break;
+
+ if ((r = try_recover(u, "snd_pcm_writei", (int) frames)) == 0)
+ continue;
+
+ if (r == 1)
+ break;
+
+ return r;
+ }
+
+ if (!after_avail && frames == 0)
+ break;
+
+ pa_assert(frames > 0);
+ after_avail = false;
+
+ written = frames * u->frame_size;
+ u->memchunk.index += written;
+ u->memchunk.length -= written;
+
+ if (u->memchunk.length <= 0) {
+ pa_memblock_unref(u->memchunk.memblock);
+ pa_memchunk_reset(&u->memchunk);
+ }
+
+ work_done = true;
+
+ u->write_count += written;
+ u->since_start += written;
+
+/* pa_log_debug("wrote %lu frames", (unsigned long) frames); */
+
+ if (written >= n_bytes)
+ break;
+
+ n_bytes -= written;
+ }
+ }
+
+ input_underrun = pa_sink_process_input_underruns(u->sink, left_to_play);
+
+ if (u->use_tsched) {
+ pa_usec_t underrun_sleep = pa_bytes_to_usec_round_up(input_underrun, &u->sink->sample_spec);
+
+ *sleep_usec = pa_bytes_to_usec(left_to_play, &u->sink->sample_spec);
+ process_usec = u->tsched_watermark_usec;
+
+ if (*sleep_usec > process_usec)
+ *sleep_usec -= process_usec;
+ else
+ *sleep_usec = 0;
+
+ *sleep_usec = PA_MIN(*sleep_usec, underrun_sleep);
+ } else
+ *sleep_usec = 0;
+
+ return work_done ? 1 : 0;
+}
+
+static void update_smoother(struct userdata *u) {
+ snd_pcm_sframes_t delay = 0;
+ int64_t position;
+ int err;
+ pa_usec_t now1 = 0, now2;
+ snd_pcm_status_t *status;
+ snd_htimestamp_t htstamp = { 0, 0 };
+
+ snd_pcm_status_alloca(&status);
+
+ pa_assert(u);
+ pa_assert(u->pcm_handle);
+
+ /* Let's update the time smoother */
+
+ if (PA_UNLIKELY((err = pa_alsa_safe_delay(u->pcm_handle, status, &delay, u->hwbuf_size, &u->sink->sample_spec, false)) < 0)) {
+ pa_log_warn("Failed to query DSP status data: %s", pa_alsa_strerror(err));
+ return;
+ }
+
+ snd_pcm_status_get_htstamp(status, &htstamp);
+ now1 = pa_timespec_load(&htstamp);
+
+ /* Hmm, if the timestamp is 0, then it wasn't set and we take the current time */
+ if (now1 <= 0)
+ now1 = pa_rtclock_now();
+
+ /* check if the time since the last update is bigger than the interval */
+ if (u->last_smoother_update > 0)
+ if (u->last_smoother_update + u->smoother_interval > now1)
+ return;
+
+ position = (int64_t) u->write_count - ((int64_t) delay * (int64_t) u->frame_size);
+
+ if (PA_UNLIKELY(position < 0))
+ position = 0;
+
+ now2 = pa_bytes_to_usec((uint64_t) position, &u->sink->sample_spec);
+
+ pa_smoother_put(u->smoother, now1, now2);
+
+ u->last_smoother_update = now1;
+ /* exponentially increase the update interval up to the MAX limit */
+ u->smoother_interval = PA_MIN (u->smoother_interval * 2, SMOOTHER_MAX_INTERVAL);
+}
+
+static int64_t sink_get_latency(struct userdata *u) {
+ int64_t delay;
+ pa_usec_t now1, now2;
+
+ pa_assert(u);
+
+ now1 = pa_rtclock_now();
+ now2 = pa_smoother_get(u->smoother, now1);
+
+ delay = (int64_t) pa_bytes_to_usec(u->write_count, &u->sink->sample_spec) - (int64_t) now2;
+
+ if (u->memchunk.memblock)
+ delay += pa_bytes_to_usec(u->memchunk.length, &u->sink->sample_spec);
+
+ return delay;
+}
+
+static int build_pollfd(struct userdata *u) {
+ pa_assert(u);
+ pa_assert(u->pcm_handle);
+
+ if (u->alsa_rtpoll_item)
+ pa_rtpoll_item_free(u->alsa_rtpoll_item);
+
+ if (!(u->alsa_rtpoll_item = pa_alsa_build_pollfd(u->pcm_handle, u->rtpoll)))
+ return -1;
+
+ return 0;
+}
+
+/* Called from IO context */
+static void suspend(struct userdata *u) {
+ pa_assert(u);
+
+ /* Handle may have been invalidated due to a device failure.
+ * In that case there is nothing to do. */
+ if (!u->pcm_handle)
+ return;
+
+ pa_smoother_pause(u->smoother, pa_rtclock_now());
+
+ /* Close PCM device */
+ close_pcm(u);
+
+ /* We reset max_rewind/max_request here to make sure that while we
+ * are suspended the old max_request/max_rewind values set before
+ * the suspend can influence the per-stream buffer of newly
+ * created streams, without their requirements having any
+ * influence on them. */
+ pa_sink_set_max_rewind_within_thread(u->sink, 0);
+ pa_sink_set_max_request_within_thread(u->sink, 0);
+
+ pa_log_info("Device suspended...");
+}
+
+/* Called from IO context */
+static int update_sw_params(struct userdata *u, bool may_need_rewind) {
+ size_t old_unused;
+ snd_pcm_uframes_t avail_min;
+ int err;
+
+ pa_assert(u);
+
+ /* Use the full buffer if no one asked us for anything specific */
+ old_unused = u->hwbuf_unused;
+ u->hwbuf_unused = 0;
+
+ if (u->use_tsched) {
+ pa_usec_t latency;
+
+ if ((latency = pa_sink_get_requested_latency_within_thread(u->sink)) != (pa_usec_t) -1) {
+ size_t b;
+
+ pa_log_debug("Latency set to %0.2fms", (double) latency / PA_USEC_PER_MSEC);
+
+ b = pa_usec_to_bytes(latency, &u->sink->sample_spec);
+
+ /* We need at least one sample in our buffer */
+
+ if (PA_UNLIKELY(b < u->frame_size))
+ b = u->frame_size;
+
+ u->hwbuf_unused = PA_LIKELY(b < u->hwbuf_size) ? (u->hwbuf_size - b) : 0;
+ }
+
+ fix_min_sleep_wakeup(u);
+ fix_tsched_watermark(u);
+ }
+
+ pa_log_debug("hwbuf_unused=%lu", (unsigned long) u->hwbuf_unused);
+
+ /* We need at last one frame in the used part of the buffer */
+ avail_min = (snd_pcm_uframes_t) u->hwbuf_unused / u->frame_size + 1;
+
+ if (u->use_tsched) {
+ pa_usec_t sleep_usec, process_usec;
+
+ hw_sleep_time(u, &sleep_usec, &process_usec);
+ avail_min += pa_usec_to_bytes(sleep_usec, &u->sink->sample_spec) / u->frame_size;
+ }
+
+ pa_log_debug("setting avail_min=%lu", (unsigned long) avail_min);
+
+ if ((err = pa_alsa_set_sw_params(u->pcm_handle, avail_min, !u->use_tsched)) < 0) {
+ pa_log("Failed to set software parameters: %s", pa_alsa_strerror(err));
+ return err;
+ }
+
+ /* If we're lowering the latency, we need to do a rewind, because otherwise
+ * we might end up in a situation where the hw buffer contains more data
+ * than the new configured latency. The rewind has to be requested before
+ * updating max_rewind, because the rewind amount is limited to max_rewind.
+ *
+ * If may_need_rewind is false, it means that we're just starting playback,
+ * and rewinding is never needed in that situation. */
+ if (may_need_rewind && u->hwbuf_unused > old_unused) {
+ pa_log_debug("Requesting rewind due to latency change.");
+ pa_sink_request_rewind(u->sink, (size_t) -1);
+ }
+
+ pa_sink_set_max_request_within_thread(u->sink, u->hwbuf_size - u->hwbuf_unused);
+ if (pa_alsa_pcm_is_hw(u->pcm_handle))
+ pa_sink_set_max_rewind_within_thread(u->sink, u->hwbuf_size - u->hwbuf_unused);
+ else {
+ pa_log_info("Disabling rewind_within_thread for device %s", u->device_name);
+ pa_sink_set_max_rewind_within_thread(u->sink, 0);
+ }
+
+ return 0;
+}
+
+/* Called from IO Context on unsuspend */
+static void update_size(struct userdata *u, pa_sample_spec *ss) {
+ pa_assert(u);
+ pa_assert(ss);
+
+ u->frame_size = pa_frame_size(ss);
+ u->frames_per_block = pa_mempool_block_size_max(u->core->mempool) / u->frame_size;
+
+ /* use initial values including module arguments */
+ u->fragment_size = u->initial_info.fragment_size;
+ u->hwbuf_size = u->initial_info.nfrags * u->fragment_size;
+ u->tsched_size = u->initial_info.tsched_size;
+ u->tsched_watermark = u->initial_info.tsched_watermark;
+ u->rewind_safeguard = u->initial_info.rewind_safeguard;
+
+ u->tsched_watermark_ref = u->tsched_watermark;
+
+ pa_log_info("Updated frame_size %zu, frames_per_block %lu, fragment_size %zu, hwbuf_size %zu, tsched(size %zu, watermark %zu), rewind_safeguard %zu",
+ u->frame_size, (unsigned long) u->frames_per_block, u->fragment_size, u->hwbuf_size, u->tsched_size, u->tsched_watermark, u->rewind_safeguard);
+}
+
+/* Called from IO context */
+static int unsuspend(struct userdata *u, bool recovering) {
+ pa_sample_spec ss;
+ int err, i;
+ bool b, d;
+ snd_pcm_uframes_t period_frames, buffer_frames;
+ snd_pcm_uframes_t tsched_frames = 0;
+ char *device_name = NULL;
+ bool frame_size_changed = false;
+
+ pa_assert(u);
+ pa_assert(!u->pcm_handle);
+
+ pa_log_info("Trying resume...");
+
+ if ((is_iec958(u) || is_hdmi(u)) && pa_sink_is_passthrough(u->sink)) {
+ /* Need to open device in NONAUDIO mode */
+ int len = strlen(u->device_name) + 8;
+
+ device_name = pa_xmalloc(len);
+ pa_snprintf(device_name, len, "%s,AES0=6", u->device_name);
+ }
+
+ /*
+ * On some machines, during the system suspend and resume, the thread_func could receive
+ * POLLERR events before the dev nodes in /dev/snd/ are accessible, and thread_func calls
+ * the unsuspend() to try to recover the PCM, this will make the snd_pcm_open() fail, here
+ * we add msleep and retry to make sure those nodes are accessible.
+ */
+ for (i = 0; i < 4; i++) {
+ if ((err = snd_pcm_open(&u->pcm_handle, device_name ? device_name : u->device_name, SND_PCM_STREAM_PLAYBACK,
+ SND_PCM_NONBLOCK|
+ SND_PCM_NO_AUTO_RESAMPLE|
+ SND_PCM_NO_AUTO_CHANNELS|
+ SND_PCM_NO_AUTO_FORMAT)) < 0 && recovering)
+ pa_msleep(25);
+ else
+ break;
+ }
+
+ if (err < 0) {
+ pa_log("Error opening PCM device %s: %s", u->device_name, pa_alsa_strerror(err));
+ goto fail;
+ }
+
+ if (pa_frame_size(&u->sink->sample_spec) != u->frame_size) {
+ update_size(u, &u->sink->sample_spec);
+ tsched_frames = u->tsched_size / u->frame_size;
+ frame_size_changed = true;
+ }
+
+ ss = u->sink->sample_spec;
+ period_frames = u->fragment_size / u->frame_size;
+ buffer_frames = u->hwbuf_size / u->frame_size;
+ b = u->use_mmap;
+ d = u->use_tsched;
+
+ if ((err = pa_alsa_set_hw_params(u->pcm_handle, &ss, &period_frames, &buffer_frames, tsched_frames, &b, &d, true)) < 0) {
+ pa_log("Failed to set hardware parameters: %s", pa_alsa_strerror(err));
+ goto fail;
+ }
+
+ if (b != u->use_mmap || d != u->use_tsched) {
+ pa_log_warn("Resume failed, couldn't get original access mode.");
+ goto fail;
+ }
+
+ if (!pa_sample_spec_equal(&ss, &u->sink->sample_spec)) {
+ pa_log_warn("Resume failed, couldn't restore original sample settings.");
+ goto fail;
+ }
+
+ if (frame_size_changed) {
+ u->fragment_size = (size_t)(period_frames * u->frame_size);
+ u->hwbuf_size = (size_t)(buffer_frames * u->frame_size);
+ pa_proplist_setf(u->sink->proplist, PA_PROP_DEVICE_BUFFERING_BUFFER_SIZE, "%zu", u->hwbuf_size);
+ pa_proplist_setf(u->sink->proplist, PA_PROP_DEVICE_BUFFERING_FRAGMENT_SIZE, "%zu", u->fragment_size);
+
+ } else if (period_frames * u->frame_size != u->fragment_size ||
+ buffer_frames * u->frame_size != u->hwbuf_size) {
+ pa_log_warn("Resume failed, couldn't restore original fragment settings. (Old: %zu/%zu, New %lu/%lu)",
+ u->hwbuf_size, u->fragment_size,
+ (unsigned long) buffer_frames * u->frame_size, (unsigned long) period_frames * u->frame_size);
+ goto fail;
+ }
+
+ if (update_sw_params(u, false) < 0)
+ goto fail;
+
+ if (build_pollfd(u) < 0)
+ goto fail;
+
+ reset_vars(u);
+
+ /* reset the watermark to the value defined when sink was created */
+ if (u->use_tsched && !recovering)
+ reset_watermark(u, u->tsched_watermark_ref, &u->sink->sample_spec, true);
+
+ pa_log_info("Resumed successfully...");
+
+ pa_xfree(device_name);
+ return 0;
+
+fail:
+ if (u->pcm_handle) {
+ snd_pcm_close(u->pcm_handle);
+ u->pcm_handle = NULL;
+ }
+
+ pa_xfree(device_name);
+
+ return -PA_ERR_IO;
+}
+
+/* Called from the IO thread or the main thread depending on whether deferred
+ * volume is enabled or not (with deferred volume all mixer handling is done
+ * from the IO thread).
+ *
+ * Sets the mixer settings to match the current sink and port state (the port
+ * is given as an argument, because active_port may still point to the old
+ * port, if we're switching ports). */
+static void sync_mixer(struct userdata *u, pa_device_port *port) {
+ pa_alsa_setting *setting = NULL;
+
+ pa_assert(u);
+
+ if (!u->mixer_path)
+ return;
+
+ /* port may be NULL, because if we use a synthesized mixer path, then the
+ * sink has no ports. */
+ if (port && !u->ucm_context) {
+ pa_alsa_port_data *data;
+
+ data = PA_DEVICE_PORT_DATA(port);
+ setting = data->setting;
+ }
+
+ pa_alsa_path_select(u->mixer_path, setting, u->mixer_handle, u->sink->muted);
+
+ if (u->sink->set_mute)
+ u->sink->set_mute(u->sink);
+ if (u->sink->flags & PA_SINK_DEFERRED_VOLUME) {
+ if (u->sink->write_volume)
+ u->sink->write_volume(u->sink);
+ } else {
+ if (u->sink->set_volume)
+ u->sink->set_volume(u->sink);
+ }
+}
+
+/* Called from IO context */
+static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
+ struct userdata *u = PA_SINK(o)->userdata;
+
+ switch (code) {
+
+ case PA_SINK_MESSAGE_GET_LATENCY: {
+ int64_t r = 0;
+
+ if (u->pcm_handle)
+ r = sink_get_latency(u);
+
+ *((int64_t*) data) = r;
+
+ return 0;
+ }
+
+ case SINK_MESSAGE_SYNC_MIXER: {
+ pa_device_port *port = data;
+
+ sync_mixer(u, port);
+ return 0;
+ }
+ }
+
+ return pa_sink_process_msg(o, code, data, offset, chunk);
+}
+
+/* Called from main context */
+static int sink_set_state_in_main_thread_cb(pa_sink *s, pa_sink_state_t new_state, pa_suspend_cause_t new_suspend_cause) {
+ pa_sink_state_t old_state;
+ struct userdata *u;
+
+ pa_sink_assert_ref(s);
+ pa_assert_se(u = s->userdata);
+
+ /* When our session becomes active, we need to sync the mixer, because
+ * another user may have changed the mixer settings.
+ *
+ * If deferred volume is enabled, the syncing is done in the
+ * set_state_in_io_thread() callback instead. */
+ if (!(s->flags & PA_SINK_DEFERRED_VOLUME)
+ && (s->suspend_cause & PA_SUSPEND_SESSION)
+ && !(new_suspend_cause & PA_SUSPEND_SESSION))
+ sync_mixer(u, s->active_port);
+
+ old_state = u->sink->state;
+
+ if (PA_SINK_IS_OPENED(old_state) && new_state == PA_SINK_SUSPENDED)
+ reserve_done(u);
+ else if (old_state == PA_SINK_SUSPENDED && PA_SINK_IS_OPENED(new_state))
+ if (reserve_init(u, u->device_name) < 0)
+ return -PA_ERR_BUSY;
+
+ return 0;
+}
+
+/* Called from the IO thread. */
+static int sink_set_state_in_io_thread_cb(pa_sink *s, pa_sink_state_t new_state, pa_suspend_cause_t new_suspend_cause) {
+ struct userdata *u;
+
+ pa_assert(s);
+ pa_assert_se(u = s->userdata);
+
+ /* When our session becomes active, we need to sync the mixer, because
+ * another user may have changed the mixer settings.
+ *
+ * If deferred volume is disabled, the syncing is done in the
+ * set_state_in_main_thread() callback instead. */
+ if ((s->flags & PA_SINK_DEFERRED_VOLUME)
+ && (s->suspend_cause & PA_SUSPEND_SESSION)
+ && !(new_suspend_cause & PA_SUSPEND_SESSION))
+ sync_mixer(u, s->active_port);
+
+ /* It may be that only the suspend cause is changing, in which case there's
+ * nothing more to do. */
+ if (new_state == s->thread_info.state)
+ return 0;
+
+ switch (new_state) {
+
+ case PA_SINK_SUSPENDED: {
+ pa_assert(PA_SINK_IS_OPENED(s->thread_info.state));
+
+ suspend(u);
+
+ break;
+ }
+
+ case PA_SINK_IDLE:
+ case PA_SINK_RUNNING: {
+ int r;
+
+ if (s->thread_info.state == PA_SINK_INIT) {
+ if (build_pollfd(u) < 0)
+ /* FIXME: This will cause an assertion failure, because
+ * with the current design pa_sink_put() is not allowed
+ * to fail and pa_sink_put() has no fallback code that
+ * would start the sink suspended if opening the device
+ * fails. */
+ return -PA_ERR_IO;
+ }
+
+ if (s->thread_info.state == PA_SINK_SUSPENDED) {
+ if ((r = unsuspend(u, false)) < 0)
+ return r;
+ }
+
+ break;
+ }
+
+ case PA_SINK_UNLINKED:
+ case PA_SINK_INIT:
+ case PA_SINK_INVALID_STATE:
+ break;
+ }
+
+ return 0;
+}
+
+static int ctl_mixer_callback(snd_mixer_elem_t *elem, unsigned int mask) {
+ struct userdata *u = snd_mixer_elem_get_callback_private(elem);
+
+ pa_assert(u);
+ pa_assert(u->mixer_handle);
+
+ if (mask == SND_CTL_EVENT_MASK_REMOVE)
+ return 0;
+
+ if (!PA_SINK_IS_LINKED(u->sink->state))
+ return 0;
+
+ if (u->sink->suspend_cause & PA_SUSPEND_SESSION)
+ return 0;
+
+ if (mask & SND_CTL_EVENT_MASK_VALUE) {
+ pa_sink_get_volume(u->sink, true);
+ pa_sink_get_mute(u->sink, true);
+ }
+
+ return 0;
+}
+
+static int io_mixer_callback(snd_mixer_elem_t *elem, unsigned int mask) {
+ struct userdata *u = snd_mixer_elem_get_callback_private(elem);
+
+ pa_assert(u);
+ pa_assert(u->mixer_handle);
+
+ if (mask == SND_CTL_EVENT_MASK_REMOVE)
+ return 0;
+
+ if (u->sink->suspend_cause & PA_SUSPEND_SESSION)
+ return 0;
+
+ if (mask & SND_CTL_EVENT_MASK_VALUE)
+ pa_sink_update_volume_and_mute(u->sink);
+
+ return 0;
+}
+
+static void sink_get_volume_cb(pa_sink *s) {
+ struct userdata *u = s->userdata;
+ pa_cvolume r;
+ char volume_buf[PA_CVOLUME_SNPRINT_VERBOSE_MAX];
+
+ pa_assert(u);
+ pa_assert(u->mixer_path);
+ pa_assert(u->mixer_handle);
+
+ if (pa_alsa_path_get_volume(u->mixer_path, u->mixer_handle, &s->channel_map, &r) < 0)
+ return;
+
+ /* Shift down by the base volume, so that 0dB becomes maximum volume */
+ pa_sw_cvolume_multiply_scalar(&r, &r, s->base_volume);
+
+ pa_log_debug("Read hardware volume: %s",
+ pa_cvolume_snprint_verbose(volume_buf, sizeof(volume_buf), &r, &s->channel_map, u->mixer_path->has_dB));
+
+ if (pa_cvolume_equal(&u->hardware_volume, &r))
+ return;
+
+ s->real_volume = u->hardware_volume = r;
+
+ /* Hmm, so the hardware volume changed, let's reset our software volume */
+ if (u->mixer_path->has_dB)
+ pa_sink_set_soft_volume(s, NULL);
+}
+
+static void sink_set_volume_cb(pa_sink *s) {
+ struct userdata *u = s->userdata;
+ pa_cvolume r;
+ char volume_buf[PA_CVOLUME_SNPRINT_VERBOSE_MAX];
+ bool deferred_volume = !!(s->flags & PA_SINK_DEFERRED_VOLUME);
+
+ pa_assert(u);
+ pa_assert(u->mixer_path);
+ pa_assert(u->mixer_handle);
+
+ /* Shift up by the base volume */
+ pa_sw_cvolume_divide_scalar(&r, &s->real_volume, s->base_volume);
+
+ if (pa_alsa_path_set_volume(u->mixer_path, u->mixer_handle, &s->channel_map, &r, deferred_volume, !deferred_volume) < 0)
+ return;
+
+ /* Shift down by the base volume, so that 0dB becomes maximum volume */
+ pa_sw_cvolume_multiply_scalar(&r, &r, s->base_volume);
+
+ u->hardware_volume = r;
+
+ if (u->mixer_path->has_dB) {
+ pa_cvolume new_soft_volume;
+ bool accurate_enough;
+
+ /* Match exactly what the user requested by software */
+ pa_sw_cvolume_divide(&new_soft_volume, &s->real_volume, &u->hardware_volume);
+
+ /* If the adjustment to do in software is only minimal we
+ * can skip it. That saves us CPU at the expense of a bit of
+ * accuracy */
+ accurate_enough =
+ (pa_cvolume_min(&new_soft_volume) >= (PA_VOLUME_NORM - VOLUME_ACCURACY)) &&
+ (pa_cvolume_max(&new_soft_volume) <= (PA_VOLUME_NORM + VOLUME_ACCURACY));
+
+ pa_log_debug("Requested volume: %s",
+ pa_cvolume_snprint_verbose(volume_buf, sizeof(volume_buf), &s->real_volume, &s->channel_map, true));
+ pa_log_debug("Got hardware volume: %s",
+ pa_cvolume_snprint_verbose(volume_buf, sizeof(volume_buf), &u->hardware_volume, &s->channel_map, true));
+ pa_log_debug("Calculated software volume: %s (accurate-enough=%s)",
+ pa_cvolume_snprint_verbose(volume_buf, sizeof(volume_buf), &new_soft_volume, &s->channel_map, true),
+ pa_yes_no(accurate_enough));
+
+ if (!accurate_enough)
+ s->soft_volume = new_soft_volume;
+
+ } else {
+ pa_log_debug("Wrote hardware volume: %s",
+ pa_cvolume_snprint_verbose(volume_buf, sizeof(volume_buf), &r, &s->channel_map, false));
+
+ /* We can't match exactly what the user requested, hence let's
+ * at least tell the user about it */
+
+ s->real_volume = r;
+ }
+}
+
+static void sink_write_volume_cb(pa_sink *s) {
+ struct userdata *u = s->userdata;
+ pa_cvolume hw_vol = s->thread_info.current_hw_volume;
+
+ pa_assert(u);
+ pa_assert(u->mixer_path);
+ pa_assert(u->mixer_handle);
+ pa_assert(s->flags & PA_SINK_DEFERRED_VOLUME);
+
+ /* Shift up by the base volume */
+ pa_sw_cvolume_divide_scalar(&hw_vol, &hw_vol, s->base_volume);
+
+ if (pa_alsa_path_set_volume(u->mixer_path, u->mixer_handle, &s->channel_map, &hw_vol, true, true) < 0)
+ pa_log_error("Writing HW volume failed");
+ else {
+ pa_cvolume tmp_vol;
+ bool accurate_enough;
+
+ /* Shift down by the base volume, so that 0dB becomes maximum volume */
+ pa_sw_cvolume_multiply_scalar(&hw_vol, &hw_vol, s->base_volume);
+
+ pa_sw_cvolume_divide(&tmp_vol, &hw_vol, &s->thread_info.current_hw_volume);
+ accurate_enough =
+ (pa_cvolume_min(&tmp_vol) >= (PA_VOLUME_NORM - VOLUME_ACCURACY)) &&
+ (pa_cvolume_max(&tmp_vol) <= (PA_VOLUME_NORM + VOLUME_ACCURACY));
+
+ if (!accurate_enough) {
+ char volume_buf[2][PA_CVOLUME_SNPRINT_VERBOSE_MAX];
+
+ pa_log_debug("Written HW volume did not match with the request: %s (request) != %s",
+ pa_cvolume_snprint_verbose(volume_buf[0],
+ sizeof(volume_buf[0]),
+ &s->thread_info.current_hw_volume,
+ &s->channel_map,
+ true),
+ pa_cvolume_snprint_verbose(volume_buf[1], sizeof(volume_buf[1]), &hw_vol, &s->channel_map, true));
+ }
+ }
+}
+
+static int sink_get_mute_cb(pa_sink *s, bool *mute) {
+ struct userdata *u = s->userdata;
+
+ pa_assert(u);
+ pa_assert(u->mixer_path);
+ pa_assert(u->mixer_handle);
+
+ if (pa_alsa_path_get_mute(u->mixer_path, u->mixer_handle, mute) < 0)
+ return -1;
+
+ return 0;
+}
+
+static void sink_set_mute_cb(pa_sink *s) {
+ struct userdata *u = s->userdata;
+
+ pa_assert(u);
+ pa_assert(u->mixer_path);
+ pa_assert(u->mixer_handle);
+
+ pa_alsa_path_set_mute(u->mixer_path, u->mixer_handle, s->muted);
+}
+
+static void mixer_volume_init(struct userdata *u) {
+ pa_assert(u);
+
+ if (!u->mixer_path || !u->mixer_path->has_volume) {
+ pa_sink_set_write_volume_callback(u->sink, NULL);
+ pa_sink_set_get_volume_callback(u->sink, NULL);
+ pa_sink_set_set_volume_callback(u->sink, NULL);
+
+ pa_log_info("Driver does not support hardware volume control, falling back to software volume control.");
+ } else {
+ pa_sink_set_get_volume_callback(u->sink, sink_get_volume_cb);
+ pa_sink_set_set_volume_callback(u->sink, sink_set_volume_cb);
+
+ if (u->mixer_path->has_dB && u->deferred_volume) {
+ pa_sink_set_write_volume_callback(u->sink, sink_write_volume_cb);
+ pa_log_info("Successfully enabled deferred volume.");
+ } else
+ pa_sink_set_write_volume_callback(u->sink, NULL);
+
+ if (u->mixer_path->has_dB) {
+ pa_sink_enable_decibel_volume(u->sink, true);
+ pa_log_info("Hardware volume ranges from %0.2f dB to %0.2f dB.", u->mixer_path->min_dB, u->mixer_path->max_dB);
+
+ u->sink->base_volume = pa_sw_volume_from_dB(-u->mixer_path->max_dB);
+ u->sink->n_volume_steps = PA_VOLUME_NORM+1;
+
+ pa_log_info("Fixing base volume to %0.2f dB", pa_sw_volume_to_dB(u->sink->base_volume));
+ } else {
+ pa_sink_enable_decibel_volume(u->sink, false);
+ pa_log_info("Hardware volume ranges from %li to %li.", u->mixer_path->min_volume, u->mixer_path->max_volume);
+
+ u->sink->base_volume = PA_VOLUME_NORM;
+ u->sink->n_volume_steps = u->mixer_path->max_volume - u->mixer_path->min_volume + 1;
+ }
+
+ pa_log_info("Using hardware volume control. Hardware dB scale %s.", u->mixer_path->has_dB ? "supported" : "not supported");
+ }
+
+ if (!u->mixer_path || !u->mixer_path->has_mute) {
+ pa_sink_set_get_mute_callback(u->sink, NULL);
+ pa_sink_set_set_mute_callback(u->sink, NULL);
+ pa_log_info("Driver does not support hardware mute control, falling back to software mute control.");
+ } else {
+ pa_sink_set_get_mute_callback(u->sink, sink_get_mute_cb);
+ pa_sink_set_set_mute_callback(u->sink, sink_set_mute_cb);
+ pa_log_info("Using hardware mute control.");
+ }
+}
+
+static int sink_set_port_ucm_cb(pa_sink *s, pa_device_port *p) {
+ struct userdata *u = s->userdata;
+ pa_alsa_ucm_port_data *data;
+
+ pa_assert(u);
+ pa_assert(p);
+ pa_assert(u->ucm_context);
+
+ data = PA_DEVICE_PORT_DATA(p);
+ u->mixer_path = data->path;
+ mixer_volume_init(u);
+
+ if (s->flags & PA_SINK_DEFERRED_VOLUME)
+ pa_asyncmsgq_send(u->sink->asyncmsgq, PA_MSGOBJECT(u->sink), SINK_MESSAGE_SYNC_MIXER, p, 0, NULL);
+ else
+ sync_mixer(u, p);
+
+ return pa_alsa_ucm_set_port(u->ucm_context, p, true);
+}
+
+static int sink_set_port_cb(pa_sink *s, pa_device_port *p) {
+ struct userdata *u = s->userdata;
+ pa_alsa_port_data *data;
+
+ pa_assert(u);
+ pa_assert(p);
+ pa_assert(u->mixer_handle);
+ pa_assert(!u->ucm_context);
+
+ data = PA_DEVICE_PORT_DATA(p);
+ pa_assert_se(u->mixer_path = data->path);
+ mixer_volume_init(u);
+
+ if (s->flags & PA_SINK_DEFERRED_VOLUME)
+ pa_asyncmsgq_send(u->sink->asyncmsgq, PA_MSGOBJECT(u->sink), SINK_MESSAGE_SYNC_MIXER, p, 0, NULL);
+ else
+ sync_mixer(u, p);
+
+ if (data->suspend_when_unavailable && p->available == PA_AVAILABLE_NO)
+ pa_sink_suspend(s, true, PA_SUSPEND_UNAVAILABLE);
+ else
+ pa_sink_suspend(s, false, PA_SUSPEND_UNAVAILABLE);
+
+ return 0;
+}
+
+static void sink_update_requested_latency_cb(pa_sink *s) {
+ struct userdata *u = s->userdata;
+ pa_assert(u);
+ pa_assert(u->use_tsched); /* only when timer scheduling is used
+ * we can dynamically adjust the
+ * latency */
+
+ if (!u->pcm_handle)
+ return;
+
+ update_sw_params(u, true);
+}
+
+static pa_idxset* sink_get_formats(pa_sink *s) {
+ struct userdata *u = s->userdata;
+
+ pa_assert(u);
+
+ return pa_idxset_copy(u->formats, (pa_copy_func_t) pa_format_info_copy);
+}
+
+static bool sink_set_formats(pa_sink *s, pa_idxset *formats) {
+ struct userdata *u = s->userdata;
+ pa_format_info *f, *g;
+ uint32_t idx, n;
+
+ pa_assert(u);
+
+ /* FIXME: also validate sample rates against what the device supports */
+ PA_IDXSET_FOREACH(f, formats, idx) {
+ if (is_iec958(u) && f->encoding == PA_ENCODING_EAC3_IEC61937)
+ /* EAC3 cannot be sent over over S/PDIF */
+ return false;
+ }
+
+ pa_idxset_free(u->formats, (pa_free_cb_t) pa_format_info_free);
+ u->formats = pa_idxset_new(NULL, NULL);
+
+ /* Note: the logic below won't apply if we're using software encoding.
+ * This is fine for now since we don't support that via the passthrough
+ * framework, but this must be changed if we do. */
+
+ /* Count how many sample rates we support */
+ for (idx = 0, n = 0; u->supported_rates[idx]; idx++)
+ n++;
+
+ /* First insert non-PCM formats since we prefer those. */
+ PA_IDXSET_FOREACH(f, formats, idx) {
+ if (!pa_format_info_is_pcm(f)) {
+ g = pa_format_info_copy(f);
+ pa_format_info_set_prop_int_array(g, PA_PROP_FORMAT_RATE, (int *) u->supported_rates, n);
+ pa_idxset_put(u->formats, g, NULL);
+ }
+ }
+
+ /* Now add any PCM formats */
+ PA_IDXSET_FOREACH(f, formats, idx) {
+ if (pa_format_info_is_pcm(f)) {
+ /* We don't set rates here since we'll just tack on a resampler for
+ * unsupported rates */
+ pa_idxset_put(u->formats, pa_format_info_copy(f), NULL);
+ }
+ }
+
+ return true;
+}
+
+static void sink_reconfigure_cb(pa_sink *s, pa_sample_spec *spec, bool passthrough) {
+ struct userdata *u = s->userdata;
+ int i;
+ bool format_supported = false;
+ bool rate_supported = false;
+
+ pa_assert(u);
+
+ for (i = 0; u->supported_formats[i] != PA_SAMPLE_MAX; i++) {
+ if (u->supported_formats[i] == spec->format) {
+ pa_sink_set_sample_format(u->sink, spec->format);
+ format_supported = true;
+ break;
+ }
+ }
+
+ if (!format_supported) {
+ pa_log_info("Sink does not support sample format of %s, set it to a verified value",
+ pa_sample_format_to_string(spec->format));
+ pa_sink_set_sample_format(u->sink, u->verified_sample_spec.format);
+ }
+
+ for (i = 0; u->supported_rates[i]; i++) {
+ if (u->supported_rates[i] == spec->rate) {
+ pa_sink_set_sample_rate(u->sink, spec->rate);
+ rate_supported = true;
+ break;
+ }
+ }
+
+ if (!rate_supported) {
+ pa_log_info("Sink does not support sample rate of %u, set it to a verified value", spec->rate);
+ pa_sink_set_sample_rate(u->sink, u->verified_sample_spec.rate);
+ }
+
+ /* Passthrough status change is handled during unsuspend */
+}
+
+static int process_rewind(struct userdata *u) {
+ snd_pcm_sframes_t unused;
+ size_t rewind_nbytes, unused_nbytes, limit_nbytes;
+ int err;
+ pa_assert(u);
+
+ if (!PA_SINK_IS_OPENED(u->sink->thread_info.state)) {
+ pa_sink_process_rewind(u->sink, 0);
+ return 0;
+ }
+
+ /* Figure out how much we shall rewind and reset the counter */
+ rewind_nbytes = u->sink->thread_info.rewind_nbytes;
+
+ pa_log_debug("Requested to rewind %lu bytes.", (unsigned long) rewind_nbytes);
+
+ if (PA_UNLIKELY((unused = pa_alsa_safe_avail(u->pcm_handle, u->hwbuf_size, &u->sink->sample_spec)) < 0)) {
+ if ((err = try_recover(u, "snd_pcm_avail", (int) unused)) < 0) {
+ pa_log_warn("Trying to recover from underrun failed during rewind");
+ return -1;
+ }
+ if (err == 1)
+ goto rewind_done;
+ }
+
+ unused_nbytes = (size_t) unused * u->frame_size;
+
+ /* make sure rewind doesn't go too far, can cause issues with DMAs */
+ unused_nbytes += u->rewind_safeguard;
+
+ if (u->hwbuf_size > unused_nbytes)
+ limit_nbytes = u->hwbuf_size - unused_nbytes;
+ else
+ limit_nbytes = 0;
+
+ if (rewind_nbytes > limit_nbytes)
+ rewind_nbytes = limit_nbytes;
+
+ if (rewind_nbytes > 0) {
+ snd_pcm_sframes_t in_frames, out_frames;
+
+ pa_log_debug("Limited to %lu bytes.", (unsigned long) rewind_nbytes);
+
+ in_frames = (snd_pcm_sframes_t) (rewind_nbytes / u->frame_size);
+ pa_log_debug("before: %lu", (unsigned long) in_frames);
+ if ((out_frames = snd_pcm_rewind(u->pcm_handle, (snd_pcm_uframes_t) in_frames)) < 0) {
+ pa_log("snd_pcm_rewind() failed: %s", pa_alsa_strerror((int) out_frames));
+ if ((err = try_recover(u, "process_rewind", out_frames)) < 0)
+ return -1;
+ if (err == 1)
+ goto rewind_done;
+ out_frames = 0;
+ }
+
+ pa_log_debug("after: %lu", (unsigned long) out_frames);
+
+ rewind_nbytes = (size_t) out_frames * u->frame_size;
+
+ if (rewind_nbytes <= 0)
+ pa_log_info("Tried rewind, but was apparently not possible.");
+ else {
+ u->write_count -= rewind_nbytes;
+ pa_log_debug("Rewound %lu bytes.", (unsigned long) rewind_nbytes);
+ pa_sink_process_rewind(u->sink, rewind_nbytes);
+
+ u->after_rewind = true;
+ return 0;
+ }
+ } else
+ pa_log_debug("Mhmm, actually there is nothing to rewind.");
+
+rewind_done:
+ pa_sink_process_rewind(u->sink, 0);
+ return 0;
+}
+
+static void thread_func(void *userdata) {
+ struct userdata *u = userdata;
+ unsigned short revents = 0;
+
+ pa_assert(u);
+
+ pa_log_debug("Thread starting up");
+
+ if (u->core->realtime_scheduling)
+ pa_thread_make_realtime(u->core->realtime_priority);
+
+ pa_thread_mq_install(&u->thread_mq);
+
+ for (;;) {
+ int ret;
+ pa_usec_t rtpoll_sleep = 0, real_sleep;
+
+#ifdef DEBUG_TIMING
+ pa_log_debug("Loop");
+#endif
+
+ if (PA_UNLIKELY(u->sink->thread_info.rewind_requested)) {
+ if (process_rewind(u) < 0)
+ goto fail;
+ }
+
+ /* Render some data and write it to the dsp */
+ if (PA_SINK_IS_OPENED(u->sink->thread_info.state)) {
+ int work_done;
+ pa_usec_t sleep_usec = 0;
+ bool on_timeout = pa_rtpoll_timer_elapsed(u->rtpoll);
+
+ if (u->use_mmap)
+ work_done = mmap_write(u, &sleep_usec, revents & POLLOUT, on_timeout);
+ else
+ work_done = unix_write(u, &sleep_usec, revents & POLLOUT, on_timeout);
+
+ if (work_done < 0)
+ goto fail;
+
+/* pa_log_debug("work_done = %i", work_done); */
+
+ if (work_done) {
+
+ if (u->first) {
+ pa_log_info("Starting playback.");
+ snd_pcm_start(u->pcm_handle);
+
+ pa_smoother_resume(u->smoother, pa_rtclock_now(), true);
+
+ u->first = false;
+ }
+
+ update_smoother(u);
+ }
+
+ if (u->use_tsched) {
+ pa_usec_t cusec;
+
+ if (u->since_start <= u->hwbuf_size) {
+
+ /* USB devices on ALSA seem to hit a buffer
+ * underrun during the first iterations much
+ * quicker then we calculate here, probably due to
+ * the transport latency. To accommodate for that
+ * we artificially decrease the sleep time until
+ * we have filled the buffer at least once
+ * completely.*/
+
+ if (pa_log_ratelimit(PA_LOG_DEBUG))
+ pa_log_debug("Cutting sleep time for the initial iterations by half.");
+ sleep_usec /= 2;
+ }
+
+ /* OK, the playback buffer is now full, let's
+ * calculate when to wake up next */
+#ifdef DEBUG_TIMING
+ pa_log_debug("Waking up in %0.2fms (sound card clock).", (double) sleep_usec / PA_USEC_PER_MSEC);
+#endif
+
+ /* Convert from the sound card time domain to the
+ * system time domain */
+ cusec = pa_smoother_translate(u->smoother, pa_rtclock_now(), sleep_usec);
+
+#ifdef DEBUG_TIMING
+ pa_log_debug("Waking up in %0.2fms (system clock).", (double) cusec / PA_USEC_PER_MSEC);
+#endif
+
+ /* We don't trust the conversion, so we wake up whatever comes first */
+ rtpoll_sleep = PA_MIN(sleep_usec, cusec);
+ }
+
+ u->after_rewind = false;
+
+ }
+
+ if (u->sink->flags & PA_SINK_DEFERRED_VOLUME) {
+ pa_usec_t volume_sleep;
+ pa_sink_volume_change_apply(u->sink, &volume_sleep);
+ if (volume_sleep > 0) {
+ if (rtpoll_sleep > 0)
+ rtpoll_sleep = PA_MIN(volume_sleep, rtpoll_sleep);
+ else
+ rtpoll_sleep = volume_sleep;
+ }
+ }
+
+ if (rtpoll_sleep > 0) {
+ pa_rtpoll_set_timer_relative(u->rtpoll, rtpoll_sleep);
+ real_sleep = pa_rtclock_now();
+ }
+ else
+ pa_rtpoll_set_timer_disabled(u->rtpoll);
+
+ /* Hmm, nothing to do. Let's sleep */
+ if ((ret = pa_rtpoll_run(u->rtpoll)) < 0)
+ goto fail;
+
+ if (rtpoll_sleep > 0) {
+ real_sleep = pa_rtclock_now() - real_sleep;
+#ifdef DEBUG_TIMING
+ pa_log_debug("Expected sleep: %0.2fms, real sleep: %0.2fms (diff %0.2f ms)",
+ (double) rtpoll_sleep / PA_USEC_PER_MSEC, (double) real_sleep / PA_USEC_PER_MSEC,
+ (double) ((int64_t) real_sleep - (int64_t) rtpoll_sleep) / PA_USEC_PER_MSEC);
+#endif
+ if (u->use_tsched && real_sleep > rtpoll_sleep + u->tsched_watermark_usec)
+ pa_log_info("Scheduling delay of %0.2f ms > %0.2f ms, you might want to investigate this to improve latency...",
+ (double) (real_sleep - rtpoll_sleep) / PA_USEC_PER_MSEC,
+ (double) (u->tsched_watermark_usec) / PA_USEC_PER_MSEC);
+ }
+
+ if (u->sink->flags & PA_SINK_DEFERRED_VOLUME)
+ pa_sink_volume_change_apply(u->sink, NULL);
+
+ if (ret == 0)
+ goto finish;
+
+ /* Tell ALSA about this and process its response */
+ if (PA_SINK_IS_OPENED(u->sink->thread_info.state)) {
+ struct pollfd *pollfd;
+ int err;
+ unsigned n;
+
+ pollfd = pa_rtpoll_item_get_pollfd(u->alsa_rtpoll_item, &n);
+
+ if ((err = snd_pcm_poll_descriptors_revents(u->pcm_handle, pollfd, n, &revents)) < 0) {
+ pa_log("snd_pcm_poll_descriptors_revents() failed: %s", pa_alsa_strerror(err));
+ goto fail;
+ }
+
+ if (revents & ~POLLOUT) {
+ if ((err = pa_alsa_recover_from_poll(u->pcm_handle, revents)) < 0)
+ goto fail;
+
+ /* Stream needs to be restarted */
+ if (err == 1) {
+ close_pcm(u);
+ if (unsuspend(u, true) < 0)
+ goto fail;
+ } else
+ reset_vars(u);
+
+ revents = 0;
+ } else if (revents && u->use_tsched && pa_log_ratelimit(PA_LOG_DEBUG))
+ pa_log_debug("Wakeup from ALSA!");
+
+ } else
+ revents = 0;
+ }
+
+fail:
+ /* If this was no regular exit from the loop we have to continue
+ * processing messages until we received PA_MESSAGE_SHUTDOWN */
+ pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
+ pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
+
+finish:
+ pa_log_debug("Thread shutting down");
+}
+
+static void set_sink_name(pa_sink_new_data *data, pa_modargs *ma, const char *device_id, const char *device_name, pa_alsa_mapping *mapping) {
+ const char *n;
+ char *t;
+
+ pa_assert(data);
+ pa_assert(ma);
+ pa_assert(device_name);
+
+ if ((n = pa_modargs_get_value(ma, "sink_name", NULL))) {
+ pa_sink_new_data_set_name(data, n);
+ data->namereg_fail = true;
+ return;
+ }
+
+ if ((n = pa_modargs_get_value(ma, "name", NULL)))
+ data->namereg_fail = true;
+ else {
+ n = device_id ? device_id : device_name;
+ data->namereg_fail = false;
+ }
+
+ if (mapping)
+ t = pa_sprintf_malloc("alsa_output.%s.%s", n, mapping->name);
+ else
+ t = pa_sprintf_malloc("alsa_output.%s", n);
+
+ pa_sink_new_data_set_name(data, t);
+ pa_xfree(t);
+}
+
+static void find_mixer(struct userdata *u, pa_alsa_mapping *mapping, const char *element, bool ignore_dB) {
+ const char *mdev;
+
+ if (!mapping && !element)
+ return;
+
+ if (!element && mapping && pa_alsa_path_set_is_empty(mapping->output_path_set))
+ return;
+
+ u->mixers = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func,
+ NULL, (pa_free_cb_t) pa_alsa_mixer_free);
+
+ mdev = pa_proplist_gets(mapping->proplist, "alsa.mixer_device");
+ if (mdev) {
+ u->mixer_handle = pa_alsa_open_mixer_by_name(u->mixers, mdev, true);
+ } else {
+ u->mixer_handle = pa_alsa_open_mixer_for_pcm(u->mixers, u->pcm_handle, true);
+ }
+ if (!u->mixer_handle) {
+ pa_log_info("Failed to find a working mixer device.");
+ return;
+ }
+
+ if (element) {
+
+ if (!(u->mixer_path = pa_alsa_path_synthesize(element, PA_ALSA_DIRECTION_OUTPUT)))
+ goto fail;
+
+ if (pa_alsa_path_probe(u->mixer_path, NULL, u->mixer_handle, ignore_dB) < 0)
+ goto fail;
+
+ pa_log_debug("Probed mixer path %s:", u->mixer_path->name);
+ pa_alsa_path_dump(u->mixer_path);
+ } else {
+ u->mixer_path_set = mapping->output_path_set;
+ }
+
+ return;
+
+fail:
+
+ if (u->mixer_path) {
+ pa_alsa_path_free(u->mixer_path);
+ u->mixer_path = NULL;
+ }
+
+ u->mixer_handle = NULL;
+ pa_hashmap_free(u->mixers);
+ u->mixers = NULL;
+}
+
+static int setup_mixer(struct userdata *u, bool ignore_dB) {
+ bool need_mixer_callback = false;
+
+ pa_assert(u);
+
+ /* This code is before the u->mixer_handle check, because if the UCM
+ * configuration doesn't specify volume or mute controls, u->mixer_handle
+ * will be NULL, but the UCM device enable sequence will still need to be
+ * executed. */
+ if (u->sink->active_port && u->ucm_context) {
+ if (pa_alsa_ucm_set_port(u->ucm_context, u->sink->active_port, true) < 0)
+ return -1;
+ }
+
+ if (!u->mixer_handle)
+ return 0;
+
+ if (u->sink->active_port) {
+ if (!u->ucm_context) {
+ pa_alsa_port_data *data;
+
+ /* We have a list of supported paths, so let's activate the
+ * one that has been chosen as active */
+
+ data = PA_DEVICE_PORT_DATA(u->sink->active_port);
+ u->mixer_path = data->path;
+
+ pa_alsa_path_select(data->path, data->setting, u->mixer_handle, u->sink->muted);
+ } else {
+ pa_alsa_ucm_port_data *data;
+
+ data = PA_DEVICE_PORT_DATA(u->sink->active_port);
+
+ /* Now activate volume controls, if any */
+ if (data->path) {
+ u->mixer_path = data->path;
+ pa_alsa_path_select(u->mixer_path, NULL, u->mixer_handle, u->sink->muted);
+ }
+ }
+ } else {
+
+ if (!u->mixer_path && u->mixer_path_set)
+ u->mixer_path = pa_hashmap_first(u->mixer_path_set->paths);
+
+ if (u->mixer_path) {
+ /* Hmm, we have only a single path, then let's activate it */
+
+ pa_alsa_path_select(u->mixer_path, u->mixer_path->settings, u->mixer_handle, u->sink->muted);
+ } else
+ return 0;
+ }
+
+ mixer_volume_init(u);
+
+ /* Will we need to register callbacks? */
+ if (u->mixer_path_set && u->mixer_path_set->paths) {
+ pa_alsa_path *p;
+ void *state;
+
+ PA_HASHMAP_FOREACH(p, u->mixer_path_set->paths, state) {
+ if (p->has_volume || p->has_mute)
+ need_mixer_callback = true;
+ }
+ }
+ else if (u->mixer_path)
+ need_mixer_callback = u->mixer_path->has_volume || u->mixer_path->has_mute;
+
+ if (need_mixer_callback) {
+ int (*mixer_callback)(snd_mixer_elem_t *, unsigned int);
+ if (u->sink->flags & PA_SINK_DEFERRED_VOLUME) {
+ u->mixer_pd = pa_alsa_mixer_pdata_new();
+ mixer_callback = io_mixer_callback;
+
+ if (pa_alsa_set_mixer_rtpoll(u->mixer_pd, u->mixer_handle, u->rtpoll) < 0) {
+ pa_log("Failed to initialize file descriptor monitoring");
+ return -1;
+ }
+ } else {
+ u->mixer_fdl = pa_alsa_fdlist_new();
+ mixer_callback = ctl_mixer_callback;
+
+ if (pa_alsa_fdlist_set_handle(u->mixer_fdl, u->mixer_handle, NULL, u->core->mainloop) < 0) {
+ pa_log("Failed to initialize file descriptor monitoring");
+ return -1;
+ }
+ }
+
+ if (u->mixer_path_set)
+ pa_alsa_path_set_set_callback(u->mixer_path_set, u->mixer_handle, mixer_callback, u);
+ else
+ pa_alsa_path_set_callback(u->mixer_path, u->mixer_handle, mixer_callback, u);
+ }
+
+ return 0;
+}
+
+pa_sink *pa_alsa_sink_new(pa_module *m, pa_modargs *ma, const char*driver, pa_card *card, pa_alsa_mapping *mapping) {
+
+ struct userdata *u = NULL;
+ const char *dev_id = NULL, *key, *mod_name;
+ pa_sample_spec ss;
+ char *thread_name = NULL;
+ uint32_t alternate_sample_rate;
+ pa_channel_map map;
+ uint32_t nfrags, frag_size, buffer_size, tsched_size, tsched_watermark, rewind_safeguard;
+ snd_pcm_uframes_t period_frames, buffer_frames, tsched_frames;
+ size_t frame_size;
+ bool use_mmap = true;
+ bool use_tsched = true;
+ bool ignore_dB = false;
+ bool namereg_fail = false;
+ bool deferred_volume = false;
+ bool set_formats = false;
+ bool fixed_latency_range = false;
+ bool b;
+ bool d;
+ bool avoid_resampling;
+ pa_sink_new_data data;
+ bool volume_is_set;
+ bool mute_is_set;
+ pa_alsa_profile_set *profile_set = NULL;
+ void *state;
+
+ pa_assert(m);
+ pa_assert(ma);
+
+ ss = m->core->default_sample_spec;
+ map = m->core->default_channel_map;
+ avoid_resampling = m->core->avoid_resampling;
+
+ /* Pick sample spec overrides from the mapping, if any */
+ if (mapping) {
+ if (mapping->sample_spec.format != PA_SAMPLE_INVALID)
+ ss.format = mapping->sample_spec.format;
+ if (mapping->sample_spec.rate != 0)
+ ss.rate = mapping->sample_spec.rate;
+ if (mapping->sample_spec.channels != 0) {
+ ss.channels = mapping->sample_spec.channels;
+ if (pa_channel_map_valid(&mapping->channel_map))
+ pa_assert(pa_channel_map_compatible(&mapping->channel_map, &ss));
+ }
+ }
+
+ /* Override with modargs if provided */
+ if (pa_modargs_get_sample_spec_and_channel_map(ma, &ss, &map, PA_CHANNEL_MAP_ALSA) < 0) {
+ pa_log("Failed to parse sample specification and channel map");
+ goto fail;
+ }
+
+ alternate_sample_rate = m->core->alternate_sample_rate;
+ if (pa_modargs_get_alternate_sample_rate(ma, &alternate_sample_rate) < 0) {
+ pa_log("Failed to parse alternate sample rate");
+ goto fail;
+ }
+
+ frame_size = pa_frame_size(&ss);
+
+ nfrags = m->core->default_n_fragments;
+ frag_size = (uint32_t) pa_usec_to_bytes(m->core->default_fragment_size_msec*PA_USEC_PER_MSEC, &ss);
+ if (frag_size <= 0)
+ frag_size = (uint32_t) frame_size;
+ tsched_size = (uint32_t) pa_usec_to_bytes(DEFAULT_TSCHED_BUFFER_USEC, &ss);
+ tsched_watermark = (uint32_t) pa_usec_to_bytes(DEFAULT_TSCHED_WATERMARK_USEC, &ss);
+
+ if (pa_modargs_get_value_u32(ma, "fragments", &nfrags) < 0 ||
+ pa_modargs_get_value_u32(ma, "fragment_size", &frag_size) < 0 ||
+ pa_modargs_get_value_u32(ma, "tsched_buffer_size", &tsched_size) < 0 ||
+ pa_modargs_get_value_u32(ma, "tsched_buffer_watermark", &tsched_watermark) < 0) {
+ pa_log("Failed to parse buffer metrics");
+ goto fail;
+ }
+
+ buffer_size = nfrags * frag_size;
+
+ period_frames = frag_size/frame_size;
+ buffer_frames = buffer_size/frame_size;
+ tsched_frames = tsched_size/frame_size;
+
+ if (pa_modargs_get_value_boolean(ma, "mmap", &use_mmap) < 0) {
+ pa_log("Failed to parse mmap argument.");
+ goto fail;
+ }
+
+ if (pa_modargs_get_value_boolean(ma, "tsched", &use_tsched) < 0) {
+ pa_log("Failed to parse tsched argument.");
+ goto fail;
+ }
+
+ if (pa_modargs_get_value_boolean(ma, "ignore_dB", &ignore_dB) < 0) {
+ pa_log("Failed to parse ignore_dB argument.");
+ goto fail;
+ }
+
+ rewind_safeguard = PA_MAX(DEFAULT_REWIND_SAFEGUARD_BYTES, pa_usec_to_bytes(DEFAULT_REWIND_SAFEGUARD_USEC, &ss));
+ if (pa_modargs_get_value_u32(ma, "rewind_safeguard", &rewind_safeguard) < 0) {
+ pa_log("Failed to parse rewind_safeguard argument");
+ goto fail;
+ }
+
+ deferred_volume = m->core->deferred_volume;
+ if (pa_modargs_get_value_boolean(ma, "deferred_volume", &deferred_volume) < 0) {
+ pa_log("Failed to parse deferred_volume argument.");
+ goto fail;
+ }
+
+ if (pa_modargs_get_value_boolean(ma, "fixed_latency_range", &fixed_latency_range) < 0) {
+ pa_log("Failed to parse fixed_latency_range argument.");
+ goto fail;
+ }
+
+ use_tsched = pa_alsa_may_tsched(use_tsched);
+
+ u = pa_xnew0(struct userdata, 1);
+ u->core = m->core;
+ u->module = m;
+ u->use_mmap = use_mmap;
+ u->use_tsched = use_tsched;
+ u->tsched_size = tsched_size;
+ u->initial_info.nfrags = (size_t) nfrags;
+ u->initial_info.fragment_size = (size_t) frag_size;
+ u->initial_info.tsched_size = (size_t) tsched_size;
+ u->initial_info.tsched_watermark = (size_t) tsched_watermark;
+ u->initial_info.rewind_safeguard = (size_t) rewind_safeguard;
+ u->deferred_volume = deferred_volume;
+ u->fixed_latency_range = fixed_latency_range;
+ u->first = true;
+ u->rewind_safeguard = rewind_safeguard;
+ u->rtpoll = pa_rtpoll_new();
+
+ if (pa_thread_mq_init(&u->thread_mq, m->core->mainloop, u->rtpoll) < 0) {
+ pa_log("pa_thread_mq_init() failed.");
+ goto fail;
+ }
+
+ u->smoother = pa_smoother_new(
+ SMOOTHER_ADJUST_USEC,
+ SMOOTHER_WINDOW_USEC,
+ true,
+ true,
+ 5,
+ pa_rtclock_now(),
+ true);
+ u->smoother_interval = SMOOTHER_MIN_INTERVAL;
+
+ /* use ucm */
+ if (mapping && mapping->ucm_context.ucm)
+ u->ucm_context = &mapping->ucm_context;
+
+ dev_id = pa_modargs_get_value(
+ ma, "device_id",
+ pa_modargs_get_value(ma, "device", DEFAULT_DEVICE));
+
+ u->paths_dir = pa_xstrdup(pa_modargs_get_value(ma, "paths_dir", NULL));
+
+ if (reserve_init(u, dev_id) < 0)
+ goto fail;
+
+ if (reserve_monitor_init(u, dev_id) < 0)
+ goto fail;
+
+ b = use_mmap;
+ d = use_tsched;
+
+ /* Force ALSA to reread its configuration if module-alsa-card didn't
+ * do it for us. This matters if our device was hot-plugged after ALSA
+ * has already read its configuration - see
+ * https://bugs.freedesktop.org/show_bug.cgi?id=54029
+ */
+
+ if (!card)
+ snd_config_update_free_global();
+
+ if (mapping) {
+
+ if (!(dev_id = pa_modargs_get_value(ma, "device_id", NULL))) {
+ pa_log("device_id= not set");
+ goto fail;
+ }
+
+ if ((mod_name = pa_proplist_gets(mapping->proplist, PA_ALSA_PROP_UCM_MODIFIER))) {
+ if (snd_use_case_set(u->ucm_context->ucm->ucm_mgr, "_enamod", mod_name) < 0)
+ pa_log("Failed to enable ucm modifier %s", mod_name);
+ else
+ pa_log_debug("Enabled ucm modifier %s", mod_name);
+ }
+
+ if (!(u->pcm_handle = pa_alsa_open_by_device_id_mapping(
+ dev_id,
+ &u->device_name,
+ &ss, &map,
+ SND_PCM_STREAM_PLAYBACK,
+ &period_frames, &buffer_frames, tsched_frames,
+ &b, &d, mapping)))
+ goto fail;
+
+ } else if ((dev_id = pa_modargs_get_value(ma, "device_id", NULL))) {
+
+ if (!(profile_set = pa_alsa_profile_set_new(NULL, &map)))
+ goto fail;
+
+ if (!(u->pcm_handle = pa_alsa_open_by_device_id_auto(
+ dev_id,
+ &u->device_name,
+ &ss, &map,
+ SND_PCM_STREAM_PLAYBACK,
+ &period_frames, &buffer_frames, tsched_frames,
+ &b, &d, profile_set, &mapping)))
+ goto fail;
+
+ } else {
+
+ if (!(u->pcm_handle = pa_alsa_open_by_device_string(
+ pa_modargs_get_value(ma, "device", DEFAULT_DEVICE),
+ &u->device_name,
+ &ss, &map,
+ SND_PCM_STREAM_PLAYBACK,
+ &period_frames, &buffer_frames, tsched_frames,
+ &b, &d, false)))
+ goto fail;
+ }
+
+ pa_assert(u->device_name);
+ pa_log_info("Successfully opened device %s.", u->device_name);
+
+ if (pa_alsa_pcm_is_modem(u->pcm_handle)) {
+ pa_log_notice("Device %s is modem, refusing further initialization.", u->device_name);
+ goto fail;
+ }
+
+ if (mapping)
+ pa_log_info("Selected mapping '%s' (%s).", mapping->description, mapping->name);
+
+ if (use_mmap && !b) {
+ pa_log_info("Device doesn't support mmap(), falling back to UNIX read/write mode.");
+ u->use_mmap = use_mmap = false;
+ }
+
+ if (use_tsched && (!b || !d)) {
+ pa_log_info("Cannot enable timer-based scheduling, falling back to sound IRQ scheduling.");
+ u->use_tsched = use_tsched = false;
+ }
+
+ if (u->use_mmap)
+ pa_log_info("Successfully enabled mmap() mode.");
+
+ if (u->use_tsched) {
+ pa_log_info("Successfully enabled timer-based scheduling mode.");
+
+ if (u->fixed_latency_range)
+ pa_log_info("Disabling latency range changes on underrun");
+ }
+
+ /* All passthrough formats supported by PulseAudio require
+ * IEC61937 framing with two fake channels. So, passthrough
+ * clients will always send two channels. Multichannel sinks
+ * cannot accept that, because nobody implemented sink channel count
+ * switching so far. So just don't show known non-working settings
+ * to the user. */
+ if ((is_iec958(u) || is_hdmi(u)) && ss.channels == 2)
+ set_formats = true;
+
+ u->verified_sample_spec = ss;
+
+ u->supported_formats = pa_alsa_get_supported_formats(u->pcm_handle, ss.format);
+ if (!u->supported_formats) {
+ pa_log_error("Failed to find any supported sample formats.");
+ goto fail;
+ }
+
+ u->supported_rates = pa_alsa_get_supported_rates(u->pcm_handle, ss.rate);
+ if (!u->supported_rates) {
+ pa_log_error("Failed to find any supported sample rates.");
+ goto fail;
+ }
+
+ /* ALSA might tweak the sample spec, so recalculate the frame size */
+ frame_size = pa_frame_size(&ss);
+
+ pa_sink_new_data_init(&data);
+ data.driver = driver;
+ data.module = m;
+ data.card = card;
+ set_sink_name(&data, ma, dev_id, u->device_name, mapping);
+
+ /* We need to give pa_modargs_get_value_boolean() a pointer to a local
+ * variable instead of using &data.namereg_fail directly, because
+ * data.namereg_fail is a bitfield and taking the address of a bitfield
+ * variable is impossible. */
+ namereg_fail = data.namereg_fail;
+ if (pa_modargs_get_value_boolean(ma, "namereg_fail", &namereg_fail) < 0) {
+ pa_log("Failed to parse namereg_fail argument.");
+ pa_sink_new_data_done(&data);
+ goto fail;
+ }
+ data.namereg_fail = namereg_fail;
+
+ if (pa_modargs_get_value_boolean(ma, "avoid_resampling", &avoid_resampling) < 0) {
+ pa_log("Failed to parse avoid_resampling argument.");
+ pa_sink_new_data_done(&data);
+ goto fail;
+ }
+ pa_sink_new_data_set_avoid_resampling(&data, avoid_resampling);
+
+ pa_sink_new_data_set_sample_spec(&data, &ss);
+ pa_sink_new_data_set_channel_map(&data, &map);
+ pa_sink_new_data_set_alternate_sample_rate(&data, alternate_sample_rate);
+
+ pa_alsa_init_proplist_pcm(m->core, data.proplist, u->pcm_handle);
+ pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, u->device_name);
+ pa_proplist_setf(data.proplist, PA_PROP_DEVICE_BUFFERING_BUFFER_SIZE, "%lu", (unsigned long) (buffer_frames * frame_size));
+ pa_proplist_setf(data.proplist, PA_PROP_DEVICE_BUFFERING_FRAGMENT_SIZE, "%lu", (unsigned long) (period_frames * frame_size));
+ pa_proplist_sets(data.proplist, PA_PROP_DEVICE_ACCESS_MODE, u->use_tsched ? "mmap+timer" : (u->use_mmap ? "mmap" : "serial"));
+
+ if (mapping) {
+ pa_proplist_sets(data.proplist, PA_PROP_DEVICE_PROFILE_NAME, mapping->name);
+ pa_proplist_sets(data.proplist, PA_PROP_DEVICE_PROFILE_DESCRIPTION, mapping->description);
+
+ state = NULL;
+ while ((key = pa_proplist_iterate(mapping->proplist, &state)))
+ pa_proplist_sets(data.proplist, key, pa_proplist_gets(mapping->proplist, key));
+ }
+
+ pa_alsa_init_description(data.proplist, card);
+
+ if (u->control_device)
+ pa_alsa_init_proplist_ctl(data.proplist, u->control_device);
+
+ if (pa_modargs_get_proplist(ma, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
+ pa_log("Invalid properties");
+ pa_sink_new_data_done(&data);
+ goto fail;
+ }
+
+ if (u->ucm_context) {
+ pa_alsa_ucm_add_ports(&data.ports, data.proplist, u->ucm_context, true, card, u->pcm_handle, ignore_dB);
+ find_mixer(u, mapping, pa_modargs_get_value(ma, "control", NULL), ignore_dB);
+ } else {
+ find_mixer(u, mapping, pa_modargs_get_value(ma, "control", NULL), ignore_dB);
+ if (u->mixer_path_set)
+ pa_alsa_add_ports(&data, u->mixer_path_set, card);
+ }
+
+ u->sink = pa_sink_new(m->core, &data, PA_SINK_HARDWARE | PA_SINK_LATENCY | (u->use_tsched ? PA_SINK_DYNAMIC_LATENCY : 0) |
+ (set_formats ? PA_SINK_SET_FORMATS : 0));
+ volume_is_set = data.volume_is_set;
+ mute_is_set = data.muted_is_set;
+ pa_sink_new_data_done(&data);
+
+ if (!u->sink) {
+ pa_log("Failed to create sink object");
+ goto fail;
+ }
+
+ if (u->ucm_context) {
+ pa_device_port *port;
+ unsigned h_prio = 0;
+ PA_HASHMAP_FOREACH(port, u->sink->ports, state) {
+ if (!h_prio || port->priority > h_prio)
+ h_prio = port->priority;
+ }
+ /* ucm ports prioriy is 100, 200, ..., 900, change it to units digit */
+ h_prio = h_prio / 100;
+ u->sink->priority += h_prio;
+ }
+
+ if (pa_modargs_get_value_u32(ma, "deferred_volume_safety_margin",
+ &u->sink->thread_info.volume_change_safety_margin) < 0) {
+ pa_log("Failed to parse deferred_volume_safety_margin parameter");
+ goto fail;
+ }
+
+ if (pa_modargs_get_value_s32(ma, "deferred_volume_extra_delay",
+ &u->sink->thread_info.volume_change_extra_delay) < 0) {
+ pa_log("Failed to parse deferred_volume_extra_delay parameter");
+ goto fail;
+ }
+
+ u->sink->parent.process_msg = sink_process_msg;
+ if (u->use_tsched)
+ u->sink->update_requested_latency = sink_update_requested_latency_cb;
+ u->sink->set_state_in_main_thread = sink_set_state_in_main_thread_cb;
+ u->sink->set_state_in_io_thread = sink_set_state_in_io_thread_cb;
+ if (u->ucm_context)
+ u->sink->set_port = sink_set_port_ucm_cb;
+ else
+ u->sink->set_port = sink_set_port_cb;
+ u->sink->reconfigure = sink_reconfigure_cb;
+ u->sink->userdata = u;
+
+ pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
+ pa_sink_set_rtpoll(u->sink, u->rtpoll);
+
+ u->frame_size = frame_size;
+ u->frames_per_block = pa_mempool_block_size_max(m->core->mempool) / frame_size;
+ u->fragment_size = frag_size = (size_t) (period_frames * frame_size);
+ u->hwbuf_size = buffer_size = (size_t) (buffer_frames * frame_size);
+ pa_cvolume_mute(&u->hardware_volume, u->sink->sample_spec.channels);
+
+ pa_log_info("Using %0.1f fragments of size %lu bytes (%0.2fms), buffer size is %lu bytes (%0.2fms)",
+ (double) u->hwbuf_size / (double) u->fragment_size,
+ (long unsigned) u->fragment_size,
+ (double) pa_bytes_to_usec(u->fragment_size, &ss) / PA_USEC_PER_MSEC,
+ (long unsigned) u->hwbuf_size,
+ (double) pa_bytes_to_usec(u->hwbuf_size, &ss) / PA_USEC_PER_MSEC);
+
+ pa_sink_set_max_request(u->sink, u->hwbuf_size);
+ if (pa_alsa_pcm_is_hw(u->pcm_handle))
+ pa_sink_set_max_rewind(u->sink, u->hwbuf_size);
+ else {
+ pa_log_info("Disabling rewind for device %s", u->device_name);
+ pa_sink_set_max_rewind(u->sink, 0);
+ }
+
+ if (u->use_tsched) {
+ u->tsched_watermark_ref = tsched_watermark;
+ reset_watermark(u, u->tsched_watermark_ref, &ss, false);
+ } else
+ pa_sink_set_fixed_latency(u->sink, pa_bytes_to_usec(u->hwbuf_size, &ss));
+
+ reserve_update(u);
+
+ if (update_sw_params(u, false) < 0)
+ goto fail;
+
+ if (setup_mixer(u, ignore_dB) < 0)
+ goto fail;
+
+ pa_alsa_dump(PA_LOG_DEBUG, u->pcm_handle);
+
+ thread_name = pa_sprintf_malloc("alsa-sink-%s", pa_strnull(pa_proplist_gets(u->sink->proplist, "alsa.id")));
+ if (!(u->thread = pa_thread_new(thread_name, thread_func, u))) {
+ pa_log("Failed to create thread.");
+ goto fail;
+ }
+ pa_xfree(thread_name);
+ thread_name = NULL;
+
+ /* Get initial mixer settings */
+ if (volume_is_set) {
+ if (u->sink->set_volume)
+ u->sink->set_volume(u->sink);
+ } else {
+ if (u->sink->get_volume)
+ u->sink->get_volume(u->sink);
+ }
+
+ if (mute_is_set) {
+ if (u->sink->set_mute)
+ u->sink->set_mute(u->sink);
+ } else {
+ if (u->sink->get_mute) {
+ bool mute;
+
+ if (u->sink->get_mute(u->sink, &mute) >= 0)
+ pa_sink_set_mute(u->sink, mute, false);
+ }
+ }
+
+ if ((volume_is_set || mute_is_set) && u->sink->write_volume)
+ u->sink->write_volume(u->sink);
+
+ if (set_formats) {
+ /* For S/PDIF and HDMI, allow getting/setting custom formats */
+ pa_format_info *format;
+
+ /* To start with, we only support PCM formats. Other formats may be added
+ * with pa_sink_set_formats().*/
+ format = pa_format_info_new();
+ format->encoding = PA_ENCODING_PCM;
+ u->formats = pa_idxset_new(NULL, NULL);
+ pa_idxset_put(u->formats, format, NULL);
+
+ u->sink->get_formats = sink_get_formats;
+ u->sink->set_formats = sink_set_formats;
+ }
+
+ pa_sink_put(u->sink);
+
+ if (profile_set)
+ pa_alsa_profile_set_free(profile_set);
+
+ /* Suspend if necessary. FIXME: It would be better to start suspended, but
+ * that would require some core changes. It's possible to set
+ * pa_sink_new_data.suspend_cause, but that has to be done before the
+ * pa_sink_new() call, and we know if we need to suspend only after the
+ * pa_sink_new() call when the initial port has been chosen. Calling
+ * pa_sink_suspend() between pa_sink_new() and pa_sink_put() would
+ * otherwise work, but currently pa_sink_suspend() will crash if
+ * pa_sink_put() hasn't been called. */
+ if (u->sink->active_port && !u->ucm_context) {
+ pa_alsa_port_data *port_data;
+
+ port_data = PA_DEVICE_PORT_DATA(u->sink->active_port);
+
+ if (port_data->suspend_when_unavailable && u->sink->active_port->available == PA_AVAILABLE_NO)
+ pa_sink_suspend(u->sink, true, PA_SUSPEND_UNAVAILABLE);
+ }
+
+ return u->sink;
+
+fail:
+ pa_xfree(thread_name);
+
+ if (u)
+ userdata_free(u);
+
+ if (profile_set)
+ pa_alsa_profile_set_free(profile_set);
+
+ return NULL;
+}
+
+static void userdata_free(struct userdata *u) {
+ pa_assert(u);
+
+ if (u->sink)
+ pa_sink_unlink(u->sink);
+
+ if (u->thread) {
+ pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
+ pa_thread_free(u->thread);
+ }
+
+ pa_thread_mq_done(&u->thread_mq);
+
+ if (u->sink)
+ pa_sink_unref(u->sink);
+
+ if (u->memchunk.memblock)
+ pa_memblock_unref(u->memchunk.memblock);
+
+ if (u->mixer_pd)
+ pa_alsa_mixer_pdata_free(u->mixer_pd);
+
+ if (u->alsa_rtpoll_item)
+ pa_rtpoll_item_free(u->alsa_rtpoll_item);
+
+ if (u->rtpoll)
+ pa_rtpoll_free(u->rtpoll);
+
+ if (u->pcm_handle) {
+ snd_pcm_drop(u->pcm_handle);
+ snd_pcm_close(u->pcm_handle);
+ }
+
+ if (u->mixer_fdl)
+ pa_alsa_fdlist_free(u->mixer_fdl);
+
+ /* Only free the mixer_path if the sink owns it */
+ if (u->mixer_path && !u->mixer_path_set && !u->ucm_context)
+ pa_alsa_path_free(u->mixer_path);
+
+ if (u->mixers)
+ pa_hashmap_free(u->mixers);
+
+ if (u->smoother)
+ pa_smoother_free(u->smoother);
+
+ if (u->formats)
+ pa_idxset_free(u->formats, (pa_free_cb_t) pa_format_info_free);
+
+ if (u->supported_formats)
+ pa_xfree(u->supported_formats);
+
+ if (u->supported_rates)
+ pa_xfree(u->supported_rates);
+
+ reserve_done(u);
+ monitor_done(u);
+
+ pa_xfree(u->device_name);
+ pa_xfree(u->control_device);
+ pa_xfree(u->paths_dir);
+ pa_xfree(u);
+}
+
+void pa_alsa_sink_free(pa_sink *s) {
+ struct userdata *u;
+
+ pa_sink_assert_ref(s);
+ pa_assert_se(u = s->userdata);
+
+ userdata_free(u);
+}
diff --git a/src/modules/alsa/alsa-sink.h b/src/modules/alsa/alsa-sink.h
new file mode 100644
index 0000000..78a2cb2
--- /dev/null
+++ b/src/modules/alsa/alsa-sink.h
@@ -0,0 +1,34 @@
+#ifndef fooalsasinkhfoo
+#define fooalsasinkhfoo
+
+/***
+ This file is part of PulseAudio.
+
+ Copyright 2004-2006 Lennart Poettering
+ Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
+
+ PulseAudio is free software; you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License,
+ or (at your option) any later version.
+
+ PulseAudio is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <pulsecore/module.h>
+#include <pulsecore/modargs.h>
+#include <pulsecore/sink.h>
+
+#include "alsa-util.h"
+
+pa_sink* pa_alsa_sink_new(pa_module *m, pa_modargs *ma, const char*driver, pa_card *card, pa_alsa_mapping *mapping);
+
+void pa_alsa_sink_free(pa_sink *s);
+
+#endif
diff --git a/src/modules/alsa/alsa-source.c b/src/modules/alsa/alsa-source.c
new file mode 100644
index 0000000..76370f8
--- /dev/null
+++ b/src/modules/alsa/alsa-source.c
@@ -0,0 +1,2473 @@
+/***
+ This file is part of PulseAudio.
+
+ Copyright 2004-2008 Lennart Poettering
+ Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
+
+ PulseAudio is free software; you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License,
+ or (at your option) any later version.
+
+ PulseAudio is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+***/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <signal.h>
+#include <stdio.h>
+
+#include <alsa/asoundlib.h>
+
+#include <pulse/rtclock.h>
+#include <pulse/timeval.h>
+#include <pulse/util.h>
+#include <pulse/volume.h>
+#include <pulse/xmalloc.h>
+
+#include <pulsecore/core.h>
+#include <pulsecore/i18n.h>
+#include <pulsecore/module.h>
+#include <pulsecore/memchunk.h>
+#include <pulsecore/sink.h>
+#include <pulsecore/modargs.h>
+#include <pulsecore/core-rtclock.h>
+#include <pulsecore/core-util.h>
+#include <pulsecore/sample-util.h>
+#include <pulsecore/log.h>
+#include <pulsecore/macro.h>
+#include <pulsecore/thread.h>
+#include <pulsecore/thread-mq.h>
+#include <pulsecore/rtpoll.h>
+#include <pulsecore/time-smoother.h>
+
+#include <modules/reserve-wrap.h>
+
+#include "alsa-util.h"
+#include "alsa-source.h"
+
+/* #define DEBUG_TIMING */
+
+#define DEFAULT_DEVICE "default"
+
+#define DEFAULT_TSCHED_BUFFER_USEC (2*PA_USEC_PER_SEC) /* 2s */
+#define DEFAULT_TSCHED_WATERMARK_USEC (20*PA_USEC_PER_MSEC) /* 20ms */
+
+#define TSCHED_WATERMARK_INC_STEP_USEC (10*PA_USEC_PER_MSEC) /* 10ms */
+#define TSCHED_WATERMARK_DEC_STEP_USEC (5*PA_USEC_PER_MSEC) /* 5ms */
+#define TSCHED_WATERMARK_VERIFY_AFTER_USEC (20*PA_USEC_PER_SEC) /* 20s */
+#define TSCHED_WATERMARK_INC_THRESHOLD_USEC (0*PA_USEC_PER_MSEC) /* 0ms */
+#define TSCHED_WATERMARK_DEC_THRESHOLD_USEC (100*PA_USEC_PER_MSEC) /* 100ms */
+#define TSCHED_WATERMARK_STEP_USEC (10*PA_USEC_PER_MSEC) /* 10ms */
+
+#define TSCHED_MIN_SLEEP_USEC (10*PA_USEC_PER_MSEC) /* 10ms */
+#define TSCHED_MIN_WAKEUP_USEC (4*PA_USEC_PER_MSEC) /* 4ms */
+
+#define SMOOTHER_WINDOW_USEC (10*PA_USEC_PER_SEC) /* 10s */
+#define SMOOTHER_ADJUST_USEC (1*PA_USEC_PER_SEC) /* 1s */
+
+#define SMOOTHER_MIN_INTERVAL (2*PA_USEC_PER_MSEC) /* 2ms */
+#define SMOOTHER_MAX_INTERVAL (200*PA_USEC_PER_MSEC) /* 200ms */
+
+#define VOLUME_ACCURACY (PA_VOLUME_NORM/100)
+
+struct userdata {
+ pa_core *core;
+ pa_module *module;
+ pa_source *source;
+
+ pa_thread *thread;
+ pa_thread_mq thread_mq;
+ pa_rtpoll *rtpoll;
+
+ snd_pcm_t *pcm_handle;
+
+ char *paths_dir;
+ pa_alsa_fdlist *mixer_fdl;
+ pa_alsa_mixer_pdata *mixer_pd;
+ pa_hashmap *mixers;
+ snd_mixer_t *mixer_handle;
+ pa_alsa_path_set *mixer_path_set;
+ pa_alsa_path *mixer_path;
+
+ pa_cvolume hardware_volume;
+
+ pa_sample_spec verified_sample_spec;
+ pa_sample_format_t *supported_formats;
+ unsigned int *supported_rates;
+ struct {
+ size_t fragment_size;
+ size_t nfrags;
+ size_t tsched_size;
+ size_t tsched_watermark;
+ } initial_info;
+
+ size_t
+ frame_size,
+ fragment_size,
+ hwbuf_size,
+ tsched_size,
+ tsched_watermark,
+ tsched_watermark_ref,
+ hwbuf_unused,
+ min_sleep,
+ min_wakeup,
+ watermark_inc_step,
+ watermark_dec_step,
+ watermark_inc_threshold,
+ watermark_dec_threshold;
+
+ snd_pcm_uframes_t frames_per_block;
+
+ pa_usec_t watermark_dec_not_before;
+ pa_usec_t min_latency_ref;
+ pa_usec_t tsched_watermark_usec;
+
+ char *device_name; /* name of the PCM device */
+ char *control_device; /* name of the control device */
+
+ bool use_mmap:1, use_tsched:1, deferred_volume:1, fixed_latency_range:1;
+
+ bool first;
+
+ pa_rtpoll_item *alsa_rtpoll_item;
+
+ pa_smoother *smoother;
+ uint64_t read_count;
+ pa_usec_t smoother_interval;
+ pa_usec_t last_smoother_update;
+
+ pa_reserve_wrapper *reserve;
+ pa_hook_slot *reserve_slot;
+ pa_reserve_monitor_wrapper *monitor;
+ pa_hook_slot *monitor_slot;
+
+ /* ucm context */
+ pa_alsa_ucm_mapping_context *ucm_context;
+};
+
+enum {
+ SOURCE_MESSAGE_SYNC_MIXER = PA_SOURCE_MESSAGE_MAX
+};
+
+static void userdata_free(struct userdata *u);
+static int unsuspend(struct userdata *u, bool recovering);
+
+static pa_hook_result_t reserve_cb(pa_reserve_wrapper *r, void *forced, struct userdata *u) {
+ pa_assert(r);
+ pa_assert(u);
+
+ pa_log_debug("Suspending source %s, because another application requested us to release the device.", u->source->name);
+
+ if (pa_source_suspend(u->source, true, PA_SUSPEND_APPLICATION) < 0)
+ return PA_HOOK_CANCEL;
+
+ return PA_HOOK_OK;
+}
+
+static void reserve_done(struct userdata *u) {
+ pa_assert(u);
+
+ if (u->reserve_slot) {
+ pa_hook_slot_free(u->reserve_slot);
+ u->reserve_slot = NULL;
+ }
+
+ if (u->reserve) {
+ pa_reserve_wrapper_unref(u->reserve);
+ u->reserve = NULL;
+ }
+}
+
+static void reserve_update(struct userdata *u) {
+ const char *description;
+ pa_assert(u);
+
+ if (!u->source || !u->reserve)
+ return;
+
+ if ((description = pa_proplist_gets(u->source->proplist, PA_PROP_DEVICE_DESCRIPTION)))
+ pa_reserve_wrapper_set_application_device_name(u->reserve, description);
+}
+
+static int reserve_init(struct userdata *u, const char *dname) {
+ char *rname;
+
+ pa_assert(u);
+ pa_assert(dname);
+
+ if (u->reserve)
+ return 0;
+
+ if (pa_in_system_mode())
+ return 0;
+
+ if (!(rname = pa_alsa_get_reserve_name(dname)))
+ return 0;
+
+ /* We are resuming, try to lock the device */
+ u->reserve = pa_reserve_wrapper_get(u->core, rname);
+ pa_xfree(rname);
+
+ if (!(u->reserve))
+ return -1;
+
+ reserve_update(u);
+
+ pa_assert(!u->reserve_slot);
+ u->reserve_slot = pa_hook_connect(pa_reserve_wrapper_hook(u->reserve), PA_HOOK_NORMAL, (pa_hook_cb_t) reserve_cb, u);
+
+ return 0;
+}
+
+static pa_hook_result_t monitor_cb(pa_reserve_monitor_wrapper *w, void* busy, struct userdata *u) {
+ pa_assert(w);
+ pa_assert(u);
+
+ if (PA_PTR_TO_UINT(busy) && !u->reserve) {
+ pa_log_debug("Suspending source %s, because another application is blocking the access to the device.", u->source->name);
+ pa_source_suspend(u->source, true, PA_SUSPEND_APPLICATION);
+ } else {
+ pa_log_debug("Resuming source %s, because other applications aren't blocking access to the device any more.", u->source->name);
+ pa_source_suspend(u->source, false, PA_SUSPEND_APPLICATION);
+ }
+
+ return PA_HOOK_OK;
+}
+
+static void monitor_done(struct userdata *u) {
+ pa_assert(u);
+
+ if (u->monitor_slot) {
+ pa_hook_slot_free(u->monitor_slot);
+ u->monitor_slot = NULL;
+ }
+
+ if (u->monitor) {
+ pa_reserve_monitor_wrapper_unref(u->monitor);
+ u->monitor = NULL;
+ }
+}
+
+static int reserve_monitor_init(struct userdata *u, const char *dname) {
+ char *rname;
+
+ pa_assert(u);
+ pa_assert(dname);
+
+ if (pa_in_system_mode())
+ return 0;
+
+ if (!(rname = pa_alsa_get_reserve_name(dname)))
+ return 0;
+
+ /* We are resuming, try to lock the device */
+ u->monitor = pa_reserve_monitor_wrapper_get(u->core, rname);
+ pa_xfree(rname);
+
+ if (!(u->monitor))
+ return -1;
+
+ pa_assert(!u->monitor_slot);
+ u->monitor_slot = pa_hook_connect(pa_reserve_monitor_wrapper_hook(u->monitor), PA_HOOK_NORMAL, (pa_hook_cb_t) monitor_cb, u);
+
+ return 0;
+}
+
+static void fix_min_sleep_wakeup(struct userdata *u) {
+ size_t max_use, max_use_2;
+
+ pa_assert(u);
+ pa_assert(u->use_tsched);
+
+ max_use = u->hwbuf_size - u->hwbuf_unused;
+ max_use_2 = pa_frame_align(max_use/2, &u->source->sample_spec);
+
+ u->min_sleep = pa_usec_to_bytes(TSCHED_MIN_SLEEP_USEC, &u->source->sample_spec);
+ u->min_sleep = PA_CLAMP(u->min_sleep, u->frame_size, max_use_2);
+
+ u->min_wakeup = pa_usec_to_bytes(TSCHED_MIN_WAKEUP_USEC, &u->source->sample_spec);
+ u->min_wakeup = PA_CLAMP(u->min_wakeup, u->frame_size, max_use_2);
+}
+
+static void fix_tsched_watermark(struct userdata *u) {
+ size_t max_use;
+ pa_assert(u);
+ pa_assert(u->use_tsched);
+
+ max_use = u->hwbuf_size - u->hwbuf_unused;
+
+ if (u->tsched_watermark > max_use - u->min_sleep)
+ u->tsched_watermark = max_use - u->min_sleep;
+
+ if (u->tsched_watermark < u->min_wakeup)
+ u->tsched_watermark = u->min_wakeup;
+
+ u->tsched_watermark_usec = pa_bytes_to_usec(u->tsched_watermark, &u->source->sample_spec);
+}
+
+static void increase_watermark(struct userdata *u) {
+ size_t old_watermark;
+ pa_usec_t old_min_latency, new_min_latency;
+
+ pa_assert(u);
+ pa_assert(u->use_tsched);
+
+ /* First, just try to increase the watermark */
+ old_watermark = u->tsched_watermark;
+ u->tsched_watermark = PA_MIN(u->tsched_watermark * 2, u->tsched_watermark + u->watermark_inc_step);
+ fix_tsched_watermark(u);
+
+ if (old_watermark != u->tsched_watermark) {
+ pa_log_info("Increasing wakeup watermark to %0.2f ms",
+ (double) u->tsched_watermark_usec / PA_USEC_PER_MSEC);
+ return;
+ }
+
+ /* Hmm, we cannot increase the watermark any further, hence let's
+ raise the latency unless doing so was disabled in
+ configuration */
+ if (u->fixed_latency_range)
+ return;
+
+ old_min_latency = u->source->thread_info.min_latency;
+ new_min_latency = PA_MIN(old_min_latency * 2, old_min_latency + TSCHED_WATERMARK_INC_STEP_USEC);
+ new_min_latency = PA_MIN(new_min_latency, u->source->thread_info.max_latency);
+
+ if (old_min_latency != new_min_latency) {
+ pa_log_info("Increasing minimal latency to %0.2f ms",
+ (double) new_min_latency / PA_USEC_PER_MSEC);
+
+ pa_source_set_latency_range_within_thread(u->source, new_min_latency, u->source->thread_info.max_latency);
+ }
+
+ /* When we reach this we're officially fucked! */
+}
+
+static void decrease_watermark(struct userdata *u) {
+ size_t old_watermark;
+ pa_usec_t now;
+
+ pa_assert(u);
+ pa_assert(u->use_tsched);
+
+ now = pa_rtclock_now();
+
+ if (u->watermark_dec_not_before <= 0)
+ goto restart;
+
+ if (u->watermark_dec_not_before > now)
+ return;
+
+ old_watermark = u->tsched_watermark;
+
+ if (u->tsched_watermark < u->watermark_dec_step)
+ u->tsched_watermark = u->tsched_watermark / 2;
+ else
+ u->tsched_watermark = PA_MAX(u->tsched_watermark / 2, u->tsched_watermark - u->watermark_dec_step);
+
+ fix_tsched_watermark(u);
+
+ if (old_watermark != u->tsched_watermark)
+ pa_log_info("Decreasing wakeup watermark to %0.2f ms",
+ (double) u->tsched_watermark_usec / PA_USEC_PER_MSEC);
+
+ /* We don't change the latency range*/
+
+restart:
+ u->watermark_dec_not_before = now + TSCHED_WATERMARK_VERIFY_AFTER_USEC;
+}
+
+/* Called from IO Context on unsuspend or from main thread when creating source */
+static void reset_watermark(struct userdata *u, size_t tsched_watermark, pa_sample_spec *ss,
+ bool in_thread) {
+ u->tsched_watermark = pa_convert_size(tsched_watermark, ss, &u->source->sample_spec);
+
+ u->watermark_inc_step = pa_usec_to_bytes(TSCHED_WATERMARK_INC_STEP_USEC, &u->source->sample_spec);
+ u->watermark_dec_step = pa_usec_to_bytes(TSCHED_WATERMARK_DEC_STEP_USEC, &u->source->sample_spec);
+
+ u->watermark_inc_threshold = pa_usec_to_bytes_round_up(TSCHED_WATERMARK_INC_THRESHOLD_USEC, &u->source->sample_spec);
+ u->watermark_dec_threshold = pa_usec_to_bytes_round_up(TSCHED_WATERMARK_DEC_THRESHOLD_USEC, &u->source->sample_spec);
+
+ fix_min_sleep_wakeup(u);
+ fix_tsched_watermark(u);
+
+ if (in_thread)
+ pa_source_set_latency_range_within_thread(u->source,
+ u->min_latency_ref,
+ pa_bytes_to_usec(u->hwbuf_size, ss));
+ else {
+ pa_source_set_latency_range(u->source,
+ 0,
+ pa_bytes_to_usec(u->hwbuf_size, ss));
+
+ /* work-around assert in pa_source_set_latency_within_thead,
+ keep track of min_latency and reuse it when
+ this routine is called from IO context */
+ u->min_latency_ref = u->source->thread_info.min_latency;
+ }
+
+ pa_log_info("Time scheduling watermark is %0.2fms",
+ (double) u->tsched_watermark_usec / PA_USEC_PER_MSEC);
+}
+
+static void hw_sleep_time(struct userdata *u, pa_usec_t *sleep_usec, pa_usec_t*process_usec) {
+ pa_usec_t wm, usec;
+
+ pa_assert(sleep_usec);
+ pa_assert(process_usec);
+
+ pa_assert(u);
+ pa_assert(u->use_tsched);
+
+ usec = pa_source_get_requested_latency_within_thread(u->source);
+
+ if (usec == (pa_usec_t) -1)
+ usec = pa_bytes_to_usec(u->hwbuf_size, &u->source->sample_spec);
+
+ wm = u->tsched_watermark_usec;
+
+ if (wm > usec)
+ wm = usec/2;
+
+ *sleep_usec = usec - wm;
+ *process_usec = wm;
+
+#ifdef DEBUG_TIMING
+ pa_log_debug("Buffer time: %lu ms; Sleep time: %lu ms; Process time: %lu ms",
+ (unsigned long) (usec / PA_USEC_PER_MSEC),
+ (unsigned long) (*sleep_usec / PA_USEC_PER_MSEC),
+ (unsigned long) (*process_usec / PA_USEC_PER_MSEC));
+#endif
+}
+
+/* Reset smoother and counters */
+static void reset_vars(struct userdata *u) {
+
+ pa_smoother_reset(u->smoother, pa_rtclock_now(), true);
+ u->smoother_interval = SMOOTHER_MIN_INTERVAL;
+ u->last_smoother_update = 0;
+
+ u->read_count = 0;
+ u->first = true;
+}
+
+/* Called from IO context */
+static void close_pcm(struct userdata *u) {
+ pa_smoother_pause(u->smoother, pa_rtclock_now());
+
+ /* Let's suspend */
+ snd_pcm_close(u->pcm_handle);
+ u->pcm_handle = NULL;
+
+ if (u->alsa_rtpoll_item) {
+ pa_rtpoll_item_free(u->alsa_rtpoll_item);
+ u->alsa_rtpoll_item = NULL;
+ }
+}
+
+static int try_recover(struct userdata *u, const char *call, int err) {
+ pa_assert(u);
+ pa_assert(call);
+ pa_assert(err < 0);
+
+ pa_log_debug("%s: %s", call, pa_alsa_strerror(err));
+
+ pa_assert(err != -EAGAIN);
+
+ if (err == -EPIPE)
+ pa_log_debug("%s: Buffer overrun!", call);
+
+ if (err == -ESTRPIPE)
+ pa_log_debug("%s: System suspended!", call);
+
+ if ((err = snd_pcm_recover(u->pcm_handle, err, 1)) < 0) {
+ pa_log("%s: %s, trying to restart PCM", call, pa_alsa_strerror(err));
+
+ /* As a last measure, restart the PCM and inform the caller about it. */
+ close_pcm(u);
+ if (unsuspend(u, true) < 0)
+ return -1;
+
+ return 1;
+ }
+
+ reset_vars(u);
+ return 0;
+}
+
+static size_t check_left_to_record(struct userdata *u, size_t n_bytes, bool on_timeout) {
+ size_t left_to_record;
+ size_t rec_space = u->hwbuf_size - u->hwbuf_unused;
+ bool overrun = false;
+
+ /* We use <= instead of < for this check here because an overrun
+ * only happens after the last sample was processed, not already when
+ * it is removed from the buffer. This is particularly important
+ * when block transfer is used. */
+
+ if (n_bytes <= rec_space)
+ left_to_record = rec_space - n_bytes;
+ else {
+
+ /* We got a dropout. What a mess! */
+ left_to_record = 0;
+ overrun = true;
+
+#ifdef DEBUG_TIMING
+ PA_DEBUG_TRAP;
+#endif
+
+ if (pa_log_ratelimit(PA_LOG_INFO))
+ pa_log_info("Overrun!");
+ }
+
+#ifdef DEBUG_TIMING
+ pa_log_debug("%0.2f ms left to record", (double) pa_bytes_to_usec(left_to_record, &u->source->sample_spec) / PA_USEC_PER_MSEC);
+#endif
+
+ if (u->use_tsched) {
+ bool reset_not_before = true;
+
+ if (overrun || left_to_record < u->watermark_inc_threshold)
+ increase_watermark(u);
+ else if (left_to_record > u->watermark_dec_threshold) {
+ reset_not_before = false;
+
+ /* We decrease the watermark only if have actually
+ * been woken up by a timeout. If something else woke
+ * us up it's too easy to fulfill the deadlines... */
+
+ if (on_timeout)
+ decrease_watermark(u);
+ }
+
+ if (reset_not_before)
+ u->watermark_dec_not_before = 0;
+ }
+
+ return left_to_record;
+}
+
+static int mmap_read(struct userdata *u, pa_usec_t *sleep_usec, bool polled, bool on_timeout) {
+ bool work_done = false;
+ bool recovery_done = false;
+ pa_usec_t max_sleep_usec = 0, process_usec = 0;
+ size_t left_to_record;
+ unsigned j = 0;
+
+ pa_assert(u);
+ pa_source_assert_ref(u->source);
+
+ if (u->use_tsched)
+ hw_sleep_time(u, &max_sleep_usec, &process_usec);
+
+ for (;;) {
+ snd_pcm_sframes_t n;
+ size_t n_bytes;
+ int r;
+ bool after_avail = true;
+
+ if (PA_UNLIKELY((n = pa_alsa_safe_avail(u->pcm_handle, u->hwbuf_size, &u->source->sample_spec)) < 0)) {
+
+ recovery_done = true;
+ if ((r = try_recover(u, "snd_pcm_avail", (int) n)) >= 0)
+ continue;
+
+ return r;
+ }
+
+ n_bytes = (size_t) n * u->frame_size;
+
+#ifdef DEBUG_TIMING
+ pa_log_debug("avail: %lu", (unsigned long) n_bytes);
+#endif
+
+ left_to_record = check_left_to_record(u, n_bytes, on_timeout);
+ on_timeout = false;
+
+ if (u->use_tsched)
+ if (!polled &&
+ pa_bytes_to_usec(left_to_record, &u->source->sample_spec) > process_usec+max_sleep_usec/2) {
+#ifdef DEBUG_TIMING
+ pa_log_debug("Not reading, because too early.");
+#endif
+ break;
+ }
+
+ if (PA_UNLIKELY(n_bytes <= 0)) {
+
+ if (polled)
+ PA_ONCE_BEGIN {
+ char *dn = pa_alsa_get_driver_name_by_pcm(u->pcm_handle);
+ pa_log(_("ALSA woke us up to read new data from the device, but there was actually nothing to read.\n"
+ "Most likely this is a bug in the ALSA driver '%s'. Please report this issue to the ALSA developers.\n"
+ "We were woken up with POLLIN set -- however a subsequent snd_pcm_avail() returned 0 or another value < min_avail."),
+ pa_strnull(dn));
+ pa_xfree(dn);
+ } PA_ONCE_END;
+
+#ifdef DEBUG_TIMING
+ pa_log_debug("Not reading, because not necessary.");
+#endif
+ break;
+ }
+
+ if (++j > 10) {
+#ifdef DEBUG_TIMING
+ pa_log_debug("Not filling up, because already too many iterations.");
+#endif
+
+ break;
+ }
+
+ polled = false;
+
+#ifdef DEBUG_TIMING
+ pa_log_debug("Reading");
+#endif
+
+ for (;;) {
+ pa_memchunk chunk;
+ void *p;
+ int err;
+ const snd_pcm_channel_area_t *areas;
+ snd_pcm_uframes_t offset, frames;
+ snd_pcm_sframes_t sframes;
+
+ frames = (snd_pcm_uframes_t) (n_bytes / u->frame_size);
+/* pa_log_debug("%lu frames to read", (unsigned long) frames); */
+
+ if (PA_UNLIKELY((err = pa_alsa_safe_mmap_begin(u->pcm_handle, &areas, &offset, &frames, u->hwbuf_size, &u->source->sample_spec)) < 0)) {
+
+ if (!after_avail && err == -EAGAIN)
+ break;
+
+ recovery_done = true;
+ if ((r = try_recover(u, "snd_pcm_mmap_begin", err)) == 0)
+ continue;
+
+ if (r == 1)
+ break;
+
+ return r;
+ }
+
+ /* Make sure that if these memblocks need to be copied they will fit into one slot */
+ frames = PA_MIN(frames, u->frames_per_block);
+
+ if (!after_avail && frames == 0)
+ break;
+
+ pa_assert(frames > 0);
+ after_avail = false;
+
+ /* Check these are multiples of 8 bit */
+ pa_assert((areas[0].first & 7) == 0);
+ pa_assert((areas[0].step & 7) == 0);
+
+ /* We assume a single interleaved memory buffer */
+ pa_assert((areas[0].first >> 3) == 0);
+ pa_assert((areas[0].step >> 3) == u->frame_size);
+
+ p = (uint8_t*) areas[0].addr + (offset * u->frame_size);
+
+ chunk.memblock = pa_memblock_new_fixed(u->core->mempool, p, frames * u->frame_size, true);
+ chunk.length = pa_memblock_get_length(chunk.memblock);
+ chunk.index = 0;
+
+ pa_source_post(u->source, &chunk);
+ pa_memblock_unref_fixed(chunk.memblock);
+
+ if (PA_UNLIKELY((sframes = snd_pcm_mmap_commit(u->pcm_handle, offset, frames)) < 0)) {
+
+ recovery_done = true;
+ if ((r = try_recover(u, "snd_pcm_mmap_commit", (int) sframes)) == 0)
+ continue;
+
+ if (r == 1)
+ break;
+
+ return r;
+ }
+
+ work_done = true;
+
+ u->read_count += frames * u->frame_size;
+
+#ifdef DEBUG_TIMING
+ pa_log_debug("Read %lu bytes (of possible %lu bytes)", (unsigned long) (frames * u->frame_size), (unsigned long) n_bytes);
+#endif
+
+ if ((size_t) frames * u->frame_size >= n_bytes)
+ break;
+
+ n_bytes -= (size_t) frames * u->frame_size;
+ }
+ }
+
+ if (u->use_tsched) {
+ *sleep_usec = pa_bytes_to_usec(left_to_record, &u->source->sample_spec);
+ process_usec = u->tsched_watermark_usec;
+
+ if (*sleep_usec > process_usec)
+ *sleep_usec -= process_usec;
+ else
+ *sleep_usec = 0;
+
+ /* If the PCM was recovered, it may need restarting. Reduce the sleep time
+ * to 0 to ensure immediate restart. */
+ if (recovery_done)
+ *sleep_usec = 0;
+ }
+
+ return work_done ? 1 : 0;
+}
+
+static int unix_read(struct userdata *u, pa_usec_t *sleep_usec, bool polled, bool on_timeout) {
+ int work_done = false;
+ bool recovery_done = false;
+ pa_usec_t max_sleep_usec = 0, process_usec = 0;
+ size_t left_to_record;
+ unsigned j = 0;
+
+ pa_assert(u);
+ pa_source_assert_ref(u->source);
+
+ if (u->use_tsched)
+ hw_sleep_time(u, &max_sleep_usec, &process_usec);
+
+ for (;;) {
+ snd_pcm_sframes_t n;
+ size_t n_bytes;
+ int r;
+ bool after_avail = true;
+
+ if (PA_UNLIKELY((n = pa_alsa_safe_avail(u->pcm_handle, u->hwbuf_size, &u->source->sample_spec)) < 0)) {
+
+ recovery_done = true;
+ if ((r = try_recover(u, "snd_pcm_avail", (int) n)) >= 0)
+ continue;
+
+ return r;
+ }
+
+ n_bytes = (size_t) n * u->frame_size;
+ left_to_record = check_left_to_record(u, n_bytes, on_timeout);
+ on_timeout = false;
+
+ if (u->use_tsched)
+ if (!polled &&
+ pa_bytes_to_usec(left_to_record, &u->source->sample_spec) > process_usec+max_sleep_usec/2)
+ break;
+
+ if (PA_UNLIKELY(n_bytes <= 0)) {
+
+ if (polled)
+ PA_ONCE_BEGIN {
+ char *dn = pa_alsa_get_driver_name_by_pcm(u->pcm_handle);
+ pa_log(_("ALSA woke us up to read new data from the device, but there was actually nothing to read.\n"
+ "Most likely this is a bug in the ALSA driver '%s'. Please report this issue to the ALSA developers.\n"
+ "We were woken up with POLLIN set -- however a subsequent snd_pcm_avail() returned 0 or another value < min_avail."),
+ pa_strnull(dn));
+ pa_xfree(dn);
+ } PA_ONCE_END;
+
+ break;
+ }
+
+ if (++j > 10) {
+#ifdef DEBUG_TIMING
+ pa_log_debug("Not filling up, because already too many iterations.");
+#endif
+
+ break;
+ }
+
+ polled = false;
+
+ for (;;) {
+ void *p;
+ snd_pcm_sframes_t frames;
+ pa_memchunk chunk;
+
+ chunk.memblock = pa_memblock_new(u->core->mempool, (size_t) -1);
+
+ frames = (snd_pcm_sframes_t) (pa_memblock_get_length(chunk.memblock) / u->frame_size);
+
+ if (frames > (snd_pcm_sframes_t) (n_bytes/u->frame_size))
+ frames = (snd_pcm_sframes_t) (n_bytes/u->frame_size);
+
+/* pa_log_debug("%lu frames to read", (unsigned long) n); */
+
+ p = pa_memblock_acquire(chunk.memblock);
+ frames = snd_pcm_readi(u->pcm_handle, (uint8_t*) p, (snd_pcm_uframes_t) frames);
+ pa_memblock_release(chunk.memblock);
+
+ if (PA_UNLIKELY(frames < 0)) {
+ pa_memblock_unref(chunk.memblock);
+
+ if (!after_avail && (int) frames == -EAGAIN)
+ break;
+
+ recovery_done = true;
+ if ((r = try_recover(u, "snd_pcm_readi", (int) frames)) == 0)
+ continue;
+
+ if (r == 1)
+ break;
+
+ return r;
+ }
+
+ if (!after_avail && frames == 0) {
+ pa_memblock_unref(chunk.memblock);
+ break;
+ }
+
+ pa_assert(frames > 0);
+ after_avail = false;
+
+ chunk.index = 0;
+ chunk.length = (size_t) frames * u->frame_size;
+
+ pa_source_post(u->source, &chunk);
+ pa_memblock_unref(chunk.memblock);
+
+ work_done = true;
+
+ u->read_count += frames * u->frame_size;
+
+/* pa_log_debug("read %lu frames", (unsigned long) frames); */
+
+ if ((size_t) frames * u->frame_size >= n_bytes)
+ break;
+
+ n_bytes -= (size_t) frames * u->frame_size;
+ }
+ }
+
+ if (u->use_tsched) {
+ *sleep_usec = pa_bytes_to_usec(left_to_record, &u->source->sample_spec);
+ process_usec = u->tsched_watermark_usec;
+
+ if (*sleep_usec > process_usec)
+ *sleep_usec -= process_usec;
+ else
+ *sleep_usec = 0;
+
+ /* If the PCM was recovered, it may need restarting. Reduce the sleep time
+ * to 0 to ensure immediate restart. */
+ if (recovery_done)
+ *sleep_usec = 0;
+ }
+
+ return work_done ? 1 : 0;
+}
+
+static void update_smoother(struct userdata *u) {
+ snd_pcm_sframes_t delay = 0;
+ uint64_t position;
+ int err;
+ pa_usec_t now1 = 0, now2;
+ snd_pcm_status_t *status;
+ snd_htimestamp_t htstamp = { 0, 0 };
+
+ snd_pcm_status_alloca(&status);
+
+ pa_assert(u);
+ pa_assert(u->pcm_handle);
+
+ /* Let's update the time smoother */
+
+ if (PA_UNLIKELY((err = pa_alsa_safe_delay(u->pcm_handle, status, &delay, u->hwbuf_size, &u->source->sample_spec, true)) < 0)) {
+ pa_log_warn("Failed to get delay: %s", pa_alsa_strerror(err));
+ return;
+ }
+
+ snd_pcm_status_get_htstamp(status, &htstamp);
+ now1 = pa_timespec_load(&htstamp);
+
+ /* Hmm, if the timestamp is 0, then it wasn't set and we take the current time */
+ if (now1 <= 0)
+ now1 = pa_rtclock_now();
+
+ /* check if the time since the last update is bigger than the interval */
+ if (u->last_smoother_update > 0)
+ if (u->last_smoother_update + u->smoother_interval > now1)
+ return;
+
+ position = u->read_count + ((uint64_t) delay * (uint64_t) u->frame_size);
+ now2 = pa_bytes_to_usec(position, &u->source->sample_spec);
+
+ pa_smoother_put(u->smoother, now1, now2);
+
+ u->last_smoother_update = now1;
+ /* exponentially increase the update interval up to the MAX limit */
+ u->smoother_interval = PA_MIN (u->smoother_interval * 2, SMOOTHER_MAX_INTERVAL);
+}
+
+static int64_t source_get_latency(struct userdata *u) {
+ int64_t delay;
+ pa_usec_t now1, now2;
+
+ pa_assert(u);
+
+ now1 = pa_rtclock_now();
+ now2 = pa_smoother_get(u->smoother, now1);
+
+ delay = (int64_t) now2 - (int64_t) pa_bytes_to_usec(u->read_count, &u->source->sample_spec);
+
+ return delay;
+}
+
+static int build_pollfd(struct userdata *u) {
+ pa_assert(u);
+ pa_assert(u->pcm_handle);
+
+ if (u->alsa_rtpoll_item)
+ pa_rtpoll_item_free(u->alsa_rtpoll_item);
+
+ if (!(u->alsa_rtpoll_item = pa_alsa_build_pollfd(u->pcm_handle, u->rtpoll)))
+ return -1;
+
+ return 0;
+}
+
+/* Called from IO context */
+static void suspend(struct userdata *u) {
+ pa_assert(u);
+
+ /* PCM may have been invalidated due to device failure.
+ * In that case, there is nothing to do. */
+ if (!u->pcm_handle)
+ return;
+
+ /* Close PCM device */
+ close_pcm(u);
+
+ pa_log_info("Device suspended...");
+}
+
+/* Called from IO context */
+static int update_sw_params(struct userdata *u) {
+ snd_pcm_uframes_t avail_min;
+ int err;
+
+ pa_assert(u);
+
+ /* Use the full buffer if no one asked us for anything specific */
+ u->hwbuf_unused = 0;
+
+ if (u->use_tsched) {
+ pa_usec_t latency;
+
+ if ((latency = pa_source_get_requested_latency_within_thread(u->source)) != (pa_usec_t) -1) {
+ size_t b;
+
+ pa_log_debug("latency set to %0.2fms", (double) latency / PA_USEC_PER_MSEC);
+
+ b = pa_usec_to_bytes(latency, &u->source->sample_spec);
+
+ /* We need at least one sample in our buffer */
+
+ if (PA_UNLIKELY(b < u->frame_size))
+ b = u->frame_size;
+
+ u->hwbuf_unused = PA_LIKELY(b < u->hwbuf_size) ? (u->hwbuf_size - b) : 0;
+ }
+
+ fix_min_sleep_wakeup(u);
+ fix_tsched_watermark(u);
+ }
+
+ pa_log_debug("hwbuf_unused=%lu", (unsigned long) u->hwbuf_unused);
+
+ avail_min = 1;
+
+ if (u->use_tsched) {
+ pa_usec_t sleep_usec, process_usec;
+
+ hw_sleep_time(u, &sleep_usec, &process_usec);
+ avail_min += pa_usec_to_bytes(sleep_usec, &u->source->sample_spec) / u->frame_size;
+ }
+
+ pa_log_debug("setting avail_min=%lu", (unsigned long) avail_min);
+
+ if ((err = pa_alsa_set_sw_params(u->pcm_handle, avail_min, !u->use_tsched)) < 0) {
+ pa_log("Failed to set software parameters: %s", pa_alsa_strerror(err));
+ return err;
+ }
+
+ return 0;
+}
+
+/* Called from IO Context on unsuspend */
+static void update_size(struct userdata *u, pa_sample_spec *ss) {
+ pa_assert(u);
+ pa_assert(ss);
+
+ u->frame_size = pa_frame_size(ss);
+ u->frames_per_block = pa_mempool_block_size_max(u->core->mempool) / u->frame_size;
+
+ /* use initial values including module arguments */
+ u->fragment_size = u->initial_info.fragment_size;
+ u->hwbuf_size = u->initial_info.nfrags * u->fragment_size;
+ u->tsched_size = u->initial_info.tsched_size;
+ u->tsched_watermark = u->initial_info.tsched_watermark;
+
+ u->tsched_watermark_ref = u->tsched_watermark;
+
+ pa_log_info("Updated frame_size %zu, frames_per_block %lu, fragment_size %zu, hwbuf_size %zu, tsched(size %zu, watermark %zu)",
+ u->frame_size, (unsigned long) u->frames_per_block, u->fragment_size, u->hwbuf_size, u->tsched_size, u->tsched_watermark);
+}
+
+/* Called from IO context */
+static int unsuspend(struct userdata *u, bool recovering) {
+ pa_sample_spec ss;
+ int err, i;
+ bool b, d;
+ snd_pcm_uframes_t period_frames, buffer_frames;
+ snd_pcm_uframes_t tsched_frames = 0;
+ bool frame_size_changed = false;
+
+ pa_assert(u);
+ pa_assert(!u->pcm_handle);
+
+ pa_log_info("Trying resume...");
+
+ /*
+ * On some machines, during the system suspend and resume, the thread_func could receive
+ * POLLERR events before the dev nodes in /dev/snd/ are accessible, and thread_func calls
+ * the unsuspend() to try to recover the PCM, this will make the snd_pcm_open() fail, here
+ * we add msleep and retry to make sure those nodes are accessible.
+ */
+ for (i = 0; i < 4; i++) {
+ if ((err = snd_pcm_open(&u->pcm_handle, u->device_name, SND_PCM_STREAM_CAPTURE,
+ SND_PCM_NONBLOCK|
+ SND_PCM_NO_AUTO_RESAMPLE|
+ SND_PCM_NO_AUTO_CHANNELS|
+ SND_PCM_NO_AUTO_FORMAT)) < 0 && recovering)
+ pa_msleep(25);
+ else
+ break;
+ }
+
+ if (err < 0) {
+ pa_log("Error opening PCM device %s: %s", u->device_name, pa_alsa_strerror(err));
+ goto fail;
+ }
+
+ if (pa_frame_size(&u->source->sample_spec) != u->frame_size) {
+ update_size(u, &u->source->sample_spec);
+ tsched_frames = u->tsched_size / u->frame_size;
+ frame_size_changed = true;
+ }
+
+ ss = u->source->sample_spec;
+ period_frames = u->fragment_size / u->frame_size;
+ buffer_frames = u->hwbuf_size / u->frame_size;
+ b = u->use_mmap;
+ d = u->use_tsched;
+
+ if ((err = pa_alsa_set_hw_params(u->pcm_handle, &ss, &period_frames, &buffer_frames, tsched_frames, &b, &d, true)) < 0) {
+ pa_log("Failed to set hardware parameters: %s", pa_alsa_strerror(err));
+ goto fail;
+ }
+
+ if (b != u->use_mmap || d != u->use_tsched) {
+ pa_log_warn("Resume failed, couldn't get original access mode.");
+ goto fail;
+ }
+
+ if (!pa_sample_spec_equal(&ss, &u->source->sample_spec)) {
+ pa_log_warn("Resume failed, couldn't restore original sample settings.");
+ goto fail;
+ }
+
+ if (frame_size_changed) {
+ u->fragment_size = (size_t)(period_frames * u->frame_size);
+ u->hwbuf_size = (size_t)(buffer_frames * u->frame_size);
+ pa_proplist_setf(u->source->proplist, PA_PROP_DEVICE_BUFFERING_BUFFER_SIZE, "%zu", u->hwbuf_size);
+ pa_proplist_setf(u->source->proplist, PA_PROP_DEVICE_BUFFERING_FRAGMENT_SIZE, "%zu", u->fragment_size);
+
+ } else if (period_frames * u->frame_size != u->fragment_size ||
+ buffer_frames * u->frame_size != u->hwbuf_size) {
+ pa_log_warn("Resume failed, couldn't restore original fragment settings. (Old: %zu/%zu, New %lu/%lu)",
+ u->hwbuf_size, u->fragment_size,
+ (unsigned long) buffer_frames * u->frame_size, (unsigned long) period_frames * u->frame_size);
+ goto fail;
+ }
+
+ if (update_sw_params(u) < 0)
+ goto fail;
+
+ if (build_pollfd(u) < 0)
+ goto fail;
+
+ /* FIXME: We need to reload the volume somehow */
+
+ reset_vars(u);
+
+ /* reset the watermark to the value defined when source was created */
+ if (u->use_tsched && !recovering)
+ reset_watermark(u, u->tsched_watermark_ref, &u->source->sample_spec, true);
+
+ pa_log_info("Resumed successfully...");
+
+ return 0;
+
+fail:
+ if (u->pcm_handle) {
+ snd_pcm_close(u->pcm_handle);
+ u->pcm_handle = NULL;
+ }
+
+ return -PA_ERR_IO;
+}
+
+/* Called from the IO thread or the main thread depending on whether deferred
+ * volume is enabled or not (with deferred volume all mixer handling is done
+ * from the IO thread).
+ *
+ * Sets the mixer settings to match the current source and port state (the port
+ * is given as an argument, because active_port may still point to the old
+ * port, if we're switching ports). */
+static void sync_mixer(struct userdata *u, pa_device_port *port) {
+ pa_alsa_setting *setting = NULL;
+
+ pa_assert(u);
+
+ if (!u->mixer_path)
+ return;
+
+ /* port may be NULL, because if we use a synthesized mixer path, then the
+ * source has no ports. */
+ if (port && !u->ucm_context) {
+ pa_alsa_port_data *data;
+
+ data = PA_DEVICE_PORT_DATA(port);
+ setting = data->setting;
+ }
+
+ pa_alsa_path_select(u->mixer_path, setting, u->mixer_handle, u->source->muted);
+
+ if (u->source->set_mute)
+ u->source->set_mute(u->source);
+ if (u->source->flags & PA_SOURCE_DEFERRED_VOLUME) {
+ if (u->source->write_volume)
+ u->source->write_volume(u->source);
+ } else {
+ if (u->source->set_volume)
+ u->source->set_volume(u->source);
+ }
+}
+
+/* Called from IO context */
+static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
+ struct userdata *u = PA_SOURCE(o)->userdata;
+
+ switch (code) {
+
+ case PA_SOURCE_MESSAGE_GET_LATENCY: {
+ int64_t r = 0;
+
+ if (u->pcm_handle)
+ r = source_get_latency(u);
+
+ *((int64_t*) data) = r;
+
+ return 0;
+ }
+
+ case SOURCE_MESSAGE_SYNC_MIXER: {
+ pa_device_port *port = data;
+
+ sync_mixer(u, port);
+ return 0;
+ }
+ }
+
+ return pa_source_process_msg(o, code, data, offset, chunk);
+}
+
+/* Called from main context */
+static int source_set_state_in_main_thread_cb(pa_source *s, pa_source_state_t new_state, pa_suspend_cause_t new_suspend_cause) {
+ pa_source_state_t old_state;
+ struct userdata *u;
+
+ pa_source_assert_ref(s);
+ pa_assert_se(u = s->userdata);
+
+ /* When our session becomes active, we need to sync the mixer, because
+ * another user may have changed the mixer settings.
+ *
+ * If deferred volume is enabled, the syncing is done in the
+ * set_state_in_io_thread() callback instead. */
+ if (!(s->flags & PA_SOURCE_DEFERRED_VOLUME)
+ && (s->suspend_cause & PA_SUSPEND_SESSION)
+ && !(new_suspend_cause & PA_SUSPEND_SESSION))
+ sync_mixer(u, s->active_port);
+
+ old_state = u->source->state;
+
+ if (PA_SOURCE_IS_OPENED(old_state) && new_state == PA_SOURCE_SUSPENDED)
+ reserve_done(u);
+ else if (old_state == PA_SOURCE_SUSPENDED && PA_SOURCE_IS_OPENED(new_state))
+ if (reserve_init(u, u->device_name) < 0)
+ return -PA_ERR_BUSY;
+
+ return 0;
+}
+
+/* Called from the IO thread. */
+static int source_set_state_in_io_thread_cb(pa_source *s, pa_source_state_t new_state, pa_suspend_cause_t new_suspend_cause) {
+ struct userdata *u;
+
+ pa_assert(s);
+ pa_assert_se(u = s->userdata);
+
+ /* When our session becomes active, we need to sync the mixer, because
+ * another user may have changed the mixer settings.
+ *
+ * If deferred volume is disabled, the syncing is done in the
+ * set_state_in_main_thread() callback instead. */
+ if ((s->flags & PA_SOURCE_DEFERRED_VOLUME)
+ && (s->suspend_cause & PA_SUSPEND_SESSION)
+ && !(new_suspend_cause & PA_SUSPEND_SESSION))
+ sync_mixer(u, s->active_port);
+
+ /* It may be that only the suspend cause is changing, in which case there's
+ * nothing more to do. */
+ if (new_state == s->thread_info.state)
+ return 0;
+
+ switch (new_state) {
+
+ case PA_SOURCE_SUSPENDED: {
+ pa_assert(PA_SOURCE_IS_OPENED(s->thread_info.state));
+
+ suspend(u);
+
+ break;
+ }
+
+ case PA_SOURCE_IDLE:
+ case PA_SOURCE_RUNNING: {
+ int r;
+
+ if (s->thread_info.state == PA_SOURCE_INIT) {
+ if (build_pollfd(u) < 0)
+ /* FIXME: This will cause an assertion failure, because
+ * with the current design pa_source_put() is not allowed
+ * to fail and pa_source_put() has no fallback code that
+ * would start the source suspended if opening the device
+ * fails. */
+ return -PA_ERR_IO;
+ }
+
+ if (s->thread_info.state == PA_SOURCE_SUSPENDED) {
+ if ((r = unsuspend(u, false)) < 0)
+ return r;
+ }
+
+ break;
+ }
+
+ case PA_SOURCE_UNLINKED:
+ case PA_SOURCE_INIT:
+ case PA_SOURCE_INVALID_STATE:
+ ;
+ }
+
+ return 0;
+}
+
+static int ctl_mixer_callback(snd_mixer_elem_t *elem, unsigned int mask) {
+ struct userdata *u = snd_mixer_elem_get_callback_private(elem);
+
+ pa_assert(u);
+ pa_assert(u->mixer_handle);
+
+ if (mask == SND_CTL_EVENT_MASK_REMOVE)
+ return 0;
+
+ if (!PA_SOURCE_IS_LINKED(u->source->state))
+ return 0;
+
+ if (u->source->suspend_cause & PA_SUSPEND_SESSION)
+ return 0;
+
+ if (mask & SND_CTL_EVENT_MASK_VALUE) {
+ pa_source_get_volume(u->source, true);
+ pa_source_get_mute(u->source, true);
+ }
+
+ return 0;
+}
+
+static int io_mixer_callback(snd_mixer_elem_t *elem, unsigned int mask) {
+ struct userdata *u = snd_mixer_elem_get_callback_private(elem);
+
+ pa_assert(u);
+ pa_assert(u->mixer_handle);
+
+ if (mask == SND_CTL_EVENT_MASK_REMOVE)
+ return 0;
+
+ if (u->source->suspend_cause & PA_SUSPEND_SESSION)
+ return 0;
+
+ if (mask & SND_CTL_EVENT_MASK_VALUE)
+ pa_source_update_volume_and_mute(u->source);
+
+ return 0;
+}
+
+static void source_get_volume_cb(pa_source *s) {
+ struct userdata *u = s->userdata;
+ pa_cvolume r;
+ char volume_buf[PA_CVOLUME_SNPRINT_VERBOSE_MAX];
+
+ pa_assert(u);
+ pa_assert(u->mixer_path);
+ pa_assert(u->mixer_handle);
+
+ if (pa_alsa_path_get_volume(u->mixer_path, u->mixer_handle, &s->channel_map, &r) < 0)
+ return;
+
+ /* Shift down by the base volume, so that 0dB becomes maximum volume */
+ pa_sw_cvolume_multiply_scalar(&r, &r, s->base_volume);
+
+ pa_log_debug("Read hardware volume: %s",
+ pa_cvolume_snprint_verbose(volume_buf, sizeof(volume_buf), &r, &s->channel_map, u->mixer_path->has_dB));
+
+ if (pa_cvolume_equal(&u->hardware_volume, &r))
+ return;
+
+ s->real_volume = u->hardware_volume = r;
+
+ /* Hmm, so the hardware volume changed, let's reset our software volume */
+ if (u->mixer_path->has_dB)
+ pa_source_set_soft_volume(s, NULL);
+}
+
+static void source_set_volume_cb(pa_source *s) {
+ struct userdata *u = s->userdata;
+ pa_cvolume r;
+ char volume_buf[PA_CVOLUME_SNPRINT_VERBOSE_MAX];
+ bool deferred_volume = !!(s->flags & PA_SOURCE_DEFERRED_VOLUME);
+
+ pa_assert(u);
+ pa_assert(u->mixer_path);
+ pa_assert(u->mixer_handle);
+
+ /* Shift up by the base volume */
+ pa_sw_cvolume_divide_scalar(&r, &s->real_volume, s->base_volume);
+
+ if (pa_alsa_path_set_volume(u->mixer_path, u->mixer_handle, &s->channel_map, &r, deferred_volume, !deferred_volume) < 0)
+ return;
+
+ /* Shift down by the base volume, so that 0dB becomes maximum volume */
+ pa_sw_cvolume_multiply_scalar(&r, &r, s->base_volume);
+
+ u->hardware_volume = r;
+
+ if (u->mixer_path->has_dB) {
+ pa_cvolume new_soft_volume;
+ bool accurate_enough;
+
+ /* Match exactly what the user requested by software */
+ pa_sw_cvolume_divide(&new_soft_volume, &s->real_volume, &u->hardware_volume);
+
+ /* If the adjustment to do in software is only minimal we
+ * can skip it. That saves us CPU at the expense of a bit of
+ * accuracy */
+ accurate_enough =
+ (pa_cvolume_min(&new_soft_volume) >= (PA_VOLUME_NORM - VOLUME_ACCURACY)) &&
+ (pa_cvolume_max(&new_soft_volume) <= (PA_VOLUME_NORM + VOLUME_ACCURACY));
+
+ pa_log_debug("Requested volume: %s",
+ pa_cvolume_snprint_verbose(volume_buf, sizeof(volume_buf), &s->real_volume, &s->channel_map, true));
+ pa_log_debug("Got hardware volume: %s",
+ pa_cvolume_snprint_verbose(volume_buf, sizeof(volume_buf), &u->hardware_volume, &s->channel_map, true));
+ pa_log_debug("Calculated software volume: %s (accurate-enough=%s)",
+ pa_cvolume_snprint_verbose(volume_buf, sizeof(volume_buf), &new_soft_volume, &s->channel_map, true),
+ pa_yes_no(accurate_enough));
+
+ if (!accurate_enough)
+ s->soft_volume = new_soft_volume;
+
+ } else {
+ pa_log_debug("Wrote hardware volume: %s",
+ pa_cvolume_snprint_verbose(volume_buf, sizeof(volume_buf), &r, &s->channel_map, false));
+
+ /* We can't match exactly what the user requested, hence let's
+ * at least tell the user about it */
+
+ s->real_volume = r;
+ }
+}
+
+static void source_write_volume_cb(pa_source *s) {
+ struct userdata *u = s->userdata;
+ pa_cvolume hw_vol = s->thread_info.current_hw_volume;
+
+ pa_assert(u);
+ pa_assert(u->mixer_path);
+ pa_assert(u->mixer_handle);
+ pa_assert(s->flags & PA_SOURCE_DEFERRED_VOLUME);
+
+ /* Shift up by the base volume */
+ pa_sw_cvolume_divide_scalar(&hw_vol, &hw_vol, s->base_volume);
+
+ if (pa_alsa_path_set_volume(u->mixer_path, u->mixer_handle, &s->channel_map, &hw_vol, true, true) < 0)
+ pa_log_error("Writing HW volume failed");
+ else {
+ pa_cvolume tmp_vol;
+ bool accurate_enough;
+
+ /* Shift down by the base volume, so that 0dB becomes maximum volume */
+ pa_sw_cvolume_multiply_scalar(&hw_vol, &hw_vol, s->base_volume);
+
+ pa_sw_cvolume_divide(&tmp_vol, &hw_vol, &s->thread_info.current_hw_volume);
+ accurate_enough =
+ (pa_cvolume_min(&tmp_vol) >= (PA_VOLUME_NORM - VOLUME_ACCURACY)) &&
+ (pa_cvolume_max(&tmp_vol) <= (PA_VOLUME_NORM + VOLUME_ACCURACY));
+
+ if (!accurate_enough) {
+ char volume_buf[2][PA_CVOLUME_SNPRINT_VERBOSE_MAX];
+
+ pa_log_debug("Written HW volume did not match with the request: %s (request) != %s",
+ pa_cvolume_snprint_verbose(volume_buf[0],
+ sizeof(volume_buf[0]),
+ &s->thread_info.current_hw_volume,
+ &s->channel_map,
+ true),
+ pa_cvolume_snprint_verbose(volume_buf[1], sizeof(volume_buf[1]), &hw_vol, &s->channel_map, true));
+ }
+ }
+}
+
+static int source_get_mute_cb(pa_source *s, bool *mute) {
+ struct userdata *u = s->userdata;
+
+ pa_assert(u);
+ pa_assert(u->mixer_path);
+ pa_assert(u->mixer_handle);
+
+ if (pa_alsa_path_get_mute(u->mixer_path, u->mixer_handle, mute) < 0)
+ return -1;
+
+ return 0;
+}
+
+static void source_set_mute_cb(pa_source *s) {
+ struct userdata *u = s->userdata;
+
+ pa_assert(u);
+ pa_assert(u->mixer_path);
+ pa_assert(u->mixer_handle);
+
+ pa_alsa_path_set_mute(u->mixer_path, u->mixer_handle, s->muted);
+}
+
+static void mixer_volume_init(struct userdata *u) {
+ pa_assert(u);
+
+ if (!u->mixer_path || !u->mixer_path->has_volume) {
+ pa_source_set_write_volume_callback(u->source, NULL);
+ pa_source_set_get_volume_callback(u->source, NULL);
+ pa_source_set_set_volume_callback(u->source, NULL);
+
+ pa_log_info("Driver does not support hardware volume control, falling back to software volume control.");
+ } else {
+ pa_source_set_get_volume_callback(u->source, source_get_volume_cb);
+ pa_source_set_set_volume_callback(u->source, source_set_volume_cb);
+
+ if (u->mixer_path->has_dB && u->deferred_volume) {
+ pa_source_set_write_volume_callback(u->source, source_write_volume_cb);
+ pa_log_info("Successfully enabled deferred volume.");
+ } else
+ pa_source_set_write_volume_callback(u->source, NULL);
+
+ if (u->mixer_path->has_dB) {
+ pa_source_enable_decibel_volume(u->source, true);
+ pa_log_info("Hardware volume ranges from %0.2f dB to %0.2f dB.", u->mixer_path->min_dB, u->mixer_path->max_dB);
+
+ u->source->base_volume = pa_sw_volume_from_dB(-u->mixer_path->max_dB);
+ u->source->n_volume_steps = PA_VOLUME_NORM+1;
+
+ pa_log_info("Fixing base volume to %0.2f dB", pa_sw_volume_to_dB(u->source->base_volume));
+ } else {
+ pa_source_enable_decibel_volume(u->source, false);
+ pa_log_info("Hardware volume ranges from %li to %li.", u->mixer_path->min_volume, u->mixer_path->max_volume);
+
+ u->source->base_volume = PA_VOLUME_NORM;
+ u->source->n_volume_steps = u->mixer_path->max_volume - u->mixer_path->min_volume + 1;
+ }
+
+ pa_log_info("Using hardware volume control. Hardware dB scale %s.", u->mixer_path->has_dB ? "supported" : "not supported");
+ }
+
+ if (!u->mixer_path || !u->mixer_path->has_mute) {
+ pa_source_set_get_mute_callback(u->source, NULL);
+ pa_source_set_set_mute_callback(u->source, NULL);
+ pa_log_info("Driver does not support hardware mute control, falling back to software mute control.");
+ } else {
+ pa_source_set_get_mute_callback(u->source, source_get_mute_cb);
+ pa_source_set_set_mute_callback(u->source, source_set_mute_cb);
+ pa_log_info("Using hardware mute control.");
+ }
+}
+
+static int source_set_port_ucm_cb(pa_source *s, pa_device_port *p) {
+ struct userdata *u = s->userdata;
+ pa_alsa_ucm_port_data *data;
+
+ pa_assert(u);
+ pa_assert(p);
+ pa_assert(u->ucm_context);
+
+ data = PA_DEVICE_PORT_DATA(p);
+ u->mixer_path = data->path;
+ mixer_volume_init(u);
+
+ if (s->flags & PA_SOURCE_DEFERRED_VOLUME)
+ pa_asyncmsgq_send(u->source->asyncmsgq, PA_MSGOBJECT(u->source), SOURCE_MESSAGE_SYNC_MIXER, p, 0, NULL);
+ else
+ sync_mixer(u, p);
+
+ return pa_alsa_ucm_set_port(u->ucm_context, p, false);
+}
+
+static int source_set_port_cb(pa_source *s, pa_device_port *p) {
+ struct userdata *u = s->userdata;
+ pa_alsa_port_data *data;
+
+ pa_assert(u);
+ pa_assert(p);
+ pa_assert(u->mixer_handle);
+ pa_assert(!u->ucm_context);
+
+ data = PA_DEVICE_PORT_DATA(p);
+ pa_assert_se(u->mixer_path = data->path);
+ mixer_volume_init(u);
+
+ if (s->flags & PA_SOURCE_DEFERRED_VOLUME)
+ pa_asyncmsgq_send(u->source->asyncmsgq, PA_MSGOBJECT(u->source), SOURCE_MESSAGE_SYNC_MIXER, p, 0, NULL);
+ else
+ sync_mixer(u, p);
+
+ return 0;
+}
+
+static void source_update_requested_latency_cb(pa_source *s) {
+ struct userdata *u = s->userdata;
+ pa_assert(u);
+ pa_assert(u->use_tsched); /* only when timer scheduling is used
+ * we can dynamically adjust the
+ * latency */
+
+ if (!u->pcm_handle)
+ return;
+
+ update_sw_params(u);
+}
+
+static void source_reconfigure_cb(pa_source *s, pa_sample_spec *spec, bool passthrough) {
+ struct userdata *u = s->userdata;
+ int i;
+ bool format_supported = false;
+ bool rate_supported = false;
+
+ pa_assert(u);
+
+ for (i = 0; u->supported_formats[i] != PA_SAMPLE_MAX; i++) {
+ if (u->supported_formats[i] == spec->format) {
+ pa_source_set_sample_format(u->source, spec->format);
+ format_supported = true;
+ break;
+ }
+ }
+
+ if (!format_supported) {
+ pa_log_info("Source does not support sample format of %s, set it to a verified value",
+ pa_sample_format_to_string(spec->format));
+ pa_source_set_sample_format(u->source, u->verified_sample_spec.format);
+ }
+
+ for (i = 0; u->supported_rates[i]; i++) {
+ if (u->supported_rates[i] == spec->rate) {
+ pa_source_set_sample_rate(u->source, spec->rate);
+ rate_supported = true;
+ break;
+ }
+ }
+
+ if (!rate_supported) {
+ pa_log_info("Source does not support sample rate of %u, set it to a verfied value", spec->rate);
+ pa_source_set_sample_rate(u->source, u->verified_sample_spec.rate);
+ }
+}
+
+static void thread_func(void *userdata) {
+ struct userdata *u = userdata;
+ unsigned short revents = 0;
+
+ pa_assert(u);
+
+ pa_log_debug("Thread starting up");
+
+ if (u->core->realtime_scheduling)
+ pa_thread_make_realtime(u->core->realtime_priority);
+
+ pa_thread_mq_install(&u->thread_mq);
+
+ for (;;) {
+ int ret;
+ pa_usec_t rtpoll_sleep = 0, real_sleep;
+
+#ifdef DEBUG_TIMING
+ pa_log_debug("Loop");
+#endif
+
+ /* Read some data and pass it to the sources */
+ if (PA_SOURCE_IS_OPENED(u->source->thread_info.state)) {
+ int work_done;
+ pa_usec_t sleep_usec = 0;
+ bool on_timeout = pa_rtpoll_timer_elapsed(u->rtpoll);
+
+ if (u->first) {
+ pa_log_info("Starting capture.");
+ snd_pcm_start(u->pcm_handle);
+
+ pa_smoother_resume(u->smoother, pa_rtclock_now(), true);
+
+ u->first = false;
+ }
+
+ if (u->use_mmap)
+ work_done = mmap_read(u, &sleep_usec, revents & POLLIN, on_timeout);
+ else
+ work_done = unix_read(u, &sleep_usec, revents & POLLIN, on_timeout);
+
+ if (work_done < 0)
+ goto fail;
+
+/* pa_log_debug("work_done = %i", work_done); */
+
+ if (work_done)
+ update_smoother(u);
+
+ if (u->use_tsched) {
+ pa_usec_t cusec;
+
+ /* OK, the capture buffer is now empty, let's
+ * calculate when to wake up next */
+
+/* pa_log_debug("Waking up in %0.2fms (sound card clock).", (double) sleep_usec / PA_USEC_PER_MSEC); */
+
+ /* Convert from the sound card time domain to the
+ * system time domain */
+ cusec = pa_smoother_translate(u->smoother, pa_rtclock_now(), sleep_usec);
+
+/* pa_log_debug("Waking up in %0.2fms (system clock).", (double) cusec / PA_USEC_PER_MSEC); */
+
+ /* We don't trust the conversion, so we wake up whatever comes first */
+ rtpoll_sleep = PA_MIN(sleep_usec, cusec);
+ }
+ }
+
+ if (u->source->flags & PA_SOURCE_DEFERRED_VOLUME) {
+ pa_usec_t volume_sleep;
+ pa_source_volume_change_apply(u->source, &volume_sleep);
+ if (volume_sleep > 0) {
+ if (rtpoll_sleep > 0)
+ rtpoll_sleep = PA_MIN(volume_sleep, rtpoll_sleep);
+ else
+ rtpoll_sleep = volume_sleep;
+ }
+ }
+
+ if (rtpoll_sleep > 0) {
+ pa_rtpoll_set_timer_relative(u->rtpoll, rtpoll_sleep);
+ real_sleep = pa_rtclock_now();
+ }
+ else
+ pa_rtpoll_set_timer_disabled(u->rtpoll);
+
+ /* Hmm, nothing to do. Let's sleep */
+ if ((ret = pa_rtpoll_run(u->rtpoll)) < 0)
+ goto fail;
+
+ if (rtpoll_sleep > 0) {
+ real_sleep = pa_rtclock_now() - real_sleep;
+#ifdef DEBUG_TIMING
+ pa_log_debug("Expected sleep: %0.2fms, real sleep: %0.2fms (diff %0.2f ms)",
+ (double) rtpoll_sleep / PA_USEC_PER_MSEC, (double) real_sleep / PA_USEC_PER_MSEC,
+ (double) ((int64_t) real_sleep - (int64_t) rtpoll_sleep) / PA_USEC_PER_MSEC);
+#endif
+ if (u->use_tsched && real_sleep > rtpoll_sleep + u->tsched_watermark_usec)
+ pa_log_info("Scheduling delay of %0.2f ms > %0.2f ms, you might want to investigate this to improve latency...",
+ (double) (real_sleep - rtpoll_sleep) / PA_USEC_PER_MSEC,
+ (double) (u->tsched_watermark_usec) / PA_USEC_PER_MSEC);
+ }
+
+ if (u->source->flags & PA_SOURCE_DEFERRED_VOLUME)
+ pa_source_volume_change_apply(u->source, NULL);
+
+ if (ret == 0)
+ goto finish;
+
+ /* Tell ALSA about this and process its response */
+ if (PA_SOURCE_IS_OPENED(u->source->thread_info.state)) {
+ struct pollfd *pollfd;
+ int err;
+ unsigned n;
+
+ pollfd = pa_rtpoll_item_get_pollfd(u->alsa_rtpoll_item, &n);
+
+ if ((err = snd_pcm_poll_descriptors_revents(u->pcm_handle, pollfd, n, &revents)) < 0) {
+ pa_log("snd_pcm_poll_descriptors_revents() failed: %s", pa_alsa_strerror(err));
+ goto fail;
+ }
+
+ if (revents & ~POLLIN) {
+ if ((err = pa_alsa_recover_from_poll(u->pcm_handle, revents)) < 0)
+ goto fail;
+
+ /* Stream needs to be restarted */
+ if (err == 1) {
+ close_pcm(u);
+ if (unsuspend(u, true) < 0)
+ goto fail;
+ } else
+ reset_vars(u);
+
+ revents = 0;
+ } else if (revents && u->use_tsched && pa_log_ratelimit(PA_LOG_DEBUG))
+ pa_log_debug("Wakeup from ALSA!");
+
+ } else
+ revents = 0;
+ }
+
+fail:
+ /* If this was no regular exit from the loop we have to continue
+ * processing messages until we received PA_MESSAGE_SHUTDOWN */
+ pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
+ pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
+
+finish:
+ pa_log_debug("Thread shutting down");
+}
+
+static void set_source_name(pa_source_new_data *data, pa_modargs *ma, const char *device_id, const char *device_name, pa_alsa_mapping *mapping) {
+ const char *n;
+ char *t;
+
+ pa_assert(data);
+ pa_assert(ma);
+ pa_assert(device_name);
+
+ if ((n = pa_modargs_get_value(ma, "source_name", NULL))) {
+ pa_source_new_data_set_name(data, n);
+ data->namereg_fail = true;
+ return;
+ }
+
+ if ((n = pa_modargs_get_value(ma, "name", NULL)))
+ data->namereg_fail = true;
+ else {
+ n = device_id ? device_id : device_name;
+ data->namereg_fail = false;
+ }
+
+ if (mapping)
+ t = pa_sprintf_malloc("alsa_input.%s.%s", n, mapping->name);
+ else
+ t = pa_sprintf_malloc("alsa_input.%s", n);
+
+ pa_source_new_data_set_name(data, t);
+ pa_xfree(t);
+}
+
+static void find_mixer(struct userdata *u, pa_alsa_mapping *mapping, const char *element, bool ignore_dB) {
+ const char *mdev;
+
+ if (!mapping && !element)
+ return;
+
+ if (!element && mapping && pa_alsa_path_set_is_empty(mapping->input_path_set))
+ return;
+
+ u->mixers = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func,
+ NULL, (pa_free_cb_t) pa_alsa_mixer_free);
+
+ mdev = pa_proplist_gets(mapping->proplist, "alsa.mixer_device");
+ if (mdev) {
+ u->mixer_handle = pa_alsa_open_mixer_by_name(u->mixers, mdev, false);
+ } else {
+ u->mixer_handle = pa_alsa_open_mixer_for_pcm(u->mixers, u->pcm_handle, false);
+ }
+ if (!u->mixer_handle) {
+ pa_log_info("Failed to find a working mixer device.");
+ return;
+ }
+
+ if (element) {
+
+ if (!(u->mixer_path = pa_alsa_path_synthesize(element, PA_ALSA_DIRECTION_INPUT)))
+ goto fail;
+
+ if (pa_alsa_path_probe(u->mixer_path, NULL, u->mixer_handle, ignore_dB) < 0)
+ goto fail;
+
+ pa_log_debug("Probed mixer path %s:", u->mixer_path->name);
+ pa_alsa_path_dump(u->mixer_path);
+ } else {
+ u->mixer_path_set = mapping->input_path_set;
+ }
+
+ return;
+
+fail:
+
+ if (u->mixer_path) {
+ pa_alsa_path_free(u->mixer_path);
+ u->mixer_path = NULL;
+ }
+
+ u->mixer_handle = NULL;
+ pa_hashmap_free(u->mixers);
+ u->mixers = NULL;
+}
+
+static int setup_mixer(struct userdata *u, bool ignore_dB) {
+ bool need_mixer_callback = false;
+
+ pa_assert(u);
+
+ /* This code is before the u->mixer_handle check, because if the UCM
+ * configuration doesn't specify volume or mute controls, u->mixer_handle
+ * will be NULL, but the UCM device enable sequence will still need to be
+ * executed. */
+ if (u->source->active_port && u->ucm_context) {
+ if (pa_alsa_ucm_set_port(u->ucm_context, u->source->active_port, false) < 0)
+ return -1;
+ }
+
+ if (!u->mixer_handle)
+ return 0;
+
+ if (u->source->active_port) {
+ if (!u->ucm_context) {
+ pa_alsa_port_data *data;
+
+ /* We have a list of supported paths, so let's activate the
+ * one that has been chosen as active */
+
+ data = PA_DEVICE_PORT_DATA(u->source->active_port);
+ u->mixer_path = data->path;
+
+ pa_alsa_path_select(data->path, data->setting, u->mixer_handle, u->source->muted);
+ } else {
+ pa_alsa_ucm_port_data *data;
+
+ data = PA_DEVICE_PORT_DATA(u->source->active_port);
+
+ /* Now activate volume controls, if any */
+ if (data->path) {
+ u->mixer_path = data->path;
+ pa_alsa_path_select(u->mixer_path, NULL, u->mixer_handle, u->source->muted);
+ }
+ }
+ } else {
+
+ if (!u->mixer_path && u->mixer_path_set)
+ u->mixer_path = pa_hashmap_first(u->mixer_path_set->paths);
+
+ if (u->mixer_path) {
+ /* Hmm, we have only a single path, then let's activate it */
+
+ pa_alsa_path_select(u->mixer_path, u->mixer_path->settings, u->mixer_handle, u->source->muted);
+ } else
+ return 0;
+ }
+
+ mixer_volume_init(u);
+
+ /* Will we need to register callbacks? */
+ if (u->mixer_path_set && u->mixer_path_set->paths) {
+ pa_alsa_path *p;
+ void *state;
+
+ PA_HASHMAP_FOREACH(p, u->mixer_path_set->paths, state) {
+ if (p->has_volume || p->has_mute)
+ need_mixer_callback = true;
+ }
+ }
+ else if (u->mixer_path)
+ need_mixer_callback = u->mixer_path->has_volume || u->mixer_path->has_mute;
+
+ if (need_mixer_callback) {
+ int (*mixer_callback)(snd_mixer_elem_t *, unsigned int);
+ if (u->source->flags & PA_SOURCE_DEFERRED_VOLUME) {
+ u->mixer_pd = pa_alsa_mixer_pdata_new();
+ mixer_callback = io_mixer_callback;
+
+ if (pa_alsa_set_mixer_rtpoll(u->mixer_pd, u->mixer_handle, u->rtpoll) < 0) {
+ pa_log("Failed to initialize file descriptor monitoring");
+ return -1;
+ }
+ } else {
+ u->mixer_fdl = pa_alsa_fdlist_new();
+ mixer_callback = ctl_mixer_callback;
+
+ if (pa_alsa_fdlist_set_handle(u->mixer_fdl, u->mixer_handle, NULL, u->core->mainloop) < 0) {
+ pa_log("Failed to initialize file descriptor monitoring");
+ return -1;
+ }
+ }
+
+ if (u->mixer_path_set)
+ pa_alsa_path_set_set_callback(u->mixer_path_set, u->mixer_handle, mixer_callback, u);
+ else
+ pa_alsa_path_set_callback(u->mixer_path, u->mixer_handle, mixer_callback, u);
+ }
+
+ return 0;
+}
+
+pa_source *pa_alsa_source_new(pa_module *m, pa_modargs *ma, const char*driver, pa_card *card, pa_alsa_mapping *mapping) {
+
+ struct userdata *u = NULL;
+ const char *dev_id = NULL, *key, *mod_name;
+ pa_sample_spec ss;
+ char *thread_name = NULL;
+ uint32_t alternate_sample_rate;
+ pa_channel_map map;
+ uint32_t nfrags, frag_size, buffer_size, tsched_size, tsched_watermark;
+ snd_pcm_uframes_t period_frames, buffer_frames, tsched_frames;
+ size_t frame_size;
+ bool use_mmap = true;
+ bool use_tsched = true;
+ bool ignore_dB = false;
+ bool namereg_fail = false;
+ bool deferred_volume = false;
+ bool fixed_latency_range = false;
+ bool b;
+ bool d;
+ bool avoid_resampling;
+ pa_source_new_data data;
+ bool volume_is_set;
+ bool mute_is_set;
+ pa_alsa_profile_set *profile_set = NULL;
+ void *state;
+
+ pa_assert(m);
+ pa_assert(ma);
+
+ ss = m->core->default_sample_spec;
+ map = m->core->default_channel_map;
+ avoid_resampling = m->core->avoid_resampling;
+
+ /* Pick sample spec overrides from the mapping, if any */
+ if (mapping) {
+ if (mapping->sample_spec.format != PA_SAMPLE_INVALID)
+ ss.format = mapping->sample_spec.format;
+ if (mapping->sample_spec.rate != 0)
+ ss.rate = mapping->sample_spec.rate;
+ if (mapping->sample_spec.channels != 0) {
+ ss.channels = mapping->sample_spec.channels;
+ if (pa_channel_map_valid(&mapping->channel_map))
+ pa_assert(pa_channel_map_compatible(&mapping->channel_map, &ss));
+ }
+ }
+
+ /* Override with modargs if provided */
+ if (pa_modargs_get_sample_spec_and_channel_map(ma, &ss, &map, PA_CHANNEL_MAP_ALSA) < 0) {
+ pa_log("Failed to parse sample specification and channel map");
+ goto fail;
+ }
+
+ alternate_sample_rate = m->core->alternate_sample_rate;
+ if (pa_modargs_get_alternate_sample_rate(ma, &alternate_sample_rate) < 0) {
+ pa_log("Failed to parse alternate sample rate");
+ goto fail;
+ }
+
+ frame_size = pa_frame_size(&ss);
+
+ nfrags = m->core->default_n_fragments;
+ frag_size = (uint32_t) pa_usec_to_bytes(m->core->default_fragment_size_msec*PA_USEC_PER_MSEC, &ss);
+ if (frag_size <= 0)
+ frag_size = (uint32_t) frame_size;
+ tsched_size = (uint32_t) pa_usec_to_bytes(DEFAULT_TSCHED_BUFFER_USEC, &ss);
+ tsched_watermark = (uint32_t) pa_usec_to_bytes(DEFAULT_TSCHED_WATERMARK_USEC, &ss);
+
+ if (pa_modargs_get_value_u32(ma, "fragments", &nfrags) < 0 ||
+ pa_modargs_get_value_u32(ma, "fragment_size", &frag_size) < 0 ||
+ pa_modargs_get_value_u32(ma, "tsched_buffer_size", &tsched_size) < 0 ||
+ pa_modargs_get_value_u32(ma, "tsched_buffer_watermark", &tsched_watermark) < 0) {
+ pa_log("Failed to parse buffer metrics");
+ goto fail;
+ }
+
+ buffer_size = nfrags * frag_size;
+
+ period_frames = frag_size/frame_size;
+ buffer_frames = buffer_size/frame_size;
+ tsched_frames = tsched_size/frame_size;
+
+ if (pa_modargs_get_value_boolean(ma, "mmap", &use_mmap) < 0) {
+ pa_log("Failed to parse mmap argument.");
+ goto fail;
+ }
+
+ if (pa_modargs_get_value_boolean(ma, "tsched", &use_tsched) < 0) {
+ pa_log("Failed to parse tsched argument.");
+ goto fail;
+ }
+
+ if (pa_modargs_get_value_boolean(ma, "ignore_dB", &ignore_dB) < 0) {
+ pa_log("Failed to parse ignore_dB argument.");
+ goto fail;
+ }
+
+ deferred_volume = m->core->deferred_volume;
+ if (pa_modargs_get_value_boolean(ma, "deferred_volume", &deferred_volume) < 0) {
+ pa_log("Failed to parse deferred_volume argument.");
+ goto fail;
+ }
+
+ if (pa_modargs_get_value_boolean(ma, "fixed_latency_range", &fixed_latency_range) < 0) {
+ pa_log("Failed to parse fixed_latency_range argument.");
+ goto fail;
+ }
+
+ use_tsched = pa_alsa_may_tsched(use_tsched);
+
+ u = pa_xnew0(struct userdata, 1);
+ u->core = m->core;
+ u->module = m;
+ u->use_mmap = use_mmap;
+ u->use_tsched = use_tsched;
+ u->tsched_size = tsched_size;
+ u->initial_info.nfrags = (size_t) nfrags;
+ u->initial_info.fragment_size = (size_t) frag_size;
+ u->initial_info.tsched_size = (size_t) tsched_size;
+ u->initial_info.tsched_watermark = (size_t) tsched_watermark;
+ u->deferred_volume = deferred_volume;
+ u->fixed_latency_range = fixed_latency_range;
+ u->first = true;
+ u->rtpoll = pa_rtpoll_new();
+
+ if (pa_thread_mq_init(&u->thread_mq, m->core->mainloop, u->rtpoll) < 0) {
+ pa_log("pa_thread_mq_init() failed.");
+ goto fail;
+ }
+
+ u->smoother = pa_smoother_new(
+ SMOOTHER_ADJUST_USEC,
+ SMOOTHER_WINDOW_USEC,
+ true,
+ true,
+ 5,
+ pa_rtclock_now(),
+ true);
+ u->smoother_interval = SMOOTHER_MIN_INTERVAL;
+
+ /* use ucm */
+ if (mapping && mapping->ucm_context.ucm)
+ u->ucm_context = &mapping->ucm_context;
+
+ dev_id = pa_modargs_get_value(
+ ma, "device_id",
+ pa_modargs_get_value(ma, "device", DEFAULT_DEVICE));
+
+ u->paths_dir = pa_xstrdup(pa_modargs_get_value(ma, "paths_dir", NULL));
+
+ if (reserve_init(u, dev_id) < 0)
+ goto fail;
+
+ if (reserve_monitor_init(u, dev_id) < 0)
+ goto fail;
+
+ b = use_mmap;
+ d = use_tsched;
+
+ /* Force ALSA to reread its configuration if module-alsa-card didn't
+ * do it for us. This matters if our device was hot-plugged after ALSA
+ * has already read its configuration - see
+ * https://bugs.freedesktop.org/show_bug.cgi?id=54029
+ */
+
+ if (!card)
+ snd_config_update_free_global();
+
+ if (mapping) {
+
+ if (!(dev_id = pa_modargs_get_value(ma, "device_id", NULL))) {
+ pa_log("device_id= not set");
+ goto fail;
+ }
+
+ if ((mod_name = pa_proplist_gets(mapping->proplist, PA_ALSA_PROP_UCM_MODIFIER))) {
+ if (snd_use_case_set(u->ucm_context->ucm->ucm_mgr, "_enamod", mod_name) < 0)
+ pa_log("Failed to enable ucm modifier %s", mod_name);
+ else
+ pa_log_debug("Enabled ucm modifier %s", mod_name);
+ }
+
+ if (!(u->pcm_handle = pa_alsa_open_by_device_id_mapping(
+ dev_id,
+ &u->device_name,
+ &ss, &map,
+ SND_PCM_STREAM_CAPTURE,
+ &period_frames, &buffer_frames, tsched_frames,
+ &b, &d, mapping)))
+ goto fail;
+
+ } else if ((dev_id = pa_modargs_get_value(ma, "device_id", NULL))) {
+
+ if (!(profile_set = pa_alsa_profile_set_new(NULL, &map)))
+ goto fail;
+
+ if (!(u->pcm_handle = pa_alsa_open_by_device_id_auto(
+ dev_id,
+ &u->device_name,
+ &ss, &map,
+ SND_PCM_STREAM_CAPTURE,
+ &period_frames, &buffer_frames, tsched_frames,
+ &b, &d, profile_set, &mapping)))
+ goto fail;
+
+ } else {
+
+ if (!(u->pcm_handle = pa_alsa_open_by_device_string(
+ pa_modargs_get_value(ma, "device", DEFAULT_DEVICE),
+ &u->device_name,
+ &ss, &map,
+ SND_PCM_STREAM_CAPTURE,
+ &period_frames, &buffer_frames, tsched_frames,
+ &b, &d, false)))
+ goto fail;
+ }
+
+ pa_assert(u->device_name);
+ pa_log_info("Successfully opened device %s.", u->device_name);
+
+ if (pa_alsa_pcm_is_modem(u->pcm_handle)) {
+ pa_log_notice("Device %s is modem, refusing further initialization.", u->device_name);
+ goto fail;
+ }
+
+ if (mapping)
+ pa_log_info("Selected mapping '%s' (%s).", mapping->description, mapping->name);
+
+ if (use_mmap && !b) {
+ pa_log_info("Device doesn't support mmap(), falling back to UNIX read/write mode.");
+ u->use_mmap = use_mmap = false;
+ }
+
+ if (use_tsched && (!b || !d)) {
+ pa_log_info("Cannot enable timer-based scheduling, falling back to sound IRQ scheduling.");
+ u->use_tsched = use_tsched = false;
+ }
+
+ if (u->use_mmap)
+ pa_log_info("Successfully enabled mmap() mode.");
+
+ if (u->use_tsched) {
+ pa_log_info("Successfully enabled timer-based scheduling mode.");
+ if (u->fixed_latency_range)
+ pa_log_info("Disabling latency range changes on overrun");
+ }
+
+ u->verified_sample_spec = ss;
+
+ u->supported_formats = pa_alsa_get_supported_formats(u->pcm_handle, ss.format);
+ if (!u->supported_formats) {
+ pa_log_error("Failed to find any supported sample formats.");
+ goto fail;
+ }
+
+ u->supported_rates = pa_alsa_get_supported_rates(u->pcm_handle, ss.rate);
+ if (!u->supported_rates) {
+ pa_log_error("Failed to find any supported sample rates.");
+ goto fail;
+ }
+
+ /* ALSA might tweak the sample spec, so recalculate the frame size */
+ frame_size = pa_frame_size(&ss);
+
+ pa_source_new_data_init(&data);
+ data.driver = driver;
+ data.module = m;
+ data.card = card;
+ set_source_name(&data, ma, dev_id, u->device_name, mapping);
+
+ /* We need to give pa_modargs_get_value_boolean() a pointer to a local
+ * variable instead of using &data.namereg_fail directly, because
+ * data.namereg_fail is a bitfield and taking the address of a bitfield
+ * variable is impossible. */
+ namereg_fail = data.namereg_fail;
+ if (pa_modargs_get_value_boolean(ma, "namereg_fail", &namereg_fail) < 0) {
+ pa_log("Failed to parse namereg_fail argument.");
+ pa_source_new_data_done(&data);
+ goto fail;
+ }
+ data.namereg_fail = namereg_fail;
+
+ if (pa_modargs_get_value_boolean(ma, "avoid_resampling", &avoid_resampling) < 0) {
+ pa_log("Failed to parse avoid_resampling argument.");
+ pa_source_new_data_done(&data);
+ goto fail;
+ }
+ pa_source_new_data_set_avoid_resampling(&data, avoid_resampling);
+
+ pa_source_new_data_set_sample_spec(&data, &ss);
+ pa_source_new_data_set_channel_map(&data, &map);
+ pa_source_new_data_set_alternate_sample_rate(&data, alternate_sample_rate);
+
+ pa_alsa_init_proplist_pcm(m->core, data.proplist, u->pcm_handle);
+ pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, u->device_name);
+ pa_proplist_setf(data.proplist, PA_PROP_DEVICE_BUFFERING_BUFFER_SIZE, "%lu", (unsigned long) (buffer_frames * frame_size));
+ pa_proplist_setf(data.proplist, PA_PROP_DEVICE_BUFFERING_FRAGMENT_SIZE, "%lu", (unsigned long) (period_frames * frame_size));
+ pa_proplist_sets(data.proplist, PA_PROP_DEVICE_ACCESS_MODE, u->use_tsched ? "mmap+timer" : (u->use_mmap ? "mmap" : "serial"));
+
+ if (mapping) {
+ pa_proplist_sets(data.proplist, PA_PROP_DEVICE_PROFILE_NAME, mapping->name);
+ pa_proplist_sets(data.proplist, PA_PROP_DEVICE_PROFILE_DESCRIPTION, mapping->description);
+
+ state = NULL;
+ while ((key = pa_proplist_iterate(mapping->proplist, &state)))
+ pa_proplist_sets(data.proplist, key, pa_proplist_gets(mapping->proplist, key));
+ }
+
+ pa_alsa_init_description(data.proplist, card);
+
+ if (u->control_device)
+ pa_alsa_init_proplist_ctl(data.proplist, u->control_device);
+
+ if (pa_modargs_get_proplist(ma, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
+ pa_log("Invalid properties");
+ pa_source_new_data_done(&data);
+ goto fail;
+ }
+
+ if (u->ucm_context) {
+ pa_alsa_ucm_add_ports(&data.ports, data.proplist, u->ucm_context, false, card, u->pcm_handle, ignore_dB);
+ find_mixer(u, mapping, pa_modargs_get_value(ma, "control", NULL), ignore_dB);
+ } else {
+ find_mixer(u, mapping, pa_modargs_get_value(ma, "control", NULL), ignore_dB);
+ if (u->mixer_path_set)
+ pa_alsa_add_ports(&data, u->mixer_path_set, card);
+ }
+
+ u->source = pa_source_new(m->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY|(u->use_tsched ? PA_SOURCE_DYNAMIC_LATENCY : 0));
+ volume_is_set = data.volume_is_set;
+ mute_is_set = data.muted_is_set;
+ pa_source_new_data_done(&data);
+
+ if (!u->source) {
+ pa_log("Failed to create source object");
+ goto fail;
+ }
+
+ if (u->ucm_context) {
+ pa_device_port *port;
+ unsigned h_prio = 0;
+ PA_HASHMAP_FOREACH(port, u->source->ports, state) {
+ if (!h_prio || port->priority > h_prio)
+ h_prio = port->priority;
+ }
+ /* ucm ports prioriy is 100, 200, ..., 900, change it to units digit */
+ h_prio = h_prio / 100;
+ u->source->priority += h_prio;
+ }
+
+ if (pa_modargs_get_value_u32(ma, "deferred_volume_safety_margin",
+ &u->source->thread_info.volume_change_safety_margin) < 0) {
+ pa_log("Failed to parse deferred_volume_safety_margin parameter");
+ goto fail;
+ }
+
+ if (pa_modargs_get_value_s32(ma, "deferred_volume_extra_delay",
+ &u->source->thread_info.volume_change_extra_delay) < 0) {
+ pa_log("Failed to parse deferred_volume_extra_delay parameter");
+ goto fail;
+ }
+
+ u->source->parent.process_msg = source_process_msg;
+ if (u->use_tsched)
+ u->source->update_requested_latency = source_update_requested_latency_cb;
+ u->source->set_state_in_main_thread = source_set_state_in_main_thread_cb;
+ u->source->set_state_in_io_thread = source_set_state_in_io_thread_cb;
+ if (u->ucm_context)
+ u->source->set_port = source_set_port_ucm_cb;
+ else
+ u->source->set_port = source_set_port_cb;
+ u->source->reconfigure = source_reconfigure_cb;
+ u->source->userdata = u;
+
+ pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
+ pa_source_set_rtpoll(u->source, u->rtpoll);
+
+ u->frame_size = frame_size;
+ u->frames_per_block = pa_mempool_block_size_max(m->core->mempool) / frame_size;
+ u->fragment_size = frag_size = (size_t) (period_frames * frame_size);
+ u->hwbuf_size = buffer_size = (size_t) (buffer_frames * frame_size);
+ pa_cvolume_mute(&u->hardware_volume, u->source->sample_spec.channels);
+
+ pa_log_info("Using %0.1f fragments of size %lu bytes (%0.2fms), buffer size is %lu bytes (%0.2fms)",
+ (double) u->hwbuf_size / (double) u->fragment_size,
+ (long unsigned) u->fragment_size,
+ (double) pa_bytes_to_usec(u->fragment_size, &ss) / PA_USEC_PER_MSEC,
+ (long unsigned) u->hwbuf_size,
+ (double) pa_bytes_to_usec(u->hwbuf_size, &ss) / PA_USEC_PER_MSEC);
+
+ if (u->use_tsched) {
+ u->tsched_watermark_ref = tsched_watermark;
+ reset_watermark(u, u->tsched_watermark_ref, &ss, false);
+ }
+ else
+ pa_source_set_fixed_latency(u->source, pa_bytes_to_usec(u->hwbuf_size, &ss));
+
+ reserve_update(u);
+
+ if (update_sw_params(u) < 0)
+ goto fail;
+
+ if (setup_mixer(u, ignore_dB) < 0)
+ goto fail;
+
+ pa_alsa_dump(PA_LOG_DEBUG, u->pcm_handle);
+
+ thread_name = pa_sprintf_malloc("alsa-source-%s", pa_strnull(pa_proplist_gets(u->source->proplist, "alsa.id")));
+ if (!(u->thread = pa_thread_new(thread_name, thread_func, u))) {
+ pa_log("Failed to create thread.");
+ goto fail;
+ }
+ pa_xfree(thread_name);
+ thread_name = NULL;
+
+ /* Get initial mixer settings */
+ if (volume_is_set) {
+ if (u->source->set_volume)
+ u->source->set_volume(u->source);
+ } else {
+ if (u->source->get_volume)
+ u->source->get_volume(u->source);
+ }
+
+ if (mute_is_set) {
+ if (u->source->set_mute)
+ u->source->set_mute(u->source);
+ } else {
+ if (u->source->get_mute) {
+ bool mute;
+
+ if (u->source->get_mute(u->source, &mute) >= 0)
+ pa_source_set_mute(u->source, mute, false);
+ }
+ }
+
+ if ((volume_is_set || mute_is_set) && u->source->write_volume)
+ u->source->write_volume(u->source);
+
+ pa_source_put(u->source);
+
+ if (profile_set)
+ pa_alsa_profile_set_free(profile_set);
+
+ return u->source;
+
+fail:
+ pa_xfree(thread_name);
+
+ if (u)
+ userdata_free(u);
+
+ if (profile_set)
+ pa_alsa_profile_set_free(profile_set);
+
+ return NULL;
+}
+
+static void userdata_free(struct userdata *u) {
+ pa_assert(u);
+
+ if (u->source)
+ pa_source_unlink(u->source);
+
+ if (u->thread) {
+ pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
+ pa_thread_free(u->thread);
+ }
+
+ pa_thread_mq_done(&u->thread_mq);
+
+ if (u->source)
+ pa_source_unref(u->source);
+
+ if (u->mixer_pd)
+ pa_alsa_mixer_pdata_free(u->mixer_pd);
+
+ if (u->alsa_rtpoll_item)
+ pa_rtpoll_item_free(u->alsa_rtpoll_item);
+
+ if (u->rtpoll)
+ pa_rtpoll_free(u->rtpoll);
+
+ if (u->pcm_handle) {
+ snd_pcm_drop(u->pcm_handle);
+ snd_pcm_close(u->pcm_handle);
+ }
+
+ if (u->mixer_fdl)
+ pa_alsa_fdlist_free(u->mixer_fdl);
+
+ /* Only free the mixer_path if the sink owns it */
+ if (u->mixer_path && !u->mixer_path_set && !u->ucm_context)
+ pa_alsa_path_free(u->mixer_path);
+
+ if (u->mixers)
+ pa_hashmap_free(u->mixers);
+
+ if (u->smoother)
+ pa_smoother_free(u->smoother);
+
+ if (u->supported_formats)
+ pa_xfree(u->supported_formats);
+
+ if (u->supported_rates)
+ pa_xfree(u->supported_rates);
+
+ reserve_done(u);
+ monitor_done(u);
+
+ pa_xfree(u->device_name);
+ pa_xfree(u->control_device);
+ pa_xfree(u->paths_dir);
+ pa_xfree(u);
+}
+
+void pa_alsa_source_free(pa_source *s) {
+ struct userdata *u;
+
+ pa_source_assert_ref(s);
+ pa_assert_se(u = s->userdata);
+
+ userdata_free(u);
+}
diff --git a/src/modules/alsa/alsa-source.h b/src/modules/alsa/alsa-source.h
new file mode 100644
index 0000000..ecbdfcd
--- /dev/null
+++ b/src/modules/alsa/alsa-source.h
@@ -0,0 +1,34 @@
+#ifndef fooalsasourcehfoo
+#define fooalsasourcehfoo
+
+/***
+ This file is part of PulseAudio.
+
+ Copyright 2004-2006 Lennart Poettering
+ Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
+
+ PulseAudio is free software; you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License,
+ or (at your option) any later version.
+
+ PulseAudio is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <pulsecore/module.h>
+#include <pulsecore/modargs.h>
+#include <pulsecore/source.h>
+
+#include "alsa-util.h"
+
+pa_source* pa_alsa_source_new(pa_module *m, pa_modargs *ma, const char*driver, pa_card *card, pa_alsa_mapping *mapping);
+
+void pa_alsa_source_free(pa_source *s);
+
+#endif
diff --git a/src/modules/alsa/alsa-ucm.c b/src/modules/alsa/alsa-ucm.c
new file mode 100644
index 0000000..d9cea61
--- /dev/null
+++ b/src/modules/alsa/alsa-ucm.c
@@ -0,0 +1,2396 @@
+/***
+ This file is part of PulseAudio.
+
+ Copyright 2011 Wolfson Microelectronics PLC
+ Author Margarita Olaya <magi@slimlogic.co.uk>
+ Copyright 2012 Feng Wei <wei.feng@freescale.com>, Freescale Ltd.
+
+ PulseAudio is free software; you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License,
+ or (at your option) any later version.
+
+ PulseAudio is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+***/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <ctype.h>
+#include <sys/types.h>
+#include <limits.h>
+#include <alsa/asoundlib.h>
+
+#ifdef HAVE_VALGRIND_MEMCHECK_H
+#include <valgrind/memcheck.h>
+#endif
+
+#include <pulse/sample.h>
+#include <pulse/xmalloc.h>
+#include <pulse/timeval.h>
+#include <pulse/util.h>
+
+#include <pulsecore/log.h>
+#include <pulsecore/macro.h>
+#include <pulsecore/core-util.h>
+#include <pulsecore/atomic.h>
+#include <pulsecore/core-error.h>
+#include <pulsecore/once.h>
+#include <pulsecore/thread.h>
+#include <pulsecore/conf-parser.h>
+#include <pulsecore/strbuf.h>
+
+#include "alsa-mixer.h"
+#include "alsa-util.h"
+#include "alsa-ucm.h"
+
+#define PA_UCM_PRE_TAG_OUTPUT "[Out] "
+#define PA_UCM_PRE_TAG_INPUT "[In] "
+
+#define PA_UCM_PLAYBACK_PRIORITY_UNSET(device) ((device)->playback_channels && !(device)->playback_priority)
+#define PA_UCM_CAPTURE_PRIORITY_UNSET(device) ((device)->capture_channels && !(device)->capture_priority)
+#define PA_UCM_DEVICE_PRIORITY_SET(device, priority) \
+ do { \
+ if (PA_UCM_PLAYBACK_PRIORITY_UNSET(device)) (device)->playback_priority = (priority); \
+ if (PA_UCM_CAPTURE_PRIORITY_UNSET(device)) (device)->capture_priority = (priority); \
+ } while (0)
+#define PA_UCM_IS_MODIFIER_MAPPING(m) ((pa_proplist_gets((m)->proplist, PA_ALSA_PROP_UCM_MODIFIER)) != NULL)
+
+#ifdef HAVE_ALSA_UCM
+
+struct ucm_type {
+ const char *prefix;
+ pa_device_port_type_t type;
+};
+
+struct ucm_items {
+ const char *id;
+ const char *property;
+};
+
+struct ucm_info {
+ const char *id;
+ unsigned priority;
+};
+
+static pa_alsa_jack* ucm_get_jack(pa_alsa_ucm_config *ucm, pa_alsa_ucm_device *device);
+static void device_set_jack(pa_alsa_ucm_device *device, pa_alsa_jack *jack);
+static void device_add_hw_mute_jack(pa_alsa_ucm_device *device, pa_alsa_jack *jack);
+
+static pa_alsa_ucm_device *verb_find_device(pa_alsa_ucm_verb *verb, const char *device_name);
+
+
+static void ucm_port_data_init(pa_alsa_ucm_port_data *port, pa_alsa_ucm_config *ucm, pa_device_port *core_port,
+ pa_alsa_ucm_device **devices, unsigned n_devices);
+static void ucm_port_data_free(pa_device_port *port);
+static void ucm_port_update_available(pa_alsa_ucm_port_data *port);
+
+static struct ucm_type types[] = {
+ {"None", PA_DEVICE_PORT_TYPE_UNKNOWN},
+ {"Speaker", PA_DEVICE_PORT_TYPE_SPEAKER},
+ {"Line", PA_DEVICE_PORT_TYPE_LINE},
+ {"Mic", PA_DEVICE_PORT_TYPE_MIC},
+ {"Headphones", PA_DEVICE_PORT_TYPE_HEADPHONES},
+ {"Headset", PA_DEVICE_PORT_TYPE_HEADSET},
+ {"Handset", PA_DEVICE_PORT_TYPE_HANDSET},
+ {"Bluetooth", PA_DEVICE_PORT_TYPE_BLUETOOTH},
+ {"Earpiece", PA_DEVICE_PORT_TYPE_EARPIECE},
+ {"SPDIF", PA_DEVICE_PORT_TYPE_SPDIF},
+ {"HDMI", PA_DEVICE_PORT_TYPE_HDMI},
+ {NULL, 0}
+};
+
+static struct ucm_items item[] = {
+ {"PlaybackPCM", PA_ALSA_PROP_UCM_SINK},
+ {"CapturePCM", PA_ALSA_PROP_UCM_SOURCE},
+ {"PlaybackCTL", PA_ALSA_PROP_UCM_PLAYBACK_CTL_DEVICE},
+ {"PlaybackVolume", PA_ALSA_PROP_UCM_PLAYBACK_VOLUME},
+ {"PlaybackSwitch", PA_ALSA_PROP_UCM_PLAYBACK_SWITCH},
+ {"PlaybackMixer", PA_ALSA_PROP_UCM_PLAYBACK_MIXER_DEVICE},
+ {"PlaybackMixerElem", PA_ALSA_PROP_UCM_PLAYBACK_MIXER_ELEM},
+ {"PlaybackMasterElem", PA_ALSA_PROP_UCM_PLAYBACK_MASTER_ELEM},
+ {"PlaybackMasterType", PA_ALSA_PROP_UCM_PLAYBACK_MASTER_TYPE},
+ {"PlaybackPriority", PA_ALSA_PROP_UCM_PLAYBACK_PRIORITY},
+ {"PlaybackRate", PA_ALSA_PROP_UCM_PLAYBACK_RATE},
+ {"PlaybackChannels", PA_ALSA_PROP_UCM_PLAYBACK_CHANNELS},
+ {"CaptureCTL", PA_ALSA_PROP_UCM_CAPTURE_CTL_DEVICE},
+ {"CaptureVolume", PA_ALSA_PROP_UCM_CAPTURE_VOLUME},
+ {"CaptureSwitch", PA_ALSA_PROP_UCM_CAPTURE_SWITCH},
+ {"CaptureMixer", PA_ALSA_PROP_UCM_CAPTURE_MIXER_DEVICE},
+ {"CaptureMixerElem", PA_ALSA_PROP_UCM_CAPTURE_MIXER_ELEM},
+ {"CaptureMasterElem", PA_ALSA_PROP_UCM_CAPTURE_MASTER_ELEM},
+ {"CaptureMasterType", PA_ALSA_PROP_UCM_CAPTURE_MASTER_TYPE},
+ {"CapturePriority", PA_ALSA_PROP_UCM_CAPTURE_PRIORITY},
+ {"CaptureRate", PA_ALSA_PROP_UCM_CAPTURE_RATE},
+ {"CaptureChannels", PA_ALSA_PROP_UCM_CAPTURE_CHANNELS},
+ {"TQ", PA_ALSA_PROP_UCM_QOS},
+ {"JackCTL", PA_ALSA_PROP_UCM_JACK_DEVICE},
+ {"JackControl", PA_ALSA_PROP_UCM_JACK_CONTROL},
+ {"JackHWMute", PA_ALSA_PROP_UCM_JACK_HW_MUTE},
+ {NULL, NULL},
+};
+
+/* UCM verb info - this should eventually be part of policy manangement */
+static struct ucm_info verb_info[] = {
+ {SND_USE_CASE_VERB_INACTIVE, 0},
+ {SND_USE_CASE_VERB_HIFI, 8000},
+ {SND_USE_CASE_VERB_HIFI_LOW_POWER, 7000},
+ {SND_USE_CASE_VERB_VOICE, 6000},
+ {SND_USE_CASE_VERB_VOICE_LOW_POWER, 5000},
+ {SND_USE_CASE_VERB_VOICECALL, 4000},
+ {SND_USE_CASE_VERB_IP_VOICECALL, 4000},
+ {SND_USE_CASE_VERB_ANALOG_RADIO, 3000},
+ {SND_USE_CASE_VERB_DIGITAL_RADIO, 3000},
+ {NULL, 0}
+};
+
+/* UCM device info - should be overwritten by ucm property */
+static struct ucm_info dev_info[] = {
+ {SND_USE_CASE_DEV_SPEAKER, 100},
+ {SND_USE_CASE_DEV_LINE, 100},
+ {SND_USE_CASE_DEV_HEADPHONES, 100},
+ {SND_USE_CASE_DEV_HEADSET, 300},
+ {SND_USE_CASE_DEV_HANDSET, 200},
+ {SND_USE_CASE_DEV_BLUETOOTH, 400},
+ {SND_USE_CASE_DEV_EARPIECE, 100},
+ {SND_USE_CASE_DEV_SPDIF, 100},
+ {SND_USE_CASE_DEV_HDMI, 100},
+ {SND_USE_CASE_DEV_NONE, 100},
+ {NULL, 0}
+};
+
+
+static char *ucm_verb_value(
+ snd_use_case_mgr_t *uc_mgr,
+ const char *verb_name,
+ const char *id) {
+
+ const char *value;
+ char *_id = pa_sprintf_malloc("=%s//%s", id, verb_name);
+ int err = snd_use_case_get(uc_mgr, _id, &value);
+ pa_xfree(_id);
+ if (err < 0)
+ return NULL;
+ pa_log_debug("Got %s for verb %s: %s", id, verb_name, value);
+ /* Use the cast here to allow free() call without casting for callers.
+ * The snd_use_case_get() returns mallocated string.
+ * See the Note: in use-case.h for snd_use_case_get().
+ */
+ return (char *)value;
+}
+
+static int ucm_device_exists(pa_idxset *idxset, pa_alsa_ucm_device *dev) {
+ pa_alsa_ucm_device *d;
+ uint32_t idx;
+
+ PA_IDXSET_FOREACH(d, idxset, idx)
+ if (d == dev)
+ return 1;
+
+ return 0;
+}
+
+static void ucm_add_devices_to_idxset(
+ pa_idxset *idxset,
+ pa_alsa_ucm_device *me,
+ pa_alsa_ucm_device *devices,
+ const char **dev_names,
+ int n) {
+
+ pa_alsa_ucm_device *d;
+
+ PA_LLIST_FOREACH(d, devices) {
+ const char *name;
+ int i;
+
+ if (d == me)
+ continue;
+
+ name = pa_proplist_gets(d->proplist, PA_ALSA_PROP_UCM_NAME);
+
+ for (i = 0; i < n; i++)
+ if (pa_streq(dev_names[i], name))
+ pa_idxset_put(idxset, d, NULL);
+ }
+}
+
+/* Split a string into words. Like pa_split_spaces() but handle '' and "". */
+static char *ucm_split_devnames(const char *c, const char **state) {
+ const char *current = *state ? *state : c;
+ char h;
+ size_t l;
+
+ if (!*current || *c == 0)
+ return NULL;
+
+ current += strspn(current, "\n\r \t");
+ h = *current;
+ if (h == '\'' || h =='"') {
+ c = ++current;
+ for (l = 0; *c && *c != h; l++) c++;
+ if (*c != h)
+ return NULL;
+ *state = c + 1;
+ } else {
+ l = strcspn(current, "\n\r \t");
+ *state = current+l;
+ }
+
+ return pa_xstrndup(current, l);
+}
+
+
+static void ucm_volume_free(pa_alsa_ucm_volume *vol) {
+ pa_assert(vol);
+ pa_xfree(vol->mixer_elem);
+ pa_xfree(vol->master_elem);
+ pa_xfree(vol->master_type);
+ pa_xfree(vol);
+}
+
+/* Get the volume identifier */
+static char *ucm_get_mixer_id(
+ pa_alsa_ucm_device *device,
+ const char *mprop,
+ const char *cprop,
+ const char *cid)
+{
+#if SND_LIB_VERSION >= 0x10201 /* alsa-lib-1.2.1+ check */
+ snd_ctl_elem_id_t *ctl;
+ int err;
+#endif
+ const char *value;
+ char *value2;
+ int index;
+
+ /* mixer element as first, if it's found, return it without modifications */
+ value = pa_proplist_gets(device->proplist, mprop);
+ if (value)
+ return pa_xstrdup(value);
+ /* fallback, get the control element identifier */
+ /* and try to do some heuristic to determine the mixer element name */
+ value = pa_proplist_gets(device->proplist, cprop);
+ if (value == NULL)
+ return NULL;
+#if SND_LIB_VERSION >= 0x10201 /* alsa-lib-1.2.1+ check */
+ /* The new parser may return also element index. */
+ snd_ctl_elem_id_alloca(&ctl);
+ err = snd_use_case_parse_ctl_elem_id(ctl, cid, value);
+ if (err < 0)
+ return NULL;
+ value = snd_ctl_elem_id_get_name(ctl);
+ index = snd_ctl_elem_id_get_index(ctl);
+#else
+#warning "Upgrade to alsa-lib 1.2.1!"
+ index = 0;
+#endif
+ if (!(value2 = pa_str_strip_suffix(value, " Playback Volume")))
+ if (!(value2 = pa_str_strip_suffix(value, " Capture Volume")))
+ if (!(value2 = pa_str_strip_suffix(value, " Volume")))
+ value2 = pa_xstrdup(value);
+ if (index > 0) {
+ char *mix = pa_sprintf_malloc("'%s',%d", value2, index);
+ pa_xfree(value2);
+ return mix;
+ }
+ return value2;
+}
+
+/* Get the volume identifier */
+static pa_alsa_ucm_volume *ucm_get_mixer_volume(
+ pa_alsa_ucm_device *device,
+ const char *mprop,
+ const char *cprop,
+ const char *cid,
+ const char *masterid,
+ const char *mastertype)
+{
+ pa_alsa_ucm_volume *vol;
+ char *mixer_elem;
+
+ mixer_elem = ucm_get_mixer_id(device, mprop, cprop, cid);
+ if (mixer_elem == NULL)
+ return NULL;
+ vol = pa_xnew0(pa_alsa_ucm_volume, 1);
+ if (vol == NULL) {
+ pa_xfree(mixer_elem);
+ return NULL;
+ }
+ vol->mixer_elem = mixer_elem;
+ vol->master_elem = pa_xstrdup(pa_proplist_gets(device->proplist, masterid));
+ vol->master_type = pa_xstrdup(pa_proplist_gets(device->proplist, mastertype));
+ return vol;
+}
+
+/* Get the ALSA mixer device for the UCM device */
+static const char *get_mixer_device(pa_alsa_ucm_device *dev, bool is_sink)
+{
+ const char *dev_name;
+
+ if (is_sink) {
+ dev_name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_PLAYBACK_MIXER_DEVICE);
+ if (!dev_name)
+ dev_name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_PLAYBACK_CTL_DEVICE);
+ } else {
+ dev_name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_CAPTURE_MIXER_DEVICE);
+ if (!dev_name)
+ dev_name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_CAPTURE_CTL_DEVICE);
+ }
+ return dev_name;
+}
+
+/* Get the ALSA mixer device for the UCM jack */
+static const char *get_jack_mixer_device(pa_alsa_ucm_device *dev, bool is_sink) {
+ const char *dev_name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_JACK_DEVICE);
+ if (!dev_name)
+ return get_mixer_device(dev, is_sink);
+ return dev_name;
+}
+
+/* Create a property list for this ucm device */
+static int ucm_get_device_property(
+ pa_alsa_ucm_device *device,
+ snd_use_case_mgr_t *uc_mgr,
+ pa_alsa_ucm_verb *verb,
+ const char *device_name) {
+
+ const char *value;
+ const char **devices;
+ char *id, *s;
+ int i;
+ int err;
+ uint32_t ui;
+ int n_confdev, n_suppdev;
+ pa_alsa_ucm_volume *vol;
+
+ /* determine the device type */
+ device->type = PA_DEVICE_PORT_TYPE_UNKNOWN;
+ id = s = pa_xstrdup(device_name);
+ while (s && *s && isalpha(*s)) s++;
+ if (s)
+ *s = '\0';
+ for (i = 0; types[i].prefix; i++)
+ if (pa_streq(id, types[i].prefix)) {
+ device->type = types[i].type;
+ break;
+ }
+ pa_xfree(id);
+
+ /* set properties */
+ for (i = 0; item[i].id; i++) {
+ id = pa_sprintf_malloc("%s/%s", item[i].id, device_name);
+ err = snd_use_case_get(uc_mgr, id, &value);
+ pa_xfree(id);
+ if (err < 0)
+ continue;
+
+ pa_log_debug("Got %s for device %s: %s", item[i].id, device_name, value);
+ pa_proplist_sets(device->proplist, item[i].property, value);
+ free((void*)value);
+ }
+
+ /* get direction and channels */
+ value = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_PLAYBACK_CHANNELS);
+ if (value) { /* output */
+ /* get channels */
+ if (pa_atou(value, &ui) == 0 && pa_channels_valid(ui))
+ device->playback_channels = ui;
+ else
+ pa_log("UCM playback channels %s for device %s out of range", value, device_name);
+
+ /* get pcm */
+ value = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_SINK);
+ if (!value) /* take pcm from verb playback default */
+ pa_log("UCM playback device %s fetch pcm failed", device_name);
+ }
+
+ if (pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_SINK) &&
+ device->playback_channels == 0) {
+ pa_log_info("UCM file does not specify 'PlaybackChannels' "
+ "for device %s, assuming stereo.", device_name);
+ device->playback_channels = 2;
+ }
+
+ value = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_CAPTURE_CHANNELS);
+ if (value) { /* input */
+ /* get channels */
+ if (pa_atou(value, &ui) == 0 && pa_channels_valid(ui))
+ device->capture_channels = ui;
+ else
+ pa_log("UCM capture channels %s for device %s out of range", value, device_name);
+
+ /* get pcm */
+ value = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_SOURCE);
+ if (!value) /* take pcm from verb capture default */
+ pa_log("UCM capture device %s fetch pcm failed", device_name);
+ }
+
+ if (pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_SOURCE) &&
+ device->capture_channels == 0) {
+ pa_log_info("UCM file does not specify 'CaptureChannels' "
+ "for device %s, assuming stereo.", device_name);
+ device->capture_channels = 2;
+ }
+
+ /* get rate and priority of device */
+ if (device->playback_channels) { /* sink device */
+ /* get rate */
+ if ((value = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_PLAYBACK_RATE))) {
+ if (pa_atou(value, &ui) == 0 && pa_sample_rate_valid(ui)) {
+ pa_log_debug("UCM playback device %s rate %d", device_name, ui);
+ device->playback_rate = ui;
+ } else
+ pa_log_debug("UCM playback device %s has bad rate %s", device_name, value);
+ }
+
+ value = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_PLAYBACK_PRIORITY);
+ if (value) {
+ /* get priority from ucm config */
+ if (pa_atou(value, &ui) == 0)
+ device->playback_priority = ui;
+ else
+ pa_log_debug("UCM playback priority %s for device %s error", value, device_name);
+ }
+
+ vol = ucm_get_mixer_volume(device,
+ PA_ALSA_PROP_UCM_PLAYBACK_MIXER_ELEM,
+ PA_ALSA_PROP_UCM_PLAYBACK_VOLUME,
+ "PlaybackVolume",
+ PA_ALSA_PROP_UCM_PLAYBACK_MASTER_ELEM,
+ PA_ALSA_PROP_UCM_PLAYBACK_MASTER_TYPE);
+ if (vol)
+ pa_hashmap_put(device->playback_volumes, pa_xstrdup(pa_proplist_gets(verb->proplist, PA_ALSA_PROP_UCM_NAME)), vol);
+ }
+
+ if (device->capture_channels) { /* source device */
+ /* get rate */
+ if ((value = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_CAPTURE_RATE))) {
+ if (pa_atou(value, &ui) == 0 && pa_sample_rate_valid(ui)) {
+ pa_log_debug("UCM capture device %s rate %d", device_name, ui);
+ device->capture_rate = ui;
+ } else
+ pa_log_debug("UCM capture device %s has bad rate %s", device_name, value);
+ }
+
+ value = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_CAPTURE_PRIORITY);
+ if (value) {
+ /* get priority from ucm config */
+ if (pa_atou(value, &ui) == 0)
+ device->capture_priority = ui;
+ else
+ pa_log_debug("UCM capture priority %s for device %s error", value, device_name);
+ }
+
+ vol = ucm_get_mixer_volume(device,
+ PA_ALSA_PROP_UCM_CAPTURE_MIXER_ELEM,
+ PA_ALSA_PROP_UCM_CAPTURE_VOLUME,
+ "CaptureVolume",
+ PA_ALSA_PROP_UCM_CAPTURE_MASTER_ELEM,
+ PA_ALSA_PROP_UCM_CAPTURE_MASTER_TYPE);
+ if (vol)
+ pa_hashmap_put(device->capture_volumes, pa_xstrdup(pa_proplist_gets(verb->proplist, PA_ALSA_PROP_UCM_NAME)), vol);
+ }
+
+ if (PA_UCM_PLAYBACK_PRIORITY_UNSET(device) || PA_UCM_CAPTURE_PRIORITY_UNSET(device)) {
+ /* get priority from static table */
+ for (i = 0; dev_info[i].id; i++) {
+ if (strcasecmp(dev_info[i].id, device_name) == 0) {
+ PA_UCM_DEVICE_PRIORITY_SET(device, dev_info[i].priority);
+ break;
+ }
+ }
+ }
+
+ if (PA_UCM_PLAYBACK_PRIORITY_UNSET(device)) {
+ /* fall through to default priority */
+ device->playback_priority = 100;
+ }
+
+ if (PA_UCM_CAPTURE_PRIORITY_UNSET(device)) {
+ /* fall through to default priority */
+ device->capture_priority = 100;
+ }
+
+ id = pa_sprintf_malloc("%s/%s", "_conflictingdevs", device_name);
+ n_confdev = snd_use_case_get_list(uc_mgr, id, &devices);
+ pa_xfree(id);
+
+ if (n_confdev <= 0)
+ pa_log_debug("No %s for device %s", "_conflictingdevs", device_name);
+ else {
+ device->conflicting_devices = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
+ ucm_add_devices_to_idxset(device->conflicting_devices, device, verb->devices, devices, n_confdev);
+ snd_use_case_free_list(devices, n_confdev);
+ }
+
+ id = pa_sprintf_malloc("%s/%s", "_supporteddevs", device_name);
+ n_suppdev = snd_use_case_get_list(uc_mgr, id, &devices);
+ pa_xfree(id);
+
+ if (n_suppdev <= 0)
+ pa_log_debug("No %s for device %s", "_supporteddevs", device_name);
+ else {
+ device->supported_devices = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
+ ucm_add_devices_to_idxset(device->supported_devices, device, verb->devices, devices, n_suppdev);
+ snd_use_case_free_list(devices, n_suppdev);
+ }
+
+ return 0;
+};
+
+/* Create a property list for this ucm modifier */
+static int ucm_get_modifier_property(pa_alsa_ucm_modifier *modifier, snd_use_case_mgr_t *uc_mgr, const char *modifier_name) {
+ const char *value;
+ char *id;
+ int i;
+
+ for (i = 0; item[i].id; i++) {
+ int err;
+
+ id = pa_sprintf_malloc("=%s/%s", item[i].id, modifier_name);
+ err = snd_use_case_get(uc_mgr, id, &value);
+ pa_xfree(id);
+ if (err < 0)
+ continue;
+
+ pa_log_debug("Got %s for modifier %s: %s", item[i].id, modifier_name, value);
+ pa_proplist_sets(modifier->proplist, item[i].property, value);
+ free((void*)value);
+ }
+
+ id = pa_sprintf_malloc("%s/%s", "_conflictingdevs", modifier_name);
+ modifier->n_confdev = snd_use_case_get_list(uc_mgr, id, &modifier->conflicting_devices);
+ pa_xfree(id);
+ if (modifier->n_confdev < 0)
+ pa_log_debug("No %s for modifier %s", "_conflictingdevs", modifier_name);
+
+ id = pa_sprintf_malloc("%s/%s", "_supporteddevs", modifier_name);
+ modifier->n_suppdev = snd_use_case_get_list(uc_mgr, id, &modifier->supported_devices);
+ pa_xfree(id);
+ if (modifier->n_suppdev < 0)
+ pa_log_debug("No %s for modifier %s", "_supporteddevs", modifier_name);
+
+ return 0;
+};
+
+/* Create a list of devices for this verb */
+static int ucm_get_devices(pa_alsa_ucm_verb *verb, snd_use_case_mgr_t *uc_mgr) {
+ const char **dev_list;
+ int num_dev, i;
+
+ num_dev = snd_use_case_get_list(uc_mgr, "_devices", &dev_list);
+ if (num_dev < 0)
+ return num_dev;
+
+ for (i = 0; i < num_dev; i += 2) {
+ pa_alsa_ucm_device *d = pa_xnew0(pa_alsa_ucm_device, 1);
+
+ d->proplist = pa_proplist_new();
+ pa_proplist_sets(d->proplist, PA_ALSA_PROP_UCM_NAME, pa_strnull(dev_list[i]));
+ pa_proplist_sets(d->proplist, PA_ALSA_PROP_UCM_DESCRIPTION, pa_strna(dev_list[i + 1]));
+ d->ucm_ports = pa_dynarray_new(NULL);
+ d->hw_mute_jacks = pa_dynarray_new(NULL);
+ d->available = PA_AVAILABLE_UNKNOWN;
+
+ d->playback_volumes = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func, pa_xfree,
+ (pa_free_cb_t) ucm_volume_free);
+ d->capture_volumes = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func, pa_xfree,
+ (pa_free_cb_t) ucm_volume_free);
+
+ PA_LLIST_PREPEND(pa_alsa_ucm_device, verb->devices, d);
+ }
+
+ snd_use_case_free_list(dev_list, num_dev);
+
+ return 0;
+};
+
+static int ucm_get_modifiers(pa_alsa_ucm_verb *verb, snd_use_case_mgr_t *uc_mgr) {
+ const char **mod_list;
+ int num_mod, i;
+
+ num_mod = snd_use_case_get_list(uc_mgr, "_modifiers", &mod_list);
+ if (num_mod < 0)
+ return num_mod;
+
+ for (i = 0; i < num_mod; i += 2) {
+ pa_alsa_ucm_modifier *m;
+
+ if (!mod_list[i]) {
+ pa_log_warn("Got a modifier with a null name. Skipping.");
+ continue;
+ }
+
+ m = pa_xnew0(pa_alsa_ucm_modifier, 1);
+ m->proplist = pa_proplist_new();
+
+ pa_proplist_sets(m->proplist, PA_ALSA_PROP_UCM_NAME, mod_list[i]);
+ pa_proplist_sets(m->proplist, PA_ALSA_PROP_UCM_DESCRIPTION, pa_strna(mod_list[i + 1]));
+
+ PA_LLIST_PREPEND(pa_alsa_ucm_modifier, verb->modifiers, m);
+ }
+
+ snd_use_case_free_list(mod_list, num_mod);
+
+ return 0;
+};
+
+static void add_role_to_device(pa_alsa_ucm_device *dev, const char *dev_name, const char *role_name, const char *role) {
+ const char *cur = pa_proplist_gets(dev->proplist, role_name);
+
+ if (!cur)
+ pa_proplist_sets(dev->proplist, role_name, role);
+ else if (!pa_str_in_list_spaces(cur, role)) { /* does not exist */
+ char *value = pa_sprintf_malloc("%s %s", cur, role);
+
+ pa_proplist_sets(dev->proplist, role_name, value);
+ pa_xfree(value);
+ }
+
+ pa_log_info("Add role %s to device %s(%s), result %s", role, dev_name, role_name, pa_proplist_gets(dev->proplist,
+ role_name));
+}
+
+static void add_media_role(const char *name, pa_alsa_ucm_device *list, const char *role_name, const char *role, bool is_sink) {
+ pa_alsa_ucm_device *d;
+
+ PA_LLIST_FOREACH(d, list) {
+ const char *dev_name = pa_proplist_gets(d->proplist, PA_ALSA_PROP_UCM_NAME);
+
+ if (pa_streq(dev_name, name)) {
+ const char *sink = pa_proplist_gets(d->proplist, PA_ALSA_PROP_UCM_SINK);
+ const char *source = pa_proplist_gets(d->proplist, PA_ALSA_PROP_UCM_SOURCE);
+
+ if (is_sink && sink)
+ add_role_to_device(d, dev_name, role_name, role);
+ else if (!is_sink && source)
+ add_role_to_device(d, dev_name, role_name, role);
+ break;
+ }
+ }
+}
+
+static char *modifier_name_to_role(const char *mod_name, bool *is_sink) {
+ char *sub = NULL, *tmp;
+
+ *is_sink = false;
+
+ if (pa_startswith(mod_name, "Play")) {
+ *is_sink = true;
+ sub = pa_xstrdup(mod_name + 4);
+ } else if (pa_startswith(mod_name, "Capture"))
+ sub = pa_xstrdup(mod_name + 7);
+
+ if (!sub || !*sub) {
+ pa_xfree(sub);
+ pa_log_warn("Can't match media roles for modifer %s", mod_name);
+ return NULL;
+ }
+
+ tmp = sub;
+
+ do {
+ *tmp = tolower(*tmp);
+ } while (*(++tmp));
+
+ return sub;
+}
+
+static void ucm_set_media_roles(pa_alsa_ucm_modifier *modifier, pa_alsa_ucm_device *list, const char *mod_name) {
+ int i;
+ bool is_sink = false;
+ char *sub = NULL;
+ const char *role_name;
+
+ sub = modifier_name_to_role(mod_name, &is_sink);
+ if (!sub)
+ return;
+
+ modifier->action_direction = is_sink ? PA_DIRECTION_OUTPUT : PA_DIRECTION_INPUT;
+ modifier->media_role = sub;
+
+ role_name = is_sink ? PA_ALSA_PROP_UCM_PLAYBACK_ROLES : PA_ALSA_PROP_UCM_CAPTURE_ROLES;
+ for (i = 0; i < modifier->n_suppdev; i++) {
+ /* if modifier has no specific pcm, we add role intent to its supported devices */
+ if (!pa_proplist_gets(modifier->proplist, PA_ALSA_PROP_UCM_SINK) &&
+ !pa_proplist_gets(modifier->proplist, PA_ALSA_PROP_UCM_SOURCE))
+ add_media_role(modifier->supported_devices[i], list, role_name, sub, is_sink);
+ }
+}
+
+static void append_lost_relationship(pa_alsa_ucm_device *dev) {
+ uint32_t idx;
+ pa_alsa_ucm_device *d;
+
+ if (dev->conflicting_devices) {
+ PA_IDXSET_FOREACH(d, dev->conflicting_devices, idx) {
+ if (!d->conflicting_devices)
+ d->conflicting_devices = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
+
+ if (pa_idxset_put(d->conflicting_devices, dev, NULL) == 0)
+ pa_log_warn("Add lost conflicting device %s to %s",
+ pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_NAME),
+ pa_proplist_gets(d->proplist, PA_ALSA_PROP_UCM_NAME));
+ }
+ }
+
+ if (dev->supported_devices) {
+ PA_IDXSET_FOREACH(d, dev->supported_devices, idx) {
+ if (!d->supported_devices)
+ d->supported_devices = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
+
+ if (pa_idxset_put(d->supported_devices, dev, NULL) == 0)
+ pa_log_warn("Add lost supported device %s to %s",
+ pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_NAME),
+ pa_proplist_gets(d->proplist, PA_ALSA_PROP_UCM_NAME));
+ }
+ }
+}
+
+int pa_alsa_ucm_query_profiles(pa_alsa_ucm_config *ucm, int card_index) {
+ char *card_name;
+ const char **verb_list, *value;
+ int num_verbs, i, err = 0;
+
+ /* support multiple card instances, address card directly by index */
+ card_name = pa_sprintf_malloc("hw:%i", card_index);
+ err = snd_use_case_mgr_open(&ucm->ucm_mgr, card_name);
+ if (err < 0) {
+ /* fallback longname: is UCM available for this card ? */
+ pa_xfree(card_name);
+ err = snd_card_get_name(card_index, &card_name);
+ if (err < 0) {
+ pa_log("Card can't get card_name from card_index %d", card_index);
+ err = -PA_ALSA_ERR_UNSPECIFIED;
+ goto name_fail;
+ }
+
+ err = snd_use_case_mgr_open(&ucm->ucm_mgr, card_name);
+ if (err < 0) {
+ pa_log_info("UCM not available for card %s", card_name);
+ err = -PA_ALSA_ERR_UCM_OPEN;
+ goto ucm_mgr_fail;
+ }
+ }
+
+ err = snd_use_case_get(ucm->ucm_mgr, "=Linked", &value);
+ if (err >= 0) {
+ if (strcasecmp(value, "true") == 0 || strcasecmp(value, "1") == 0) {
+ free((void *)value);
+ pa_log_info("Empty (linked) UCM for card %s", card_name);
+ err = -PA_ALSA_ERR_UCM_LINKED;
+ goto ucm_verb_fail;
+ }
+ free((void *)value);
+ }
+
+ pa_log_info("UCM available for card %s", card_name);
+
+ /* get a list of all UCM verbs (profiles) for this card */
+ num_verbs = snd_use_case_verb_list(ucm->ucm_mgr, &verb_list);
+ if (num_verbs < 0) {
+ pa_log("UCM verb list not found for %s", card_name);
+ err = -PA_ALSA_ERR_UNSPECIFIED;
+ goto ucm_verb_fail;
+ }
+
+ /* get the properties of each UCM verb */
+ for (i = 0; i < num_verbs; i += 2) {
+ pa_alsa_ucm_verb *verb;
+
+ /* Get devices and modifiers for each verb */
+ err = pa_alsa_ucm_get_verb(ucm->ucm_mgr, verb_list[i], verb_list[i+1], &verb);
+ if (err < 0) {
+ pa_log("Failed to get the verb %s", verb_list[i]);
+ continue;
+ }
+
+ PA_LLIST_PREPEND(pa_alsa_ucm_verb, ucm->verbs, verb);
+ }
+
+ if (!ucm->verbs) {
+ pa_log("No UCM verb is valid for %s", card_name);
+ err = -PA_ALSA_ERR_UCM_NO_VERB;
+ }
+
+ snd_use_case_free_list(verb_list, num_verbs);
+
+ucm_verb_fail:
+ if (err < 0) {
+ snd_use_case_mgr_close(ucm->ucm_mgr);
+ ucm->ucm_mgr = NULL;
+ }
+
+ucm_mgr_fail:
+ pa_xfree(card_name);
+
+name_fail:
+ return err;
+}
+
+int pa_alsa_ucm_get_verb(snd_use_case_mgr_t *uc_mgr, const char *verb_name, const char *verb_desc, pa_alsa_ucm_verb **p_verb) {
+ pa_alsa_ucm_device *d;
+ pa_alsa_ucm_modifier *mod;
+ pa_alsa_ucm_verb *verb;
+ char *value;
+ unsigned ui;
+ int err = 0;
+
+ *p_verb = NULL;
+ pa_log_info("Set UCM verb to %s", verb_name);
+ err = snd_use_case_set(uc_mgr, "_verb", verb_name);
+ if (err < 0)
+ return err;
+
+ verb = pa_xnew0(pa_alsa_ucm_verb, 1);
+ verb->proplist = pa_proplist_new();
+
+ pa_proplist_sets(verb->proplist, PA_ALSA_PROP_UCM_NAME, pa_strnull(verb_name));
+ pa_proplist_sets(verb->proplist, PA_ALSA_PROP_UCM_DESCRIPTION, pa_strna(verb_desc));
+
+ value = ucm_verb_value(uc_mgr, verb_name, "Priority");
+ if (value && !pa_atou(value, &ui))
+ verb->priority = ui > 10000 ? 10000 : ui;
+ free(value);
+
+ err = ucm_get_devices(verb, uc_mgr);
+ if (err < 0)
+ pa_log("No UCM devices for verb %s", verb_name);
+
+ err = ucm_get_modifiers(verb, uc_mgr);
+ if (err < 0)
+ pa_log("No UCM modifiers for verb %s", verb_name);
+
+ PA_LLIST_FOREACH(d, verb->devices) {
+ const char *dev_name = pa_proplist_gets(d->proplist, PA_ALSA_PROP_UCM_NAME);
+
+ /* Devices properties */
+ ucm_get_device_property(d, uc_mgr, verb, dev_name);
+ }
+ /* make conflicting or supported device mutual */
+ PA_LLIST_FOREACH(d, verb->devices)
+ append_lost_relationship(d);
+
+ PA_LLIST_FOREACH(mod, verb->modifiers) {
+ const char *mod_name = pa_proplist_gets(mod->proplist, PA_ALSA_PROP_UCM_NAME);
+
+ /* Modifier properties */
+ ucm_get_modifier_property(mod, uc_mgr, mod_name);
+
+ /* Set PA_PROP_DEVICE_INTENDED_ROLES property to devices */
+ pa_log_debug("Set media roles for verb %s, modifier %s", verb_name, mod_name);
+ ucm_set_media_roles(mod, verb->devices, mod_name);
+ }
+
+ *p_verb = verb;
+ return 0;
+}
+
+static int pa_alsa_ucm_device_cmp(const void *a, const void *b) {
+ const pa_alsa_ucm_device *d1 = *(pa_alsa_ucm_device **)a;
+ const pa_alsa_ucm_device *d2 = *(pa_alsa_ucm_device **)b;
+
+ return strcmp(pa_proplist_gets(d1->proplist, PA_ALSA_PROP_UCM_NAME), pa_proplist_gets(d2->proplist, PA_ALSA_PROP_UCM_NAME));
+}
+
+static void set_eld_devices(pa_hashmap *hash)
+{
+ pa_device_port *port;
+ pa_alsa_ucm_port_data *data;
+ pa_alsa_ucm_device *dev;
+ const char *eld_mixer_device_name;
+ void *state;
+ int idx, eld_device;
+
+ PA_HASHMAP_FOREACH(port, hash, state) {
+ data = PA_DEVICE_PORT_DATA(port);
+ eld_mixer_device_name = NULL;
+ eld_device = -1;
+ PA_DYNARRAY_FOREACH(dev, data->devices, idx) {
+ if (dev->eld_device >= 0 && dev->eld_mixer_device_name) {
+ if (eld_device >= 0 && eld_device != dev->eld_device) {
+ pa_log_error("The ELD device is already set!");
+ } else if (eld_mixer_device_name && pa_streq(dev->eld_mixer_device_name, eld_mixer_device_name)) {
+ pa_log_error("The ELD mixer device is already set (%s, %s)!", dev->eld_mixer_device_name, dev->eld_mixer_device_name);
+ } else {
+ eld_mixer_device_name = dev->eld_mixer_device_name;
+ eld_device = dev->eld_device;
+ }
+ }
+ }
+ data->eld_device = eld_device;
+ data->eld_mixer_device_name = pa_xstrdup(eld_mixer_device_name);
+ }
+}
+
+static void probe_volumes(pa_hashmap *hash, bool is_sink, snd_pcm_t *pcm_handle, pa_hashmap *mixers, bool ignore_dB) {
+ pa_device_port *port;
+ pa_alsa_path *path;
+ pa_alsa_ucm_port_data *data;
+ pa_alsa_ucm_device *dev;
+ snd_mixer_t *mixer_handle;
+ const char *profile, *mdev, *mdev2;
+ void *state, *state2;
+ int idx;
+
+ PA_HASHMAP_FOREACH(port, hash, state) {
+ data = PA_DEVICE_PORT_DATA(port);
+
+ mdev = NULL;
+ PA_DYNARRAY_FOREACH(dev, data->devices, idx) {
+ mdev2 = get_mixer_device(dev, is_sink);
+ if (mdev && mdev2 && !pa_streq(mdev, mdev2)) {
+ pa_log_error("Two mixer device names found ('%s', '%s'), using s/w volume", mdev, mdev2);
+ goto fail;
+ }
+ if (mdev2)
+ mdev = mdev2;
+ }
+
+ if (mdev == NULL || !(mixer_handle = pa_alsa_open_mixer_by_name(mixers, mdev, true))) {
+ pa_log_error("Failed to find a working mixer device (%s).", mdev);
+ goto fail;
+ }
+
+ PA_HASHMAP_FOREACH_KV(profile, path, data->paths, state2) {
+ if (pa_alsa_path_probe(path, NULL, mixer_handle, ignore_dB) < 0) {
+ pa_log_warn("Could not probe path: %s, using s/w volume", data->path->name);
+ pa_hashmap_remove(data->paths, profile);
+ } else if (!path->has_volume) {
+ pa_log_warn("Path %s is not a volume control", data->path->name);
+ pa_hashmap_remove(data->paths, profile);
+ } else
+ pa_log_debug("Set up h/w volume using '%s' for %s:%s", path->name, profile, port->name);
+ }
+ }
+
+ return;
+
+fail:
+ /* We could not probe the paths we created. Free them and revert to software volumes. */
+ PA_HASHMAP_FOREACH(port, hash, state) {
+ data = PA_DEVICE_PORT_DATA(port);
+ pa_hashmap_remove_all(data->paths);
+ }
+}
+
+static void ucm_add_port_combination(
+ pa_hashmap *hash,
+ pa_alsa_ucm_mapping_context *context,
+ bool is_sink,
+ pa_alsa_ucm_device **pdevices,
+ int num,
+ pa_hashmap *ports,
+ pa_card_profile *cp,
+ pa_core *core) {
+
+ pa_device_port *port;
+ int i;
+ unsigned priority;
+ double prio2;
+ char *name, *desc;
+ const char *dev_name;
+ const char *direction;
+ const char *profile;
+ pa_alsa_ucm_device *sorted[num], *dev;
+ pa_alsa_ucm_port_data *data;
+ pa_alsa_ucm_volume *vol;
+ pa_alsa_jack *jack, *jack2;
+ pa_device_port_type_t type, type2;
+ void *state;
+
+ for (i = 0; i < num; i++)
+ sorted[i] = pdevices[i];
+
+ /* Sort by alphabetical order so as to have a deterministic naming scheme
+ * for combination ports */
+ qsort(&sorted[0], num, sizeof(pa_alsa_ucm_device *), pa_alsa_ucm_device_cmp);
+
+ dev = sorted[0];
+ dev_name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_NAME);
+
+ name = pa_sprintf_malloc("%s%s", is_sink ? PA_UCM_PRE_TAG_OUTPUT : PA_UCM_PRE_TAG_INPUT, dev_name);
+ desc = num == 1 ? pa_xstrdup(pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_DESCRIPTION))
+ : pa_sprintf_malloc("Combination port for %s", dev_name);
+
+ priority = is_sink ? dev->playback_priority : dev->capture_priority;
+ prio2 = (priority == 0 ? 0 : 1.0/priority);
+ jack = ucm_get_jack(context->ucm, dev);
+ type = dev->type;
+
+ for (i = 1; i < num; i++) {
+ char *tmp;
+
+ dev = sorted[i];
+ dev_name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_NAME);
+
+ tmp = pa_sprintf_malloc("%s+%s", name, dev_name);
+ pa_xfree(name);
+ name = tmp;
+
+ tmp = pa_sprintf_malloc("%s,%s", desc, dev_name);
+ pa_xfree(desc);
+ desc = tmp;
+
+ priority = is_sink ? dev->playback_priority : dev->capture_priority;
+ if (priority != 0 && prio2 > 0)
+ prio2 += 1.0/priority;
+
+ jack2 = ucm_get_jack(context->ucm, dev);
+ if (jack2) {
+ if (jack && jack != jack2)
+ pa_log_warn("Multiple jacks per combined device '%s': '%s' '%s'", name, jack->name, jack2->name);
+ jack = jack2;
+ }
+
+ type2 = dev->type;
+ if (type2 != PA_DEVICE_PORT_TYPE_UNKNOWN) {
+ if (type != PA_DEVICE_PORT_TYPE_UNKNOWN && type != type2)
+ pa_log_warn("Multiple device types per combined device '%s': %d %d", name, type, type2);
+ type = type2;
+ }
+ }
+
+ /* Make combination ports always have lower priority, and use the formula
+ 1/p = 1/p1 + 1/p2 + ... 1/pn.
+ This way, the result will always be less than the individual components,
+ yet higher components will lead to higher result. */
+
+ if (num > 1)
+ priority = prio2 > 0 ? 1.0/prio2 : 0;
+
+ port = pa_hashmap_get(ports, name);
+ if (!port) {
+ pa_device_port_new_data port_data;
+
+ pa_device_port_new_data_init(&port_data);
+ pa_device_port_new_data_set_name(&port_data, name);
+ pa_device_port_new_data_set_description(&port_data, desc);
+ pa_device_port_new_data_set_type(&port_data, type);
+ pa_device_port_new_data_set_direction(&port_data, is_sink ? PA_DIRECTION_OUTPUT : PA_DIRECTION_INPUT);
+ if (jack)
+ pa_device_port_new_data_set_availability_group(&port_data, jack->name);
+
+ port = pa_device_port_new(core, &port_data, sizeof(pa_alsa_ucm_port_data));
+ pa_device_port_new_data_done(&port_data);
+
+ data = PA_DEVICE_PORT_DATA(port);
+ ucm_port_data_init(data, context->ucm, port, pdevices, num);
+ port->impl_free = ucm_port_data_free;
+
+ pa_hashmap_put(ports, port->name, port);
+ pa_log_debug("Add port %s: %s", port->name, port->description);
+
+ if (num == 1) {
+ /* To keep things simple and not worry about stacking controls, we only support hardware volumes on non-combination
+ * ports. */
+ data = PA_DEVICE_PORT_DATA(port);
+
+ PA_HASHMAP_FOREACH_KV(profile, vol, is_sink ? dev->playback_volumes : dev->capture_volumes, state) {
+ pa_alsa_path *path = pa_alsa_path_synthesize(vol->mixer_elem,
+ is_sink ? PA_ALSA_DIRECTION_OUTPUT : PA_ALSA_DIRECTION_INPUT);
+
+ if (!path)
+ pa_log_warn("Failed to set up volume control: %s", vol->mixer_elem);
+ else {
+ if (vol->master_elem) {
+ pa_alsa_element *e = pa_alsa_element_get(path, vol->master_elem, false);
+ e->switch_use = PA_ALSA_SWITCH_MUTE;
+ e->volume_use = PA_ALSA_VOLUME_MERGE;
+ }
+
+ pa_hashmap_put(data->paths, pa_xstrdup(profile), path);
+
+ /* Add path also to already created empty path set */
+ dev = sorted[0];
+ if (is_sink)
+ pa_hashmap_put(dev->playback_mapping->output_path_set->paths, pa_xstrdup(vol->mixer_elem), path);
+ else
+ pa_hashmap_put(dev->capture_mapping->input_path_set->paths, pa_xstrdup(vol->mixer_elem), path);
+ }
+ }
+ }
+ }
+
+ port->priority = priority;
+
+ pa_xfree(name);
+ pa_xfree(desc);
+
+ direction = is_sink ? "output" : "input";
+ pa_log_debug("Port %s direction %s, priority %d", port->name, direction, priority);
+
+ if (cp) {
+ pa_log_debug("Adding profile %s to port %s.", cp->name, port->name);
+ pa_hashmap_put(port->profiles, cp->name, cp);
+ }
+
+ if (hash) {
+ pa_hashmap_put(hash, port->name, port);
+ pa_device_port_ref(port);
+ }
+}
+
+static int ucm_port_contains(const char *port_name, const char *dev_name, bool is_sink) {
+ int ret = 0;
+ const char *r;
+ const char *state = NULL;
+ size_t len;
+
+ if (!port_name || !dev_name)
+ return false;
+
+ port_name += is_sink ? strlen(PA_UCM_PRE_TAG_OUTPUT) : strlen(PA_UCM_PRE_TAG_INPUT);
+
+ while ((r = pa_split_in_place(port_name, "+", &len, &state))) {
+ if (strlen(dev_name) == len && !strncmp(r, dev_name, len)) {
+ ret = 1;
+ break;
+ }
+ }
+
+ return ret;
+}
+
+static int ucm_check_conformance(
+ pa_alsa_ucm_mapping_context *context,
+ pa_alsa_ucm_device **pdevices,
+ int dev_num,
+ pa_alsa_ucm_device *dev) {
+
+ uint32_t idx;
+ pa_alsa_ucm_device *d;
+ int i;
+
+ pa_assert(dev);
+
+ pa_log_debug("Check device %s conformance with %d other devices",
+ pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_NAME), dev_num);
+ if (dev_num == 0) {
+ pa_log_debug("First device in combination, number 1");
+ return 1;
+ }
+
+ if (dev->conflicting_devices) { /* the device defines conflicting devices */
+ PA_IDXSET_FOREACH(d, dev->conflicting_devices, idx) {
+ for (i = 0; i < dev_num; i++) {
+ if (pdevices[i] == d) {
+ pa_log_debug("Conflicting device found");
+ return 0;
+ }
+ }
+ }
+ } else if (dev->supported_devices) { /* the device defines supported devices */
+ for (i = 0; i < dev_num; i++) {
+ if (!ucm_device_exists(dev->supported_devices, pdevices[i])) {
+ pa_log_debug("Supported device not found");
+ return 0;
+ }
+ }
+ } else { /* not support any other devices */
+ pa_log_debug("Not support any other devices");
+ return 0;
+ }
+
+ pa_log_debug("Device added to combination, number %d", dev_num + 1);
+ return 1;
+}
+
+static inline pa_alsa_ucm_device *get_next_device(pa_idxset *idxset, uint32_t *idx) {
+ pa_alsa_ucm_device *dev;
+
+ if (*idx == PA_IDXSET_INVALID)
+ dev = pa_idxset_first(idxset, idx);
+ else
+ dev = pa_idxset_next(idxset, idx);
+
+ return dev;
+}
+
+static void ucm_add_ports_combination(
+ pa_hashmap *hash,
+ pa_alsa_ucm_mapping_context *context,
+ bool is_sink,
+ pa_alsa_ucm_device **pdevices,
+ int dev_num,
+ uint32_t map_index,
+ pa_hashmap *ports,
+ pa_card_profile *cp,
+ pa_core *core) {
+
+ pa_alsa_ucm_device *dev;
+ uint32_t idx = map_index;
+
+ if ((dev = get_next_device(context->ucm_devices, &idx)) == NULL)
+ return;
+
+ /* check if device at map_index can combine with existing devices combination */
+ if (ucm_check_conformance(context, pdevices, dev_num, dev)) {
+ /* add device at map_index to devices combination */
+ pdevices[dev_num] = dev;
+ /* add current devices combination as a new port */
+ ucm_add_port_combination(hash, context, is_sink, pdevices, dev_num + 1, ports, cp, core);
+ /* try more elements combination */
+ ucm_add_ports_combination(hash, context, is_sink, pdevices, dev_num + 1, idx, ports, cp, core);
+ }
+
+ /* try other device with current elements number */
+ ucm_add_ports_combination(hash, context, is_sink, pdevices, dev_num, idx, ports, cp, core);
+}
+
+static char* merge_roles(const char *cur, const char *add) {
+ char *r, *ret;
+ const char *state = NULL;
+
+ if (add == NULL)
+ return pa_xstrdup(cur);
+ else if (cur == NULL)
+ return pa_xstrdup(add);
+
+ ret = pa_xstrdup(cur);
+
+ while ((r = pa_split_spaces(add, &state))) {
+ char *value;
+
+ if (!pa_str_in_list_spaces(ret, r))
+ value = pa_sprintf_malloc("%s %s", ret, r);
+ else {
+ pa_xfree(r);
+ continue;
+ }
+
+ pa_xfree(ret);
+ ret = value;
+ pa_xfree(r);
+ }
+
+ return ret;
+}
+
+void pa_alsa_ucm_add_ports_combination(
+ pa_hashmap *p,
+ pa_alsa_ucm_mapping_context *context,
+ bool is_sink,
+ pa_hashmap *ports,
+ pa_card_profile *cp,
+ pa_core *core) {
+
+ pa_alsa_ucm_device **pdevices;
+
+ pa_assert(context->ucm_devices);
+
+ if (pa_idxset_size(context->ucm_devices) > 0) {
+ pdevices = pa_xnew(pa_alsa_ucm_device *, pa_idxset_size(context->ucm_devices));
+ ucm_add_ports_combination(p, context, is_sink, pdevices, 0, PA_IDXSET_INVALID, ports, cp, core);
+ pa_xfree(pdevices);
+ }
+
+ /* ELD devices */
+ set_eld_devices(ports);
+}
+
+void pa_alsa_ucm_add_ports(
+ pa_hashmap **p,
+ pa_proplist *proplist,
+ pa_alsa_ucm_mapping_context *context,
+ bool is_sink,
+ pa_card *card,
+ snd_pcm_t *pcm_handle,
+ bool ignore_dB) {
+
+ uint32_t idx;
+ char *merged_roles;
+ const char *role_name = is_sink ? PA_ALSA_PROP_UCM_PLAYBACK_ROLES : PA_ALSA_PROP_UCM_CAPTURE_ROLES;
+ pa_alsa_ucm_device *dev;
+ pa_alsa_ucm_modifier *mod;
+ char *tmp;
+
+ pa_assert(p);
+ pa_assert(*p);
+
+ /* add ports first */
+ pa_alsa_ucm_add_ports_combination(*p, context, is_sink, card->ports, NULL, card->core);
+
+ /* now set up volume paths if any */
+ probe_volumes(*p, is_sink, pcm_handle, context->ucm->mixers, ignore_dB);
+
+ /* then set property PA_PROP_DEVICE_INTENDED_ROLES */
+ merged_roles = pa_xstrdup(pa_proplist_gets(proplist, PA_PROP_DEVICE_INTENDED_ROLES));
+ PA_IDXSET_FOREACH(dev, context->ucm_devices, idx) {
+ const char *roles = pa_proplist_gets(dev->proplist, role_name);
+ tmp = merge_roles(merged_roles, roles);
+ pa_xfree(merged_roles);
+ merged_roles = tmp;
+ }
+
+ if (context->ucm_modifiers)
+ PA_IDXSET_FOREACH(mod, context->ucm_modifiers, idx) {
+ tmp = merge_roles(merged_roles, mod->media_role);
+ pa_xfree(merged_roles);
+ merged_roles = tmp;
+ }
+
+ if (merged_roles)
+ pa_proplist_sets(proplist, PA_PROP_DEVICE_INTENDED_ROLES, merged_roles);
+
+ pa_log_info("ALSA device %s roles: %s", pa_proplist_gets(proplist, PA_PROP_DEVICE_STRING), pa_strnull(merged_roles));
+ pa_xfree(merged_roles);
+}
+
+/* Change UCM verb and device to match selected card profile */
+int pa_alsa_ucm_set_profile(pa_alsa_ucm_config *ucm, pa_card *card, const char *new_profile, const char *old_profile) {
+ int ret = 0;
+ const char *profile;
+ pa_alsa_ucm_verb *verb;
+ pa_device_port *port;
+ pa_alsa_ucm_port_data *data;
+ void *state;
+
+ if (new_profile == old_profile)
+ return ret;
+ else if (new_profile == NULL || old_profile == NULL)
+ profile = new_profile ? new_profile : SND_USE_CASE_VERB_INACTIVE;
+ else if (!pa_streq(new_profile, old_profile))
+ profile = new_profile;
+ else
+ return ret;
+
+ /* change verb */
+ pa_log_info("Set UCM verb to %s", profile);
+ if ((snd_use_case_set(ucm->ucm_mgr, "_verb", profile)) < 0) {
+ pa_log("Failed to set verb %s", profile);
+ ret = -1;
+ }
+
+ /* find active verb */
+ ucm->active_verb = NULL;
+ PA_LLIST_FOREACH(verb, ucm->verbs) {
+ const char *verb_name;
+ verb_name = pa_proplist_gets(verb->proplist, PA_ALSA_PROP_UCM_NAME);
+ if (pa_streq(verb_name, profile)) {
+ ucm->active_verb = verb;
+ break;
+ }
+ }
+
+ /* select volume controls on ports */
+ PA_HASHMAP_FOREACH(port, card->ports, state) {
+ data = PA_DEVICE_PORT_DATA(port);
+ data->path = pa_hashmap_get(data->paths, profile);
+ }
+
+ return ret;
+}
+
+int pa_alsa_ucm_set_port(pa_alsa_ucm_mapping_context *context, pa_device_port *port, bool is_sink) {
+ int i;
+ int ret = 0;
+ pa_alsa_ucm_config *ucm;
+ const char **enable_devs;
+ int enable_num = 0;
+ uint32_t idx;
+ pa_alsa_ucm_device *dev;
+
+ pa_assert(context && context->ucm);
+
+ ucm = context->ucm;
+ pa_assert(ucm->ucm_mgr);
+
+ enable_devs = pa_xnew(const char *, pa_idxset_size(context->ucm_devices));
+
+ /* first disable then enable */
+ PA_IDXSET_FOREACH(dev, context->ucm_devices, idx) {
+ const char *dev_name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_NAME);
+
+ if (ucm_port_contains(port->name, dev_name, is_sink))
+ enable_devs[enable_num++] = dev_name;
+ else {
+ pa_log_debug("Disable ucm device %s", dev_name);
+ if (snd_use_case_set(ucm->ucm_mgr, "_disdev", dev_name) > 0) {
+ pa_log("Failed to disable ucm device %s", dev_name);
+ ret = -1;
+ break;
+ }
+ }
+ }
+
+ for (i = 0; i < enable_num; i++) {
+ pa_log_debug("Enable ucm device %s", enable_devs[i]);
+ if (snd_use_case_set(ucm->ucm_mgr, "_enadev", enable_devs[i]) < 0) {
+ pa_log("Failed to enable ucm device %s", enable_devs[i]);
+ ret = -1;
+ break;
+ }
+ }
+
+ pa_xfree(enable_devs);
+
+ return ret;
+}
+
+static void ucm_add_mapping(pa_alsa_profile *p, pa_alsa_mapping *m) {
+
+ pa_alsa_path_set *ps;
+
+ /* create empty path set for the future path additions */
+ ps = pa_xnew0(pa_alsa_path_set, 1);
+ ps->direction = m->direction;
+ ps->paths = pa_hashmap_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
+
+ switch (m->direction) {
+ case PA_ALSA_DIRECTION_ANY:
+ pa_idxset_put(p->output_mappings, m, NULL);
+ pa_idxset_put(p->input_mappings, m, NULL);
+ m->output_path_set = ps;
+ m->input_path_set = ps;
+ break;
+ case PA_ALSA_DIRECTION_OUTPUT:
+ pa_idxset_put(p->output_mappings, m, NULL);
+ m->output_path_set = ps;
+ break;
+ case PA_ALSA_DIRECTION_INPUT:
+ pa_idxset_put(p->input_mappings, m, NULL);
+ m->input_path_set = ps;
+ break;
+ }
+}
+
+static void alsa_mapping_add_ucm_device(pa_alsa_mapping *m, pa_alsa_ucm_device *device) {
+ char *cur_desc;
+ const char *new_desc, *mdev;
+ bool is_sink = m->direction == PA_ALSA_DIRECTION_OUTPUT;
+
+ pa_idxset_put(m->ucm_context.ucm_devices, device, NULL);
+
+ new_desc = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_DESCRIPTION);
+ cur_desc = m->description;
+ if (cur_desc)
+ m->description = pa_sprintf_malloc("%s + %s", cur_desc, new_desc);
+ else
+ m->description = pa_xstrdup(new_desc);
+ pa_xfree(cur_desc);
+
+ /* walk around null case */
+ m->description = m->description ? m->description : pa_xstrdup("");
+
+ /* save mapping to ucm device */
+ if (is_sink)
+ device->playback_mapping = m;
+ else
+ device->capture_mapping = m;
+
+ mdev = get_mixer_device(device, is_sink);
+ if (mdev)
+ pa_proplist_sets(m->proplist, "alsa.mixer_device", mdev);
+}
+
+static void alsa_mapping_add_ucm_modifier(pa_alsa_mapping *m, pa_alsa_ucm_modifier *modifier) {
+ char *cur_desc;
+ const char *new_desc, *mod_name, *channel_str;
+ uint32_t channels = 0;
+
+ pa_idxset_put(m->ucm_context.ucm_modifiers, modifier, NULL);
+
+ new_desc = pa_proplist_gets(modifier->proplist, PA_ALSA_PROP_UCM_DESCRIPTION);
+ cur_desc = m->description;
+ if (cur_desc)
+ m->description = pa_sprintf_malloc("%s + %s", cur_desc, new_desc);
+ else
+ m->description = pa_xstrdup(new_desc);
+ pa_xfree(cur_desc);
+
+ m->description = m->description ? m->description : pa_xstrdup("");
+
+ /* Modifier sinks should not be routed to by default */
+ m->priority = 0;
+
+ mod_name = pa_proplist_gets(modifier->proplist, PA_ALSA_PROP_UCM_NAME);
+ pa_proplist_sets(m->proplist, PA_ALSA_PROP_UCM_MODIFIER, mod_name);
+
+ /* save mapping to ucm modifier */
+ if (m->direction == PA_ALSA_DIRECTION_OUTPUT) {
+ modifier->playback_mapping = m;
+ channel_str = pa_proplist_gets(modifier->proplist, PA_ALSA_PROP_UCM_PLAYBACK_CHANNELS);
+ } else {
+ modifier->capture_mapping = m;
+ channel_str = pa_proplist_gets(modifier->proplist, PA_ALSA_PROP_UCM_CAPTURE_CHANNELS);
+ }
+
+ if (channel_str) {
+ /* FIXME: channel_str is unsanitized input from the UCM configuration,
+ * we should do proper error handling instead of asserting.
+ * https://bugs.freedesktop.org/show_bug.cgi?id=71823 */
+ pa_assert_se(pa_atou(channel_str, &channels) == 0 && pa_channels_valid(channels));
+ pa_log_debug("Got channel count %" PRIu32 " for modifier", channels);
+ }
+
+ if (channels)
+ pa_channel_map_init_extend(&m->channel_map, channels, PA_CHANNEL_MAP_ALSA);
+ else
+ pa_channel_map_init(&m->channel_map);
+}
+
+static int ucm_create_mapping_direction(
+ pa_alsa_ucm_config *ucm,
+ pa_alsa_profile_set *ps,
+ pa_alsa_profile *p,
+ pa_alsa_ucm_device *device,
+ const char *verb_name,
+ const char *device_name,
+ const char *device_str,
+ bool is_sink) {
+
+ pa_alsa_mapping *m;
+ char *mapping_name;
+ unsigned priority, rate, channels;
+
+ mapping_name = pa_sprintf_malloc("Mapping %s: %s: %s", verb_name, device_str, is_sink ? "sink" : "source");
+
+ m = pa_alsa_mapping_get(ps, mapping_name);
+ if (!m) {
+ pa_log("No mapping for %s", mapping_name);
+ pa_xfree(mapping_name);
+ return -1;
+ }
+ pa_log_debug("UCM mapping: %s dev %s", mapping_name, device_name);
+ pa_xfree(mapping_name);
+
+ priority = is_sink ? device->playback_priority : device->capture_priority;
+ rate = is_sink ? device->playback_rate : device->capture_rate;
+ channels = is_sink ? device->playback_channels : device->capture_channels;
+
+ if (!m->ucm_context.ucm_devices) { /* new mapping */
+ m->ucm_context.ucm_devices = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
+ m->ucm_context.ucm = ucm;
+ m->ucm_context.direction = is_sink ? PA_DIRECTION_OUTPUT : PA_DIRECTION_INPUT;
+
+ m->device_strings = pa_xnew0(char*, 2);
+ m->device_strings[0] = pa_xstrdup(device_str);
+ m->direction = is_sink ? PA_ALSA_DIRECTION_OUTPUT : PA_ALSA_DIRECTION_INPUT;
+
+ ucm_add_mapping(p, m);
+ if (rate)
+ m->sample_spec.rate = rate;
+ pa_channel_map_init_extend(&m->channel_map, channels, PA_CHANNEL_MAP_ALSA);
+ }
+
+ /* mapping priority is the highest one of ucm devices */
+ if (priority > m->priority)
+ m->priority = priority;
+
+ /* mapping channels is the lowest one of ucm devices */
+ if (channels < m->channel_map.channels)
+ pa_channel_map_init_extend(&m->channel_map, channels, PA_CHANNEL_MAP_ALSA);
+
+ alsa_mapping_add_ucm_device(m, device);
+
+ return 0;
+}
+
+static int ucm_create_mapping_for_modifier(
+ pa_alsa_ucm_config *ucm,
+ pa_alsa_profile_set *ps,
+ pa_alsa_profile *p,
+ pa_alsa_ucm_modifier *modifier,
+ const char *verb_name,
+ const char *mod_name,
+ const char *device_str,
+ bool is_sink) {
+
+ pa_alsa_mapping *m;
+ char *mapping_name;
+
+ mapping_name = pa_sprintf_malloc("Mapping %s: %s: %s", verb_name, device_str, is_sink ? "sink" : "source");
+
+ m = pa_alsa_mapping_get(ps, mapping_name);
+ if (!m) {
+ pa_log("no mapping for %s", mapping_name);
+ pa_xfree(mapping_name);
+ return -1;
+ }
+ pa_log_info("ucm mapping: %s modifier %s", mapping_name, mod_name);
+ pa_xfree(mapping_name);
+
+ if (!m->ucm_context.ucm_devices && !m->ucm_context.ucm_modifiers) { /* new mapping */
+ m->ucm_context.ucm_devices = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
+ m->ucm_context.ucm_modifiers = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
+ m->ucm_context.ucm = ucm;
+ m->ucm_context.direction = is_sink ? PA_DIRECTION_OUTPUT : PA_DIRECTION_INPUT;
+
+ m->device_strings = pa_xnew0(char*, 2);
+ m->device_strings[0] = pa_xstrdup(device_str);
+ m->direction = is_sink ? PA_ALSA_DIRECTION_OUTPUT : PA_ALSA_DIRECTION_INPUT;
+ /* Modifier sinks should not be routed to by default */
+ m->priority = 0;
+
+ ucm_add_mapping(p, m);
+ } else if (!m->ucm_context.ucm_modifiers) /* share pcm with device */
+ m->ucm_context.ucm_modifiers = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
+
+ alsa_mapping_add_ucm_modifier(m, modifier);
+
+ return 0;
+}
+
+static int ucm_create_mapping(
+ pa_alsa_ucm_config *ucm,
+ pa_alsa_profile_set *ps,
+ pa_alsa_profile *p,
+ pa_alsa_ucm_device *device,
+ const char *verb_name,
+ const char *device_name,
+ const char *sink,
+ const char *source) {
+
+ int ret = 0;
+
+ if (!sink && !source) {
+ pa_log("No sink and source at %s: %s", verb_name, device_name);
+ return -1;
+ }
+
+ if (sink)
+ ret = ucm_create_mapping_direction(ucm, ps, p, device, verb_name, device_name, sink, true);
+ if (ret == 0 && source)
+ ret = ucm_create_mapping_direction(ucm, ps, p, device, verb_name, device_name, source, false);
+
+ return ret;
+}
+
+static pa_alsa_jack* ucm_get_jack(pa_alsa_ucm_config *ucm, pa_alsa_ucm_device *device) {
+ pa_alsa_jack *j;
+ const char *device_name;
+ const char *jack_control;
+ const char *mixer_device_name;
+ char *name;
+
+ pa_assert(ucm);
+ pa_assert(device);
+
+ device_name = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_NAME);
+
+ jack_control = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_JACK_CONTROL);
+ if (jack_control) {
+#if SND_LIB_VERSION >= 0x10201
+ snd_ctl_elem_id_t *ctl;
+ int err, index;
+ snd_ctl_elem_id_alloca(&ctl);
+ err = snd_use_case_parse_ctl_elem_id(ctl, "JackControl", jack_control);
+ if (err < 0)
+ return NULL;
+ jack_control = snd_ctl_elem_id_get_name(ctl);
+ index = snd_ctl_elem_id_get_index(ctl);
+ if (index > 0) {
+ pa_log("[%s] Invalid JackControl index value: \"%s\",%d", device_name, jack_control, index);
+ return NULL;
+ }
+#else
+#warning "Upgrade to alsa-lib 1.2.1!"
+#endif
+ if (!pa_endswith(jack_control, " Jack")) {
+ pa_log("[%s] Invalid JackControl value: \"%s\"", device_name, jack_control);
+ return NULL;
+ }
+
+ /* pa_alsa_jack_new() expects a jack name without " Jack" at the
+ * end, so drop the trailing " Jack". */
+ name = pa_xstrndup(jack_control, strlen(jack_control) - 5);
+ } else {
+ /* The jack control hasn't been explicitly configured, fail. */
+ return NULL;
+ }
+
+ PA_LLIST_FOREACH(j, ucm->jacks)
+ if (pa_streq(j->name, name))
+ goto finish;
+
+ mixer_device_name = get_jack_mixer_device(device, true);
+ if (!mixer_device_name)
+ mixer_device_name = get_jack_mixer_device(device, false);
+ if (!mixer_device_name) {
+ pa_log("[%s] No mixer device name for JackControl \"%s\"", device_name, jack_control);
+ return NULL;
+ }
+ j = pa_alsa_jack_new(NULL, mixer_device_name, name, 0);
+ PA_LLIST_PREPEND(pa_alsa_jack, ucm->jacks, j);
+
+finish:
+ pa_xfree(name);
+
+ return j;
+}
+
+static int ucm_create_profile(
+ pa_alsa_ucm_config *ucm,
+ pa_alsa_profile_set *ps,
+ pa_alsa_ucm_verb *verb,
+ const char *verb_name,
+ const char *verb_desc) {
+
+ pa_alsa_profile *p;
+ pa_alsa_ucm_device *dev;
+ pa_alsa_ucm_modifier *mod;
+ int i = 0;
+ const char *name, *sink, *source;
+ unsigned int priority;
+
+ pa_assert(ps);
+
+ if (pa_hashmap_get(ps->profiles, verb_name)) {
+ pa_log("Verb %s already exists", verb_name);
+ return -1;
+ }
+
+ p = pa_xnew0(pa_alsa_profile, 1);
+ p->profile_set = ps;
+ p->name = pa_xstrdup(verb_name);
+ p->description = pa_xstrdup(verb_desc);
+
+ p->output_mappings = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
+ p->input_mappings = pa_idxset_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
+
+ p->supported = true;
+ pa_hashmap_put(ps->profiles, p->name, p);
+
+ /* TODO: get profile priority from policy management */
+ priority = verb->priority;
+
+ if (priority == 0) {
+ char *verb_cmp, *c;
+ c = verb_cmp = pa_xstrdup(verb_name);
+ while (*c) {
+ if (*c == '_') *c = ' ';
+ c++;
+ }
+ for (i = 0; verb_info[i].id; i++) {
+ if (strcasecmp(verb_info[i].id, verb_cmp) == 0) {
+ priority = verb_info[i].priority;
+ break;
+ }
+ }
+ pa_xfree(verb_cmp);
+ }
+
+ p->priority = priority;
+
+ PA_LLIST_FOREACH(dev, verb->devices) {
+ pa_alsa_jack *jack;
+ const char *jack_hw_mute;
+
+ name = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_NAME);
+
+ sink = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_SINK);
+ source = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_SOURCE);
+
+ ucm_create_mapping(ucm, ps, p, dev, verb_name, name, sink, source);
+
+ jack = ucm_get_jack(ucm, dev);
+ if (jack)
+ device_set_jack(dev, jack);
+
+ /* JackHWMute contains a list of device names. Each listed device must
+ * be associated with the jack object that we just created. */
+ jack_hw_mute = pa_proplist_gets(dev->proplist, PA_ALSA_PROP_UCM_JACK_HW_MUTE);
+ if (jack_hw_mute && !jack) {
+ pa_log("[%s] JackHWMute set, but JackControl is missing", name);
+ jack_hw_mute = NULL;
+ }
+ if (jack_hw_mute) {
+ char *hw_mute_device_name;
+ const char *state = NULL;
+
+ while ((hw_mute_device_name = ucm_split_devnames(jack_hw_mute, &state))) {
+ pa_alsa_ucm_verb *verb2;
+ bool device_found = false;
+
+ /* Search the referenced device from all verbs. If there are
+ * multiple verbs that have a device with this name, we add the
+ * hw mute association to each of those devices. */
+ PA_LLIST_FOREACH(verb2, ucm->verbs) {
+ pa_alsa_ucm_device *hw_mute_device;
+
+ hw_mute_device = verb_find_device(verb2, hw_mute_device_name);
+ if (hw_mute_device) {
+ device_found = true;
+ device_add_hw_mute_jack(hw_mute_device, jack);
+ }
+ }
+
+ if (!device_found)
+ pa_log("[%s] JackHWMute references an unknown device: %s", name, hw_mute_device_name);
+
+ pa_xfree(hw_mute_device_name);
+ }
+ }
+ }
+
+ /* Now find modifiers that have their own PlaybackPCM and create
+ * separate sinks for them. */
+ PA_LLIST_FOREACH(mod, verb->modifiers) {
+ name = pa_proplist_gets(mod->proplist, PA_ALSA_PROP_UCM_NAME);
+
+ sink = pa_proplist_gets(mod->proplist, PA_ALSA_PROP_UCM_SINK);
+ source = pa_proplist_gets(mod->proplist, PA_ALSA_PROP_UCM_SOURCE);
+
+ if (sink)
+ ucm_create_mapping_for_modifier(ucm, ps, p, mod, verb_name, name, sink, true);
+ else if (source)
+ ucm_create_mapping_for_modifier(ucm, ps, p, mod, verb_name, name, source, false);
+ }
+
+ pa_alsa_profile_dump(p);
+
+ return 0;
+}
+
+static void mapping_init_eld(pa_alsa_mapping *m, snd_pcm_t *pcm)
+{
+ pa_alsa_ucm_mapping_context *context = &m->ucm_context;
+ pa_alsa_ucm_device *dev;
+ uint32_t idx;
+ char *mdev;
+ snd_pcm_info_t *info;
+ int pcm_card, pcm_device;
+
+ snd_pcm_info_alloca(&info);
+ if (snd_pcm_info(pcm, info) < 0)
+ return;
+
+ if ((pcm_card = snd_pcm_info_get_card(info)) < 0)
+ return;
+ if ((pcm_device = snd_pcm_info_get_device(info)) < 0)
+ return;
+
+ PA_IDXSET_FOREACH(dev, context->ucm_devices, idx) {
+ mdev = pa_sprintf_malloc("hw:%i", pcm_card);
+ if (mdev == NULL)
+ continue;
+ dev->eld_mixer_device_name = mdev;
+ dev->eld_device = pcm_device;
+ }
+}
+
+static snd_pcm_t* mapping_open_pcm(pa_alsa_ucm_config *ucm, pa_alsa_mapping *m, int mode) {
+ snd_pcm_t* pcm;
+ pa_sample_spec try_ss = ucm->core->default_sample_spec;
+ pa_channel_map try_map;
+ snd_pcm_uframes_t try_period_size, try_buffer_size;
+ bool exact_channels = m->channel_map.channels > 0;
+
+ if (exact_channels) {
+ try_map = m->channel_map;
+ try_ss.channels = try_map.channels;
+ } else
+ pa_channel_map_init_extend(&try_map, try_ss.channels, PA_CHANNEL_MAP_ALSA);
+
+ try_period_size =
+ pa_usec_to_bytes(ucm->core->default_fragment_size_msec * PA_USEC_PER_MSEC, &try_ss) /
+ pa_frame_size(&try_ss);
+ try_buffer_size = ucm->core->default_n_fragments * try_period_size;
+
+ pcm = pa_alsa_open_by_device_string(m->device_strings[0], NULL, &try_ss,
+ &try_map, mode, &try_period_size, &try_buffer_size, 0, NULL, NULL, exact_channels);
+
+ if (pcm) {
+ if (!exact_channels)
+ m->channel_map = try_map;
+ mapping_init_eld(m, pcm);
+ }
+
+ return pcm;
+}
+
+static void profile_finalize_probing(pa_alsa_profile *p) {
+ pa_alsa_mapping *m;
+ uint32_t idx;
+
+ PA_IDXSET_FOREACH(m, p->output_mappings, idx) {
+ if (p->supported)
+ m->supported++;
+
+ if (!m->output_pcm)
+ continue;
+
+ snd_pcm_close(m->output_pcm);
+ m->output_pcm = NULL;
+ }
+
+ PA_IDXSET_FOREACH(m, p->input_mappings, idx) {
+ if (p->supported)
+ m->supported++;
+
+ if (!m->input_pcm)
+ continue;
+
+ snd_pcm_close(m->input_pcm);
+ m->input_pcm = NULL;
+ }
+}
+
+static void ucm_mapping_jack_probe(pa_alsa_mapping *m, pa_hashmap *mixers) {
+ snd_mixer_t *mixer_handle;
+ pa_alsa_ucm_mapping_context *context = &m->ucm_context;
+ pa_alsa_ucm_device *dev;
+ uint32_t idx;
+
+ PA_IDXSET_FOREACH(dev, context->ucm_devices, idx) {
+ bool has_control;
+
+ if (!dev->jack || !dev->jack->mixer_device_name)
+ continue;
+
+ mixer_handle = pa_alsa_open_mixer_by_name(mixers, dev->jack->mixer_device_name, true);
+ if (!mixer_handle) {
+ pa_log_error("Unable to determine open mixer device '%s' for jack %s", dev->jack->mixer_device_name, dev->jack->name);
+ continue;
+ }
+
+ has_control = pa_alsa_mixer_find_card(mixer_handle, &dev->jack->alsa_id, 0) != NULL;
+ pa_alsa_jack_set_has_control(dev->jack, has_control);
+ pa_log_info("UCM jack %s has_control=%d", dev->jack->name, dev->jack->has_control);
+ }
+}
+
+static void ucm_probe_profile_set(pa_alsa_ucm_config *ucm, pa_alsa_profile_set *ps) {
+ void *state;
+ pa_alsa_profile *p;
+ pa_alsa_mapping *m;
+ uint32_t idx;
+
+ PA_HASHMAP_FOREACH(p, ps->profiles, state) {
+ /* change verb */
+ pa_log_info("Set ucm verb to %s", p->name);
+
+ if ((snd_use_case_set(ucm->ucm_mgr, "_verb", p->name)) < 0) {
+ pa_log("Failed to set verb %s", p->name);
+ p->supported = false;
+ continue;
+ }
+
+ PA_IDXSET_FOREACH(m, p->output_mappings, idx) {
+ if (PA_UCM_IS_MODIFIER_MAPPING(m)) {
+ /* Skip jack probing on modifier PCMs since we expect this to
+ * only be controlled on the main device/verb PCM. */
+ continue;
+ }
+
+ m->output_pcm = mapping_open_pcm(ucm, m, SND_PCM_STREAM_PLAYBACK);
+ if (!m->output_pcm) {
+ p->supported = false;
+ break;
+ }
+ }
+
+ if (p->supported) {
+ PA_IDXSET_FOREACH(m, p->input_mappings, idx) {
+ if (PA_UCM_IS_MODIFIER_MAPPING(m)) {
+ /* Skip jack probing on modifier PCMs since we expect this to
+ * only be controlled on the main device/verb PCM. */
+ continue;
+ }
+
+ m->input_pcm = mapping_open_pcm(ucm, m, SND_PCM_STREAM_CAPTURE);
+ if (!m->input_pcm) {
+ p->supported = false;
+ break;
+ }
+ }
+ }
+
+ if (!p->supported) {
+ profile_finalize_probing(p);
+ continue;
+ }
+
+ pa_log_debug("Profile %s supported.", p->name);
+
+ PA_IDXSET_FOREACH(m, p->output_mappings, idx)
+ if (!PA_UCM_IS_MODIFIER_MAPPING(m))
+ ucm_mapping_jack_probe(m, ucm->mixers);
+
+ PA_IDXSET_FOREACH(m, p->input_mappings, idx)
+ if (!PA_UCM_IS_MODIFIER_MAPPING(m))
+ ucm_mapping_jack_probe(m, ucm->mixers);
+
+ profile_finalize_probing(p);
+ }
+
+ /* restore ucm state */
+ snd_use_case_set(ucm->ucm_mgr, "_verb", SND_USE_CASE_VERB_INACTIVE);
+
+ pa_alsa_profile_set_drop_unsupported(ps);
+}
+
+pa_alsa_profile_set* pa_alsa_ucm_add_profile_set(pa_alsa_ucm_config *ucm, pa_channel_map *default_channel_map) {
+ pa_alsa_ucm_verb *verb;
+ pa_alsa_profile_set *ps;
+
+ ps = pa_xnew0(pa_alsa_profile_set, 1);
+ ps->mappings = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
+ ps->profiles = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
+ ps->decibel_fixes = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
+
+ /* create a profile for each verb */
+ PA_LLIST_FOREACH(verb, ucm->verbs) {
+ const char *verb_name;
+ const char *verb_desc;
+
+ verb_name = pa_proplist_gets(verb->proplist, PA_ALSA_PROP_UCM_NAME);
+ verb_desc = pa_proplist_gets(verb->proplist, PA_ALSA_PROP_UCM_DESCRIPTION);
+ if (verb_name == NULL) {
+ pa_log("Verb with no name");
+ continue;
+ }
+
+ ucm_create_profile(ucm, ps, verb, verb_name, verb_desc);
+ }
+
+ ucm_probe_profile_set(ucm, ps);
+ ps->probed = true;
+
+ return ps;
+}
+
+static void free_verb(pa_alsa_ucm_verb *verb) {
+ pa_alsa_ucm_device *di, *dn;
+ pa_alsa_ucm_modifier *mi, *mn;
+
+ PA_LLIST_FOREACH_SAFE(di, dn, verb->devices) {
+ PA_LLIST_REMOVE(pa_alsa_ucm_device, verb->devices, di);
+
+ if (di->hw_mute_jacks)
+ pa_dynarray_free(di->hw_mute_jacks);
+
+ if (di->ucm_ports)
+ pa_dynarray_free(di->ucm_ports);
+
+ if (di->playback_volumes)
+ pa_hashmap_free(di->playback_volumes);
+ if (di->capture_volumes)
+ pa_hashmap_free(di->capture_volumes);
+
+ pa_proplist_free(di->proplist);
+
+ if (di->conflicting_devices)
+ pa_idxset_free(di->conflicting_devices, NULL);
+ if (di->supported_devices)
+ pa_idxset_free(di->supported_devices, NULL);
+
+ pa_xfree(di->eld_mixer_device_name);
+
+ pa_xfree(di);
+ }
+
+ PA_LLIST_FOREACH_SAFE(mi, mn, verb->modifiers) {
+ PA_LLIST_REMOVE(pa_alsa_ucm_modifier, verb->modifiers, mi);
+ pa_proplist_free(mi->proplist);
+ if (mi->n_suppdev > 0)
+ snd_use_case_free_list(mi->supported_devices, mi->n_suppdev);
+ if (mi->n_confdev > 0)
+ snd_use_case_free_list(mi->conflicting_devices, mi->n_confdev);
+ pa_xfree(mi->media_role);
+ pa_xfree(mi);
+ }
+ pa_proplist_free(verb->proplist);
+ pa_xfree(verb);
+}
+
+static pa_alsa_ucm_device *verb_find_device(pa_alsa_ucm_verb *verb, const char *device_name) {
+ pa_alsa_ucm_device *device;
+
+ pa_assert(verb);
+ pa_assert(device_name);
+
+ PA_LLIST_FOREACH(device, verb->devices) {
+ const char *name;
+
+ name = pa_proplist_gets(device->proplist, PA_ALSA_PROP_UCM_NAME);
+ if (pa_streq(name, device_name))
+ return device;
+ }
+
+ return NULL;
+}
+
+void pa_alsa_ucm_free(pa_alsa_ucm_config *ucm) {
+ pa_alsa_ucm_verb *vi, *vn;
+ pa_alsa_jack *ji, *jn;
+
+ PA_LLIST_FOREACH_SAFE(vi, vn, ucm->verbs) {
+ PA_LLIST_REMOVE(pa_alsa_ucm_verb, ucm->verbs, vi);
+ free_verb(vi);
+ }
+ PA_LLIST_FOREACH_SAFE(ji, jn, ucm->jacks) {
+ PA_LLIST_REMOVE(pa_alsa_jack, ucm->jacks, ji);
+ pa_alsa_jack_free(ji);
+ }
+ if (ucm->ucm_mgr) {
+ snd_use_case_mgr_close(ucm->ucm_mgr);
+ ucm->ucm_mgr = NULL;
+ }
+}
+
+void pa_alsa_ucm_mapping_context_free(pa_alsa_ucm_mapping_context *context) {
+ pa_alsa_ucm_device *dev;
+ pa_alsa_ucm_modifier *mod;
+ uint32_t idx;
+
+ if (context->ucm_devices) {
+ /* clear ucm device pointer to mapping */
+ PA_IDXSET_FOREACH(dev, context->ucm_devices, idx) {
+ if (context->direction == PA_DIRECTION_OUTPUT)
+ dev->playback_mapping = NULL;
+ else
+ dev->capture_mapping = NULL;
+ }
+
+ pa_idxset_free(context->ucm_devices, NULL);
+ }
+
+ if (context->ucm_modifiers) {
+ PA_IDXSET_FOREACH(mod, context->ucm_modifiers, idx) {
+ if (context->direction == PA_DIRECTION_OUTPUT)
+ mod->playback_mapping = NULL;
+ else
+ mod->capture_mapping = NULL;
+ }
+
+ pa_idxset_free(context->ucm_modifiers, NULL);
+ }
+}
+
+/* Enable the modifier when the first stream with matched role starts */
+void pa_alsa_ucm_roled_stream_begin(pa_alsa_ucm_config *ucm, const char *role, pa_direction_t dir) {
+ pa_alsa_ucm_modifier *mod;
+
+ if (!ucm->active_verb)
+ return;
+
+ PA_LLIST_FOREACH(mod, ucm->active_verb->modifiers) {
+ if ((mod->action_direction == dir) && (pa_streq(mod->media_role, role))) {
+ if (mod->enabled_counter == 0) {
+ const char *mod_name = pa_proplist_gets(mod->proplist, PA_ALSA_PROP_UCM_NAME);
+
+ pa_log_info("Enable ucm modifier %s", mod_name);
+ if (snd_use_case_set(ucm->ucm_mgr, "_enamod", mod_name) < 0) {
+ pa_log("Failed to enable ucm modifier %s", mod_name);
+ }
+ }
+
+ mod->enabled_counter++;
+ break;
+ }
+ }
+}
+
+/* Disable the modifier when the last stream with matched role ends */
+void pa_alsa_ucm_roled_stream_end(pa_alsa_ucm_config *ucm, const char *role, pa_direction_t dir) {
+ pa_alsa_ucm_modifier *mod;
+
+ if (!ucm->active_verb)
+ return;
+
+ PA_LLIST_FOREACH(mod, ucm->active_verb->modifiers) {
+ if ((mod->action_direction == dir) && (pa_streq(mod->media_role, role))) {
+
+ mod->enabled_counter--;
+ if (mod->enabled_counter == 0) {
+ const char *mod_name = pa_proplist_gets(mod->proplist, PA_ALSA_PROP_UCM_NAME);
+
+ pa_log_info("Disable ucm modifier %s", mod_name);
+ if (snd_use_case_set(ucm->ucm_mgr, "_dismod", mod_name) < 0) {
+ pa_log("Failed to disable ucm modifier %s", mod_name);
+ }
+ }
+
+ break;
+ }
+ }
+}
+
+static void device_add_ucm_port(pa_alsa_ucm_device *device, pa_alsa_ucm_port_data *port) {
+ pa_assert(device);
+ pa_assert(port);
+
+ pa_dynarray_append(device->ucm_ports, port);
+}
+
+static void device_set_jack(pa_alsa_ucm_device *device, pa_alsa_jack *jack) {
+ pa_assert(device);
+ pa_assert(jack);
+
+ device->jack = jack;
+ pa_alsa_jack_add_ucm_device(jack, device);
+
+ pa_alsa_ucm_device_update_available(device);
+}
+
+static void device_add_hw_mute_jack(pa_alsa_ucm_device *device, pa_alsa_jack *jack) {
+ pa_assert(device);
+ pa_assert(jack);
+
+ pa_dynarray_append(device->hw_mute_jacks, jack);
+ pa_alsa_jack_add_ucm_hw_mute_device(jack, device);
+
+ pa_alsa_ucm_device_update_available(device);
+}
+
+static void device_set_available(pa_alsa_ucm_device *device, pa_available_t available) {
+ pa_alsa_ucm_port_data *port;
+ unsigned idx;
+
+ pa_assert(device);
+
+ if (available == device->available)
+ return;
+
+ device->available = available;
+
+ PA_DYNARRAY_FOREACH(port, device->ucm_ports, idx)
+ ucm_port_update_available(port);
+}
+
+void pa_alsa_ucm_device_update_available(pa_alsa_ucm_device *device) {
+ pa_available_t available = PA_AVAILABLE_UNKNOWN;
+ pa_alsa_jack *jack;
+ unsigned idx;
+
+ pa_assert(device);
+
+ if (device->jack && device->jack->has_control)
+ available = device->jack->plugged_in ? PA_AVAILABLE_YES : PA_AVAILABLE_NO;
+
+ PA_DYNARRAY_FOREACH(jack, device->hw_mute_jacks, idx) {
+ if (jack->plugged_in) {
+ available = PA_AVAILABLE_NO;
+ break;
+ }
+ }
+
+ device_set_available(device, available);
+}
+
+static void ucm_port_data_init(pa_alsa_ucm_port_data *port, pa_alsa_ucm_config *ucm, pa_device_port *core_port,
+ pa_alsa_ucm_device **devices, unsigned n_devices) {
+ unsigned i;
+
+ pa_assert(ucm);
+ pa_assert(core_port);
+ pa_assert(devices);
+
+ port->ucm = ucm;
+ port->core_port = core_port;
+ port->devices = pa_dynarray_new(NULL);
+ port->eld_device = -1;
+
+ for (i = 0; i < n_devices; i++) {
+ pa_dynarray_append(port->devices, devices[i]);
+ device_add_ucm_port(devices[i], port);
+ }
+
+ port->paths = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func, pa_xfree,
+ (pa_free_cb_t) pa_alsa_path_free);
+
+ ucm_port_update_available(port);
+}
+
+static void ucm_port_data_free(pa_device_port *port) {
+ pa_alsa_ucm_port_data *ucm_port;
+
+ pa_assert(port);
+
+ ucm_port = PA_DEVICE_PORT_DATA(port);
+
+ if (ucm_port->devices)
+ pa_dynarray_free(ucm_port->devices);
+
+ if (ucm_port->paths)
+ pa_hashmap_free(ucm_port->paths);
+
+ pa_xfree(ucm_port->eld_mixer_device_name);
+}
+
+static void ucm_port_update_available(pa_alsa_ucm_port_data *port) {
+ pa_alsa_ucm_device *device;
+ unsigned idx;
+ pa_available_t available = PA_AVAILABLE_YES;
+
+ pa_assert(port);
+
+ PA_DYNARRAY_FOREACH(device, port->devices, idx) {
+ if (device->available == PA_AVAILABLE_UNKNOWN)
+ available = PA_AVAILABLE_UNKNOWN;
+ else if (device->available == PA_AVAILABLE_NO) {
+ available = PA_AVAILABLE_NO;
+ break;
+ }
+ }
+
+ pa_device_port_set_available(port->core_port, available);
+}
+
+#else /* HAVE_ALSA_UCM */
+
+/* Dummy functions for systems without UCM support */
+
+int pa_alsa_ucm_query_profiles(pa_alsa_ucm_config *ucm, int card_index) {
+ pa_log_info("UCM not available.");
+ return -1;
+}
+
+pa_alsa_profile_set* pa_alsa_ucm_add_profile_set(pa_alsa_ucm_config *ucm, pa_channel_map *default_channel_map) {
+ return NULL;
+}
+
+int pa_alsa_ucm_set_profile(pa_alsa_ucm_config *ucm, pa_card *card, const char *new_profile, const char *old_profile) {
+ return -1;
+}
+
+int pa_alsa_ucm_get_verb(snd_use_case_mgr_t *uc_mgr, const char *verb_name, const char *verb_desc, pa_alsa_ucm_verb **p_verb) {
+ return -1;
+}
+
+void pa_alsa_ucm_add_ports(
+ pa_hashmap **hash,
+ pa_proplist *proplist,
+ pa_alsa_ucm_mapping_context *context,
+ bool is_sink,
+ pa_card *card,
+ snd_pcm_t *pcm_handle,
+ bool ignore_dB) {
+}
+
+void pa_alsa_ucm_add_ports_combination(
+ pa_hashmap *hash,
+ pa_alsa_ucm_mapping_context *context,
+ bool is_sink,
+ pa_hashmap *ports,
+ pa_card_profile *cp,
+ pa_core *core) {
+}
+
+int pa_alsa_ucm_set_port(pa_alsa_ucm_mapping_context *context, pa_device_port *port, bool is_sink) {
+ return -1;
+}
+
+void pa_alsa_ucm_free(pa_alsa_ucm_config *ucm) {
+}
+
+void pa_alsa_ucm_mapping_context_free(pa_alsa_ucm_mapping_context *context) {
+}
+
+void pa_alsa_ucm_roled_stream_begin(pa_alsa_ucm_config *ucm, const char *role, pa_direction_t dir) {
+}
+
+void pa_alsa_ucm_roled_stream_end(pa_alsa_ucm_config *ucm, const char *role, pa_direction_t dir) {
+}
+
+#endif
diff --git a/src/modules/alsa/alsa-ucm.h b/src/modules/alsa/alsa-ucm.h
new file mode 100644
index 0000000..0bb2eb5
--- /dev/null
+++ b/src/modules/alsa/alsa-ucm.h
@@ -0,0 +1,294 @@
+#ifndef fooalsaucmhfoo
+#define fooalsaucmhfoo
+
+/***
+ This file is part of PulseAudio.
+
+ Copyright 2011 Wolfson Microelectronics PLC
+ Author Margarita Olaya <magi@slimlogic.co.uk>
+ Copyright 2012 Feng Wei <wei.feng@freescale.com>, Freescale Ltd.
+
+ PulseAudio is free software; you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License,
+ or (at your option) any later version.
+
+ PulseAudio is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+***/
+
+#ifdef HAVE_ALSA_UCM
+#include <alsa/use-case.h>
+#else
+typedef void snd_use_case_mgr_t;
+#endif
+
+#include "alsa-mixer.h"
+
+/** For devices: List of verbs, devices or modifiers available */
+#define PA_ALSA_PROP_UCM_NAME "alsa.ucm.name"
+
+/** For devices: List of supported devices per verb*/
+#define PA_ALSA_PROP_UCM_DESCRIPTION "alsa.ucm.description"
+
+/** For devices: Playback device name e.g PlaybackPCM */
+#define PA_ALSA_PROP_UCM_SINK "alsa.ucm.sink"
+
+/** For devices: Capture device name e.g CapturePCM*/
+#define PA_ALSA_PROP_UCM_SOURCE "alsa.ucm.source"
+
+/** For devices: Playback roles */
+#define PA_ALSA_PROP_UCM_PLAYBACK_ROLES "alsa.ucm.playback.roles"
+
+/** For devices: Playback control device name */
+#define PA_ALSA_PROP_UCM_PLAYBACK_CTL_DEVICE "alsa.ucm.playback.ctldev"
+
+/** For devices: Playback control volume ID string. e.g PlaybackVolume */
+#define PA_ALSA_PROP_UCM_PLAYBACK_VOLUME "alsa.ucm.playback.volume"
+
+/** For devices: Playback switch e.g PlaybackSwitch */
+#define PA_ALSA_PROP_UCM_PLAYBACK_SWITCH "alsa.ucm.playback.switch"
+
+/** For devices: Playback mixer device name */
+#define PA_ALSA_PROP_UCM_PLAYBACK_MIXER_DEVICE "alsa.ucm.playback.mixer.device"
+
+/** For devices: Playback mixer identifier */
+#define PA_ALSA_PROP_UCM_PLAYBACK_MIXER_ELEM "alsa.ucm.playback.mixer.element"
+
+/** For devices: Playback mixer master identifier */
+#define PA_ALSA_PROP_UCM_PLAYBACK_MASTER_ELEM "alsa.ucm.playback.master.element"
+
+/** For devices: Playback mixer master type */
+#define PA_ALSA_PROP_UCM_PLAYBACK_MASTER_TYPE "alsa.ucm.playback.master.type"
+
+/** For devices: Playback mixer master identifier */
+#define PA_ALSA_PROP_UCM_PLAYBACK_MASTER_ID "alsa.ucm.playback.master.id"
+
+/** For devices: Playback mixer master type */
+#define PA_ALSA_PROP_UCM_PLAYBACK_MASTER_TYPE "alsa.ucm.playback.master.type"
+
+/** For devices: Playback priority */
+#define PA_ALSA_PROP_UCM_PLAYBACK_PRIORITY "alsa.ucm.playback.priority"
+
+/** For devices: Playback rate */
+#define PA_ALSA_PROP_UCM_PLAYBACK_RATE "alsa.ucm.playback.rate"
+
+/** For devices: Playback channels */
+#define PA_ALSA_PROP_UCM_PLAYBACK_CHANNELS "alsa.ucm.playback.channels"
+
+/** For devices: Capture roles */
+#define PA_ALSA_PROP_UCM_CAPTURE_ROLES "alsa.ucm.capture.roles"
+
+/** For devices: Capture control device name */
+#define PA_ALSA_PROP_UCM_CAPTURE_CTL_DEVICE "alsa.ucm.capture.ctldev"
+
+/** For devices: Capture controls volume ID string. e.g CaptureVolume */
+#define PA_ALSA_PROP_UCM_CAPTURE_VOLUME "alsa.ucm.capture.volume"
+
+/** For devices: Capture switch e.g CaptureSwitch */
+#define PA_ALSA_PROP_UCM_CAPTURE_SWITCH "alsa.ucm.capture.switch"
+
+/** For devices: Capture mixer device name */
+#define PA_ALSA_PROP_UCM_CAPTURE_MIXER_DEVICE "alsa.ucm.capture.mixer.device"
+
+/** For devices: Capture mixer identifier */
+#define PA_ALSA_PROP_UCM_CAPTURE_MIXER_ELEM "alsa.ucm.capture.mixer.element"
+
+/** For devices: Capture mixer identifier */
+#define PA_ALSA_PROP_UCM_CAPTURE_MASTER_ELEM "alsa.ucm.capture.master.element"
+
+/** For devices: Capture mixer identifier */
+#define PA_ALSA_PROP_UCM_CAPTURE_MASTER_TYPE "alsa.ucm.capture.master.type"
+
+/** For devices: Capture mixer identifier */
+#define PA_ALSA_PROP_UCM_CAPTURE_MASTER_ID "alsa.ucm.capture.master.id"
+
+/** For devices: Capture mixer identifier */
+#define PA_ALSA_PROP_UCM_CAPTURE_MASTER_TYPE "alsa.ucm.capture.master.type"
+
+/** For devices: Capture priority */
+#define PA_ALSA_PROP_UCM_CAPTURE_PRIORITY "alsa.ucm.capture.priority"
+
+/** For devices: Capture rate */
+#define PA_ALSA_PROP_UCM_CAPTURE_RATE "alsa.ucm.capture.rate"
+
+/** For devices: Capture channels */
+#define PA_ALSA_PROP_UCM_CAPTURE_CHANNELS "alsa.ucm.capture.channels"
+
+/** For devices: Quality of Service */
+#define PA_ALSA_PROP_UCM_QOS "alsa.ucm.qos"
+
+/** For devices: The modifier (if any) that this device corresponds to */
+#define PA_ALSA_PROP_UCM_MODIFIER "alsa.ucm.modifier"
+
+/* Corresponds to the "JackCTL" UCM value. */
+#define PA_ALSA_PROP_UCM_JACK_DEVICE "alsa.ucm.jack_device"
+
+/* Corresponds to the "JackControl" UCM value. */
+#define PA_ALSA_PROP_UCM_JACK_CONTROL "alsa.ucm.jack_control"
+
+/* Corresponds to the "JackHWMute" UCM value. */
+#define PA_ALSA_PROP_UCM_JACK_HW_MUTE "alsa.ucm.jack_hw_mute"
+
+typedef struct pa_alsa_ucm_verb pa_alsa_ucm_verb;
+typedef struct pa_alsa_ucm_modifier pa_alsa_ucm_modifier;
+typedef struct pa_alsa_ucm_device pa_alsa_ucm_device;
+typedef struct pa_alsa_ucm_config pa_alsa_ucm_config;
+typedef struct pa_alsa_ucm_mapping_context pa_alsa_ucm_mapping_context;
+typedef struct pa_alsa_ucm_port_data pa_alsa_ucm_port_data;
+typedef struct pa_alsa_ucm_volume pa_alsa_ucm_volume;
+
+int pa_alsa_ucm_query_profiles(pa_alsa_ucm_config *ucm, int card_index);
+pa_alsa_profile_set* pa_alsa_ucm_add_profile_set(pa_alsa_ucm_config *ucm, pa_channel_map *default_channel_map);
+int pa_alsa_ucm_set_profile(pa_alsa_ucm_config *ucm, pa_card *card, const char *new_profile, const char *old_profile);
+
+int pa_alsa_ucm_get_verb(snd_use_case_mgr_t *uc_mgr, const char *verb_name, const char *verb_desc, pa_alsa_ucm_verb **p_verb);
+
+void pa_alsa_ucm_add_ports(
+ pa_hashmap **hash,
+ pa_proplist *proplist,
+ pa_alsa_ucm_mapping_context *context,
+ bool is_sink,
+ pa_card *card,
+ snd_pcm_t *pcm_handle,
+ bool ignore_dB);
+void pa_alsa_ucm_add_ports_combination(
+ pa_hashmap *hash,
+ pa_alsa_ucm_mapping_context *context,
+ bool is_sink,
+ pa_hashmap *ports,
+ pa_card_profile *cp,
+ pa_core *core);
+int pa_alsa_ucm_set_port(pa_alsa_ucm_mapping_context *context, pa_device_port *port, bool is_sink);
+
+void pa_alsa_ucm_free(pa_alsa_ucm_config *ucm);
+void pa_alsa_ucm_mapping_context_free(pa_alsa_ucm_mapping_context *context);
+
+void pa_alsa_ucm_roled_stream_begin(pa_alsa_ucm_config *ucm, const char *role, pa_direction_t dir);
+void pa_alsa_ucm_roled_stream_end(pa_alsa_ucm_config *ucm, const char *role, pa_direction_t dir);
+
+/* UCM - Use Case Manager is available on some audio cards */
+
+struct pa_alsa_ucm_device {
+ PA_LLIST_FIELDS(pa_alsa_ucm_device);
+
+ pa_proplist *proplist;
+
+ pa_device_port_type_t type;
+
+ unsigned playback_priority;
+ unsigned capture_priority;
+
+ unsigned playback_rate;
+ unsigned capture_rate;
+
+ unsigned playback_channels;
+ unsigned capture_channels;
+
+ /* These may be different per verb, so we store this as a hashmap of verb -> volume_control. We might eventually want to
+ * make this a hashmap of verb -> per-verb-device-properties-struct. */
+ pa_hashmap *playback_volumes;
+ pa_hashmap *capture_volumes;
+
+ pa_alsa_mapping *playback_mapping;
+ pa_alsa_mapping *capture_mapping;
+
+ pa_idxset *conflicting_devices;
+ pa_idxset *supported_devices;
+
+ /* One device may be part of multiple ports, since each device has
+ * a dedicated port, and in addition to that we sometimes generate ports
+ * that represent combinations of devices. */
+ pa_dynarray *ucm_ports; /* struct ucm_port */
+
+ pa_alsa_jack *jack;
+ pa_dynarray *hw_mute_jacks; /* pa_alsa_jack */
+ pa_available_t available;
+
+ char *eld_mixer_device_name;
+ int eld_device;
+};
+
+void pa_alsa_ucm_device_update_available(pa_alsa_ucm_device *device);
+
+struct pa_alsa_ucm_modifier {
+ PA_LLIST_FIELDS(pa_alsa_ucm_modifier);
+
+ pa_proplist *proplist;
+
+ int n_confdev;
+ int n_suppdev;
+
+ const char **conflicting_devices;
+ const char **supported_devices;
+
+ pa_direction_t action_direction;
+
+ char *media_role;
+
+ /* Non-NULL if the modifier has its own PlaybackPCM/CapturePCM */
+ pa_alsa_mapping *playback_mapping;
+ pa_alsa_mapping *capture_mapping;
+
+ /* Count how many role matched streams are running */
+ int enabled_counter;
+};
+
+struct pa_alsa_ucm_verb {
+ PA_LLIST_FIELDS(pa_alsa_ucm_verb);
+
+ pa_proplist *proplist;
+ unsigned priority;
+
+ PA_LLIST_HEAD(pa_alsa_ucm_device, devices);
+ PA_LLIST_HEAD(pa_alsa_ucm_modifier, modifiers);
+};
+
+struct pa_alsa_ucm_config {
+ pa_core *core;
+ snd_use_case_mgr_t *ucm_mgr;
+ pa_alsa_ucm_verb *active_verb;
+
+ pa_hashmap *mixers;
+ PA_LLIST_HEAD(pa_alsa_ucm_verb, verbs);
+ PA_LLIST_HEAD(pa_alsa_jack, jacks);
+};
+
+struct pa_alsa_ucm_mapping_context {
+ pa_alsa_ucm_config *ucm;
+ pa_direction_t direction;
+
+ pa_idxset *ucm_devices;
+ pa_idxset *ucm_modifiers;
+};
+
+struct pa_alsa_ucm_port_data {
+ pa_alsa_ucm_config *ucm;
+ pa_device_port *core_port;
+
+ /* A single port will be associated with multiple devices if it represents
+ * a combination of devices. */
+ pa_dynarray *devices; /* pa_alsa_ucm_device */
+
+ /* profile name -> pa_alsa_path for volume control */
+ pa_hashmap *paths;
+ /* Current path, set when activating profile */
+ pa_alsa_path *path;
+
+ /* ELD info */
+ char *eld_mixer_device_name;
+ int eld_device; /* PCM device number */
+};
+
+struct pa_alsa_ucm_volume {
+ char *mixer_elem; /* mixer element identifier */
+ char *master_elem; /* master mixer element identifier */
+ char *master_type;
+};
+
+#endif
diff --git a/src/modules/alsa/alsa-util.c b/src/modules/alsa/alsa-util.c
new file mode 100644
index 0000000..172a7bb
--- /dev/null
+++ b/src/modules/alsa/alsa-util.c
@@ -0,0 +1,1891 @@
+/***
+ This file is part of PulseAudio.
+
+ Copyright 2004-2009 Lennart Poettering
+ Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
+
+ PulseAudio is free software; you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License,
+ or (at your option) any later version.
+
+ PulseAudio is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+***/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <sys/types.h>
+#include <alsa/asoundlib.h>
+
+#include <pulse/sample.h>
+#include <pulse/xmalloc.h>
+#include <pulse/timeval.h>
+#include <pulse/util.h>
+#include <pulse/utf8.h>
+
+#include <pulsecore/i18n.h>
+#include <pulsecore/log.h>
+#include <pulsecore/macro.h>
+#include <pulsecore/core-util.h>
+#include <pulsecore/atomic.h>
+#include <pulsecore/core-error.h>
+#include <pulsecore/thread.h>
+#include <pulsecore/conf-parser.h>
+#include <pulsecore/core-rtclock.h>
+
+#include "alsa-util.h"
+#include "alsa-mixer.h"
+
+#ifdef HAVE_UDEV
+#include <modules/udev-util.h>
+#endif
+
+static int set_format(snd_pcm_t *pcm_handle, snd_pcm_hw_params_t *hwparams, pa_sample_format_t *f) {
+
+ static const snd_pcm_format_t format_trans[] = {
+ [PA_SAMPLE_U8] = SND_PCM_FORMAT_U8,
+ [PA_SAMPLE_ALAW] = SND_PCM_FORMAT_A_LAW,
+ [PA_SAMPLE_ULAW] = SND_PCM_FORMAT_MU_LAW,
+ [PA_SAMPLE_S16LE] = SND_PCM_FORMAT_S16_LE,
+ [PA_SAMPLE_S16BE] = SND_PCM_FORMAT_S16_BE,
+ [PA_SAMPLE_FLOAT32LE] = SND_PCM_FORMAT_FLOAT_LE,
+ [PA_SAMPLE_FLOAT32BE] = SND_PCM_FORMAT_FLOAT_BE,
+ [PA_SAMPLE_S32LE] = SND_PCM_FORMAT_S32_LE,
+ [PA_SAMPLE_S32BE] = SND_PCM_FORMAT_S32_BE,
+ [PA_SAMPLE_S24LE] = SND_PCM_FORMAT_S24_3LE,
+ [PA_SAMPLE_S24BE] = SND_PCM_FORMAT_S24_3BE,
+ [PA_SAMPLE_S24_32LE] = SND_PCM_FORMAT_S24_LE,
+ [PA_SAMPLE_S24_32BE] = SND_PCM_FORMAT_S24_BE,
+ };
+
+ static const pa_sample_format_t try_order[] = {
+ PA_SAMPLE_FLOAT32NE,
+ PA_SAMPLE_FLOAT32RE,
+ PA_SAMPLE_S32NE,
+ PA_SAMPLE_S32RE,
+ PA_SAMPLE_S24_32NE,
+ PA_SAMPLE_S24_32RE,
+ PA_SAMPLE_S24NE,
+ PA_SAMPLE_S24RE,
+ PA_SAMPLE_S16NE,
+ PA_SAMPLE_S16RE,
+ PA_SAMPLE_ALAW,
+ PA_SAMPLE_ULAW,
+ PA_SAMPLE_U8
+ };
+
+ unsigned i;
+ int ret;
+
+ pa_assert(pcm_handle);
+ pa_assert(hwparams);
+ pa_assert(f);
+
+ if ((ret = snd_pcm_hw_params_set_format(pcm_handle, hwparams, format_trans[*f])) >= 0)
+ return ret;
+
+ pa_log_debug("snd_pcm_hw_params_set_format(%s) failed: %s",
+ snd_pcm_format_description(format_trans[*f]),
+ pa_alsa_strerror(ret));
+
+ if (*f == PA_SAMPLE_FLOAT32BE)
+ *f = PA_SAMPLE_FLOAT32LE;
+ else if (*f == PA_SAMPLE_FLOAT32LE)
+ *f = PA_SAMPLE_FLOAT32BE;
+ else if (*f == PA_SAMPLE_S24BE)
+ *f = PA_SAMPLE_S24LE;
+ else if (*f == PA_SAMPLE_S24LE)
+ *f = PA_SAMPLE_S24BE;
+ else if (*f == PA_SAMPLE_S24_32BE)
+ *f = PA_SAMPLE_S24_32LE;
+ else if (*f == PA_SAMPLE_S24_32LE)
+ *f = PA_SAMPLE_S24_32BE;
+ else if (*f == PA_SAMPLE_S16BE)
+ *f = PA_SAMPLE_S16LE;
+ else if (*f == PA_SAMPLE_S16LE)
+ *f = PA_SAMPLE_S16BE;
+ else if (*f == PA_SAMPLE_S32BE)
+ *f = PA_SAMPLE_S32LE;
+ else if (*f == PA_SAMPLE_S32LE)
+ *f = PA_SAMPLE_S32BE;
+ else
+ goto try_auto;
+
+ if ((ret = snd_pcm_hw_params_set_format(pcm_handle, hwparams, format_trans[*f])) >= 0)
+ return ret;
+
+ pa_log_debug("snd_pcm_hw_params_set_format(%s) failed: %s",
+ snd_pcm_format_description(format_trans[*f]),
+ pa_alsa_strerror(ret));
+
+try_auto:
+
+ for (i = 0; i < PA_ELEMENTSOF(try_order); i++) {
+ *f = try_order[i];
+
+ if ((ret = snd_pcm_hw_params_set_format(pcm_handle, hwparams, format_trans[*f])) >= 0)
+ return ret;
+
+ pa_log_debug("snd_pcm_hw_params_set_format(%s) failed: %s",
+ snd_pcm_format_description(format_trans[*f]),
+ pa_alsa_strerror(ret));
+ }
+
+ return -1;
+}
+
+static int set_period_size(snd_pcm_t *pcm_handle, snd_pcm_hw_params_t *hwparams, snd_pcm_uframes_t size) {
+ snd_pcm_uframes_t s;
+ int d, ret;
+
+ pa_assert(pcm_handle);
+ pa_assert(hwparams);
+
+ s = size;
+ d = 0;
+ if (snd_pcm_hw_params_set_period_size_near(pcm_handle, hwparams, &s, &d) < 0) {
+ s = size;
+ d = -1;
+ if (snd_pcm_hw_params_set_period_size_near(pcm_handle, hwparams, &s, &d) < 0) {
+ s = size;
+ d = 1;
+ if ((ret = snd_pcm_hw_params_set_period_size_near(pcm_handle, hwparams, &s, &d)) < 0) {
+ pa_log_info("snd_pcm_hw_params_set_period_size_near() failed: %s", pa_alsa_strerror(ret));
+ return ret;
+ }
+ }
+ }
+
+ return 0;
+}
+
+static int set_buffer_size(snd_pcm_t *pcm_handle, snd_pcm_hw_params_t *hwparams, snd_pcm_uframes_t size) {
+ int ret;
+
+ pa_assert(pcm_handle);
+ pa_assert(hwparams);
+
+ if ((ret = snd_pcm_hw_params_set_buffer_size_near(pcm_handle, hwparams, &size)) < 0) {
+ pa_log_info("snd_pcm_hw_params_set_buffer_size_near() failed: %s", pa_alsa_strerror(ret));
+ return ret;
+ }
+
+ return 0;
+}
+
+static void check_access(snd_pcm_t *pcm_handle, snd_pcm_hw_params_t *hwparams, bool use_mmap) {
+ if ((use_mmap && !snd_pcm_hw_params_test_access(pcm_handle, hwparams, SND_PCM_ACCESS_MMAP_INTERLEAVED)) ||
+ !snd_pcm_hw_params_test_access(pcm_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED))
+ pa_log_error("Weird, PCM claims to support interleaved access, but snd_pcm_hw_params_set_access() failed.");
+
+ if ((use_mmap && !snd_pcm_hw_params_test_access(pcm_handle, hwparams, SND_PCM_ACCESS_MMAP_NONINTERLEAVED)) ||
+ !snd_pcm_hw_params_test_access(pcm_handle, hwparams, SND_PCM_ACCESS_RW_NONINTERLEAVED))
+ pa_log_debug("PCM seems to support non-interleaved access, but PA doesn't.");
+ else if (use_mmap && !snd_pcm_hw_params_test_access(pcm_handle, hwparams, SND_PCM_ACCESS_MMAP_COMPLEX)) {
+ pa_log_debug("PCM seems to support mmapped complex access, but PA doesn't.");
+ }
+}
+
+/* Set the hardware parameters of the given ALSA device. Returns the
+ * selected fragment settings in *buffer_size and *period_size. Determine
+ * whether mmap and tsched mode can be enabled. */
+int pa_alsa_set_hw_params(
+ snd_pcm_t *pcm_handle,
+ pa_sample_spec *ss,
+ snd_pcm_uframes_t *period_size,
+ snd_pcm_uframes_t *buffer_size,
+ snd_pcm_uframes_t tsched_size,
+ bool *use_mmap,
+ bool *use_tsched,
+ bool require_exact_channel_number) {
+
+ int ret = -1;
+ snd_pcm_hw_params_t *hwparams, *hwparams_copy;
+ int dir;
+ snd_pcm_uframes_t _period_size = period_size ? *period_size : 0;
+ snd_pcm_uframes_t _buffer_size = buffer_size ? *buffer_size : 0;
+ bool _use_mmap = use_mmap && *use_mmap;
+ bool _use_tsched = use_tsched && *use_tsched;
+ pa_sample_spec _ss = *ss;
+
+ pa_assert(pcm_handle);
+ pa_assert(ss);
+
+ snd_pcm_hw_params_alloca(&hwparams);
+ snd_pcm_hw_params_alloca(&hwparams_copy);
+
+ if ((ret = snd_pcm_hw_params_any(pcm_handle, hwparams)) < 0) {
+ pa_log_debug("snd_pcm_hw_params_any() failed: %s", pa_alsa_strerror(ret));
+ goto finish;
+ }
+
+ if ((ret = snd_pcm_hw_params_set_rate_resample(pcm_handle, hwparams, 0)) < 0) {
+ pa_log_debug("snd_pcm_hw_params_set_rate_resample() failed: %s", pa_alsa_strerror(ret));
+ goto finish;
+ }
+
+ if (_use_mmap) {
+
+ if (snd_pcm_hw_params_set_access(pcm_handle, hwparams, SND_PCM_ACCESS_MMAP_INTERLEAVED) < 0) {
+
+ /* mmap() didn't work, fall back to interleaved */
+
+ if ((ret = snd_pcm_hw_params_set_access(pcm_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) {
+ pa_log_debug("snd_pcm_hw_params_set_access() failed: %s", pa_alsa_strerror(ret));
+ check_access(pcm_handle, hwparams, true);
+ goto finish;
+ }
+
+ _use_mmap = false;
+ }
+
+ } else if ((ret = snd_pcm_hw_params_set_access(pcm_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) {
+ pa_log_debug("snd_pcm_hw_params_set_access() failed: %s", pa_alsa_strerror(ret));
+ check_access(pcm_handle, hwparams, false);
+ goto finish;
+ }
+
+ if (!_use_mmap)
+ _use_tsched = false;
+
+ if (!pa_alsa_pcm_is_hw(pcm_handle))
+ _use_tsched = false;
+
+ /* The PCM pointer is only updated with period granularity */
+ if (snd_pcm_hw_params_is_batch(hwparams)) {
+ bool is_usb = false;
+ const char *id;
+ snd_pcm_info_t* pcm_info;
+ snd_pcm_info_alloca(&pcm_info);
+
+ if (snd_pcm_info(pcm_handle, pcm_info) == 0 &&
+ (id = snd_pcm_info_get_id(pcm_info))) {
+ /* This horrible hack makes sure we don't disable tsched on USB
+ * devices, which have a low enough transfer size for timer-based
+ * scheduling to work. This can go away when the ALSA API supprots
+ * querying the block transfer size. */
+ if (pa_streq(id, "USB Audio"))
+ is_usb = true;
+ }
+
+ if (!is_usb) {
+ pa_log_info("Disabling tsched mode since BATCH flag is set");
+ _use_tsched = false;
+ }
+ }
+
+#if (SND_LIB_VERSION >= ((1<<16)|(0<<8)|24)) /* API additions in 1.0.24 */
+ if (_use_tsched) {
+
+ /* try to disable period wakeups if hardware can do so */
+ if (snd_pcm_hw_params_can_disable_period_wakeup(hwparams)) {
+
+ if ((ret = snd_pcm_hw_params_set_period_wakeup(pcm_handle, hwparams, false)) < 0)
+ /* don't bail, keep going with default mode with period wakeups */
+ pa_log_debug("snd_pcm_hw_params_set_period_wakeup() failed: %s", pa_alsa_strerror(ret));
+ else
+ pa_log_info("Trying to disable ALSA period wakeups, using timers only");
+ } else
+ pa_log_info("Cannot disable ALSA period wakeups");
+ }
+#endif
+
+ if ((ret = set_format(pcm_handle, hwparams, &_ss.format)) < 0)
+ goto finish;
+
+ if ((ret = snd_pcm_hw_params_set_rate_near(pcm_handle, hwparams, &_ss.rate, NULL)) < 0) {
+ pa_log_debug("snd_pcm_hw_params_set_rate_near() failed: %s", pa_alsa_strerror(ret));
+ goto finish;
+ }
+
+ /* We ignore very small sampling rate deviations */
+ if (_ss.rate >= ss->rate*.95 && _ss.rate <= ss->rate*1.05)
+ _ss.rate = ss->rate;
+
+ if (require_exact_channel_number) {
+ if ((ret = snd_pcm_hw_params_set_channels(pcm_handle, hwparams, _ss.channels)) < 0) {
+ pa_log_debug("snd_pcm_hw_params_set_channels(%u) failed: %s", _ss.channels, pa_alsa_strerror(ret));
+ goto finish;
+ }
+ } else {
+ unsigned int c = _ss.channels;
+
+ if ((ret = snd_pcm_hw_params_set_channels_near(pcm_handle, hwparams, &c)) < 0) {
+ pa_log_debug("snd_pcm_hw_params_set_channels_near(%u) failed: %s", _ss.channels, pa_alsa_strerror(ret));
+ goto finish;
+ }
+
+ _ss.channels = c;
+ }
+
+ if (_use_tsched && tsched_size > 0) {
+ _buffer_size = (snd_pcm_uframes_t) (((uint64_t) tsched_size * _ss.rate) / ss->rate);
+ _period_size = _buffer_size;
+ } else {
+ _period_size = (snd_pcm_uframes_t) (((uint64_t) _period_size * _ss.rate) / ss->rate);
+ _buffer_size = (snd_pcm_uframes_t) (((uint64_t) _buffer_size * _ss.rate) / ss->rate);
+ }
+
+ if (_buffer_size > 0 || _period_size > 0) {
+ snd_pcm_uframes_t max_frames = 0;
+
+ if ((ret = snd_pcm_hw_params_get_buffer_size_max(hwparams, &max_frames)) < 0)
+ pa_log_warn("snd_pcm_hw_params_get_buffer_size_max() failed: %s", pa_alsa_strerror(ret));
+ else
+ pa_log_debug("Maximum hw buffer size is %lu ms", (long unsigned) (max_frames * PA_MSEC_PER_SEC / _ss.rate));
+
+ /* Some ALSA drivers really don't like if we set the buffer
+ * size first and the number of periods second (which would
+ * make a lot more sense to me). So, try a few combinations
+ * before we give up. */
+
+ if (_buffer_size > 0 && _period_size > 0) {
+ snd_pcm_hw_params_copy(hwparams_copy, hwparams);
+
+ /* First try: set buffer size first, followed by period size */
+ if (set_buffer_size(pcm_handle, hwparams_copy, _buffer_size) >= 0 &&
+ set_period_size(pcm_handle, hwparams_copy, _period_size) >= 0 &&
+ snd_pcm_hw_params(pcm_handle, hwparams_copy) >= 0) {
+ pa_log_debug("Set buffer size first (to %lu samples), period size second (to %lu samples).", (unsigned long) _buffer_size, (unsigned long) _period_size);
+ goto success;
+ }
+
+ snd_pcm_hw_params_copy(hwparams_copy, hwparams);
+ /* Second try: set period size first, followed by buffer size */
+ if (set_period_size(pcm_handle, hwparams_copy, _period_size) >= 0 &&
+ set_buffer_size(pcm_handle, hwparams_copy, _buffer_size) >= 0 &&
+ snd_pcm_hw_params(pcm_handle, hwparams_copy) >= 0) {
+ pa_log_debug("Set period size first (to %lu samples), buffer size second (to %lu samples).", (unsigned long) _period_size, (unsigned long) _buffer_size);
+ goto success;
+ }
+ }
+
+ if (_buffer_size > 0) {
+ snd_pcm_hw_params_copy(hwparams_copy, hwparams);
+
+ /* Third try: set only buffer size */
+ if (set_buffer_size(pcm_handle, hwparams_copy, _buffer_size) >= 0 &&
+ snd_pcm_hw_params(pcm_handle, hwparams_copy) >= 0) {
+ pa_log_debug("Set only buffer size (to %lu samples).", (unsigned long) _buffer_size);
+ goto success;
+ }
+ }
+
+ if (_period_size > 0) {
+ snd_pcm_hw_params_copy(hwparams_copy, hwparams);
+
+ /* Fourth try: set only period size */
+ if (set_period_size(pcm_handle, hwparams_copy, _period_size) >= 0 &&
+ snd_pcm_hw_params(pcm_handle, hwparams_copy) >= 0) {
+ pa_log_debug("Set only period size (to %lu samples).", (unsigned long) _period_size);
+ goto success;
+ }
+ }
+ }
+
+ pa_log_debug("Set neither period nor buffer size.");
+
+ /* Last chance, set nothing */
+ if ((ret = snd_pcm_hw_params(pcm_handle, hwparams)) < 0) {
+ pa_log_info("snd_pcm_hw_params failed: %s", pa_alsa_strerror(ret));
+ goto finish;
+ }
+
+success:
+
+ if (ss->rate != _ss.rate)
+ pa_log_info("Device %s doesn't support %u Hz, changed to %u Hz.", snd_pcm_name(pcm_handle), ss->rate, _ss.rate);
+
+ if (ss->channels != _ss.channels)
+ pa_log_info("Device %s doesn't support %u channels, changed to %u.", snd_pcm_name(pcm_handle), ss->channels, _ss.channels);
+
+ if (ss->format != _ss.format)
+ pa_log_info("Device %s doesn't support sample format %s, changed to %s.", snd_pcm_name(pcm_handle), pa_sample_format_to_string(ss->format), pa_sample_format_to_string(_ss.format));
+
+ if ((ret = snd_pcm_hw_params_current(pcm_handle, hwparams)) < 0) {
+ pa_log_info("snd_pcm_hw_params_current() failed: %s", pa_alsa_strerror(ret));
+ goto finish;
+ }
+
+ if ((ret = snd_pcm_hw_params_get_period_size(hwparams, &_period_size, &dir)) < 0 ||
+ (ret = snd_pcm_hw_params_get_buffer_size(hwparams, &_buffer_size)) < 0) {
+ pa_log_info("snd_pcm_hw_params_get_{period|buffer}_size() failed: %s", pa_alsa_strerror(ret));
+ goto finish;
+ }
+
+#if (SND_LIB_VERSION >= ((1<<16)|(0<<8)|24)) /* API additions in 1.0.24 */
+ if (_use_tsched) {
+ unsigned int no_wakeup;
+ /* see if period wakeups were disabled */
+ snd_pcm_hw_params_get_period_wakeup(pcm_handle, hwparams, &no_wakeup);
+ if (no_wakeup == 0)
+ pa_log_info("ALSA period wakeups disabled");
+ else
+ pa_log_info("ALSA period wakeups were not disabled");
+ }
+#endif
+
+ ss->rate = _ss.rate;
+ ss->channels = _ss.channels;
+ ss->format = _ss.format;
+
+ pa_assert(_period_size > 0);
+ pa_assert(_buffer_size > 0);
+
+ if (buffer_size)
+ *buffer_size = _buffer_size;
+
+ if (period_size)
+ *period_size = _period_size;
+
+ if (use_mmap)
+ *use_mmap = _use_mmap;
+
+ if (use_tsched)
+ *use_tsched = _use_tsched;
+
+ ret = 0;
+
+finish:
+
+ return ret;
+}
+
+int pa_alsa_set_sw_params(snd_pcm_t *pcm, snd_pcm_uframes_t avail_min, bool period_event) {
+ snd_pcm_sw_params_t *swparams;
+ snd_pcm_uframes_t boundary;
+ int err;
+
+ pa_assert(pcm);
+
+ snd_pcm_sw_params_alloca(&swparams);
+
+ if ((err = snd_pcm_sw_params_current(pcm, swparams)) < 0) {
+ pa_log_warn("Unable to determine current swparams: %s", pa_alsa_strerror(err));
+ return err;
+ }
+
+ if ((err = snd_pcm_sw_params_set_period_event(pcm, swparams, period_event)) < 0) {
+ pa_log_warn("Unable to disable period event: %s", pa_alsa_strerror(err));
+ return err;
+ }
+
+ if ((err = snd_pcm_sw_params_set_tstamp_mode(pcm, swparams, SND_PCM_TSTAMP_ENABLE)) < 0) {
+ pa_log_warn("Unable to enable time stamping: %s", pa_alsa_strerror(err));
+ return err;
+ }
+
+ if ((err = snd_pcm_sw_params_get_boundary(swparams, &boundary)) < 0) {
+ pa_log_warn("Unable to get boundary: %s", pa_alsa_strerror(err));
+ return err;
+ }
+
+ if ((err = snd_pcm_sw_params_set_stop_threshold(pcm, swparams, boundary)) < 0) {
+ pa_log_warn("Unable to set stop threshold: %s", pa_alsa_strerror(err));
+ return err;
+ }
+
+ if ((err = snd_pcm_sw_params_set_start_threshold(pcm, swparams, (snd_pcm_uframes_t) -1)) < 0) {
+ pa_log_warn("Unable to set start threshold: %s", pa_alsa_strerror(err));
+ return err;
+ }
+
+ if ((err = snd_pcm_sw_params_set_avail_min(pcm, swparams, avail_min)) < 0) {
+ pa_log_error("snd_pcm_sw_params_set_avail_min() failed: %s", pa_alsa_strerror(err));
+ return err;
+ }
+
+ if ((err = snd_pcm_sw_params(pcm, swparams)) < 0) {
+ pa_log_warn("Unable to set sw params: %s", pa_alsa_strerror(err));
+ return err;
+ }
+
+ return 0;
+}
+
+snd_pcm_t *pa_alsa_open_by_device_id_auto(
+ const char *dev_id,
+ char **dev,
+ pa_sample_spec *ss,
+ pa_channel_map* map,
+ int mode,
+ snd_pcm_uframes_t *period_size,
+ snd_pcm_uframes_t *buffer_size,
+ snd_pcm_uframes_t tsched_size,
+ bool *use_mmap,
+ bool *use_tsched,
+ pa_alsa_profile_set *ps,
+ pa_alsa_mapping **mapping) {
+
+ char *d;
+ snd_pcm_t *pcm_handle;
+ void *state;
+ pa_alsa_mapping *m;
+
+ pa_assert(dev_id);
+ pa_assert(dev);
+ pa_assert(ss);
+ pa_assert(map);
+ pa_assert(ps);
+
+ /* First we try to find a device string with a superset of the
+ * requested channel map. We iterate through our device table from
+ * top to bottom and take the first that matches. If we didn't
+ * find a working device that way, we iterate backwards, and check
+ * all devices that do not provide a superset of the requested
+ * channel map.*/
+
+ PA_HASHMAP_FOREACH(m, ps->mappings, state) {
+ if (!pa_channel_map_superset(&m->channel_map, map))
+ continue;
+
+ pa_log_debug("Checking for superset %s (%s)", m->name, m->device_strings[0]);
+
+ pcm_handle = pa_alsa_open_by_device_id_mapping(
+ dev_id,
+ dev,
+ ss,
+ map,
+ mode,
+ period_size,
+ buffer_size,
+ tsched_size,
+ use_mmap,
+ use_tsched,
+ m);
+
+ if (pcm_handle) {
+ if (mapping)
+ *mapping = m;
+
+ return pcm_handle;
+ }
+ }
+
+ PA_HASHMAP_FOREACH_BACKWARDS(m, ps->mappings, state) {
+ if (pa_channel_map_superset(&m->channel_map, map))
+ continue;
+
+ pa_log_debug("Checking for subset %s (%s)", m->name, m->device_strings[0]);
+
+ pcm_handle = pa_alsa_open_by_device_id_mapping(
+ dev_id,
+ dev,
+ ss,
+ map,
+ mode,
+ period_size,
+ buffer_size,
+ tsched_size,
+ use_mmap,
+ use_tsched,
+ m);
+
+ if (pcm_handle) {
+ if (mapping)
+ *mapping = m;
+
+ return pcm_handle;
+ }
+ }
+
+ /* OK, we didn't find any good device, so let's try the raw hw: stuff */
+ d = pa_sprintf_malloc("hw:%s", dev_id);
+ pa_log_debug("Trying %s as last resort...", d);
+ pcm_handle = pa_alsa_open_by_device_string(
+ d,
+ dev,
+ ss,
+ map,
+ mode,
+ period_size,
+ buffer_size,
+ tsched_size,
+ use_mmap,
+ use_tsched,
+ false);
+ pa_xfree(d);
+
+ if (pcm_handle && mapping)
+ *mapping = NULL;
+
+ return pcm_handle;
+}
+
+snd_pcm_t *pa_alsa_open_by_device_id_mapping(
+ const char *dev_id,
+ char **dev,
+ pa_sample_spec *ss,
+ pa_channel_map* map,
+ int mode,
+ snd_pcm_uframes_t *period_size,
+ snd_pcm_uframes_t *buffer_size,
+ snd_pcm_uframes_t tsched_size,
+ bool *use_mmap,
+ bool *use_tsched,
+ pa_alsa_mapping *m) {
+
+ snd_pcm_t *pcm_handle;
+ pa_sample_spec try_ss;
+ pa_channel_map try_map;
+
+ pa_assert(dev_id);
+ pa_assert(dev);
+ pa_assert(ss);
+ pa_assert(map);
+ pa_assert(m);
+
+ try_ss.channels = m->channel_map.channels;
+ try_ss.rate = ss->rate;
+ try_ss.format = ss->format;
+ try_map = m->channel_map;
+
+ pcm_handle = pa_alsa_open_by_template(
+ m->device_strings,
+ dev_id,
+ dev,
+ &try_ss,
+ &try_map,
+ mode,
+ period_size,
+ buffer_size,
+ tsched_size,
+ use_mmap,
+ use_tsched,
+ pa_channel_map_valid(&m->channel_map) /* Query the channel count if we don't know what we want */);
+
+ if (!pcm_handle)
+ return NULL;
+
+ *ss = try_ss;
+ *map = try_map;
+ pa_assert(map->channels == ss->channels);
+
+ return pcm_handle;
+}
+
+snd_pcm_t *pa_alsa_open_by_device_string(
+ const char *device,
+ char **dev,
+ pa_sample_spec *ss,
+ pa_channel_map* map,
+ int mode,
+ snd_pcm_uframes_t *period_size,
+ snd_pcm_uframes_t *buffer_size,
+ snd_pcm_uframes_t tsched_size,
+ bool *use_mmap,
+ bool *use_tsched,
+ bool require_exact_channel_number) {
+
+ int err;
+ char *d;
+ snd_pcm_t *pcm_handle;
+ bool reformat = false;
+
+ pa_assert(device);
+ pa_assert(ss);
+ pa_assert(map);
+
+ d = pa_xstrdup(device);
+
+ for (;;) {
+ pa_log_debug("Trying %s %s SND_PCM_NO_AUTO_FORMAT ...", d, reformat ? "without" : "with");
+
+ if ((err = snd_pcm_open(&pcm_handle, d, mode,
+ SND_PCM_NONBLOCK|
+ SND_PCM_NO_AUTO_RESAMPLE|
+ SND_PCM_NO_AUTO_CHANNELS|
+ (reformat ? 0 : SND_PCM_NO_AUTO_FORMAT))) < 0) {
+ pa_log_info("Error opening PCM device %s: %s", d, pa_alsa_strerror(err));
+ goto fail;
+ }
+
+ pa_log_debug("Managed to open %s", d);
+
+ if ((err = pa_alsa_set_hw_params(
+ pcm_handle,
+ ss,
+ period_size,
+ buffer_size,
+ tsched_size,
+ use_mmap,
+ use_tsched,
+ require_exact_channel_number)) < 0) {
+
+ if (!reformat) {
+ reformat = true;
+
+ snd_pcm_close(pcm_handle);
+ continue;
+ }
+
+ /* Hmm, some hw is very exotic, so we retry with plug, if without it didn't work */
+ if (!pa_startswith(d, "plug:") && !pa_startswith(d, "plughw:")) {
+ char *t;
+
+ t = pa_sprintf_malloc("plug:%s", d);
+ pa_xfree(d);
+ d = t;
+
+ reformat = false;
+
+ snd_pcm_close(pcm_handle);
+ continue;
+ }
+
+ pa_log_info("Failed to set hardware parameters on %s: %s", d, pa_alsa_strerror(err));
+ snd_pcm_close(pcm_handle);
+
+ goto fail;
+ }
+
+ if (ss->channels > PA_CHANNELS_MAX) {
+ pa_log("Device %s has %u channels, but PulseAudio supports only %u channels. Unable to use the device.",
+ d, ss->channels, PA_CHANNELS_MAX);
+ snd_pcm_close(pcm_handle);
+ goto fail;
+ }
+
+ if (dev)
+ *dev = d;
+ else
+ pa_xfree(d);
+
+ if (ss->channels != map->channels)
+ pa_channel_map_init_extend(map, ss->channels, PA_CHANNEL_MAP_ALSA);
+
+ return pcm_handle;
+ }
+
+fail:
+ pa_xfree(d);
+
+ return NULL;
+}
+
+snd_pcm_t *pa_alsa_open_by_template(
+ char **template,
+ const char *dev_id,
+ char **dev,
+ pa_sample_spec *ss,
+ pa_channel_map* map,
+ int mode,
+ snd_pcm_uframes_t *period_size,
+ snd_pcm_uframes_t *buffer_size,
+ snd_pcm_uframes_t tsched_size,
+ bool *use_mmap,
+ bool *use_tsched,
+ bool require_exact_channel_number) {
+
+ snd_pcm_t *pcm_handle;
+ char **i;
+
+ for (i = template; *i; i++) {
+ char *d;
+
+ d = pa_replace(*i, "%f", dev_id);
+
+ pcm_handle = pa_alsa_open_by_device_string(
+ d,
+ dev,
+ ss,
+ map,
+ mode,
+ period_size,
+ buffer_size,
+ tsched_size,
+ use_mmap,
+ use_tsched,
+ require_exact_channel_number);
+
+ pa_xfree(d);
+
+ if (pcm_handle)
+ return pcm_handle;
+ }
+
+ return NULL;
+}
+
+void pa_alsa_dump(pa_log_level_t level, snd_pcm_t *pcm) {
+ int err;
+ snd_output_t *out;
+
+ pa_assert(pcm);
+
+ pa_assert_se(snd_output_buffer_open(&out) == 0);
+
+ if ((err = snd_pcm_dump(pcm, out)) < 0)
+ pa_logl(level, "snd_pcm_dump(): %s", pa_alsa_strerror(err));
+ else {
+ char *s = NULL;
+ snd_output_buffer_string(out, &s);
+ pa_logl(level, "snd_pcm_dump():\n%s", pa_strnull(s));
+ }
+
+ pa_assert_se(snd_output_close(out) == 0);
+}
+
+void pa_alsa_dump_status(snd_pcm_t *pcm) {
+ int err;
+ snd_output_t *out;
+ snd_pcm_status_t *status;
+ char *s = NULL;
+
+ pa_assert(pcm);
+
+ snd_pcm_status_alloca(&status);
+
+ if ((err = snd_output_buffer_open(&out)) < 0) {
+ pa_log_debug("snd_output_buffer_open() failed: %s", pa_cstrerror(err));
+ return;
+ }
+
+ if ((err = snd_pcm_status(pcm, status)) < 0) {
+ pa_log_debug("snd_pcm_status() failed: %s", pa_cstrerror(err));
+ goto finish;
+ }
+
+ if ((err = snd_pcm_status_dump(status, out)) < 0) {
+ pa_log_debug("snd_pcm_status_dump(): %s", pa_alsa_strerror(err));
+ goto finish;
+ }
+
+ snd_output_buffer_string(out, &s);
+ pa_log_debug("snd_pcm_status_dump():\n%s", pa_strnull(s));
+
+finish:
+
+ snd_output_close(out);
+}
+
+static void alsa_error_handler(const char *file, int line, const char *function, int err, const char *fmt,...) {
+ va_list ap;
+ char *alsa_file;
+
+ alsa_file = pa_sprintf_malloc("(alsa-lib)%s", file);
+
+ va_start(ap, fmt);
+
+ pa_log_levelv_meta(PA_LOG_INFO, alsa_file, line, function, fmt, ap);
+
+ va_end(ap);
+
+ pa_xfree(alsa_file);
+}
+
+static pa_atomic_t n_error_handler_installed = PA_ATOMIC_INIT(0);
+
+void pa_alsa_refcnt_inc(void) {
+ /* This is not really thread safe, but we do our best */
+
+ if (pa_atomic_inc(&n_error_handler_installed) == 0)
+ snd_lib_error_set_handler(alsa_error_handler);
+}
+
+void pa_alsa_refcnt_dec(void) {
+ int r;
+
+ pa_assert_se((r = pa_atomic_dec(&n_error_handler_installed)) >= 1);
+
+ if (r == 1) {
+ snd_lib_error_set_handler(NULL);
+ snd_config_update_free_global();
+ }
+}
+
+bool pa_alsa_init_description(pa_proplist *p, pa_card *card) {
+ const char *d, *k;
+ pa_assert(p);
+
+ if (pa_device_init_description(p, card))
+ return true;
+
+ if (!(d = pa_proplist_gets(p, "alsa.card_name")))
+ d = pa_proplist_gets(p, "alsa.name");
+
+ if (!d)
+ return false;
+
+ k = pa_proplist_gets(p, PA_PROP_DEVICE_PROFILE_DESCRIPTION);
+
+ if (d && k)
+ pa_proplist_setf(p, PA_PROP_DEVICE_DESCRIPTION, "%s %s", d, k);
+ else if (d)
+ pa_proplist_sets(p, PA_PROP_DEVICE_DESCRIPTION, d);
+
+ return false;
+}
+
+void pa_alsa_init_proplist_card(pa_core *c, pa_proplist *p, int card) {
+ char *cn, *lcn, *dn;
+
+ pa_assert(p);
+ pa_assert(card >= 0);
+
+ pa_proplist_setf(p, "alsa.card", "%i", card);
+
+ if (snd_card_get_name(card, &cn) >= 0) {
+ pa_proplist_sets(p, "alsa.card_name", pa_strip(cn));
+ free(cn);
+ }
+
+ if (snd_card_get_longname(card, &lcn) >= 0) {
+ pa_proplist_sets(p, "alsa.long_card_name", pa_strip(lcn));
+ free(lcn);
+ }
+
+ if ((dn = pa_alsa_get_driver_name(card))) {
+ pa_proplist_sets(p, "alsa.driver_name", dn);
+ pa_xfree(dn);
+ }
+
+#ifdef HAVE_UDEV
+ pa_udev_get_info(card, p);
+#endif
+}
+
+void pa_alsa_init_proplist_pcm_info(pa_core *c, pa_proplist *p, snd_pcm_info_t *pcm_info) {
+
+ static const char * const alsa_class_table[SND_PCM_CLASS_LAST+1] = {
+ [SND_PCM_CLASS_GENERIC] = "generic",
+ [SND_PCM_CLASS_MULTI] = "multi",
+ [SND_PCM_CLASS_MODEM] = "modem",
+ [SND_PCM_CLASS_DIGITIZER] = "digitizer"
+ };
+ static const char * const class_table[SND_PCM_CLASS_LAST+1] = {
+ [SND_PCM_CLASS_GENERIC] = "sound",
+ [SND_PCM_CLASS_MULTI] = NULL,
+ [SND_PCM_CLASS_MODEM] = "modem",
+ [SND_PCM_CLASS_DIGITIZER] = NULL
+ };
+ static const char * const alsa_subclass_table[SND_PCM_SUBCLASS_LAST+1] = {
+ [SND_PCM_SUBCLASS_GENERIC_MIX] = "generic-mix",
+ [SND_PCM_SUBCLASS_MULTI_MIX] = "multi-mix"
+ };
+
+ snd_pcm_class_t class;
+ snd_pcm_subclass_t subclass;
+ const char *n, *id, *sdn;
+ int card;
+
+ pa_assert(p);
+ pa_assert(pcm_info);
+
+ pa_proplist_sets(p, PA_PROP_DEVICE_API, "alsa");
+
+ if ((class = snd_pcm_info_get_class(pcm_info)) <= SND_PCM_CLASS_LAST) {
+ if (class_table[class])
+ pa_proplist_sets(p, PA_PROP_DEVICE_CLASS, class_table[class]);
+ if (alsa_class_table[class])
+ pa_proplist_sets(p, "alsa.class", alsa_class_table[class]);
+ }
+
+ if ((subclass = snd_pcm_info_get_subclass(pcm_info)) <= SND_PCM_SUBCLASS_LAST)
+ if (alsa_subclass_table[subclass])
+ pa_proplist_sets(p, "alsa.subclass", alsa_subclass_table[subclass]);
+
+ if ((n = snd_pcm_info_get_name(pcm_info))) {
+ char *t = pa_xstrdup(n);
+ pa_proplist_sets(p, "alsa.name", pa_strip(t));
+ pa_xfree(t);
+ }
+
+ if ((id = snd_pcm_info_get_id(pcm_info)))
+ pa_proplist_sets(p, "alsa.id", id);
+
+ pa_proplist_setf(p, "alsa.subdevice", "%u", snd_pcm_info_get_subdevice(pcm_info));
+ if ((sdn = snd_pcm_info_get_subdevice_name(pcm_info)))
+ pa_proplist_sets(p, "alsa.subdevice_name", sdn);
+
+ pa_proplist_setf(p, "alsa.device", "%u", snd_pcm_info_get_device(pcm_info));
+
+ if ((card = snd_pcm_info_get_card(pcm_info)) >= 0)
+ pa_alsa_init_proplist_card(c, p, card);
+}
+
+void pa_alsa_init_proplist_pcm(pa_core *c, pa_proplist *p, snd_pcm_t *pcm) {
+ snd_pcm_hw_params_t *hwparams;
+ snd_pcm_info_t *info;
+ int bits, err;
+
+ snd_pcm_hw_params_alloca(&hwparams);
+ snd_pcm_info_alloca(&info);
+
+ if ((err = snd_pcm_hw_params_current(pcm, hwparams)) < 0)
+ pa_log_warn("Error fetching hardware parameter info: %s", pa_alsa_strerror(err));
+ else {
+
+ if ((bits = snd_pcm_hw_params_get_sbits(hwparams)) >= 0)
+ pa_proplist_setf(p, "alsa.resolution_bits", "%i", bits);
+ }
+
+ if ((err = snd_pcm_info(pcm, info)) < 0)
+ pa_log_warn("Error fetching PCM info: %s", pa_alsa_strerror(err));
+ else
+ pa_alsa_init_proplist_pcm_info(c, p, info);
+}
+
+void pa_alsa_init_proplist_ctl(pa_proplist *p, const char *name) {
+ int err;
+ snd_ctl_t *ctl;
+ snd_ctl_card_info_t *info;
+ const char *t;
+
+ pa_assert(p);
+
+ snd_ctl_card_info_alloca(&info);
+
+ if ((err = snd_ctl_open(&ctl, name, 0)) < 0) {
+ pa_log_warn("Error opening low-level control device '%s': %s", name, snd_strerror(err));
+ return;
+ }
+
+ if ((err = snd_ctl_card_info(ctl, info)) < 0) {
+ pa_log_warn("Control device %s card info: %s", name, snd_strerror(err));
+ snd_ctl_close(ctl);
+ return;
+ }
+
+ if ((t = snd_ctl_card_info_get_mixername(info)) && *t)
+ pa_proplist_sets(p, "alsa.mixer_name", t);
+
+ if ((t = snd_ctl_card_info_get_components(info)) && *t)
+ pa_proplist_sets(p, "alsa.components", t);
+
+ snd_ctl_close(ctl);
+}
+
+int pa_alsa_recover_from_poll(snd_pcm_t *pcm, int revents) {
+ snd_pcm_state_t state;
+ snd_pcm_hw_params_t *hwparams;
+ int err;
+
+ pa_assert(pcm);
+
+ if (revents & POLLERR)
+ pa_log_debug("Got POLLERR from ALSA");
+ if (revents & POLLNVAL)
+ pa_log_warn("Got POLLNVAL from ALSA");
+ if (revents & POLLHUP)
+ pa_log_warn("Got POLLHUP from ALSA");
+ if (revents & POLLPRI)
+ pa_log_warn("Got POLLPRI from ALSA");
+ if (revents & POLLIN)
+ pa_log_debug("Got POLLIN from ALSA");
+ if (revents & POLLOUT)
+ pa_log_debug("Got POLLOUT from ALSA");
+
+ state = snd_pcm_state(pcm);
+ pa_log_debug("PCM state is %s", snd_pcm_state_name(state));
+
+ /* Try to recover from this error */
+
+ switch (state) {
+
+ case SND_PCM_STATE_DISCONNECTED:
+ /* Do not try to recover */
+ pa_log_info("Device disconnected.");
+ return -1;
+
+ case SND_PCM_STATE_XRUN:
+ if ((err = snd_pcm_recover(pcm, -EPIPE, 1)) != 0) {
+ pa_log_warn("Could not recover from POLLERR|POLLNVAL|POLLHUP and XRUN: %s", pa_alsa_strerror(err));
+ return -1;
+ }
+ break;
+
+ case SND_PCM_STATE_SUSPENDED:
+ snd_pcm_hw_params_alloca(&hwparams);
+
+ if ((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0) {
+ pa_log_debug("snd_pcm_hw_params_any() failed: %s", pa_alsa_strerror(err));
+ return -1;
+ }
+
+ if (snd_pcm_hw_params_can_resume(hwparams)) {
+ /* Retry resume 3 times before giving up, then fallback to restarting the stream. */
+ for (int i = 0; i < 3; i++) {
+ if ((err = snd_pcm_resume(pcm)) == 0)
+ return 0;
+ if (err != -EAGAIN)
+ break;
+ pa_msleep(25);
+ }
+ pa_log_warn("Could not recover alsa device from SUSPENDED state, trying to restart PCM");
+ }
+ /* Fall through */
+
+ default:
+
+ snd_pcm_drop(pcm);
+ return 1;
+ }
+
+ return 0;
+}
+
+pa_rtpoll_item* pa_alsa_build_pollfd(snd_pcm_t *pcm, pa_rtpoll *rtpoll) {
+ int n, err;
+ struct pollfd *pollfd;
+ pa_rtpoll_item *item;
+
+ pa_assert(pcm);
+
+ if ((n = snd_pcm_poll_descriptors_count(pcm)) < 0) {
+ pa_log("snd_pcm_poll_descriptors_count() failed: %s", pa_alsa_strerror(n));
+ return NULL;
+ }
+
+ item = pa_rtpoll_item_new(rtpoll, PA_RTPOLL_NEVER, (unsigned) n);
+ pollfd = pa_rtpoll_item_get_pollfd(item, NULL);
+
+ if ((err = snd_pcm_poll_descriptors(pcm, pollfd, (unsigned) n)) < 0) {
+ pa_log("snd_pcm_poll_descriptors() failed: %s", pa_alsa_strerror(err));
+ pa_rtpoll_item_free(item);
+ return NULL;
+ }
+
+ return item;
+}
+
+snd_pcm_sframes_t pa_alsa_safe_avail(snd_pcm_t *pcm, size_t hwbuf_size, const pa_sample_spec *ss) {
+ snd_pcm_sframes_t n;
+ size_t k;
+
+ pa_assert(pcm);
+ pa_assert(hwbuf_size > 0);
+ pa_assert(ss);
+
+ /* Some ALSA driver expose weird bugs, let's inform the user about
+ * what is going on */
+
+ n = snd_pcm_avail(pcm);
+
+ if (n <= 0)
+ return n;
+
+ k = (size_t) n * pa_frame_size(ss);
+
+ if (PA_UNLIKELY(k >= hwbuf_size * 5 ||
+ k >= pa_bytes_per_second(ss)*10)) {
+
+ PA_ONCE_BEGIN {
+ char *dn = pa_alsa_get_driver_name_by_pcm(pcm);
+ pa_log_debug(ngettext("snd_pcm_avail() returned a value that is exceptionally large: %lu byte (%lu ms).\n"
+ "Most likely this is a bug in the ALSA driver '%s'. Please report this issue to the ALSA developers.",
+ "snd_pcm_avail() returned a value that is exceptionally large: %lu bytes (%lu ms).\n"
+ "Most likely this is a bug in the ALSA driver '%s'. Please report this issue to the ALSA developers.",
+ (unsigned long) k),
+ (unsigned long) k,
+ (unsigned long) (pa_bytes_to_usec(k, ss) / PA_USEC_PER_MSEC),
+ pa_strnull(dn));
+ pa_xfree(dn);
+ pa_alsa_dump(PA_LOG_DEBUG, pcm);
+ } PA_ONCE_END;
+
+ /* Mhmm, let's try not to fail completely */
+ n = (snd_pcm_sframes_t) (hwbuf_size / pa_frame_size(ss));
+ }
+
+ return n;
+}
+
+int pa_alsa_safe_delay(snd_pcm_t *pcm, snd_pcm_status_t *status, snd_pcm_sframes_t *delay, size_t hwbuf_size, const pa_sample_spec *ss,
+ bool capture) {
+ ssize_t k;
+ size_t abs_k;
+ int err;
+ snd_pcm_sframes_t avail = 0;
+#if (SND_LIB_VERSION >= ((1<<16)|(1<<8)|0)) /* API additions in 1.1.0 */
+ snd_pcm_audio_tstamp_config_t tstamp_config;
+#endif
+
+ pa_assert(pcm);
+ pa_assert(delay);
+ pa_assert(hwbuf_size > 0);
+ pa_assert(ss);
+
+ /* Some ALSA driver expose weird bugs, let's inform the user about
+ * what is going on. We're going to get both the avail and delay values so
+ * that we can compare and check them for capture.
+ * This is done with snd_pcm_status() which provides
+ * avail, delay and timestamp values in a single kernel call to improve
+ * timer-based scheduling */
+
+#if (SND_LIB_VERSION >= ((1<<16)|(1<<8)|0)) /* API additions in 1.1.0 */
+
+ /* The time stamp configuration needs to be set so that the
+ * ALSA code will use the internal delay reported by the driver.
+ * The time stamp configuration was introduced in alsa version 1.1.0. */
+ tstamp_config.type_requested = 1; /* ALSA default time stamp type */
+ tstamp_config.report_delay = 1;
+ snd_pcm_status_set_audio_htstamp_config(status, &tstamp_config);
+#endif
+
+ if ((err = snd_pcm_status(pcm, status)) < 0)
+ return err;
+
+ avail = snd_pcm_status_get_avail(status);
+ *delay = snd_pcm_status_get_delay(status);
+
+ k = (ssize_t) *delay * (ssize_t) pa_frame_size(ss);
+
+ abs_k = k >= 0 ? (size_t) k : (size_t) -k;
+
+ if (PA_UNLIKELY(abs_k >= hwbuf_size * 5 ||
+ abs_k >= pa_bytes_per_second(ss)*10)) {
+
+ PA_ONCE_BEGIN {
+ char *dn = pa_alsa_get_driver_name_by_pcm(pcm);
+ pa_log_debug(ngettext("snd_pcm_delay() returned a value that is exceptionally large: %li byte (%s%lu ms).\n"
+ "Most likely this is a bug in the ALSA driver '%s'. Please report this issue to the ALSA developers.",
+ "snd_pcm_delay() returned a value that is exceptionally large: %li bytes (%s%lu ms).\n"
+ "Most likely this is a bug in the ALSA driver '%s'. Please report this issue to the ALSA developers.",
+ (signed long) k),
+ (signed long) k,
+ k < 0 ? "-" : "",
+ (unsigned long) (pa_bytes_to_usec(abs_k, ss) / PA_USEC_PER_MSEC),
+ pa_strnull(dn));
+ pa_xfree(dn);
+ pa_alsa_dump(PA_LOG_DEBUG, pcm);
+ } PA_ONCE_END;
+
+ /* Mhmm, let's try not to fail completely */
+ if (k < 0)
+ *delay = -(snd_pcm_sframes_t) (hwbuf_size / pa_frame_size(ss));
+ else
+ *delay = (snd_pcm_sframes_t) (hwbuf_size / pa_frame_size(ss));
+ }
+
+ if (capture) {
+ abs_k = (size_t) avail * pa_frame_size(ss);
+
+ if (PA_UNLIKELY(abs_k >= hwbuf_size * 5 ||
+ abs_k >= pa_bytes_per_second(ss)*10)) {
+
+ PA_ONCE_BEGIN {
+ char *dn = pa_alsa_get_driver_name_by_pcm(pcm);
+ pa_log_debug(ngettext("snd_pcm_avail() returned a value that is exceptionally large: %lu byte (%lu ms).\n"
+ "Most likely this is a bug in the ALSA driver '%s'. Please report this issue to the ALSA developers.",
+ "snd_pcm_avail() returned a value that is exceptionally large: %lu bytes (%lu ms).\n"
+ "Most likely this is a bug in the ALSA driver '%s'. Please report this issue to the ALSA developers.",
+ (unsigned long) k),
+ (unsigned long) k,
+ (unsigned long) (pa_bytes_to_usec(k, ss) / PA_USEC_PER_MSEC),
+ pa_strnull(dn));
+ pa_xfree(dn);
+ pa_alsa_dump(PA_LOG_DEBUG, pcm);
+ } PA_ONCE_END;
+
+ /* Mhmm, let's try not to fail completely */
+ avail = (snd_pcm_sframes_t) (hwbuf_size / pa_frame_size(ss));
+ }
+
+ if (PA_UNLIKELY(*delay < avail)) {
+ PA_ONCE_BEGIN {
+ char *dn = pa_alsa_get_driver_name_by_pcm(pcm);
+ pa_log(_("snd_pcm_avail_delay() returned strange values: delay %lu is less than avail %lu.\n"
+ "Most likely this is a bug in the ALSA driver '%s'. Please report this issue to the ALSA developers."),
+ (unsigned long) *delay,
+ (unsigned long) avail,
+ pa_strnull(dn));
+ pa_xfree(dn);
+ pa_alsa_dump(PA_LOG_ERROR, pcm);
+ } PA_ONCE_END;
+
+ /* try to fixup */
+ *delay = avail;
+ }
+ }
+
+ return 0;
+}
+
+int pa_alsa_safe_mmap_begin(snd_pcm_t *pcm, const snd_pcm_channel_area_t **areas, snd_pcm_uframes_t *offset, snd_pcm_uframes_t *frames, size_t hwbuf_size, const pa_sample_spec *ss) {
+ int r;
+ snd_pcm_uframes_t before;
+ size_t k;
+
+ pa_assert(pcm);
+ pa_assert(areas);
+ pa_assert(offset);
+ pa_assert(frames);
+ pa_assert(hwbuf_size > 0);
+ pa_assert(ss);
+
+ before = *frames;
+
+ r = snd_pcm_mmap_begin(pcm, areas, offset, frames);
+
+ if (r < 0)
+ return r;
+
+ k = (size_t) *frames * pa_frame_size(ss);
+
+ if (PA_UNLIKELY(*frames > before ||
+ k >= hwbuf_size * 3 ||
+ k >= pa_bytes_per_second(ss)*10))
+ PA_ONCE_BEGIN {
+ char *dn = pa_alsa_get_driver_name_by_pcm(pcm);
+ pa_log_debug(ngettext("snd_pcm_mmap_begin() returned a value that is exceptionally large: %lu byte (%lu ms).\n"
+ "Most likely this is a bug in the ALSA driver '%s'. Please report this issue to the ALSA developers.",
+ "snd_pcm_mmap_begin() returned a value that is exceptionally large: %lu bytes (%lu ms).\n"
+ "Most likely this is a bug in the ALSA driver '%s'. Please report this issue to the ALSA developers.",
+ (unsigned long) k),
+ (unsigned long) k,
+ (unsigned long) (pa_bytes_to_usec(k, ss) / PA_USEC_PER_MSEC),
+ pa_strnull(dn));
+ pa_xfree(dn);
+ pa_alsa_dump(PA_LOG_DEBUG, pcm);
+ } PA_ONCE_END;
+
+ return r;
+}
+
+char *pa_alsa_get_driver_name(int card) {
+ char *t, *m, *n;
+
+ pa_assert(card >= 0);
+
+ t = pa_sprintf_malloc("/sys/class/sound/card%i/device/driver/module", card);
+ m = pa_readlink(t);
+ pa_xfree(t);
+
+ if (!m)
+ return NULL;
+
+ n = pa_xstrdup(pa_path_get_filename(m));
+ pa_xfree(m);
+
+ return n;
+}
+
+char *pa_alsa_get_driver_name_by_pcm(snd_pcm_t *pcm) {
+ int card;
+ snd_pcm_info_t* info;
+ snd_pcm_info_alloca(&info);
+
+ pa_assert(pcm);
+
+ if (snd_pcm_info(pcm, info) < 0)
+ return NULL;
+
+ if ((card = snd_pcm_info_get_card(info)) < 0)
+ return NULL;
+
+ return pa_alsa_get_driver_name(card);
+}
+
+char *pa_alsa_get_reserve_name(const char *device) {
+ const char *t;
+ int i;
+
+ pa_assert(device);
+
+ if ((t = strchr(device, ':')))
+ device = t+1;
+
+ if ((i = snd_card_get_index(device)) < 0) {
+ int32_t k;
+
+ if (pa_atoi(device, &k) < 0)
+ return NULL;
+
+ i = (int) k;
+ }
+
+ return pa_sprintf_malloc("Audio%i", i);
+}
+
+unsigned int *pa_alsa_get_supported_rates(snd_pcm_t *pcm, unsigned int fallback_rate) {
+ static unsigned int all_rates[] = { 8000, 11025, 12000,
+ 16000, 22050, 24000,
+ 32000, 44100, 48000,
+ 64000, 88200, 96000,
+ 128000, 176400, 192000,
+ 384000 };
+ bool supported[PA_ELEMENTSOF(all_rates)] = { false, };
+ snd_pcm_hw_params_t *hwparams;
+ unsigned int i, j, n, *rates = NULL;
+ int ret;
+
+ snd_pcm_hw_params_alloca(&hwparams);
+
+ if ((ret = snd_pcm_hw_params_any(pcm, hwparams)) < 0) {
+ pa_log_debug("snd_pcm_hw_params_any() failed: %s", pa_alsa_strerror(ret));
+ return NULL;
+ }
+
+ for (i = 0, n = 0; i < PA_ELEMENTSOF(all_rates); i++) {
+ if (snd_pcm_hw_params_test_rate(pcm, hwparams, all_rates[i], 0) == 0) {
+ supported[i] = true;
+ n++;
+ }
+ }
+
+ if (n > 0) {
+ rates = pa_xnew(unsigned int, n + 1);
+
+ for (i = 0, j = 0; i < PA_ELEMENTSOF(all_rates); i++) {
+ if (supported[i])
+ rates[j++] = all_rates[i];
+ }
+
+ rates[j] = 0;
+ } else {
+ rates = pa_xnew(unsigned int, 2);
+
+ rates[0] = fallback_rate;
+ if ((ret = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rates[0], NULL)) < 0) {
+ pa_log_debug("snd_pcm_hw_params_set_rate_near() failed: %s", pa_alsa_strerror(ret));
+ pa_xfree(rates);
+ return NULL;
+ }
+
+ rates[1] = 0;
+ }
+
+ return rates;
+}
+
+pa_sample_format_t *pa_alsa_get_supported_formats(snd_pcm_t *pcm, pa_sample_format_t fallback_format) {
+ static const snd_pcm_format_t format_trans_to_pa[] = {
+ [SND_PCM_FORMAT_U8] = PA_SAMPLE_U8,
+ [SND_PCM_FORMAT_A_LAW] = PA_SAMPLE_ALAW,
+ [SND_PCM_FORMAT_MU_LAW] = PA_SAMPLE_ULAW,
+ [SND_PCM_FORMAT_S16_LE] = PA_SAMPLE_S16LE,
+ [SND_PCM_FORMAT_S16_BE] = PA_SAMPLE_S16BE,
+ [SND_PCM_FORMAT_FLOAT_LE] = PA_SAMPLE_FLOAT32LE,
+ [SND_PCM_FORMAT_FLOAT_BE] = PA_SAMPLE_FLOAT32BE,
+ [SND_PCM_FORMAT_S32_LE] = PA_SAMPLE_S32LE,
+ [SND_PCM_FORMAT_S32_BE] = PA_SAMPLE_S32BE,
+ [SND_PCM_FORMAT_S24_3LE] = PA_SAMPLE_S24LE,
+ [SND_PCM_FORMAT_S24_3BE] = PA_SAMPLE_S24BE,
+ [SND_PCM_FORMAT_S24_LE] = PA_SAMPLE_S24_32LE,
+ [SND_PCM_FORMAT_S24_BE] = PA_SAMPLE_S24_32BE,
+ };
+ static const snd_pcm_format_t all_formats[] = {
+ SND_PCM_FORMAT_U8,
+ SND_PCM_FORMAT_A_LAW,
+ SND_PCM_FORMAT_MU_LAW,
+ SND_PCM_FORMAT_S16_LE,
+ SND_PCM_FORMAT_S16_BE,
+ SND_PCM_FORMAT_FLOAT_LE,
+ SND_PCM_FORMAT_FLOAT_BE,
+ SND_PCM_FORMAT_S32_LE,
+ SND_PCM_FORMAT_S32_BE,
+ SND_PCM_FORMAT_S24_3LE,
+ SND_PCM_FORMAT_S24_3BE,
+ SND_PCM_FORMAT_S24_LE,
+ SND_PCM_FORMAT_S24_BE,
+ };
+ bool supported[PA_ELEMENTSOF(all_formats)] = {
+ false,
+ };
+ snd_pcm_hw_params_t *hwparams;
+ unsigned int i, j, n;
+ pa_sample_format_t *formats = NULL;
+ int ret;
+
+ snd_pcm_hw_params_alloca(&hwparams);
+
+ if ((ret = snd_pcm_hw_params_any(pcm, hwparams)) < 0) {
+ pa_log_debug("snd_pcm_hw_params_any() failed: %s", pa_alsa_strerror(ret));
+ return NULL;
+ }
+
+ for (i = 0, n = 0; i < PA_ELEMENTSOF(all_formats); i++) {
+ if (snd_pcm_hw_params_test_format(pcm, hwparams, all_formats[i]) == 0) {
+ supported[i] = true;
+ n++;
+ }
+ }
+
+ if (n > 0) {
+ formats = pa_xnew(pa_sample_format_t, n + 1);
+
+ for (i = 0, j = 0; i < PA_ELEMENTSOF(all_formats); i++) {
+ if (supported[i])
+ formats[j++] = format_trans_to_pa[all_formats[i]];
+ }
+
+ formats[j] = PA_SAMPLE_MAX;
+ } else {
+ formats = pa_xnew(pa_sample_format_t, 2);
+
+ formats[0] = fallback_format;
+ if ((ret = snd_pcm_hw_params_set_format(pcm, hwparams, format_trans_to_pa[formats[0]])) < 0) {
+ pa_log_debug("snd_pcm_hw_params_set_format() failed: %s", pa_alsa_strerror(ret));
+ pa_xfree(formats);
+ return NULL;
+ }
+
+ formats[1] = PA_SAMPLE_MAX;
+ }
+
+ return formats;
+}
+
+bool pa_alsa_pcm_is_hw(snd_pcm_t *pcm) {
+ snd_pcm_info_t* info;
+ snd_pcm_info_alloca(&info);
+
+ pa_assert(pcm);
+
+ if (snd_pcm_info(pcm, info) < 0)
+ return false;
+
+ return snd_pcm_info_get_card(info) >= 0;
+}
+
+bool pa_alsa_pcm_is_modem(snd_pcm_t *pcm) {
+ snd_pcm_info_t* info;
+ snd_pcm_info_alloca(&info);
+
+ pa_assert(pcm);
+
+ if (snd_pcm_info(pcm, info) < 0)
+ return false;
+
+ return snd_pcm_info_get_class(info) == SND_PCM_CLASS_MODEM;
+}
+
+PA_STATIC_TLS_DECLARE(cstrerror, pa_xfree);
+
+const char* pa_alsa_strerror(int errnum) {
+ const char *original = NULL;
+ char *translated, *t;
+ char errbuf[128];
+
+ if ((t = PA_STATIC_TLS_GET(cstrerror)))
+ pa_xfree(t);
+
+ original = snd_strerror(errnum);
+
+ if (!original) {
+ pa_snprintf(errbuf, sizeof(errbuf), "Unknown error %i", errnum);
+ original = errbuf;
+ }
+
+ if (!(translated = pa_locale_to_utf8(original))) {
+ pa_log_warn("Unable to convert error string to locale, filtering.");
+ translated = pa_utf8_filter(original);
+ }
+
+ PA_STATIC_TLS_SET(cstrerror, translated);
+
+ return translated;
+}
+
+bool pa_alsa_may_tsched(bool want) {
+
+ if (!want)
+ return false;
+
+ if (!pa_rtclock_hrtimer()) {
+ /* We cannot depend on being woken up in time when the timers
+ are inaccurate, so let's fallback to classic IO based playback
+ then. */
+ pa_log_notice("Disabling timer-based scheduling because high-resolution timers are not available from the kernel.");
+ return false; }
+
+ if (pa_running_in_vm()) {
+ /* We cannot depend on being woken up when we ask for in a VM,
+ * so let's fallback to classic IO based playback then. */
+ pa_log_notice("Disabling timer-based scheduling because running inside a VM.");
+ return false;
+ }
+
+ return true;
+}
+
+#define SND_MIXER_ELEM_PULSEAUDIO (SND_MIXER_ELEM_LAST + 10)
+
+static snd_mixer_elem_t *pa_alsa_mixer_find(snd_mixer_t *mixer,
+ snd_ctl_elem_iface_t iface,
+ const char *name,
+ unsigned int index,
+ unsigned int device) {
+ snd_mixer_elem_t *elem;
+
+ for (elem = snd_mixer_first_elem(mixer); elem; elem = snd_mixer_elem_next(elem)) {
+ snd_hctl_elem_t *helem;
+ if (snd_mixer_elem_get_type(elem) != SND_MIXER_ELEM_PULSEAUDIO)
+ continue;
+ helem = snd_mixer_elem_get_private(elem);
+ if (snd_hctl_elem_get_interface(helem) != iface)
+ continue;
+ if (!pa_streq(snd_hctl_elem_get_name(helem), name))
+ continue;
+ if (snd_hctl_elem_get_index(helem) != index)
+ continue;
+ if (snd_hctl_elem_get_device(helem) != device)
+ continue;
+ return elem;
+ }
+ return NULL;
+}
+
+snd_mixer_elem_t *pa_alsa_mixer_find_card(snd_mixer_t *mixer, struct pa_alsa_mixer_id *alsa_id, unsigned int device) {
+ return pa_alsa_mixer_find(mixer, SND_CTL_ELEM_IFACE_CARD, alsa_id->name, alsa_id->index, device);
+}
+
+snd_mixer_elem_t *pa_alsa_mixer_find_pcm(snd_mixer_t *mixer, const char *name, unsigned int device) {
+ return pa_alsa_mixer_find(mixer, SND_CTL_ELEM_IFACE_PCM, name, 0, device);
+}
+
+static int mixer_class_compare(const snd_mixer_elem_t *c1, const snd_mixer_elem_t *c2)
+{
+ /* Dummy compare function */
+ return c1 == c2 ? 0 : (c1 > c2 ? 1 : -1);
+}
+
+static int mixer_class_event(snd_mixer_class_t *class, unsigned int mask,
+ snd_hctl_elem_t *helem, snd_mixer_elem_t *melem)
+{
+ int err;
+ const char *name = snd_hctl_elem_get_name(helem);
+ if (mask & SND_CTL_EVENT_MASK_ADD) {
+ snd_ctl_elem_iface_t iface = snd_hctl_elem_get_interface(helem);
+ if (iface == SND_CTL_ELEM_IFACE_CARD || iface == SND_CTL_ELEM_IFACE_PCM) {
+ snd_mixer_elem_t *new_melem;
+
+ /* Put the hctl pointer as our private data - it will be useful for callbacks */
+ if ((err = snd_mixer_elem_new(&new_melem, SND_MIXER_ELEM_PULSEAUDIO, 0, helem, NULL)) < 0) {
+ pa_log_warn("snd_mixer_elem_new failed: %s", pa_alsa_strerror(err));
+ return 0;
+ }
+
+ if ((err = snd_mixer_elem_attach(new_melem, helem)) < 0) {
+ pa_log_warn("snd_mixer_elem_attach failed: %s", pa_alsa_strerror(err));
+ snd_mixer_elem_free(melem);
+ return 0;
+ }
+
+ if ((err = snd_mixer_elem_add(new_melem, class)) < 0) {
+ pa_log_warn("snd_mixer_elem_add failed: %s", pa_alsa_strerror(err));
+ return 0;
+ }
+ }
+ }
+ else if (mask & SND_CTL_EVENT_MASK_VALUE) {
+ snd_mixer_elem_value(melem); /* Calls the element callback */
+ return 0;
+ }
+ else
+ pa_log_info("Got an unknown mixer class event for %s: mask 0x%x", name, mask);
+
+ return 0;
+}
+
+static int prepare_mixer(snd_mixer_t *mixer, const char *dev) {
+ int err;
+ snd_mixer_class_t *class;
+
+ pa_assert(mixer);
+ pa_assert(dev);
+
+ if ((err = snd_mixer_attach(mixer, dev)) < 0) {
+ pa_log_info("Unable to attach to mixer %s: %s", dev, pa_alsa_strerror(err));
+ return -1;
+ }
+
+ if (snd_mixer_class_malloc(&class)) {
+ pa_log_info("Failed to allocate mixer class for %s", dev);
+ return -1;
+ }
+ snd_mixer_class_set_event(class, mixer_class_event);
+ snd_mixer_class_set_compare(class, mixer_class_compare);
+ if ((err = snd_mixer_class_register(class, mixer)) < 0) {
+ pa_log_info("Unable register mixer class for %s: %s", dev, pa_alsa_strerror(err));
+ snd_mixer_class_free(class);
+ return -1;
+ }
+ /* From here on, the mixer class is deallocated by alsa on snd_mixer_close/free. */
+
+ if ((err = snd_mixer_selem_register(mixer, NULL, NULL)) < 0) {
+ pa_log_warn("Unable to register mixer: %s", pa_alsa_strerror(err));
+ return -1;
+ }
+
+ if ((err = snd_mixer_load(mixer)) < 0) {
+ pa_log_warn("Unable to load mixer: %s", pa_alsa_strerror(err));
+ return -1;
+ }
+
+ pa_log_info("Successfully attached to mixer '%s'", dev);
+ return 0;
+}
+
+snd_mixer_t *pa_alsa_open_mixer(pa_hashmap *mixers, int alsa_card_index, bool probe) {
+ char *md = pa_sprintf_malloc("hw:%i", alsa_card_index);
+ snd_mixer_t *m = pa_alsa_open_mixer_by_name(mixers, md, probe);
+ pa_xfree(md);
+ return m;
+}
+
+snd_mixer_t *pa_alsa_open_mixer_by_name(pa_hashmap *mixers, const char *dev, bool probe) {
+ int err;
+ snd_mixer_t *m;
+ pa_alsa_mixer *pm;
+ char *dev2;
+ void *state;
+
+ pa_assert(mixers);
+ pa_assert(dev);
+
+ pm = pa_hashmap_get(mixers, dev);
+
+ /* The quick card number/index lookup (hw:#)
+ * We already know the card number/index, thus use the mixer
+ * from the cache at first.
+ */
+ if (!pm && pa_strneq(dev, "hw:", 3)) {
+ const char *s = dev + 3;
+ int card_index;
+ while (*s && *s >= '0' && *s <= '9') s++;
+ if (*s == '\0' && pa_atoi(dev + 3, &card_index) >= 0) {
+ PA_HASHMAP_FOREACH_KV(dev2, pm, mixers, state) {
+ if (pm->card_index == card_index) {
+ dev = dev2;
+ pm = pa_hashmap_get(mixers, dev);
+ break;
+ }
+ }
+ }
+ }
+
+ if (pm) {
+ if (!probe)
+ pm->used_for_probe_only = false;
+ return pm->mixer_handle;
+ }
+
+ if ((err = snd_mixer_open(&m, 0)) < 0) {
+ pa_log("Error opening mixer: %s", pa_alsa_strerror(err));
+ return NULL;
+ }
+
+ if (prepare_mixer(m, dev) >= 0) {
+ pm = pa_xnew0(pa_alsa_mixer, 1);
+ if (pm) {
+ snd_hctl_t *hctl;
+ pm->card_index = -1;
+ /* determine the ALSA card number (index) and store it to card_index */
+ err = snd_mixer_get_hctl(m, dev, &hctl);
+ if (err >= 0) {
+ snd_ctl_card_info_t *info;
+ snd_ctl_card_info_alloca(&info);
+ err = snd_ctl_card_info(snd_hctl_ctl(hctl), info);
+ if (err >= 0)
+ pm->card_index = snd_ctl_card_info_get_card(info);
+ }
+ pm->used_for_probe_only = probe;
+ pm->mixer_handle = m;
+ pa_hashmap_put(mixers, pa_xstrdup(dev), pm);
+ return m;
+ }
+ }
+
+ snd_mixer_close(m);
+ return NULL;
+}
+
+snd_mixer_t *pa_alsa_open_mixer_for_pcm(pa_hashmap *mixers, snd_pcm_t *pcm, bool probe) {
+ snd_pcm_info_t* info;
+ snd_pcm_info_alloca(&info);
+
+ pa_assert(pcm);
+
+ if (snd_pcm_info(pcm, info) >= 0) {
+ int card_idx;
+
+ if ((card_idx = snd_pcm_info_get_card(info)) >= 0)
+ return pa_alsa_open_mixer(mixers, card_idx, probe);
+ }
+
+ return NULL;
+}
+
+void pa_alsa_mixer_set_fdlist(pa_hashmap *mixers, snd_mixer_t *mixer_handle, pa_mainloop_api *ml)
+{
+ pa_alsa_mixer *pm;
+ void *state;
+
+ PA_HASHMAP_FOREACH(pm, mixers, state)
+ if (pm->mixer_handle == mixer_handle) {
+ pm->used_for_probe_only = false;
+ if (!pm->fdl) {
+ pm->fdl = pa_alsa_fdlist_new();
+ if (pm->fdl)
+ pa_alsa_fdlist_set_handle(pm->fdl, pm->mixer_handle, NULL, ml);
+ }
+ }
+}
+
+void pa_alsa_mixer_free(pa_alsa_mixer *mixer)
+{
+ if (mixer->fdl)
+ pa_alsa_fdlist_free(mixer->fdl);
+ if (mixer->mixer_handle)
+ snd_mixer_close(mixer->mixer_handle);
+ pa_xfree(mixer);
+}
+
+int pa_alsa_get_hdmi_eld(snd_hctl_elem_t *elem, pa_hdmi_eld *eld) {
+
+ /* The ELD format is specific to HDA Intel sound cards and defined in the
+ HDA specification: http://www.intel.com/content/www/us/en/standards/high-definition-audio-specification.html */
+ int err;
+ snd_ctl_elem_info_t *info;
+ snd_ctl_elem_value_t *value;
+ uint8_t *elddata;
+ unsigned int eldsize, mnl;
+ unsigned int device;
+
+ pa_assert(eld != NULL);
+ pa_assert(elem != NULL);
+
+ /* Does it have any contents? */
+ snd_ctl_elem_info_alloca(&info);
+ snd_ctl_elem_value_alloca(&value);
+ if ((err = snd_hctl_elem_info(elem, info)) < 0 ||
+ (err = snd_hctl_elem_read(elem, value)) < 0) {
+ pa_log_warn("Accessing ELD control failed with error %s", snd_strerror(err));
+ return -1;
+ }
+
+ device = snd_hctl_elem_get_device(elem);
+ eldsize = snd_ctl_elem_info_get_count(info);
+ elddata = (unsigned char *) snd_ctl_elem_value_get_bytes(value);
+ if (elddata == NULL || eldsize == 0) {
+ pa_log_debug("ELD info empty (for device=%d)", device);
+ return -1;
+ }
+ if (eldsize < 20 || eldsize > 256) {
+ pa_log_debug("ELD info has wrong size (for device=%d)", device);
+ return -1;
+ }
+
+ /* Try to fetch monitor name */
+ mnl = elddata[4] & 0x1f;
+ if (mnl == 0 || mnl > 16 || 20 + mnl > eldsize) {
+ pa_log_debug("No monitor name in ELD info (for device=%d)", device);
+ mnl = 0;
+ }
+ memcpy(eld->monitor_name, &elddata[20], mnl);
+ eld->monitor_name[mnl] = '\0';
+ if (mnl)
+ pa_log_debug("Monitor name in ELD info is '%s' (for device=%d)", eld->monitor_name, device);
+
+ return 0;
+}
diff --git a/src/modules/alsa/alsa-util.h b/src/modules/alsa/alsa-util.h
new file mode 100644
index 0000000..2eed3ea
--- /dev/null
+++ b/src/modules/alsa/alsa-util.h
@@ -0,0 +1,167 @@
+#ifndef fooalsautilhfoo
+#define fooalsautilhfoo
+
+/***
+ This file is part of PulseAudio.
+
+ Copyright 2004-2006 Lennart Poettering
+ Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
+
+ PulseAudio is free software; you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License,
+ or (at your option) any later version.
+
+ PulseAudio is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <alsa/asoundlib.h>
+
+#include <pulse/sample.h>
+#include <pulse/channelmap.h>
+#include <pulse/proplist.h>
+
+#include <pulsecore/rtpoll.h>
+#include <pulsecore/core.h>
+#include <pulsecore/log.h>
+
+#include "alsa-mixer.h"
+
+enum {
+ PA_ALSA_ERR_UNSPECIFIED = 1,
+ PA_ALSA_ERR_UCM_OPEN = 1000,
+ PA_ALSA_ERR_UCM_NO_VERB = 1001,
+ PA_ALSA_ERR_UCM_LINKED = 1002
+};
+
+int pa_alsa_set_hw_params(
+ snd_pcm_t *pcm_handle,
+ pa_sample_spec *ss, /* modified at return */
+ snd_pcm_uframes_t *period_size, /* modified at return */
+ snd_pcm_uframes_t *buffer_size, /* modified at return */
+ snd_pcm_uframes_t tsched_size,
+ bool *use_mmap, /* modified at return */
+ bool *use_tsched, /* modified at return */
+ bool require_exact_channel_number);
+
+int pa_alsa_set_sw_params(
+ snd_pcm_t *pcm,
+ snd_pcm_uframes_t avail_min,
+ bool period_event);
+
+/* Picks a working mapping from the profile set based on the specified ss/map */
+snd_pcm_t *pa_alsa_open_by_device_id_auto(
+ const char *dev_id,
+ char **dev, /* modified at return */
+ pa_sample_spec *ss, /* modified at return */
+ pa_channel_map* map, /* modified at return */
+ int mode,
+ snd_pcm_uframes_t *period_size, /* modified at return */
+ snd_pcm_uframes_t *buffer_size, /* modified at return */
+ snd_pcm_uframes_t tsched_size,
+ bool *use_mmap, /* modified at return */
+ bool *use_tsched, /* modified at return */
+ pa_alsa_profile_set *ps,
+ pa_alsa_mapping **mapping); /* modified at return */
+
+/* Uses the specified mapping */
+snd_pcm_t *pa_alsa_open_by_device_id_mapping(
+ const char *dev_id,
+ char **dev, /* modified at return */
+ pa_sample_spec *ss, /* modified at return */
+ pa_channel_map* map, /* modified at return */
+ int mode,
+ snd_pcm_uframes_t *period_size, /* modified at return */
+ snd_pcm_uframes_t *buffer_size, /* modified at return */
+ snd_pcm_uframes_t tsched_size,
+ bool *use_mmap, /* modified at return */
+ bool *use_tsched, /* modified at return */
+ pa_alsa_mapping *mapping);
+
+/* Opens the explicit ALSA device */
+snd_pcm_t *pa_alsa_open_by_device_string(
+ const char *dir,
+ char **dev, /* modified at return */
+ pa_sample_spec *ss, /* modified at return */
+ pa_channel_map* map, /* modified at return */
+ int mode,
+ snd_pcm_uframes_t *period_size, /* modified at return */
+ snd_pcm_uframes_t *buffer_size, /* modified at return */
+ snd_pcm_uframes_t tsched_size,
+ bool *use_mmap, /* modified at return */
+ bool *use_tsched, /* modified at return */
+ bool require_exact_channel_number);
+
+/* Opens the explicit ALSA device with a fallback list */
+snd_pcm_t *pa_alsa_open_by_template(
+ char **template,
+ const char *dev_id,
+ char **dev, /* modified at return */
+ pa_sample_spec *ss, /* modified at return */
+ pa_channel_map* map, /* modified at return */
+ int mode,
+ snd_pcm_uframes_t *period_size, /* modified at return */
+ snd_pcm_uframes_t *buffer_size, /* modified at return */
+ snd_pcm_uframes_t tsched_size,
+ bool *use_mmap, /* modified at return */
+ bool *use_tsched, /* modified at return */
+ bool require_exact_channel_number);
+
+void pa_alsa_dump(pa_log_level_t level, snd_pcm_t *pcm);
+void pa_alsa_dump_status(snd_pcm_t *pcm);
+
+void pa_alsa_refcnt_inc(void);
+void pa_alsa_refcnt_dec(void);
+
+void pa_alsa_init_proplist_pcm_info(pa_core *c, pa_proplist *p, snd_pcm_info_t *pcm_info);
+void pa_alsa_init_proplist_card(pa_core *c, pa_proplist *p, int card);
+void pa_alsa_init_proplist_pcm(pa_core *c, pa_proplist *p, snd_pcm_t *pcm);
+void pa_alsa_init_proplist_ctl(pa_proplist *p, const char *name);
+bool pa_alsa_init_description(pa_proplist *p, pa_card *card);
+
+int pa_alsa_recover_from_poll(snd_pcm_t *pcm, int revents);
+
+pa_rtpoll_item* pa_alsa_build_pollfd(snd_pcm_t *pcm, pa_rtpoll *rtpoll);
+
+snd_pcm_sframes_t pa_alsa_safe_avail(snd_pcm_t *pcm, size_t hwbuf_size, const pa_sample_spec *ss);
+int pa_alsa_safe_delay(snd_pcm_t *pcm, snd_pcm_status_t *status, snd_pcm_sframes_t *delay, size_t hwbuf_size, const pa_sample_spec *ss, bool capture);
+int pa_alsa_safe_mmap_begin(snd_pcm_t *pcm, const snd_pcm_channel_area_t **areas, snd_pcm_uframes_t *offset, snd_pcm_uframes_t *frames, size_t hwbuf_size, const pa_sample_spec *ss);
+
+char *pa_alsa_get_driver_name(int card);
+char *pa_alsa_get_driver_name_by_pcm(snd_pcm_t *pcm);
+
+char *pa_alsa_get_reserve_name(const char *device);
+
+unsigned int *pa_alsa_get_supported_rates(snd_pcm_t *pcm, unsigned int fallback_rate);
+pa_sample_format_t *pa_alsa_get_supported_formats(snd_pcm_t *pcm, pa_sample_format_t fallback_format);
+
+bool pa_alsa_pcm_is_hw(snd_pcm_t *pcm);
+bool pa_alsa_pcm_is_modem(snd_pcm_t *pcm);
+
+const char* pa_alsa_strerror(int errnum);
+
+bool pa_alsa_may_tsched(bool want);
+
+snd_mixer_elem_t *pa_alsa_mixer_find_card(snd_mixer_t *mixer, struct pa_alsa_mixer_id *alsa_id, unsigned int device);
+snd_mixer_elem_t *pa_alsa_mixer_find_pcm(snd_mixer_t *mixer, const char *name, unsigned int device);
+
+snd_mixer_t *pa_alsa_open_mixer(pa_hashmap *mixers, int alsa_card_index, bool probe);
+snd_mixer_t *pa_alsa_open_mixer_by_name(pa_hashmap *mixers, const char *dev, bool probe);
+snd_mixer_t *pa_alsa_open_mixer_for_pcm(pa_hashmap *mixers, snd_pcm_t *pcm, bool probe);
+void pa_alsa_mixer_set_fdlist(pa_hashmap *mixers, snd_mixer_t *mixer, pa_mainloop_api *ml);
+void pa_alsa_mixer_free(pa_alsa_mixer *mixer);
+
+typedef struct pa_hdmi_eld pa_hdmi_eld;
+struct pa_hdmi_eld {
+ char monitor_name[17];
+};
+
+int pa_alsa_get_hdmi_eld(snd_hctl_elem_t *elem, pa_hdmi_eld *eld);
+
+#endif
diff --git a/src/modules/alsa/meson.build b/src/modules/alsa/meson.build
new file mode 100644
index 0000000..f31eeb5
--- /dev/null
+++ b/src/modules/alsa/meson.build
@@ -0,0 +1,51 @@
+libalsa_util_sources = [
+ 'alsa-util.c',
+ 'alsa-ucm.c',
+ 'alsa-mixer.c',
+ 'alsa-sink.c',
+ 'alsa-source.c',
+ '../reserve-wrap.c',
+]
+
+libalsa_util_headers = [
+ 'alsa-util.h',
+ 'alsa-ucm.h',
+ 'alsa-mixer.h',
+ 'alsa-sink.h',
+ 'alsa-source.h',
+ '../reserve-wrap.h',
+]
+
+if dbus_dep.found()
+ libalsa_util_sources += [ '../reserve.c', '../reserve-monitor.c' ]
+ libalsa_util_headers += [ '../reserve.h', '../reserve-monitor.h' ]
+endif
+
+if udev_dep.found()
+ libalsa_util_sources += [ '../udev-util.c' ]
+ libalsa_util_headers += [ '../udev-util.h' ]
+endif
+
+libalsa_util = shared_library('alsa-util',
+ libalsa_util_sources,
+ libalsa_util_headers,
+ c_args : [pa_c_args, server_c_args],
+ link_args : [nodelete_link_args],
+ include_directories : [configinc, topinc],
+ dependencies : [libpulse_dep, libpulsecommon_dep, libpulsecore_dep, alsa_dep, dbus_dep, libatomic_ops_dep, libm_dep, udev_dep, libintl_dep],
+ install : true,
+ install_rpath : privlibdir,
+ install_dir : modlibexecdir,
+)
+
+alsa_udevrules = [
+ '90-pulseaudio.rules',
+]
+
+if udev_dep.found()
+ install_data(alsa_udevrules,
+ install_dir : udevrulesdir,
+ )
+endif
+
+subdir('mixer')
diff --git a/src/modules/alsa/mixer/meson.build b/src/modules/alsa/mixer/meson.build
new file mode 100644
index 0000000..d4327b8
--- /dev/null
+++ b/src/modules/alsa/mixer/meson.build
@@ -0,0 +1,7 @@
+install_subdir('paths',
+ install_dir : alsadatadir
+)
+
+install_subdir('profile-sets',
+ install_dir : alsadatadir
+)
diff --git a/src/modules/alsa/mixer/paths/analog-input-aux.conf b/src/modules/alsa/mixer/paths/analog-input-aux.conf
new file mode 100644
index 0000000..47e22c5
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-input-aux.conf
@@ -0,0 +1,65 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; For devices where an 'Aux' element exists
+;
+; See analog-output.conf.common for an explanation on the directives
+
+[General]
+priority = 80
+description-key = analog-input
+
+[Element Capture]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Mic]
+switch = off
+volume = off
+
+[Element Internal Mic]
+switch = off
+volume = off
+
+[Element Line]
+switch = off
+volume = off
+
+[Element Aux]
+required = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Video]
+switch = off
+volume = off
+
+[Element Mic/Line]
+switch = off
+volume = off
+
+[Element TV Tuner]
+switch = off
+volume = off
+
+[Element FM]
+switch = off
+volume = off
+
+.include analog-input.conf.common
diff --git a/src/modules/alsa/mixer/paths/analog-input-dock-mic.conf b/src/modules/alsa/mixer/paths/analog-input-dock-mic.conf
new file mode 100644
index 0000000..96861e7
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-input-dock-mic.conf
@@ -0,0 +1,104 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; For devices where a 'Dock Mic' or 'Dock Mic Boost' element exists
+;
+; See analog-output.conf.common for an explanation on the directives
+
+[General]
+priority = 78
+description-key = analog-input-microphone-dock
+
+[Jack Dock Mic]
+required-any = any
+
+[Jack Dock Mic Phantom]
+state.plugged = unknown
+state.unplugged = unknown
+required-any = any
+
+[Element Capture]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Dock Mic Boost]
+required-any = any
+switch = select
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Option Dock Mic Boost:on]
+name = input-boost-on
+
+[Option Dock Mic Boost:off]
+name = input-boost-off
+
+[Element Dock Mic]
+required-any = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Input Source]
+enumeration = select
+
+[Option Input Source:Dock Mic]
+name = analog-input-microphone-dock
+required-any = any
+
+[Element Capture Source]
+enumeration = select
+
+[Option Capture Source:Dock Mic]
+name = analog-input-microphone-dock
+required-any = any
+
+[Element Mic]
+switch = off
+volume = off
+
+[Element Internal Mic]
+switch = off
+volume = off
+
+[Element Front Mic]
+switch = off
+volume = off
+
+[Element Rear Mic]
+switch = off
+volume = off
+
+[Element Mic Boost]
+switch = off
+volume = off
+
+[Element Internal Mic Boost]
+switch = off
+volume = off
+
+[Element Front Mic Boost]
+switch = off
+volume = off
+
+[Element Rear Mic Boost]
+switch = off
+volume = off
+
+.include analog-input-mic.conf.common
diff --git a/src/modules/alsa/mixer/paths/analog-input-fm.conf b/src/modules/alsa/mixer/paths/analog-input-fm.conf
new file mode 100644
index 0000000..d3501a8
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-input-fm.conf
@@ -0,0 +1,65 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; For devices where an 'FM' element exists
+;
+; See analog-output.conf.common for an explanation on the directives
+
+[General]
+priority = 70
+description-key = analog-input-radio
+
+[Element Capture]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Mic]
+switch = off
+volume = off
+
+[Element Internal Mic]
+switch = off
+volume = off
+
+[Element Line]
+switch = off
+volume = off
+
+[Element Aux]
+switch = off
+volume = off
+
+[Element Video]
+switch = off
+volume = off
+
+[Element Mic/Line]
+switch = off
+volume = off
+
+[Element TV Tuner]
+switch = off
+volume = off
+
+[Element FM]
+required = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+.include analog-input.conf.common
diff --git a/src/modules/alsa/mixer/paths/analog-input-front-mic.conf b/src/modules/alsa/mixer/paths/analog-input-front-mic.conf
new file mode 100644
index 0000000..6e7775c
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-input-front-mic.conf
@@ -0,0 +1,104 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; For devices where a 'Front Mic' or 'Front Mic Boost' element exists
+;
+; See analog-output.conf.common for an explanation on the directives
+
+[General]
+priority = 85
+description-key = analog-input-microphone-front
+
+[Jack Front Mic]
+required-any = any
+
+[Jack Front Mic Phantom]
+required-any = any
+state.plugged = unknown
+state.unplugged = unknown
+
+[Element Capture]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Front Mic Boost]
+required-any = any
+switch = select
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Option Front Mic Boost:on]
+name = input-boost-on
+
+[Option Front Mic Boost:off]
+name = input-boost-off
+
+[Element Front Mic]
+required-any = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Input Source]
+enumeration = select
+
+[Option Input Source:Front Mic]
+name = analog-input-microphone-front
+required-any = any
+
+[Element Capture Source]
+enumeration = select
+
+[Option Capture Source:Front Mic]
+name = analog-input-microphone-front
+required-any = any
+
+[Element Mic]
+switch = off
+volume = off
+
+[Element Internal Mic]
+switch = off
+volume = off
+
+[Element Rear Mic]
+switch = off
+volume = off
+
+[Element Dock Mic]
+switch = off
+volume = off
+
+[Element Mic Boost]
+switch = off
+volume = off
+
+[Element Dock Mic Boost]
+switch = off
+volume = off
+
+[Element Internal Mic Boost]
+switch = off
+volume = off
+
+[Element Rear Mic Boost]
+switch = off
+volume = off
+
+.include analog-input-mic.conf.common
diff --git a/src/modules/alsa/mixer/paths/analog-input-headphone-mic.conf b/src/modules/alsa/mixer/paths/analog-input-headphone-mic.conf
new file mode 100644
index 0000000..eb5740a
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-input-headphone-mic.conf
@@ -0,0 +1,102 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; For some ASUS netbooks that have one jack that can be either a Headphone
+; *or* a mic. This path will be active only when it is used as a mic.
+;
+; See analog-output.conf.common for an explanation on the directives
+
+[General]
+priority = 87
+description-key = analog-input-microphone
+
+[Jack Headphone Mic]
+required-any = any
+state.plugged = unknown
+
+[Element Capture]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Headphone Mic Boost]
+required-any = any
+switch = select
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Headphone Mic]
+required-any = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Input Source]
+enumeration = select
+
+[Option Input Source:Headphone Mic]
+name = analog-input-microphone
+required-any = any
+
+[Element Capture Source]
+enumeration = select
+
+[Option Capture Source:Headphone Mic]
+name = analog-input-microphone
+required-any = any
+
+; Make sure the internal speakers are not auto-muted when you plug a mic in
+[Element Auto-Mute Mode]
+enumeration = select
+
+[Option Auto-Mute Mode:Disabled]
+name = analog-input-microphone
+
+[Element Front Mic]
+switch = off
+volume = off
+
+[Element Internal Mic]
+switch = off
+volume = off
+
+[Element Rear Mic]
+switch = off
+volume = off
+
+[Element Dock Mic]
+switch = off
+volume = off
+
+[Element Dock Mic Boost]
+switch = off
+volume = off
+
+[Element Internal Mic Boost]
+switch = off
+volume = off
+
+[Element Front Mic Boost]
+switch = off
+volume = off
+
+[Element Rear Mic Boost]
+switch = off
+volume = off
+
+.include analog-input-mic.conf.common
diff --git a/src/modules/alsa/mixer/paths/analog-input-headset-mic.conf b/src/modules/alsa/mixer/paths/analog-input-headset-mic.conf
new file mode 100644
index 0000000..579db6b
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-input-headset-mic.conf
@@ -0,0 +1,114 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; For devices where a 'Headset Mic' or 'Headset Mic Boost' element exists
+;
+; See analog-output.conf.common for an explanation on the directives
+
+[General]
+priority = 88
+description-key = analog-input-microphone-headset
+
+[Jack Headset Mic]
+required-any = any
+
+[Jack Headset Mic Phantom]
+state.plugged = unknown
+state.unplugged = unknown
+required-any = any
+
+[Jack Headphone]
+state.plugged = unknown
+
+[Jack Front Headphone]
+state.plugged = unknown
+
+[Jack Headphone Mic]
+state.plugged = unknown
+
+[Element Capture]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Headset Mic Boost]
+required-any = any
+switch = select
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Headset Mic]
+required-any = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Headset]
+required-any = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Input Source]
+enumeration = select
+
+[Option Input Source:Headset Mic]
+name = Headset Microphone
+required-any = any
+
+[Element Capture Source]
+enumeration = select
+
+[Option Capture Source:Headset Mic]
+name = Headset Microphone
+required-any = any
+
+[Element Front Mic]
+switch = off
+volume = off
+
+[Element Internal Mic]
+switch = off
+volume = off
+
+[Element Rear Mic]
+switch = off
+volume = off
+
+[Element Dock Mic]
+switch = off
+volume = off
+
+[Element Dock Mic Boost]
+switch = off
+volume = off
+
+[Element Internal Mic Boost]
+switch = off
+volume = off
+
+[Element Front Mic Boost]
+switch = off
+volume = off
+
+[Element Rear Mic Boost]
+switch = off
+volume = off
+
+.include analog-input-mic.conf.common
diff --git a/src/modules/alsa/mixer/paths/analog-input-internal-mic-always.conf b/src/modules/alsa/mixer/paths/analog-input-internal-mic-always.conf
new file mode 100644
index 0000000..9e22008
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-input-internal-mic-always.conf
@@ -0,0 +1,133 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; For devices where a 'Internal Mic' or 'Internal Mic Boost' element exists
+; 'Int Mic' and 'Int Mic Boost' are for compatibility with kernels < 2.6.38
+;
+; See analog-output.conf.common for an explanation on the directives
+
+[General]
+priority = 89
+description-key = analog-input-microphone-internal
+
+[Jack Mic]
+state.plugged = no
+state.unplugged = unknown
+
+[Jack Dock Mic]
+state.plugged = no
+state.unplugged = unknown
+
+[Jack Front Mic]
+state.plugged = no
+state.unplugged = unknown
+
+[Jack Rear Mic]
+state.plugged = no
+state.unplugged = unknown
+
+[Element Capture]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Internal Mic Boost]
+switch = select
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Option Internal Mic Boost:on]
+name = input-boost-on
+
+[Option Internal Mic Boost:off]
+name = input-boost-off
+
+[Element Int Mic Boost]
+switch = select
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Option Int Mic Boost:on]
+name = input-boost-on
+
+[Option Int Mic Boost:off]
+name = input-boost-off
+
+[Element Internal Mic]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Int Mic]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Input Source]
+enumeration = select
+
+[Option Input Source:Internal Mic]
+name = analog-input-microphone-internal
+
+[Option Input Source:Int Mic]
+name = analog-input-microphone-internal
+
+[Element Capture Source]
+enumeration = select
+
+[Option Capture Source:Internal Mic]
+name = analog-input-microphone-internal
+
+[Option Capture Source:Int Mic]
+name = analog-input-microphone-internal
+
+[Element Mic]
+switch = off
+volume = off
+
+[Element Dock Mic]
+switch = off
+volume = off
+
+[Element Front Mic]
+switch = off
+volume = off
+
+[Element Rear Mic]
+switch = off
+volume = off
+
+[Element Mic Boost]
+switch = off
+volume = off
+
+[Element Dock Mic Boost]
+switch = off
+volume = off
+
+[Element Front Mic Boost]
+switch = off
+volume = off
+
+[Element Rear Mic Boost]
+switch = off
+volume = off
+
+.include analog-input-mic.conf.common
diff --git a/src/modules/alsa/mixer/paths/analog-input-internal-mic.conf b/src/modules/alsa/mixer/paths/analog-input-internal-mic.conf
new file mode 100644
index 0000000..898410a
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-input-internal-mic.conf
@@ -0,0 +1,154 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; For devices where a 'Internal Mic' or 'Internal Mic Boost' element exists
+; 'Int Mic' and 'Int Mic Boost' are for compatibility with kernels < 2.6.38
+;
+; See analog-output.conf.common for an explanation on the directives
+
+[General]
+priority = 89
+description-key = analog-input-microphone-internal
+
+[Jack Mic]
+state.plugged = no
+state.unplugged = unknown
+
+[Jack Dock Mic]
+state.plugged = no
+state.unplugged = unknown
+
+[Jack Front Mic]
+state.plugged = no
+state.unplugged = unknown
+
+[Jack Rear Mic]
+state.plugged = no
+state.unplugged = unknown
+
+[Jack Internal Mic Phantom]
+state.plugged = unknown
+state.unplugged = unknown
+required-any = any
+
+[Element Capture]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Internal Mic Boost]
+required-any = any
+switch = select
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Option Internal Mic Boost:on]
+name = input-boost-on
+
+[Option Internal Mic Boost:off]
+name = input-boost-off
+
+[Element Int Mic Boost]
+required-any = any
+switch = select
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Option Int Mic Boost:on]
+name = input-boost-on
+
+[Option Int Mic Boost:off]
+name = input-boost-off
+
+[Element Internal Mic]
+required-any = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Int Mic]
+required-any = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Input Source]
+enumeration = select
+
+[Option Input Source:Internal Mic]
+name = analog-input-microphone-internal
+required-any = any
+
+[Option Input Source:Int Mic]
+name = analog-input-microphone-internal
+required-any = any
+
+[Element Capture Source]
+enumeration = select
+
+[Option Capture Source:Internal Mic]
+name = analog-input-microphone-internal
+required-any = any
+
+[Option Capture Source:Int Mic]
+name = analog-input-microphone-internal
+required-any = any
+
+[Element Mic]
+switch = off
+volume = off
+
+[Element Dock Mic]
+switch = off
+volume = off
+
+[Element Front Mic]
+switch = off
+volume = off
+
+[Element Rear Mic]
+switch = off
+volume = off
+
+[Element Headphone Mic]
+switch = off
+volume = off
+
+[Element Headphone Mic Boost]
+switch = off
+volume = off
+
+[Element Mic Boost]
+switch = off
+volume = off
+
+[Element Dock Mic Boost]
+switch = off
+volume = off
+
+[Element Front Mic Boost]
+switch = off
+volume = off
+
+[Element Rear Mic Boost]
+switch = off
+volume = off
+
+.include analog-input-mic.conf.common
diff --git a/src/modules/alsa/mixer/paths/analog-input-linein.conf b/src/modules/alsa/mixer/paths/analog-input-linein.conf
new file mode 100644
index 0000000..cf20790
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-input-linein.conf
@@ -0,0 +1,144 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; For devices where a 'Line' element exists
+;
+; See analog-output.conf.common for an explanation on the directives
+
+[General]
+priority = 81
+
+[Jack Line]
+required-any = any
+
+[Jack Line Phantom]
+required-any = any
+state.plugged = unknown
+state.unplugged = unknown
+
+[Jack Line - Input]
+required-any = any
+
+[Element Capture]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Line Boost]
+required-any = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Line]
+required-any = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Input Source]
+enumeration = select
+
+[Option Input Source:Line]
+name = analog-input-linein
+required-any = any
+
+[Element Capture Source]
+enumeration = select
+
+[Option Capture Source:Line]
+name = analog-input-linein
+required-any = any
+
+[Element PCM Capture Source]
+enumeration = select
+
+[Option PCM Capture Source:Line]
+name = analog-input-linein
+required-any = any
+
+[Option PCM Capture Source:Line In]
+name = analog-input-linein
+required-any = any
+
+[Element Mic]
+switch = off
+volume = off
+
+[Element Dock Mic]
+switch = off
+volume = off
+
+[Element Internal Mic]
+switch = off
+volume = off
+
+[Element Front Mic]
+switch = off
+volume = off
+
+[Element Rear Mic]
+switch = off
+volume = off
+
+[Element Mic Boost]
+switch = off
+volume = off
+
+[Element Dock Mic Boost]
+switch = off
+volume = off
+
+[Element Internal Mic Boost]
+switch = off
+volume = off
+
+[Element Front Mic Boost]
+switch = off
+volume = off
+
+[Element Rear Mic Boost]
+switch = off
+volume = off
+
+[Element Aux]
+switch = off
+volume = off
+
+[Element Video]
+switch = off
+volume = off
+
+[Element Mic/Line]
+switch = off
+volume = off
+
+[Element TV Tuner]
+switch = off
+volume = off
+
+[Element FM]
+switch = off
+volume = off
+
+[Element Mic Jack Mode]
+enumeration = select
+
+[Option Mic Jack Mode:Line In]
+priority = 19
+name = input-linein
diff --git a/src/modules/alsa/mixer/paths/analog-input-mic-line.conf b/src/modules/alsa/mixer/paths/analog-input-mic-line.conf
new file mode 100644
index 0000000..7147d20
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-input-mic-line.conf
@@ -0,0 +1,66 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; For devices where a 'Mic/Line' element exists
+;
+; See analog-output.conf.common for an explanation on the directives
+
+[General]
+priority = 85
+description-key = analog-input
+
+[Element Capture]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Mic]
+switch = off
+volume = off
+
+[Element Internal Mic]
+switch = off
+volume = off
+
+[Element Line]
+switch = off
+volume = off
+
+[Element Aux]
+switch = off
+volume = off
+
+[Element Video]
+switch = off
+volume = off
+
+[Element Mic/Line]
+required = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element TV Tuner]
+switch = off
+volume = off
+
+[Element FM]
+switch = off
+volume = off
+
+.include analog-input.conf.common
+.include analog-input-mic.conf.common
diff --git a/src/modules/alsa/mixer/paths/analog-input-mic.conf b/src/modules/alsa/mixer/paths/analog-input-mic.conf
new file mode 100644
index 0000000..53c03c8
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-input-mic.conf
@@ -0,0 +1,141 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; For devices where a 'Mic' or 'Mic Boost' element exists
+;
+; See analog-output.conf.common for an explanation on the directives
+
+[General]
+priority = 87
+description-key = analog-input-microphone
+
+[Jack Mic]
+required-any = any
+
+[Jack Mic Phantom]
+required-any = any
+state.plugged = unknown
+state.unplugged = unknown
+
+[Jack Mic - Input]
+required-any = any
+
+[Element Capture]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Mic Boost]
+required-any = any
+switch = select
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Option Mic Boost:on]
+name = input-boost-on
+
+[Option Mic Boost:off]
+name = input-boost-off
+
+[Element Mic]
+required-any = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Input Source]
+enumeration = select
+
+[Option Input Source:Mic]
+name = analog-input-microphone
+required-any = any
+
+[Element Capture Source]
+enumeration = select
+
+[Option Capture Source:Mic]
+name = analog-input-microphone
+required-any = any
+
+[Element PCM Capture Source]
+enumeration = select
+
+[Option PCM Capture Source:Mic]
+name = analog-input-microphone
+required-any = any
+
+[Option PCM Capture Source:Mic-In/Mic Array]
+name = analog-input-microphone
+required-any = any
+
+;;; Some AC'97s have "Mic Select" and "Mic Boost (+20dB)"
+
+[Element Mic Select]
+enumeration = select
+
+[Option Mic Select:Mic1]
+name = input-microphone
+priority = 20
+
+[Option Mic Select:Mic2]
+name = input-microphone
+priority = 19
+
+[Element Mic Boost (+20dB)]
+switch = select
+volume = merge
+
+[Option Mic Boost (+20dB):on]
+name = input-boost-on
+
+[Option Mic Boost (+20dB):off]
+name = input-boost-off
+
+[Element Front Mic]
+switch = off
+volume = off
+
+[Element Internal Mic]
+switch = off
+volume = off
+
+[Element Rear Mic]
+switch = off
+volume = off
+
+[Element Dock Mic]
+switch = off
+volume = off
+
+[Element Dock Mic Boost]
+switch = off
+volume = off
+
+[Element Internal Mic Boost]
+switch = off
+volume = off
+
+[Element Front Mic Boost]
+switch = off
+volume = off
+
+[Element Rear Mic Boost]
+switch = off
+volume = off
+
+.include analog-input-mic.conf.common
diff --git a/src/modules/alsa/mixer/paths/analog-input-mic.conf.common b/src/modules/alsa/mixer/paths/analog-input-mic.conf.common
new file mode 100644
index 0000000..e5ced21
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-input-mic.conf.common
@@ -0,0 +1,60 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Common element for all microphone inputs
+;
+; See analog-output.conf.common for an explanation on the directives
+
+[Properties]
+device.icon_name = audio-input-microphone
+
+[Element Line]
+switch = off
+volume = off
+
+[Element Line Boost]
+switch = off
+volume = off
+
+[Element Aux]
+switch = off
+volume = off
+
+[Element Video]
+switch = off
+volume = off
+
+[Element Mic/Line]
+switch = off
+volume = off
+
+[Element TV Tuner]
+switch = off
+volume = off
+
+[Element FM]
+switch = off
+volume = off
+
+[Element Inverted Internal Mic]
+switch = off
+volume = off
+
+[Element Mic Jack Mode]
+enumeration = select
+
+[Option Mic Jack Mode:Mic In]
+priority = 19
+name = input-microphone
diff --git a/src/modules/alsa/mixer/paths/analog-input-rear-mic.conf b/src/modules/alsa/mixer/paths/analog-input-rear-mic.conf
new file mode 100644
index 0000000..7136193
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-input-rear-mic.conf
@@ -0,0 +1,104 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; For devices where a 'Rear Mic' or 'Rear Mic Boost' element exists
+;
+; See analog-output.conf.common for an explanation on the directives
+
+[General]
+priority = 82
+description-key = analog-input-microphone-rear
+
+[Jack Rear Mic]
+required-any = any
+
+[Jack Rear Mic Phantom]
+required-any = any
+state.plugged = unknown
+state.unplugged = unknown
+
+[Element Capture]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Rear Mic Boost]
+required-any = any
+switch = select
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Option Rear Mic Boost:on]
+name = input-boost-on
+
+[Option Rear Mic Boost:off]
+name = input-boost-off
+
+[Element Rear Mic]
+required-any = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Input Source]
+enumeration = select
+
+[Option Input Source:Rear Mic]
+name = analog-input-microphone-rear
+required-any = any
+
+[Element Capture Source]
+enumeration = select
+
+[Option Capture Source:Rear Mic]
+name = analog-input-microphone-rear
+required-any = any
+
+[Element Mic]
+switch = off
+volume = off
+
+[Element Internal Mic]
+switch = off
+volume = off
+
+[Element Front Mic]
+switch = off
+volume = off
+
+[Element Dock Mic]
+switch = off
+volume = off
+
+[Element Mic Boost]
+switch = off
+volume = off
+
+[Element Dock Mic Boost]
+switch = off
+volume = off
+
+[Element Internal Mic Boost]
+switch = off
+volume = off
+
+[Element Front Mic Boost]
+switch = off
+volume = off
+
+.include analog-input-mic.conf.common
diff --git a/src/modules/alsa/mixer/paths/analog-input-tvtuner.conf b/src/modules/alsa/mixer/paths/analog-input-tvtuner.conf
new file mode 100644
index 0000000..99d1d79
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-input-tvtuner.conf
@@ -0,0 +1,65 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; For devices where a 'TV Tuner' element exists
+;
+; See analog-output.conf.common for an explanation on the directives
+
+[General]
+priority = 70
+description-key = analog-input-video
+
+[Element Capture]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Mic]
+switch = off
+volume = off
+
+[Element Internal Mic]
+switch = off
+volume = off
+
+[Element Line]
+switch = off
+volume = off
+
+[Element Aux]
+switch = off
+volume = off
+
+[Element Video]
+switch = off
+volume = off
+
+[Element Mic/Line]
+switch = off
+volume = off
+
+[Element TV Tuner]
+required = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element FM]
+switch = off
+volume = off
+
+.include analog-input.conf.common
diff --git a/src/modules/alsa/mixer/paths/analog-input-video.conf b/src/modules/alsa/mixer/paths/analog-input-video.conf
new file mode 100644
index 0000000..50c999e
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-input-video.conf
@@ -0,0 +1,64 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; For devices where a 'Video' element exists
+;
+; See analog-output.conf.common for an explanation on the directives
+
+[General]
+priority = 70
+
+[Element Capture]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Mic]
+switch = off
+volume = off
+
+[Element Internal Mic]
+switch = off
+volume = off
+
+[Element Line]
+switch = off
+volume = off
+
+[Element Aux]
+switch = off
+volume = off
+
+[Element Video]
+required = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Mic/Line]
+switch = off
+volume = off
+
+[Element TV Tuner]
+switch = off
+volume = off
+
+[Element FM]
+switch = off
+volume = off
+
+.include analog-input.conf.common
diff --git a/src/modules/alsa/mixer/paths/analog-input.conf b/src/modules/alsa/mixer/paths/analog-input.conf
new file mode 100644
index 0000000..c9db677
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-input.conf
@@ -0,0 +1,102 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; A fallback for devices that lack separate Mic/Line/Aux/Video/TV
+; Tuner/FM elements
+;
+; See analog-output.conf.common for an explanation on the directives
+
+[General]
+priority = 100
+
+[Element Capture]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Mic]
+required-absent = any
+
+[Element Mic Boost]
+required-absent = any
+
+[Element Dock Mic]
+required-absent = any
+
+[Element Dock Mic Boost]
+required-absent = any
+
+[Element Front Mic]
+required-absent = any
+
+[Element Front Mic Boost]
+required-absent = any
+
+[Element Int Mic]
+required-absent = any
+
+[Element Int Mic Boost]
+required-absent = any
+
+[Element Internal Mic]
+required-absent = any
+
+[Element Internal Mic Boost]
+required-absent = any
+
+[Element Rear Mic]
+required-absent = any
+
+[Element Rear Mic Boost]
+required-absent = any
+
+[Element Headset]
+required-absent = any
+
+[Element Headset Mic]
+required-absent = any
+
+[Element Headset Mic Boost]
+required-absent = any
+
+[Element Headphone Mic]
+required-absent = any
+
+[Element Headphone Mic Boost]
+required-absent = any
+
+[Element Line]
+required-absent = any
+
+[Element Line Boost]
+required-absent = any
+
+[Element Aux]
+required-absent = any
+
+[Element Video]
+required-absent = any
+
+[Element Mic/Line]
+required-absent = any
+
+[Element TV Tuner]
+required-absent = any
+
+[Element FM]
+required-absent = any
+
+.include analog-input.conf.common
diff --git a/src/modules/alsa/mixer/paths/analog-input.conf.common b/src/modules/alsa/mixer/paths/analog-input.conf.common
new file mode 100644
index 0000000..201087e
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-input.conf.common
@@ -0,0 +1,289 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Mixer path for PulseAudio's ALSA backend, common elements for all
+; input paths. If multiple options by the same id are discovered they
+; will be suffixed with a number to distinguish them, in the same
+; order they appear here.
+;
+; Source selection should use the following names:
+;
+; input -- If we don't know the exact kind of input
+; input-microphone
+; input-microphone-internal
+; input-microphone-external
+; input-linein
+; input-video
+; input-radio
+; input-docking-microphone
+; input-docking-linein
+; input-docking
+;
+; We explicitly don't want to wrap the following sources:
+;
+; CD
+; Synth/MIDI
+; Phone
+; Mix
+; Digital/SPDIF
+; Master
+; PC Speaker
+;
+; See analog-output.conf.common for an explanation on the directives
+
+;;; 'Input Source Select'
+
+[Element Input Source Select]
+enumeration = select
+
+[Option Input Source Select:Input1]
+name = input
+priority = 10
+
+[Option Input Source Select:Input2]
+name = input
+priority = 5
+
+;;; 'Input Source'
+
+[Element Input Source]
+enumeration = select
+
+[Option Input Source:Digital Mic]
+name = input-microphone
+priority = 20
+
+[Option Input Source:Microphone]
+name = input-microphone
+priority = 20
+
+[Option Input Source:Front Microphone]
+name = input-microphone
+priority = 19
+
+[Option Input Source:Internal Mic 1]
+name = input-microphone
+priority = 19
+
+[Option Input Source:Line-In]
+name = input-linein
+priority = 18
+
+[Option Input Source:Line In]
+name = input-linein
+priority = 18
+
+[Option Input Source:Docking-Station]
+name = input-docking
+priority = 17
+
+[Option Input Source:AUX IN]
+name = input
+priority = 10
+
+;;; 'Capture Source'
+
+[Element Capture Source]
+enumeration = select
+
+[Option Capture Source:TV Tuner]
+name = input-video
+
+[Option Capture Source:FM]
+name = input-radio
+
+[Option Capture Source:Mic/Line]
+name = input
+
+[Option Capture Source:Line/Mic]
+name = input
+
+[Option Capture Source:Microphone]
+name = input-microphone
+
+[Option Capture Source:Int DMic]
+name = input-microphone-internal
+
+[Option Capture Source:iMic]
+name = input-microphone-internal
+
+[Option Capture Source:i-Mic]
+name = input-microphone-internal
+
+[Option Capture Source:Internal Microphone]
+name = input-microphone-internal
+
+[Option Capture Source:Front Microphone]
+name = input-microphone
+
+[Option Capture Source:Mic1]
+name = input-microphone
+
+[Option Capture Source:Mic2]
+name = input-microphone
+
+[Option Capture Source:D-Mic]
+name = input-microphone
+
+[Option Capture Source:IntMic]
+name = input-microphone-internal
+
+[Option Capture Source:ExtMic]
+name = input-microphone-external
+
+[Option Capture Source:Ext Mic]
+name = input-microphone-external
+
+[Option Capture Source:E-Mic]
+name = input-microphone-external
+
+[Option Capture Source:e-Mic]
+name = input-microphone-external
+
+[Option Capture Source:LineIn]
+name = input-linein
+
+[Option Capture Source:Analog]
+name = input
+
+[Option Capture Source:Line-In]
+name = input-linein
+
+[Option Capture Source:Line In]
+name = input-linein
+
+[Option Capture Source:Video]
+name = input-video
+
+[Option Capture Source:Aux]
+name = input
+
+[Option Capture Source:Aux0]
+name = input
+
+[Option Capture Source:Aux1]
+name = input
+
+[Option Capture Source:Aux2]
+name = input
+
+[Option Capture Source:Aux3]
+name = input
+
+[Option Capture Source:AUX IN]
+name = input
+
+[Option Capture Source:Aux In]
+name = input
+
+[Option Capture Source:AOUT]
+name = input
+
+[Option Capture Source:AUX]
+name = input
+
+[Option Capture Source:Cam Mic]
+name = input-microphone
+
+[Option Capture Source:Digital Mic]
+name = input-microphone
+
+[Option Capture Source:Digital Mic 1]
+name = input-microphone
+
+[Option Capture Source:Digital Mic 2]
+name = input-microphone
+
+[Option Capture Source:Analog Inputs]
+name = input
+
+[Option Capture Source:Unknown1]
+name = input
+
+[Option Capture Source:Unknown2]
+name = input
+
+[Option Capture Source:Docking-Station]
+name = input-docking
+
+;;; 'Mic Jack Mode'
+
+[Element Mic Jack Mode]
+enumeration = select
+
+[Option Mic Jack Mode:Mic In]
+name = input-microphone
+
+[Option Mic Jack Mode:Line In]
+name = input-linein
+
+;;; 'Digital Input Source'
+
+[Element Digital Input Source]
+enumeration = select
+
+[Option Digital Input Source:Digital Mic 1]
+name = input-microphone
+
+[Option Digital Input Source:Analog Inputs]
+name = input
+
+[Option Digital Input Source:Digital Mic 2]
+name = input-microphone
+
+;;; 'Analog Source'
+
+[Element Analog Source]
+enumeration = select
+
+[Option Analog Source:Mic]
+name = input-microphone
+
+[Option Analog Source:Line in]
+name = input-linein
+
+[Option Analog Source:Aux]
+name = input
+
+;;; 'Shared Mic/Line in'
+
+[Element Shared Mic/Line in]
+enumeration = select
+
+[Option Shared Mic/Line in:Mic in]
+name = input-microphone
+
+[Option Shared Mic/Line in:Line in]
+name = input-linein
+
+;;; Various Boosts
+
+[Element Capture Boost]
+switch = select
+
+[Option Capture Boost:on]
+name = input-boost-on
+
+[Option Capture Boost:off]
+name = input-boost-off
+
+[Element Auto Gain Control]
+switch = select
+
+[Option Auto Gain Control:on]
+name = input-agc-on
+
+[Option Auto Gain Control:off]
+name = input-agc-off
diff --git a/src/modules/alsa/mixer/paths/analog-output-headphones-2.conf b/src/modules/alsa/mixer/paths/analog-output-headphones-2.conf
new file mode 100644
index 0000000..1789990
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-output-headphones-2.conf
@@ -0,0 +1,116 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Path for the second headphone output on dual-headphone machines.
+;
+; See analog-output.conf.common for an explanation on the directives
+
+[General]
+priority = 98
+
+[Properties]
+device.icon_name = audio-headphones
+
+; HP EliteDesk 800 SFF Headphone
+[Jack Front Headphone,1]
+required-any = any
+
+; HP EliteDesk 800 DM Headphone
+[Jack Front Headphone Surround]
+required-any = any
+
+[Element Hardware Master]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Master]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Master Mono]
+switch = off
+volume = off
+
+; This profile path is intended to control the second headphones, not
+; the first headphones. But it should not hurt if we leave the
+; headphone jack enabled nonetheless.
+[Element Headphone]
+switch = mute
+volume = zero
+
+[Element Headphone,1]
+required-any = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Headphone+LO]
+switch = mute
+volume = zero
+
+[Element Speaker+LO]
+switch = off
+volume = off
+
+[Element Headphone2]
+required-any = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Speaker]
+switch = off
+volume = off
+
+[Element Desktop Speaker]
+switch = off
+volume = off
+
+; On some machines Front is actually a part of the Headphone path
+[Element Front]
+switch = mute
+volume = zero
+
+[Element Rear]
+switch = off
+volume = off
+
+[Element Surround]
+switch = off
+volume = off
+
+[Element Side]
+switch = off
+volume = off
+
+[Element Center]
+switch = off
+volume = off
+
+[Element LFE]
+switch = off
+volume = off
+
+[Element Bass Speaker]
+switch = off
+volume = off
+
+.include analog-output.conf.common
diff --git a/src/modules/alsa/mixer/paths/analog-output-headphones.conf b/src/modules/alsa/mixer/paths/analog-output-headphones.conf
new file mode 100644
index 0000000..88907f0
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-output-headphones.conf
@@ -0,0 +1,174 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Path for mixers that have a 'Headphone' control
+;
+; See analog-output.conf.common for an explanation on the directives
+
+[General]
+priority = 99
+description-key = analog-output-headphones
+
+[Properties]
+device.icon_name = audio-headphones
+
+[Jack Dock Headphone]
+required-any = any
+
+[Jack Dock Headphone Phantom]
+required-any = any
+state.plugged = unknown
+state.unplugged = unknown
+
+[Jack Front Headphone]
+required-any = any
+
+; HP EliteDesk 800 DM Headset
+[Jack Front Headphone Front]
+required-any = any
+
+[Jack Front Headphone Phantom]
+required-any = any
+state.plugged = unknown
+state.unplugged = unknown
+
+[Jack Headphone]
+required-any = any
+
+[Jack Headphone Phantom]
+required-any = any
+state.plugged = unknown
+state.unplugged = unknown
+
+# This jack can be either a headphone *or* a mic. Used on some ASUS netbooks.
+[Jack Headphone Mic]
+required-any = any
+
+[Jack Headphone - Output]
+required-any = any
+
+[Element Hardware Master]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Master]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Master Mono]
+switch = off
+volume = off
+
+[Element Speaker+LO]
+switch = off
+volume = off
+
+[Element Headphone+LO]
+required-any = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Headphone]
+required-any = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+; This path is intended to control the first headphones, not
+; the second headphones. But it should not hurt if we leave the second
+; headphone jack enabled nonetheless.
+[Element Headphone,1]
+switch = mute
+volume = zero
+
+[Element Headset]
+required-any = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Line HP Swap]
+switch = on
+required-any = any
+
+; This profile path is intended to control the first headphones, not
+; the second headphones. But it should not hurt if we leave the second
+; headphone jack enabled nonetheless.
+[Element Headphone2]
+switch = mute
+volume = zero
+
+[Element Speaker]
+switch = off
+volume = off
+
+[Element Desktop Speaker]
+switch = off
+volume = off
+
+; On some machines Front is actually a part of the Headphone path
+[Element Front]
+switch = mute
+volume = zero
+
+[Element Rear]
+switch = off
+volume = off
+
+[Element Surround]
+switch = off
+volume = off
+
+[Element Side]
+switch = off
+volume = off
+
+[Element Center]
+switch = off
+volume = off
+
+[Element LFE]
+switch = off
+volume = off
+
+[Element Bass Speaker]
+switch = off
+volume = off
+
+[Element Speaker Front]
+switch = off
+volume = off
+
+[Element Speaker Surround]
+switch = off
+volume = off
+
+[Element Speaker Side]
+switch = off
+volume = off
+
+[Element Speaker CLFE]
+switch = off
+volume = off
+
+.include analog-output.conf.common
diff --git a/src/modules/alsa/mixer/paths/analog-output-lineout.conf b/src/modules/alsa/mixer/paths/analog-output-lineout.conf
new file mode 100644
index 0000000..2dde159
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-output-lineout.conf
@@ -0,0 +1,208 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+[General]
+priority = 90
+description-key = analog-output-lineout
+
+[Jack Line Out]
+required-any = any
+
+[Jack Line Out Phantom]
+state.plugged = unknown
+state.unplugged = unknown
+required-any = any
+
+[Jack Front Line Out]
+required-any = any
+
+[Jack Front Line Out Phantom]
+state.plugged = unknown
+state.unplugged = unknown
+required-any = any
+
+[Jack Rear Line Out]
+required-any = any
+
+[Jack Rear Line Out Phantom]
+state.plugged = unknown
+state.unplugged = unknown
+required-any = any
+
+[Jack Line Out Front]
+required-any = any
+
+[Jack Line Out Front Phantom]
+state.plugged = unknown
+state.unplugged = unknown
+required-any = any
+
+[Jack Line Out CLFE]
+state.plugged = unknown
+state.unplugged = unknown
+required-any = any
+
+[Jack Line Out CLFE Phantom]
+state.plugged = unknown
+state.unplugged = unknown
+required-any = any
+
+[Jack Line Out Surround]
+state.plugged = unknown
+state.unplugged = unknown
+required-any = any
+
+[Jack Line Out Surround Phantom]
+state.plugged = unknown
+state.unplugged = unknown
+required-any = any
+
+[Jack Line Out Side]
+state.plugged = unknown
+state.unplugged = unknown
+required-any = any
+
+[Jack Line Out Side Phantom]
+state.plugged = unknown
+state.unplugged = unknown
+required-any = any
+
+[Jack Dock Line Out]
+required-any = any
+
+[Jack Dock Line Out Phantom]
+state.plugged = unknown
+state.unplugged = unknown
+required-any = any
+
+[Element Hardware Master]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Master]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Speaker+LO]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+required-any = any
+
+[Element Headphone+LO]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+required-any = any
+
+[Element Master Mono]
+switch = off
+volume = off
+
+[Element Line HP Swap]
+switch = off
+required-any = any
+
+; This profile path is intended to control line out, let's mute headphones
+; else there will be a spike when plugging in headphones
+[Element Headphone]
+switch = off
+volume = off
+
+[Element Headphone,1]
+switch = off
+volume = off
+
+[Element Headphone2]
+switch = off
+volume = off
+
+[Element Speaker]
+switch = off
+volume = off
+
+[Element Desktop Speaker]
+switch = off
+volume = off
+
+[Element Front]
+switch = mute
+volume = merge
+override-map.1 = all-front
+override-map.2 = front-left,front-right
+
+[Element Rear]
+switch = mute
+volume = merge
+override-map.1 = all-rear
+override-map.2 = rear-left,rear-right
+
+[Element Surround]
+switch = mute
+volume = merge
+override-map.1 = all-rear
+override-map.2 = rear-left,rear-right
+
+[Element Side]
+switch = mute
+volume = merge
+override-map.1 = all-side
+override-map.2 = side-left,side-right
+
+[Element Center]
+switch = mute
+volume = merge
+override-map.1 = all-center
+override-map.2 = all-center,all-center
+
+[Element LFE]
+switch = mute
+volume = merge
+override-map.1 = lfe
+override-map.2 = lfe,lfe
+
+[Element CLFE]
+switch = mute
+volume = merge
+override-map.1 = all-center
+override-map.2 = all-center,lfe
+
+[Element Bass Speaker]
+switch = off
+volume = off
+
+[Element Speaker Front]
+switch = off
+volume = off
+
+[Element Speaker Surround]
+switch = off
+volume = off
+
+[Element Speaker Side]
+switch = off
+volume = off
+
+[Element Speaker CLFE]
+switch = off
+volume = off
+
+.include analog-output.conf.common
diff --git a/src/modules/alsa/mixer/paths/analog-output-mono.conf b/src/modules/alsa/mixer/paths/analog-output-mono.conf
new file mode 100644
index 0000000..5e49405
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-output-mono.conf
@@ -0,0 +1,99 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Intended for usage on boards that have a separate Mono output plug.
+;
+; See analog-output.conf.common for an explanation on the directives
+
+[General]
+priority = 50
+
+[Element Hardware Master]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Master]
+switch = off
+volume = off
+
+[Element Master Mono]
+required = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+; This profile path is intended to control the speaker, not the
+; headphones. But it should not hurt if we leave the headphone jack
+; enabled nonetheless.
+[Element Headphone]
+switch = mute
+volume = zero
+
+[Element Headphone,1]
+switch = mute
+volume = zero
+
+[Element Headphone+LO]
+switch = mute
+volume = zero
+
+[Element Headphone2]
+switch = mute
+volume = zero
+
+[Element Speaker]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Speaker+LO]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Desktop Speaker]
+switch = off
+volume = off
+
+[Element Front]
+switch = off
+volume = off
+
+[Element Rear]
+switch = off
+volume = off
+
+[Element Surround]
+switch = off
+volume = off
+
+[Element Side]
+switch = off
+volume = off
+
+[Element Center]
+switch = off
+volume = off
+
+[Element LFE]
+switch = off
+volume = off
+
+.include analog-output.conf.common
diff --git a/src/modules/alsa/mixer/paths/analog-output-speaker-always.conf b/src/modules/alsa/mixer/paths/analog-output-speaker-always.conf
new file mode 100644
index 0000000..4ee72f5
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-output-speaker-always.conf
@@ -0,0 +1,181 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Path for mixers that don't have a 'Speaker' control, but where we
+; force enable the speaker paths nonetheless.
+; Needed for some older Dell laptops.
+; See analog-output.conf.common for an explanation on the directives
+
+[General]
+priority = 100
+description-key = analog-output-speaker
+
+[Properties]
+device.icon_name = audio-speakers
+
+[Jack Headphone]
+state.plugged = no
+state.unplugged = unknown
+
+[Jack Front Headphone]
+state.plugged = no
+state.unplugged = unknown
+
+[Jack Line Out]
+state.plugged = no
+state.unplugged = unknown
+
+[Jack Line Out Front]
+state.plugged = no
+state.unplugged = unknown
+
+[Jack Front Line Out]
+state.plugged = no
+state.unplugged = unknown
+
+[Jack Rear Line Out]
+state.plugged = no
+state.unplugged = unknown
+
+[Jack Dock Line Out]
+state.plugged = no
+state.unplugged = unknown
+
+[Element Hardware Master]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Master]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Master Mono]
+switch = off
+volume = off
+
+; This profile path is intended to control the speaker, not the
+; headphones. But it should not hurt if we leave the headphone jack
+; enabled nonetheless.
+[Element Headphone]
+switch = mute
+volume = zero
+
+[Element Headphone,1]
+switch = mute
+volume = zero
+
+[Element Headphone2]
+switch = mute
+volume = zero
+
+[Element Headphone+LO]
+switch = off
+volume = off
+
+[Element Speaker+LO]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Speaker]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Desktop Speaker]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Front]
+switch = mute
+volume = merge
+override-map.1 = all-front
+override-map.2 = front-left,front-right
+
+[Element Front Speaker]
+switch = mute
+volume = merge
+override-map.1 = all-front
+override-map.2 = front-left,front-right
+
+[Element Rear]
+switch = mute
+volume = merge
+override-map.1 = all-rear
+override-map.2 = rear-left,rear-right
+
+[Element Surround]
+switch = mute
+volume = merge
+override-map.1 = all-rear
+override-map.2 = rear-left,rear-right
+
+[Element Surround Speaker]
+switch = mute
+volume = merge
+override-map.1 = all-rear
+override-map.2 = rear-left,rear-right
+
+[Element Side]
+switch = mute
+volume = merge
+override-map.1 = all-side
+override-map.2 = side-left,side-right
+
+[Element Center]
+switch = mute
+volume = merge
+override-map.1 = all-center
+override-map.2 = all-center,all-center
+
+[Element Center Speaker]
+switch = mute
+volume = merge
+override-map.1 = all-center
+override-map.2 = all-center,all-center
+
+[Element LFE]
+switch = mute
+volume = merge
+override-map.1 = lfe
+override-map.2 = lfe,lfe
+
+[Element LFE Speaker]
+switch = mute
+volume = merge
+override-map.1 = lfe
+override-map.2 = lfe,lfe
+
+[Element Bass Speaker]
+switch = mute
+volume = merge
+override-map.1 = lfe
+override-map.2 = lfe,lfe
+
+[Element CLFE]
+switch = mute
+volume = merge
+override-map.1 = all-center
+override-map.2 = all-center,lfe
+
+.include analog-output.conf.common
diff --git a/src/modules/alsa/mixer/paths/analog-output-speaker.conf b/src/modules/alsa/mixer/paths/analog-output-speaker.conf
new file mode 100644
index 0000000..fcf2f5c
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-output-speaker.conf
@@ -0,0 +1,233 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Path for mixers that have a 'Speaker' control
+;
+; See analog-output.conf.common for an explanation on the directives
+
+[General]
+priority = 100
+description-key = analog-output-speaker
+
+[Properties]
+device.icon_name = audio-speakers
+
+[Jack Headphone]
+state.plugged = no
+state.unplugged = unknown
+
+[Jack Dock Headphone]
+state.plugged = no
+state.unplugged = unknown
+
+[Jack Front Headphone]
+state.plugged = no
+state.unplugged = unknown
+
+[Jack Line Out]
+state.plugged = no
+state.unplugged = unknown
+
+[Jack Line Out Front]
+state.plugged = no
+state.unplugged = unknown
+
+[Jack Front Line Out]
+state.plugged = no
+state.unplugged = unknown
+
+[Jack Rear Line Out]
+state.plugged = no
+state.unplugged = unknown
+
+[Jack Dock Line Out]
+state.plugged = no
+state.unplugged = unknown
+
+[Jack Speaker]
+required-any = any
+
+[Jack Speaker Phantom]
+required-any = any
+state.plugged = unknown
+state.unplugged = unknown
+
+[Jack Speaker Front Phantom]
+required-any = any
+state.plugged = unknown
+state.unplugged = unknown
+
+[Jack Speaker - Output]
+required-any = any
+
+[Element Hardware Master]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Master]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Master Mono]
+switch = off
+volume = off
+
+; This profile path is intended to control the speaker, let's mute headphones
+; else there will be a spike when plugging in headphones
+[Element Headphone]
+switch = off
+volume = off
+
+[Element Headphone,1]
+switch = off
+volume = off
+
+[Element Headphone2]
+switch = off
+volume = off
+
+[Element Headphone+LO]
+switch = off
+volume = off
+
+[Element Speaker+LO]
+required-any = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Speaker]
+required-any = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Desktop Speaker]
+required-any = any
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Front]
+switch = mute
+volume = merge
+override-map.1 = all-front
+override-map.2 = front-left,front-right
+
+[Element Front Speaker]
+switch = mute
+volume = merge
+override-map.1 = all-front
+override-map.2 = front-left,front-right
+required-any = any
+
+[Element Speaker Front]
+switch = mute
+volume = merge
+override-map.1 = all-front
+override-map.2 = front-left,front-right
+required-any = any
+
+[Element Rear]
+switch = mute
+volume = merge
+override-map.1 = all-rear
+override-map.2 = rear-left,rear-right
+
+[Element Surround]
+switch = mute
+volume = merge
+override-map.1 = all-rear
+override-map.2 = rear-left,rear-right
+
+[Element Surround Speaker]
+switch = mute
+volume = merge
+override-map.1 = all-rear
+override-map.2 = rear-left,rear-right
+required-any = any
+
+[Element Speaker Surround]
+switch = mute
+volume = merge
+override-map.1 = all-rear
+override-map.2 = rear-left,rear-right
+required-any = any
+
+[Element Side]
+switch = mute
+volume = merge
+override-map.1 = all-side
+override-map.2 = side-left,side-right
+
+[Element Speaker Side]
+switch = mute
+volume = merge
+override-map.1 = all-side
+override-map.2 = side-left,side-right
+
+[Element Center]
+switch = mute
+volume = merge
+override-map.1 = all-center
+override-map.2 = all-center,all-center
+
+[Element Center Speaker]
+switch = mute
+volume = merge
+override-map.1 = all-center
+override-map.2 = all-center,all-center
+required-any = any
+
+[Element LFE]
+switch = mute
+volume = merge
+override-map.1 = lfe
+override-map.2 = lfe,lfe
+
+[Element LFE Speaker]
+switch = mute
+volume = merge
+override-map.1 = lfe
+override-map.2 = lfe,lfe
+required-any = any
+
+[Element Bass Speaker]
+switch = mute
+volume = merge
+override-map.1 = lfe
+override-map.2 = lfe,lfe
+required-any = any
+
+[Element CLFE]
+switch = mute
+volume = merge
+override-map.1 = all-center
+override-map.2 = all-center,lfe
+
+[Element Speaker CLFE]
+switch = mute
+volume = merge
+override-map.1 = all-center
+override-map.2 = all-center,lfe
+
+.include analog-output.conf.common
diff --git a/src/modules/alsa/mixer/paths/analog-output.conf b/src/modules/alsa/mixer/paths/analog-output.conf
new file mode 100644
index 0000000..e6ba983
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-output.conf
@@ -0,0 +1,82 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Intended for the 'default' output. Note that a-o-speaker.conf has a
+; higher priority than this
+;
+; See analog-output.conf.common for an explanation on the directives
+
+[General]
+priority = 99
+
+[Element Hardware Master]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Master]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element Master Mono]
+switch = off
+volume = off
+
+[Element Front]
+switch = mute
+volume = merge
+override-map.1 = all-front
+override-map.2 = front-left,front-right
+
+[Element Rear]
+switch = mute
+volume = merge
+override-map.1 = all-rear
+override-map.2 = rear-left,rear-right
+
+[Element Surround]
+switch = mute
+volume = merge
+override-map.1 = all-rear
+override-map.2 = rear-left,rear-right
+
+[Element Side]
+switch = mute
+volume = merge
+override-map.1 = all-side
+override-map.2 = side-left,side-right
+
+[Element Center]
+switch = mute
+volume = merge
+override-map.1 = all-center
+override-map.2 = all-center,all-center
+
+[Element LFE]
+switch = mute
+volume = merge
+override-map.1 = lfe
+override-map.2 = lfe,lfe
+
+[Element CLFE]
+switch = mute
+volume = merge
+override-map.1 = all-center
+override-map.2 = all-center,lfe
+
+.include analog-output.conf.common
diff --git a/src/modules/alsa/mixer/paths/analog-output.conf.common b/src/modules/alsa/mixer/paths/analog-output.conf.common
new file mode 100644
index 0000000..31d4b44
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/analog-output.conf.common
@@ -0,0 +1,186 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Common part of all paths
+
+; So here's generally how mixer paths are used by PA: PA goes through
+; a mixer path file from top to bottom and checks if a mixer element
+; described therein exists. If so it is added to the list of mixer
+; elements PA will control, keeping the order it read them in. If a
+; mixer element described here has set the required= or
+; required-absent= directives a path might not be accepted as valid
+; and is ignored in its entirety (see below). However usually if a
+; element listed here is missing this one element is ignored but not
+; the entire path.
+;
+; When a device shall be muted/unmuted *all* elements listed in a path
+; file with "switch = mute" will be toggled.
+;
+; When a device shall change its volume, PA will got through the list
+; of all elements with "volume = merge" and set the volume on the
+; first element. If that element does not support dB volumes, this is
+; where the story ends. If it does support dB volumes, PA divides the
+; requested volume by the volume that was set on this element, and
+; then go on to the next element with "volume = merge" and then set
+; that there, and so on. That way the first volume element in the
+; path will be the one that does the 'biggest' part of the overall
+; volume adjustment, with the remaining elements usually being set to
+; some value next to 0dB. This logic makes sure we get the full range
+; over all volume sliders and a very high granularity of volumes
+; already in hardware.
+;
+; All switches and enumerations set to "select" are exposed via the
+; "port" functionality of sinks/sources. Basically every possible
+; switch setting and every possible enumeration setting will be
+; combined and made into a "port". So make sure you don't list too
+; many switches/enums for exposing, because the number of ports might
+; rise exponentially.
+;
+; Only one path can be selected at a time. All paths that are valid
+; for an audio device will be exposed as "port" for the sink/source.
+
+
+; [General]
+; type = ... # The device type. It's highly recommended to set a type for every path.
+; # See parse_type() in alsa-mixer.c for supported values.
+; priority = ... # Priority for this path
+; description-key = ... # The path description is looked up from a table in path_verify() in
+; # src/modules/alsa/alsa-mixer.c. By default the path name (i.e. the file name
+; # minus the ".conf" suffix) is used as the lookup key, but if this option is
+; # set, then the given string is used as the key instead. In any case the
+; # "description" option can be used to override the path description.
+; description = ... # Description for this path. Overrides the normal description lookup logic, as
+; # described in the "description-key" documentation above.
+; mute-during-activation = yes | no # If this path supports hardware mute, should the hw mute be used while activating this
+; # path? In some cases this can reduce extra noises during port switching, while in other
+; # cases this can increase such noises. Default: no.
+; eld-device = ... # If this is an HDMI port, set to "auto" so that PulseAudio will try to read
+; # the monitor ELD information from the ALSA mixer. By default the ELD information
+; # is not read, because it's only applicable with HDMI. Earlier the "auto" option
+; # didn't exist, and the hw device index had to be manually configured. For
+; # backwards compatibility, it's still possible to manually configure the device
+; # index using this option.
+;
+; [Properties] # Property list for this path. The list is merged into the port property list.
+; <key> = <value> # Each property is defined on its own line.
+; ...
+;
+; [Option ...:...] # For each option of an enumeration or switch element
+; # that shall be exposed as a sink/source port. Needs to
+; # be named after the Element, followed by a colon, followed
+; # by the option name, resp. on/off if the element is a switch.
+; name = ... # Logical name to use in the path identifier
+; priority = ... # Priority if this is made into a device port
+; required = ignore | enumeration | any # In this element, this option must exist or the path will be invalid. ("any" is an alias for "enumeration".)
+; required-any = ignore | enumeration | any # In this element, either this or another option must exist (or an element)
+; required-absent = ignore | enumeration | any # In this element, this option must not exist or the path will be invalid
+;
+; [Element ...] # For each element that we shall control. The "..." here is the element name,
+; # or name and index separated by a comma.
+; required = ignore | switch | volume | enumeration | any # If set, require this element to be of this kind and available,
+; # otherwise don't consider this path valid for the card
+; required-any = ignore | switch | volume | enumeration | any # If set, at least one of the elements or jacks with required-any in this
+; # path must be present, otherwise this path is invalid for the card
+; required-absent = ignore | switch | volume # If set, require this element to not be of this kind and not
+; # available, otherwise don't consider this path valid for the card
+;
+; switch = ignore | mute | off | on | select # What to do with this switch: ignore it, make it follow mute status,
+; # always set it to off, always to on, or make it selectable as port.
+; # If set to 'select' you need to define an Option section for on
+; # and off
+; volume = ignore | merge | off | zero | <volume step> # What to do with this volume: ignore it, merge it into the device
+; # volume slider, always set it to the lowest value possible, or always
+; # set it to 0 dB (for whatever that means), or always set it to
+; # <volume step> (this only makes sense in path configurations where
+; # the exact hardware and driver are known beforehand).
+; volume-limit = <volume step> # Limit the maximum volume by disabling the volume steps above <volume step>.
+; enumeration = ignore | select # What to do with this enumeration, ignore it or make it selectable
+; # via device ports. If set to 'select' you need to define an Option section
+; # for each of the items you want to expose
+; direction = playback | capture # Is this relevant only for playback or capture? If not set this will implicitly be
+; # set the direction of the PCM device is opened as. Generally this doesn't need to be set
+; # unless you have a broken driver that has playback controls marked for capture or vice
+; # versa
+; direction-try-other = no | yes # If the element does not supported what is requested, try the other direction, too?
+;
+; override-map.1 = ... # Override the channel mask of the mixer control if the control only exposes a single channel
+; override-map.2 = ... # Override the channel masks of the mixer control if the control only exposes two channels
+; # Override maps should list for each element channel which high-level channels it controls via a
+; # channel mask. A channel mask may either be the name of a single channel, or the words "all-left",
+; # "all-right", "all-center", "all-front", "all-rear", and "all" to encode a specific subset of
+; # channels in a mask
+; [Jack ...] # For each jack that we will use for jack detection
+; # The name 'Jack Foo' must match ALSA's 'Foo Jack' control.
+; required = ignore | any # If not set to ignore, make the path invalid if this jack control is not present.
+; required-absent = ignore | any # If not set to ignore, make the path invalid if this jack control is present.
+; required-any = ignore | any # If not set to ignore, make the path invalid if no jack controls and no elements with
+; # the required-any are present.
+; state.plugged = yes | no | unknown # Normally a plugged jack would mean the port becomes available, and an unplugged means it's
+; state.unplugged = yes | no | unknown # unavailable, but the port status can be overridden by specifying state.plugged and/or state.unplugged.
+; append-pcm-to-name = no | yes # Add ",pcm=N" to the jack name? N is the hw PCM device index. HDMI jacks have
+; # the PCM device index in their name, but different drivers use different
+; # numbering schemes, so we can't hardcode the full jack name in our configuration
+; # files.
+
+[Element PCM]
+switch = mute
+volume = merge
+override-map.1 = all
+override-map.2 = all-left,all-right
+
+[Element External Amplifier]
+switch = select
+
+[Option External Amplifier:on]
+name = output-amplifier-on
+priority = 10
+
+[Option External Amplifier:off]
+name = output-amplifier-off
+priority = 0
+
+[Element Bass Boost]
+switch = select
+
+[Option Bass Boost:on]
+name = output-bass-boost-on
+priority = 0
+
+[Option Bass Boost:off]
+name = output-bass-boost-off
+priority = 10
+
+[Element IEC958]
+switch = off
+
+[Element IEC958 Optical Raw]
+switch = off
+
+;;; 'Analog Output'
+
+[Element Analog Output]
+enumeration = select
+
+[Option Analog Output:Speakers]
+name = output-speaker
+priority = 10
+
+[Option Analog Output:Headphones]
+name = output-headphones
+priority = 9
+
+[Option Analog Output:FP Headphones]
+name = output-headphones
+priority = 8
diff --git a/src/modules/alsa/mixer/paths/hdmi-output-0.conf b/src/modules/alsa/mixer/paths/hdmi-output-0.conf
new file mode 100644
index 0000000..bb3cec1
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/hdmi-output-0.conf
@@ -0,0 +1,12 @@
+[General]
+description = HDMI / DisplayPort
+type = hdmi
+priority = 59
+eld-device = auto
+
+[Properties]
+device.icon_name = video-display
+
+[Jack HDMI/DP]
+append-pcm-to-name = yes
+required = ignore
diff --git a/src/modules/alsa/mixer/paths/hdmi-output-1.conf b/src/modules/alsa/mixer/paths/hdmi-output-1.conf
new file mode 100644
index 0000000..3389a72
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/hdmi-output-1.conf
@@ -0,0 +1,12 @@
+[General]
+description = HDMI / DisplayPort 2
+type = hdmi
+priority = 58
+eld-device = auto
+
+[Properties]
+device.icon_name = video-display
+
+[Jack HDMI/DP]
+append-pcm-to-name = yes
+required = ignore
diff --git a/src/modules/alsa/mixer/paths/hdmi-output-2.conf b/src/modules/alsa/mixer/paths/hdmi-output-2.conf
new file mode 100644
index 0000000..316d810
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/hdmi-output-2.conf
@@ -0,0 +1,12 @@
+[General]
+description = HDMI / DisplayPort 3
+type = hdmi
+priority = 57
+eld-device = auto
+
+[Properties]
+device.icon_name = video-display
+
+[Jack HDMI/DP]
+append-pcm-to-name = yes
+required = ignore
diff --git a/src/modules/alsa/mixer/paths/hdmi-output-3.conf b/src/modules/alsa/mixer/paths/hdmi-output-3.conf
new file mode 100644
index 0000000..0601ef7
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/hdmi-output-3.conf
@@ -0,0 +1,12 @@
+[General]
+description = HDMI / DisplayPort 4
+type = hdmi
+priority = 56
+eld-device = auto
+
+[Properties]
+device.icon_name = video-display
+
+[Jack HDMI/DP]
+append-pcm-to-name = yes
+required = ignore
diff --git a/src/modules/alsa/mixer/paths/hdmi-output-4.conf b/src/modules/alsa/mixer/paths/hdmi-output-4.conf
new file mode 100644
index 0000000..ded155b
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/hdmi-output-4.conf
@@ -0,0 +1,12 @@
+[General]
+description = HDMI / DisplayPort 5
+type = hdmi
+priority = 55
+eld-device = auto
+
+[Properties]
+device.icon_name = video-display
+
+[Jack HDMI/DP]
+append-pcm-to-name = yes
+required = ignore
diff --git a/src/modules/alsa/mixer/paths/hdmi-output-5.conf b/src/modules/alsa/mixer/paths/hdmi-output-5.conf
new file mode 100644
index 0000000..de31791
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/hdmi-output-5.conf
@@ -0,0 +1,12 @@
+[General]
+description = HDMI / DisplayPort 6
+type = hdmi
+priority = 54
+eld-device = auto
+
+[Properties]
+device.icon_name = video-display
+
+[Jack HDMI/DP]
+append-pcm-to-name = yes
+required = ignore
diff --git a/src/modules/alsa/mixer/paths/hdmi-output-6.conf b/src/modules/alsa/mixer/paths/hdmi-output-6.conf
new file mode 100644
index 0000000..6d72176
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/hdmi-output-6.conf
@@ -0,0 +1,12 @@
+[General]
+description = HDMI / DisplayPort 7
+type = hdmi
+priority = 53
+eld-device = auto
+
+[Properties]
+device.icon_name = video-display
+
+[Jack HDMI/DP]
+append-pcm-to-name = yes
+required = ignore
diff --git a/src/modules/alsa/mixer/paths/hdmi-output-7.conf b/src/modules/alsa/mixer/paths/hdmi-output-7.conf
new file mode 100644
index 0000000..d5d0771
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/hdmi-output-7.conf
@@ -0,0 +1,12 @@
+[General]
+description = HDMI / DisplayPort 8
+type = hdmi
+priority = 52
+eld-device = auto
+
+[Properties]
+device.icon_name = video-display
+
+[Jack HDMI/DP]
+append-pcm-to-name = yes
+required = ignore
diff --git a/src/modules/alsa/mixer/paths/iec958-stereo-input.conf b/src/modules/alsa/mixer/paths/iec958-stereo-input.conf
new file mode 100644
index 0000000..babc839
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/iec958-stereo-input.conf
@@ -0,0 +1,20 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+[Element PCM Capture Source]
+enumeration = select
+
+[Option PCM Capture Source:IEC958 In]
+name = iec958-input
diff --git a/src/modules/alsa/mixer/paths/iec958-stereo-output.conf b/src/modules/alsa/mixer/paths/iec958-stereo-output.conf
new file mode 100644
index 0000000..d47e5eb
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/iec958-stereo-output.conf
@@ -0,0 +1,18 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+
+[Element IEC958]
+switch = mute
diff --git a/src/modules/alsa/mixer/paths/steelseries-arctis-output-chat-common.conf b/src/modules/alsa/mixer/paths/steelseries-arctis-output-chat-common.conf
new file mode 100644
index 0000000..5842bfe
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/steelseries-arctis-output-chat-common.conf
@@ -0,0 +1,27 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Steelseries Arctis 5 USB headset stereo chat path. The headset has two
+; output devices. The first one is meant for voice audio, and the second
+; one meant for everything else. The purpose of this unusual design is to
+; provide separate volume controls for voice and other audio, which can be
+; useful in gaming.
+
+[General]
+priority = 50
+
+[Element Com Speaker]
+switch = mute
+volume = merge
diff --git a/src/modules/alsa/mixer/paths/steelseries-arctis-output-game-common.conf b/src/modules/alsa/mixer/paths/steelseries-arctis-output-game-common.conf
new file mode 100644
index 0000000..b758a6f
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/steelseries-arctis-output-game-common.conf
@@ -0,0 +1,27 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Steelseries Arctis 5 USB headset stereo game path. The headset has two
+; output devices. The first one is meant for voice audio, and the second
+; one meant for everything else. The purpose of this unusual design is to
+; provide separate volume controls for voice and other audio, which can be
+; useful in gaming.
+
+[General]
+priority = 99
+
+[Element PCM]
+switch = mute
+volume = merge
diff --git a/src/modules/alsa/mixer/paths/usb-gaming-headset-input.conf b/src/modules/alsa/mixer/paths/usb-gaming-headset-input.conf
new file mode 100644
index 0000000..9fa7fe9
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/usb-gaming-headset-input.conf
@@ -0,0 +1,34 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; USB gaming headset microphone input path. These headsets usually have two
+; output devices. The first one is mono, meant for voice audio, and the second
+; one is stereo, meant for everything else. The purpose of this unusual design
+; is to provide separate volume controls for voice and other audio, which can
+; be useful in gaming.
+;
+; Works with:
+; Steelseries Arctis 7
+; Steelseries Arctis Pro Wireless.
+; Lucidsound LS31
+
+[General]
+description-key = analog-input-microphone-headset
+
+[Element Headset]
+volume = merge
+switch = mute
+override-map.1 = all
+override-map.2 = all-left,all-right
diff --git a/src/modules/alsa/mixer/paths/usb-gaming-headset-output-mono.conf b/src/modules/alsa/mixer/paths/usb-gaming-headset-output-mono.conf
new file mode 100644
index 0000000..6df662f
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/usb-gaming-headset-output-mono.conf
@@ -0,0 +1,34 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; USB gaming headset mono output path. These headsets usually have two
+; output devices. The first one is mono, meant for voice audio, and the second
+; one is stereo, meant for everything else. The purpose of this unusual design
+; is to provide separate volume controls for voice and other audio, which can
+; be useful in gaming.
+;
+; Works with:
+; Steelseries Arctis 7
+; Steelseries Arctis Pro Wireless.
+; Lucidsound LS31
+
+[General]
+description-key = analog-output-headphones-mono
+
+[Element PCM]
+volume = merge
+switch = mute
+override-map.1 = all
+override-map.2 = all-left,all-right
diff --git a/src/modules/alsa/mixer/paths/usb-gaming-headset-output-stereo.conf b/src/modules/alsa/mixer/paths/usb-gaming-headset-output-stereo.conf
new file mode 100644
index 0000000..e3f91cd
--- /dev/null
+++ b/src/modules/alsa/mixer/paths/usb-gaming-headset-output-stereo.conf
@@ -0,0 +1,32 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; USB gaming headset mono output path. These headsets usually have two
+; output devices. The first one is mono, meant for voice audio, and the second
+; one is stereo, meant for everything else. The purpose of this unusual design
+; is to provide separate volume controls for voice and other audio, which can
+; be useful in gaming.
+;
+; Works with:
+; Steelseries Arctis 7
+; Steelseries Arctis Pro Wireless.
+; Lucidsound LS31
+;
+; This path doesn't provide hardware volume control, because the stereo
+; output is controlled by the PCM element with index 1, and currently
+; PulseAudio only supports elements with index 0.
+
+[General]
+description-key = analog-output-headphones
diff --git a/src/modules/alsa/mixer/profile-sets/audigy.conf b/src/modules/alsa/mixer/profile-sets/audigy.conf
new file mode 100644
index 0000000..043596e
--- /dev/null
+++ b/src/modules/alsa/mixer/profile-sets/audigy.conf
@@ -0,0 +1,94 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Creative Sound Blaster Audigy product line
+;
+; These are just copies of the mappings we find in default.conf, with the
+; small change of making analog-stereo and analog-mono non-fallback mappings.
+; This is needed because these cards only support duplex profiles with mono
+; inputs, and in the default configuration, with stereo being a fallback
+; mapping, the mono mapping is never tried.
+;
+; See default.conf for an explanation on the directives used here.
+
+[General]
+auto-profiles = yes
+
+# Based on stereo-fallback
+[Mapping analog-stereo]
+device-strings = hw:%f
+channel-map = front-left,front-right
+paths-output = analog-output analog-output-lineout analog-output-speaker analog-output-headphones analog-output-headphones-2
+paths-input = analog-input-front-mic analog-input-rear-mic analog-input-internal-mic analog-input-dock-mic analog-input analog-input-mic analog-input-linein analog-input-aux analog-input-video analog-input-tvtuner analog-input-fm analog-input-mic-line analog-input-headphone-mic analog-input-headset-mic
+priority = 1
+
+# Based on mono-fallback
+[Mapping analog-mono]
+device-strings = hw:%f
+channel-map = mono
+paths-output = analog-output analog-output-lineout analog-output-speaker analog-output-headphones analog-output-headphones-2 analog-output-mono
+paths-input = analog-input-front-mic analog-input-rear-mic analog-input-internal-mic analog-input-dock-mic analog-input analog-input-mic analog-input-linein analog-input-aux analog-input-video analog-input-tvtuner analog-input-fm analog-input-mic-line analog-input-headset-mic
+priority = 1
+
+# The rest of these are identical to what's in default.conf
+[Mapping analog-surround-21]
+device-strings = surround21:%f
+channel-map = front-left,front-right,lfe
+paths-output = analog-output analog-output-lineout analog-output-speaker
+priority = 13
+direction = output
+
+[Mapping analog-surround-40]
+device-strings = surround40:%f
+channel-map = front-left,front-right,rear-left,rear-right
+paths-output = analog-output analog-output-lineout analog-output-speaker
+priority = 12
+direction = output
+
+[Mapping analog-surround-41]
+device-strings = surround41:%f
+channel-map = front-left,front-right,rear-left,rear-right,lfe
+paths-output = analog-output analog-output-lineout analog-output-speaker
+priority = 13
+direction = output
+
+[Mapping analog-surround-50]
+device-strings = surround50:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center
+paths-output = analog-output analog-output-lineout analog-output-speaker
+priority = 12
+direction = output
+
+[Mapping analog-surround-51]
+device-strings = surround51:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+paths-output = analog-output analog-output-lineout analog-output-speaker
+priority = 13
+direction = output
+
+[Mapping analog-surround-71]
+device-strings = surround71:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe,side-left,side-right
+description = Analog Surround 7.1
+paths-output = analog-output analog-output-lineout analog-output-speaker
+priority = 12
+direction = output
+
+[Mapping iec958-stereo]
+device-strings = iec958:%f
+channel-map = left,right
+paths-input = iec958-stereo-input
+paths-output = iec958-stereo-output
+priority = 5
diff --git a/src/modules/alsa/mixer/profile-sets/cmedia-high-speed-true-hdaudio.conf b/src/modules/alsa/mixer/profile-sets/cmedia-high-speed-true-hdaudio.conf
new file mode 100644
index 0000000..1b6f61c
--- /dev/null
+++ b/src/modules/alsa/mixer/profile-sets/cmedia-high-speed-true-hdaudio.conf
@@ -0,0 +1,66 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+# Config for CMEDIA USB2.0 High-Speed True HD Audio 147a:e055
+# Added by Jean-Philippe Guillemin <h1p8r10n@gmail.com>
+
+
+[General]
+auto-profiles = yes
+
+[Mapping analog-stereo]
+device-strings = front:%f
+channel-map = left,right
+paths-output = analog-output analog-output-lineout analog-output-speaker analog-output-headphones analog-output-headphones-2
+paths-input = analog-input-front-mic analog-input-rear-mic analog-input-internal-mic analog-input-dock-mic analog-input analog-input-mic analog-input-linein analog-input-aux analog-input-video analog-input-tvtuner analog-input-fm analog-input-mic-line analog-input-headphone-mic analog-input-headset-mic
+priority = 10
+
+# If everything else fails, try to use hw:0 as a stereo device.
+[Mapping stereo-fallback]
+device-strings = hw:%f
+fallback = yes
+channel-map = front-left,front-right
+paths-output = analog-output analog-output-lineout analog-output-speaker analog-output-headphones analog-output-headphones-2
+paths-input = analog-input-front-mic analog-input-rear-mic analog-input-internal-mic analog-input-dock-mic analog-input analog-input-mic analog-input-linein analog-input-aux analog-input-video analog-input-tvtuner analog-input-fm analog-input-mic-line analog-input-headphone-mic analog-input-headset-mic
+priority = 1
+
+[Mapping analog-surround-21]
+device-strings = surround21:%f
+channel-map = front-left,front-right,lfe
+paths-output = analog-output analog-output-lineout analog-output-speaker
+priority = 8
+direction = output
+
+[Mapping analog-surround-51]
+device-strings = surround51:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+paths-output = analog-output analog-output-lineout analog-output-speaker
+priority = 8
+direction = output
+
+[Mapping analog-surround-71]
+device-strings = surround71:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe,side-left,side-right
+description = Analog Surround 7.1
+paths-output = analog-output analog-output-lineout analog-output-speaker
+priority = 7
+direction = output
+
+[Mapping iec958-stereo]
+device-strings = hw:%f,2 hw:%f,0
+channel-map = left,right
+paths-output = iec958-stereo-output
+paths-input = iec958-stereo-input
+priority = 5
diff --git a/src/modules/alsa/mixer/profile-sets/default.conf b/src/modules/alsa/mixer/profile-sets/default.conf
new file mode 100644
index 0000000..9b691fe
--- /dev/null
+++ b/src/modules/alsa/mixer/profile-sets/default.conf
@@ -0,0 +1,484 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Default profile definitions for the ALSA backend of PulseAudio. This
+; is used as fallback for all cards that have no special mapping
+; assigned (and should be good enough for the vast majority of
+; cards). If you want to assign a different profile set than this one
+; to a device, either set the udev property PULSE_PROFILE_SET for the
+; card, or use the "profile_set" module argument when loading
+; module-alsa-card.
+;
+; So what is this about? Simply, what we do here is map ALSA devices
+; to how they are exposed in PA. We say which ALSA device string to
+; use to open a device, which channel mapping to use then, and which
+; mixer path to use. This is encoded in a 'mapping'. Multiple of these
+; mappings can be bound together in a 'profile' which is then directly
+; exposed in the UI as a card profile. Each mapping assigned to a
+; profile will result in one sink/source to be created if the profile
+; is selected for the card.
+;
+; Additionally, the path set configuration files can describe the
+; decibel values assigned to the steps of the volume elements. This
+; can be used to work around situations when the alsa driver doesn't
+; provide any decibel information, or when the information is
+; incorrect.
+
+
+; [General]
+; auto-profiles = no | yes # Instead of defining all profiles manually, autogenerate
+; # them by combining every input mapping with every output mapping.
+;
+; [Mapping id]
+; device-strings = ... # ALSA device string. %f will be replaced by the card identifier.
+; channel-map = ... # Channel mapping to use for this device
+; description = ... # Description for the mapping. Note that it's better to set the description
+; # in the well_known_descriptions table in alsa-mixer.c than with this
+; # option, because the descriptions in alsa-mixer.c are translatable.
+; description-key = ... # A custom key for the well_known_descriptions table (by default the mapping
+; # name is used).
+; paths-input = ... # A list of mixer paths to use. Every path in this list will be probed.
+; # If multiple are found to be working they will be available as device ports
+; paths-output = ...
+; element-input = ... # Instead of configuring a full mixer path simply configure a single
+; # mixer element for volume/mute handling. The value can be an element
+; # name, or name and index separated by a comma.
+; element-output = ...
+; priority = ...
+; direction = any | input | output # Only useful for?
+;
+; exact-channels = yes | no # If no, and the exact number of channels is not supported,
+; # allow device to be opened with another channel count
+; fallback = no | yes # This mapping will only be considered if all non-fallback mappings fail
+; intended-roles = ... # Set the device.intended_roles property for the sink/source.
+;
+; [Profile id]
+; input-mappings = ... # Lists mappings for sources on this profile, those mapping must be
+; # defined in this file too
+; output-mappings = ... # Lists mappings for sinks on this profile, those mappings must be
+; # defined in this file too
+; description = ...
+; priority = ... # Numeric value to deduce priority for this profile
+; skip-probe = no | yes # Skip probing for availability? If this is yes then this profile
+; # will be assumed as working without probing. Makes initialization
+; # a bit faster but only works if the card is really known well.
+;
+; fallback = no | yes # This profile will only be considered if all non-fallback profiles fail
+; [DecibelFix element] # Decibel fixes can be used to work around missing or incorrect dB
+; # information from alsa. A decibel fix is a table that maps volume steps
+; # to decibel values for one volume element. The "element" part in the
+; # section title is the name of the volume element (or name and index
+; # separated by a comma).
+; #
+; # NOTE: This feature is meant just as a help for figuring out the correct
+; # decibel values. PulseAudio is not the correct place to maintain the
+; # decibel mappings!
+; #
+; # If you need this feature, then you should make sure that when you have
+; # the correct values figured out, the alsa driver developers get informed
+; # too, so that they can fix the driver.
+;
+; db-values = ... # The option value consists of pairs of step numbers and decibel values.
+; # The pairs are separated with whitespace, and steps are separated from
+; # the corresponding decibel values with a colon. The values must be in an
+; # increasing order. Here's an example of a valid string:
+; #
+; # "0:-40.50 1:-38.70 3:-33.00 11:0"
+; #
+; # The lowest step imposes a lower limit for hardware volume and the
+; # highest step correspondingly imposes a higher limit. That means that
+; # that the mixer will never be set outside those values - the rest of the
+; # volume scale is done using software volume.
+; #
+; # As can be seen in the example, you don't need to specify a dB value for
+; # each step. The dB values for skipped steps will be linearly interpolated
+; # using the nearest steps that are given.
+
+[General]
+auto-profiles = yes
+
+[Mapping analog-stereo]
+device-strings = front:%f
+channel-map = left,right
+paths-output = analog-output analog-output-lineout analog-output-speaker analog-output-headphones analog-output-headphones-2
+paths-input = analog-input-front-mic analog-input-rear-mic analog-input-internal-mic analog-input-dock-mic analog-input analog-input-mic analog-input-linein analog-input-aux analog-input-video analog-input-tvtuner analog-input-fm analog-input-mic-line analog-input-headphone-mic analog-input-headset-mic
+priority = 15
+
+# If everything else fails, try to use hw:0 as a stereo device...
+[Mapping stereo-fallback]
+device-strings = hw:%f
+fallback = yes
+channel-map = front-left,front-right
+paths-output = analog-output analog-output-lineout analog-output-speaker analog-output-headphones analog-output-headphones-2
+paths-input = analog-input-front-mic analog-input-rear-mic analog-input-internal-mic analog-input-dock-mic analog-input analog-input-mic analog-input-linein analog-input-aux analog-input-video analog-input-tvtuner analog-input-fm analog-input-mic-line analog-input-headphone-mic analog-input-headset-mic
+priority = 1
+
+# ...and if even that fails, try to use hw:0 as a mono device.
+[Mapping mono-fallback]
+device-strings = hw:%f
+fallback = yes
+channel-map = mono
+paths-output = analog-output analog-output-lineout analog-output-speaker analog-output-headphones analog-output-headphones-2 analog-output-mono
+paths-input = analog-input-front-mic analog-input-rear-mic analog-input-internal-mic analog-input-dock-mic analog-input analog-input-mic analog-input-linein analog-input-aux analog-input-video analog-input-tvtuner analog-input-fm analog-input-mic-line analog-input-headset-mic
+priority = 1
+
+[Mapping analog-surround-21]
+device-strings = surround21:%f
+channel-map = front-left,front-right,lfe
+paths-output = analog-output analog-output-lineout analog-output-speaker
+priority = 13
+direction = output
+
+[Mapping analog-surround-40]
+device-strings = surround40:%f
+channel-map = front-left,front-right,rear-left,rear-right
+paths-output = analog-output analog-output-lineout analog-output-speaker
+priority = 12
+direction = output
+
+[Mapping analog-surround-41]
+device-strings = surround41:%f
+channel-map = front-left,front-right,rear-left,rear-right,lfe
+paths-output = analog-output analog-output-lineout analog-output-speaker
+priority = 13
+direction = output
+
+[Mapping analog-surround-50]
+device-strings = surround50:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center
+paths-output = analog-output analog-output-lineout analog-output-speaker
+priority = 12
+direction = output
+
+[Mapping analog-surround-51]
+device-strings = surround51:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+paths-output = analog-output analog-output-lineout analog-output-speaker
+priority = 13
+direction = output
+
+[Mapping analog-surround-71]
+device-strings = surround71:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe,side-left,side-right
+description = Analog Surround 7.1
+paths-output = analog-output analog-output-lineout analog-output-speaker
+priority = 12
+direction = output
+
+[Mapping iec958-stereo]
+device-strings = iec958:%f
+channel-map = left,right
+paths-input = iec958-stereo-input
+paths-output = iec958-stereo-output
+priority = 5
+
+[Mapping iec958-ac3-surround-40]
+device-strings = a52:%f
+channel-map = front-left,front-right,rear-left,rear-right
+paths-output = iec958-stereo-output
+priority = 2
+direction = output
+
+[Mapping iec958-ac3-surround-51]
+device-strings = a52:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+paths-output = iec958-stereo-output
+priority = 3
+direction = output
+
+[Mapping iec958-dts-surround-51]
+device-strings = dca:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+paths-output = iec958-stereo-output
+priority = 3
+direction = output
+
+[Mapping hdmi-stereo]
+description = Digital Stereo (HDMI)
+device-strings = hdmi:%f
+paths-output = hdmi-output-0
+channel-map = left,right
+priority = 9
+direction = output
+
+[Mapping hdmi-surround]
+description = Digital Surround 5.1 (HDMI)
+device-strings = hdmi:%f
+paths-output = hdmi-output-0
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+priority = 8
+direction = output
+
+[Mapping hdmi-surround71]
+description = Digital Surround 7.1 (HDMI)
+device-strings = hdmi:%f
+paths-output = hdmi-output-0
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe,side-left,side-right
+priority = 8
+direction = output
+
+[Mapping hdmi-dts-surround]
+description = Digital Surround 5.1 (HDMI/DTS)
+device-strings = dcahdmi:%f
+paths-output = hdmi-output-0
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+priority = 6
+direction = output
+
+[Mapping hdmi-stereo-extra1]
+description = Digital Stereo (HDMI 2)
+device-strings = hdmi:%f,1
+paths-output = hdmi-output-1
+channel-map = left,right
+priority = 7
+direction = output
+
+[Mapping hdmi-surround-extra1]
+description = Digital Surround 5.1 (HDMI 2)
+device-strings = hdmi:%f,1
+paths-output = hdmi-output-1
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+priority = 6
+direction = output
+
+[Mapping hdmi-surround71-extra1]
+description = Digital Surround 7.1 (HDMI 2)
+device-strings = hdmi:%f,1
+paths-output = hdmi-output-1
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe,side-left,side-right
+priority = 6
+direction = output
+
+[Mapping hdmi-dts-surround-extra1]
+description = Digital Surround 5.1 (HDMI 2/DTS)
+device-strings = dcahdmi:%f,1
+paths-output = hdmi-output-1
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+priority = 6
+direction = output
+
+[Mapping hdmi-stereo-extra2]
+description = Digital Stereo (HDMI 3)
+device-strings = hdmi:%f,2
+paths-output = hdmi-output-2
+channel-map = left,right
+priority = 7
+direction = output
+
+[Mapping hdmi-surround-extra2]
+description = Digital Surround 5.1 (HDMI 3)
+device-strings = hdmi:%f,2
+paths-output = hdmi-output-2
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+priority = 6
+direction = output
+
+[Mapping hdmi-surround71-extra2]
+description = Digital Surround 7.1 (HDMI 3)
+device-strings = hdmi:%f,2
+paths-output = hdmi-output-2
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe,side-left,side-right
+priority = 6
+direction = output
+
+[Mapping hdmi-dts-surround-extra2]
+description = Digital Surround 5.1 (HDMI 3/DTS)
+device-strings = dcahdmi:%f,2
+paths-output = hdmi-output-2
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+priority = 6
+direction = output
+
+[Mapping hdmi-stereo-extra3]
+description = Digital Stereo (HDMI 4)
+device-strings = hdmi:%f,3
+paths-output = hdmi-output-3
+channel-map = left,right
+priority = 7
+direction = output
+
+[Mapping hdmi-surround-extra3]
+description = Digital Surround 5.1 (HDMI 4)
+device-strings = hdmi:%f,3
+paths-output = hdmi-output-3
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+priority = 6
+direction = output
+
+[Mapping hdmi-surround71-extra3]
+description = Digital Surround 7.1 (HDMI 4)
+device-strings = hdmi:%f,3
+paths-output = hdmi-output-3
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe,side-left,side-right
+priority = 6
+direction = output
+
+[Mapping hdmi-dts-surround-extra3]
+description = Digital Surround 5.1 (HDMI 4/DTS)
+device-strings = dcahdmi:%f,3
+paths-output = hdmi-output-3
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+priority = 6
+direction = output
+
+[Mapping hdmi-stereo-extra4]
+description = Digital Stereo (HDMI 5)
+device-strings = hdmi:%f,4
+paths-output = hdmi-output-4
+channel-map = left,right
+priority = 7
+direction = output
+
+[Mapping hdmi-surround-extra4]
+description = Digital Surround 5.1 (HDMI 5)
+device-strings = hdmi:%f,4
+paths-output = hdmi-output-4
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+priority = 6
+direction = output
+
+[Mapping hdmi-surround71-extra4]
+description = Digital Surround 7.1 (HDMI 5)
+device-strings = hdmi:%f,4
+paths-output = hdmi-output-4
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe,side-left,side-right
+priority = 6
+direction = output
+
+[Mapping hdmi-dts-surround-extra4]
+description = Digital Surround 5.1 (HDMI 5/DTS)
+device-strings = dcahdmi:%f,4
+paths-output = hdmi-output-4
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+priority = 6
+direction = output
+
+[Mapping hdmi-stereo-extra5]
+description = Digital Stereo (HDMI 6)
+device-strings = hdmi:%f,5
+paths-output = hdmi-output-5
+channel-map = left,right
+priority = 7
+direction = output
+
+[Mapping hdmi-surround-extra5]
+description = Digital Surround 5.1 (HDMI 6)
+device-strings = hdmi:%f,5
+paths-output = hdmi-output-5
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+priority = 6
+direction = output
+
+[Mapping hdmi-surround71-extra5]
+description = Digital Surround 7.1 (HDMI 6)
+device-strings = hdmi:%f,5
+paths-output = hdmi-output-5
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe,side-left,side-right
+priority = 6
+direction = output
+
+[Mapping hdmi-dts-surround-extra5]
+description = Digital Surround 5.1 (HDMI 6/DTS)
+device-strings = dcahdmi:%f,5
+paths-output = hdmi-output-5
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+priority = 6
+direction = output
+
+[Mapping hdmi-stereo-extra6]
+description = Digital Stereo (HDMI 7)
+device-strings = hdmi:%f,6
+paths-output = hdmi-output-6
+channel-map = left,right
+priority = 7
+direction = output
+
+[Mapping hdmi-surround-extra6]
+description = Digital Surround 5.1 (HDMI 7)
+device-strings = hdmi:%f,6
+paths-output = hdmi-output-6
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+priority = 6
+direction = output
+
+[Mapping hdmi-surround71-extra6]
+description = Digital Surround 7.1 (HDMI 7)
+device-strings = hdmi:%f,6
+paths-output = hdmi-output-6
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe,side-left,side-right
+priority = 6
+direction = output
+
+[Mapping hdmi-dts-surround-extra6]
+description = Digital Surround 5.1 (HDMI 7/DTS)
+device-strings = dcahdmi:%f,6
+paths-output = hdmi-output-6
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+priority = 6
+direction = output
+
+[Mapping hdmi-stereo-extra7]
+description = Digital Stereo (HDMI 8)
+device-strings = hdmi:%f,7
+paths-output = hdmi-output-7
+channel-map = left,right
+priority = 7
+direction = output
+
+[Mapping hdmi-surround-extra7]
+description = Digital Surround 5.1 (HDMI 8)
+device-strings = hdmi:%f,7
+paths-output = hdmi-output-7
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+priority = 6
+direction = output
+
+[Mapping hdmi-surround71-extra7]
+description = Digital Surround 7.1 (HDMI 8)
+device-strings = hdmi:%f,7
+paths-output = hdmi-output-7
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe,side-left,side-right
+priority = 6
+direction = output
+
+[Mapping hdmi-dts-surround-extra7]
+description = Digital Surround 5.1 (HDMI 8/DTS)
+device-strings = dcahdmi:%f,7
+paths-output = hdmi-output-7
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+priority = 6
+direction = output
+
+[Mapping multichannel-output]
+device-strings = hw:%f
+channel-map = left,right,rear-left,rear-right
+exact-channels = false
+fallback = yes
+priority = 1
+direction = output
+
+[Mapping multichannel-input]
+device-strings = hw:%f
+channel-map = left,right,rear-left,rear-right
+exact-channels = false
+fallback = yes
+priority = 1
+direction = input
+
+; An example for defining multiple-sink profiles
+#[Profile output:analog-stereo+output:iec958-stereo+input:analog-stereo]
+#description = Foobar
+#output-mappings = analog-stereo iec958-stereo
+#input-mappings = analog-stereo
diff --git a/src/modules/alsa/mixer/profile-sets/dell-dock-tb16-usb-audio.conf b/src/modules/alsa/mixer/profile-sets/dell-dock-tb16-usb-audio.conf
new file mode 100644
index 0000000..1186552
--- /dev/null
+++ b/src/modules/alsa/mixer/profile-sets/dell-dock-tb16-usb-audio.conf
@@ -0,0 +1,55 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Dell Dock TB16 USB audio
+;
+; This card has two stereo pairs of output, One Mono input.
+;
+; See default.conf for an explanation on the directives used here.
+
+[General]
+auto-profiles = no
+
+[Mapping analog-stereo-headphone]
+description = Headphone
+device-strings = hw:%f,0,0
+channel-map = left,right
+direction = output
+
+[Mapping analog-stereo-speaker]
+description = Speaker
+device-strings = hw:%f,1,0
+channel-map = left,right
+direction = output
+
+[Mapping analog-stereo-mic]
+description = Headset-Mic
+device-strings = hw:%f,0,0
+channel-map = left,right
+direction = input
+
+
+[Profile output:analog-stereo-speaker]
+description = Speaker
+output-mappings = analog-stereo-speaker
+priority = 60
+skip-probe = yes
+
+[Profile output:analog-stereo-headphone+input:analog-stereo-mic]
+description = Headset
+output-mappings = analog-stereo-headphone
+input-mappings = analog-stereo-mic
+priority = 80
+skip-probe = yes
diff --git a/src/modules/alsa/mixer/profile-sets/force-speaker-and-int-mic.conf b/src/modules/alsa/mixer/profile-sets/force-speaker-and-int-mic.conf
new file mode 100644
index 0000000..41924f4
--- /dev/null
+++ b/src/modules/alsa/mixer/profile-sets/force-speaker-and-int-mic.conf
@@ -0,0 +1,153 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; This profile forces speaker and internal mic ports even if we have no way
+; of identifying those.
+; See default.conf for explanations.
+
+[General]
+auto-profiles = yes
+
+[Mapping analog-mono]
+device-strings = hw:%f
+channel-map = mono
+paths-output = analog-output analog-output-lineout analog-output-speaker-always analog-output-headphones analog-output-headphones-2 analog-output-mono
+paths-input = analog-input-front-mic analog-input-rear-mic analog-input-internal-mic-always analog-input-dock-mic analog-input analog-input-mic analog-input-linein analog-input-aux analog-input-video analog-input-tvtuner analog-input-fm analog-input-mic-line
+priority = 1
+
+[Mapping analog-stereo]
+device-strings = front:%f hw:%f
+channel-map = left,right
+paths-output = analog-output analog-output-lineout analog-output-speaker-always analog-output-headphones analog-output-headphones-2 analog-output-mono
+paths-input = analog-input-front-mic analog-input-rear-mic analog-input-internal-mic-always analog-input-dock-mic analog-input analog-input-mic analog-input-linein analog-input-aux analog-input-video analog-input-tvtuner analog-input-fm analog-input-mic-line
+priority = 10
+
+[Mapping analog-surround-21]
+device-strings = surround21:%f
+channel-map = front-left,front-right,lfe
+paths-output = analog-output analog-output-lineout analog-output-speaker-always
+priority = 8
+direction = output
+
+[Mapping analog-surround-40]
+device-strings = surround40:%f
+channel-map = front-left,front-right,rear-left,rear-right
+paths-output = analog-output analog-output-lineout analog-output-speaker-always
+priority = 7
+direction = output
+
+[Mapping analog-surround-41]
+device-strings = surround41:%f
+channel-map = front-left,front-right,rear-left,rear-right,lfe
+paths-output = analog-output analog-output-lineout analog-output-speaker-always
+priority = 8
+direction = output
+
+[Mapping analog-surround-50]
+device-strings = surround50:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center
+paths-output = analog-output analog-output-lineout analog-output-speaker-always
+priority = 7
+direction = output
+
+[Mapping analog-surround-51]
+device-strings = surround51:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+paths-output = analog-output analog-output-lineout analog-output-speaker-always
+priority = 8
+direction = output
+
+[Mapping analog-surround-71]
+device-strings = surround71:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe,side-left,side-right
+description = Analog Surround 7.1
+paths-output = analog-output analog-output-lineout analog-output-speaker-always
+priority = 7
+direction = output
+
+[Mapping analog-4-channel-input]
+# Alsa doesn't currently provide any better device name than "hw" for 4-channel
+# input. If this causes trouble at some point, then we will need to get a new
+# device name standardized in alsa.
+device-strings = hw:%f
+channel-map = aux0,aux1,aux2,aux3
+priority = 1
+direction = input
+
+[Mapping iec958-stereo]
+device-strings = iec958:%f
+channel-map = left,right
+paths-input = iec958-stereo-input
+paths-output = iec958-stereo-output
+priority = 5
+
+[Mapping iec958-ac3-surround-40]
+device-strings = a52:%f
+channel-map = front-left,front-right,rear-left,rear-right
+paths-output = iec958-stereo-output
+priority = 2
+direction = output
+
+[Mapping iec958-ac3-surround-51]
+device-strings = a52:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+paths-output = iec958-stereo-output
+priority = 3
+direction = output
+
+[Mapping iec958-dts-surround-51]
+device-strings = dca:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+paths-output = iec958-stereo-output
+priority = 3
+direction = output
+
+[Mapping hdmi-stereo]
+description = Digital Stereo (HDMI)
+device-strings = hdmi:%f
+paths-output = hdmi-output-0
+channel-map = left,right
+priority = 4
+direction = output
+
+[Mapping hdmi-surround]
+description = Digital Surround 5.1 (HDMI)
+device-strings = hdmi:%f
+paths-output = hdmi-output-0
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+priority = 3
+direction = output
+
+[Mapping hdmi-surround71]
+description = Digital Surround 7.1 (HDMI)
+device-strings = hdmi:%f
+paths-output = hdmi-output-0
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe,side-left,side-right
+priority = 3
+direction = output
+
+[Mapping hdmi-dts-surround]
+description = Digital Surround 5.1 (HDMI/DTS)
+device-strings = dcahdmi:%f
+paths-output = hdmi-output-0
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+priority = 1
+direction = output
+
+; An example for defining multiple-sink profiles
+#[Profile output:analog-stereo+output:iec958-stereo+input:analog-stereo]
+#description = Foobar
+#output-mappings = analog-stereo iec958-stereo
+#input-mappings = analog-stereo
diff --git a/src/modules/alsa/mixer/profile-sets/force-speaker.conf b/src/modules/alsa/mixer/profile-sets/force-speaker.conf
new file mode 100644
index 0000000..dec57d5
--- /dev/null
+++ b/src/modules/alsa/mixer/profile-sets/force-speaker.conf
@@ -0,0 +1,152 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; This profile forces a speaker port even if we have no way of identifying it.
+; See default.conf for explanations.
+
+[General]
+auto-profiles = yes
+
+[Mapping analog-mono]
+device-strings = hw:%f
+channel-map = mono
+paths-output = analog-output analog-output-lineout analog-output-speaker-always analog-output-headphones analog-output-headphones-2 analog-output-mono
+paths-input = analog-input-front-mic analog-input-rear-mic analog-input-internal-mic analog-input-dock-mic analog-input analog-input-mic analog-input-linein analog-input-aux analog-input-video analog-input-tvtuner analog-input-fm analog-input-mic-line
+priority = 1
+
+[Mapping analog-stereo]
+device-strings = front:%f hw:%f
+channel-map = left,right
+paths-output = analog-output analog-output-lineout analog-output-speaker-always analog-output-headphones analog-output-headphones-2 analog-output-mono
+paths-input = analog-input-front-mic analog-input-rear-mic analog-input-internal-mic analog-input-dock-mic analog-input analog-input-mic analog-input-linein analog-input-aux analog-input-video analog-input-tvtuner analog-input-fm analog-input-mic-line
+priority = 10
+
+[Mapping analog-surround-21]
+device-strings = surround21:%f
+channel-map = front-left,front-right,lfe
+paths-output = analog-output analog-output-lineout analog-output-speaker-always
+priority = 8
+direction = output
+
+[Mapping analog-surround-40]
+device-strings = surround40:%f
+channel-map = front-left,front-right,rear-left,rear-right
+paths-output = analog-output analog-output-lineout analog-output-speaker-always
+priority = 7
+direction = output
+
+[Mapping analog-surround-41]
+device-strings = surround41:%f
+channel-map = front-left,front-right,rear-left,rear-right,lfe
+paths-output = analog-output analog-output-lineout analog-output-speaker-always
+priority = 8
+direction = output
+
+[Mapping analog-surround-50]
+device-strings = surround50:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center
+paths-output = analog-output analog-output-lineout analog-output-speaker-always
+priority = 7
+direction = output
+
+[Mapping analog-surround-51]
+device-strings = surround51:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+paths-output = analog-output analog-output-lineout analog-output-speaker-always
+priority = 8
+direction = output
+
+[Mapping analog-surround-71]
+device-strings = surround71:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe,side-left,side-right
+description = Analog Surround 7.1
+paths-output = analog-output analog-output-lineout analog-output-speaker-always
+priority = 7
+direction = output
+
+[Mapping analog-4-channel-input]
+# Alsa doesn't currently provide any better device name than "hw" for 4-channel
+# input. If this causes trouble at some point, then we will need to get a new
+# device name standardized in alsa.
+device-strings = hw:%f
+channel-map = aux0,aux1,aux2,aux3
+priority = 1
+direction = input
+
+[Mapping iec958-stereo]
+device-strings = iec958:%f
+channel-map = left,right
+paths-input = iec958-stereo-input
+paths-output = iec958-stereo-output
+priority = 5
+
+[Mapping iec958-ac3-surround-40]
+device-strings = a52:%f
+channel-map = front-left,front-right,rear-left,rear-right
+paths-output = iec958-stereo-output
+priority = 2
+direction = output
+
+[Mapping iec958-ac3-surround-51]
+device-strings = a52:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+paths-output = iec958-stereo-output
+priority = 3
+direction = output
+
+[Mapping iec958-dts-surround-51]
+device-strings = dca:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+paths-output = iec958-stereo-output
+priority = 3
+direction = output
+
+[Mapping hdmi-stereo]
+description = Digital Stereo (HDMI)
+device-strings = hdmi:%f
+paths-output = hdmi-output-0
+channel-map = left,right
+priority = 4
+direction = output
+
+[Mapping hdmi-surround]
+description = Digital Surround 5.1 (HDMI)
+device-strings = hdmi:%f
+paths-output = hdmi-output-0
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+priority = 3
+direction = output
+
+[Mapping hdmi-surround71]
+description = Digital Surround 7.1 (HDMI)
+device-strings = hdmi:%f
+paths-output = hdmi-output-0
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe,side-left,side-right
+priority = 3
+direction = output
+
+[Mapping hdmi-dts-surround]
+description = Digital Surround 5.1 (HDMI/DTS)
+device-strings = dcahdmi:%f
+paths-output = hdmi-output-0
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+priority = 1
+direction = output
+
+; An example for defining multiple-sink profiles
+#[Profile output:analog-stereo+output:iec958-stereo+input:analog-stereo]
+#description = Foobar
+#output-mappings = analog-stereo iec958-stereo
+#input-mappings = analog-stereo
diff --git a/src/modules/alsa/mixer/profile-sets/kinect-audio.conf b/src/modules/alsa/mixer/profile-sets/kinect-audio.conf
new file mode 100644
index 0000000..d51fd17
--- /dev/null
+++ b/src/modules/alsa/mixer/profile-sets/kinect-audio.conf
@@ -0,0 +1,38 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Audio profile for the Microsoft Kinect Sensor device in UAC mode.
+;
+; Copyright (C) 2011 Antonio Ospite <ospite@studenti.unina.it>
+;
+; This device has an array of four microphones, and no playback capability.
+;
+; See default.conf for an explanation on the directives used here.
+
+[General]
+auto-profiles = no
+
+[Mapping input-4-channels]
+device-strings = hw:%f
+channel-map = front-left,front-right,rear-left,rear-right
+description = 4 Channels Input
+direction = input
+priority = 5
+
+[Profile input:mic-array]
+description = Microphone Array
+input-mappings = input-4-channels
+priority = 2
+skip-probe = yes
diff --git a/src/modules/alsa/mixer/profile-sets/maudio-fasttrack-pro.conf b/src/modules/alsa/mixer/profile-sets/maudio-fasttrack-pro.conf
new file mode 100644
index 0000000..5122907
--- /dev/null
+++ b/src/modules/alsa/mixer/profile-sets/maudio-fasttrack-pro.conf
@@ -0,0 +1,86 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; M-Audio FastTrack Pro
+;
+; This card has one duplex stereo channel called A and an additional
+; stereo output channel called B.
+;
+; We knowingly only define a subset of the theoretically possible
+; mapping combinations as profiles here.
+;
+; See default.conf for an explanation on the directives used here.
+
+[General]
+auto-profiles = no
+
+[Mapping analog-stereo-a-output]
+description = Analog Stereo Channel A
+device-strings = hw:%f,0,0
+channel-map = left,right
+direction = output
+
+; Try both device 0 and device 1 for input, see
+; http://mailman.alsa-project.org/pipermail/alsa-devel/2012-March/050701.html
+[Mapping analog-stereo-a-input]
+description = Analog Stereo Channel A
+device-strings = hw:%f,0,0 hw:%f,1,0
+channel-map = left,right
+direction = input
+
+[Mapping analog-stereo-b-output]
+description = Analog Stereo Channel B
+device-strings = hw:%f,1,0
+channel-map = left,right
+direction = output
+
+[Profile output:analog-stereo-all+input:analog-stereo-all]
+description = Analog Stereo Duplex Channel A, Analog Stereo output Channel B
+output-mappings = analog-stereo-a-output analog-stereo-b-output
+input-mappings = analog-stereo-a-input
+priority = 100
+skip-probe = yes
+
+[Profile output:analog-stereo-a-output+input:analog-stereo-a-input]
+description = Analog Stereo Duplex Channel A
+output-mappings = analog-stereo-a-output
+input-mappings = analog-stereo-a-input
+priority = 40
+skip-probe = yes
+
+[Profile output:analog-stereo-b+input:analog-stereo-b]
+description = Analog Stereo Output Channel B
+output-mappings = analog-stereo-b-output
+input-mappings =
+priority = 50
+skip-probe = yes
+
+[Profile output:analog-stereo-a]
+description = Analog Stereo Output Channel A
+output-mappings = analog-stereo-a-output
+priority = 5
+skip-probe = yes
+
+[Profile output:analog-stereo-b]
+description = Analog Stereo Output Channel B
+output-mappings = analog-stereo-b-output
+priority = 6
+skip-probe = yes
+
+[Profile input:analog-stereo-a]
+description = Analog Stereo Input Channel A
+input-mappings = analog-stereo-a-input
+priority = 2
+skip-probe = yes
diff --git a/src/modules/alsa/mixer/profile-sets/native-instruments-audio4dj.conf b/src/modules/alsa/mixer/profile-sets/native-instruments-audio4dj.conf
new file mode 100644
index 0000000..f7cbc15
--- /dev/null
+++ b/src/modules/alsa/mixer/profile-sets/native-instruments-audio4dj.conf
@@ -0,0 +1,90 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Native Instruments Audio 4 DJ
+;
+; This card has two stereo pairs of input and two stereo pairs of
+; output, named channels A and B. Channel B has an additional
+; Headphone connector.
+;
+; We knowingly only define a subset of the theoretically possible
+; mapping combinations as profiles here.
+;
+; See default.conf for an explanation on the directives used here.
+
+[General]
+auto-profiles = no
+
+[Mapping analog-stereo-a]
+description = Analog Stereo Channel A
+device-strings = hw:%f,0,0
+channel-map = left,right
+
+[Mapping analog-stereo-b-output]
+description = Analog Stereo Channel B (Headphones)
+device-strings = hw:%f,0,1
+channel-map = left,right
+direction = output
+
+[Mapping analog-stereo-b-input]
+description = Analog Stereo Channel B
+device-strings = hw:%f,0,1
+channel-map = left,right
+direction = input
+
+[Profile output:analog-stereo-all+input:analog-stereo-all]
+description = Analog Stereo Duplex Channels A, B (Headphones)
+output-mappings = analog-stereo-a analog-stereo-b-output
+input-mappings = analog-stereo-a analog-stereo-b-input
+priority = 100
+skip-probe = yes
+
+[Profile output:analog-stereo-a+input:analog-stereo-a]
+description = Analog Stereo Duplex Channel A
+output-mappings = analog-stereo-a
+input-mappings = analog-stereo-a
+priority = 40
+skip-probe = yes
+
+[Profile output:analog-stereo-b+input:analog-stereo-b]
+description = Analog Stereo Duplex Channel B (Headphones)
+output-mappings = analog-stereo-b-output
+input-mappings = analog-stereo-b-input
+priority = 50
+skip-probe = yes
+
+[Profile output:analog-stereo-a]
+description = Analog Stereo Output Channel A
+output-mappings = analog-stereo-a
+priority = 5
+skip-probe = yes
+
+[Profile output:analog-stereo-b]
+description = Analog Stereo Output Channel B (Headphones)
+output-mappings = analog-stereo-b-output
+priority = 6
+skip-probe = yes
+
+[Profile input:analog-stereo-a]
+description = Analog Stereo Input Channel A
+input-mappings = analog-stereo-a
+priority = 2
+skip-probe = yes
+
+[Profile input:analog-stereo-b]
+description = Analog Stereo Input Channel B
+input-mappings = analog-stereo-b-input
+priority = 1
+skip-probe = yes
diff --git a/src/modules/alsa/mixer/profile-sets/native-instruments-audio8dj.conf b/src/modules/alsa/mixer/profile-sets/native-instruments-audio8dj.conf
new file mode 100644
index 0000000..dc1b780
--- /dev/null
+++ b/src/modules/alsa/mixer/profile-sets/native-instruments-audio8dj.conf
@@ -0,0 +1,161 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Native Instruments Audio 8 DJ
+;
+; This card has four stereo pairs of input and four stereo pairs of
+; output, named channels A to D. Channel C has an additional Mic/Line
+; connector, channel D an additional Headphone connector.
+;
+; We knowingly only define a subset of the theoretically possible
+; mapping combinations as profiles here.
+;
+; See default.conf for an explanation on the directives used here.
+
+[General]
+auto-profiles = no
+
+[Mapping analog-stereo-a]
+description = Analog Stereo Channel A
+device-strings = hw:%f,0,0
+channel-map = left,right
+
+[Mapping analog-stereo-b]
+description = Analog Stereo Channel B
+device-strings = hw:%f,0,1
+channel-map = left,right
+
+# Since we want to set a different description for channel C's/D's input
+# and output we define two separate mappings for them
+[Mapping analog-stereo-c-output]
+description = Analog Stereo Channel C
+device-strings = hw:%f,0,2
+channel-map = left,right
+direction = output
+
+[Mapping analog-stereo-c-input]
+description = Analog Stereo Channel C (Line/Mic)
+device-strings = hw:%f,0,2
+channel-map = left,right
+direction = input
+
+[Mapping analog-stereo-d-output]
+description = Analog Stereo Channel D (Headphones)
+device-strings = hw:%f,0,3
+channel-map = left,right
+direction = output
+
+[Mapping analog-stereo-d-input]
+description = Analog Stereo Channel D
+device-strings = hw:%f,0,3
+channel-map = left,right
+direction = input
+
+[Profile output:analog-stereo-all+input:analog-stereo-all]
+description = Analog Stereo Duplex Channels A, B, C (Line/Mic), D (Headphones)
+output-mappings = analog-stereo-a analog-stereo-b analog-stereo-c-output analog-stereo-d-output
+input-mappings = analog-stereo-a analog-stereo-b analog-stereo-c-input analog-stereo-d-input
+priority = 100
+skip-probe = yes
+
+[Profile output:analog-stereo-d+input:analog-stereo-c]
+description = Analog Stereo Channel D (Headphones) Output, Channel C (Line/Mic) Input
+output-mappings = analog-stereo-d-output
+input-mappings = analog-stereo-c-input
+priority = 90
+skip-probe = yes
+
+[Profile output:analog-stereo-c-d+input:analog-stereo-c-d]
+description = Analog Stereo Duplex Channels C (Line/Mic), D (Line/Mic)
+output-mappings = analog-stereo-c-output analog-stereo-d-output
+input-mappings = analog-stereo-c-input analog-stereo-d-input
+priority = 80
+skip-probe = yes
+
+[Profile output:analog-stereo-a+input:analog-stereo-a]
+description = Analog Stereo Duplex Channel A
+output-mappings = analog-stereo-a
+input-mappings = analog-stereo-a
+priority = 50
+skip-probe = yes
+
+[Profile output:analog-stereo-b+input:analog-stereo-b]
+description = Analog Stereo Duplex Channel B
+output-mappings = analog-stereo-b
+input-mappings = analog-stereo-b
+priority = 40
+skip-probe = yes
+
+[Profile output:analog-stereo-c+input:analog-stereo-c]
+description = Analog Stereo Duplex Channel C (Line/Mic)
+output-mappings = analog-stereo-c-output
+input-mappings = analog-stereo-c-input
+priority = 60
+skip-probe = yes
+
+[Profile output:analog-stereo-d+input:analog-stereo-d]
+description = Analog Stereo Duplex Channel D (Headphones)
+output-mappings = analog-stereo-d-output
+input-mappings = analog-stereo-d-input
+priority = 70
+skip-probe = yes
+
+[Profile output:analog-stereo-a]
+description = Analog Stereo Output Channel A
+output-mappings = analog-stereo-a
+priority = 6
+skip-probe = yes
+
+[Profile output:analog-stereo-b]
+description = Analog Stereo Output Channel B
+output-mappings = analog-stereo-b
+priority = 5
+skip-probe = yes
+
+[Profile output:analog-stereo-c]
+description = Analog Stereo Output Channel C
+output-mappings = analog-stereo-c-output
+priority = 7
+skip-probe = yes
+
+[Profile output:analog-stereo-d]
+description = Analog Stereo Output Channel D (Headphones)
+output-mappings = analog-stereo-d-output
+priority = 8
+skip-probe = yes
+
+[Profile input:analog-stereo-a]
+description = Analog Stereo Input Channel A
+input-mappings = analog-stereo-a
+priority = 2
+skip-probe = yes
+
+[Profile input:analog-stereo-b]
+description = Analog Stereo Input Channel B
+input-mappings = analog-stereo-b
+priority = 1
+skip-probe = yes
+
+[Profile input:analog-stereo-c]
+description = Analog Stereo Input Channel C (Line/Mic)
+input-mappings = analog-stereo-c-input
+priority = 4
+skip-probe = yes
+
+[Profile input:analog-stereo-d]
+description = Analog Stereo Input Channel D
+input-mappings = analog-stereo-d-input
+priority = 3
+skip-probe = yes
diff --git a/src/modules/alsa/mixer/profile-sets/native-instruments-korecontroller.conf b/src/modules/alsa/mixer/profile-sets/native-instruments-korecontroller.conf
new file mode 100644
index 0000000..35b3d06
--- /dev/null
+++ b/src/modules/alsa/mixer/profile-sets/native-instruments-korecontroller.conf
@@ -0,0 +1,84 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Native Instruments Kore Controller
+;
+; This card has one stereo pairs of input and two stereo pairs of
+; output, named "Master" and "Headphone". The master channel has
+; an additional Coax S/PDIF connector which is always on.
+;
+; We knowingly only define a subset of the theoretically possible
+; mapping combinations as profiles here.
+;
+; See default.conf for an explanation on the directives used here.
+
+[General]
+auto-profiles = no
+
+[Mapping analog-stereo-master-out]
+description = Analog Stereo Master Channel
+device-strings = hw:%f,0,0
+channel-map = left,right
+
+[Mapping analog-stereo-headphone-out]
+description = Analog Stereo Headphone Channel
+device-strings = hw:%f,0,1
+channel-map = left,right
+direction = output
+
+[Mapping analog-stereo-input]
+description = Analog Stereo
+device-strings = hw:%f,0,0
+channel-map = left,right
+direction = input
+
+[Profile output:analog-stereo-all+input:analog-stereo-all]
+description = Analog Stereo Duplex Master Output, Headphones Output
+output-mappings = analog-stereo-master-out analog-stereo-headphone-out
+input-mappings = analog-stereo-input
+priority = 100
+skip-probe = yes
+
+[Profile output:analog-stereo-master+input:analog-stereo-input]
+description = Analog Stereo Duplex Master Output
+output-mappings = analog-stereo-master-out
+input-mappings = analog-stereo-input
+priority = 40
+skip-probe = yes
+
+[Profile output:analog-stereo-headphone-out+input:analog-stereo-input]
+description = Analog Stereo Headphones Output
+output-mappings = analog-stereo-headphone-out
+input-mappings = analog-stereo-input
+priority = 30
+skip-probe = yes
+
+[Profile output:analog-stereo-master]
+description = Analog Stereo Master Output
+output-mappings = analog-stereo-master-out
+priority = 3
+skip-probe = yes
+
+[Profile output:analog-stereo-headphone]
+description = Analog Stereo Headphones Output
+output-mappings = analog-stereo-headphone-out
+priority = 2
+skip-probe = yes
+
+[Profile input:analog-stereo-input]
+description = Analog Stereo Input
+input-mappings = analog-stereo-input
+priority = 1
+skip-probe = yes
diff --git a/src/modules/alsa/mixer/profile-sets/native-instruments-traktor-audio10.conf b/src/modules/alsa/mixer/profile-sets/native-instruments-traktor-audio10.conf
new file mode 100644
index 0000000..c210297
--- /dev/null
+++ b/src/modules/alsa/mixer/profile-sets/native-instruments-traktor-audio10.conf
@@ -0,0 +1,130 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Native Instruments Audio 10 DJ
+;
+; This card has five stereo pairs of input and five stereo pairs of
+; output
+;
+; We knowingly only define a subset of the theoretically possible
+; mapping combinations as profiles here.
+;
+; See default.conf for an explanation on the directives used here.
+
+[General]
+auto-profiles = no
+
+[Mapping analog-stereo-out-main]
+description = Analog Stereo Main
+device-strings = hw:%f,0,0
+channel-map = left,right
+
+[Mapping analog-stereo-out-a]
+description = Analog Stereo Channel A
+device-strings = hw:%f,0,1
+channel-map = left,right
+direction = output
+
+[Mapping analog-stereo-out-b]
+description = Analog Stereo Channel B
+device-strings = hw:%f,0,1
+channel-map = left,right
+direction = output
+
+[Mapping analog-stereo-out-c]
+description = Analog Stereo Channel C
+device-strings = hw:%f,0,2
+channel-map = left,right
+direction = output
+
+[Mapping analog-stereo-out-d]
+description = Analog Stereo Channel D
+device-strings = hw:%f,0,3
+channel-map = left,right
+direction = output
+
+[Mapping analog-stereo-in-main]
+description = Analog Stereo Main
+device-strings = hw:%f,0,0
+channel-map = left,right
+
+[Mapping analog-stereo-in-a]
+description = Analog Stereo Channel A
+device-strings = hw:%f,0,1
+channel-map = left,right
+direction = input
+
+[Mapping analog-stereo-in-b]
+description = Analog Stereo Channel B
+device-strings = hw:%f,0,1
+channel-map = left,right
+direction = input
+
+[Mapping analog-stereo-in-c]
+description = Analog Stereo Channel C
+device-strings = hw:%f,0,2
+channel-map = left,right
+direction = input
+
+[Mapping analog-stereo-in-d]
+description = Analog Stereo Channel D
+device-strings = hw:%f,0,3
+channel-map = left,right
+direction = input
+
+
+
+
+[Profile output:analog-stereo-all+input:analog-stereo-all]
+description = Analog Stereo Duplex Channels Main, A, B, C, D
+output-mappings = analog-stereo-out-main analog-stereo-out-a analog-stereo-out-b analog-stereo-out-c analog-stereo-out-d
+input-mappings = analog-stereo-in-main analog-stereo-in-a analog-stereo-in-b analog-stereo-in-c analog-stereo-in-d
+priority = 100
+skip-probe = yes
+
+[Profile output:analog-stereo-main+input:analog-stereo-main]
+description = Analog Stereo Duplex Main
+output-mappings = analog-stereo-out-main
+input-mappings = analog-stereo-in-main
+priority = 50
+skip-probe = yes
+
+[Profile output:analog-stereo-a+input:analog-stereo-a]
+description = Analog Stereo Duplex Channel A
+output-mappings = analog-stereo-out-a
+input-mappings = analog-stereo-in-a
+priority = 40
+skip-probe = yes
+
+[Profile output:analog-stereo-b+input:analog-stereo-b]
+description = Analog Stereo Duplex Channel B
+output-mappings = analog-stereo-out-b
+input-mappings = analog-stereo-in-b
+priority = 30
+skip-probe = yes
+
+[Profile output:analog-stereo-a+input:analog-stereo-c]
+description = Analog Stereo Duplex Channel C
+output-mappings = analog-stereo-out-c
+input-mappings = analog-stereo-in-c
+priority = 20
+skip-probe = yes
+
+[Profile output:analog-stereo-a+input:analog-stereo-d]
+description = Analog Stereo Duplex Channel D
+output-mappings = analog-stereo-out-d
+input-mappings = analog-stereo-in-d
+priority = 10
+skip-probe = yes
diff --git a/src/modules/alsa/mixer/profile-sets/native-instruments-traktor-audio2.conf b/src/modules/alsa/mixer/profile-sets/native-instruments-traktor-audio2.conf
new file mode 100644
index 0000000..145dace
--- /dev/null
+++ b/src/modules/alsa/mixer/profile-sets/native-instruments-traktor-audio2.conf
@@ -0,0 +1,53 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Native Instruments Traktor Audio 2
+;
+; This card has two stereo pairs of output.
+;
+; See default.conf for an explanation on the directives used here.
+
+[General]
+auto-profiles = no
+
+[Mapping analog-stereo-a]
+description = Analog Stereo Channel A
+device-strings = hw:%f,0,0
+channel-map = left,right
+direction = output
+
+[Mapping analog-stereo-b]
+description = Analog Stereo Channel B
+device-strings = hw:%f,0,1
+channel-map = left,right
+direction = output
+
+[Profile output:analog-stereo-a]
+description = Analog Stereo Output Channel A
+output-mappings = analog-stereo-a
+priority = 60
+skip-probe = yes
+
+[Profile output:analog-stereo-b]
+description = Analog Stereo Output Channel B
+output-mappings = analog-stereo-b
+priority = 50
+skip-probe = yes
+
+[Profile analog-stereo-all]
+description = Analog Stereo Output Channels A & B
+output-mappings = analog-stereo-a analog-stereo-b
+priority = 100
+skip-probe = yes
diff --git a/src/modules/alsa/mixer/profile-sets/native-instruments-traktor-audio6.conf b/src/modules/alsa/mixer/profile-sets/native-instruments-traktor-audio6.conf
new file mode 100644
index 0000000..a08e9fc
--- /dev/null
+++ b/src/modules/alsa/mixer/profile-sets/native-instruments-traktor-audio6.conf
@@ -0,0 +1,91 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Native Instruments Audio 6 DJ
+;
+; This card has three stereo pairs of input and three stereo pairs of
+; output
+;
+; We knowingly only define a subset of the theoretically possible
+; mapping combinations as profiles here.
+;
+; See default.conf for an explanation on the directives used here.
+
+[General]
+auto-profiles = no
+
+[Mapping analog-stereo-out-main]
+description = Analog Stereo Main
+device-strings = hw:%f,0,0
+channel-map = left,right
+
+[Mapping analog-stereo-out-a]
+description = Analog Stereo Channel A
+device-strings = hw:%f,0,1
+channel-map = left,right
+direction = output
+
+[Mapping analog-stereo-out-b]
+description = Analog Stereo Channel B
+device-strings = hw:%f,0,1
+channel-map = left,right
+direction = output
+
+[Mapping analog-stereo-in-main]
+description = Analog Stereo Main
+device-strings = hw:%f,0,0
+channel-map = left,right
+
+[Mapping analog-stereo-in-a]
+description = Analog Stereo Channel A
+device-strings = hw:%f,0,1
+channel-map = left,right
+direction = input
+
+[Mapping analog-stereo-in-b]
+description = Analog Stereo Channel B
+device-strings = hw:%f,0,1
+channel-map = left,right
+direction = input
+
+
+
+[Profile output:analog-stereo-all+input:analog-stereo-all]
+description = Analog Stereo Duplex Channels A, B (Headphones)
+output-mappings = analog-stereo-out-main analog-stereo-out-a analog-stereo-out-b
+input-mappings = analog-stereo-in-main analog-stereo-in-a analog-stereo-in-b
+priority = 100
+skip-probe = yes
+
+[Profile output:analog-stereo-main+input:analog-stereo-main]
+description = Analog Stereo Duplex Channel Main
+output-mappings = analog-stereo-out-main
+input-mappings = analog-stereo-in-main
+priority = 50
+skip-probe = yes
+
+[Profile output:analog-stereo-a+input:analog-stereo-a]
+description = Analog Stereo Duplex Channel A
+output-mappings = analog-stereo-out-a
+input-mappings = analog-stereo-in-a
+priority = 40
+skip-probe = yes
+
+[Profile output:analog-stereo-b+input:analog-stereo-b]
+description = Analog Stereo Duplex Channel B
+output-mappings = analog-stereo-out-b
+input-mappings = analog-stereo-in-b
+priority = 30
+skip-probe = yes
diff --git a/src/modules/alsa/mixer/profile-sets/native-instruments-traktorkontrol-s4.conf b/src/modules/alsa/mixer/profile-sets/native-instruments-traktorkontrol-s4.conf
new file mode 100644
index 0000000..934965f
--- /dev/null
+++ b/src/modules/alsa/mixer/profile-sets/native-instruments-traktorkontrol-s4.conf
@@ -0,0 +1,80 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Native Instruments Traktor Kontrol S4
+;
+; This controller has two stereo pairs of input (named "Channel C" and
+; "Channel D") and two stereo pairs of output, one "Main Out" and
+; "Headphone Out".
+;
+; See default.conf for an explanation on the directives used here.
+
+[General]
+auto-profiles = no
+
+[Mapping analog-stereo-output-main]
+description = Analog Stereo Main Out
+device-strings = hw:%f,0,0
+channel-map = left,right
+
+[Mapping analog-stereo-output-headphone]
+description = Analog Stereo Headphones Out
+device-strings = hw:%f,0,1
+channel-map = left,right
+direction = output
+
+[Mapping analog-stereo-c-input]
+description = Analog Stereo Channel C
+device-strings = hw:%f,0,1
+channel-map = left,right
+direction = input
+
+[Mapping analog-stereo-d-input]
+description = Analog Stereo Channel D
+device-strings = hw:%f,0,1
+channel-map = left,right
+direction = input
+
+[Profile output:analog-stereo-all+input:analog-stereo-all]
+description = Analog Stereo Duplex
+output-mappings = analog-stereo-output-main analog-stereo-output-headphone
+input-mappings = analog-stereo-c-input analog-stereo-d-input
+priority = 100
+skip-probe = yes
+
+[Profile output:analog-stereo-main]
+description = Analog Stereo Main Output
+output-mappings = analog-stereo-output-main
+priority = 4
+skip-probe = yes
+
+[Profile output:analog-stereo-headphone]
+description = Analog Stereo Output Headphones Out
+output-mappings = analog-stereo-output-headphone
+priority = 3
+skip-probe = yes
+
+[Profile input:analog-stereo-c]
+description = Analog Stereo Input Channel C
+input-mappings = analog-stereo-c-input
+priority = 2
+skip-probe = yes
+
+[Profile input:analog-stereo-d]
+description = Analog Stereo Input Channel D
+input-mappings = analog-stereo-d-input
+priority = 1
+skip-probe = yes
+
diff --git a/src/modules/alsa/mixer/profile-sets/sb-omni-surround-5.1.conf b/src/modules/alsa/mixer/profile-sets/sb-omni-surround-5.1.conf
new file mode 100644
index 0000000..d5d1d65
--- /dev/null
+++ b/src/modules/alsa/mixer/profile-sets/sb-omni-surround-5.1.conf
@@ -0,0 +1,112 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; Creative Sound Blaster Omni Surround 5.1
+;
+; This config supports Linux 4.3-rc1+.
+; By default there are some non-existing (physically) inputs and outputs that
+; are not present in this config.
+; Also in addition to natively supported modes (such as stereo, 5.1 and stereo
+; S/PDIF) following useful output modes are added: 2.1, 4.0, 4.1 and 5.0.
+;
+; NOTE: in 2.1 and 4.1 physical LFE output will be different than in 5.1 mode.
+;
+; See default.conf for an explanation on the directives used here.
+
+[General]
+auto-profiles = no
+
+[Mapping analog-stereo-input]
+device-strings = hw:%f
+channel-map = left,right
+paths-input = analog-input-mic analog-input-linein
+direction = input
+
+[Mapping analog-stereo-output]
+device-strings = front:%f
+channel-map = left,right
+paths-output = analog-output
+direction = output
+
+[Mapping analog-surround-21]
+device-strings = surround51:%f
+channel-map = front-left,front-right,aux1,aux2,aux3,lfe
+paths-output = analog-output
+direction = output
+
+[Mapping analog-surround-40]
+device-strings = surround51:%f
+channel-map = front-left,front-right,rear-left,rear-right
+paths-output = analog-output
+direction = output
+
+[Mapping analog-surround-41]
+device-strings = surround51:%f
+channel-map = front-left,front-right,rear-left,rear-right,aux1,lfe
+paths-output = analog-output
+direction = output
+
+[Mapping analog-surround-50]
+device-strings = surround51:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center
+paths-output = analog-output
+direction = output
+
+[Mapping analog-surround-51]
+device-strings = surround51:%f
+channel-map = front-left,front-right,rear-left,rear-right,front-center,lfe
+paths-output = analog-output
+direction = output
+
+[Mapping iec958-stereo]
+device-strings = iec958:%f
+channel-map = left,right
+paths-output = iec958-stereo-output
+direction = output
+
+[Profile output:analog-stereo-output+input:analog-stereo-input]
+output-mappings = analog-stereo-output
+input-mappings = analog-stereo-input
+priority = 7
+
+[Profile output:analog-surround-21+input:analog-stereo-input]
+output-mappings = analog-surround-21
+input-mappings = analog-stereo-input
+priority = 6
+
+[Profile output:analog-surround-40+input:analog-stereo-input]
+output-mappings = analog-surround-40
+input-mappings = analog-stereo-input
+priority = 5
+
+[Profile output:analog-surround-41+input:analog-stereo-input]
+output-mappings = analog-surround-41
+input-mappings = analog-stereo-input
+priority = 4
+
+[Profile output:analog-surround-50+input:analog-stereo-input]
+output-mappings = analog-surround-50
+input-mappings = analog-stereo-input
+priority = 3
+
+[Profile output:analog-surround-51+input:analog-stereo-input]
+output-mappings = analog-surround-51
+input-mappings = analog-stereo-input
+priority = 2
+
+[Profile output:iec958-stereo+input:analog-stereo-input]
+output-mappings = iec958-stereo
+input-mappings = analog-stereo-input
+priority = 1
diff --git a/src/modules/alsa/mixer/profile-sets/steelseries-arctis-common-usb-audio.conf b/src/modules/alsa/mixer/profile-sets/steelseries-arctis-common-usb-audio.conf
new file mode 100644
index 0000000..0c58917
--- /dev/null
+++ b/src/modules/alsa/mixer/profile-sets/steelseries-arctis-common-usb-audio.conf
@@ -0,0 +1,23 @@
+[General]
+auto-profiles = yes
+
+[Mapping analog-chat]
+description-key = gaming-headset-chat
+device-strings = hw:%f,0,0
+channel-map = left,right
+paths-input = analog-input-mic
+paths-output = steelseries-arctis-output-chat-common
+intended-roles = phone
+
+[Mapping analog-game]
+description-key = gaming-headset-game
+device-strings = hw:%f,1,0
+channel-map = left,right
+paths-output = steelseries-arctis-output-game-common
+direction = output
+
+[Profile output:analog-chat+output:analog-game+input:analog-chat]
+output-mappings = analog-chat analog-game
+input-mappings = analog-chat
+priority = 5100
+skip-probe = yes
diff --git a/src/modules/alsa/mixer/profile-sets/usb-gaming-headset.conf b/src/modules/alsa/mixer/profile-sets/usb-gaming-headset.conf
new file mode 100644
index 0000000..adda54d
--- /dev/null
+++ b/src/modules/alsa/mixer/profile-sets/usb-gaming-headset.conf
@@ -0,0 +1,64 @@
+# This file is part of PulseAudio.
+#
+# PulseAudio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation; either version 2.1 of the
+# License, or (at your option) any later version.
+#
+# PulseAudio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+
+; USB gaming headset.
+; These headsets usually have two output devices. The first one is meant
+; for voice audio, and the second one is meant for everything else.
+; The purpose of this unusual design is to provide separate volume
+; controls for voice and other audio, which can be useful in gaming.
+;
+; Works with:
+; Steelseries Arctis 7
+; Steelseries Arctis Pro Wireless.
+; Lucidsound LS31
+; Astro A50
+;
+; See default.conf for an explanation on the directives used here.
+
+[General]
+auto-profiles = yes
+
+[Mapping mono-chat]
+description-key = gaming-headset-chat
+device-strings = hw:%f,0,0
+channel-map = mono
+paths-output = usb-gaming-headset-output-mono
+paths-input = usb-gaming-headset-input
+intended-roles = phone
+
+[Mapping stereo-chat]
+description-key = gaming-headset-chat
+device-strings = hw:%f,0,0
+channel-map = left,right
+paths-output = usb-gaming-headset-output-stereo
+paths-input = usb-gaming-headset-input
+intended-roles = phone
+
+[Mapping stereo-game]
+description-key = gaming-headset-game
+device-strings = hw:%f,1,0
+channel-map = left,right
+paths-output = usb-gaming-headset-output-stereo
+direction = output
+
+[Profile output:mono-chat+output:stereo-game+input:mono-chat]
+output-mappings = mono-chat stereo-game
+input-mappings = mono-chat
+priority = 5100
+
+[Profile output:stereo-game+output:stereo-chat+input:mono-chat]
+output-mappings = stereo-game stereo-chat
+input-mappings = mono-chat
+priority = 5100
diff --git a/src/modules/alsa/module-alsa-card.c b/src/modules/alsa/module-alsa-card.c
new file mode 100644
index 0000000..08e655e
--- /dev/null
+++ b/src/modules/alsa/module-alsa-card.c
@@ -0,0 +1,1115 @@
+/***
+ This file is part of PulseAudio.
+
+ Copyright 2009 Lennart Poettering
+
+ PulseAudio is free software; you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License,
+ or (at your option) any later version.
+
+ PulseAudio is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+***/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <pulse/xmalloc.h>
+
+#include <pulsecore/core-util.h>
+#include <pulsecore/i18n.h>
+#include <pulsecore/modargs.h>
+#include <pulsecore/queue.h>
+
+#include <modules/reserve-wrap.h>
+
+#ifdef HAVE_UDEV
+#include <modules/udev-util.h>
+#endif
+
+#include "alsa-util.h"
+#include "alsa-ucm.h"
+#include "alsa-sink.h"
+#include "alsa-source.h"
+
+PA_MODULE_AUTHOR("Lennart Poettering");
+PA_MODULE_DESCRIPTION("ALSA Card");
+PA_MODULE_VERSION(PACKAGE_VERSION);
+PA_MODULE_LOAD_ONCE(false);
+PA_MODULE_USAGE(
+ "name=<name for the card/sink/source, to be prefixed> "
+ "card_name=<name for the card> "
+ "card_properties=<properties for the card> "
+ "sink_name=<name for the sink> "
+ "sink_properties=<properties for the sink> "
+ "source_name=<name for the source> "
+ "source_properties=<properties for the source> "
+ "namereg_fail=<when false attempt to synthesise new names if they are already taken> "
+ "device_id=<ALSA card index> "
+ "format=<sample format> "
+ "rate=<sample rate> "
+ "fragments=<number of fragments> "
+ "fragment_size=<fragment size> "
+ "mmap=<enable memory mapping?> "
+ "tsched=<enable system timer based scheduling mode?> "
+ "tsched_buffer_size=<buffer size when using timer based scheduling> "
+ "tsched_buffer_watermark=<lower fill watermark> "
+ "profile=<profile name> "
+ "fixed_latency_range=<disable latency range changes on underrun?> "
+ "ignore_dB=<ignore dB information from the device?> "
+ "deferred_volume=<Synchronize software and hardware volume changes to avoid momentary jumps?> "
+ "profile_set=<profile set configuration file> "
+ "paths_dir=<directory containing the path configuration files> "
+ "use_ucm=<load use case manager> "
+ "avoid_resampling=<use stream original sample rate if possible?> "
+ "control=<name of mixer control> "
+);
+
+static const char* const valid_modargs[] = {
+ "name",
+ "card_name",
+ "card_properties",
+ "sink_name",
+ "sink_properties",
+ "source_name",
+ "source_properties",
+ "namereg_fail",
+ "device_id",
+ "format",
+ "rate",
+ "fragments",
+ "fragment_size",
+ "mmap",
+ "tsched",
+ "tsched_buffer_size",
+ "tsched_buffer_watermark",
+ "fixed_latency_range",
+ "profile",
+ "ignore_dB",
+ "deferred_volume",
+ "profile_set",
+ "paths_dir",
+ "use_ucm",
+ "avoid_resampling",
+ "control",
+ NULL
+};
+
+#define DEFAULT_DEVICE_ID "0"
+
+struct userdata {
+ pa_core *core;
+ pa_module *module;
+
+ char *device_id;
+ int alsa_card_index;
+
+ pa_hashmap *mixers;
+ pa_hashmap *jacks;
+
+ pa_card *card;
+
+ pa_modargs *modargs;
+
+ pa_alsa_profile_set *profile_set;
+
+ /* ucm stuffs */
+ bool use_ucm;
+ pa_alsa_ucm_config ucm;
+
+};
+
+struct profile_data {
+ pa_alsa_profile *profile;
+};
+
+static void add_profiles(struct userdata *u, pa_hashmap *h, pa_hashmap *ports) {
+ pa_alsa_profile *ap;
+ void *state;
+
+ pa_assert(u);
+ pa_assert(h);
+
+ PA_HASHMAP_FOREACH(ap, u->profile_set->profiles, state) {
+ struct profile_data *d;
+ pa_card_profile *cp;
+ pa_alsa_mapping *m;
+ uint32_t idx;
+
+ cp = pa_card_profile_new(ap->name, ap->description, sizeof(struct profile_data));
+ cp->priority = ap->priority ? ap->priority : 1;
+ cp->input_name = pa_xstrdup(ap->input_name);
+ cp->output_name = pa_xstrdup(ap->output_name);
+
+ if (ap->output_mappings) {
+ cp->n_sinks = pa_idxset_size(ap->output_mappings);
+
+ PA_IDXSET_FOREACH(m, ap->output_mappings, idx) {
+ if (u->use_ucm)
+ pa_alsa_ucm_add_ports_combination(NULL, &m->ucm_context, true, ports, cp, u->core);
+ else
+ pa_alsa_path_set_add_ports(m->output_path_set, cp, ports, NULL, u->core);
+ if (m->channel_map.channels > cp->max_sink_channels)
+ cp->max_sink_channels = m->channel_map.channels;
+ }
+ }
+
+ if (ap->input_mappings) {
+ cp->n_sources = pa_idxset_size(ap->input_mappings);
+
+ PA_IDXSET_FOREACH(m, ap->input_mappings, idx) {
+ if (u->use_ucm)
+ pa_alsa_ucm_add_ports_combination(NULL, &m->ucm_context, false, ports, cp, u->core);
+ else
+ pa_alsa_path_set_add_ports(m->input_path_set, cp, ports, NULL, u->core);
+ if (m->channel_map.channels > cp->max_source_channels)
+ cp->max_source_channels = m->channel_map.channels;
+ }
+ }
+
+ d = PA_CARD_PROFILE_DATA(cp);
+ d->profile = ap;
+
+ pa_hashmap_put(h, cp->name, cp);
+ }
+}
+
+static void add_disabled_profile(pa_hashmap *profiles) {
+ pa_card_profile *p;
+ struct profile_data *d;
+
+ p = pa_card_profile_new("off", _("Off"), sizeof(struct profile_data));
+
+ d = PA_CARD_PROFILE_DATA(p);
+ d->profile = NULL;
+
+ pa_hashmap_put(profiles, p->name, p);
+}
+
+static int card_set_profile(pa_card *c, pa_card_profile *new_profile) {
+ struct userdata *u;
+ struct profile_data *nd, *od;
+ uint32_t idx;
+ pa_alsa_mapping *am;
+ pa_queue *sink_inputs = NULL, *source_outputs = NULL;
+ int ret = 0;
+
+ pa_assert(c);
+ pa_assert(new_profile);
+ pa_assert_se(u = c->userdata);
+
+ nd = PA_CARD_PROFILE_DATA(new_profile);
+ od = PA_CARD_PROFILE_DATA(c->active_profile);
+
+ if (od->profile && od->profile->output_mappings)
+ PA_IDXSET_FOREACH(am, od->profile->output_mappings, idx) {
+ if (!am->sink)
+ continue;
+
+ if (nd->profile &&
+ nd->profile->output_mappings &&
+ pa_idxset_get_by_data(nd->profile->output_mappings, am, NULL))
+ continue;
+
+ sink_inputs = pa_sink_move_all_start(am->sink, sink_inputs);
+ pa_alsa_sink_free(am->sink);
+ am->sink = NULL;
+ }
+
+ if (od->profile && od->profile->input_mappings)
+ PA_IDXSET_FOREACH(am, od->profile->input_mappings, idx) {
+ if (!am->source)
+ continue;
+
+ if (nd->profile &&
+ nd->profile->input_mappings &&
+ pa_idxset_get_by_data(nd->profile->input_mappings, am, NULL))
+ continue;
+
+ source_outputs = pa_source_move_all_start(am->source, source_outputs);
+ pa_alsa_source_free(am->source);
+ am->source = NULL;
+ }
+
+ /* if UCM is available for this card then update the verb */
+ if (u->use_ucm) {
+ if (pa_alsa_ucm_set_profile(&u->ucm, c, nd->profile ? nd->profile->name : NULL,
+ od->profile ? od->profile->name : NULL) < 0) {
+ ret = -1;
+ goto finish;
+ }
+ }
+
+ if (nd->profile && nd->profile->output_mappings)
+ PA_IDXSET_FOREACH(am, nd->profile->output_mappings, idx) {
+
+ if (!am->sink)
+ am->sink = pa_alsa_sink_new(c->module, u->modargs, __FILE__, c, am);
+
+ if (sink_inputs && am->sink) {
+ pa_sink_move_all_finish(am->sink, sink_inputs, false);
+ sink_inputs = NULL;
+ }
+ }
+
+ if (nd->profile && nd->profile->input_mappings)
+ PA_IDXSET_FOREACH(am, nd->profile->input_mappings, idx) {
+
+ if (!am->source)
+ am->source = pa_alsa_source_new(c->module, u->modargs, __FILE__, c, am);
+
+ if (source_outputs && am->source) {
+ pa_source_move_all_finish(am->source, source_outputs, false);
+ source_outputs = NULL;
+ }
+ }
+
+finish:
+ if (sink_inputs)
+ pa_sink_move_all_fail(sink_inputs);
+
+ if (source_outputs)
+ pa_source_move_all_fail(source_outputs);
+
+ return ret;
+}
+
+static void init_profile(struct userdata *u) {
+ uint32_t idx;
+ pa_alsa_mapping *am;
+ struct profile_data *d;
+ pa_alsa_ucm_config *ucm = &u->ucm;
+
+ pa_assert(u);
+
+ d = PA_CARD_PROFILE_DATA(u->card->active_profile);
+
+ if (d->profile && u->use_ucm) {
+ /* Set initial verb */
+ if (pa_alsa_ucm_set_profile(ucm, u->card, d->profile->name, NULL) < 0) {
+ pa_log("Failed to set ucm profile %s", d->profile->name);
+ return;
+ }
+ }
+
+ if (d->profile && d->profile->output_mappings)
+ PA_IDXSET_FOREACH(am, d->profile->output_mappings, idx)
+ am->sink = pa_alsa_sink_new(u->module, u->modargs, __FILE__, u->card, am);
+
+ if (d->profile && d->profile->input_mappings)
+ PA_IDXSET_FOREACH(am, d->profile->input_mappings, idx)
+ am->source = pa_alsa_source_new(u->module, u->modargs, __FILE__, u->card, am);
+}
+
+static pa_available_t calc_port_state(pa_device_port *p, struct userdata *u) {
+ void *state;
+ pa_alsa_jack *jack;
+ pa_available_t pa = PA_AVAILABLE_UNKNOWN;
+ pa_device_port *port;
+
+ PA_HASHMAP_FOREACH(jack, u->jacks, state) {
+ pa_available_t cpa;
+
+ if (u->use_ucm)
+ port = pa_hashmap_get(u->card->ports, jack->name);
+ else {
+ if (jack->path)
+ port = jack->path->port;
+ else
+ continue;
+ }
+
+ if (p != port)
+ continue;
+
+ cpa = jack->plugged_in ? jack->state_plugged : jack->state_unplugged;
+
+ if (cpa == PA_AVAILABLE_NO) {
+ /* If a plugged-in jack causes the availability to go to NO, it
+ * should override all other availability information (like a
+ * blacklist) so set and bail */
+ if (jack->plugged_in) {
+ pa = cpa;
+ break;
+ }
+
+ /* If the current availablility is unknown go the more precise no,
+ * but otherwise don't change state */
+ if (pa == PA_AVAILABLE_UNKNOWN)
+ pa = cpa;
+ } else if (cpa == PA_AVAILABLE_YES) {
+ /* Output is available through at least one jack, so go to that
+ * level of availability. We still need to continue iterating through
+ * the jacks in case a jack is plugged in that forces the state to no
+ */
+ pa = cpa;
+ }
+ }
+ return pa;
+}
+
+struct temp_port_avail {
+ pa_device_port *port;
+ pa_available_t avail;
+};
+
+static int report_jack_state(snd_mixer_elem_t *melem, unsigned int mask) {
+ struct userdata *u = snd_mixer_elem_get_callback_private(melem);
+ snd_hctl_elem_t *elem = snd_mixer_elem_get_private(melem);
+ snd_ctl_elem_value_t *elem_value;
+ bool plugged_in;
+ void *state;
+ pa_alsa_jack *jack;
+ struct temp_port_avail *tp, *tports;
+ pa_card_profile *profile;
+ pa_available_t active_available = PA_AVAILABLE_UNKNOWN;
+
+ pa_assert(u);
+
+ /* Changing the jack state may cause a port change, and a port change will
+ * make the sink or source change the mixer settings. If there are multiple
+ * users having pulseaudio running, the mixer changes done by inactive
+ * users may mess up the volume settings for the active users, because when
+ * the inactive users change the mixer settings, those changes are picked
+ * up by the active user's pulseaudio instance and the changes are
+ * interpreted as if the active user changed the settings manually e.g.
+ * with alsamixer. Even single-user systems suffer from this, because gdm
+ * runs its own pulseaudio instance.
+ *
+ * We rerun this function when being unsuspended to catch up on jack state
+ * changes */
+ if (u->card->suspend_cause & PA_SUSPEND_SESSION)
+ return 0;
+
+ if (mask == SND_CTL_EVENT_MASK_REMOVE)
+ return 0;
+
+ snd_ctl_elem_value_alloca(&elem_value);
+ if (snd_hctl_elem_read(elem, elem_value) < 0) {
+ pa_log_warn("Failed to read jack detection from '%s'", pa_strnull(snd_hctl_elem_get_name(elem)));
+ return 0;
+ }
+
+ plugged_in = !!snd_ctl_elem_value_get_boolean(elem_value, 0);
+
+ pa_log_debug("Jack '%s' is now %s", pa_strnull(snd_hctl_elem_get_name(elem)), plugged_in ? "plugged in" : "unplugged");
+
+ tports = tp = pa_xnew0(struct temp_port_avail, pa_hashmap_size(u->jacks)+1);
+
+ PA_HASHMAP_FOREACH(jack, u->jacks, state)
+ if (jack->melem == melem) {
+ pa_alsa_jack_set_plugged_in(jack, plugged_in);
+
+ if (u->use_ucm) {
+ /* When using UCM, pa_alsa_jack_set_plugged_in() maps the jack
+ * state to port availability. */
+ continue;
+ }
+
+ /* When not using UCM, we have to do the jack state -> port
+ * availability mapping ourselves. */
+ pa_assert_se(tp->port = jack->path->port);
+ tp->avail = calc_port_state(tp->port, u);
+ tp++;
+ }
+
+ /* Report available ports before unavailable ones: in case port 1 becomes available when port 2 becomes unavailable,
+ this prevents an unnecessary switch port 1 -> port 3 -> port 2 */
+
+ for (tp = tports; tp->port; tp++)
+ if (tp->avail != PA_AVAILABLE_NO)
+ pa_device_port_set_available(tp->port, tp->avail);
+ for (tp = tports; tp->port; tp++)
+ if (tp->avail == PA_AVAILABLE_NO)
+ pa_device_port_set_available(tp->port, tp->avail);
+
+ for (tp = tports; tp->port; tp++) {
+ pa_alsa_port_data *data;
+ pa_sink *sink;
+ uint32_t idx;
+
+ data = PA_DEVICE_PORT_DATA(tp->port);
+
+ if (!data->suspend_when_unavailable)
+ continue;
+
+ PA_IDXSET_FOREACH(sink, u->core->sinks, idx) {
+ if (sink->active_port == tp->port)
+ pa_sink_suspend(sink, tp->avail == PA_AVAILABLE_NO, PA_SUSPEND_UNAVAILABLE);
+ }
+ }
+
+ /* Update profile availabilities. Ideally we would mark all profiles
+ * unavailable that contain unavailable devices. We can't currently do that
+ * in all cases, because if there are multiple sinks in a profile, and the
+ * profile contains a mix of available and unavailable ports, we don't know
+ * how the ports are distributed between the different sinks. It's possible
+ * that some sinks contain only unavailable ports, in which case we should
+ * mark the profile as unavailable, but it's also possible that all sinks
+ * contain at least one available port, in which case we should mark the
+ * profile as available. Until the data structures are improved so that we
+ * can distinguish between these two cases, we mark the problematic cases
+ * as available (well, "unknown" to be precise, but there's little
+ * practical difference).
+ *
+ * When all output ports are unavailable, we know that all sinks are
+ * unavailable, and therefore the profile is marked unavailable as well.
+ * The same applies to input ports as well, of course.
+ *
+ * If there are no output ports at all, but the profile contains at least
+ * one sink, then the output is considered to be available. */
+ if (u->card->active_profile)
+ active_available = u->card->active_profile->available;
+ PA_HASHMAP_FOREACH(profile, u->card->profiles, state) {
+ pa_device_port *port;
+ void *state2;
+ bool has_input_port = false;
+ bool has_output_port = false;
+ bool found_available_input_port = false;
+ bool found_available_output_port = false;
+ pa_available_t available = PA_AVAILABLE_UNKNOWN;
+
+ PA_HASHMAP_FOREACH(port, u->card->ports, state2) {
+ if (!pa_hashmap_get(port->profiles, profile->name))
+ continue;
+
+ if (port->direction == PA_DIRECTION_INPUT) {
+ has_input_port = true;
+
+ if (port->available != PA_AVAILABLE_NO)
+ found_available_input_port = true;
+ } else {
+ has_output_port = true;
+
+ if (port->available != PA_AVAILABLE_NO)
+ found_available_output_port = true;
+ }
+ }
+
+ if ((has_input_port && !found_available_input_port) || (has_output_port && !found_available_output_port))
+ available = PA_AVAILABLE_NO;
+
+ /* We want to update the active profile's status last, so logic that
+ * may change the active profile based on profile availability status
+ * has an updated view of all profiles' availabilities. */
+ if (profile == u->card->active_profile)
+ active_available = available;
+ else
+ pa_card_profile_set_available(profile, available);
+ }
+
+ if (u->card->active_profile)
+ pa_card_profile_set_available(u->card->active_profile, active_available);
+
+ pa_xfree(tports);
+ return 0;
+}
+
+static pa_device_port* find_port_with_eld_device(struct userdata *u, int device) {
+ void *state;
+ pa_device_port *p;
+
+ if (u->use_ucm) {
+ PA_HASHMAP_FOREACH(p, u->card->ports, state) {
+ pa_alsa_ucm_port_data *data = PA_DEVICE_PORT_DATA(p);
+ pa_assert(data->eld_mixer_device_name);
+ if (device == data->eld_device)
+ return p;
+ }
+ } else {
+ PA_HASHMAP_FOREACH(p, u->card->ports, state) {
+ pa_alsa_port_data *data = PA_DEVICE_PORT_DATA(p);
+ pa_assert(data->path);
+ if (device == data->path->eld_device)
+ return p;
+ }
+ }
+ return NULL;
+}
+
+static int hdmi_eld_changed(snd_mixer_elem_t *melem, unsigned int mask) {
+ struct userdata *u = snd_mixer_elem_get_callback_private(melem);
+ snd_hctl_elem_t *elem = snd_mixer_elem_get_private(melem);
+ int device = snd_hctl_elem_get_device(elem);
+ const char *old_monitor_name;
+ pa_device_port *p;
+ pa_hdmi_eld eld;
+ bool changed = false;
+
+ if (mask == SND_CTL_EVENT_MASK_REMOVE)
+ return 0;
+
+ p = find_port_with_eld_device(u, device);
+ if (p == NULL) {
+ pa_log_error("Invalid device changed in ALSA: %d", device);
+ return 0;
+ }
+
+ if (pa_alsa_get_hdmi_eld(elem, &eld) < 0)
+ memset(&eld, 0, sizeof(eld));
+
+ old_monitor_name = pa_proplist_gets(p->proplist, PA_PROP_DEVICE_PRODUCT_NAME);
+ if (eld.monitor_name[0] == '\0') {
+ changed |= old_monitor_name != NULL;
+ pa_proplist_unset(p->proplist, PA_PROP_DEVICE_PRODUCT_NAME);
+ } else {
+ changed |= (old_monitor_name == NULL) || (strcmp(old_monitor_name, eld.monitor_name) != 0);
+ pa_proplist_sets(p->proplist, PA_PROP_DEVICE_PRODUCT_NAME, eld.monitor_name);
+ }
+
+ if (changed && mask != 0)
+ pa_subscription_post(u->core, PA_SUBSCRIPTION_EVENT_CARD|PA_SUBSCRIPTION_EVENT_CHANGE, u->card->index);
+
+ return 0;
+}
+
+static void init_eld_ctls(struct userdata *u) {
+ void *state;
+ pa_device_port *port;
+
+ /* The code in this function expects ports to have a pa_alsa_port_data
+ * struct as their data, but in UCM mode ports don't have any data. Hence,
+ * the ELD controls can't currently be used in UCM mode. */
+ PA_HASHMAP_FOREACH(port, u->card->ports, state) {
+ snd_mixer_t *mixer_handle;
+ snd_mixer_elem_t* melem;
+ int device;
+
+ if (u->use_ucm) {
+ pa_alsa_ucm_port_data *data = PA_DEVICE_PORT_DATA(port);
+ device = data->eld_device;
+ if (device < 0 || !data->eld_mixer_device_name)
+ continue;
+
+ mixer_handle = pa_alsa_open_mixer_by_name(u->mixers, data->eld_mixer_device_name, true);
+ } else {
+ pa_alsa_port_data *data = PA_DEVICE_PORT_DATA(port);
+
+ pa_assert(data->path);
+
+ device = data->path->eld_device;
+ if (device < 0)
+ continue;
+
+ mixer_handle = pa_alsa_open_mixer(u->mixers, u->alsa_card_index, true);
+ }
+
+ if (!mixer_handle)
+ continue;
+
+ melem = pa_alsa_mixer_find_pcm(mixer_handle, "ELD", device);
+ if (melem) {
+ pa_alsa_mixer_set_fdlist(u->mixers, mixer_handle, u->core->mainloop);
+ snd_mixer_elem_set_callback(melem, hdmi_eld_changed);
+ snd_mixer_elem_set_callback_private(melem, u);
+ hdmi_eld_changed(melem, 0);
+ pa_log_info("ELD device found for port %s (%d).", port->name, device);
+ }
+ else
+ pa_log_debug("No ELD device found for port %s (%d).", port->name, device);
+ }
+}
+
+static void init_jacks(struct userdata *u) {
+ void *state;
+ pa_alsa_path* path;
+ pa_alsa_jack* jack;
+ char buf[64];
+
+ u->jacks = pa_hashmap_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
+
+ if (u->use_ucm) {
+ PA_LLIST_FOREACH(jack, u->ucm.jacks)
+ if (jack->has_control)
+ pa_hashmap_put(u->jacks, jack, jack);
+ } else {
+ /* See if we have any jacks */
+ if (u->profile_set->output_paths)
+ PA_HASHMAP_FOREACH(path, u->profile_set->output_paths, state)
+ PA_LLIST_FOREACH(jack, path->jacks)
+ if (jack->has_control)
+ pa_hashmap_put(u->jacks, jack, jack);
+
+ if (u->profile_set->input_paths)
+ PA_HASHMAP_FOREACH(path, u->profile_set->input_paths, state)
+ PA_LLIST_FOREACH(jack, path->jacks)
+ if (jack->has_control)
+ pa_hashmap_put(u->jacks, jack, jack);
+ }
+
+ pa_log_debug("Found %d jacks.", pa_hashmap_size(u->jacks));
+
+ if (pa_hashmap_size(u->jacks) == 0)
+ return;
+
+ PA_HASHMAP_FOREACH(jack, u->jacks, state) {
+ if (!jack->mixer_device_name) {
+ jack->mixer_handle = pa_alsa_open_mixer(u->mixers, u->alsa_card_index, false);
+ if (!jack->mixer_handle) {
+ pa_log("Failed to open mixer for card %d for jack detection", u->alsa_card_index);
+ continue;
+ }
+ } else {
+ jack->mixer_handle = pa_alsa_open_mixer_by_name(u->mixers, jack->mixer_device_name, false);
+ if (!jack->mixer_handle) {
+ pa_log("Failed to open mixer '%s' for jack detection", jack->mixer_device_name);
+ continue;
+ }
+ }
+ pa_alsa_mixer_set_fdlist(u->mixers, jack->mixer_handle, u->core->mainloop);
+ jack->melem = pa_alsa_mixer_find_card(jack->mixer_handle, &jack->alsa_id, 0);
+ if (!jack->melem) {
+ pa_alsa_mixer_id_to_string(buf, sizeof(buf), &jack->alsa_id);
+ pa_log_warn("Jack %s seems to have disappeared.", buf);
+ pa_alsa_jack_set_has_control(jack, false);
+ continue;
+ }
+ snd_mixer_elem_set_callback(jack->melem, report_jack_state);
+ snd_mixer_elem_set_callback_private(jack->melem, u);
+ report_jack_state(jack->melem, 0);
+ }
+}
+
+static void prune_singleton_availability_groups(pa_hashmap *ports) {
+ pa_device_port *p;
+ pa_hashmap *group_counts;
+ void *state, *count;
+ const char *group;
+
+ /* Collect groups and erase those that don't have more than 1 path */
+ group_counts = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
+
+ PA_HASHMAP_FOREACH(p, ports, state) {
+ if (p->availability_group) {
+ count = pa_hashmap_get(group_counts, p->availability_group);
+ pa_hashmap_remove(group_counts, p->availability_group);
+ pa_hashmap_put(group_counts, p->availability_group, PA_UINT_TO_PTR(PA_PTR_TO_UINT(count) + 1));
+ }
+ }
+
+ /* Now we have an availability_group -> count map, let's drop all groups
+ * that have only one member */
+ PA_HASHMAP_FOREACH_KV(group, count, group_counts, state) {
+ if (count == PA_UINT_TO_PTR(1))
+ pa_hashmap_remove(group_counts, group);
+ }
+
+ PA_HASHMAP_FOREACH(p, ports, state) {
+ if (p->availability_group && !pa_hashmap_get(group_counts, p->availability_group)) {
+ pa_log_debug("Pruned singleton availability group %s from port %s", p->availability_group, p->name);
+
+ pa_xfree(p->availability_group);
+ p->availability_group = NULL;
+ }
+ }
+
+ pa_hashmap_free(group_counts);
+}
+
+static void set_card_name(pa_card_new_data *data, pa_modargs *ma, const char *device_id) {
+ char *t;
+ const char *n;
+
+ pa_assert(data);
+ pa_assert(ma);
+ pa_assert(device_id);
+
+ if ((n = pa_modargs_get_value(ma, "card_name", NULL))) {
+ pa_card_new_data_set_name(data, n);
+ data->namereg_fail = true;
+ return;
+ }
+
+ if ((n = pa_modargs_get_value(ma, "name", NULL)))
+ data->namereg_fail = true;
+ else {
+ n = device_id;
+ data->namereg_fail = false;
+ }
+
+ t = pa_sprintf_malloc("alsa_card.%s", n);
+ pa_card_new_data_set_name(data, t);
+ pa_xfree(t);
+}
+
+static pa_hook_result_t card_suspend_changed(pa_core *c, pa_card *card, struct userdata *u) {
+ void *state;
+ pa_alsa_jack *jack;
+
+ if (card->suspend_cause == 0) {
+ /* We were unsuspended, update jack state in case it changed while we were suspended */
+ PA_HASHMAP_FOREACH(jack, u->jacks, state) {
+ if (jack->melem)
+ report_jack_state(jack->melem, 0);
+ }
+ }
+
+ return PA_HOOK_OK;
+}
+
+static pa_hook_result_t sink_input_put_hook_callback(pa_core *c, pa_sink_input *sink_input, struct userdata *u) {
+ const char *role;
+ pa_sink *sink = sink_input->sink;
+
+ pa_assert(sink);
+
+ role = pa_proplist_gets(sink_input->proplist, PA_PROP_MEDIA_ROLE);
+
+ /* new sink input linked to sink of this card */
+ if (role && sink->card == u->card)
+ pa_alsa_ucm_roled_stream_begin(&u->ucm, role, PA_DIRECTION_OUTPUT);
+
+ return PA_HOOK_OK;
+}
+
+static pa_hook_result_t source_output_put_hook_callback(pa_core *c, pa_source_output *source_output, struct userdata *u) {
+ const char *role;
+ pa_source *source = source_output->source;
+
+ pa_assert(source);
+
+ role = pa_proplist_gets(source_output->proplist, PA_PROP_MEDIA_ROLE);
+
+ /* new source output linked to source of this card */
+ if (role && source->card == u->card)
+ pa_alsa_ucm_roled_stream_begin(&u->ucm, role, PA_DIRECTION_INPUT);
+
+ return PA_HOOK_OK;
+}
+
+static pa_hook_result_t sink_input_unlink_hook_callback(pa_core *c, pa_sink_input *sink_input, struct userdata *u) {
+ const char *role;
+ pa_sink *sink = sink_input->sink;
+
+ pa_assert(sink);
+
+ role = pa_proplist_gets(sink_input->proplist, PA_PROP_MEDIA_ROLE);
+
+ /* new sink input unlinked from sink of this card */
+ if (role && sink->card == u->card)
+ pa_alsa_ucm_roled_stream_end(&u->ucm, role, PA_DIRECTION_OUTPUT);
+
+ return PA_HOOK_OK;
+}
+
+static pa_hook_result_t source_output_unlink_hook_callback(pa_core *c, pa_source_output *source_output, struct userdata *u) {
+ const char *role;
+ pa_source *source = source_output->source;
+
+ pa_assert(source);
+
+ role = pa_proplist_gets(source_output->proplist, PA_PROP_MEDIA_ROLE);
+
+ /* new source output unlinked from source of this card */
+ if (role && source->card == u->card)
+ pa_alsa_ucm_roled_stream_end(&u->ucm, role, PA_DIRECTION_INPUT);
+
+ return PA_HOOK_OK;
+}
+
+int pa__init(pa_module *m) {
+ pa_card_new_data data;
+ bool ignore_dB = false;
+ struct userdata *u;
+ pa_reserve_wrapper *reserve = NULL;
+ const char *description;
+ const char *profile_str = NULL;
+ char *fn = NULL;
+ bool namereg_fail = false;
+ int err = -PA_MODULE_ERR_UNSPECIFIED, rval;
+
+ pa_alsa_refcnt_inc();
+
+ pa_assert(m);
+
+ m->userdata = u = pa_xnew0(struct userdata, 1);
+ u->core = m->core;
+ u->module = m;
+ u->use_ucm = true;
+ u->ucm.core = m->core;
+
+ u->mixers = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func,
+ pa_xfree, (pa_free_cb_t) pa_alsa_mixer_free);
+ u->ucm.mixers = u->mixers; /* alias */
+
+ if (!(u->modargs = pa_modargs_new(m->argument, valid_modargs))) {
+ pa_log("Failed to parse module arguments.");
+ goto fail;
+ }
+
+ u->device_id = pa_xstrdup(pa_modargs_get_value(u->modargs, "device_id", DEFAULT_DEVICE_ID));
+
+ if ((u->alsa_card_index = snd_card_get_index(u->device_id)) < 0) {
+ pa_log("Card '%s' doesn't exist: %s", u->device_id, pa_alsa_strerror(u->alsa_card_index));
+ goto fail;
+ }
+
+ if (pa_modargs_get_value_boolean(u->modargs, "ignore_dB", &ignore_dB) < 0) {
+ pa_log("Failed to parse ignore_dB argument.");
+ goto fail;
+ }
+
+ if (!pa_in_system_mode()) {
+ char *rname;
+
+ if ((rname = pa_alsa_get_reserve_name(u->device_id))) {
+ reserve = pa_reserve_wrapper_get(m->core, rname);
+ pa_xfree(rname);
+
+ if (!reserve)
+ goto fail;
+ }
+ }
+
+ if (pa_modargs_get_value_boolean(u->modargs, "use_ucm", &u->use_ucm) < 0) {
+ pa_log("Failed to parse use_ucm argument.");
+ goto fail;
+ }
+
+ /* Force ALSA to reread its configuration. This matters if our device
+ * was hot-plugged after ALSA has already read its configuration - see
+ * https://bugs.freedesktop.org/show_bug.cgi?id=54029
+ */
+
+ snd_config_update_free_global();
+
+ rval = u->use_ucm ? pa_alsa_ucm_query_profiles(&u->ucm, u->alsa_card_index) : -1;
+ if (rval == -PA_ALSA_ERR_UCM_LINKED) {
+ err = -PA_MODULE_ERR_SKIP;
+ goto fail;
+ }
+ if (rval == 0) {
+ pa_log_info("Found UCM profiles");
+
+ u->profile_set = pa_alsa_ucm_add_profile_set(&u->ucm, &u->core->default_channel_map);
+
+ /* hook start of sink input/source output to enable modifiers */
+ /* A little bit later than module-role-cork */
+ pa_module_hook_connect(m, &m->core->hooks[PA_CORE_HOOK_SINK_INPUT_PUT], PA_HOOK_LATE+10,
+ (pa_hook_cb_t) sink_input_put_hook_callback, u);
+ pa_module_hook_connect(m, &m->core->hooks[PA_CORE_HOOK_SOURCE_OUTPUT_PUT], PA_HOOK_LATE+10,
+ (pa_hook_cb_t) source_output_put_hook_callback, u);
+
+ /* hook end of sink input/source output to disable modifiers */
+ /* A little bit later than module-role-cork */
+ pa_module_hook_connect(m, &m->core->hooks[PA_CORE_HOOK_SINK_INPUT_UNLINK], PA_HOOK_LATE+10,
+ (pa_hook_cb_t) sink_input_unlink_hook_callback, u);
+ pa_module_hook_connect(m, &m->core->hooks[PA_CORE_HOOK_SOURCE_OUTPUT_UNLINK], PA_HOOK_LATE+10,
+ (pa_hook_cb_t) source_output_unlink_hook_callback, u);
+ }
+ else {
+ u->use_ucm = false;
+#ifdef HAVE_UDEV
+ fn = pa_udev_get_property(u->alsa_card_index, "PULSE_PROFILE_SET");
+#endif
+
+ if (pa_modargs_get_value(u->modargs, "profile_set", NULL)) {
+ pa_xfree(fn);
+ fn = pa_xstrdup(pa_modargs_get_value(u->modargs, "profile_set", NULL));
+ }
+
+ u->profile_set = pa_alsa_profile_set_new(fn, &u->core->default_channel_map);
+ pa_xfree(fn);
+ }
+
+ if (!u->profile_set)
+ goto fail;
+
+ u->profile_set->ignore_dB = ignore_dB;
+
+ pa_alsa_profile_set_probe(u->profile_set, u->mixers, u->device_id, &m->core->default_sample_spec, m->core->default_n_fragments, m->core->default_fragment_size_msec);
+ pa_alsa_profile_set_dump(u->profile_set);
+
+ pa_card_new_data_init(&data);
+ data.driver = __FILE__;
+ data.module = m;
+
+ pa_alsa_init_proplist_card(m->core, data.proplist, u->alsa_card_index);
+
+ pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, u->device_id);
+ pa_alsa_init_description(data.proplist, NULL);
+ set_card_name(&data, u->modargs, u->device_id);
+
+ /* We need to give pa_modargs_get_value_boolean() a pointer to a local
+ * variable instead of using &data.namereg_fail directly, because
+ * data.namereg_fail is a bitfield and taking the address of a bitfield
+ * variable is impossible. */
+ namereg_fail = data.namereg_fail;
+ if (pa_modargs_get_value_boolean(u->modargs, "namereg_fail", &namereg_fail) < 0) {
+ pa_log("Failed to parse namereg_fail argument.");
+ pa_card_new_data_done(&data);
+ goto fail;
+ }
+ data.namereg_fail = namereg_fail;
+
+ if (reserve)
+ if ((description = pa_proplist_gets(data.proplist, PA_PROP_DEVICE_DESCRIPTION)))
+ pa_reserve_wrapper_set_application_device_name(reserve, description);
+
+ add_profiles(u, data.profiles, data.ports);
+
+ if (pa_hashmap_isempty(data.profiles)) {
+ pa_log("Failed to find a working profile.");
+ pa_card_new_data_done(&data);
+ goto fail;
+ }
+
+ add_disabled_profile(data.profiles);
+ prune_singleton_availability_groups(data.ports);
+
+ if (pa_modargs_get_proplist(u->modargs, "card_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
+ pa_log("Invalid properties");
+ pa_card_new_data_done(&data);
+ goto fail;
+ }
+
+ /* The Intel HDMI LPE driver needs some special handling. When the HDMI
+ * cable is not plugged in, trying to play audio doesn't work. Any written
+ * audio is immediately discarded and an underrun is reported, and that
+ * results in an infinite loop of "fill buffer, handle underrun". To work
+ * around this issue, the suspend_when_unavailable flag is used to stop
+ * playback when the HDMI cable is unplugged. */
+ if (!u->use_ucm &&
+ pa_safe_streq(pa_proplist_gets(data.proplist, "alsa.driver_name"), "snd_hdmi_lpe_audio")) {
+ pa_device_port *port;
+ void *state;
+
+ PA_HASHMAP_FOREACH(port, data.ports, state) {
+ pa_alsa_port_data *port_data;
+
+ port_data = PA_DEVICE_PORT_DATA(port);
+ port_data->suspend_when_unavailable = true;
+ }
+ }
+
+ u->card = pa_card_new(m->core, &data);
+ pa_card_new_data_done(&data);
+
+ if (!u->card)
+ goto fail;
+
+ u->card->userdata = u;
+ u->card->set_profile = card_set_profile;
+
+ pa_module_hook_connect(m, &m->core->hooks[PA_CORE_HOOK_CARD_SUSPEND_CHANGED], PA_HOOK_NORMAL,
+ (pa_hook_cb_t) card_suspend_changed, u);
+
+ init_jacks(u);
+
+ pa_card_choose_initial_profile(u->card);
+
+ /* If the "profile" modarg is given, we have to override whatever the usual
+ * policy chose in pa_card_choose_initial_profile(). */
+ profile_str = pa_modargs_get_value(u->modargs, "profile", NULL);
+ if (profile_str) {
+ pa_card_profile *profile;
+
+ profile = pa_hashmap_get(u->card->profiles, profile_str);
+ if (!profile) {
+ pa_log("No such profile: %s", profile_str);
+ goto fail;
+ }
+
+ pa_card_set_profile(u->card, profile, false);
+ }
+
+ pa_card_put(u->card);
+
+ init_profile(u);
+ init_eld_ctls(u);
+
+ /* Remove all probe only mixers */
+ if (u->mixers) {
+ const char *devname;
+ pa_alsa_mixer *pm;
+ void *state;
+ PA_HASHMAP_FOREACH_KV(devname, pm, u->mixers, state)
+ if (pm->used_for_probe_only)
+ pa_hashmap_remove_and_free(u->mixers, devname);
+ }
+
+ if (reserve)
+ pa_reserve_wrapper_unref(reserve);
+
+ if (!pa_hashmap_isempty(u->profile_set->decibel_fixes))
+ pa_log_warn("Card %s uses decibel fixes (i.e. overrides the decibel information for some alsa volume elements). "
+ "Please note that this feature is meant just as a help for figuring out the correct decibel values. "
+ "PulseAudio is not the correct place to maintain the decibel mappings! The fixed decibel values "
+ "should be sent to ALSA developers so that they can fix the driver. If it turns out that this feature "
+ "is abused (i.e. fixes are not pushed to ALSA), the decibel fix feature may be removed in some future "
+ "PulseAudio version.", u->card->name);
+
+ return 0;
+
+fail:
+ if (reserve)
+ pa_reserve_wrapper_unref(reserve);
+
+ pa__done(m);
+
+ return err;
+}
+
+int pa__get_n_used(pa_module *m) {
+ struct userdata *u;
+ int n = 0;
+ uint32_t idx;
+ pa_sink *sink;
+ pa_source *source;
+
+ pa_assert(m);
+ pa_assert_se(u = m->userdata);
+ pa_assert(u->card);
+
+ PA_IDXSET_FOREACH(sink, u->card->sinks, idx)
+ n += pa_sink_linked_by(sink);
+
+ PA_IDXSET_FOREACH(source, u->card->sources, idx)
+ n += pa_source_linked_by(source);
+
+ return n;
+}
+
+void pa__done(pa_module*m) {
+ struct userdata *u;
+
+ pa_assert(m);
+
+ if (!(u = m->userdata))
+ goto finish;
+
+ if (u->mixers)
+ pa_hashmap_free(u->mixers);
+ if (u->jacks)
+ pa_hashmap_free(u->jacks);
+
+ if (u->card && u->card->sinks)
+ pa_idxset_remove_all(u->card->sinks, (pa_free_cb_t) pa_alsa_sink_free);
+
+ if (u->card && u->card->sources)
+ pa_idxset_remove_all(u->card->sources, (pa_free_cb_t) pa_alsa_source_free);
+
+ if (u->card)
+ pa_card_free(u->card);
+
+ if (u->modargs)
+ pa_modargs_free(u->modargs);
+
+ if (u->profile_set)
+ pa_alsa_profile_set_free(u->profile_set);
+
+ pa_alsa_ucm_free(&u->ucm);
+
+ pa_xfree(u->device_id);
+ pa_xfree(u);
+
+finish:
+ pa_alsa_refcnt_dec();
+}
diff --git a/src/modules/alsa/module-alsa-sink.c b/src/modules/alsa/module-alsa-sink.c
new file mode 100644
index 0000000..a90c5e4
--- /dev/null
+++ b/src/modules/alsa/module-alsa-sink.c
@@ -0,0 +1,137 @@
+/***
+ This file is part of PulseAudio.
+
+ Copyright 2004-2008 Lennart Poettering
+ Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
+
+ PulseAudio is free software; you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License,
+ or (at your option) any later version.
+
+ PulseAudio is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+***/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <pulsecore/module.h>
+#include <pulsecore/sink.h>
+#include <pulsecore/modargs.h>
+
+#include "alsa-util.h"
+#include "alsa-sink.h"
+
+PA_MODULE_AUTHOR("Lennart Poettering");
+PA_MODULE_DESCRIPTION("ALSA Sink");
+PA_MODULE_VERSION(PACKAGE_VERSION);
+PA_MODULE_LOAD_ONCE(false);
+PA_MODULE_USAGE(
+ "name=<name of the sink, to be prefixed> "
+ "sink_name=<name for the sink> "
+ "sink_properties=<properties for the sink> "
+ "namereg_fail=<when false attempt to synthesise new sink_name if it is already taken> "
+ "device=<ALSA device> "
+ "device_id=<ALSA card index> "
+ "format=<sample format> "
+ "rate=<sample rate> "
+ "alternate_rate=<alternate sample rate> "
+ "channels=<number of channels> "
+ "channel_map=<channel map> "
+ "fragments=<number of fragments> "
+ "fragment_size=<fragment size> "
+ "mmap=<enable memory mapping?> "
+ "tsched=<enable system timer based scheduling mode?> "
+ "tsched_buffer_size=<buffer size when using timer based scheduling> "
+ "tsched_buffer_watermark=<lower fill watermark> "
+ "ignore_dB=<ignore dB information from the device?> "
+ "control=<name of mixer control, or name and index separated by a comma> "
+ "rewind_safeguard=<number of bytes that cannot be rewound> "
+ "deferred_volume=<Synchronize software and hardware volume changes to avoid momentary jumps?> "
+ "deferred_volume_safety_margin=<usec adjustment depending on volume direction> "
+ "deferred_volume_extra_delay=<usec adjustment to HW volume changes> "
+ "fixed_latency_range=<disable latency range changes on underrun?>");
+
+static const char* const valid_modargs[] = {
+ "name",
+ "sink_name",
+ "sink_properties",
+ "namereg_fail",
+ "device",
+ "device_id",
+ "format",
+ "rate",
+ "alternate_rate",
+ "channels",
+ "channel_map",
+ "fragments",
+ "fragment_size",
+ "mmap",
+ "tsched",
+ "tsched_buffer_size",
+ "tsched_buffer_watermark",
+ "ignore_dB",
+ "control",
+ "rewind_safeguard",
+ "deferred_volume",
+ "deferred_volume_safety_margin",
+ "deferred_volume_extra_delay",
+ "fixed_latency_range",
+ NULL
+};
+
+int pa__init(pa_module*m) {
+ pa_modargs *ma = NULL;
+
+ pa_assert(m);
+
+ pa_alsa_refcnt_inc();
+
+ if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
+ pa_log("Failed to parse module arguments");
+ goto fail;
+ }
+
+ if (!(m->userdata = pa_alsa_sink_new(m, ma, __FILE__, NULL, NULL)))
+ goto fail;
+
+ pa_modargs_free(ma);
+
+ return 0;
+
+fail:
+
+ if (ma)
+ pa_modargs_free(ma);
+
+ pa__done(m);
+
+ return -1;
+}
+
+int pa__get_n_used(pa_module *m) {
+ pa_sink *sink;
+
+ pa_assert(m);
+ pa_assert_se(sink = m->userdata);
+
+ return pa_sink_linked_by(sink);
+}
+
+void pa__done(pa_module*m) {
+ pa_sink *sink;
+
+ pa_assert(m);
+
+ if ((sink = m->userdata))
+ pa_alsa_sink_free(sink);
+
+ pa_alsa_refcnt_dec();
+}
diff --git a/src/modules/alsa/module-alsa-source.c b/src/modules/alsa/module-alsa-source.c
new file mode 100644
index 0000000..d152283
--- /dev/null
+++ b/src/modules/alsa/module-alsa-source.c
@@ -0,0 +1,144 @@
+/***
+ This file is part of PulseAudio.
+
+ Copyright 2004-2008 Lennart Poettering
+ Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
+
+ PulseAudio is free software; you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License,
+ or (at your option) any later version.
+
+ PulseAudio is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
+***/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <stdio.h>
+
+#include <alsa/asoundlib.h>
+
+#ifdef HAVE_VALGRIND_MEMCHECK_H
+#include <valgrind/memcheck.h>
+#endif
+
+#include <pulsecore/module.h>
+#include <pulsecore/modargs.h>
+#include <pulsecore/log.h>
+#include <pulsecore/macro.h>
+
+#include "alsa-util.h"
+#include "alsa-source.h"
+
+PA_MODULE_AUTHOR("Lennart Poettering");
+PA_MODULE_DESCRIPTION("ALSA Source");
+PA_MODULE_VERSION(PACKAGE_VERSION);
+PA_MODULE_LOAD_ONCE(false);
+PA_MODULE_USAGE(
+ "name=<name for the source, to be prefixed> "
+ "source_name=<name for the source> "
+ "source_properties=<properties for the source> "
+ "namereg_fail=<when false attempt to synthesise new source_name if it is already taken> "
+ "device=<ALSA device> "
+ "device_id=<ALSA card index> "
+ "format=<sample format> "
+ "rate=<sample rate> "
+ "alternate_rate=<alternate sample rate> "
+ "channels=<number of channels> "
+ "channel_map=<channel map> "
+ "fragments=<number of fragments> "
+ "fragment_size=<fragment size> "
+ "mmap=<enable memory mapping?> "
+ "tsched=<enable system timer based scheduling mode?> "
+ "tsched_buffer_size=<buffer size when using timer based scheduling> "
+ "tsched_buffer_watermark=<upper fill watermark> "
+ "ignore_dB=<ignore dB information from the device?> "
+ "control=<name of mixer control, or name and index separated by a comma>"
+ "deferred_volume=<Synchronize software and hardware volume changes to avoid momentary jumps?> "
+ "deferred_volume_safety_margin=<usec adjustment depending on volume direction> "
+ "deferred_volume_extra_delay=<usec adjustment to HW volume changes> "
+ "fixed_latency_range=<disable latency range changes on overrun?>");
+
+static const char* const valid_modargs[] = {
+ "name",
+ "source_name",
+ "source_properties",
+ "namereg_fail",
+ "device",
+ "device_id",
+ "format",
+ "rate",
+ "alternate_rate",
+ "channels",
+ "channel_map",
+ "fragments",
+ "fragment_size",
+ "mmap",
+ "tsched",
+ "tsched_buffer_size",
+ "tsched_buffer_watermark",
+ "ignore_dB",
+ "control",
+ "deferred_volume",
+ "deferred_volume_safety_margin",
+ "deferred_volume_extra_delay",
+ "fixed_latency_range",
+ NULL
+};
+
+int pa__init(pa_module*m) {
+ pa_modargs *ma = NULL;
+
+ pa_assert(m);
+
+ pa_alsa_refcnt_inc();
+
+ if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
+ pa_log("Failed to parse module arguments");
+ goto fail;
+ }
+
+ if (!(m->userdata = pa_alsa_source_new(m, ma, __FILE__, NULL, NULL)))
+ goto fail;
+
+ pa_modargs_free(ma);
+
+ return 0;
+
+fail:
+
+ if (ma)
+ pa_modargs_free(ma);
+
+ pa__done(m);
+
+ return -1;
+}
+
+int pa__get_n_used(pa_module *m) {
+ pa_source *source;
+
+ pa_assert(m);
+ pa_assert_se(source = m->userdata);
+
+ return pa_source_linked_by(source);
+}
+
+void pa__done(pa_module*m) {
+ pa_source *source;
+
+ pa_assert(m);
+
+ if ((source = m->userdata))
+ pa_alsa_source_free(source);
+
+ pa_alsa_refcnt_dec();
+}