#include <gst/gst.h>

static GstPadProbeReturn
event_cb (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
{
  GMainLoop *loop = user_data;

  if (GST_EVENT_TYPE (info->data) == GST_EVENT_CAPS)
    g_main_loop_quit (loop);

  return GST_PAD_PROBE_OK;
}

static gboolean
start_cb (gpointer user_data)
{
  gst_element_set_state (GST_ELEMENT (user_data), GST_STATE_PLAYING);
  return FALSE;
}

int
main (int argc, char ** argv)
{
  GMainLoop *loop;
  GstElement *pipeline, *src, *sink;
  GstPad *srcpad, *sinkpad;

  gst_init (&argc, &argv);

  loop = g_main_loop_new (NULL, FALSE);

  src = gst_parse_bin_from_description ("audiotestsrc is-live=1", TRUE, NULL);
  sink = gst_parse_bin_from_description ("fakesink", TRUE, NULL);

  g_return_val_if_fail (src && sink, -1);

  g_object_ref_sink (src);

  pipeline = gst_pipeline_new (NULL);
  gst_bin_add_many (GST_BIN (pipeline), src, sink, NULL);
  
  g_return_val_if_fail (gst_element_link (src, sink), -1);

  srcpad = gst_element_get_static_pad (src, "src");
  sinkpad = gst_element_get_static_pad (sink, "sink");

  gst_pad_add_probe (sinkpad, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM, event_cb,
      loop, NULL);

  g_idle_add (start_cb, pipeline);
  g_main_loop_run (loop);

  /* Get rid of the source */
  gst_pad_unlink (srcpad, sinkpad);
  gst_object_unref (srcpad);
  gst_object_unref (sinkpad);
  gst_bin_remove (GST_BIN (pipeline), src);
  gst_element_set_state (src, GST_STATE_NULL);

  /* Drain the sink */
  gst_element_send_event (sink, gst_event_new_eos ());

  gst_element_set_state (pipeline, GST_STATE_NULL);
  gst_object_unref (pipeline);
  gst_object_unref (src);
  
  return 0;
}

