#include "avilib.h"

void bgr24toxrgb32(u8_t *xrgb_ptr,u8_t *rgb_ptr,int width,int height)
{
	u8_t *endsrcptr = rgb_ptr + (width * height * 3);
	while(rgb_ptr < endsrcptr)
	{
		xrgb_ptr[0] = rgb_ptr[2];
		xrgb_ptr[1] = rgb_ptr[1];
		xrgb_ptr[2] = rgb_ptr[0];
		xrgb_ptr[3] = 0;
		
		rgb_ptr += 3;
		xrgb_ptr += 4;
	}
}

void decompose(avi_t *avi)
{
	u8_t *rawptr;
	u8_t *frameptr;
	int i,frames,width,height;
	char fname[_MAX_PATH];
	if(memcmp(AVI_video_compressor(avi),"DIB ",4))
	{
		puts("Compressed file, couldn't decompose()");
		return;
	}
	frames = AVI_video_frames(avi);
	width = AVI_video_width(avi);
	height = AVI_video_height(avi);
	rawptr = memAlloc(width * height * 3);
	frameptr = memAlloc(width * height * 4);

	for(i=0;i<frames;i++)
	{
		AVI_read_frame(avi,rawptr);
		bgr24toxrgb32(frameptr,rawptr,width,height);
		sprintf(fname,"frame%04d.tga",i);
		tgaSave(fname,width,height,frameptr);
	}

	memFree(frameptr);
	memFree(rawptr);
}

int main()
{
	avi_t *avi;

	logStartConsoleLog();
	logUpperLevel(LOG_TRACE);
	avi = AVI_open_input_file("../../../media/rings.avi",1);
	if(!avi)
		return -1;
	printf(
		"frames\t%d\n"
		"width\t%d\n"
		"height\t%d\n"
		"fps\t%f\n"
		"compressor\t'%s'\n",
		AVI_video_frames(avi),
		AVI_video_width(avi),
		AVI_video_height(avi),
		AVI_video_frame_rate(avi),
		AVI_video_compressor(avi));
	
	decompose(avi);
	
	AVI_close(avi);
	memPrintStats();
	return 0;
}
