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