/***************************************************************************
 *   Copyright (C) 2011 by Andreas Frisch                                  *
 *   fraxinas@opendreambox.org                                             *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

// gcc -Wall -g `pkg-config gstreamer-0.10 --cflags --libs` reverseseektest.c -oreverseseektest

#include <gst/gst.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <linux/dvb/dmx.h>
#include <linux/dvb/video.h>
#include <fcntl.h>
#include <string.h>
#include <glib.h>
// #include <mcheck.h>

GST_DEBUG_CATEGORY (rs_debug);
#define GST_CAT_DEFAULT rs_debug

#define CLOCK_BASE 9LL
#define CLOCK_FREQ (CLOCK_BASE * 10000)

#define MPEGTIME_TO_GSTTIME(time) (gst_util_uint64_scale ((time), \
            GST_MSECOND/10, CLOCK_BASE))
#define GSTTIME_TO_MPEGTIME(time) (gst_util_uint64_scale ((time), \
            CLOCK_BASE, GST_MSECOND/10))
#define TIME_TO_STR(mytimestamp) g_strdup_printf("%"GST_TIME_FORMAT, GST_TIME_ARGS(mytimestamp))

typedef struct _App App;

struct _App
{
  GstElement *pipeline;
  GMainLoop *loop;
  int current_segment;
  gfloat rate1;
  gfloat rate2;
};

App s_app;

#if 1
static gboolean do_seek (gpointer data)
{
  App *app = data;
  static int state = -1;
  GstFormat fmt = GST_FORMAT_TIME;
  GstSeekFlags flags = 0;
  gfloat rate = 1.0;
  int ret;
  GstEvent *s_event = GST_EVENT_UNKNOWN;
  gint64 pos, len;

  GST_INFO ("do_seek... %i", 0);
  flags |= GST_SEEK_FLAG_FLUSH;
//   flags |= GST_SEEK_FLAG_ACCURATE;
//   flags |= GST_SEEK_FLAG_KEY_UNIT;
//   flags |= GST_SEEK_FLAG_SKIP;
//   flags |= GST_SEEK_FLAG_SEGMENT;
  
  gst_element_query_position ((app->pipeline), &fmt, &pos);
  gst_element_query_duration(app->pipeline, &fmt, &len);
  
  if (state == -1)
    s_event = gst_event_new_seek ((gdouble)rate, GST_FORMAT_TIME, (GstSeekFlags)flags, GST_SEEK_TYPE_SET, pos+GST_SECOND*(240), GST_SEEK_TYPE_SET, len);
  else
  {
  if (state % 2 == 0)
    rate = app->rate1; 
  else
    rate = app->rate2; 
 
  g_print ("****************do_seek::initial %i gst_element_query_position = %s rate = %f (len=%s)\n", state, TIME_TO_STR(pos), rate, TIME_TO_STR(len));

  if ( rate > 0 )
    s_event = gst_event_new_seek ((gdouble)rate, GST_FORMAT_TIME, (GstSeekFlags)flags, GST_SEEK_TYPE_NONE, -1, GST_SEEK_TYPE_SET, len);

  else 
    s_event = gst_event_new_seek ((gdouble)rate, GST_FORMAT_TIME, (GstSeekFlags)flags, GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_SET, pos);
  }
  ret = gst_element_send_event ( GST_ELEMENT (app->pipeline), s_event);
	
  gst_element_query_position ((app->pipeline), &fmt, &pos);
  g_print
      ("do_seek::seek rate %f command returned %i. new gst_element_query_position = %s\n", rate, 
      ret, TIME_TO_STR(pos));

  state++;
  return TRUE;
}
#endif

static gboolean
bus_message (GstBus * bus, GstMessage * message, App * app)
{
  gchar *sourceName;
  GstObject *source;
  gchar *string;

  if (!message)
    return FALSE;
  source = GST_MESSAGE_SRC (message);
  if (!GST_IS_OBJECT (source))
    return FALSE;
  sourceName = gst_object_get_name (source);

  if (gst_message_get_structure (message))
    string = gst_structure_to_string (gst_message_get_structure (message));
  else
    string = g_strdup (GST_MESSAGE_TYPE_NAME (message));
#if 1
  if (GST_MESSAGE_TYPE(message) != GST_MESSAGE_TAG)
    g_print ("gst_message from %s: %s\n", sourceName, string);
#endif
  g_free (string);

  switch (GST_MESSAGE_TYPE (message)) {
    case GST_MESSAGE_ERROR:
    {
      GError *gerror;
      gchar *debug;

      gst_message_parse_error (message, &gerror, &debug);
      gst_object_default_error (GST_MESSAGE_SRC (message), gerror, debug);
      g_error_free (gerror);
      g_free (debug);

      g_main_loop_quit (app->loop);
      break;
    }
    case GST_MESSAGE_WARNING:
    {
      GError *gerror;
      gchar *debug;

      gst_message_parse_warning (message, &gerror, &debug);
      gst_object_default_error (GST_MESSAGE_SRC (message), gerror, debug);
      g_error_free (gerror);
      g_free (debug);

//       g_main_loop_quit (app->loop);
      break;
    }
    case GST_MESSAGE_SEGMENT_DONE:
    {
      GST_DEBUG ("GST_MESSAGE_SEGMENT_DONE!!!");
//       do_seek (app);
      break;
    }
    case GST_MESSAGE_EOS:
      g_message ("received EOS");
      g_main_loop_quit (app->loop);
      break;
    case GST_MESSAGE_ASYNC_DONE:
    {
       if(GST_MESSAGE_SRC(message) != GST_OBJECT(app->pipeline))
	 break;
       break;
    }
    default:
      break;
  }
  return TRUE;
}

int
main (int argc, char *argv[])
{
  App *app = &s_app;
  GstBus *bus;
  const gchar *nano_str;
  guint major, minor, micro, nano;

  app->current_segment = 0;

  gst_init (NULL, NULL);
  GST_DEBUG_CATEGORY_INIT (rs_debug, "reverseseektest",
      GST_DEBUG_BOLD | GST_DEBUG_FG_YELLOW | GST_DEBUG_BG_BLUE,
      "playbin2 reverse seek testcase");

  if (argc < 4) {
    g_print ("usage: %s <uri> <first seek rate> <second seek rate>\n", argv[0]);
    return -1;
  }

  app->rate1 = g_strtod(argv[2], NULL);
  app->rate2 = g_strtod(argv[3], NULL);

  gst_version (&major, &minor, &micro, &nano);

  if (nano == 1)
    nano_str = "(CVS)";
  else if (nano == 2)
    nano_str = "(Prerelease)";
  else
    nano_str = "";

  printf ("%s is linked against GStreamer %d.%d.%d %s for dreambox 8000\n",
      argv[0], major, minor, micro, nano_str);

  /* create a mainloop to get messages */
  app->loop = g_main_loop_new (NULL, TRUE);

  app->pipeline = gst_element_factory_make ("playbin2", NULL);
  
//   GstElement *videosink = gst_element_factory_make ("fakesink", "videosink");
//   GstElement *audiosink = gst_element_factory_make ("fakesink", "audiosink");
// 
//   g_object_set (G_OBJECT (app->pipeline), "audio-sink", audiosink, NULL);
//   g_object_set (G_OBJECT (app->pipeline), "video-sink", videosink, NULL);

  g_assert (app->pipeline);

  bus = gst_pipeline_get_bus (GST_PIPELINE (app->pipeline));

  /* add watch for messages */
  gst_bus_add_watch (bus, (GstBusFunc) bus_message, app);

  /* set to read from appsrc */
  g_object_set (app->pipeline, "uri", argv[1], NULL);
  
  g_timeout_add (10000, do_seek, app);

  /* go to playing and wait in a mainloop. */
//      mtrace();
  gst_element_set_state (app->pipeline, GST_STATE_PLAYING);

  /* this mainloop is stopped when we receive an error or EOS */
  g_main_loop_run (app->loop);

  g_message ("stopping");

  gst_element_set_state (app->pipeline, GST_STATE_NULL);

  gst_object_unref (bus);
  g_main_loop_unref (app->loop);
//      muntrace();
  return 0;
}
