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


static gboolean
bus_call (GstBus     *bus,
          GstMessage *msg,
          gpointer    data)
{
  GMainLoop *loop = (GMainLoop *) data;

  switch (GST_MESSAGE_TYPE (msg)) {

    case GST_MESSAGE_EOS:
      g_print ("End of stream\n");
      g_main_loop_quit (loop);
      break;

    case GST_MESSAGE_ERROR: {
      gchar  *debug;
      GError *error;

      gst_message_parse_error (msg, &error, &debug);
      g_free (debug);

      g_printerr ("Error: %s\n", error->message);
      g_error_free (error);

      g_main_loop_quit (loop);
      break;
    }
    default:
      break;
  }

  return TRUE;
}


static void
on_pad_added (GstElement *element,
              GstPad     *pad,
              gpointer    data)
{
  GstPad *sinkpad;
  GstElement *decoder = (GstElement *) data;

  g_print (" [linking] .... ");

  sinkpad = gst_element_get_static_pad (decoder, "sink");

  gst_pad_link (pad, sinkpad);

  gst_object_unref (sinkpad);
}


void
wait_for_state_change(GstElement *pipeline) {
	  GstState *state = NULL, *pending = NULL;
	  gst_element_get_state(pipeline, state, pending, GST_CLOCK_TIME_NONE);
}

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

  GstElement *pipeline, *source, *depay, *parser, *decoder, *sink;
  GstBus *bus;

  /* Initialisation */
  gst_init (&argc, &argv);

  loop = g_main_loop_new (NULL, FALSE);


  /* Check input arguments */
  if (argc != 2) {
    g_printerr ("Usage: %s rtsp url\n", argv[0]);
    return -1;
  }

  /* Create gstreamer elements */
  pipeline = gst_pipeline_new ("rtsp-player");
  source   = gst_element_factory_make ("rtspsrc",       "rtsp-source");
  depay  = gst_element_factory_make ("rtph264depay",      "depay");
  parser  = gst_element_factory_make ("h264parse",     "h264-parser");
  decoder     = gst_element_factory_make ("ffdec_h264",  "h264-decoder");
  sink     = gst_element_factory_make ("fakesink", 		"fake-sink");

  if (!pipeline || !source || !depay || !parser || !decoder || !sink) {
    g_printerr ("One element could not be created. Exiting.\n");
    return -1;
  }

  /* Set up the pipeline */

  /* we set the input filename to the source element */
  g_object_set (G_OBJECT (source), "location", argv[1], NULL);
  g_object_set (G_OBJECT (source), "protocols", 4, NULL);
  g_object_set (G_OBJECT (depay), "access-unit", TRUE, NULL);
  g_object_set (G_OBJECT (parser), "split-packetized", TRUE, NULL);
  g_object_set (G_OBJECT (sink), "sync", TRUE, NULL);

  /* we add a message handler */
  bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
  gst_bus_add_watch (bus, bus_call, loop);
  gst_object_unref (bus);

  /* we add all elements into the pipeline */
  /* file-source | ogg-demuxer | vorbis-decoder | converter | alsa-output */
  gst_bin_add_many (GST_BIN (pipeline),
                    source, depay, parser, decoder, sink, NULL);

  /* we link the elements together */
  //gst_element_link (source, depay);
  gst_element_link_many (depay, parser, decoder, sink, NULL);
  g_signal_connect (source, "pad-added", G_CALLBACK (on_pad_added), depay);


  /* Set the pipeline to "playing" state*/
  g_print ("Now playing: %s\n", argv[1]);


  int i;
  for (i=0; i<100; ++i) {
	  printf(" >>> %d\n",i);
	  printf(" Change state to PLAYING .... ");
	  gst_element_set_state (pipeline, GST_STATE_PLAYING);
	  wait_for_state_change(pipeline);
	  printf("[ OK ]\n");
	  sleep(3);
	  printf(" Change state to NULL .... ");
	  gst_element_set_state (pipeline, GST_STATE_NULL);
	  wait_for_state_change(pipeline);
	  printf("[ OK ]\n");
	  sleep(2);
  }


  g_print ("Running...\n");
  g_main_loop_run (loop);

  g_print ("Returned, stopping playback\n");
  gst_element_set_state (pipeline, GST_STATE_NULL);

  g_print ("Deleting pipeline\n");
  gst_object_unref (GST_OBJECT (pipeline));

  return 0;
}
