#include <gst/gst.h>

GstElement *pipeline, *source, *sink;

static void
new_pad (GstElement *element,
	 GstPad     *pad,
	 gpointer    data)
{
  GstPad *sinkpad;
  /* We can now link this pad with the audio decoder */
  g_print ("Dynamic pad created, linking source/sink\n");

  sinkpad = gst_element_get_pad (sink, "sink");
  gst_pad_link (pad, sinkpad);

  gst_object_unref (sinkpad);
}

static GstElement *
create_pipeline(gchar *location)
{
  GstElement *pipeline;

  pipeline = gst_pipeline_new ("pipeline");
  source = gst_element_factory_make ("rtspsrc", "rtsp-source");
	sink = gst_element_factory_make ("fakesink", "fake-sink");
  
  if (!pipeline || !source || !sink) {
    g_print ("One element could not be created\n");
    return NULL;
  }

  g_object_set (G_OBJECT (source), "location", location, NULL);
	gst_bin_add_many (GST_BIN (pipeline), source, sink, NULL);

	g_signal_connect (source, "pad-added", G_CALLBACK (new_pad), NULL);

  return pipeline;
}

int
main (int   argc,
      char *argv[])
{
  GMainLoop *loop;
  int i;

  /* initialize GStreamer */
  gst_init (&argc, &argv);
  loop = g_main_loop_new (NULL, TRUE);

  /* check input arguments */
  if (argc < 2) {
    g_print ("Usage: %s <rtsp url>\n", argv[0]);
    return -1;
  }

  fprintf(stderr, "playing location = '%s'\n", argv[1]);fflush(stderr);

  for (i = 0; i < 100000; i++) {
    pipeline = create_pipeline(argv[1]);

    gst_element_set_state (pipeline, GST_STATE_PLAYING);

    g_usleep(2 * G_USEC_PER_SEC);

    gst_element_set_state (pipeline, GST_STATE_NULL);
    gst_object_unref (GST_OBJECT (pipeline));
  }

  return 0;
}
