#include <gavl/gavl.h>
#include <gavl/peakdetector.h>
#include <stdio.h>
#include <assert.h>

void print_audioframe(gavl_audio_frame_t*frame, int channels, int with_samples) {
	int i, j;
	printf("audio-frame @ %p\n", frame);
	printf("\ttime   : %lld\n", (long long)frame->timestamp);
	printf("\tstride : %d\n", frame->channel_stride);
	printf("\tsamples: %d\n", frame->valid_samples);
	printf("\tsamples: %p\n", frame->samples.f);
	for (i=0; i<channels; i++) {
		printf("\t	[%d]: %p\n", i, frame->channels.f[i]);
	}
}

int main() {
	int i;
	float*left, *right;
	double min, max, abs;
	gavl_peak_detector_t* pd = 0;
	gavl_audio_frame_t* frame = 0;
	gavl_audio_format_t fmt = {
		.samples_per_frame=64,
		.samplerate=44100,
		.num_channels=2,
		.sample_format=GAVL_SAMPLE_FLOAT,
		.interleave_mode=GAVL_INTERLEAVE_ALL,
		.center_level=1.f,
		.rear_level=1.f,
	};
	fmt.channel_locations[0] = GAVL_CHID_FRONT_LEFT;
	fmt.channel_locations[1] = GAVL_CHID_FRONT_RIGHT;
	//gavl_audio_format_dump(&fmt);

	frame = gavl_audio_frame_create (&fmt);
	assert(frame);

	/* fill the audio frame */
	left = frame->channels.f[0];
	right = frame->channels.f[1];
	for(i=0; i<fmt.samples_per_frame; i++) {
		*left++ = ((float)i)/((float)fmt.samples_per_frame) * 1.5f - 0.5;
		*right++ = 0.f;
	}
	frame->valid_samples=fmt.samples_per_frame;

	/* print the audio frames */
	print_audioframe(frame, fmt.num_channels, 0);

	/* detect peaks */
	pd = gavl_peak_detector_create ();
	assert(pd);

	gavl_peak_detector_set_format(pd, &fmt);
	gavl_peak_detector_update(pd, frame);
	gavl_peak_detector_get_peak(pd, &min, &max, &abs);

	printf("min=%g, max=%g, abs=%g\n", min, max, abs);

	/* cleanup */
	gavl_peak_detector_destroy(pd);
	gavl_audio_frame_destroy(frame);

	/* check if values are correct */
	assert(min == -0.5);
	assert(max == ((1.5f*63.)/64. - 0.5));
	assert(max == abs);

	return 0;
}
