#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <gst/gst.h>

#define PRINTF(format, ...) {fprintf(stderr, format, ##__VA_ARGS__);}

int main(int argc, char **argv) {
	char buf[2048];
	FILE *status;
	status = fopen("/proc/self/status", "r");
	while(fgets(buf, 1024, status))
		if (strstr(buf, "VmSize") != NULL)
			PRINTF("%s", buf);
	fclose(status);

	gst_init(&argc, &argv);

	GstElement *gstPipeline;

	PRINTF("Gstreamer Playback: Starting\n");
	gstPipeline = gst_parse_launch("videotestsrc num-buffers=10 ! fakesink", NULL);

	gst_element_set_state(gstPipeline, GST_STATE_PLAYING);
	GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE(gstPipeline));
	while (1) {
		GstMessage *message = gst_bus_timed_pop(bus, 10 * 1000 * 1000);
		if (message) {
			if (GST_MESSAGE_TYPE(message) == GST_MESSAGE_EOS) {
				PRINTF("Gstreamer Playback: receiving eos and stop\n");
				gst_message_unref(message);
				break;
			} else if (GST_MESSAGE_TYPE(message) == GST_MESSAGE_ERROR) {
				PRINTF("Gstreamer Playback: receiving error\n");
				gst_message_unref(message);
				break;
			} else {
				//PRINTF("Gstreamer Playback: %s\n", GST_MESSAGE_TYPE_NAME(message));
				gst_message_unref(message);
			}
		}
	}

	PRINTF("Gstreamer Playback: ending\n");

	if (bus) gst_object_unref(bus);
	gst_element_set_state(gstPipeline, GST_STATE_NULL);

	if (gstPipeline) gst_object_unref(gstPipeline);

	PRINTF("Gstreamer Playback: post cleaning\n");

	usleep(1000 * 1000);

	status = fopen("/proc/self/status", "r");
	while(fgets(buf, 1024, status))
		if (strstr(buf, "VmSize") != NULL)
			PRINTF("%s", buf);
	fclose(status);
}
