1 // vim:ts=4:sw=4:expandtab
8 #include <yajl/yajl_gen.h>
9 #include <yajl/yajl_version.h>
12 #include <alsa/asoundlib.h>
17 #if defined(__FreeBSD__) || defined(__DragonFly__)
20 #include <sys/soundcard.h>
26 #include <sys/audioio.h>
27 #include <sys/ioctl.h>
33 #define ALSA_VOLUME(channel) \
34 err = snd_mixer_selem_get_##channel##_dB_range(elem, &min, &max) || \
35 snd_mixer_selem_get_##channel##_dB(elem, 0, &val); \
36 if (err != 0 || min >= max) { \
37 err = snd_mixer_selem_get_##channel##_volume_range(elem, &min, &max) || \
38 snd_mixer_selem_get_##channel##_volume(elem, 0, &val); \
39 force_linear = true; \
42 #define ALSA_MUTE_SWITCH(channel) \
43 if ((err = snd_mixer_selem_get_##channel##_switch(elem, 0, &pbval)) < 0) \
44 fprintf(stderr, "i3status: ALSA: " #channel "_switch: %s\n", snd_strerror(err)); \
46 START_COLOR("color_degraded"); \
50 static char *apply_volume_format(const char *fmt, char *outwalk, int ivolume, const char *devicename) {
51 const char *walk = fmt;
53 for (; *walk != '\0'; walk++) {
57 } else if (BEGINS_WITH(walk + 1, "%")) {
58 outwalk += sprintf(outwalk, "%s", pct_mark);
61 } else if (BEGINS_WITH(walk + 1, "volume")) {
62 outwalk += sprintf(outwalk, "%d%s", ivolume, pct_mark);
63 walk += strlen("volume");
65 } else if (BEGINS_WITH(walk + 1, "devicename")) {
66 outwalk += sprintf(outwalk, "%s", devicename);
67 walk += strlen("devicename");
76 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) {
77 char *outwalk = buffer;
80 /* Printing volume works with ALSA and PulseAudio at the moment */
81 if (output_format == O_I3BAR) {
83 asprintf(&instance, "%s.%s.%d", device, mixer, mixer_idx);
88 #if !defined(__DragonFly__) && !defined(__OpenBSD__)
89 /* Try PulseAudio first */
91 /* If the device name has the format "pulse[:N]" where N is the
92 * index of the PulseAudio sink then force PulseAudio, optionally
93 * overriding the default sink */
94 if (!strncasecmp(device, "pulse", strlen("pulse"))) {
95 uint32_t sink_idx = device[strlen("pulse")] == ':' ? (uint32_t)atoi(device + strlen("pulse:")) : DEFAULT_SINK_INDEX;
96 const char *sink_name = device[strlen("pulse")] == ':' &&
97 !isdigit(device[strlen("pulse:")])
98 ? device + strlen("pulse:")
101 char description[MAX_SINK_DESCRIPTION_LEN] = {'\0'};
103 if (pulse_initialize()) {
104 cvolume = volume_pulseaudio(sink_idx, sink_name);
105 /* false result means error, stick to empty-string */
106 if (!description_pulseaudio(sink_idx, sink_name, description)) {
107 description[0] = '\0';
111 int ivolume = DECOMPOSE_VOLUME(cvolume);
112 bool muted = DECOMPOSE_MUTED(cvolume);
114 START_COLOR("color_degraded");
118 /* negative result means error, stick to 0 */
121 outwalk = apply_volume_format(muted ? fmt_muted : fmt,
126 } else if (!strcasecmp(device, "default") && pulse_initialize()) {
127 /* no device specified or "default" set */
128 char description[MAX_SINK_DESCRIPTION_LEN];
129 bool success = description_pulseaudio(DEFAULT_SINK_INDEX, NULL, description);
130 int cvolume = volume_pulseaudio(DEFAULT_SINK_INDEX, NULL);
131 int ivolume = DECOMPOSE_VOLUME(cvolume);
132 bool muted = DECOMPOSE_MUTED(cvolume);
133 if (ivolume >= 0 && success) {
135 START_COLOR("color_degraded");
138 outwalk = apply_volume_format(muted ? fmt_muted : fmt,
144 /* negative result or NULL description means error, fail PulseAudio attempt */
146 /* If some other device was specified or PulseAudio is not detected,
147 * proceed to ALSA / OSS */
151 const long MAX_LINEAR_DB_SCALE = 24;
154 snd_mixer_selem_id_t *sid;
155 snd_mixer_elem_t *elem;
157 const char *mixer_name;
158 bool force_linear = false;
161 if ((err = snd_mixer_open(&m, 0)) < 0) {
162 fprintf(stderr, "i3status: ALSA: Cannot open mixer: %s\n", snd_strerror(err));
166 /* Attach this mixer handle to the given device */
167 if ((err = snd_mixer_attach(m, device)) < 0) {
168 fprintf(stderr, "i3status: ALSA: Cannot attach mixer to device: %s\n", snd_strerror(err));
173 /* Register this mixer */
174 if ((err = snd_mixer_selem_register(m, NULL, NULL)) < 0) {
175 fprintf(stderr, "i3status: ALSA: snd_mixer_selem_register: %s\n", snd_strerror(err));
180 if ((err = snd_mixer_load(m)) < 0) {
181 fprintf(stderr, "i3status: ALSA: snd_mixer_load: %s\n", snd_strerror(err));
186 snd_mixer_selem_id_malloc(&sid);
192 /* Find the given mixer */
193 snd_mixer_selem_id_set_index(sid, mixer_idx);
194 snd_mixer_selem_id_set_name(sid, mixer);
195 if (!(elem = snd_mixer_find_selem(m, sid))) {
196 fprintf(stderr, "i3status: ALSA: Cannot find mixer %s (index %u)\n",
197 snd_mixer_selem_id_get_name(sid), snd_mixer_selem_id_get_index(sid));
199 snd_mixer_selem_id_free(sid);
203 /* Get the volume range to convert the volume later */
204 snd_mixer_handle_events(m);
205 if (!strncasecmp(mixer, "capture", strlen("capture"))) {
208 ALSA_VOLUME(playback)
212 fprintf(stderr, "i3status: ALSA: Cannot get playback volume.\n");
216 mixer_name = snd_mixer_selem_get_name(elem);
218 fprintf(stderr, "i3status: ALSA: NULL mixer_name.\n");
222 /* Use linear mapping for raw register values or small ranges of 24 dB */
223 if (force_linear || max - min <= MAX_LINEAR_DB_SCALE * 100) {
224 float avgf = ((float)(val - min) / (max - min)) * 100;
226 avg = (avgf - avg < 0.5 ? avg : (avg + 1));
228 /* mapped volume to be more natural for the human ear */
229 double normalized = exp10((val - max) / 6000.0);
230 if (min != SND_CTL_TLV_DB_GAIN_MUTE) {
231 double min_norm = exp10((min - max) / 6000.0);
232 normalized = (normalized - min_norm) / (1 - min_norm);
234 avg = lround(normalized * 100);
238 if (snd_mixer_selem_has_playback_switch(elem)) {
239 ALSA_MUTE_SWITCH(playback)
240 } else if (snd_mixer_selem_has_capture_switch(elem)) {
241 ALSA_MUTE_SWITCH(capture)
244 outwalk = apply_volume_format(fmt, outwalk, avg, mixer_name);
247 snd_mixer_selem_id_free(sid);
250 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
252 char defaultmixer[] = "/dev/mixer";
253 int mixfd, vol, devmask = 0;
254 const char *devicename = "UNSUPPORTED"; /* TODO: implement support for this */
258 asprintf(&mixerpath, "/dev/mixer%d", mixer_idx);
260 mixerpath = defaultmixer;
262 if ((mixfd = open(mixerpath, O_RDWR)) < 0) {
263 #if defined(__OpenBSD__)
264 warn("audioio: Cannot open mixer");
266 warn("OSS: Cannot open mixer");
274 #if defined(__OpenBSD__)
275 int oclass_idx = -1, master_idx = -1, master_mute_idx = -1;
276 int master_next = AUDIO_MIXER_LAST;
277 mixer_devinfo_t devinfo, devinfo2;
281 while (ioctl(mixfd, AUDIO_MIXER_DEVINFO, &devinfo) >= 0) {
282 if (devinfo.type != AUDIO_MIXER_CLASS) {
286 if (strncmp(devinfo.label.name, AudioCoutputs, MAX_AUDIO_DEV_LEN) == 0)
287 oclass_idx = devinfo.index;
293 while (ioctl(mixfd, AUDIO_MIXER_DEVINFO, &devinfo2) >= 0) {
294 if ((devinfo2.type == AUDIO_MIXER_VALUE) && (devinfo2.mixer_class == oclass_idx) && (strncmp(devinfo2.label.name, AudioNmaster, MAX_AUDIO_DEV_LEN) == 0)) {
295 master_idx = devinfo2.index;
296 master_next = devinfo2.next;
299 if ((devinfo2.type == AUDIO_MIXER_ENUM) && (devinfo2.mixer_class == oclass_idx) && (strncmp(devinfo2.label.name, AudioNmute, MAX_AUDIO_DEV_LEN) == 0))
300 if (master_next == devinfo2.index)
301 master_mute_idx = devinfo2.index;
303 if (master_next != AUDIO_MIXER_LAST)
304 master_next = devinfo2.next;
308 if (master_idx == -1)
311 devinfo.index = master_idx;
312 if (ioctl(mixfd, AUDIO_MIXER_DEVINFO, &devinfo) == -1)
315 vinfo.dev = master_idx;
316 vinfo.type = AUDIO_MIXER_VALUE;
317 vinfo.un.value.num_channels = devinfo.un.v.num_channels;
318 if (ioctl(mixfd, AUDIO_MIXER_READ, &vinfo) == -1)
321 if (AUDIO_MAX_GAIN != 100) {
322 float avgf = ((float)vinfo.un.value.level[AUDIO_MIXER_LEVEL_MONO] / AUDIO_MAX_GAIN) * 100;
324 vol = (avgf - vol < 0.5 ? vol : (vol + 1));
326 vol = (int)vinfo.un.value.level[AUDIO_MIXER_LEVEL_MONO];
329 vinfo.dev = master_mute_idx;
330 vinfo.type = AUDIO_MIXER_ENUM;
331 if (ioctl(mixfd, AUDIO_MIXER_READ, &vinfo) == -1)
334 if (master_mute_idx != -1 && vinfo.un.ord) {
335 START_COLOR("color_degraded");
341 if (ioctl(mixfd, SOUND_MIXER_READ_DEVMASK, &devmask) == -1) {
342 warn("OSS: Cannot read mixer information");
345 if (ioctl(mixfd, MIXER_READ(0), &vol) == -1) {
346 warn("OSS: Cannot read mixer information");
350 if (((vol & 0x7f) == 0) && (((vol >> 8) & 0x7f) == 0)) {
351 START_COLOR("color_degraded");
356 outwalk = apply_volume_format(fmt, outwalk, vol & 0x7f, devicename);
364 OUTPUT_FULL_TEXT(buffer);