/*
 * test metadata filtering
 *
 * gcc `pkg-config --cflags --libs gstreamer-0.10` tagfilter.c -o tagfilter
 *
 */

#include <stdlib.h>
#include <string.h>
#include <glib.h>
#include <gst/gst.h>

static void
event_loop (GstElement * pipe)
{
  GstBus *bus;
  GstMessage *message = NULL;

  bus = gst_element_get_bus (GST_ELEMENT (pipe));

  while (TRUE) {
    message = gst_bus_poll (bus, GST_MESSAGE_ANY, -1);

    g_assert (message != NULL);

    switch (message->type) {
      case GST_MESSAGE_EOS:
        gst_message_unref (message);
        return;
      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);
        gst_message_unref (message);
        g_error_free (gerror);
        g_free (debug);
        return;
      }
      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);
        gst_message_unref (message);
        g_error_free (gerror);
        g_free (debug);
        return;
      }
      default:
        gst_message_unref (message);
        break;
    }
  }
}

int
main (int argc, char **argv)
{
  GstElement *pipeline;
  GstTagSetter *setter;

  if (!g_thread_supported ())
    g_thread_init (NULL);
  gst_init (&argc,&argv);

  pipeline = gst_parse_launch ("filesrc location=input.avi ! avidemux ! queue ! avimux ! filesink location=output.avi", NULL);
  if (!pipeline) {
    g_printerr("Can't create pipeline\n");
    return -1;
  }
  
  /* preparse and set tags */
  gst_element_set_state (pipeline, GST_STATE_READY);
  
  setter = GST_TAG_SETTER (gst_bin_get_by_interface (GST_BIN (pipeline), GST_TYPE_TAG_SETTER));
  if (!pipeline) {
    g_printerr("No tag setter in pipeline\n");
    return -1;
  }
  gst_tag_setter_add_tags (setter, GST_TAG_MERGE_REPLACE_ALL, GST_TAG_TITLE,
    "title", NULL);

  /* start playing */
  gst_element_set_state (pipeline, GST_STATE_PLAYING);
  
  /* Run event loop listening for bus messages until EOS or ERROR */
  event_loop (pipeline);

  /* stop & unref */
  gst_element_set_state (pipeline, GST_STATE_NULL);
  gst_object_unref (pipeline);
  
  return 0;
}
