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

int main (int argc, char**argv)
{
  GstElement *pipeline;
  GstElement *pipeline2;
  GstElement *asrc, *v;
  GstClock *c;
  
  gst_init(&argc, &argv);

  c = gst_system_clock_obtain ();

  pipeline = gst_parse_launch ("gstrtpbin name=r alsasrc name=asrc ! valve name=v ! alawenc name=e ! rtppcmapay !  application/x-rtp, clock-rate=8000  ! r.send_rtp_sink_0 r.send_rtp_src_0 ! udpsink host=127.0.0.1 port=7777 sync=0 async=0", NULL);

  gst_pipeline_use_clock(GST_PIPELINE(pipeline), c);

  asrc = gst_bin_get_by_name(GST_BIN(pipeline), "asrc");
  v = gst_bin_get_by_name(GST_BIN(pipeline), "v");

  pipeline2 = gst_parse_launch ("gstrtpbin name=r udpsrc port=7777 ! application/x-rtp, clock-rate=8000 ! r.recv_rtp_sink_0 r. ! rtppcmadepay ! alawdec ! alsasink", NULL);
 
  gst_pipeline_use_clock(GST_PIPELINE(pipeline2), c);

  gst_element_set_state(pipeline2, GST_STATE_PLAYING);
  gst_element_set_state(pipeline, GST_STATE_PLAYING);

  sleep(2);

  g_object_set(v, "drop", TRUE, NULL);
  gst_element_set_locked_state(asrc, TRUE);
  gst_element_set_state(asrc, GST_STATE_READY);
  fprintf(stderr, "STOPPED\n");
  printf("STOPPED\n");

  usleep (500000);

  g_object_set(v, "drop", FALSE, NULL);
  gst_element_set_locked_state(asrc, FALSE);
  g_object_set(v, "drop", FALSE, NULL);
  gst_element_set_state(asrc, GST_STATE_PLAYING);
  g_object_set(v, "drop", FALSE, NULL);
  fprintf(stderr, "RESTARTED\n");
  printf("RESTARTED\n");

  sleep (10);

  return 0;
}
