/* vim: set sw=2: -*- Mode: C; tab-width: 2; indent-tabs-mode: t; c-basic-offset: 2; c-indent-level: 2 -*- */
/* GStreamer MythTV Plug-in
 * Copyright (C) <2006> Rosfran Borges <rosfran.borges@indt.org.br>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Library General Public License for more 
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "gstmythtvsrc.h"
#include "myth_file_transfer.h"
#include "myth_livetv.h"

#include <gmyth/gmyth_socket.h>
#include <gmyth/gmyth_tvchain.h>

#include <string.h>
#include <unistd.h>

GST_DEBUG_CATEGORY_STATIC (mythtvsrc_debug);
#define GST_CAT_DEFAULT mythtvsrc_debug

#define GST_MYTHTV_ID_NUM		1

#define MYTHTV_VERSION_DEFAULT		30

#define MYTHTV_TRANSFER_MAX_WAITS	100

#define MYTHTV_TRANSFER_MAX_BUFFER	( 32*1024  )

/* 4*1024 ??? */
#define MAX_READ_SIZE                   ( 16*1024 )

#define ENABLE_TIMING_POSITION		1

/* stablish a maximum iteration value to the IS_RECORDING message */
static guint wait_to_transfer = 0;

static const GstElementDetails gst_mythtv_src_details =
GST_ELEMENT_DETAILS ("MythTV client source",
    "Source/Network",
    "Control and receive data as a client over the network via raw socket connections using the MythTV protocol",
    "Rosfran Borges <rosfran.borges@indt.org.br>");

static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
    GST_PAD_SRC,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS_ANY);

static GstTask *update_size_task = NULL;

static GStaticRecMutex update_size_mutex = G_STATIC_REC_MUTEX_INIT;

enum
{
  PROP_0,
  PROP_LOCATION,
  PROP_URI,
#ifndef GST_DISABLE_GST_DEBUG
  PROP_MYTHTV_DBG,
#endif
  PROP_MYTHTV_VERSION,
  PROP_MYTHTV_LIVE,
  PROP_MYTHTV_LIVEID,
  PROP_MYTHTV_LIVE_CHAINID
};

static void gst_mythtv_src_finalize (GObject * gobject);

static GstFlowReturn gst_mythtv_src_create (GstBaseSrc * psrc,
    guint64 offset, guint size, GstBuffer ** outbuf);
static gboolean gst_mythtv_src_start (GstBaseSrc * bsrc);
static gboolean gst_mythtv_src_stop (GstBaseSrc * bsrc);
static gboolean gst_mythtv_src_get_size (GstBaseSrc * bsrc, guint64 * size);
static gboolean gst_mythtv_src_is_seekable( GstBaseSrc *base_src );

static void gst_mythtv_src_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec);
static void gst_mythtv_src_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec);

static void
gst_mythtv_src_uri_handler_init (gpointer g_iface, gpointer iface_data);

static gboolean
gst_mythtv_src_handle_event (GstPad * pad, GstEvent * event);

  static void
_urihandler_init (GType type)
{
  static const GInterfaceInfo urihandler_info = {
    gst_mythtv_src_uri_handler_init,
    NULL,
    NULL
  };

  g_type_add_interface_static (type, GST_TYPE_URI_HANDLER, &urihandler_info);

  GST_DEBUG_CATEGORY_INIT (mythtvsrc_debug, "mythtvsrc", 0,
      "MythTV src");
}

GST_BOILERPLATE_FULL (GstMythtvSrc, gst_mythtv_src, GstBaseSrc,
    GST_TYPE_BASE_SRC, _urihandler_init);

  static void
gst_mythtv_src_base_init (gpointer g_class)
{
  GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);

  gst_element_class_add_pad_template (element_class,
      gst_static_pad_template_get (&srctemplate));

  gst_element_class_set_details (element_class, &gst_mythtv_src_details);
}

  static void
gst_mythtv_src_class_init (GstMythtvSrcClass * klass)
{
  GObjectClass *gobject_class;
  GstBaseSrcClass *gstbasesrc_class;

  gobject_class = (GObjectClass *) klass;
  gstbasesrc_class = (GstBaseSrcClass *) klass;

  gobject_class->set_property = gst_mythtv_src_set_property;
  gobject_class->get_property = gst_mythtv_src_get_property;
  gobject_class->finalize = gst_mythtv_src_finalize;

  g_object_class_install_property
    (gobject_class, PROP_LOCATION,
     g_param_spec_string ("location", "Location",
       "The location. In the form:"
       "\n\t\t\tmyth://a.com/file.nuv"
       "\n\t\t\tmyth://a.com:23223/file.nuv "
       "\n\t\t\ta.com/file.nuv - default scheme 'myth'",
       "", G_PARAM_READWRITE));

  g_object_class_install_property
    (gobject_class, PROP_URI,
     g_param_spec_string ("uri", "Uri",
       "The location in form of a URI (deprecated; use location)",
       "", G_PARAM_READWRITE));

  g_object_class_install_property
    (gobject_class, PROP_MYTHTV_VERSION,
     g_param_spec_int ("mythtv-version", "mythtv-version",
       "Change Myth TV version",
       26, 30, 26, G_PARAM_READWRITE));

  g_object_class_install_property
    (gobject_class, PROP_MYTHTV_LIVEID,
     g_param_spec_int ("mythtv-live-id", "mythtv-live-id",
       "Change Myth TV version",
       0, 200, GST_MYTHTV_ID_NUM, G_PARAM_READWRITE));

  g_object_class_install_property
    (gobject_class, PROP_MYTHTV_LIVE_CHAINID,
     g_param_spec_string ("mythtv-live-chainid", "mythtv-live-chainid",
       "Sets the Myth TV chain ID (from TV Chain)",
       "", G_PARAM_READWRITE));

  g_object_class_install_property
    (gobject_class, PROP_MYTHTV_LIVE,
     g_param_spec_boolean ("mythtv-live", "mythtv-live",
       "Enable MythTV Live TV content streaming",
       FALSE, G_PARAM_READWRITE));

#ifndef GST_DISABLE_GST_DEBUG
  g_object_class_install_property
    (gobject_class, PROP_MYTHTV_DBG,
     g_param_spec_boolean ("mythtv-debug", "mythtv-debug",
       "Enable MythTV debug messages",
       FALSE, G_PARAM_READWRITE));
#endif

  gstbasesrc_class->start = gst_mythtv_src_start;
  gstbasesrc_class->stop = gst_mythtv_src_stop;
  gstbasesrc_class->get_size = gst_mythtv_src_get_size;
  gstbasesrc_class->is_seekable = gst_mythtv_src_is_seekable;

  gstbasesrc_class->create = gst_mythtv_src_create;

  GST_DEBUG_CATEGORY_INIT (mythtvsrc_debug, "mythtvsrc", 0,
      "MythTV Client Source");
}

  static void
gst_mythtv_src_init (GstMythtvSrc * this, GstMythtvSrcClass * g_class)
{
  this->file_transfer = NULL;

  this->unique_setup = FALSE;

  this->mythtv_version = MYTHTV_VERSION_DEFAULT;

  this->bytes_read = 0;

  this->content_size = -1;
  this->read_offset = 0;

  this->live_tv = FALSE;

  this->user_agent = g_strdup ("mythtvsrc");
  this->mythtv_caps = NULL;    

  gst_base_src_set_live ( GST_BASE_SRC( this ), TRUE );

  gst_pad_set_event_function (GST_BASE_SRC_PAD(GST_BASE_SRC(this)),
      GST_DEBUG_FUNCPTR (gst_mythtv_src_handle_event));

}

  static void
gst_mythtv_src_finalize (GObject * gobject)
{
  GstMythtvSrc *this = GST_MYTHTV_SRC (gobject);

  g_free (this->user_agent);

  if (this->mythtv_caps) {
    gst_caps_unref (this->mythtv_caps);
    this->mythtv_caps = NULL;
  }

  if (this->file_transfer) {
    g_object_unref (this->file_transfer);
    this->file_transfer = NULL;
  }

  if (this->uri_name) {
    g_free (this->uri_name);
  }

  if (this->user_agent) {
    g_free (this->user_agent);
  }

  if ( update_size_task != NULL ) {

    if ( GST_TASK_STATE( update_size_task ) != GST_TASK_STOPPED )
    	gst_task_stop( update_size_task );

    gst_object_unref( update_size_task );

    update_size_task = NULL;

  }

  G_OBJECT_CLASS (parent_class)->finalize (gobject);
}

#if 0
  static guint
do_seek( GstMythtvSrc *src, guint64 offset, guint size, GstBuffer *outbuf )
{
  guint64 off_uint64 = myth_file_transfer_seek(src->file_transfer, offset, 1);

  g_print( "[%s] Call MythTV SEEK with offset %llu, got a new one %llu...\n", __FUNCTION__, 
      offset, off_uint64 );

  return off_uint64;

}
#endif

  static guint
do_read_request_response (GstMythtvSrc * src, guint64 offset, guint size, GstBuffer * outbuf)
{
  guint read = 0;
  guint sizetoread = size; //GST_BUFFER_SIZE (outbuf);

  g_print( "[%s] Reading %d bytes...\n", __FUNCTION__, sizetoread ); 

  /* Loop sending the request:
   * Retry whilst authentication fails and we supply it. */

  ssize_t len = 0;

  //GST_OBJECT_LOCK(src);

  while ( sizetoread > 0 ) {

    len = myth_file_transfer_read( src->file_transfer,
	GST_BUFFER_DATA (outbuf) + read, sizetoread, TRUE );

    if ( len > 0 ) {
      read += len;
      src->read_offset += read;
      sizetoread -= len;
    } else if ( len < 0 ) {
      goto done;
    }
    else if ( len == 0 ) {
      if ( src->live_tv == FALSE )
	goto done;
      else
	goto eos;

    }

    if ( len == sizetoread )
      break;

  }

  if ( read > 0 ) {
    src->bytes_read += read;

    GST_BUFFER_SIZE (outbuf) = read;
  } else if ( read <= 0 || len <= 0 ) {
    if ( src->live_tv == FALSE )
      goto eos;
    else
      goto done;
  }
  //GST_BUFFER_OFFSET (outbuf) = src->read_offset;

  g_print( "[%s]\tBYTES READ (actual) = %d, BYTES READ (cumulative) = %llu, "\
      "OFFSET = %llu, CONTENT SIZE = %llu.\n", __FUNCTION__, read, src->bytes_read, 
      src->read_offset, src->content_size );

  //GST_OBJECT_UNLOCK(src);

  if ( len < 0 ) {
    read = len;
    if ( src->live_tv == FALSE ) 
      goto eos;
    else
      goto done;
  }

  if ( src->bytes_read < src->content_size )
    goto done;

eos:
  //GST_OBJECT_UNLOCK(src);

  src->eos = TRUE;
done:
  //GST_OBJECT_UNLOCK(src);

  return read;
}

  static GstFlowReturn
gst_mythtv_src_create ( GstBaseSrc * psrc, guint64 offset, 
    guint size, GstBuffer **outbuf )
{
  GstMythtvSrc *src;
  GstFlowReturn ret = GST_FLOW_OK;
  guint read = 0;

  src = GST_MYTHTV_SRC (psrc);

  //src->do_start = FALSE;
  src->do_start = FALSE;
  gst_task_join ( update_size_task );

  g_print( "[%s]\tBUFFER OFFSET = %llu, BUFFER SIZE = %d.\n", __FUNCTION__, offset, 
      size );

  /* The caller should know the number of bytes and not read beyond EOS. */
  //if (G_UNLIKELY (src->eos))
  //  goto eos;
  //g_static_rec_mutex_lock( &update_size_mutex );

  /* Create the buffer. */
  ret = gst_pad_alloc_buffer ( GST_BASE_SRC_PAD (GST_BASE_SRC (psrc)),
      //      GST_BUFFER_OFFSET_NONE, GST_BASE_SRC (psrc)->blocksize,
      offset, size,
      src->mythtv_caps ? src->mythtv_caps :
      GST_PAD_CAPS (GST_BASE_SRC_PAD (GST_BASE_SRC (psrc))), outbuf );

  //if (G_UNLIKELY (ret == GST_FLOW_UNEXPECTED))
  //  goto eos;

  if (G_UNLIKELY (ret != GST_FLOW_OK))
    goto eos;

  if (G_UNLIKELY (ret == GST_FLOW_ERROR))
    goto read_error;

  read = do_read_request_response ( src, offset, size, *outbuf );

  //g_static_rec_mutex_unlock( &update_size_mutex );

  src->do_start = TRUE;
  gst_task_start ( update_size_task );

#if 0
  g_static_rec_mutex_lock( &update_size_mutex );
  src->do_start = FALSE;  
  g_static_rec_mutex_unlock( &update_size_mutex );
  GST_TASK_SIGNAL( update_size_task );
#endif

  //g_static_rec_mutex_unlock( &update_size_mutex );

#if 0
#if ENABLE_TIMING_POSITION == 1
  guint64 size_tmp = 0;
  if (src->live_tv == TRUE) {
    //g_usleep( 1000 );
get_file_pos:
    //g_usleep( 100 );
    size_tmp = myth_file_transfer_get_file_position( src->file_transfer );
    if ( size_tmp > ( src->content_size + MYTHTV_TRANSFER_MAX_BUFFER ) )
      src->content_size = size_tmp;
    else
      goto get_file_pos;
    g_print( "\t[%s]\tGET_POSITION: file_position = %llu\n", 
	__FUNCTION__, size_tmp);

  }
#endif
#endif

  //if (G_UNLIKELY (read < 0))
  //  goto read_error;

  if (G_UNLIKELY(src->eos))
    goto eos;
  else
    goto done;

done:
  return ret;
eos:
#if 0
#if ENABLE_TIMING_POSITION == 1
  if ( src->live_tv == TRUE ) {
    //g_usleep( 1000 );
    guint64 size_tmp = 0;
get_file_pos_eos:
    //g_usleep( 100 );
    size_tmp = myth_file_transfer_get_file_position( src->file_transfer );
    if ( size_tmp > ( src->content_size + MYTHTV_TRANSFER_MAX_BUFFER ) )
      src->content_size = size_tmp;
    else
      goto get_file_pos_eos;
    g_print( "\t[%s]\tGET_POSITION: file_position = %llu\n", 
	__FUNCTION__, size_tmp);
    goto done;
  } else 
#endif
#endif
  {
    GST_DEBUG_OBJECT (src, "EOS reached");
    return GST_FLOW_UNEXPECTED;
  }
  /* ERRORS */
read_error:
  {
    GST_ELEMENT_ERROR (src, RESOURCE, READ,
	(NULL), ("Could not read any bytes (%i, %s)", read,
	  src->uri_name));
    return GST_FLOW_ERROR;
  }
  #if 0
need_pause:
  {
    const gchar *reason = gst_flow_get_name (ret);

    GST_DEBUG_OBJECT (src, "pausing task, reason %s", reason);
    return GST_FLOW_UNEXPECTED;
  }
  #endif

}

#if 0
/* The following two charset mangling functions were copied from gnomevfssrc.
 * Preserve them under the unverified assumption that they do something vaguely
 * worthwhile.
 */
  static char *
unicodify (const char *str, int len, ...)
{
  char *ret = NULL, *cset;
  va_list args;
  gsize bytes_read, bytes_written;

  if (g_utf8_validate (str, len, NULL))
    return g_strndup (str, len >= 0 ? len : strlen (str));

  va_start (args, len);
  while ((cset = va_arg (args, char *)) != NULL)
  {
    if (!strcmp (cset, "locale"))
      ret = g_locale_to_utf8 (str, len, &bytes_read, &bytes_written, NULL);
    else
      ret = g_convert (str, len, "UTF-8", cset,
	  &bytes_read, &bytes_written, NULL);
    if (ret)
      break;
  }
  va_end (args);

  return ret;
}

  static char *
gst_mythtv_src_unicodify (const char *str)
{
  return unicodify (str, -1, "locale", "ISO-8859-1", NULL);
}
#endif

void
update_size_func( void *mythtv_data ) 
{
  GstMythtvSrc *src;

  g_return_if_fail( mythtv_data != NULL );

  src = GST_MYTHTV_SRC ( mythtv_data );
  if ( src->do_start ) {
 #if ENABLE_TIMING_POSITION == 1
  guint64 size_tmp = 0;
  if (src->live_tv == TRUE) {
get_file_pos:
    //g_usleep( 50 );
    size_tmp = myth_file_transfer_get_file_position( src->file_transfer );
    if ( size_tmp > ( src->content_size + MYTHTV_TRANSFER_MAX_BUFFER ) )
      src->content_size = size_tmp;
    else
      goto get_file_pos;
    g_print( "\t[%s]\tGET_POSITION: file_position = %llu\n",
	__FUNCTION__, size_tmp );
  }
#endif
}
  gst_task_pause( update_size_task );
 // src->do_start = FALSE;
  //GST_TASK_SIGNAL( update_size_task );

}

/* create a socket for connecting to remote server */
  static gboolean
gst_mythtv_src_start ( GstBaseSrc * bsrc )
{
  GstMythtvSrc *src = GST_MYTHTV_SRC (bsrc);

  GString *chain_id_local = NULL;

  gboolean ret = TRUE;
#if 0
  if (src->live_tv == TRUE && src->file_transfer != NULL) {
    guint64 size_tmp = myth_file_transfer_get_file_position( src->file_transfer );
    if (size_tmp > src->content_size)
      src->content_size = size_tmp;
    g_print( "\t[%s]\tGET_POSITION: file_position = %llu\n", 
	__FUNCTION__, size_tmp);
  }
#endif
  if (src->unique_setup == FALSE) {
    src->unique_setup = TRUE;
  } else {
    goto done;
  }

  //GST_OBJECT_LOCK(src);

  if ( src->live_tv ) {
    src->spawn_livetv = myth_livetv_new( );
    if ( myth_livetv_setup( src->spawn_livetv ) == FALSE ) {
    	ret = FALSE;
    	goto init_failed;
    }
    /* set up the uri variable */
    src->uri_name = g_strdup( src->spawn_livetv->proginfo->pathname->str );
    chain_id_local = gmyth_tvchain_get_id( src->spawn_livetv->tvchain );
    if ( chain_id_local != NULL ) {
      src->live_chain_id = g_strdup( chain_id_local->str );
      g_print( "\t[%s]\tLocal chain ID = %s.\n", __FUNCTION__, src->live_chain_id );
    }
    src->live_tv_id = src->spawn_livetv->remote_encoder->recorder_num;
    g_print ( "[%s] LiveTV id = %d, URI path = %s.\n", __FUNCTION__, src->live_tv_id, src->uri_name );
  }

  src->file_transfer = myth_file_transfer_new( src->live_tv_id, 
      g_string_new( src->uri_name ), -1, src->mythtv_version );

  if ( src->file_transfer == NULL ) {
    //GST_OBJECT_UNLOCK(src);

    goto init_failed;
  }

  if ( src->live_tv ) {
    g_print ( "[%s] GST MYTHTVSRC: live_chain_id = %s\n", __FUNCTION__, src->live_chain_id );
    /* sets the MythSocket to the FileTransfer */
    //ret = myth_file_transfer_livetv_setup( &(src->file_transfer), src->spawn_livetv->remote_encoder->myth_socket );
  }
  /* sets the Playback monitor connection */
  ret = myth_file_transfer_playback_setup( &(src->file_transfer), src->live_tv );

  if ( src->live_tv == TRUE && ret == TRUE ) {
    /* loop finished, set the max tries variable to zero again... */
    wait_to_transfer = 0;

    while ( wait_to_transfer++ < MYTHTV_TRANSFER_MAX_WAITS && ( myth_file_transfer_is_recording( src->file_transfer ) == FALSE 
	  /*|| ( myth_file_transfer_get_file_position( src->file_transfer ) < ( src->content_size + 327680 ) )*/ ) )
      g_usleep( 100 );
  }

  /* sets the FileTransfer instance connection (video/audio download) */
  ret = myth_file_transfer_setup( &(src->file_transfer), src->live_tv );

  if ( ret == FALSE ) {
    //GST_OBJECT_UNLOCK(src);
#ifndef GST_DISABLE_GST_DEBUG  
    if ( src->mythtv_msgs_dbg )
      g_printerr( "MythTV FileTransfer request failed when setting up socket connection!\n" );  	  
#endif
    goto begin_req_failed;
  }

  src->content_size = src->file_transfer->filesize;

  //GST_OBJECT_UNLOCK(src);

  update_size_task = gst_task_create( update_size_func, src );

  gst_task_set_lock( update_size_task, &update_size_mutex );

  g_print( "[%s] Update Size task = %s\n", __FUNCTION__, gst_task_start( update_size_task ) && 
  		GST_TASK_STATE( update_size_task ) == GST_TASK_STARTED ? "OK !" : "ERROR!!!" );

  src->do_start = TRUE;

#if 0
  const char *str_value;
  gint gint_value;

  str_value = ne_get_response_header (src->request, "myth-metaint");
  if (str_value) {
    if ( sscanf (str_value, "%d", &gint_value) == 1 ) {
      if (src->myth_caps) {
	gst_caps_unref (src->myth_caps);
	src->myth_caps = NULL;
      }
      src->myth_metaint = gint_value;
#endif
      //src->mythtv_caps = gst_caps_new_simple ("application/x-gst_ff-nuv", NULL);
      //   }
      // }
done:
      return TRUE;

      /* ERRORS */
init_failed:
      {
      	if (src->spawn_livetv != NULL )
	  g_object_unref( src->spawn_livetv );

	GST_ELEMENT_ERROR (src, LIBRARY, INIT,
	    (NULL), ("Could not initialize MythTV library (%i, %s)", ret, src->uri_name));
	return FALSE;
      }
begin_req_failed:
      {
	GST_ELEMENT_ERROR (src, LIBRARY, INIT,
	    (NULL), ("Could not begin request sent to MythTV server (%i, %s)", ret, src->uri_name));
	return FALSE;
      }
}

#if 0
static gboolean
gst_mythtv_src_get_size (GstBaseSrc * bsrc, guint64 * size)
{
  GstMythtvSrc *src;
  gboolean ret = FALSE;

  src = GST_MYTHTV_SRC (bsrc);

  g_static_rec_mutex_lock( &update_size_mutex );
  src->do_start = FALSE;  
  g_static_rec_mutex_unlock( &update_size_mutex );
  GST_TASK_SIGNAL( update_size_task );
 

  while (1) {

    g_static_rec_mutex_lock( &update_size_mutex );
    if ( !src->do_start ) {

      g_print( "[%s] GET SIZE: do_start? == %s\n", __FUNCTION__, src->do_start ? "YES" : "NO" );

      GST_TASK_WAIT( update_size_task );
    } else {
      if (src->content_size <= 0) {
	g_static_rec_mutex_unlock( &update_size_mutex );
	goto done;
      }

      *size = src->content_size;
      src->do_start = FALSE;

      g_static_rec_mutex_unlock( &update_size_mutex );

      break;
    }
    g_static_rec_mutex_unlock( &update_size_mutex );

  } // while (1) 

done:
  return ret;

}
#endif

static gboolean
gst_mythtv_src_get_size (GstBaseSrc * bsrc, guint64 * size)
{
  GstMythtvSrc *src;
  gboolean ret = TRUE;

  src = GST_MYTHTV_SRC (bsrc);

  if (src->content_size <= 0)
    ret= FALSE;

  *size = src->content_size;

  return ret;

}
/* close the socket and associated resources
 * used both to recover from errors and go to NULL state */
  static gboolean
gst_mythtv_src_stop (GstBaseSrc * bsrc)
{
  GstMythtvSrc *src;

  src = GST_MYTHTV_SRC (bsrc);

  if (src->uri_name) {
    g_free (src->uri_name);
    src->uri_name = NULL;
  }

  if (src->mythtv_caps) {
    gst_caps_unref (src->mythtv_caps);
    src->mythtv_caps = NULL;
  }

  src->eos = FALSE;

  return TRUE;
}

  static gboolean
gst_mythtv_src_handle_event (GstPad * pad, GstEvent * event)
{
  GstMythtvSrc *src = GST_MYTHTV_SRC (GST_PAD_PARENT (pad));

  switch (GST_EVENT_TYPE (event)) {
    case GST_EVENT_FLUSH_START:
      src->eos = FALSE;
      break;
      //return TRUE;
#if 0
case GST_EVENT_FLUSH_STOP:
      src->do_start = TRUE;
      src->eos = FALSE;
      gst_element_set_state (GST_ELEMENT(src), GST_STATE_NULL);
      //gst_element_set_locked_state (GST_ELEMENT(src), TRUE);
      break;
#endif
    case GST_EVENT_SEEK:  	  
      {
	gdouble rate;
	//gboolean update = TRUE;
	GstFormat format;
	GstSeekType cur_type, stop_type;
	GstSeekFlags flags;
	gint64 cur = 0, stop = 0;
	gst_event_parse_seek ( event, &rate, &format,
	    &flags, &cur_type, &cur,
	    &stop_type, &stop );

	g_print( "[%s] Got EVENT_SEEK.\n", __FUNCTION__ );
	if ( !( flags & GST_SEEK_FLAG_FLUSH ) ) {
	  g_print( "[%s] Could get the FLAG_FLUSH message.\n", __FUNCTION__ );
	}
	//gboolean ret = gst_event_parse_new_segment ( event,
	//    &update, &rate, &format, &start, &stop,
	//    &position );
	//GstFlowReturn flow_ret = gst_mythtv_src_create (GST_BASE_SRC( GST_PAD_PARENT( psrc ) ), 
	//			cur, stop - cur + 1, GstBuffer)

      } 
    default:
      return gst_pad_event_default (pad, event);
  }

  return gst_pad_event_default (pad, event);
}

  static gboolean
gst_mythtv_src_is_seekable( GstBaseSrc *base_src )
{
  return TRUE;
}

  static void
gst_mythtv_src_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec)
{
  GstMythtvSrc *mythtvsrc = GST_MYTHTV_SRC (object);

  GST_OBJECT_LOCK (mythtvsrc);
  switch (prop_id) {
    case PROP_URI:
    case PROP_LOCATION:
      {
	if (!g_value_get_string (value)) {
	  GST_WARNING ("location property cannot be NULL");
	  goto done;
	}

	if (mythtvsrc->uri_name != NULL) {
	  g_free (mythtvsrc->uri_name);
	  mythtvsrc->uri_name = NULL;
	}
	mythtvsrc->uri_name = g_value_dup_string (value);

	break;
      }
#ifndef GST_DISABLE_GST_DEBUG
    case PROP_MYTHTV_DBG:
      {
	mythtvsrc->mythtv_msgs_dbg = g_value_get_boolean (value);
	break;
      }
#endif
    case PROP_MYTHTV_VERSION:
      {
	mythtvsrc->mythtv_version = g_value_get_int (value);
	break;
      }
    case PROP_MYTHTV_LIVEID:
      {
	mythtvsrc->live_tv_id = g_value_get_int (value);
	break;
      }
    case PROP_MYTHTV_LIVE:
      {
	mythtvsrc->live_tv = g_value_get_boolean (value);
	break;
      }
    case PROP_MYTHTV_LIVE_CHAINID:
      {
	if (!g_value_get_string (value)) {
	  GST_WARNING ("MythTV Live chainid property cannot be NULL");
	  goto done;
	}

	if (mythtvsrc->live_chain_id != NULL) {
	  g_free (mythtvsrc->live_chain_id);
	  mythtvsrc->live_chain_id = NULL;
	}
	mythtvsrc->live_chain_id = g_value_dup_string (value);

	break;
      }

    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
  GST_OBJECT_UNLOCK (mythtvsrc);
done:
  return;
}

  static void
gst_mythtv_src_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec)
{
  GstMythtvSrc *mythtvsrc = GST_MYTHTV_SRC (object);

  GST_OBJECT_LOCK (mythtvsrc);
  switch (prop_id) {
    case PROP_URI:
    case PROP_LOCATION:
      {
	gchar *str = g_strdup( "" );

	if ( mythtvsrc->uri_name == NULL ) {
	  g_free (mythtvsrc->uri_name);
	  mythtvsrc->uri_name = NULL;
	} else {
	  str = g_strdup( mythtvsrc->uri_name );
	}
	g_value_set_string ( value, str );
	break;
      }
#ifndef GST_DISABLE_GST_DEBUG
    case PROP_MYTHTV_DBG:
      g_value_set_boolean ( value, mythtvsrc->mythtv_msgs_dbg );
      break;
#endif
    case PROP_MYTHTV_VERSION:
      {
	g_value_set_int ( value, mythtvsrc->mythtv_version );
	break;
      }
    case PROP_MYTHTV_LIVEID:
      {
	g_value_set_int ( value, mythtvsrc->live_tv_id );
	break;
      }
    case PROP_MYTHTV_LIVE:
      g_value_set_boolean ( value, mythtvsrc->live_tv );
      break;
    case PROP_MYTHTV_LIVE_CHAINID:
      {
	gchar *str = g_strdup( "" );

	if ( mythtvsrc->live_chain_id == NULL ) {
	  g_free (mythtvsrc->live_chain_id);
	  mythtvsrc->live_chain_id = NULL;
	} else {
	  str = g_strdup( mythtvsrc->live_chain_id );
	}
	g_value_set_string ( value, str );
	break;
      }
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
  GST_OBJECT_UNLOCK (mythtvsrc);
}

/* entry point to initialize the plug-in
 * initialize the plug-in itself
 * register the element factories and pad templates
 * register the features
 */
  static gboolean
plugin_init (GstPlugin * plugin)
{
  return gst_element_register (plugin, "mythtvsrc", GST_RANK_NONE,
      GST_TYPE_MYTHTV_SRC);
}

/* this is the structure that gst-register looks for
 * so keep the name plugin_desc, or you cannot get your plug-in registered */
GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
    GST_VERSION_MINOR,
    "mythtv",
    "lib MythTV src",
    plugin_init, VERSION, "LGPL", "GStreamer", "http://gstreamer.net/")


/*** GSTURIHANDLER INTERFACE *************************************************/
  static guint 
gst_mythtv_src_uri_get_type (void)
{
  return GST_URI_SRC;
}

  static gchar **
gst_mythtv_src_uri_get_protocols (void)
{
  static gchar *protocols[] = { "myth", "myths", NULL };

  return protocols;
}

  static const gchar *
gst_mythtv_src_uri_get_uri (GstURIHandler * handler)
{
  GstMythtvSrc *src = GST_MYTHTV_SRC (handler);

  return src->uri_name;
}

  static gboolean
gst_mythtv_src_uri_set_uri (GstURIHandler * handler, const gchar * uri)
{
  GstMythtvSrc *src = GST_MYTHTV_SRC (handler);

  gchar *protocol;

  protocol = gst_uri_get_protocol (uri);
  if ((strcmp (protocol, "myth") != 0) && (strcmp (protocol, "myths") != 0)) {
    g_free (protocol);
    return FALSE;
  }
  g_free (protocol);
  g_object_set (src, "location", uri, NULL);

  return TRUE;
}

  static void
gst_mythtv_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
{
  GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;

  iface->get_type = gst_mythtv_src_uri_get_type;
  iface->get_protocols = gst_mythtv_src_uri_get_protocols;
  iface->get_uri = gst_mythtv_src_uri_get_uri;
  iface->set_uri = gst_mythtv_src_uri_set_uri;
}

  void
size_header_handler (void *userdata, const char *value)
{
  GstMythtvSrc *src = GST_MYTHTV_SRC (userdata);

  //src->content_size = g_ascii_strtoull (value, NULL, 10);

  GST_DEBUG_OBJECT (src, "content size = %lld bytes", src->content_size);
}