Xinqi Bao's Git

4c9a6ac4887df6dff50e744e939a814a6ccc94cf
[slstatus.git] / components / volume.c
1 /* See LICENSE file for copyright and license details. */
2 #if defined(__linux__)
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <sys/soundcard.h>
6 #include <sys/ioctl.h>
7 #include <stdio.h>
8 #include <string.h>
9 #include <unistd.h>
10
11 #include "../util.h"
12
13 const char *
14 vol_perc(const char *card)
15 {
16 unsigned int i;
17 int v, afd, devmask;
18 char *vnames[] = SOUND_DEVICE_NAMES;
19
20 afd = open(card, O_RDONLY | O_NONBLOCK);
21 if (afd == -1) {
22 fprintf(stderr, "open '%s': %s\n", card, strerror(errno));
23 return NULL;
24 }
25
26 if (ioctl(afd, SOUND_MIXER_READ_DEVMASK, &devmask) == -1) {
27 fprintf(stderr, "ioctl 'SOUND_MIXER_READ_DEVMASK': %s\n", strerror(errno));
28 close(afd);
29 return NULL;
30 }
31 for (i = 0; i < LEN(vnames); i++) {
32 if (devmask & (1 << i) && !strcmp("vol", vnames[i])) {
33 if (ioctl(afd, MIXER_READ(i), &v) == -1) {
34 fprintf(stderr, "ioctl 'MIXER_READ(%d)': %s\n", i, strerror(errno));
35 close(afd);
36 return NULL;
37 }
38 }
39 }
40
41 close(afd);
42
43 return bprintf("%d", v & 0xff);
44 }
45 #endif