#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdlib.h>
#include <glib.h>
#include <gst/gst.h>
#include <gst/pbutils/pbutils.h>
#include <gst/pbutils/gstdiscoverer.h>

void print_info (GstDiscovererStreamInfo *streamInfo) {
  gchar *desc = NULL;
  GstCaps *caps;

  caps = gst_discoverer_stream_info_get_caps (streamInfo);

  if (caps) {
    if (gst_caps_is_fixed (caps))
      desc = gst_pb_utils_get_codec_description (caps);
    else
      desc = gst_caps_to_string (caps);
    gst_caps_unref (caps);
  }

  g_print ("%s: %s\n",
      gst_discoverer_stream_info_get_stream_type_nick (streamInfo), desc);

  if (desc) {
    g_free (desc);
    desc = NULL;
  }

  const GstStructure *str = gst_caps_get_structure (caps, 0);

  const gchar *mime = gst_structure_get_name (str);

  g_print ("Caps Mime: %s", mime);

  if (g_strrstr (mime, "video")) {
    gint width, height;

    if (gst_structure_get_int (str, "width", &width) &&
      gst_structure_get_int (str, "height", &height)) {

      g_print (" Width: %d Height: %d", width, height);
    }
  }

  if (g_strrstr (mime, "audio")) {
    gint rate, channels;

    gst_structure_get_int (str, "rate", &rate);
    gst_structure_get_int (str, "channels", &channels);

    g_print (" Rate: %d Channels: %d", rate, channels);
  }

  g_print ("\n\n");
}


int
main (int argc, char **argv)
{
  GError *err = NULL;
  GstDiscoverer *dc;
  gint timeout = 10;
  gchar *uri = g_filename_to_uri (argv[1], NULL, &err);

  /* Initialisation */
  gst_init (&argc, &argv);

  dc = gst_discoverer_new (timeout * GST_SECOND, &err);
  if (G_UNLIKELY (dc == NULL)) {
    g_print ("Error initializing: %s\n", err->message);
    exit (1);
  }

    g_print ("Before gst_discoverer_discover_uri.\n");
  GstDiscovererInfo *info = gst_discoverer_discover_uri (dc, uri, &err);
    g_print ("After gst_discoverer_discover_uri.\n");

  if (info == NULL) g_print ("Info Bugger!\n\n");
  if (err == NULL) g_print ("hmmmm\n\n");

  GstDiscovererResult result = gst_discoverer_info_get_result (info);

  if (result > 0) {
    g_print ("result Bugger! %d\n\n", result);
    g_print (" %s\n", err->message);
  }

  GstDiscovererStreamInfo *streamInfo = gst_discoverer_info_get_stream_info (info);

  if (streamInfo == NULL) g_print ("streamInfo Bugger!\n\n");

  print_info (streamInfo);

  if (GST_IS_DISCOVERER_CONTAINER_INFO (streamInfo)) {
    GList *tmp, *streams;

    streams = gst_discoverer_container_info_get_streams (GST_DISCOVERER_CONTAINER_INFO (streamInfo));
    for (tmp = streams; tmp; tmp = tmp->next) {
      GstDiscovererStreamInfo *tmpinf = (GstDiscovererStreamInfo *) tmp->data;
      print_info (tmpinf);
    }
    gst_discoverer_stream_info_list_free (streams);
  }

  gst_discoverer_stream_info_unref(streamInfo);

  gst_discoverer_info_unref(info);

  g_object_unref (dc);

  return 0;
}

