#include <fb.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/nttypes.h>
#include <sys/xboxkrnl.h>
#include <ntfile.h>
#include <xbox.h>
#include <string.h>
#include <stdio.h>

#include "VideoHelpers.h"


void jpeg_direct_src (j_decompress_ptr pcinfo, char * pbStartOfBuffer, unsigned int nLength);

int JpegUnpackAsRgb(BYTE *pbaJpegFileImage,ULONG nFileLength, JPEG *pJpeg) {

	BYTE *pbaResultAsRgb;
	BYTE *pbaResultAsRgbStart;
	int row_stride=0;	
	struct jpeg_decompress_struct cinfo;
	struct jpeg_error_mgr jerr;
	JSAMPARRAY buffer;
  
	pJpeg->pBitmapData=NULL;
	cinfo.err = jpeg_std_error(&jerr);
  
	jpeg_create_decompress(&cinfo);
	jpeg_direct_src(&cinfo, pbaJpegFileImage, nFileLength);
	(void) jpeg_read_header(&cinfo, TRUE);
	(void) jpeg_start_decompress(&cinfo);

	row_stride = cinfo.output_width * cinfo.output_components;
	pbaResultAsRgb=(PUCHAR)MmAllocateContiguousMemoryEx(row_stride * cinfo.output_height,
			MIN_KERNEL, MAX_KERNEL, 0, PAGE_READWRITE);
	pbaResultAsRgbStart=pbaResultAsRgb;

	buffer = (*(cinfo.mem->alloc_sarray))((j_common_ptr)&cinfo, JPOOL_IMAGE, row_stride, 1);

	pJpeg->nWidth=cinfo.output_width;
	pJpeg->nHeight=cinfo.output_height;
	pJpeg->nBytesPerPixel=cinfo.output_components;
	pJpeg->pBitmapData=pbaResultAsRgbStart;
      

	while (cinfo.output_scanline < cinfo.output_height) {
		(void) jpeg_read_scanlines(&cinfo, buffer, 1);
		memcpy(pbaResultAsRgb, buffer[0], row_stride);
		pbaResultAsRgb+=row_stride;
	}
	if(jerr.num_warnings==0) {
		return 1;
	}

	MmFreeContiguousMemory(pbaResultAsRgbStart);
	return 0;
}

int LoadJpeg(char *szFileName, JPEG *pJpeg) {

	PUCHAR Buffer;
	ULONGLONG FileSize = 0;
	FILE *fp;

	fp = fopen(szFileName,"r");
	if(fp == NULL) return 0;
	
	fseek(fp,0,SEEK_END);
	FileSize = ftell(fp);
	fseek(fp,0,SEEK_SET);
	Buffer = (PUCHAR)MmAllocateContiguousMemoryEx(FileSize, MIN_KERNEL, 
			MAX_KERNEL, 0, PAGE_READWRITE);
	if(!Buffer) {
		fclose(fp);
		return 0;
	}

	fread(Buffer,1,FileSize,fp);
	fclose(fp);

	memset(pJpeg,0,sizeof(JPEG));
	if(!JpegUnpackAsRgb(Buffer,FileSize,pJpeg)) {
		
		free(Buffer);
		return 0;
	}
	
	free(Buffer);
	return 1;

}
