#include <gst/gst.h>
#include <gst/rtp/gstrtpbuffer.h>

gboolean started = FALSE;
guint16 s_seqnum = 0;
gint64 last_ts = 0;
guint64 last_pktcount = 0;
guint64 pktcount = 0;
gint lost = 0;
gint total_lost = 0;

void
pull_samples (GstElement *appsink, gint64 now)
{
  GstSample *sample = NULL;
  GstBuffer *buf = NULL;
  GstRTPBuffer rtp = GST_RTP_BUFFER_INIT;
  guint16 seq;

  g_signal_emit_by_name (appsink, "pull-sample", &sample);
  buf = gst_sample_get_buffer (sample);

  if (!gst_rtp_buffer_map (buf, GST_MAP_READ, &rtp)) {
    g_print ("failed to map\n");
    goto out;
  }

  seq = gst_rtp_buffer_get_seq (&rtp);

  if (G_UNLIKELY (!started)) {
    started = TRUE;
  } else {
    if (seq != (++s_seqnum)) {
      g_print ("Lost: %u - %u\n", s_seqnum, seq == 0 ? G_MAXUINT16 : seq - 1);

      /* stats */
      if (seq > s_seqnum)
        lost += seq - s_seqnum;
      else
        lost += seq + (G_MAXUINT16 - s_seqnum);
    }
  }

  s_seqnum = seq;
  gst_rtp_buffer_unmap (&rtp);

  pktcount++;

  if (now - last_ts > G_USEC_PER_SEC) {
    g_print ("Processed: %" G_GUINT64_FORMAT ",", pktcount);
    g_print (" rate: %.2f kbps, ",
        gst_util_uint64_scale (
            (pktcount - last_pktcount) * gst_buffer_get_size (buf) * 8,
            now - last_ts, G_USEC_PER_SEC) / 1000.0);
    g_print (" last seqnum: %u, lost: %d\n", s_seqnum, lost);

    last_pktcount = pktcount;
    last_ts = now;
    total_lost += lost;
    lost = 0;
  }

out:
  gst_sample_unref (sample);
}

gint
main(gint argc, gchar **argv)
{
  GstElement *recv;
  GstElement *send;
  GstElement *appsink;
  gint64 ts, now;

  gst_init (&argc, &argv);

  /* attempt to stream about 57 Mbit/s (400px*300px*32bpp*15fps)
   * in 1400-byte packets */
  send = gst_parse_launch (
    "videotestsrc is-live=true pattern=black "
    "! video/x-raw,format=RGBA,width=400,height=300,framerate=15/1 "
    "! rtpgstpay mtu=1400 "
    "! udpsink host=127.0.0.1 port=6022 max-bitrate=60000000", NULL);

  recv = gst_parse_launch (
    "udpsrc address=127.0.0.1 port=6022 mtu=1400 max-read-packets=400 buffer-size=10000000 "
    " caps=\"application/x-rtp,media=application,clock-rate=90000,encoding-name=X-GST,payload=96\" "
   // "! queue max-size-buffers=0 max-size-bytes=0 max-size-time=0 "
    "! appsink name=appsink", NULL);

  appsink = gst_bin_get_by_name (GST_BIN (recv), "appsink");

  gst_element_set_state (send, GST_STATE_PLAYING);
  gst_element_set_state (recv, GST_STATE_PLAYING);

  ts = g_get_monotonic_time ();
  while ((now = g_get_monotonic_time()) - ts < 15 * G_USEC_PER_SEC) {
    pull_samples (appsink, now);
  }

  g_print ("total lost: %d (%.3f %%)\n", total_lost,
      ((double) total_lost) / ((double) pktcount + total_lost));

  gst_element_set_state (recv, GST_STATE_NULL);
  gst_element_set_state (send, GST_STATE_NULL);

  g_object_unref (appsink);
  g_object_unref (recv);
  g_object_unref (send);

  return 0;
}
