#include <gst/gst.h>

static gboolean
bus_call (GstBus     *bus,
	  GstMessage *msg,
	  gpointer    data)
{
  GMainLoop *loop = 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 *err;

      gst_message_parse_error (msg, &err, &debug);
      g_free (debug);

      g_print ("Error: %s\n", err->message);
      g_error_free (err);

      g_main_loop_quit (loop);
      break;
    }
    default:
      break;
  }

  return TRUE;
}

gint
main (gint   argc,
      gchar *argv[])
{
  GstElement *pipeline, *filesrc, *decoder, *filter, *sink;
  GMainLoop *loop;

  /* initialization */
  gst_init (&argc, &argv);
  loop = g_main_loop_new (NULL, FALSE);
  if (argc != 2) {
    g_print ("Usage: %s <myth uri>\n", argv[0]);
    return 01;
  }

  /* create elements */
  pipeline = gst_pipeline_new ("mythtvsrc_pipeline");
  gst_bus_add_watch (gst_pipeline_get_bus (GST_PIPELINE (pipeline)),
		     bus_call, loop);

  filesrc  = gst_element_factory_make ("mythtvsrc", "mythtvsrc");
  decoder  = gst_element_factory_make ("mad", "my_decoder");
  filter   = gst_element_factory_make ("my_filter", "my_filter");
  sink     = gst_element_factory_make ("osssink", "audiosink");
  if (!sink || !decoder) {
    g_print ("Decoder or output could not be found - check your install\n");
    return -1;
  } else if (!filter) {
    g_print ("Your self-written filter could not be found. Make sure it "
             "is installed correctly in $(libdir)/gstreamer-0.9/ and that "
             "you've ran gst-register-0.9 to register it. Check availability "
             "of the plugin afterwards using \"gst-inspect-0.9 my_filter\"");
    return -1;
  }

  g_object_set (G_OBJECT (filesrc), "location", argv[1], NULL);

  /* link everything together */
  gst_element_link_many (filesrc, decoder, filter, sink, NULL);
  gst_bin_add_many (GST_BIN (pipeline), filesrc, decoder, filter, sink, NULL);

  /* run */
  gst_element_set_state (pipeline, GST_STATE_PLAYING);
  g_main_loop_run (loop);

  /* clean up */
  gst_element_set_state (pipeline, GST_STATE_NULL);
  gst_object_unref (GST_OBJECT (pipeline));

  return 0;
}