summaryrefslogtreecommitdiff
path: root/components/custom.c
blob: d68f50605ca9efedba40022a3f99a3c9c03be949 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <alsa/asoundlib.h>
#include <alsa/mixer.h>
#include <limits.h>

#include "../util.h"

// https://stackoverflow.com/questions/7657624/get-master-sound-volume-in-c-in-linux
const char *vol_pulse(void)
{
    snd_mixer_t *handle;
    snd_mixer_elem_t *elem;
    snd_mixer_selem_id_t *sid;

    static const char *mix_name = "Master";
    static const char *card = "default";
    static int mix_index = 0;

    static const char *notfound = "n/a";

    snd_mixer_selem_id_alloca(&sid);

    snd_mixer_selem_id_set_index(sid, mix_index);
    snd_mixer_selem_id_set_name(sid, mix_name);

    if ((snd_mixer_open(&handle, 0)) < 0) {
        fprintf(stderr, "could not open mixer\n");
        return notfound;
    }
    if ((snd_mixer_attach(handle, card)) < 0) {
        snd_mixer_close(handle);
        fprintf(stderr, "could not open card %s\n", card);
        return notfound;
    }
    if ((snd_mixer_selem_register(handle, NULL, NULL)) < 0) {
        snd_mixer_close(handle);
        fprintf(stderr, "could not register selem\n");
        return notfound;
    }
    int ret = snd_mixer_load(handle);
    if (ret < 0) {
        snd_mixer_close(handle);
        fprintf(stderr, "could not load mixer\n");
        return notfound;
    }
    elem = snd_mixer_find_selem(handle, sid);
    if (!elem) {
        snd_mixer_close(handle);
        fprintf(stderr, "could not find selem with index=%d, name=%s\n", mix_index, mix_name);
        return notfound;
    }

    long minv, maxv;
    long outvol;
    int muted;

    snd_mixer_selem_get_playback_volume_range(elem, &minv, &maxv);

    if(snd_mixer_selem_get_playback_volume(elem, 0, &outvol) < 0) {
        fprintf(stderr, "could not read output volume\n");
        snd_mixer_close(handle);
        return notfound;
    }

    if(snd_mixer_selem_get_playback_switch(elem, 0, &muted) < 0) {
        fprintf(stderr, "could not read mute output\n");
        snd_mixer_close(handle);
        return notfound;
    }

    snd_mixer_close(handle);

    return bprintf("%0.0f%s", ((float)outvol / (float)maxv) * 100, muted ? "" : "M");
}