/* output.c */

#include "mphead.h"

#include <linux/string.h>
#include <sys/types.h>
#include <sys/timeb.h>

extern mb_width,width,height,mod_y,mod_c,gray,frames;
extern struct pict_image *current;
extern char *vram;

extern double_display;

double y_scale = 2.0,c_scale = 2.0,c_offset = 0.4;

static __ll;

#define LIMIT(a)	(__ll=(a),__ll<0 ? 0 : __ll>255 ? 255 : __ll)
#define Y_CONV(a)	LIMIT((a)*y_scale*128)
#define C_CONV(a)	LIMIT((a)*c_scale*256+256*c_offset)

static frames = 0;
static struct timeb start;

init_output()
{
	int i;
	double j;
	unsigned char pal[768];

	if (gray)
		for (i=0; i<64*3; i++)
			pal[i] = i*4/3;
	else
		for (i=0; i<64; i++) {
			j = i/64.0;
			pal[i*3+0] = pal[i*3+1] = pal[i*3+2] = Y_CONV(j);
			j -= 0.5;
			pal[(i+64)*3+0] = C_CONV(j*1.40200);
			pal[(i+64)*3+1] = C_CONV(-j*0.71414);
			pal[(i+64)*3+2] = pal[(i+128)*3+0] = C_CONV(0);
			pal[(i+128)*3+1] = C_CONV(-j*0.34414);
			pal[(i+128)*3+2] = C_CONV(j*1.77200);
		}
	graph_mode(pal);
	ftime(&start);
}

output_frame()
{
	int hs,vs;
	unsigned char *a,*b;

	frames++;
	if (gray) {
		hs = width>320 ? 320 : width;
		vs = height>200 ? 200 : height;
		a = vram;
		b = current->lum;
		do {
			memcpy(a,b,hs);
			a += 320;	
			b += mod_y;
		} while (--vs);
	}
	else if (double_display) {
		hs = (width>160 ? 160 : width)/2;
		vs = (height>100 ? 100 : height)/2;
		dither2(vram,current->lum,current->lum+mod_y,
current->cb,current->cr,
mod_c-hs,(mod_y-hs)*2,(320-hs)*4,hs,vs);
	}
	else {
		hs = (width>320 ? 320 : width)/2 + 1 & ~1;
		vs = (height>200 ? 200 : height)/2;
		dither(vram,current->lum,current->lum+mod_y,
current->cb,current->cr,
mod_c-hs,(mod_y-hs)*2,(320-hs)*2,hs,vs);
	}
}

end_output()
{
	int i;
	struct timeb end;

	ftime(&end);
	i = (end.time-start.time)*1000+end.millitm-start.millitm;
	printf("%d frames %g frames/sec\n",frames,frames*1000.0/i);
}
