/***************************************************************************
 *   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` playbin2segmentseek.c -oplaybin2segmentseek

#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 (playbin2segmentseek_debug);
#define GST_CAT_DEFAULT playbin2segmentseek_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))


typedef struct _App App;

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

App s_app;

static gboolean
do_seek (App * app)
{
  gint64 in_pos, out_pos;
  gfloat rate = 1.0;
  GstFormat fmt = GST_FORMAT_TIME;
  GstSeekFlags flags = 0;
  int ret;

  GST_INFO ("do_seek...");
  flags |= GST_SEEK_FLAG_FLUSH;
  flags |= GST_SEEK_FLAG_ACCURATE;
//   flags |= GST_SEEK_FLAG_KEY_UNIT;
  flags |= GST_SEEK_FLAG_SEGMENT;

  gst_element_query_position ((app->pipeline), &fmt, &in_pos);
  GST_DEBUG ("do_seek::initial gst_element_query_position = %lld ms",
      in_pos / 1000000);

  in_pos = MPEGTIME_TO_GSTTIME (5400000);
  GST_DEBUG ("do_seek::in_time for segment = %lld ms", in_pos / 1000000);

  out_pos = MPEGTIME_TO_GSTTIME (9000000);
  GST_DEBUG ("do_seek::out_time for segment = %lld ms", out_pos / 1000000);

  ret = gst_element_seek ((app->pipeline), rate, GST_FORMAT_TIME, flags,
      GST_SEEK_TYPE_SET, in_pos, GST_SEEK_TYPE_SET, out_pos);

  gst_element_query_position ((app->pipeline), &fmt, &in_pos);
  GST_DEBUG
      ("do_seek::seek command returned %i. new gst_element_query_position = %lld ms",
      ret, in_pos / 1000000);

  app->current_segment++;

  return ret;
}

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

  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
  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;
    default:
      break;
  }
  gst_element_get_state (app->pipeline, &current_state, NULL, 0);
  if (app->current_segment == 0 && current_state == GST_STATE_PLAYING)
    do_seek (app);
  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 (&argc, &argv);

  GST_DEBUG_CATEGORY_INIT (playbin2segmentseek_debug, "playbin2segmentseek",
      GST_DEBUG_BOLD | GST_DEBUG_FG_YELLOW | GST_DEBUG_BG_BLUE,
      "mpeg-ts segment seek testcase");

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


  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);
  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);

  /* 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;
}
