/* test-playbin2.c

libtool --mode=link gcc `pkg-config --cflags --libs gstreamer-0.10` -o test-playbin2 test-playbin2.c -Wall -ggdb

*/

#include <gst/gst.h>

#define URI_APPLE_REDIRECT \
    "http://stream.qtv.apple.com/events/jan/1001q3f8hhr/1001908r5ft6dswz_1_350_ref.mov"

#define gst_structure_dup_string(s,f) \
    g_strdup(gst_structure_get_string(s,f))

int
main (int argc, char **argv)
{
  GstStateChangeReturn sret;
  GstElement *playbin;
  gboolean done = FALSE;
  gchar *next_uri = NULL;

  gst_init (&argc, &argv);

  playbin = gst_element_factory_make ("playbin2", NULL);

  g_object_set (playbin, "uri", URI_APPLE_REDIRECT, NULL);

  sret = gst_element_set_state (playbin, GST_STATE_PAUSED);

  if (sret == GST_STATE_CHANGE_FAILURE)
    g_error ("State change failed\n");

  do {
    GstMessage *msg;

    msg = gst_bus_timed_pop_filtered (GST_ELEMENT_BUS (playbin),
        GST_CLOCK_TIME_NONE, GST_MESSAGE_ELEMENT);

    if (gst_structure_has_name (msg->structure, "redirect")) {
      next_uri = gst_structure_dup_string (msg->structure, "new-location");
      if (next_uri != NULL)
        break;
      g_error ("Redirect message without new location!\n");
    }

    gst_message_unref (msg);
  }
  while (!done);

  g_print ("Got redirect to: %s\n", next_uri);

  gst_bus_set_flushing (GST_ELEMENT_BUS (playbin), TRUE);

  //gst_element_set_state (playbin, GST_STATE_NULL);
  gst_element_set_state (playbin, GST_STATE_READY);

  gst_bus_set_flushing (GST_ELEMENT_BUS (playbin), FALSE);

  g_object_set (playbin, "uri", next_uri, NULL);
  g_free (next_uri);

  sret = gst_element_set_state (playbin, GST_STATE_PLAYING);

  if (sret == GST_STATE_CHANGE_FAILURE)
    g_error ("State change failed\n");

  do {
    GstMessage *msg;

    msg = gst_bus_timed_pop_filtered (GST_ELEMENT_BUS (playbin),
        GST_CLOCK_TIME_NONE, GST_MESSAGE_EOS | GST_MESSAGE_ASYNC_DONE |
        GST_MESSAGE_ERROR);

    switch (GST_MESSAGE_TYPE (msg)) {
      case GST_MESSAGE_ASYNC_DONE:
        g_print ("Prerolled.\n");
        break;
      case GST_MESSAGE_EOS:
        g_print ("EOS\n");
        done = TRUE;
        break;
      case GST_MESSAGE_ERROR:
        g_error ("ERROR: %s\n", gst_structure_to_string (msg->structure));
        done = TRUE;
        break;
      default:
        break;
    }

    gst_message_unref (msg);
  }
  while (!done);

  gst_element_set_state (playbin, GST_STATE_NULL);
  gst_object_unref (playbin);

  return 0;
}

