/* sane - Scanner Access Now Easy.
   Copyright (C) 2001 Daan Vreeken

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   This program 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
   General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place - Suite 330, Boston,
   MA 02111-1307, USA.

   As a special exception, the authors of SANE give permission for
   additional uses of the libraries contained in this release of SANE.

   The exception is that, if you link a SANE library with other files
   to produce an executable, this does not by itself cause the
   resulting executable to be covered by the GNU General Public
   License.  Your use of that executable is in no way restricted on
   account of linking the SANE library code into it.

   This exception does not, however, invalidate any other reasons why
   the executable file might be covered by the GNU General Public
   License.

   If you submit changes to SANE to the maintainers to be included in
   a subsequent release, you agree by submitting the changes that
   those changes may be distributed with this exception intact.

   If you write modifications of your own for SANE, it is your choice
   whether to permit this exception to apply to your modifications.
   If you do not wish that, delete this exception notice.  */

#include "sane/config.h"

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

#include <stdarg.h>
#include <signal.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <machine/ioctl_bt848.h>
#include <machine/ioctl_meteor.h>

#include "sane/sane.h"
#include "sane/sanei.h"
#include "sane/saneopts.h"

#define BACKEND_NAME	bktr
#include "sane/sanei_backend.h"


#define MAGIC		(void *)0x123



static int		is_open = 0;
static SANE_Fixed	Width = 320;
static SANE_Fixed	Height = 240;
static SANE_Fixed	SelectedSource = 1;

static SANE_Byte	*FrameBuffer = NULL;
static SANE_Byte	*FrameEnd = NULL;
static SANE_Byte	*FramePos = NULL;
int			Device = 0;



static const SANE_Range			OptionRange =
{
	0,255,0
};


static const SANE_String_Const		InputList[] =
{
	"EXT-1",
	"Tuner",
	"SVHS-composite",
	"SVHS",
	"EXT-2",
	0
};


static const SANE_Option_Descriptor	Option[] =
{
	{
		SANE_NAME_NUM_OPTIONS,
		SANE_TITLE_NUM_OPTIONS,
		SANE_DESC_NUM_OPTIONS,
		SANE_TYPE_INT,
		SANE_UNIT_NONE,
		sizeof (SANE_Word),
		SANE_CAP_SOFT_DETECT,
		SANE_CONSTRAINT_NONE,
		{NULL}
	},
	{
		SANE_NAME_BRIGHTNESS,
		SANE_TITLE_BRIGHTNESS,
		SANE_DESC_BRIGHTNESS,
		SANE_TYPE_INT,
		SANE_UNIT_NONE,
		sizeof (SANE_Word),
		SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT,
		SANE_CONSTRAINT_RANGE,
		{(SANE_String_Const *)&OptionRange}	// this is ANSI conformant!
	},
	{
		SANE_NAME_CONTRAST,
		SANE_TITLE_CONTRAST,
		SANE_DESC_CONTRAST,
		SANE_TYPE_INT,
		SANE_UNIT_NONE,
		sizeof (SANE_Word),
		SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT,
		SANE_CONSTRAINT_RANGE,
		{(SANE_String_Const *)&OptionRange}	// this is ANSI conformant!
	},
	{
		SANE_NAME_HUE,
		SANE_TITLE_HUE,
		SANE_DESC_HUE,
		SANE_TYPE_INT,
		SANE_UNIT_NONE,
		sizeof (SANE_Word),
		SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT,
		SANE_CONSTRAINT_RANGE,
		{(SANE_String_Const *)&OptionRange}	// this is ANSI conformant!
	},
	{
		"source",
		"Video source",
		"Selects the video source",
		SANE_TYPE_STRING,
		SANE_UNIT_NONE,
		15,					//sizeof("SVHS-composite")
		SANE_UNIT_NONE,
		SANE_CONSTRAINT_STRING_LIST,
		{InputList},
	},
};



static SANE_Parameters			parms =
{
	SANE_FRAME_RGB,
	0,
	0,			// Number of bytes returned per scan line:
	0,			// Number of pixels per scan line.
	0,			// Number of lines for the current scan.
	8,			// Number of bits per sample.
};


//
///// Daantje's test bktr SANE backend.
//


void DEBUG(int Level, char *Fmt, ...)
{
	va_list		List;
	
	Level=0;
	
	va_start(List,Fmt);
	printf("bktr:");
	vprintf(Fmt,List);
	printf("\n");
	va_end(List);
}




SANE_Status sane_init (SANE_Int *version_code, SANE_Auth_Callback authorize)
{
	DBG_INIT();
	DEBUG(2, "sane_init: version_code %s 0, authorize %s 0",
		version_code == 0 ? "=" : "!=", authorize == 0 ? "=" : "!="); 

	if (version_code)
		*version_code=SANE_VERSION_CODE(V_MAJOR,V_MINOR,0);

	return SANE_STATUS_GOOD;
}



void sane_exit (void)
{
	DEBUG(2, "sane_exit");
}



//=========--
//==============---------- Device select/open/close
//=========--


static const SANE_Device dev[] =
{
	{
		"/dev/bktr0",
		"Brooktree",
		"bt878",
		"video capture card"
	},
};



SANE_Status sane_get_devices(const SANE_Device ***device_list, SANE_Bool local_only)
{
	static const SANE_Device *devlist[] =
	{
		dev,0
	};

	DEBUG(2, "sane_get_devices: local_only = %d", local_only);
	
	*device_list = devlist;
	return SANE_STATUS_GOOD;
}



SANE_Status sane_open(SANE_String_Const devicename, SANE_Handle *handle)
{
	int		i;
	int		Sig = SIGUSR1;
	

	if (!devicename)
		return SANE_STATUS_INVAL;
	
	DEBUG(2, "sane_open: devicename = \"%s\"", devicename);  

	if (!devicename[0])
		i=0;
	else
		for (i=0; i<NELEMS(dev); ++i)
			if (strcmp(devicename,dev[i].name) == 0)
				break;
	if (i>=NELEMS(dev))
		return SANE_STATUS_INVAL;

	if (is_open)
		return SANE_STATUS_DEVICE_BUSY;

	Device=open("/dev/bktr0",O_RDONLY);
	if (Device==-1)
		return SANE_STATUS_ACCESS_DENIED;

	if (ioctl(Device,METEORSSIGNAL,&Sig)==-1)
	{
		DEBUG(1,"Could not do ioctl!");
		return SANE_STATUS_INVAL;
	}

	is_open=1;
	*handle=MAGIC;
	
	return SANE_STATUS_GOOD;
}



void sane_close (SANE_Handle handle)
{
	DEBUG(2,"sane_close");
	
	if (FrameBuffer!=NULL)
	{
		free(FrameBuffer);
	}
	
	if (Device!=0)
	{
		close(Device);
		Device=0;
	}
	
	if (handle==MAGIC)
		is_open=0;
}



const SANE_Option_Descriptor *sane_get_option_descriptor (SANE_Handle handle, SANE_Int option)
{
	DEBUG(2, "sane_get_option_descriptor: option = %d", option);
	
	if (handle!=MAGIC || !is_open)
		return NULL;			// wrong device
	if (option<0 || option>=NELEMS(Option))
		return NULL;
		
	return &Option[option];
}



SANE_Status sane_control_option (
		SANE_Handle handle, SANE_Int option,
		SANE_Action action, void *value,
		SANE_Int *info)
{
	SANE_Int	myinfo = 0;
	SANE_Status	status;
	unsigned char	Temp;
	unsigned long	Input;
	int		Cnt;
	int		Found = 0;


	DEBUG(2,"sane_control_option: handle=%p, opt=%d, act=%d, val=%p, info=%p",
		handle, option, action, value, info);

	if (handle!=MAGIC || !is_open)
		return SANE_STATUS_INVAL;	//Unknown handle...

	if (option<0 || option>=NELEMS(Option))
		return SANE_STATUS_INVAL;	//Unknown option...

	switch (action)
	{
	case SANE_ACTION_SET_VALUE:
	
		status=sanei_constrain_value(Option+option,value,&myinfo);
		if (status!=SANE_STATUS_GOOD)
			return status;

		switch (option)
		{
		case 1:					//Brightness
			Temp=(u_char)*(SANE_Word *)value;
			DEBUG(1,"lala: %d",Temp);
			if (ioctl(Device,METEORSBRIG,&Temp)==-1)
				return SANE_STATUS_INVAL;
			break;
			
		case 2:					//Contrast
			Temp=(u_char)*(SANE_Word *)value;
			if (ioctl(Device,METEORSCONT,&Temp)==-1)
				return SANE_STATUS_INVAL;
			break;
			
		case 3:					//Hue
			Temp=(u_char)*(SANE_Word *)value;
			Temp-=128;
			if (ioctl(Device,METEORSHUE,&Temp)==-1)
				return SANE_STATUS_INVAL;
			break;
			
		case 4:					//Source
			for (Cnt=0; Cnt<=4; Cnt++)
				if (!strcmp(value,InputList[Cnt]))
				{
					Found=1;
					SelectedSource=Cnt;
					
					switch (SelectedSource)
					{
					case 0:
						Input=METEOR_INPUT_DEV0;
						break;
					case 1:
						Input=METEOR_INPUT_DEV1;
						break;
					case 2:
						Input=METEOR_INPUT_DEV2;
						break;
					case 3:
						Input=METEOR_INPUT_DEV_SVIDEO;
						break;
					case 4:
						Input=METEOR_INPUT_DEV3;
						break;
					}
					if (ioctl(Device,METEORSINPUT,&Input)==-1)
						return SANE_STATUS_INVAL;
				}
			
			if (!Found)
				return SANE_STATUS_INVAL;
			break;

		default:
			return SANE_STATUS_INVAL;
		}
		break;

	case SANE_ACTION_GET_VALUE:
	
		switch (option)
		{
		case 0:					//NUMOPTS
			*(SANE_Word *)value=NELEMS(Option);
			break;
			
		case 1:					//Brightness
			if (ioctl(Device,METEORGBRIG,&Temp)==-1)
				return SANE_STATUS_INVAL;
				
			//BUG in bktr_core.c :
			//128 is substracted from our value when setting
			//brightness, but when reading it, it isn't added
			//up again... So we'll have to do that ourselfs.
			Temp+=128;
			
			*(SANE_Word *)value=(SANE_Word)Temp;
			break;
			
		case 2:					//Contrast
			if (ioctl(Device,METEORGCONT,&Temp)==-1)
				return SANE_STATUS_INVAL;
			*(SANE_Word *)value=Temp;
			break;

		case 3:					//Hue
			if (ioctl(Device,METEORGHUE,&Temp)==-1)
				return SANE_STATUS_INVAL;
			Temp+=128;
			*(SANE_Word *)value=Temp;
			break;
			
		case 4:					//Source
			strcpy (value,InputList[SelectedSource]);
			break;

		default:
			return SANE_STATUS_INVAL;
		}
		break;

	case SANE_ACTION_SET_AUTO:
		return SANE_STATUS_UNSUPPORTED;	// We are DUMB
	}
	
 	if (info)
		*info=myinfo;
		
	return SANE_STATUS_GOOD;
}



SANE_Status sane_get_parameters(SANE_Handle handle,
		SANE_Parameters *params)
{
	int	rc = SANE_STATUS_GOOD;

	DEBUG(2,"sane_get_parameters");

	if (handle!=MAGIC || !is_open)
		rc=SANE_STATUS_INVAL;		//Unknown handle...

	parms.format=SANE_FRAME_RGB;
	parms.bytes_per_line=3*Width;
	parms.pixels_per_line=Width;
	parms.lines=Height;
	parms.depth=8;
	parms.last_frame=1;

	*params=parms;
	return rc;
}



void Capture_SetFormat(void)
{
	unsigned long		Format;
	struct meteor_geomet	Geo;
	

	//PAL
	Format=BT848_IFORM_F_PALBDGHI;
	
	if (ioctl(Device,BT848SFMT,&Format)==-1)
		DEBUG(1,"ioctl failed!");
	
	//Geometry
	Geo.columns=Width;
	Geo.rows=Height;
	Geo.frames=1;
	Geo.oformat=METEOR_GEO_RGB24 | METEOR_GEO_ODD_ONLY;
	
	if (ioctl(Device,METEORSETGEO,&Geo)==-1)
		DEBUG(1,"ioctl failed!");
}



void Capture_SetSource(void)
{
	int		Source;

	
	//external video input
	Source=METEOR_INPUT_DEV0;
	
	if (ioctl(Device,METEORSINPUT,&Source)==-1)
		DEBUG(1,"ioctl failed!");
}



void		Ident;



sig_t Capture_SignalHandler(void)
{
	//Don't do anything here...
	return 0;
}




SANE_Status sane_start(SANE_Handle handle)
{
	unsigned long	Capture = METEOR_CAP_SINGLE;
	int		Signal = SIGUSR1;
	
	
	DEBUG(2,"sane_start");
	if (handle!=MAGIC || !is_open)
		return SANE_STATUS_INVAL;	//Unknown handle...

	//Allocate framebuffer for mmap
	if (FrameBuffer==NULL)
	{
		FrameBuffer=(unsigned char *)mmap((caddr_t)0,4*Width*Height,PROT_READ,MAP_SHARED,Device,(off_t)0);
		if (FrameBuffer==NULL)
			return SANE_STATUS_NO_MEM;
			
		FrameEnd=FrameBuffer+4*Width*Height;
	}
	
	//Set capture format...
	Capture_SetFormat();
	//Set source
	Capture_SetSource();
	
	//Set read position to beginning of buffer
	FramePos=FrameBuffer;

	//Ask bktr device to give us a signal when frame is completed...
	if (ioctl(Device,METEORSSIGNAL,&Signal)==-1)
	{
		DEBUG(1,"bktr does not want to send us a signal!??");
		return SANE_STATUS_INVAL;
	}
	
	//Install a signal handler
	signal(SIGUSR1,(sig_t)&Capture_SignalHandler);
	
	//Start capture
	if (ioctl(Device,METEORCAPTUR,&Capture)==-1)
	{
		DEBUG(1,"coult not start capture!");
		return SANE_STATUS_INVAL;
	}
	
	wait(NULL);

	return SANE_STATUS_GOOD;
}



static SANE_Byte	*Src;
static SANE_Byte	*Dst;



SANE_Status sane_read(SANE_Handle handle, SANE_Byte *data,
	   SANE_Int max_length, SANE_Int *length)
{
	int		Cnt;
	long		PixelsLeft = (FrameEnd-FramePos)/4;
	
	DEBUG(2,"sane_read: max_length = %d",
		max_length);

	if (handle!=MAGIC || !is_open || !data || !length)
		return SANE_STATUS_INVAL;	//Unknown handle or no file to read...
    

	if (PixelsLeft<=0)
	{
		*length=0;
		return SANE_STATUS_EOF;
	}
	
	if (max_length>3)
	{
		if (PixelsLeft>max_length/3)
			PixelsLeft=max_length/3;
			
		Src=FramePos;
		Dst=data;
		
		for (Cnt=0; Cnt<PixelsLeft; Cnt++)
		{
			//Reverse BGR to RGB byte order
			*Dst++=*(Src+2);
			*Dst++=*(Src+1);
			*Dst++=*(Src+0);
			Src+=4;
		}
		FramePos+=PixelsLeft*4;
		*length=PixelsLeft*3;
		
		if (FramePos==FrameEnd)
			return SANE_STATUS_EOF;
	}
	else
	{
		DEBUG(1,"Not enough data space to store 1 pixel!");
		return SANE_STATUS_INVAL;
	}
		
	
	return SANE_STATUS_GOOD;
}



void sane_cancel(SANE_Handle handle)
{
	DEBUG(2, "sane_cancel: handle = %p", handle);
	
	/*
	pass = 0;
	if (infile!=NULL)
	{
		fclose (infile);
		infile = NULL;
	}
	*/
}



SANE_Status sane_set_io_mode(SANE_Handle handle, SANE_Bool non_blocking)
{
	DEBUG(2,"sane_set_io_mode: handle = %p, non_blocking = %d",handle,
		non_blocking);

	return SANE_STATUS_UNSUPPORTED;
}


SANE_Status sane_get_select_fd(SANE_Handle handle, SANE_Int *fd)
{
	DEBUG(2,"sane_get_select_fd: handle = %p, fd %s 0",handle,
		fd ? "!=" : "=");

	return SANE_STATUS_UNSUPPORTED;
}








