/*
 * PWCBSD - Philips USB webcam driver for FreeBSD 5.4 and higher
 *
 *  Copyright (C) 2006 Raaf 
 *
 * Based on the Linux pwc driver.
 *  
 *  Copyright (C) 1999-2003 Nemosoft Unv.
 *  Copyright (C) 2004-2006 Luc Saillard
 *  
 * 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., 51 Franklin Street, Fifth Floor, Boston,
 * MA  02110-1301  USA
 */

#ifndef PWC_H
#define PWC_H
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/module.h>
#include <sys/bus.h>
#include <sys/conf.h>
#include <sys/fcntl.h>
#include <sys/tty.h>
#include <sys/selinfo.h>
#include <sys/poll.h>
#include <sys/uio.h>
#include <sys/sysctl.h>
#include <sys/malloc.h>
#include <sys/mman.h>
#include <vm/vm.h>
#include <vm/pmap.h>

#include <dev/usb/usb.h>
#include <dev/usb/usbdi.h>
#include <dev/usb/usbdi_util.h>
#include "pwc-uncompress.h"
#include "pwc-ioctl.h"
#include "videodev.h"

#define PWC_ASLEEP	1
#define PWC_INIT	2
#define PWC_POLL	4

/* Trace certain actions in the driver */
#define TRACE_MODULE	0x0001
#define TRACE_PROBE	0x0002
#define TRACE_OPEN	0x0004
#define TRACE_READ	0x0008
#define TRACE_MEMORY	0x0010
#define TRACE_FLOW	0x0020
#define TRACE_SIZE	0x0040
#define TRACE_PWCX	0x0080
#define TRACE_IOCTL	0x0100
#define TRACE_ISOC	0x0200
#define TRACE_ISOC_VERBOSE 0x0400
#define TRACE_READ_VERBOSE 0x0800
#define TRACE_SEQUENCE	0x1000

#ifdef USB_DEBUG
#define Trace(R, A...) if (pwcdebug & R) printf(PWC_NAME " " A)
#define Debug(A...) if(pwcdebug) printf(PWC_NAME " " A)
extern int  pwcdebug;
#else
#define Trace(R, A...)
#define Debug(A...)
#endif
#define Info(A...)  printf(PWC_NAME " " A)
#define Err(A...)   printf(PWC_NAME " " A)


/* Defines for ToUCam cameras */
#define TOUCAM_HEADER_SIZE		8
#define TOUCAM_TRAILER_SIZE		4

#define FEATURE_MOTOR_PANTILT		0x0001

#define PWC_NAME 	"pwc"

/* Ignore errors in the first N frames, to allow for startup delays */
#define FRAME_LOWMARK 5

/* Size and number of buffers for the ISO pipe. */
#define MAX_ISO_BUFS		3

/* !!!!!!!!!! IMPORTANT DO NOT SET THIS HIGHER THAN 8 !!!!!!!!!!!!!!! 
 * !!!!!!!!!! OHCI IS BUGGY IF YOU DO SO              !!!!!!!!!!!!!!!*/
#define ISO_FRAMES_PER_DESC	8

#define ISO_MAX_FRAME_SIZE	960
#define ISO_BUFFER_SIZE 	(ISO_FRAMES_PER_DESC * ISO_MAX_FRAME_SIZE)

/* Frame buffers: contains compressed or uncompressed video data. */
#define MAX_FRAMES		5
/* Maximum size after decompression is 640x480 YUV data, 1.5 * 640 * 480 */
#define PWC_FRAME_SIZE 		(460800 + TOUCAM_HEADER_SIZE + TOUCAM_TRAILER_SIZE)

/* Absolute maximum number of buffers available for mmap() */
#define MAX_IMAGES 		10

#ifndef V4L2_PIX_FMT_PWC1
#define V4L2_PIX_FMT_PWC1	v4l2_fourcc('P','W','C','1')
#define V4L2_PIX_FMT_PWC2	v4l2_fourcc('P','W','C','2')
#endif

/* intermediate buffers with raw data from the USB cam */
struct pwc_frame_buf
{
   char *data;
   volatile int filled;		/* number of bytes filled */
   struct pwc_frame_buf *next;	/* list */
};

/* additionnal informations used when dealing image between kernel and userland */
struct pwc_imgbuf
{
	char  *bufmem;		/* addr of this buffer in kernel space */
	int   vma_use_count;	/* count the number of time this memory is mapped */
};

struct pwc_softc
{
   device_t sc_dev;
   usbd_device_handle udev;
   usbd_interface_handle sc_iface;
   usbd_pipe_handle sc_videopipe;
   struct cdev *sc_dev_t;
   
   struct selinfo rsel;
   char *name;
   int type;                    /* type of cam (645, 646, 675, 680, 690, 720, 730, 740, 750) */
   int release;			/* release number */
   int features;		/* feature bits */
   char serial[USB_MAX_STRING_LEN]; /* serial number (string) */
   int error_status;		/* set when something goes wrong with the cam (unplugged, USB errors) */
   int usb_init;		/* set when the cam has been initialized over USB */

   int power_save;
   int led_on;
   int led_off;
   int stats;
   int pwc_mbufs;
   int pwc_fbufs;
   int pwc_pad;

   /*** Video data ***/
   int vopen;			/* flag */
   int vendpoint;		/* video isoc endpoint */
   int vcinterface;		/* video control interface */
   int valternate;		/* alternate interface needed */
   int vframes, vsize;		/* frames-per-second & size (see PSZ_*) */
   int vpalette;		/* palette: 420P, RAW or RGBBAYER */
   int vframe_count;		/* received frames */
   int vframes_dumped; 		/* counter for dumped frames */
   int vframes_error;		/* frames received in error */
   int vmax_packet_size;	/* USB maxpacket size */
   u_int16_t vlast_packet_size;	/* for frame synchronisation */
   int visoc_errors;		/* number of contiguous ISOC errors */
   int vcompression;		/* desired compression factor */
   int vbandlength;		/* compressed band length; 0 is uncompressed */
   char vsnapshot;		/* snapshot mode */
   char vsync;			/* used by isoc handler */
   char vmirror;		/* for ToUCaM series */
   
   int cmd_len;
   unsigned char cmd_buf[13];

   /* The image acquisition requires 3 to 4 steps:
      1. data is gathered in short packets from the USB controller
      2. data is synchronized and packed into a frame buffer
      3a. in case data is compressed, decompress it directly into image buffer
      3b. in case data is uncompressed, copy into image buffer with viewport
      4. data is transferred to the user process

      Note that MAX_ISO_BUFS != MAX_FRAMES != MAX_IMAGES....
      We have in effect a back-to-back-double-buffer system.
    */
   /* 1: isoc */
   struct pwc_iso_buf
   {
	unsigned char *data;
	usbd_xfer_handle xfer;
 	u_int16_t sizes[ISO_FRAMES_PER_DESC];
	struct pwc_softc *sc;
   } sbuf[MAX_ISO_BUFS];
 
   char iso_init;

   /* 2: frame */
   struct pwc_frame_buf *fbuf;	/* all frames */
   struct pwc_frame_buf *empty_frames, *empty_frames_tail;	/* all empty frames */
   struct pwc_frame_buf *full_frames, *full_frames_tail;	/* all filled frames */
   struct pwc_frame_buf *fill_frame;	/* frame currently being filled */
   struct pwc_frame_buf *read_frame;	/* frame currently read by user process */
   int frame_header_size, frame_trailer_size;
   int frame_size;
   int frame_total_size; /* including header & trailer */
   int drop_frames;

   /* 3: decompression */
   void *decompress_data;		/* private data for decompression engine */

   /* 4: image */
   /* We have an 'image' and a 'view', where 'image' is the fixed-size image
      as delivered by the camera, and 'view' is the size requested by the
      program. The camera image is centered in this viewport, laced with
      a gray or black border. view_min <= image <= view <= view_max;
    */
   int image_mask;			/* bitmask of supported sizes */
   struct pwc_coord view_min, view_max;	/* minimum and maximum viewable sizes */
   struct pwc_coord abs_max;            /* maximum supported size with compression */
   struct pwc_coord image, view;	/* image and viewport size */
   struct pwc_coord offset;		/* offset within the viewport */

   void *image_data;			/* total buffer, which is subdivided into ... */
   struct pwc_imgbuf images[MAX_IMAGES];/* ...several images... */
   int fill_image;			/* ...which are rotated. */
   int len_per_image;			/* length per image */
   int image_read_pos;			/* In case we read data in pieces, keep track of were we are in the imagebuffer */
   int image_used[MAX_IMAGES];		/* For MCAPTURE and SYNC */

   struct mtx ptrlock;			/* for manipulating the buffer pointers */
   
   /*** motorized pan/tilt feature */
   struct pwc_mpt_range angle_range;
   int pan_angle;			/* in degrees * 100 */
   int tilt_angle;			/* absolute angle; 0,0 is home position */
   int snapshot_button_status;		/* set to 1 when the user push the button, reset to 0 when this value is read */

   /*** Misc. data ***/
   int state;				/* When waiting for a frame to finish... */
};


#ifdef __cplusplus
extern "C" {
#endif


/** functions in pwc-if.c */
int pwc_try_video_mode(struct pwc_softc *pdev, int width, int height, int new_fps, int new_compression, int new_snapshot);
int pwc_handle_frame(struct pwc_softc *pdev);
void pwc_next_image(struct pwc_softc *pdev);

/** Functions in pwc-misc.c */
/* sizes in pixels */
extern struct pwc_coord pwc_image_sizes[PSZ_MAX];

int pwc_decode_size(struct pwc_softc *pdev, int width, int height);
void pwc_construct(struct pwc_softc *pdev);

/** Functions in pwc-ctrl.c */
/* Request a certain video mode. Returns < 0 if not possible */
extern int pwc_set_video_mode(struct pwc_softc *pdev, int width, int height, int frames, int compression, int snapshot);
/* Calculate the number of bytes per image (not frame) */
extern int pwc_mpt_reset(struct pwc_softc *pdev, int flags);
extern int pwc_mpt_set_angle(struct pwc_softc *pdev, int pan, int tilt);

/* Various controls; should be obvious. Value 0..65535, or < 0 on error */
extern int pwc_get_brightness(struct pwc_softc *pdev);
extern int pwc_set_brightness(struct pwc_softc *pdev, int value);
extern int pwc_get_contrast(struct pwc_softc *pdev);
extern int pwc_set_contrast(struct pwc_softc *pdev, int value);
extern int pwc_get_gamma(struct pwc_softc *pdev);
extern int pwc_set_gamma(struct pwc_softc *pdev, int value);
extern int pwc_get_saturation(struct pwc_softc *pdev);
extern int pwc_set_saturation(struct pwc_softc *pdev, int value);
extern int pwc_set_leds(struct pwc_softc *pdev, int on_value, int off_value);
extern int pwc_get_leds(struct pwc_softc *pdev, int *on_value, int *off_value);
extern int pwc_get_cmos_sensor(struct pwc_softc *pdev, int *sensor);
extern int pwc_restore_user(struct pwc_softc *pdev);
extern int pwc_save_user(struct pwc_softc *pdev);
extern int pwc_restore_factory(struct pwc_softc *pdev);

/* exported for use by v4l2 controls */
extern int pwc_get_red_gain(struct pwc_softc *pdev, int *value);
extern int pwc_set_red_gain(struct pwc_softc *pdev, int value);
extern int pwc_get_blue_gain(struct pwc_softc *pdev, int *value);
extern int pwc_set_blue_gain(struct pwc_softc *pdev, int value);
extern int pwc_get_awb(struct pwc_softc *pdev);
extern int pwc_set_awb(struct pwc_softc *pdev, int mode);
extern int pwc_set_agc(struct pwc_softc *pdev, int mode, int value);
extern int pwc_get_agc(struct pwc_softc *pdev, int *value);
extern int pwc_set_shutter_speed(struct pwc_softc *pdev, int mode, int value);
extern int pwc_get_shutter_speed(struct pwc_softc *pdev,int *value);
extern int pwc_set_colour_mode(struct pwc_softc *pdev, int colour);
extern int pwc_get_colour_mode(struct pwc_softc *pdev, int *colour);

/* Power down or up the camera; not supported by all models */
extern int pwc_camera_power(struct pwc_softc *pdev, int power);

/* Private ioctl()s; see pwc-ioctl.h */
extern int pwc_do_ioctl(struct pwc_softc *pdev, unsigned int cmd, void *arg);

/** Functions in pwc-v4l.c */
extern int pwc_video_do_ioctl(struct pwc_softc *pdev, unsigned int cmd, void *arg, int unit);
/** pwc-uncompress.c */
/* Expand frame to image, possibly including decompression. Uses read_frame and fill_image */
extern int pwc_decompress(struct pwc_softc *pdev);

#ifdef __cplusplus
}
#endif


#endif
