ssize_t
fread_dyn(char **destp, size_t *n, FILE *stream)
{
    const unsigned bsize = 8192;
    size_t total = 0, cnt = 0; 

    assert(destp);
    assert(n);
    assert(stream);

    if (!*destp) 
        *destp = xmalloc(*n = bsize);

    while (1) {
        cnt = fread(*destp+total, 1, *n-total, stream);
        if (cnt != *n-total)
        {
            if (feof(stream))
                return total+cnt;
            else if (ferror(stream))
			{
				CWARNING3(filesys, "read error: %s", strerror(errno));
                return -1;
			}
        }
        total += cnt;

        if (*n <= total)
            *destp = xrealloc(*destp, *n *= 2);
    }
}
Beispiel #2
0
ssize_t
load_audio_file(const char *name, char **data, size_t *size)
{
    mm_file mf;
    unsigned channels, rate;
    const size_t def_size = 16 * 1024;
    size_t offset = 0;
    ssize_t read = 0;
    double start = get_time();

    /* make compiler happy */
    start *= 1.0;

    assert(name);
    assert(data);
    assert(size);

    if (mm_open_fp(&mf, sOpen(name, "rb", FT_AUDIO)) < 0) {
        return -1;
    }

    if (mm_audio_info(&mf, &channels, &rate) < 0) {
        CWARNING3(audio, "no audio data in file `%s'", name);
        mm_close(&mf);
        return -1;
    }

    if (channels != 1 || rate != 11025) {
        CERROR3(audio, "file `%s' should be mono, 11025Hz", name);
        mm_close(&mf);
        return -1;
    }

    if (!*data) {
        *data = (char *)xmalloc(*size = def_size);
    }

    while (0 < (read = mm_decode_audio(&mf,
                                       *data + offset, *size - offset))) {
        offset += read;

        if (*size <= offset) {
            *data = (char *)xrealloc(*data, *size *= 2);
        }
    }

    mm_close(&mf);

    CDEBUG4(audio, "loading file `%s' took %5.4f seconds",
            name, get_time() - start);

    return offset;
}