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