8 #include <alsa/asoundlib.h>
20 snd_mixer_selem_id_t *sid;
22 snd_mixer_elem_t *elem;
26 TAILQ_ENTRY(mixer_hdl) handles;
29 TAILQ_HEAD(handles_head, mixer_hdl) cached = TAILQ_HEAD_INITIALIZER(cached);
32 static void free_hdl(struct mixer_hdl *hdl) {
38 void print_volume(const char *fmt, const char *device, const char *mixer, int mixer_idx) {
39 /* Printing volume only works with ALSA at the moment */
43 /* Check if we already opened the mixer and get the handle
47 struct mixer_hdl *hdl;
48 TAILQ_FOREACH(hdl, &cached, handles) {
49 if (strcmp(hdl->device, device) != 0 ||
50 strcmp(hdl->mixer, mixer) != 0 ||
51 hdl->mixer_idx != mixer_idx)
58 if ((hdl = calloc(sizeof(struct mixer_hdl), 1)) == NULL)
61 if ((hdl->device = strdup(device)) == NULL) {
66 if ((hdl->mixer = strdup(mixer)) == NULL) {
72 hdl->mixer_idx = mixer_idx;
73 snd_mixer_selem_id_malloc(&(hdl->sid));
74 if (hdl->sid == NULL) {
79 if ((err = snd_mixer_open(&(hdl->m), 0)) < 0) {
80 fprintf(stderr, "ALSA: Cannot open mixer: %s\n", snd_strerror(err));
85 /* Attach this mixer handle to the given device */
86 if ((err = snd_mixer_attach(hdl->m, device)) < 0) {
87 fprintf(stderr, "ALSA: Cannot attach mixer to device: %s\n", snd_strerror(err));
88 snd_mixer_close(hdl->m);
93 /* Register this mixer */
94 if ((err = snd_mixer_selem_register(hdl->m, NULL, NULL)) < 0) {
95 fprintf(stderr, "ALSA: snd_mixer_selem_register: %s\n", snd_strerror(err));
96 snd_mixer_close(hdl->m);
101 if ((err = snd_mixer_load(hdl->m)) < 0) {
102 fprintf(stderr, "ALSA: snd_mixer_load: %s\n", snd_strerror(err));
103 snd_mixer_close(hdl->m);
108 /* Find the given mixer */
109 snd_mixer_selem_id_set_index(hdl->sid, mixer_idx);
110 snd_mixer_selem_id_set_name(hdl->sid, mixer);
111 if (!(hdl->elem = snd_mixer_find_selem(hdl->m, hdl->sid))) {
112 fprintf(stderr, "ALSA: Cannot find mixer %s (index %i)\n",
113 snd_mixer_selem_id_get_name(hdl->sid), snd_mixer_selem_id_get_index(hdl->sid));
114 snd_mixer_close(hdl->m);
119 /* Get the volume range to convert the volume later */
120 snd_mixer_selem_get_playback_volume_range(hdl->elem, &(hdl->min), &(hdl->max));
121 TAILQ_INSERT_TAIL(&cached, hdl, handles);
125 snd_mixer_handle_events (hdl->m);
126 snd_mixer_selem_get_playback_volume (hdl->elem, 0, &val);
128 if (hdl->max != 100) {
129 float avgf = ((float)val / hdl->max) * 100;
131 avg = (avgf - avg < 0.5 ? avg : (avg+1));
132 } else avg = (int)val;
135 if (snd_mixer_selem_has_playback_switch(hdl->elem)) {
137 if ((err = snd_mixer_selem_get_playback_switch(hdl->elem, 0, &pbval)) < 0)
138 fprintf (stderr, "ALSA: playback_switch: %s\n", snd_strerror(err));
143 const char *walk = fmt;
144 for (; *walk != '\0'; walk++) {
149 if (BEGINS_WITH(walk+1, "volume")) {
151 walk += strlen("volume");