/* Eloi Bail : eloi.bail<at>savoirfairelinux.com
 *
 * Simple test showing that reverve playback is not working with videotestsrc
 * - Reproduced on 0.10 SDK and 1.0 HEAD
 * - Working fine with audiotestsrc
 * - audiotestsrc and videotestsrc are both used for gap on Gstreamer Editing Services
*/

#include <gst/gst.h>
/* comment it if you want to test audiotestsrc */
#define TEST_VIDEOTEST

GstElement *pipeline, *videotestsrc, *sink;
GstBus *bus;
GMainLoop * main_loop;
gdouble rate = 1.0;


static gboolean 
cb_changerate(gpointer data)
{
  GstEvent *seek_event;
  gint64 position;
  GstFormat format = GST_FORMAT_TIME;

  if (!gst_element_query_position (GST_ELEMENT (pipeline), &format, &position)) {
    g_printerr ("Unable to retrieve current position.\n");
    return;
  }
  rate = -rate;
  if(rate > 0.0){

    g_print("Forward \n"); 
    seek_event =
        gst_event_new_seek (rate, GST_FORMAT_TIME,
        (GstSeekFlags) (GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE), GST_SEEK_TYPE_SET,
        position , GST_SEEK_TYPE_SET, -1);
  }else{
    g_print("Backward \n"); 
    seek_event =
        gst_event_new_seek (rate, GST_FORMAT_TIME,
        (GstSeekFlags) (GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE), GST_SEEK_TYPE_SET,
        0 , GST_SEEK_TYPE_SET, position);

  }
  gst_element_send_event (sink, seek_event);
  return TRUE;
}


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



  gst_init (&argc, &argv);

  pipeline = gst_pipeline_new ("test_pipeline");
#ifdef TEST_VIDEOTEST
  g_print("Checking reverse playback with videotestsrc \n");
  videotestsrc =  gst_parse_bin_from_description ("timeoverlay ! videotestsrc", TRUE,NULL);
  sink = gst_element_factory_make ("autovideosink", "sink");
#else
  g_print("Checking reverse playback with audiotestsrc \n");
  videotestsrc = gst_element_factory_make ("audiotestsrc", "myvideotestsrc");
  sink = gst_parse_bin_from_description ("autoaudiosink ", TRUE, NULL);
#endif
  if(!(pipeline && videotestsrc && sink)){
    g_printerr("some element can not be created \n");
    if(!videotestsrc)
      g_printerr("videotestsrc NULL !!! \n");
    return -1;
  }

  gst_bin_add_many (GST_ELEMENT(pipeline), videotestsrc, sink, NULL);
  gst_element_link_many (videotestsrc, sink, NULL);


  g_print("Setting pipeline to playing \n");
  
  gst_element_set_state (GST_PIPELINE (pipeline), GST_STATE_PLAYING);
 
  main_loop = g_main_loop_new (NULL, FALSE);
  bus = gst_element_get_bus (GST_ELEMENT (pipeline));
  /* Random call each 20 sec */
  g_timeout_add_seconds(rand() % 20, cb_changerate,NULL);
  /* Create a GLib Main Loop and set it to run */
  g_main_loop_run (main_loop);
 }
