#include <gst/gst.h>

static void
pad_added_cb (GstElement * qtdemux, GstPad * pad, GstElement * sink)
{
  GstPad *sinkpad;

  g_print ("Got pad %s\n", GST_PAD_NAME (pad));

  sinkpad = gst_element_get_static_pad (sink, "sink");
  if (gst_pad_is_linked (sinkpad))
    goto done;

  if (!g_str_has_prefix (GST_PAD_NAME (pad), "video_"))
    goto done;

  gst_pad_link (pad, sinkpad);

done:

  gst_object_unref (sinkpad);
}

static void
handoff_cb (GstElement * sink, GstBuffer * buf, GstPad * pad, gpointer userdata)
{
  g_print ("ts %" GST_TIME_FORMAT "\n",
      GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
}

int
main (int argc, char *argv[])
{
  GstElement *pipe, *src, *demux, *sink;
  GstMessage *msg;

  gst_init (&argc, &argv);

  if (argc <= 1)
    g_error ("Usage: %s PATH-TO.MP4\n", argv[0]);

  pipe = gst_pipeline_new ("pipeline");

  src = gst_element_factory_make ("filesrc", "filesrc");
  g_object_set (src, "location", argv[1], NULL);

  demux = gst_element_factory_make ("qtdemux", "qtdemux");

  sink = gst_element_factory_make ("fakesink", "sink");
  g_object_set (sink, "signal-handoffs", TRUE, NULL);

  gst_bin_add_many (GST_BIN (pipe), src, demux, sink, NULL);
  gst_element_link_many (src, demux, NULL);

  g_signal_connect (demux, "pad-added", G_CALLBACK (pad_added_cb), sink);

#if 0
  gst_element_set_state (pipe, GST_STATE_PAUSED);

  msg = gst_bus_timed_pop_filtered (GST_ELEMENT_BUS (pipe), -1,
       GST_MESSAGE_ASYNC_DONE | GST_MESSAGE_ERROR);

  gst_element_seek_simple (pipe, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH,
      2 * GST_SECOND);

  msg = gst_bus_timed_pop_filtered (GST_ELEMENT_BUS (pipe), -1,
       GST_MESSAGE_ASYNC_DONE | GST_MESSAGE_ERROR);

  gst_message_unref (msg);
#endif

  /* and go ! */
  g_signal_connect (sink, "handoff", G_CALLBACK (handoff_cb), NULL);

  gst_element_set_state (pipe, GST_STATE_PLAYING);

  msg = gst_bus_timed_pop_filtered (GST_ELEMENT_BUS (pipe), -1,
       GST_MESSAGE_EOS | GST_MESSAGE_ERROR);

  gst_message_unref (msg);

  return 0;
}
