// a little hack by Chris MacGregor (www.cybermato.com) to help determine what
// format to tell vlc (www.videolan.org) to use for a USB webcam on Linux.

#include <sys/ioctl.h>
#include <linux/videodev.h>

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

// This table was taken from the vlc sources (v4l.c) and restructured
// slightly.

struct format_to_fourcc
{
    int format;
    const char * fourcc;
};

static struct format_to_fourcc format_to_fourcc[] =
{
    { VIDEO_PALETTE_GREY, "GREY" },
    { VIDEO_PALETTE_HI240, "I240" },
    { VIDEO_PALETTE_RGB565, "RV16" },
    { VIDEO_PALETTE_RGB555, "RV15" },
    { VIDEO_PALETTE_RGB24, "RV24" },
    { VIDEO_PALETTE_RGB32, "RV32" },
    { VIDEO_PALETTE_YUV422, "I422" },
    { VIDEO_PALETTE_YUYV, "YUYV" },
    { VIDEO_PALETTE_UYVY, "UYVY" },
    { VIDEO_PALETTE_YUV420, "I42N" },
    { VIDEO_PALETTE_YUV411, "I41N" },
    { VIDEO_PALETTE_RAW, "GRAW" },
    { VIDEO_PALETTE_YUV422P, "I422" },
    { VIDEO_PALETTE_YUV420P, "I420" },
    { VIDEO_PALETTE_YUV411P, "I411" },
    { 0, 0 }
};

int main (int argc, const char * argv [])
{
    const char * usage_message
        = "Usage: %s /dev/video  (or whatever device you wish to query)\n";

    if (argc != 2)
    {
        printf (usage_message, argv[0]);
        return 1;
    }

    const char * devname = argv[1];

    int fd = open (devname, O_RDWR);
    if (fd < 0)
    {
        perror (devname);
        printf (usage_message, argv[0]);
        return 1;
    }

    struct video_picture vpic;
    if (ioctl (fd, VIDIOCGPICT, &vpic) < 0)
    {
        perror ("ioctl VIDIOCGPICT");
        close (fd);
        return 1;
    }

    const char * fourcc = "(unknown)";
    struct format_to_fourcc * fptr = format_to_fourcc;
    while (fptr->fourcc)
    {
        if (fptr->format == vpic.palette)
        {
            fourcc = fptr->fourcc;
            break;
        }
        ++fptr;
    }
    printf ("Current format is %d, fourcc is %s\n",
            vpic.palette, fourcc);

    close (fd);
    return 0;
}

