/*
 *	modified by Yoshifumi Nishida <nishida@csl.sony.co.jp> for magicpoint
 */
/*
	mngplay

	$Date: 2004/09/01 03:50:32 $

	Ralph Giles <giles@ashlu.bc.ca>

	This program my be redistributed under the terms of the
	GNU General Public Licence, version 2, or at your preference,
	any later version.

	(this assuming there's no problem with libmng not being GPL...)


	this is an SDL based mng player. the code is very rough;
	patches welcome.
*/
/*
 * $Id: mng.c,v 1.2 2004/09/01 03:50:32 nishida Exp $
 */

#ifdef MNG

#include <sys/time.h>
#include <libmng.h>
#include "mgp.h"

static GC gcmng;
static Display *mngdisplay;
static int mngscreen;
static Visual  *mngvisual;
static mng_handle mng;

/* structure for keeping track of our mng stream inside the callbacks */
typedef struct {
	FILE		*file;	   /* pointer to the file we're decoding */
	char		*filename; /* pointer to the file's path/name */
	Image 		*image;	
	Window 		window;
	mng_uint32	delay;     /* ticks to wait before resuming decode */
} mngstuff;

void mng_window_setup __P((mngstuff *mymng, int x, int y, int width, int height));

/* callbacks for the mng decoder */

/* memory allocation; data must be zeroed */
mng_ptr mymngalloc(mng_uint32 size)
{
	return (mng_ptr)calloc(1, size);
}

/* memory deallocation */
void mymngfree(mng_ptr p, mng_uint32 size)
{
	free(p);
	return;
}

mng_bool mymngopenstream(mng_handle mng)
{
	mngstuff	*mymng;

	/* look up our stream struct */
	mymng = (mngstuff*)mng_get_userdata(mng);
	
	/* open the file */
	mymng->file = fopen(mymng->filename, "rb");
	if (mymng->file == NULL) {
		fprintf(stderr, "unable to open '%s'\n", mymng->filename);
		return MNG_FALSE;
	}

	return MNG_TRUE;
}

mng_bool mymngclosestream(mng_handle mng)
{
	mngstuff	*mymng;

	/* look up our stream struct */
        mymng = (mngstuff*)mng_get_userdata(mng);

	/* close the file */
	fclose(mymng->file);
	mymng->file = NULL;	/* for safety */

	return MNG_TRUE;
}

/* feed data to the decoder */
mng_bool mymngreadstream(mng_handle mng, mng_ptr buffer,
		mng_uint32 size, mng_uint32 *bytesread)
{
	mngstuff *mymng;

	/* look up our stream struct */
	mymng = (mngstuff*)mng_get_userdata(mng);

	/* read the requested amount of data from the file */
	*bytesread = fread(buffer, 1, size, mymng->file);

	return MNG_TRUE;
}

/* the header's been read. set up the display stuff */
mng_bool mymngprocessheader(mng_handle mng,
		mng_uint32 width, mng_uint32 height)
{
	mngstuff	*mymng;
	Image 		*image;
	Visual		*get_visual();

	image = (Image *)malloc(sizeof(Image));
	image->type= ITRUE;
	image->title= strdup("");
	image->rgb.used= image->rgb.size= 0;
	image->width= width;
	image->height= height;
	image->depth= 24;
	image->pixlen= 3;
	image->data = (char *)malloc(width * height * 24);

	if (image->data == NULL){
		fprintf(stderr, "unable to allocate %dx%d video memory \n", 
			width, height);
		return MNG_FALSE;
	}

	/* save the image pointer */
 	mymng = (mngstuff*)mng_get_userdata(mng);
	mymng->image = image;

	/* tell the mng decoder about our bit-depth choice */
	/* FIXME: this works on intel. is it correct in general? */
	mng_set_canvasstyle(mng, MNG_CANVAS_RGB8);

	return MNG_TRUE;
}

/* return a row pointer for the decoder to fill */
mng_ptr mymnggetcanvasline(mng_handle mng, mng_uint32 line)
{
	mngstuff	*mymng;
	mng_ptr		row;

	/* dereference our structure */
	mymng = (mngstuff*)mng_get_userdata(mng);

	/* we assume any necessary locking has happened 
	   outside, in the frame level code */
	row = mymng->image->data + 
				mymng->image->pixlen * mymng->image->width * line;

	return (row);
}

/* timer */
mng_uint32 mymnggetticks(mng_handle mng)
{
	struct timeval now;
	mng_uint32 ticks;

    gettimeofday(&now, NULL);
    ticks=(now.tv_sec)*1000+(now.tv_usec)/1000;

	return(ticks);
}

mng_bool mymngrefresh(mng_handle mng, mng_uint32 x, mng_uint32 y,
			mng_uint32 w, mng_uint32 h)
{
	XImageInfo *ximageinfo;
	mngstuff	*mymng;

	/* dereference our structure */
	mymng = (mngstuff*)mng_get_userdata(mng);

	ximageinfo= imageToXImage(mngdisplay, mngscreen, mngvisual, depth,
			mymng->image, 0, 0, 0, 0);
	if (ximageinfo == NULL) {
		fprintf(stderr, "Cannot convert Image to XImage\n");
		exit(-1);
	}
	XPutImage(mngdisplay, mymng->window, gcmng, ximageinfo->ximage, 
		0, 0, 0, 0, mymng->image->width, mymng->image->height);

	freeXImage(ximageinfo->ximage, ximageinfo);

	return MNG_TRUE;
}

/* interframe delay callback */
mng_bool mymngsettimer(mng_handle mng, mng_uint32 msecs)
{
	mngstuff	*mymng;

	/* look up our stream struct */
	mymng = (mngstuff*)mng_get_userdata(mng);

	/* set the timer for when the decoder wants to be woken */
	mymng->delay = msecs;

	return MNG_TRUE;
}

mng_bool mymngerror(mng_handle mng, mng_int32 code, mng_int8 severity,
	mng_chunkid chunktype, mng_uint32 chunkseq,
	mng_int32 extra1, mng_int32 extra2, mng_pchar text)
{
	mngstuff	*mymng;
	char		chunk[5];
	
	/* dereference our data so we can get the filename */
	mymng = (mngstuff*)mng_get_userdata(mng);

	/* pull out the chuck type as a string */
	// FIXME: does this assume unsigned char?
	chunk[0] = (char)((chunktype >> 24) & 0xFF);
	chunk[1] = (char)((chunktype >> 16) & 0xFF);
	chunk[2] = (char)((chunktype >>  8) & 0xFF);
	chunk[3] = (char)((chunktype      ) & 0xFF);
	chunk[4] = '\0';

	/* output the error */

	return (0);
}

void mymngquit()
{
	mngstuff	*mymng;

	/* dereference our data so we can free it */
	mymng = (mngstuff*)mng_get_userdata(mng);

	XDestroyWindow(display, mymng->window);	

	/* cleanup. this will call mymngclosestream */
	mng_cleanup(&mng);

	/* free our data */
	free(mymng);

	/* quit */
	exit(0);
}

int checkevents(mng_handle mng)
{
	/* not implemented yet */
}

void
mngload(mngfile, x, y, width, height)
	char *mngfile;
	int x, y;
	int width, height;
{
	mngstuff	*mymng;
	u_int		myretcode;

	signal(SIGTERM, mymngquit);

	/* allocate our stream data structure */
	mymng = (mngstuff*)calloc(1, sizeof(*mymng));
	if (mymng == NULL) {
		fprintf(stderr, "could not allocate stream structure.\n");
		exit(0);
	}

	/* pass the name of the file we want to play */
	mymng->filename = mngfile;

	/* set up the mng decoder for our stream */
	mng = mng_initialize(mymng, mymngalloc, mymngfree, MNG_NULL);
	if (mng == MNG_NULL) {
		fprintf(stderr, "could not initialize libmng.\n");
		exit(1);
	}

	/* set the callbacks */
	mng_setcb_errorproc(mng, mymngerror);
	mng_setcb_openstream(mng, mymngopenstream);
	mng_setcb_closestream(mng, mymngclosestream);
	mng_setcb_readdata(mng, mymngreadstream);
	mng_setcb_gettickcount(mng, mymnggetticks);
	mng_setcb_settimer(mng, mymngsettimer);
	mng_setcb_processheader(mng, mymngprocessheader);
	mng_setcb_getcanvasline(mng, mymnggetcanvasline);
	mng_setcb_refresh(mng, mymngrefresh);
	/* FIXME: should check for errors here */

	myretcode = mng_set_suspensionmode(mng, MNG_TRUE);
	if (myretcode != MNG_NOERROR){
		fprintf(stderr, "something happen.\n");
		exit(-1);
	}

	mng_window_setup(mymng, x, y, width, height);
	mng_readdisplay(mng);

	/* loop though the frames */
	while (mymng->delay) {

		usleep(mymng->delay * 1000);

		/* reset the delay in case the decoder
		   doesn't update it again */
		mymng->delay = 0;

		mng_display_resume(mng);

		/* check for user input (just quit at this point) */
		checkevents(mng);
	}
}

void 
mng_window_setup(mymng, x, y, width, height)
	mngstuff	*mymng;
	int x, y;
	int width, height;
{
	Visual		*get_visual();

	if (!mngdisplay){
	    if ((mngdisplay = XOpenDisplay(NULL)) == NULL) {
			fprintf(stderr, "Can't open display\n");
			exit(-1);
		}
		mngscreen = DefaultScreen(mngdisplay);
		mngvisual = get_visual(mngdisplay, mngscreen, &depth);
	}

	mymng->window = XCreateSimpleWindow(mngdisplay, 
		window,
		0, 0,
		width, height, 0, 
		WhitePixel(display, 0), WhitePixel(display, 0));

	XMoveWindow(mngdisplay, mymng->window, x, y);
	XMapRaised(mngdisplay, mymng->window);
	XFlush(mngdisplay);

	if (!gcmng)
		gcmng = XCreateGC(mngdisplay, mymng->window, 0, 0);
}

void
mngpreload(state, mngfile, width, height)
	struct render_state *state;
	char *mngfile;
	int *width, *height;
{
	mngstuff	*mymng;
	mng_handle	mng;
	u_int		myretcode;

	/* allocate our stream data structure */
	mymng = (mngstuff*)calloc(1, sizeof(*mymng));
	if (mymng == NULL) {
		fprintf(stderr, "could not allocate stream structure.\n");
		exit(0);
	}

	/* pass the name of the file we want to play */
	mymng->filename = mngfile;

	/* set up the mng decoder for our stream */
	mng = mng_initialize(mymng, mymngalloc, mymngfree, MNG_NULL);
	if (mng == MNG_NULL) {
		fprintf(stderr, "could not initialize libmng.\n");
		exit(1);
	}

	/* set the callbacks */
	mng_setcb_errorproc(mng, mymngerror);
	mng_setcb_openstream(mng, mymngopenstream);
	mng_setcb_closestream(mng, mymngclosestream);
	mng_setcb_readdata(mng, mymngreadstream);
	mng_setcb_gettickcount(mng, mymnggetticks);
	mng_setcb_settimer(mng, mymngsettimer);
	mng_setcb_processheader(mng, mymngprocessheader);
	mng_setcb_getcanvasline(mng, mymnggetcanvasline);
	mng_setcb_refresh(mng, mymngrefresh);
	/* FIXME: should check for errors here */

	mng_read(mng);
	*width = mymng->image->width;
	*height = mymng->image->height;

	mng_cleanup(&mng);
	free(mymng);
}
#endif
