/* 
 *
 * Copyright (C) 2002 George Staikos <staikos@kde.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */


#include <stdlib.h>

#ifdef __STRICT_ANSI__
#define FOO__STRICT_ANSI__
#undef __STRICT_ANSI__
#endif
#include <asm/types.h>
#ifdef FOO__STRICT_ANSI__
#define __STRICT_ANSI__
#undef FOO__STRICT_ANSI__
#endif

#include "v4limage.h"
#include <linux/videodev.h>
#include <limits.h>
#include <string.h>


V4LImage::V4LImage() {
	buffer = 0;
	width = 0;
	height = 0;
	bpp = 0;
	format = 0;
	owner = true;
}


V4LImage::~V4LImage() {
	if (owner)
		delete[] buffer;
}


int V4LImage::toQImage(QImage& img) {
	if (!buffer) {
		return -1;
	}

	switch (format) {
	case VIDEO_PALETTE_RGB32:
		img.create(width,height,32,INT_MAX);
		memcpy(img.bits(),buffer,width*height*bpp);
		break;
	case VIDEO_PALETTE_RGB24:
		{
		printf("V4L(RGB24)->QImage conversion: %dx%d %dBpp\n", width, height, bpp);
		fflush(stdout);
		uchar *bits;
		img.create(width,height,32,0x1000000);
		bits = img.bits();
		for (int i = 0; i < width*height; i++) {
			((long *)bits)[i] = *((long*)&buffer[3*i]) & 0xffffff00;
		}
		}
		break;
	case VIDEO_PALETTE_RGB565:
		printf("V4L(RGB565)->QImage conversion: %dx%d %dBpp\n", width, height, bpp);
		fflush(stdout);
		img.create(width,height,16,0x10000);
		memcpy(img.bits(),buffer,width*height*bpp);
		break;
	case VIDEO_PALETTE_RGB555:
		printf("V4L(RGB555)->QImage conversion: %dx%d %dBpp\n", width, height, bpp);
		fflush(stdout);
		img.create(width,height,16,0x10000);
		memcpy(img.bits(),buffer,width*height*bpp);
		break;
	case VIDEO_PALETTE_GREY:
	case VIDEO_PALETTE_HI240:
	case VIDEO_PALETTE_YUV422:
	case VIDEO_PALETTE_YUYV:
	case VIDEO_PALETTE_UYVY:
	case VIDEO_PALETTE_YUV420:
	case VIDEO_PALETTE_YUV411:
	case VIDEO_PALETTE_RAW:
	case VIDEO_PALETTE_YUV422P:
	case VIDEO_PALETTE_YUV411P:
	case VIDEO_PALETTE_YUV420P:
	case VIDEO_PALETTE_YUV410P:
	default:
		// unknown format
		return -1;
	}

return 0;
}



