/*
* gcc ko.c -o ko `pkg-config --cflags --libs gstreamer-1.0`
 */
#include <gst/gst.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define DEVICE "/dev/video0"

int main(int argc, char *argv[]) {
    GstElement *pipeline;
    GstState state, pending;
    GstBus *bus;
    GstMessage *msg;
    int i = 0;
    int gstPipInterval = 1;
    char *pipelinestr;

    /* Initialize GStreamer */
    gst_init (&argc, &argv);

    if(argc == 2){
      gstPipInterval = atoi(argv[1]);
      printf("Test interval: %d\n", gstPipInterval);
    }
    else {
      printf("Insert test interval: ");
      scanf("%d", &gstPipInterval);
    }

    //GST 1.0
    //pipelinestr = "v4l2src name=gc-v4l2-src device="DEVICE" ! video/x-raw,framerate=24/1,width=640,height=480 ! xvimagesink";
    //GST 0.10
    pipelinestr = "v4l2src name=gc-v4l2-src device="DEVICE" ! video/x-raw-yuv,framerate=24/1,width=800,height=600 ! xvimagesink";
    printf("%s", pipelinestr);

    while(1) {
      printf(" ---> %d\n", i++);
        /* Build the pipeline */
        pipeline = gst_parse_launch (pipelinestr, NULL);


        if (pipeline == NULL) {
            printf("Error gen pipeline\n");
            return -1;
        }

        /* Start playing */
        gst_element_set_state (pipeline, GST_STATE_PLAYING);

        /* Wait until error or EOS */
        bus = gst_element_get_bus (pipeline);
        msg = gst_bus_timed_pop_filtered (bus, gstPipInterval * GST_SECOND, GST_MESSAGE_ERROR | GST_MESSAGE_EOS);

        if (msg != NULL) {
            printf("Error waiting 1 sec\n");
            return -1;

        }

        gst_element_send_event (pipeline, gst_event_new_eos ());
        msg = gst_bus_timed_pop_filtered (bus, GST_CLOCK_TIME_NONE, GST_MESSAGE_ERROR | GST_MESSAGE_EOS);

        /* Free resources */
        if (msg != NULL)
            gst_message_unref (msg);
        gst_object_unref (bus);
        gst_element_set_state (pipeline, GST_STATE_NULL);
        gst_element_get_state (pipeline, &state, &pending, GST_CLOCK_TIME_NONE);

        gst_object_unref (pipeline);
    }
    return 0;
}
