#include <libavdevice/avdevice.h>
#include <libavformat/avformat.h>

/* compile with
   cc v4l2_testcase.c -o v4l2_testcase `pkg-config --cflags --libs libavdevice libavformat` */

#define RETURN_IF_FAIL(A, M, ...) if (!(A)) { fprintf(stderr, M "\n", ##__VA_ARGS__); return 1; }

int main()
{
    av_register_all();
    avdevice_register_all();

    int i;
    for (i = 0; i < 20; ++i) {
        const char *const format_str = "video4linux2";
        AVInputFormat *file_iformat = av_find_input_format(format_str);
        RETURN_IF_FAIL(file_iformat, "Could not find format \"%s\"", format_str);

        AVDictionary *options = NULL;
        // Open video file
        printf("Opening input\n");
        AVFormatContext *input_ctx = avformat_alloc_context();
        const char * const dev = "/dev/video0";
        int ret = avformat_open_input(&input_ctx, dev, file_iformat, NULL);
        RETURN_IF_FAIL(ret == 0, "Could not open input \"%s\"", dev);

        if (input_ctx)
            avformat_close_input(&input_ctx);
    }

    return 0;
}
