#include <gst/gst.h>
#include <glib.h>
#include <unistd.h>

static void
on_pad_added (GstElement *element,
              GstPad     *pad,
              gpointer    data)
{
  GstPad *sinkpad;
  GstElement *sink = (GstElement *) data;

  /* We can now link this pad with the file-sink sink pad */
  g_print ("Dynamic pad created, linking demuxer/sink\n");

  sinkpad = gst_element_get_static_pad (sink, "sink");

  gst_pad_link (pad, sinkpad);

  gst_object_unref (sinkpad);
}

int
main (int   argc,
      char *argv[])
{
  GstElement *pipeline, *source, *demuxer, *sink;

  /* Initialisation */
  gst_init (&argc, &argv);

  /* Check input arguments */
  if (argc != 3) {
    g_printerr ("Usage: %s <matroska filename> <output filename>\n", argv[0]);
    return -1;
  }

  /* Create gstreamer elements */
  pipeline = gst_pipeline_new ("test-pipeline");
  source   = gst_element_factory_make ("filesrc", "file-source");
  demuxer  = gst_element_factory_make ("matroskademux", "matroska-demuxer");
  sink     = gst_element_factory_make ("filesink", "audio-output");


  if (!pipeline || !source || !demuxer || !sink) {
    g_printerr ("One element could not be created. Exiting.\n");
    return -1;
  }

  g_object_set (G_OBJECT (sink), "async", FALSE, NULL);

  /* Set up the pipeline */

  /* we set the input filename to the source element */
  g_object_set (G_OBJECT (source), "location", argv[1], NULL);

  /* we set the output filename to the sink element */
  g_object_set (G_OBJECT (sink), "location", argv[2], NULL);

  /* we add all elements into the pipeline */
  /* file-source | matroska-demuxer | file-sink */
  gst_bin_add_many (GST_BIN (pipeline), source, demuxer, sink, NULL);

  /* we link the elements together */
  /* file-source -> matroska-demuxer */
  gst_element_link (source, demuxer);
  g_signal_connect (demuxer, "pad-added", G_CALLBACK (on_pad_added), sink);

  g_print ("Now pausing: %s\n", argv[1]);
  gst_element_set_state (pipeline, GST_STATE_PAUSED);

  g_print ("sleeping 1 second before seek\n");
  sleep (1);

  g_print ("Seeking\n");
  g_assert (gst_element_seek (demuxer, 1.0, GST_FORMAT_TIME,
      GST_SEEK_FLAG_FLUSH, GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_SET, -1));

  g_print ("sleeping 5 seconds after seek\n");
  sleep (5);

  g_print ("bring pipe to state NULL\n");
  gst_element_set_state (pipeline, GST_STATE_NULL);

  g_print ("Deleting pipeline\n");
  gst_object_unref (GST_OBJECT (pipeline));

  return 0;
}