[pulseaudio-discuss] [PATCH] utils: Adding a function to get volume from string

Tanu Kaskinen tanuk at iki.fi
Thu Oct 25 02:13:41 PDT 2012


On Wed, 2012-10-24 at 17:29 -0200, Flavio Ceolin wrote:
> The allowed volume formats are dB, % or integer.
> For example: 10% or 10db or 10.

Thanks, applied with some fixes (see below).

> +/* Try to parse a volume string to pa_volume_t. The allowed formats are:
> + * db,  % and unsigned integer */
> +int pa_parse_volume(const char *v, pa_volume_t *volume) {
> +    int len, ret = -1;
> +    uint32_t i;
> +    double d;
> +    char str[64];
> +    pa_assert(v);

I added an empty line before the assertion, and added pa_assert(volume)
too.

> +
> +    len = strlen(v);
> +    memcpy(str, v, PA_MIN(len, 64));

Changed this to

    len = strlen(v);

    if (len >= 64)
        return -1;

    memcpy(str, v, len + 1);

to avoid issues with the terminating null byte.

> +
> +    if (str[len - 1] == '%') {
> +        str[len - 1] = '\0';
> +        if (pa_atoi(str, &i) == 0) {

Use pa_atou() instead of pa_atoi() (sorry for not noticing this
yesterday when we discussed).

> +            /* using 64 bits integer to avoid overflow */
> +            uint64_t temp;
> +            temp = PA_VOLUME_NORM * i;

This doesn't work, the cast to 64 bits is done only at the assignment
time, so PA_VOLUME_NORM * i is still calculated with only 32 bits.

> +            *volume = PA_CLAMP_VOLUME(temp / 100);
> +            ret = 0;
> +        }
> +    } else if (len > 2 && (str[len - 1] == 'b' || str[len - 1] == 'B') &&
> +               (str[len - 2] == 'd' || str[len - 2] == 'D')) {
> +        str[len - 2] = '\0';
> +        if (pa_atod(str, &d) == 0) {
> +            *volume = pa_sw_volume_from_dB(d);
> +            ret = 0;
> +        }
> +    } else {
> +        if (pa_atoi(v, &i) == 0) {

pa_atou().

-- 
Tanu



More information about the pulseaudio-discuss mailing list