/* testing using queue2 to do http-streaming while save-to-file 
 * 
 * To build the sample:
 * gcc -o pp save-test.c -g `pkg-config --cflags --libs gstreamer-base-0.10 gobject-2.0`
 * To Run the sample:
 * ./a.out URI
 * ex:
 * ./a.out http://some.address/test.mp4
 *
 */
#include <gst/gst.h>

static void
deep_cb(GstObject  *gstobject,
      GstObject  *prop_object,
      GParamSpec *prop,
      gpointer data)
{
  char *name;
  g_object_get (G_OBJECT (prop_object),
    "temp-location", &name,
    NULL);
  g_print("deep_cb:%s\n", name);

}

static gboolean 
bus_call (GstBus * bus, GstMessage * msg, gpointer data)
{
    GMainLoop *loop = 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_ERROR:{
            gchar *debug = NULL;
            GError *err = NULL;
            gst_message_parse_error(msg, &err, &debug);
            g_print("Error: %s\n", err->message);
            g_error_free(err);
            if (debug) {
                g_print("Debug details: %s\n", debug);
                g_free(debug);
            }
            g_main_loop_quit(loop);
            break;
        }
    default:
        break;
    }
    return GST_BUS_PASS;
}

gint main(gint argc, gchar * argv[])
{
    GstStateChangeReturn ret;
    GstElement *pipeline, *src, *filter, *sink, *decoder;
    GMainLoop *loop;
    GstBus *bus;
    GError *error = NULL;
    gint flags;
/* initialization */
    gst_init(&argc, &argv);
    loop = g_main_loop_new(NULL, FALSE);
    pipeline = gst_element_factory_make ("playbin2", "playbin");

    if (!pipeline) {
      fprintf (stderr, "Parse error: %s", error->message);
      exit (-1);
    }
    g_object_get (pipeline, "flags", &flags, NULL);
    g_object_set (pipeline, "flags", flags | 0x80, NULL);

    g_object_set (G_OBJECT (pipeline), "uri", argv[1], NULL);

    g_signal_connect (pipeline, "deep-notify::temp-location",
      G_CALLBACK (deep_cb), pipeline);

    bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline));
    gst_bus_add_watch(bus, bus_call, loop);
//    gst_bus_set_sync_handler (bus, (GstBusSyncHandler) bus_sync_handler, loop);
    gst_object_unref(bus);

/* run */
    ret = gst_element_set_state(pipeline, GST_STATE_PLAYING);
    if (ret == GST_STATE_CHANGE_FAILURE) {
        GstMessage *msg;
        g_print("Failed to start up pipeline!\n");
        return -1;
    }
    g_main_loop_run(loop);
/* clean up */
    gst_element_set_state(pipeline, GST_STATE_NULL);
    gst_object_unref(pipeline);
    return 0;
}
