#include <string.h>

#include <gst/gst.h>

static gboolean
on_message (GstBus * bus, GstMessage * message, gpointer user_data)
{
  GMainLoop *loop = (GMainLoop *) user_data;

  switch (GST_MESSAGE_TYPE (message)) {
    case GST_MESSAGE_ERROR:
      g_error ("Got ERROR");
      g_main_loop_quit (loop);
      break;
    case GST_MESSAGE_WARNING:
      g_warning ("Got WARNING");
      g_main_loop_quit (loop);
      break;
    case GST_MESSAGE_EOS:
      g_main_loop_quit (loop);
      break;
    default:
      break;
  }

  return TRUE;
}

gint
main (gint argc, gchar * argv[])
{
  GstElement *playbin, *sink;
  GstBus *bus;
  GMainLoop *loop;

  gst_init (NULL, NULL);

  playbin = gst_element_factory_make ("playbin2", NULL);
  sink = gst_element_factory_make ("xvimagesink", NULL);
  g_object_set (G_OBJECT (playbin), "video-sink", sink,
      "uri", "file:///home/slomo/test.avi", NULL);

  loop = g_main_loop_new (NULL, FALSE);

  bus = gst_pipeline_get_bus (GST_PIPELINE (playbin));
  gst_bus_add_signal_watch (bus);
  g_signal_connect (G_OBJECT (bus), "message", G_CALLBACK (on_message), loop);
  gst_object_unref (GST_OBJECT (bus));

  if (gst_element_set_state (playbin,
          GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
    g_error ("Failed to go into PLAYING state");
    return -1;
  }

  // Doesn't fail with or without the line below
  // gst_element_get_state (playbin, NULL, NULL, GST_CLOCK_TIME_NONE);

  //g_main_loop_run (loop);

  gst_element_set_state (playbin, GST_STATE_NULL);

  g_main_loop_unref (loop);
  gst_object_unref (playbin);

  return 0;
}
