* OpenBSD support added to Conky (thanks hifi)
[monky] / src / mixer.c
1 /*
2  * Conky, a system monitor, based on torsmo
3  *
4  * This program is licensed under BSD license, read COPYING
5  *
6  *  $Id$
7  */
8
9 #include <sys/ioctl.h>
10
11 #include <errno.h>
12 #include <fcntl.h>
13 #include <string.h>
14 #include <stdlib.h>
15
16 #include "conky.h"
17
18 #ifdef HAVE_LINUX_SOUNDCARD_H
19 #include <linux/soundcard.h>
20 #else
21 #ifdef __OpenBSD__
22 #include <soundcard.h>
23 #else
24 #include <sys/soundcard.h>
25 #endif                          /* __OpenBSD__ */
26 #endif                          /* HAVE_LINUX_SOUNDCARD_H */
27
28 #define MIXER_DEV "/dev/mixer"
29
30 static int mixer_fd;
31 static const char *devs[] = SOUND_DEVICE_NAMES;
32
33 int mixer_init(const char *name)
34 {
35         unsigned int i;
36
37         if (name == 0 || name[0] == '\0')
38                 name = "vol";
39
40         /* open mixer */
41         if (mixer_fd <= 0) {
42                 mixer_fd = open(MIXER_DEV, O_RDONLY);
43                 if (mixer_fd == -1) {
44                         ERR("can't open %s: %s", MIXER_DEV,
45                             strerror(errno));
46                         return -1;
47                 }
48         }
49
50         for (i = 0; i < sizeof(devs) / sizeof(const char *); i++) {
51                 if (strcasecmp(devs[i], name) == 0) {
52                         return i;
53                 }
54         }
55
56         return -1;
57 }
58
59 static int mixer_get(int i)
60 {
61         static char rep = 0;
62         int val = -1;
63
64         if (ioctl(mixer_fd, MIXER_READ(i), &val) == -1) {
65                 if (!rep)
66                         ERR("mixer ioctl: %s", strerror(errno));
67                 rep = 1;
68                 return 0;
69         }
70         rep = 0;
71
72         return val;
73 }
74
75 int mixer_get_avg(int i)
76 {
77         int v = mixer_get(i);
78         return ((v >> 8) + (v & 0xFF)) / 2;
79 }
80
81 int mixer_get_left(int i)
82 {
83         return mixer_get(i) >> 8;
84 }
85
86 int mixer_get_right(int i)
87 {
88         return mixer_get(i) & 0xFF;
89 }