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);
31 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 */
41 /* Check if we already opened the mixer and get the handle
45 struct mixer_hdl *hdl;
46 TAILQ_FOREACH(hdl, &cached, handles) {
47 if (strcmp(hdl->device, device) != 0 ||
48 strcmp(hdl->mixer, mixer) != 0 ||
49 hdl->mixer_idx != mixer_idx)
56 if ((hdl = calloc(sizeof(struct mixer_hdl), 1)) == NULL)
59 if ((hdl->device = strdup(device)) == NULL) {
64 if ((hdl->mixer = strdup(mixer)) == NULL) {
70 hdl->mixer_idx = mixer_idx;
71 snd_mixer_selem_id_malloc(&(hdl->sid));
72 if (hdl->sid == NULL) {
77 if ((err = snd_mixer_open(&(hdl->m), 0)) < 0) {
78 fprintf(stderr, "ALSA: Cannot open mixer: %s\n", snd_strerror(err));
83 /* Attach this mixer handle to the given device */
84 if ((err = snd_mixer_attach(hdl->m, device)) < 0) {
85 fprintf(stderr, "ALSA: Cannot attach mixer to device: %s\n", snd_strerror(err));
86 snd_mixer_close(hdl->m);
91 /* Register this mixer */
92 if ((err = snd_mixer_selem_register(hdl->m, NULL, NULL)) < 0) {
93 fprintf(stderr, "ALSA: snd_mixer_selem_register: %s\n", snd_strerror(err));
94 snd_mixer_close(hdl->m);
99 if ((err = snd_mixer_load(hdl->m)) < 0) {
100 fprintf(stderr, "ALSA: snd_mixer_load: %s\n", snd_strerror(err));
101 snd_mixer_close(hdl->m);
106 /* Find the given mixer */
107 snd_mixer_selem_id_set_index(hdl->sid, mixer_idx);
108 snd_mixer_selem_id_set_name(hdl->sid, mixer);
109 if (!(hdl->elem = snd_mixer_find_selem(hdl->m, hdl->sid))) {
110 fprintf(stderr, "ALSA: Cannot find mixer %s (index %i)\n",
111 snd_mixer_selem_id_get_name(hdl->sid), snd_mixer_selem_id_get_index(hdl->sid));
112 snd_mixer_close(hdl->m);
117 /* Get the volume range to convert the volume later */
118 snd_mixer_selem_get_playback_volume_range(hdl->elem, &(hdl->min), &(hdl->max));
119 TAILQ_INSERT_TAIL(&cached, hdl, handles);
123 snd_mixer_handle_events (hdl->m);
124 snd_mixer_selem_get_playback_volume (hdl->elem, 0, &val);
126 if (hdl->max != 100) {
127 float avgf = ((float)val / hdl->max) * 100;
129 avg = (avgf - avg < 0.5 ? avg : (avg+1));
130 } else avg = (int)val;
133 if (snd_mixer_selem_has_playback_switch(hdl->elem)) {
135 if ((err = snd_mixer_selem_get_playback_switch(hdl->elem, 0, &pbval)) < 0)
136 fprintf (stderr, "ALSA: playback_switch: %s\n", snd_strerror(err));
141 const char *walk = fmt;
142 for (; *walk != '\0'; walk++) {
147 if (BEGINS_WITH(walk+1, "volume")) {
149 walk += strlen("volume");