#include <gst/gst.h>

static gdouble rate = 1.0; 

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 gboolean
change_rate_timeout(GstElement *pipe)
{
	if (rate == 1.0){
		rate = 4.0;
	} else {
		rate = 1.0;
	}
	g_print("try to change rate to %f\n",rate);
	if (gst_element_seek(pipe,rate,GST_FORMAT_TIME,GST_SEEK_FLAG_NONE,GST_SEEK_TYPE_NONE,GST_CLOCK_TIME_NONE,GST_SEEK_TYPE_NONE,GST_CLOCK_TIME_NONE)){
		g_print("change rate ok\n");
	} else {
		g_print("change rate error\n");
	}
	return TRUE;
}


int
main (int argc, char *argv[])
{
  signal (SIGPIPE, SIG_IGN);
  GMainLoop *loop;
  gst_init (&argc, &argv);
  
  GstElement *pipe;
  GstBus *bus; 
  guint tout;
  loop = g_main_loop_new (NULL, FALSE);

  //pipe = gst_parse_launch ("filesrc location=/var/www/test.mkv ! matroskademux ! h264parse ! avdec_h264 ! xvimagesink",NULL);
  pipe = gst_parse_launch ("souphttpsrc location=http://195.250.34.59/temp/test.mkv ! matroskademux ! h264parse ! avdec_h264 ! xvimagesink",NULL);
  bus = gst_pipeline_get_bus (GST_PIPELINE (pipe));
  gst_bus_add_watch (bus, bus_call, loop);
  gst_object_unref (bus);
 
  tout = g_timeout_add_seconds (5, (GSourceFunc) change_rate_timeout, pipe);
 
  gst_element_set_state (pipe, GST_STATE_PLAYING);
  
  g_print ("Starting main loop ...\n");
  g_main_loop_run (loop);
  gst_element_set_state (pipe, GST_STATE_NULL);
  g_object_unref (pipe);
  g_source_remove (tout);
  g_print ("Application end\n");

  return 0;
}
