

#include <gst/gst.h>
#include <string>
   
/* Structure to contain all our information, so we can pass it to callbacks */
typedef struct _CustomData {
  GstElement *pipeline;
  GstElement *rtspSource;
  GstElement *rtpH264Depay;
  GstElement *mp4Mux;
  GstElement *fileSink;
} CustomData;
   
/* Handler for the pad-added signal */
static void pad_added_handler (GstElement *src, GstPad *pad, CustomData *data);
   
int main(int argc, char *argv[]) {
  CustomData data;
  GstBus *bus;
  GstMessage *msg;
  GstStateChangeReturn ret;
  gboolean terminate = FALSE;
   
  /* Initialize GStreamer */
  gst_init (&argc, &argv);
    
  /* Create the elements */
  data.rtspSource = gst_element_factory_make ("rtspsrc", "rtsp source");
  data.rtpH264Depay = gst_element_factory_make ("rtph264depay", "rtp depacketizer");
  data.mp4Mux = gst_element_factory_make ("mp4mux", "mp4 multiplexer");
  data.fileSink = gst_element_factory_make ("filesink", "file sink");

   
  /* Create the empty pipeline */
  data.pipeline = gst_pipeline_new ("test-pipeline");
    
  if (!data.pipeline || !data.rtspSource || !data.rtpH264Depay || !data.mp4Mux || !data.fileSink) 
  {
    g_printerr ("Not all elements could be created.\n");
    return -1;
  }
   
  /* Build the pipeline. Note that we are NOT linking the source at this
   * point. We will do it later. */

  gst_bin_add_many (GST_BIN (data.pipeline), data.rtspSource, NULL);
   
  /* Set the URI to play */
  g_object_set (data.rtspSource, "location", "rtsp://streaming1.osu.edu/media2/ufsap/ufsap.mov", NULL);
   
  /* Connect to the pad-added signal */
  g_signal_connect (data.rtspSource, "pad-added", G_CALLBACK (pad_added_handler), &data);
   
  /* Start playing */
  ret = gst_element_set_state (data.pipeline, GST_STATE_PLAYING);
  if (ret == GST_STATE_CHANGE_FAILURE) {
    g_printerr ("Unable to set the pipeline to the playing state.\n");
    gst_object_unref (data.pipeline);
    return -1;
  }
   
  /* Listen to the bus */
  bus = gst_element_get_bus (data.pipeline);
  do {
	  msg = gst_bus_timed_pop_filtered (bus, GST_CLOCK_TIME_NONE, (GstMessageType)(GST_MESSAGE_STATE_CHANGED | GST_MESSAGE_ERROR | GST_MESSAGE_EOS) );
   
    /* Parse message */
    if (msg != NULL) {
      GError *err;
      gchar *debug_info;
       
      switch (GST_MESSAGE_TYPE (msg)) {
        case GST_MESSAGE_ERROR:
          gst_message_parse_error (msg, &err, &debug_info);
          g_printerr ("Error received from element %s: %s\n", GST_OBJECT_NAME (msg->src), err->message);
          g_printerr ("Debugging information: %s\n", debug_info ? debug_info : "none");
          g_clear_error (&err);
          g_free (debug_info);
          terminate = TRUE;
          break;
        case GST_MESSAGE_EOS:
          g_print ("End-Of-Stream reached.\n");
          terminate = TRUE;
          break;
        case GST_MESSAGE_STATE_CHANGED:
          /* We are only interested in state-changed messages from the pipeline */
          if (GST_MESSAGE_SRC (msg) == GST_OBJECT (data.pipeline)) {
            GstState old_state, new_state, pending_state;
            gst_message_parse_state_changed (msg, &old_state, &new_state, &pending_state);
            g_print ("Pipeline state changed from %s to %s:\n",
                gst_element_state_get_name (old_state), gst_element_state_get_name (new_state));
          }
          break;
        default:
          /* We should not reach here */
          g_printerr ("Unexpected message received.\n");
          break;
      }
      gst_message_unref (msg);
    }
  } while (!terminate);
   
  GST_DEBUG_BIN_TO_DOT_FILE( GST_BIN (data.pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "prog_graph_end");

  /* Free resources */
  gst_object_unref (bus);
  gst_element_set_state (data.pipeline, GST_STATE_NULL);
  gst_object_unref (data.pipeline);
  return 0;
}
   
/* This function will be called by the pad-added signal */
static void pad_added_handler (GstElement *src, GstPad *new_pad, CustomData *data) 
{
    GstPad *sink_pad = gst_element_get_static_pad (data->rtpH264Depay, "sink");
    GstPadLinkReturn ret;
    GstCaps *new_pad_caps = NULL;
    GstStructure *new_pad_struct = NULL;
    const gchar *new_pad_type = NULL;
    gboolean retValue;

    g_print ("Received new pad '%s' from '%s':\n", GST_PAD_NAME (new_pad), GST_ELEMENT_NAME (src));

    /* Check the new pad's type */
    new_pad_caps = gst_pad_get_caps (new_pad);
    new_pad_struct = gst_caps_get_structure (new_pad_caps, 0);
    new_pad_type = gst_structure_get_name (new_pad_struct);

    if (!g_str_has_prefix (new_pad_type, "application/x-rtp" )  )
    {
        g_print ("  It has type '%s' which is not H264 video. Ignoring.\n", new_pad_type);
        goto exit;
    }

    const gchar* encName = gst_structure_get_string (new_pad_struct, (const gchar*)"encoding-name" );

    if(strcmp( encName, "H264"))
    {
        g_print ("  It has type '%s' which is not H264 video. Ignoring.\n", new_pad_type);
        goto exit;
    }

    /* set byte-stream to false */
    g_object_set (data->rtpH264Depay, "byte-stream", FALSE, NULL);

    /* set file dump location */
    g_object_set (data->fileSink, "location", "D:\\test\\dump.mp4", NULL);

    /* add elements to the bin before starting any linking */
    gst_bin_add_many (GST_BIN (data->pipeline), data->rtpH264Depay, data->mp4Mux, data->fileSink, NULL);

    /* link new pad and rtpdepay */
    {
        ret = gst_pad_link (new_pad, sink_pad);

        if (GST_PAD_LINK_FAILED(ret)) 
        {
            g_print ("  Type is '%s' but link failed.\n", new_pad_type);
        } 
        else 
        {
            g_print ("  Link succeeded (type '%s').\n", new_pad_type);
        }
    }

    /* link rtp-depay and mp4mux */
    {
        GstCaps *caps, *negCaps;
        caps = gst_caps_new_simple ("video/x-h264",
	            "width", G_TYPE_INT, 320,
	            "height", G_TYPE_INT, 240,
	            "framerate", GST_TYPE_FRACTION, 25, 1,
	            NULL);

        retValue = gst_element_link_filtered( data->rtpH264Depay, data->mp4Mux, caps);

        if (!retValue) 
        {
            g_print ("  Type is '%s' but link failed.\n", new_pad_type);
        } 
        else 
        {
            g_print ("  Link succeeded (type '%s').\n", new_pad_type);
        }

        /* get the negotiated caps */
        GstPad *src_pad = gst_element_get_static_pad (data->rtpH264Depay, "src");
        negCaps  = gst_pad_get_negotiated_caps( src_pad );
    }

    /* link mp4mux and filesink */
    {
        retValue = gst_element_link_many (data->mp4Mux, data->fileSink, NULL);

        if (!retValue) 
        {
            g_print ("  Type is '%s' but link failed.\n", new_pad_type);
        } 
        else 
        {
            g_print ("  Link succeeded (type '%s').\n", new_pad_type);
            GST_DEBUG_BIN_TO_DOT_FILE( GST_BIN (data->pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "prog_graph_begin");
        }
    }
exit:
    /* Unreference the new pad's caps, if we got them */
    if (new_pad_caps != NULL)
        gst_caps_unref (new_pad_caps);

    /* Unreference the sink pad */
    gst_object_unref (sink_pad);
}
