#include <gst/gst.h>
#include <ges/ges.h>
#include <stdio.h>
#include <string.h>

/**** Test case for GStreamer Editing Services *****/
/* Compile using:
 * gcc `pkg-config gst-editing-services-1.0 --cflags` \
 *     `pkg-config gst-editing-services-1.0 --libs` \
 *     -Wall main.c -o main
 */

char* effectbin = "taginject tags=\"replaygain-track-gain=-10.0,replaygain-track-peak=1.0,replaygain-reference-level=89.000\" ! rgvolume";

void add_effect_to_clip(GESClip *clip) {
	GESAsset *effect_asset = ges_asset_request(GES_TYPE_EFFECT, effectbin, NULL);
	GESEffect *effect = GES_EFFECT(ges_asset_extract(effect_asset, NULL));
	printf("Adding effect: %s\n", effectbin);
	ges_container_add(GES_CONTAINER(clip), GES_TIMELINE_ELEMENT(effect));
}

int main(int argc, char *argv[]) {
	/* Initialization */
	gst_init(&argc, &argv);
	ges_init();

	GMainLoop *loop = g_main_loop_new(NULL, FALSE);

	GESPipeline *pipeline = ges_pipeline_new();
	GESTimeline *timeline = ges_timeline_new();
	ges_pipeline_set_timeline(pipeline, timeline);

	GESTrack *audiotrack = GES_TRACK(ges_audio_track_new());
	ges_timeline_add_track(timeline, audiotrack);

	/* work-around for #753147 */
	{
		GstElement *sink = gst_parse_bin_from_description ("audioconvert ! autoaudiosink", TRUE, NULL);
		ges_pipeline_preview_set_audio_sink(pipeline, sink);
	}

	/* Initialization of test sound layer to prevent gaps */
	{
		GESLayer *beep_layer = ges_timeline_append_layer(timeline);
		GESAsset *test_asset = ges_asset_request (GES_TYPE_TEST_CLIP, NULL, NULL);
		GESClip *test_clip = ges_layer_add_asset(beep_layer, test_asset,
			0, 0, 6 * GST_SECOND, GES_TRACK_TYPE_UNKNOWN);
		ges_test_clip_set_volume(GES_TEST_CLIP(test_clip), 0.05);

		GESClip *test_clip2 = ges_layer_add_asset(beep_layer, test_asset,
			6 * GST_SECOND, 6 * GST_SECOND, 6 * GST_SECOND, GES_TRACK_TYPE_UNKNOWN);
		ges_test_clip_set_volume(GES_TEST_CLIP(test_clip2), 0.01);
	}

	/* Initialization of layer */
	GESLayer *layer = ges_timeline_append_layer(timeline);

	/* Another test sound probably works as well, but then the tempo change isn't audible */
	gchar *uri = gst_filename_to_uri("foo.mp3", NULL);
	GESUriClipAsset *asset = GES_URI_CLIP_ASSET(ges_uri_clip_asset_request_sync(uri, NULL));
	GESClip *clip = ges_layer_add_asset(layer, GES_ASSET(asset),
		0, 0, 20 * GST_SECOND, GES_TRACK_TYPE_UNKNOWN);

	if(!asset || !clip) {
		fprintf(stderr, "Asset not created, check that a 'foo.mp3' exists\n");
		return 1;
	}

	add_effect_to_clip(clip);

	gst_element_set_state(GST_ELEMENT(pipeline), GST_STATE_PLAYING);
	g_main_loop_run(loop);

	return 0;
}
