如果断言失败,则防止崩溃(未正确配置alsa)

时间:2013-02-07 02:13:04

标签: c alsa

如果用户崩溃未正确配置alsa混音器 alsa_get_unmute_volume:断言`elem'失败

static const char alsa_core_devnames[] = "default";
static char *card, *channel;
static int muted = 0;
static int mutecount = 0;
static snd_mixer_t *handle = NULL;
static snd_mixer_elem_t *elem = NULL;

static long alsa_min, alsa_max, alsa_vol;

static int alsa_get_unmute_volume( void )
{
    long val;
    assert(elem);

    if (snd_mixer_selem_is_playback_mono(elem)) {
        snd_mixer_selem_get_playback_volume(elem, SND_MIXER_SCHN_MONO, &val);
        return val;
    } else {
        int c, n = 0;
        long sum = 0;
        for (c = 0; c <= SND_MIXER_SCHN_LAST; c++) {
            if (snd_mixer_selem_has_playback_channel(elem, c)) {
                snd_mixer_selem_get_playback_volume(elem, SND_MIXER_SCHN_FRONT_LEFT, &val);
                sum += val;
                n++;
            }
        }
        if (! n) {
            return 0;
        }

        val = sum / n;
        sum = (long)((double)(alsa_vol * (alsa_max - alsa_min)) / 100. + 0.5);

        if (sum != val) {
           alsa_vol = (long)(((val * 100.) / (alsa_max - alsa_min)) + 0.5);
        }
        return alsa_vol;
    }
}

碰撞

alsa_get_unmute_volume: Assertion `elem' failed. Aborted (core dumped)

可以在代码中防止这种情况吗?

我认为这个问题就在这里。当用户手动设置,在gtkentry中,设备和通道的值错误,例如/ dev / mixer:line,然后按回车键,程序崩溃

设置混音器设备和通道的代码(正确值,例如,hw:0 / Line,默认/ CD,...)是这样的:

static int alsa_set_device( const char *devname )
{
    int i;

    if (card) free(card);
    card = strdup( devname );
    if( !card ) return -1;

    i = strcspn( card, "/" );
    if( i == strlen( card ) ) {
        channel = "Line";
    } else {
        card[i] = 0;
        channel = card + i + 1;
    }
    alsa_open_mixer();
    if (!handle) {
        fprintf( stderr, "mixer: Can't open mixer %s, "
                 "mixer volume and mute unavailable.\n", card );
        return -1;
    }
    return 0;
}

由于

1 个答案:

答案 0 :(得分:1)

您必须重新编译ALSA才能禁用断言。当您定义NDEBUG断言被禁用时。

请注意,如果断言失败,即使您禁用断言,可能程序也会崩溃或导致意外行为。

一个断言应该永远是真的,如果它是假的某人在某个地方犯了错误。