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


int main (int argc, char **argv)
{
  GstElement *pipeline = NULL;
  GstElement *s, *a, *c;
  gint i;
  GstCaps *caps;
  GstPad *pad;
  gboolean has_alaw = TRUE;

  gst_init(&argc, &argv);
  

  pipeline = gst_parse_launch("audiotestsrc name=s ! alawenc name=a ! capsfilter name=c ! fakesink", NULL);
  g_assert(pipeline);

  s = gst_bin_get_by_name(GST_BIN(pipeline), "s");
  a = gst_bin_get_by_name(GST_BIN(pipeline), "a");
  c = gst_bin_get_by_name(GST_BIN(pipeline), "c");

  pad = gst_element_get_static_pad(s, "src");

  g_assert(a && s && c && pad);

  caps = gst_caps_new_simple("audio/x-alaw", NULL);
  g_object_set(c, "caps", caps, NULL);
  gst_caps_unref(caps);

  g_assert (gst_element_set_state(pipeline, GST_STATE_PLAYING) !=
	    GST_STATE_CHANGE_FAILURE);

  for (i=0; i< 100; i++) {

    sleep(1);

    gst_pad_set_blocked(pad, TRUE);

    gst_element_set_state(a, GST_STATE_NULL);
    gst_bin_remove(GST_BIN(pipeline), a);
    gst_object_unref(a);

    if (has_alaw) {
      a = gst_element_factory_make("mulawenc", NULL);
      caps = gst_caps_new_simple("audio/x-mulaw", NULL);
      g_object_set(c, "caps", caps, NULL);
      gst_caps_unref(caps);
      has_alaw = FALSE;
    } else {
      a = gst_element_factory_make("alawenc", NULL);
      caps = gst_caps_new_simple("audio/x-alaw", NULL);
      g_object_set(c, "caps", caps, NULL);
      gst_caps_unref(caps);
      has_alaw = TRUE;
    }

    gst_object_ref(a);
    gst_bin_add(GST_BIN(pipeline), a);
    gst_element_link(s,a);
    gst_element_link(a,c);

    gst_element_set_state(a, GST_STATE_PLAYING);

    gst_pad_set_blocked(pad, FALSE);
  }


  
  g_assert (gst_element_set_state(pipeline, GST_STATE_PLAYING) !=
	    GST_STATE_NULL);

  gst_object_unref(pad);
  gst_object_unref(a);
  gst_object_unref(s);
  gst_object_unref(c);
  

  gst_object_unref(pipeline);

  return 0;
}
