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

void
close_func (GstElement *pipeline)
{
	usleep ((rand() / RAND_MAX) * 100000);
	gst_element_set_state (pipeline, GST_STATE_NULL);
}

gint
main (gint argc, gchar * argv[])
{
	GstElement *src, *queue, *sink;
	GstElement *pipeline;
	GstQuery *query;
	GstPad *pad;
	gint bytes;
	GThread *thread;

	gst_init (&argc, &argv);

	src = gst_element_factory_make ("audiotestsrc", NULL);
	queue = gst_element_factory_make ("queue", NULL);
	sink = gst_element_factory_make ("fakesink", NULL);

	g_object_set (queue, "leaky", 2, "min-threshold-bytes", 10000, NULL);

	pad = gst_element_get_static_pad (queue, "sink");
	query = gst_query_new_allocation (NULL, FALSE);

	pipeline = gst_pipeline_new (NULL);

	gst_bin_add_many (GST_BIN (pipeline), src, queue, sink, NULL);
	gst_element_link_many (src, queue, sink, NULL);

	while (1) {
		gst_element_set_state (pipeline, GST_STATE_PLAYING);
		thread = g_thread_new ("CLOSE", (GThreadFunc)close_func, pipeline);
		gst_pad_query (pad, query);
		g_thread_join (thread);
		g_print ("Restarting\n");
	}
}
