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


static GstElement *pipeline;

static gboolean
bus_call (GstBus * bus, GstMessage * msg, gpointer data)
{
  GMainLoop *loop = (GMainLoop *) data;

  switch (GST_MESSAGE_TYPE (msg)) {
    case GST_MESSAGE_EOS:
      g_print ("End of stream\n");
      g_main_loop_quit (loop);
      break;

    case GST_MESSAGE_SEGMENT_DONE:
      g_print ("Segment done, send non-flush seek to the beginning \n");
      if (!gst_element_seek (pipeline, 1.0,
              GST_FORMAT_TIME, GST_SEEK_FLAG_ACCURATE | GST_SEEK_FLAG_SEGMENT,
              GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE)) {
        g_print ("Non flush seek failed!\n");
      }
      break;

    case GST_MESSAGE_STATE_CHANGED:
      if (GST_MESSAGE_SRC (msg) == GST_OBJECT_CAST (pipeline)) {
        GstState olds, news, pendings;
        gst_message_parse_state_changed (msg, &olds, &news, &pendings);
        if (news == GST_STATE_PAUSED && pendings == GST_STATE_PLAYING) {
          g_print ("Initial/one-shot flush seek \n");
          if (!gst_element_seek (pipeline, 1.0, GST_FORMAT_TIME,
                  GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE |
                  GST_SEEK_FLAG_SEGMENT, GST_SEEK_TYPE_SET, -1,
                  GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE)) {
            g_print ("Flush seek failed!\n");
          }
        }

      }
      break;

    case GST_MESSAGE_ERROR:{
      gchar *debug;
      GError *error;

      gst_message_parse_error (msg, &error, &debug);
      g_free (debug);

      g_printerr ("Error: %s\n", error->message);
      g_error_free (error);

      g_main_loop_quit (loop);
      break;
    }
    default:
      break;
  }

  return TRUE;
}

/* gcc -Wall -O0 main.c -o main $(pkg-config --cflags --libs gstreamer-1.0) */
int
main (int argc, char *argv[])
{
  GMainLoop *loop;

  GstElement *playbin;
  GstElement *audiovisbin, *videosink, *audiovisualizer;
  GstBus *bus;
  GstPad *pad;
  guint bus_watch_id;

  /* Initialisation */
  gst_init (&argc, &argv);
  loop = g_main_loop_new (NULL, FALSE);

  /* Check input arguments */
  if (argc != 2) {
    g_printerr ("Usage: %s <filename>\n", argv[0]);
    return -1;
  }

  /* Create gstreamer elements */
  pipeline = gst_pipeline_new ("audio-player");
  playbin = gst_element_factory_make ("playbin", NULL);
  if (!pipeline || !playbin) {
    g_printerr ("One element could not be created. Exiting.\n");
    return -1;
  }

  /* Optionally use an audio visualizer instead of autoaudiosink */
  if (g_getenv ("VISU")) {
    audiovisbin = gst_pipeline_new ("audio-visualizer");
    videosink = gst_element_factory_make ("glimagesink", NULL);
    audiovisualizer = gst_element_factory_make ("goom", NULL);
    gst_bin_add_many (GST_BIN (audiovisbin), videosink, audiovisualizer, NULL);
    pad = gst_element_get_static_pad (audiovisualizer, "sink");
    gst_element_add_pad (audiovisbin, gst_ghost_pad_new ("sink", pad));
    gst_object_unref (pad);
    gst_element_link (audiovisualizer, videosink);

    g_object_set (G_OBJECT (playbin), "audio-sink", audiovisbin, NULL);
  }

  /* we set the input filename to the source element */
  g_object_set (G_OBJECT (playbin), "uri", argv[1], NULL);

  /* we add a message handler */
  bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
  bus_watch_id = gst_bus_add_watch (bus, bus_call, loop);
  gst_object_unref (bus);

  gst_bin_add_many (GST_BIN (pipeline), playbin, NULL);

  /* Set the pipeline to "playing" state */
  g_print ("Now playing: %s\n", argv[1]);
  gst_element_set_state (pipeline, GST_STATE_PLAYING);

  /* Iterate */
  g_print ("Running...\n");
  g_main_loop_run (loop);


  /* Out of the main loop, clean up nicely */
  g_print ("Returned, stopping playback\n");
  gst_element_set_state (pipeline, GST_STATE_NULL);

  g_print ("Deleting pipeline\n");
  gst_object_unref (GST_OBJECT (pipeline));
  g_source_remove (bus_watch_id);
  g_main_loop_unref (loop);

  return 0;
}
