#include "testlib.h"

#include <AL/al.h>
#include <AL/alc.h>
#include <AL/alext.h>
#include <AL/alut.h>

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


#define NUMCAPTURES   3
#define WAVEFILE      "boom.wav"
#define FREQ          44100
#define SAMPLES       (10 * FREQ)

static void cleanup(void);

static ALuint caps[NUMCAPTURES] = { 0 };

static void *context_id;

void cleanup(void) {
	alcDestroyContext(context_id);

#ifdef JLIB
	jv_check_mem();
#endif
}

int main( int argc, char* argv[] ) {
	ALCdevice *dev;
	ALuint cpid;
	ALuint sid = 0;
	ALuint cbid;
	ALuint sbid;
	ALuint retval;
	ALvoid *buffer = NULL;
	FILE *fh;

	dev = alcOpenDevice( NULL );
	if( dev == NULL ) {
		return 1;
	}

	/* Initialize openal. */
	context_id = alcCreateContext( dev, NULL);
	if(context_id == NULL) {
		alcCloseDevice( dev );

		return 1;
	}

	alcMakeContextCurrent( context_id );

	alEnable( AL_CAPTURE_EXT );

	fixup_function_pointers();

	/*                    test 1              */
	fprintf(stderr, "test1\n");

	alGenCaptures(NUMCAPTURES, caps);
	sleep(1);
	alDeleteCaptures(NUMCAPTURES, caps);


	/*                    test 2              */
	fprintf(stderr, "test2\n");

	alGenCaptures(1, &cpid);
	alGenBuffers(1, &cbid);

	alCapturei(cpid, AL_BUFFER, cbid);

	fprintf(stderr, "recording...");
	alCaptureStart(cpid);
	sleep(SAMPLES / FREQ);
	alCaptureStop(cpid);
	fprintf(stderr, "\n");

	buffer = malloc(SAMPLES * 2);

	retval = alBufferRetrieveData(cbid,
			    AL_FORMAT_MONO16,
			    buffer,
			    SAMPLES,
			    FREQ);

	fh = fopen("outpcm.pcm", "wb");
	if(fh != NULL) {
		fwrite(buffer, retval * 2, 1, fh);
		fclose(fh);
	}

	free(buffer);

	/*                    test 3              */
	fprintf(stderr, "test3\n");

	fprintf(stderr, "recording...");
	alCaptureStart(cpid);
	sleep(SAMPLES / FREQ);
	alCaptureStop(cpid);
	fprintf(stderr, "\n");

	fprintf(stderr, "retrieving...");
	buffer = malloc( SAMPLES * 2 );

	retval = alBufferRetrieveData(cbid,
			    AL_FORMAT_MONO16,
			    buffer,
			    SAMPLES,
			    FREQ);
	fprintf(stderr, "\n");

	fprintf(stderr, "playback...");
	alGenSources(1, &sid);
	alGenBuffers(1, &sbid);
	alSourcei(sid, AL_BUFFER, sbid);

	alBufferData(sbid, AL_FORMAT_MONO16, buffer, SAMPLES * 2, FREQ);
	free(buffer);

	alSourcePlay(sid);

	while(SourceIsPlaying(sid) == AL_TRUE) {
		sleep(1);
	}

	fprintf(stderr, "\n");

	cleanup();

	alcCloseDevice( dev );

	return 0;
}
