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