#include <glib.h>
#include <gst/gst.h>
#include <gst/mpegts/mpegts.h>

static void
_on_bus_message (GstBus * bus, GstMessage * message, GMainLoop * mainloop)
{
   switch (GST_MESSAGE_TYPE (message)) {
      case GST_MESSAGE_ERROR:
      case GST_MESSAGE_EOS:
         g_main_loop_quit (mainloop);
         break;
      default:
         break;
   }
}

int
main (int argc, gchar ** argv)
{
   GstElement *pipeline = NULL;
   GstElement *mux;
   GstBus *bus;
   GError *error = NULL;
   GMainLoop *mainloop;
   GstMpegTsSection *section;
   GstMpegTsDescriptor *descriptor;
   GstMpegTsNIT *nit;
   gchar *name = "Network name";

   gst_init (&argc, &argv);

   gst_mpegts_initialize ();

   pipeline = gst_parse_launchv ((const gchar **) &argv[1], &error);
   if (error) {
      g_print ("pipeline could not be constructed: %s\n", error->message);
      g_error_free (error);
      return 1;
   }

   nit = gst_mpegts_section_new_nit ();
   nit->actual_network = TRUE;
   nit->network_id = 0x10FF;

   descriptor = gst_mpegts_descriptor_from_dvb_network_name (name);
   g_ptr_array_add (nit->descriptors, descriptor);

   section = gst_mpegts_section_from_nit (nit);

   mux = gst_bin_get_by_name (GST_BIN (pipeline), "mux");
   if (!mux) {
      g_print ("pipeline did not contain an element named `mux`\n");
      return 2;
   }

   if(!gst_mpegts_section_send_event (section, GST_ELEMENT (mux)))
      g_print ("Could not send event\n");

   mainloop = g_main_loop_new (NULL, FALSE);

   /* Put a bus handler */
   bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
   gst_bus_add_signal_watch (bus);
   g_signal_connect (bus, "message", (GCallback) _on_bus_message, mainloop);

   /* Start pipeline */
   gst_element_set_state (pipeline, GST_STATE_PLAYING);
   g_main_loop_run (mainloop);

   gst_element_set_state (pipeline, GST_STATE_NULL);

   gst_object_unref (pipeline);

   return 0;
}

