#include <gst/gst.h>
#include <gst/gsterror.h>
#include <gst/pbutils/install-plugins.h>

static GstElement *element = NULL;
static void make_element();

static void bus_message_cb(GstBus *bus, GstMessage *message)
{
    GError *error = NULL;
    gchar *debug;
    gchar *details[] = {"gstreamer|0.10|totem|MPEG-4 AAC decoder|decoder-audio/mpeg, mpegversion=(int)4, framed=(boolean)true", NULL};

    switch(message->type)
    {
    case GST_MESSAGE_ERROR:
        gst_message_parse_error(message, &error, &debug);
        if(error->domain == GST_CORE_ERROR && error->code == GST_CORE_ERROR_MISSING_PLUGIN)
        {
            printf("Missing plugin\n");
            gst_element_set_state(element, GST_STATE_PAUSED);

            gst_install_plugins_sync(details, NULL);
            gst_update_registry();

            gst_element_set_state(element, GST_STATE_PLAYING);
            
            /* This is required to make it work for me */
            //make_element();
        }
        else if(error->domain == GST_STREAM_ERROR && error->code == GST_STREAM_ERROR_CODEC_NOT_FOUND)
            printf("Codec not found\n");
        else
            printf("error: '%s', debug='%s'\n", error->message, debug);
        break;
    case GST_MESSAGE_EOS:
        exit(0);
        break;
    default:
        break;
    }
}

static void make_element()
{
    GstBus *bus;
    GstElement *sink;

    element = gst_element_factory_make("playbin2", NULL);
    sink = gst_element_factory_make("pulsesink", NULL);
    g_object_set(element, "audio-sink", sink, NULL);
    g_object_set(element, "uri", "file:///media/sda2/Documents and Settings/Robert Ancell/My Documents/My Music/iTunes/iTunes Music/AIR/Pocket Symphony/01 Space Maker.m4a", NULL);
    
    gst_element_set_state(sink, GST_STATE_READY);
    gst_element_set_state(element, GST_STATE_PLAYING);
    
    bus = gst_element_get_bus(element);
    gst_bus_add_signal_watch(bus);
    g_signal_connect(bus, "message", G_CALLBACK(bus_message_cb), NULL);
}

int main(int argc, char **argv)
{
    GMainLoop *loop;
    
    gst_init(&argc, &argv);
    
    make_element();

    loop = g_main_loop_new(NULL, FALSE);
    g_main_loop_run(loop);

    return 0;
}
