/* ppmtosunyuv.c - convert a portable pixmap into an Abekas YUV file
**
** Copyright (C) 2009 by Fedor Konstantinov <blmink@gmail.com>
**
** by Marc Boucher
** Internet: marc@PostImage.COM
**
** Based on Example Conversion Program, A60/A64 Digital Video Interface
** Manual, page 69.
**
** Copyright (C) 1991 by DHD PostImage Inc.
** Copyright (C) 1987 by Abekas Video Systems Inc.
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted, provided
** that the above copyright notice appear in all copies and that both that
** copyright notice and this permission notice appear in supporting
** documentation.  This software is provided "as is" without express or
** implied warranty.
*/

#include "ppm.h"

int
main(argc, argv)
char **argv;
{
	FILE *ifp;
	pixel          *pixelrow;
	register pixel *pP;
	int             rows, cols, format, row;
	register int    col;
	pixval          maxval;
	unsigned long   y1, u1, v1;
	unsigned char  *yuvbuf;

	ppm_init(&argc, argv);

	if (argc > 2) pm_usage("[ppmfile]");

	if (argc == 2) ifp = pm_openr(argv[1]);
	else ifp = stdin;

	ppm_readppminit(ifp, &cols, &rows, &maxval, &format);

	pixelrow = ((pixel*) pm_allocrow( cols, sizeof(pixel) ));
	yuvbuf = (unsigned char *) malloc( cols * 3 );

	printf("AYUV");
	printf("%c%c", (cols >> 8) & 0xff, cols & 0xff);
	printf("%c%c", (rows >> 8) & 0xff, rows & 0xff);
	printf("%c%c%c%c", 1, 1, 0, 0);

	for (row = 0; row < rows; ++row) {
		unsigned char *yuvptr;

		ppm_readppmrow(ifp, pixelrow, cols, maxval, format);

		for (col = 0, pP = pixelrow, yuvptr=yuvbuf; col < cols; col++, ++pP) {
			pixval r, g, b;

			r = PPM_GETR(*pP);
			g = PPM_GETG(*pP);
			b = PPM_GETB(*pP);

			y1 = 16829 * r + 33039 * g + 6416 * b;
			u1 = -4853 * r - 9530 * g + 14383 * b;
			v1 = 14386 * r - 12046 * g - 2340 * b;

			y1 = (y1 >> 16) + 16;
			u1 = (u1 >> 16) + 128;
			v1 = (v1 >> 16) + 128;

			*yuvptr = u1;
			*(yuvptr + cols) = v1;
			*(yuvptr + (cols * 2)) = y1;
			yuvptr++;
		}
		fwrite(yuvbuf, cols*3, 1, stdout);
	}

	free(yuvbuf);
	pm_close(ifp);
	exit(0);
}
