]> git.sur5r.net Git - i3/i3status/blob - src/print_volume.c
OpenBSD: fix volume display on some hardware
[i3/i3status] / src / print_volume.c
1 // vim:ts=4:sw=4:expandtab
2 #include <time.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <stdio.h>
6 #include <err.h>
7 #include <ctype.h>
8 #include <yajl/yajl_gen.h>
9 #include <yajl/yajl_version.h>
10
11 #ifdef LINUX
12 #include <alsa/asoundlib.h>
13 #include <alloca.h>
14 #endif
15
16 #if defined(__FreeBSD__) || defined(__DragonFly__)
17 #include <fcntl.h>
18 #include <unistd.h>
19 #include <sys/soundcard.h>
20 #endif
21
22 #ifdef __OpenBSD__
23 #include <fcntl.h>
24 #include <unistd.h>
25 #include <sys/audioio.h>
26 #include <sys/ioctl.h>
27 #endif
28
29 #include "i3status.h"
30 #include "queue.h"
31
32 static char *apply_volume_format(const char *fmt, char *outwalk, int ivolume) {
33     const char *walk = fmt;
34
35     for (; *walk != '\0'; walk++) {
36         if (*walk != '%') {
37             *(outwalk++) = *walk;
38             continue;
39         }
40         if (BEGINS_WITH(walk + 1, "%")) {
41             outwalk += sprintf(outwalk, "%s", pct_mark);
42             walk += strlen("%");
43         }
44         if (BEGINS_WITH(walk + 1, "volume")) {
45             outwalk += sprintf(outwalk, "%d%s", ivolume, pct_mark);
46             walk += strlen("volume");
47         }
48     }
49     return outwalk;
50 }
51
52 void print_volume(yajl_gen json_gen, char *buffer, const char *fmt, const char *fmt_muted, const char *device, const char *mixer, int mixer_idx) {
53     char *outwalk = buffer;
54     int pbval = 1;
55
56     /* Printing volume works with ALSA and PulseAudio at the moment */
57     if (output_format == O_I3BAR) {
58         char *instance;
59         asprintf(&instance, "%s.%s.%d", device, mixer, mixer_idx);
60         INSTANCE(instance);
61         free(instance);
62     }
63
64 #ifndef __OpenBSD__
65     /* Try PulseAudio first */
66
67     /* If the device name has the format "pulse[:N]" where N is the
68      * index of the PulseAudio sink then force PulseAudio, optionally
69      * overriding the default sink */
70     if (!strncasecmp(device, "pulse", strlen("pulse"))) {
71         uint32_t sink_idx = device[strlen("pulse")] == ':' ? (uint32_t)atoi(device + strlen("pulse:")) : DEFAULT_SINK_INDEX;
72         const char *sink_name = device[strlen("pulse")] == ':' &&
73                                         !isdigit(device[strlen("pulse:")])
74                                     ? device + strlen("pulse:")
75                                     : NULL;
76         int cvolume = pulse_initialize() ? volume_pulseaudio(sink_idx, sink_name) : 0;
77         int ivolume = DECOMPOSE_VOLUME(cvolume);
78         bool muted = DECOMPOSE_MUTED(cvolume);
79         if (muted) {
80             START_COLOR("color_degraded");
81             pbval = 0;
82         }
83         /* negative result means error, stick to 0 */
84         if (ivolume < 0)
85             ivolume = 0;
86         outwalk = apply_volume_format(muted ? fmt_muted : fmt,
87                                       outwalk,
88                                       ivolume);
89         goto out;
90     } else if (!strcasecmp(device, "default") && pulse_initialize()) {
91         /* no device specified or "default" set */
92         int cvolume = volume_pulseaudio(DEFAULT_SINK_INDEX, NULL);
93         int ivolume = DECOMPOSE_VOLUME(cvolume);
94         bool muted = DECOMPOSE_MUTED(cvolume);
95         if (ivolume >= 0) {
96             if (muted) {
97                 START_COLOR("color_degraded");
98                 pbval = 0;
99             }
100             outwalk = apply_volume_format(muted ? fmt_muted : fmt,
101                                           outwalk,
102                                           ivolume);
103             goto out;
104         }
105         /* negative result means error, fail PulseAudio attempt */
106     }
107 /* If some other device was specified or PulseAudio is not detected,
108  * proceed to ALSA / OSS */
109 #endif
110
111 #ifdef LINUX
112     int err;
113     snd_mixer_t *m;
114     snd_mixer_selem_id_t *sid;
115     snd_mixer_elem_t *elem;
116     long min, max, val;
117     int avg;
118
119     if ((err = snd_mixer_open(&m, 0)) < 0) {
120         fprintf(stderr, "i3status: ALSA: Cannot open mixer: %s\n", snd_strerror(err));
121         goto out;
122     }
123
124     /* Attach this mixer handle to the given device */
125     if ((err = snd_mixer_attach(m, device)) < 0) {
126         fprintf(stderr, "i3status: ALSA: Cannot attach mixer to device: %s\n", snd_strerror(err));
127         snd_mixer_close(m);
128         goto out;
129     }
130
131     /* Register this mixer */
132     if ((err = snd_mixer_selem_register(m, NULL, NULL)) < 0) {
133         fprintf(stderr, "i3status: ALSA: snd_mixer_selem_register: %s\n", snd_strerror(err));
134         snd_mixer_close(m);
135         goto out;
136     }
137
138     if ((err = snd_mixer_load(m)) < 0) {
139         fprintf(stderr, "i3status: ALSA: snd_mixer_load: %s\n", snd_strerror(err));
140         snd_mixer_close(m);
141         goto out;
142     }
143
144     snd_mixer_selem_id_malloc(&sid);
145     if (sid == NULL) {
146         snd_mixer_close(m);
147         goto out;
148     }
149
150     /* Find the given mixer */
151     snd_mixer_selem_id_set_index(sid, mixer_idx);
152     snd_mixer_selem_id_set_name(sid, mixer);
153     if (!(elem = snd_mixer_find_selem(m, sid))) {
154         fprintf(stderr, "i3status: ALSA: Cannot find mixer %s (index %i)\n",
155                 snd_mixer_selem_id_get_name(sid), snd_mixer_selem_id_get_index(sid));
156         snd_mixer_close(m);
157         snd_mixer_selem_id_free(sid);
158         goto out;
159     }
160
161     /* Get the volume range to convert the volume later */
162     snd_mixer_selem_get_playback_volume_range(elem, &min, &max);
163
164     snd_mixer_handle_events(m);
165     snd_mixer_selem_get_playback_volume(elem, 0, &val);
166     if (max != 100) {
167         float avgf = ((float)val / max) * 100;
168         avg = (int)avgf;
169         avg = (avgf - avg < 0.5 ? avg : (avg + 1));
170     } else
171         avg = (int)val;
172
173     /* Check for mute */
174     if (snd_mixer_selem_has_playback_switch(elem)) {
175         if ((err = snd_mixer_selem_get_playback_switch(elem, 0, &pbval)) < 0)
176             fprintf(stderr, "i3status: ALSA: playback_switch: %s\n", snd_strerror(err));
177         if (!pbval) {
178             START_COLOR("color_degraded");
179             fmt = fmt_muted;
180         }
181     }
182
183     snd_mixer_close(m);
184     snd_mixer_selem_id_free(sid);
185
186     outwalk = apply_volume_format(fmt, outwalk, avg);
187
188 #endif
189 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
190     char *mixerpath;
191     char defaultmixer[] = "/dev/mixer";
192     int mixfd, vol, devmask = 0;
193     pbval = 1;
194
195     if (mixer_idx > 0)
196         asprintf(&mixerpath, "/dev/mixer%d", mixer_idx);
197     else
198         mixerpath = defaultmixer;
199
200     if ((mixfd = open(mixerpath, O_RDWR)) < 0) {
201 #if defined(__OpenBSD__)
202         warn("audioio: Cannot open mixer");
203 #else
204         warn("OSS: Cannot open mixer");
205 #endif
206         goto out;
207     }
208
209     if (mixer_idx > 0)
210         free(mixerpath);
211
212 #if defined(__OpenBSD__)
213     int oclass_idx = -1, master_idx = -1, master_mute_idx = -1;
214     int master_next = AUDIO_MIXER_LAST;
215     mixer_devinfo_t devinfo, devinfo2;
216     mixer_ctrl_t vinfo;
217
218     devinfo.index = 0;
219     while (ioctl(mixfd, AUDIO_MIXER_DEVINFO, &devinfo) >= 0) {
220         if (devinfo.type != AUDIO_MIXER_CLASS) {
221             devinfo.index++;
222             continue;
223         }
224         if (strncmp(devinfo.label.name, AudioCoutputs, MAX_AUDIO_DEV_LEN) == 0)
225             oclass_idx = devinfo.index;
226
227         devinfo.index++;
228     }
229
230     devinfo2.index = 0;
231     while (ioctl(mixfd, AUDIO_MIXER_DEVINFO, &devinfo2) >= 0) {
232         if ((devinfo2.type == AUDIO_MIXER_VALUE) && (devinfo2.mixer_class == oclass_idx) && (strncmp(devinfo2.label.name, AudioNmaster, MAX_AUDIO_DEV_LEN) == 0)) {
233             master_idx = devinfo2.index;
234             master_next = devinfo2.next;
235         }
236
237         if ((devinfo2.type == AUDIO_MIXER_ENUM) && (devinfo2.mixer_class == oclass_idx) && (strncmp(devinfo2.label.name, AudioNmute, MAX_AUDIO_DEV_LEN) == 0))
238             if (master_next == devinfo2.index)
239                 master_mute_idx = devinfo2.index;
240
241         if (master_next != AUDIO_MIXER_LAST)
242             master_next = devinfo2.next;
243         devinfo2.index++;
244     }
245
246     if (master_idx == -1)
247         goto out;
248
249     devinfo.index = master_idx;
250     if (ioctl(mixfd, AUDIO_MIXER_DEVINFO, &devinfo) == -1)
251         goto out;
252
253     vinfo.dev = master_idx;
254     vinfo.type = AUDIO_MIXER_VALUE;
255     vinfo.un.value.num_channels = devinfo.un.v.num_channels;
256     if (ioctl(mixfd, AUDIO_MIXER_READ, &vinfo) == -1)
257         goto out;
258
259     if (AUDIO_MAX_GAIN != 100) {
260         float avgf = ((float)vinfo.un.value.level[AUDIO_MIXER_LEVEL_MONO] / AUDIO_MAX_GAIN) * 100;
261         vol = (int)avgf;
262         vol = (avgf - vol < 0.5 ? vol : (vol + 1));
263     } else {
264         vol = (int)vinfo.un.value.level[AUDIO_MIXER_LEVEL_MONO];
265     }
266
267     vinfo.dev = master_mute_idx;
268     vinfo.type = AUDIO_MIXER_ENUM;
269     if (ioctl(mixfd, AUDIO_MIXER_READ, &vinfo) == -1)
270         goto out;
271
272     if (master_mute_idx != -1 && vinfo.un.ord) {
273         START_COLOR("color_degraded");
274         fmt = fmt_muted;
275         pbval = 0;
276     }
277
278 #else
279     if (ioctl(mixfd, SOUND_MIXER_READ_DEVMASK, &devmask) == -1) {
280         warn("OSS: Cannot read mixer information");
281         goto out;
282     }
283     if (ioctl(mixfd, MIXER_READ(0), &vol) == -1) {
284         warn("OSS: Cannot read mixer information");
285         goto out;
286     }
287
288     if (((vol & 0x7f) == 0) && (((vol >> 8) & 0x7f) == 0)) {
289         START_COLOR("color_degraded");
290         pbval = 0;
291     }
292
293 #endif
294     outwalk = apply_volume_format(fmt, outwalk, vol & 0x7f);
295     close(mixfd);
296 #endif
297
298 out:
299     *outwalk = '\0';
300     if (!pbval)
301         END_COLOR;
302     OUTPUT_FULL_TEXT(buffer);
303 }