1 // vim:ts=4:sw=4:expandtab
9 #include <yajl/yajl_gen.h>
10 #include <yajl/yajl_version.h>
13 #include <alsa/asoundlib.h>
18 #if defined(__FreeBSD__) || defined(__DragonFly__)
21 #include <sys/soundcard.h>
27 #include <sys/audioio.h>
28 #include <sys/ioctl.h>
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; \
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)); \
47 START_COLOR("color_degraded"); \
51 static char *apply_volume_format(const char *fmt, char *outwalk, int ivolume, const char *devicename) {
52 const char *walk = fmt;
54 for (; *walk != '\0'; walk++) {
58 } else if (BEGINS_WITH(walk + 1, "%")) {
59 outwalk += sprintf(outwalk, "%s", pct_mark);
62 } else if (BEGINS_WITH(walk + 1, "volume")) {
63 outwalk += sprintf(outwalk, "%d%s", ivolume, pct_mark);
64 walk += strlen("volume");
66 } else if (BEGINS_WITH(walk + 1, "devicename")) {
67 outwalk += sprintf(outwalk, "%s", devicename);
68 walk += strlen("devicename");
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;
81 /* Printing volume works with ALSA and PulseAudio at the moment */
82 if (output_format == O_I3BAR) {
84 asprintf(&instance, "%s.%s.%d", device, mixer, mixer_idx);
89 #if !defined(__DragonFly__) && !defined(__OpenBSD__)
90 /* Try PulseAudio first */
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:")
102 char description[MAX_SINK_DESCRIPTION_LEN] = {'\0'};
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';
112 int ivolume = DECOMPOSE_VOLUME(cvolume);
113 bool muted = DECOMPOSE_MUTED(cvolume);
115 START_COLOR("color_degraded");
119 /* negative result means error, stick to 0 */
122 outwalk = apply_volume_format(muted ? fmt_muted : fmt,
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) {
136 START_COLOR("color_degraded");
139 outwalk = apply_volume_format(muted ? fmt_muted : fmt,
145 /* negative result or NULL description means error, fail PulseAudio attempt */
147 /* If some other device was specified or PulseAudio is not detected,
148 * proceed to ALSA / OSS */
152 const long MAX_LINEAR_DB_SCALE = 24;
155 snd_mixer_selem_id_t *sid;
156 snd_mixer_elem_t *elem;
158 const char *mixer_name;
159 bool force_linear = false;
162 if ((err = snd_mixer_open(&m, 0)) < 0) {
163 fprintf(stderr, "i3status: ALSA: Cannot open mixer: %s\n", snd_strerror(err));
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));
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));
181 if ((err = snd_mixer_load(m)) < 0) {
182 fprintf(stderr, "i3status: ALSA: snd_mixer_load: %s\n", snd_strerror(err));
187 snd_mixer_selem_id_malloc(&sid);
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));
200 snd_mixer_selem_id_free(sid);
204 /* Get the volume range to convert the volume later */
205 snd_mixer_handle_events(m);
206 if (!strncasecmp(mixer, "capture", strlen("capture"))) {
209 ALSA_VOLUME(playback)
213 fprintf(stderr, "i3status: ALSA: Cannot get playback volume.\n");
217 mixer_name = snd_mixer_selem_get_name(elem);
219 fprintf(stderr, "i3status: ALSA: NULL mixer_name.\n");
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;
227 avg = (avgf - avg < 0.5 ? avg : (avg + 1));
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);
235 avg = lround(normalized * 100);
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)
245 outwalk = apply_volume_format(fmt, outwalk, avg, mixer_name);
248 snd_mixer_selem_id_free(sid);
251 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
253 char defaultmixer[] = "/dev/mixer";
254 int mixfd, vol, devmask = 0;
255 const char *devicename = "UNSUPPORTED"; /* TODO: implement support for this */
259 asprintf(&mixerpath, "/dev/mixer%d", mixer_idx);
261 mixerpath = defaultmixer;
263 if ((mixfd = open(mixerpath, O_RDWR)) < 0) {
264 #if defined(__OpenBSD__)
265 warn("audioio: Cannot open mixer");
267 warn("OSS: Cannot open mixer");
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;
282 while (ioctl(mixfd, AUDIO_MIXER_DEVINFO, &devinfo) >= 0) {
283 if (devinfo.type != AUDIO_MIXER_CLASS) {
287 if (strncmp(devinfo.label.name, AudioCoutputs, MAX_AUDIO_DEV_LEN) == 0)
288 oclass_idx = devinfo.index;
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;
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;
304 if (master_next != AUDIO_MIXER_LAST)
305 master_next = devinfo2.next;
309 if (master_idx == -1)
312 devinfo.index = master_idx;
313 if (ioctl(mixfd, AUDIO_MIXER_DEVINFO, &devinfo) == -1)
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)
322 if (AUDIO_MAX_GAIN != 100) {
323 float avgf = ((float)vinfo.un.value.level[AUDIO_MIXER_LEVEL_MONO] / AUDIO_MAX_GAIN) * 100;
325 vol = (avgf - vol < 0.5 ? vol : (vol + 1));
327 vol = (int)vinfo.un.value.level[AUDIO_MIXER_LEVEL_MONO];
330 vinfo.dev = master_mute_idx;
331 vinfo.type = AUDIO_MIXER_ENUM;
332 if (ioctl(mixfd, AUDIO_MIXER_READ, &vinfo) == -1)
335 if (master_mute_idx != -1 && vinfo.un.ord) {
336 START_COLOR("color_degraded");
342 if (ioctl(mixfd, SOUND_MIXER_READ_DEVMASK, &devmask) == -1) {
343 warn("OSS: Cannot read mixer information");
346 if (ioctl(mixfd, MIXER_READ(0), &vol) == -1) {
347 warn("OSS: Cannot read mixer information");
351 if (((vol & 0x7f) == 0) && (((vol >> 8) & 0x7f) == 0)) {
352 START_COLOR("color_degraded");
357 outwalk = apply_volume_format(fmt, outwalk, vol & 0x7f, devicename);
365 OUTPUT_FULL_TEXT(buffer);