Showing posts with label ffmpeg. Show all posts
Showing posts with label ffmpeg. Show all posts

Friday, November 29, 2013

Add current time to ffmpeg segment muxer filename

The function below should replace the existing one in libavformat/utils.c. It is for libav 0.8.9 version so it might not work on other versions.

Usage: add %t to the filename pattern, it gets replaced with the date and time in format "YYYY-MM-DD_hh-mm-ss".


int av_get_frame_filename(char *buf, int buf_size,
                          const char *path, int number)
{
    const char *p;
    char *q, buf1[30], c;
    int nd, len, percentd_found, percentt_found;
    struct timeval tv;

    q = buf;
    p = path;
    percentd_found = 0;
    percentt_found = 0;
    for(;;) {
        c = *p++;
        if (c == '\0')
            break;
        if (c == '%') {
            do {
                nd = 0;
                while (isdigit(*p)) {
                    nd = nd * 10 + *p++ - '0';
                }
                c = *p++;
            } while (isdigit(c));

            switch(c) {
            case '%':
                goto addchar;
            case 'd':
                if (percentd_found)
                    goto fail;
                percentd_found = 1;
                snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
                len = strlen(buf1);
                if ((q - buf + len) > buf_size - 1)
                    goto fail;
                memcpy(q, buf1, len);
                q += len;
                break;
            case 't':

                if (percentt_found)
                    goto fail;
                percentt_found = 1;

                gettimeofday(&tv, NULL);
                strftime(buf1, sizeof(buf1), "%Y-%m-%d_%H-%M-%S", localtime(&tv.tv_sec));
                len = strlen(buf1);
                if ((q - buf + len) > buf_size - 1)
                    goto fail;
                memcpy(q, buf1, len);
                q += len;
                break;
            default:
                goto fail;
            }
        } else {
        addchar:
            if ((q - buf) < buf_size - 1)
                *q++ = c;
        }
    }
    if (!percentd_found && !percentt_found)
        goto fail;
    *q = '\0';
    return 0;
 fail:
    *q = '\0';
    return -1;
}