#include <stdlib.h>
#include <stdio.h>

#include <glib.h>
#include <gst/gst.h>
#include <gst/tag/tag.h>
#include <gst/audio/gstaudiocdsrc.h>

int main(void) {
	GstElement *source, *pipeline, *sink;
	GstBus *bus;
	GstMessage *msg;
	GstTagList *tags;
	gchar *device;
	gchar *discid = NULL;
	gchar *discid_full = NULL;
	char **hex_offsets;
	int i, count;

	gst_init(NULL, NULL);
	printf("gstreamer version: %s\n", gst_version_string());

	source = gst_element_make_from_uri(GST_URI_SRC, "cdda://", NULL, NULL);
	pipeline = gst_pipeline_new(NULL);
	sink = gst_element_factory_make("fakesink", NULL);
	bus = gst_pipeline_get_bus(GST_PIPELINE (pipeline));
	if (!source || !pipeline || !sink || !bus) {
		fprintf(stderr, "aborted!\n");
		return 1;
	}

	g_object_get(G_OBJECT (source), "device", &device, NULL);
	g_print("device name: %s\n", device);
	g_free(device);

	gst_bin_add_many(GST_BIN (pipeline), source, sink, NULL);
	gst_element_link(source, sink);

	gst_element_set_state(pipeline, GST_STATE_PAUSED);
	while(1) {
		msg = gst_bus_pop(bus); 
		if (msg && GST_MESSAGE_TYPE (msg) == GST_MESSAGE_TAG) {
			gst_message_parse_tag(msg, &tags);
			gst_tag_list_get_string(tags,
					GST_TAG_CDDA_MUSICBRAINZ_DISCID,
					&discid);
			gst_tag_list_get_string(tags,
					GST_TAG_CDDA_MUSICBRAINZ_DISCID_FULL,
					&discid_full);
			if (tags) gst_tag_list_free(tags);
			break;
		}
		if (msg) gst_message_unref(msg);
	}
	g_print("discid: %s\n", discid);
	/* display discid_full in readable form (non-hex) */
	hex_offsets = g_strsplit(discid_full, " ", 0);
	count = g_strv_length(hex_offsets);
	g_print("discid full: ");
	for (i = 1; i < count; i++) {
		g_print("%ld ", strtol(hex_offsets[i], 0, 16));
	}
	g_print("\n");
	return 0;
}
