ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / usb / media / stv680.c
1 /*
2  *  STV0680 USB Camera Driver, by Kevin Sisson (kjsisson@bellsouth.net)
3  *  
4  * Thanks to STMicroelectronics for information on the usb commands, and 
5  * to Steve Miller at STM for his help and encouragement while I was 
6  * writing this driver.
7  *
8  * This driver is based heavily on the 
9  * Endpoints (formerly known as AOX) se401 USB Camera Driver
10  * Copyright (c) 2000 Jeroen B. Vreeken (pe1rxq@amsat.org)
11  *
12  * Still somewhat based on the Linux ov511 driver.
13  * 
14  * This program is free software; you can redistribute it and/or modify it
15  * under the terms of the GNU General Public License as published by the
16  * Free Software Foundation; either version 2 of the License, or (at your
17  * option) any later version.
18  *
19  * This program is distributed in the hope that it will be useful, but
20  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
21  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
22  * for more details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program; if not, write to the Free Software Foundation,
26  * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27  *
28  * History: 
29  * ver 0.1 October, 2001. Initial attempt. 
30  *
31  * ver 0.2 November, 2001. Fixed asbility to resize, added brightness
32  *                         function, made more stable (?)
33  *
34  * ver 0.21 Nov, 2001.     Added gamma correction and white balance, 
35  *                         due to Alexander Schwartz. Still trying to 
36  *                         improve stablility. Moved stuff into stv680.h
37  *
38  * ver 0.22 Nov, 2001.     Added sharpen function (by Michael Sweet, 
39  *                         mike@easysw.com) from GIMP, also used in pencam. 
40  *                         Simple, fast, good integer math routine.
41  *
42  * ver 0.23 Dec, 2001 (gkh)
43  *                         Took out sharpen function, ran code through
44  *                         Lindent, and did other minor tweaks to get
45  *                         things to work properly with 2.5.1
46  *
47  * ver 0.24 Jan, 2002 (kjs) 
48  *                         Fixed the problem with webcam crashing after
49  *                         two pictures. Changed the way pic is halved to 
50  *                         improve quality. Got rid of green line around 
51  *                         frame. Fix brightness reset when changing size 
52  *                         bug. Adjusted gamma filters slightly.
53  *
54  * ver 0.25 Jan, 2002 (kjs)
55  *                         Fixed a bug in which the driver sometimes attempted
56  *                         to set to a non-supported size. This allowed
57  *                         gnomemeeting to work.
58  *                         Fixed proc entry removal bug.
59  */
60
61 #include <linux/config.h>
62 #include <linux/module.h>
63 #include <linux/init.h>
64 #include <linux/vmalloc.h>
65 #include <linux/slab.h>
66 #include <linux/pagemap.h>
67 #include <linux/errno.h>
68 #include <linux/videodev.h>
69 #include <linux/usb.h>
70
71 #include "stv680.h"
72
73 static int video_nr = -1;
74 static int swapRGB = 0;   /* default for auto sleect */
75 static int swapRGB_on = 0; /* default to allow auto select; -1=swap never, +1= swap always */
76
77 static unsigned int debug = 0;
78
79 #define PDEBUG(level, fmt, args...) \
80         do { \
81         if (debug >= level)     \
82                 info("[%s:%d] " fmt, __FUNCTION__, __LINE__ , ## args); \
83         } while (0)
84
85
86 /*
87  * Version Information
88  */
89 #define DRIVER_VERSION "v0.25"
90 #define DRIVER_AUTHOR "Kevin Sisson <kjsisson@bellsouth.net>"
91 #define DRIVER_DESC "STV0680 USB Camera Driver"
92
93 MODULE_AUTHOR (DRIVER_AUTHOR);
94 MODULE_DESCRIPTION (DRIVER_DESC);
95 MODULE_LICENSE ("GPL");
96 MODULE_PARM (debug, "i");
97 MODULE_PARM_DESC (debug, "Debug enabled or not");
98 MODULE_PARM (swapRGB_on, "i");
99 MODULE_PARM_DESC (swapRGB_on, "Red/blue swap: 1=always, 0=auto, -1=never");
100 MODULE_PARM (video_nr, "i");
101
102 /********************************************************************
103  *
104  * Memory management
105  *
106  * This is a shameless copy from the USB-cpia driver (linux kernel
107  * version 2.3.29 or so, I have no idea what this code actually does ;).
108  * Actually it seems to be a copy of a shameless copy of the bttv-driver.
109  * Or that is a copy of a shameless copy of ... (To the powers: is there
110  * no generic kernel-function to do this sort of stuff?)
111  *
112  * Yes, it was a shameless copy from the bttv-driver. IIRC, Alan says
113  * there will be one, but apparentely not yet -jerdfelt
114  *
115  * So I copied it again for the ov511 driver -claudio
116  *
117  * Same for the se401 driver -Jeroen
118  *
119  * And the STV0680 driver - Kevin
120  ********************************************************************/
121
122 /* Here we want the physical address of the memory.
123  * This is used when initializing the contents of the area.
124  */
125 static inline unsigned long kvirt_to_pa (unsigned long adr)
126 {
127         unsigned long kva, ret;
128
129         kva = (unsigned long) page_address(vmalloc_to_page((void *)adr));
130         kva |= adr & (PAGE_SIZE-1); /* restore the offset */
131         ret = __pa(kva);
132         return ret;
133 }
134
135 static void *rvmalloc (unsigned long size)
136 {
137         void *mem;
138         unsigned long adr;
139
140         size = PAGE_ALIGN(size);
141         mem = vmalloc_32 (size);
142         if (!mem)
143                 return NULL;
144
145         memset (mem, 0, size);  /* Clear the ram out, no junk to the user */
146         adr = (unsigned long) mem;
147         while (size > 0) {
148                 SetPageReserved(vmalloc_to_page((void *)adr));
149                 adr += PAGE_SIZE;
150                 size -= PAGE_SIZE;
151         }
152         return mem;
153 }
154
155 static void rvfree (void *mem, unsigned long size)
156 {
157         unsigned long adr;
158
159         if (!mem)
160                 return;
161
162         adr = (unsigned long) mem;
163         while ((long) size > 0) {
164                 ClearPageReserved(vmalloc_to_page((void *)adr));
165                 adr += PAGE_SIZE;
166                 size -= PAGE_SIZE;
167         }
168         vfree (mem);
169 }
170
171
172 /*********************************************************************
173  * pencam read/write functions
174  ********************************************************************/
175
176 static int stv_sndctrl (int set, struct usb_stv *stv680, unsigned short req, unsigned short value, unsigned char *buffer, int size)
177 {
178         int ret = -1;
179
180         switch (set) {
181         case 0:         /*  0xc1  */
182                 ret = usb_control_msg (stv680->udev,
183                                        usb_rcvctrlpipe (stv680->udev, 0),
184                                        req,
185                                        (USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_ENDPOINT),
186                                        value, 0, buffer, size, PENCAM_TIMEOUT);
187                 break;
188
189         case 1:         /*  0x41  */
190                 ret = usb_control_msg (stv680->udev,
191                                        usb_sndctrlpipe (stv680->udev, 0),
192                                        req,
193                                        (USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_ENDPOINT),
194                                        value, 0, buffer, size, PENCAM_TIMEOUT);
195                 break;
196
197         case 2:         /*  0x80  */
198                 ret = usb_control_msg (stv680->udev,
199                                        usb_rcvctrlpipe (stv680->udev, 0),
200                                        req,
201                                        (USB_DIR_IN | USB_RECIP_DEVICE),
202                                        value, 0, buffer, size, PENCAM_TIMEOUT);
203                 break;
204
205         case 3:         /*  0x40  */
206                 ret = usb_control_msg (stv680->udev,
207                                        usb_sndctrlpipe (stv680->udev, 0),
208                                        req,
209                                        (USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE),
210                                        value, 0, buffer, size, PENCAM_TIMEOUT);
211                 break;
212
213         }
214         if ((ret < 0) && (req != 0x0a)) {
215                 PDEBUG (1, "STV(e): usb_control_msg error %i, request = 0x%x, error = %i", set, req, ret);
216         }
217         return ret;
218 }
219
220 static int stv_set_config (struct usb_stv *dev, int configuration, int interface, int alternate)
221 {
222
223         if (configuration != dev->udev->actconfig->desc.bConfigurationValue
224                         || usb_reset_configuration (dev->udev) < 0) {
225                 PDEBUG (1, "STV(e): FAILED to reset configuration %i", configuration);
226                 return -1;
227         }
228         if (usb_set_interface (dev->udev, interface, alternate) < 0) {
229                 PDEBUG (1, "STV(e): FAILED to set alternate interface %i", alternate);
230                 return -1;
231         }
232         return 0;
233 }
234
235 static int stv_stop_video (struct usb_stv *dev)
236 {
237         int i;
238         unsigned char *buf;
239
240         buf = kmalloc (40, GFP_KERNEL);
241         if (buf == NULL) {
242                 PDEBUG (0, "STV(e): Out of (small buf) memory");
243                 return -1;
244         }
245
246         /* this is a high priority command; it stops all lower order commands */
247         if ((i = stv_sndctrl (1, dev, 0x04, 0x0000, buf, 0x0)) < 0) {
248                 i = stv_sndctrl (0, dev, 0x80, 0, buf, 0x02);   /* Get Last Error; 2 = busy */
249                 PDEBUG (1, "STV(i): last error: %i,  command = 0x%x", buf[0], buf[1]);
250         } else {
251                 PDEBUG (1, "STV(i): Camera reset to idle mode.");
252         }
253
254         if ((i = stv_set_config (dev, 1, 0, 0)) < 0)
255                 PDEBUG (1, "STV(e): Reset config during exit failed");
256
257         /*  get current mode  */
258         buf[0] = 0xf0;
259         if ((i = stv_sndctrl (0, dev, 0x87, 0, buf, 0x08)) != 0x08)     /* get mode */
260                 PDEBUG (0, "STV(e): Stop_video: problem setting original mode");
261         if (dev->origMode != buf[0]) {
262                 memset (buf, 0, 8);
263                 buf[0] = (unsigned char) dev->origMode;
264                 if ((i = stv_sndctrl (3, dev, 0x07, 0x0100, buf, 0x08)) != 0x08) {
265                         PDEBUG (0, "STV(e): Stop_video: Set_Camera_Mode failed");
266                         i = -1;
267                 }
268                 buf[0] = 0xf0;
269                 i = stv_sndctrl (0, dev, 0x87, 0, buf, 0x08);
270                 if ((i != 0x08) || (buf[0] != dev->origMode)) {
271                         PDEBUG (0, "STV(e): camera NOT set to original resolution.");
272                         i = -1;
273                 } else
274                         PDEBUG (0, "STV(i): Camera set to original resolution");
275         }
276         /* origMode */
277         kfree (buf);
278         return i;
279 }
280
281 static int stv_set_video_mode (struct usb_stv *dev)
282 {
283         int i, stop_video = 1;
284         unsigned char *buf;
285
286         buf = kmalloc (40, GFP_KERNEL);
287         if (buf == NULL) {
288                 PDEBUG (0, "STV(e): Out of (small buf) memory");
289                 return -1;
290         }
291
292         if ((i = stv_set_config (dev, 1, 0, 0)) < 0) {
293                 kfree (buf);
294                 return i;
295         }
296
297         i = stv_sndctrl (2, dev, 0x06, 0x0100, buf, 0x12);
298         if (!(i > 0) && (buf[8] == 0x53) && (buf[9] == 0x05)) {
299                 PDEBUG (1, "STV(e): Could not get descriptor 0100.");
300                 goto error;
301         }
302
303         /*  set alternate interface 1 */
304         if ((i = stv_set_config (dev, 1, 0, 1)) < 0)
305                 goto error;
306
307         if ((i = stv_sndctrl (0, dev, 0x85, 0, buf, 0x10)) != 0x10)
308                 goto error;
309         PDEBUG (1, "STV(i): Setting video mode.");
310         /*  Switch to Video mode: 0x0100 = VGA (640x480), 0x0000 = CIF (352x288) 0x0300 = QVGA (320x240)  */
311         if ((i = stv_sndctrl (1, dev, 0x09, dev->VideoMode, buf, 0x0)) < 0) {
312                 stop_video = 0;
313                 goto error;
314         }
315         goto exit;
316
317 error:
318         kfree (buf);
319         if (stop_video == 1)
320                 stv_stop_video (dev);
321         return -1;
322
323 exit:
324         kfree (buf);
325         return 0;
326 }
327
328 static int stv_init (struct usb_stv *stv680)
329 {
330         int i = 0;
331         unsigned char *buffer;
332         unsigned long int bufsize;
333
334         buffer = kmalloc (40, GFP_KERNEL);
335         if (buffer == NULL) {
336                 PDEBUG (0, "STV(e): Out of (small buf) memory");
337                 return -1;
338         }
339         memset (buffer, 0, 40);
340         udelay (100);
341
342         /* set config 1, interface 0, alternate 0 */
343         if ((i = stv_set_config (stv680, 1, 0, 0)) < 0) {
344                 kfree (buffer);
345                 PDEBUG (0, "STV(e): set config 1,0,0 failed");
346                 return -1;
347         }
348         /* ping camera to be sure STV0680 is present */
349         if ((i = stv_sndctrl (0, stv680, 0x88, 0x5678, buffer, 0x02)) != 0x02)
350                 goto error;
351         if ((buffer[0] != 0x56) || (buffer[1] != 0x78)) {
352                 PDEBUG (1, "STV(e): camera ping failed!!");
353                 goto error;
354         }
355
356         /* get camera descriptor */
357         if ((i = stv_sndctrl (2, stv680, 0x06, 0x0200, buffer, 0x09)) != 0x09)
358                 goto error;
359         i = stv_sndctrl (2, stv680, 0x06, 0x0200, buffer, 0x22);
360         if (!(i >= 0) && (buffer[7] == 0xa0) && (buffer[8] == 0x23)) {
361                 PDEBUG (1, "STV(e): Could not get descriptor 0200.");
362                 goto error;
363         }
364         if ((i = stv_sndctrl (0, stv680, 0x8a, 0, buffer, 0x02)) != 0x02)
365                 goto error;
366         if ((i = stv_sndctrl (0, stv680, 0x8b, 0, buffer, 0x24)) != 0x24)
367                 goto error;
368         if ((i = stv_sndctrl (0, stv680, 0x85, 0, buffer, 0x10)) != 0x10)
369                 goto error;
370
371         stv680->SupportedModes = buffer[7];
372         i = stv680->SupportedModes;
373         stv680->CIF = 0;
374         stv680->VGA = 0;
375         stv680->QVGA = 0;
376         if (i & 1)
377                 stv680->CIF = 1;
378         if (i & 2)
379                 stv680->VGA = 1;
380         if (i & 8)
381                 stv680->QVGA = 1;
382         if (stv680->SupportedModes == 0) {
383                 PDEBUG (0, "STV(e): There are NO supported STV680 modes!!");
384                 i = -1;
385                 goto error;
386         } else {
387                 if (stv680->CIF)
388                         PDEBUG (0, "STV(i): CIF is supported");
389                 if (stv680->QVGA)
390                         PDEBUG (0, "STV(i): QVGA is supported");
391         }
392         /* FW rev, ASIC rev, sensor ID  */
393         PDEBUG (1, "STV(i): Firmware rev is %i.%i", buffer[0], buffer[1]);
394         PDEBUG (1, "STV(i): ASIC rev is %i.%i", buffer[2], buffer[3]);
395         PDEBUG (1, "STV(i): Sensor ID is %i", (buffer[4]*16) + (buffer[5]>>4));
396
397         /*  set alternate interface 1 */
398         if ((i = stv_set_config (stv680, 1, 0, 1)) < 0)
399                 goto error;
400
401         if ((i = stv_sndctrl (0, stv680, 0x85, 0, buffer, 0x10)) != 0x10)
402                 goto error;
403         if ((i = stv_sndctrl (0, stv680, 0x8d, 0, buffer, 0x08)) != 0x08)
404                 goto error;
405         i = buffer[3];
406         PDEBUG (0, "STV(i): Camera has %i pictures.", i);
407
408         /*  get current mode */
409         if ((i = stv_sndctrl (0, stv680, 0x87, 0, buffer, 0x08)) != 0x08)
410                 goto error;
411         stv680->origMode = buffer[0];   /* 01 = VGA, 03 = QVGA, 00 = CIF */
412
413         /* This will attemp CIF mode, if supported. If not, set to QVGA  */
414         memset (buffer, 0, 8);
415         if (stv680->CIF)
416                 buffer[0] = 0x00;
417         else if (stv680->QVGA)
418                 buffer[0] = 0x03;
419         if ((i = stv_sndctrl (3, stv680, 0x07, 0x0100, buffer, 0x08)) != 0x08) {
420                 PDEBUG (0, "STV(i): Set_Camera_Mode failed");
421                 i = -1;
422                 goto error;
423         }
424         buffer[0] = 0xf0;
425         stv_sndctrl (0, stv680, 0x87, 0, buffer, 0x08);
426         if (((stv680->CIF == 1) && (buffer[0] != 0x00)) || ((stv680->QVGA == 1) && (buffer[0] != 0x03))) {
427                 PDEBUG (0, "STV(e): Error setting camera video mode!");
428                 i = -1;
429                 goto error;
430         } else {
431                 if (buffer[0] == 0) {
432                         stv680->VideoMode = 0x0000;
433                         PDEBUG (0, "STV(i): Video Mode set to CIF");
434                 }
435                 if (buffer[0] == 0x03) {
436                         stv680->VideoMode = 0x0300;
437                         PDEBUG (0, "STV(i): Video Mode set to QVGA");
438                 }
439         }
440         if ((i = stv_sndctrl (0, stv680, 0x8f, 0, buffer, 0x10)) != 0x10)
441                 goto error;
442         bufsize = (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | (buffer[3]);
443         stv680->cwidth = (buffer[4] << 8) | (buffer[5]);        /* ->camera = 322, 356, 644  */
444         stv680->cheight = (buffer[6] << 8) | (buffer[7]);       /* ->camera = 242, 292, 484  */
445         stv680->origGain = buffer[12];
446
447         goto exit;
448
449 error:
450         i = stv_sndctrl (0, stv680, 0x80, 0, buffer, 0x02);     /* Get Last Error */
451         PDEBUG (1, "STV(i): last error: %i,  command = 0x%x", buffer[0], buffer[1]);
452         kfree (buffer);
453         return -1;
454
455 exit:
456         kfree (buffer);
457
458         /* video = 320x240, 352x288 */
459         if (stv680->CIF == 1) {
460                 stv680->maxwidth = 352;
461                 stv680->maxheight = 288;
462                 stv680->vwidth = 352;
463                 stv680->vheight = 288;
464         }
465         if (stv680->QVGA == 1) {
466                 stv680->maxwidth = 320;
467                 stv680->maxheight = 240;
468                 stv680->vwidth = 320;
469                 stv680->vheight = 240;
470         }
471
472         stv680->rawbufsize = bufsize;   /* must be ./. by 8 */
473         stv680->maxframesize = bufsize * 3;     /* RGB size */
474         PDEBUG (2, "STV(i): cwidth = %i, cheight = %i", stv680->cwidth, stv680->cheight);
475         PDEBUG (1, "STV(i): width = %i, height = %i, rawbufsize = %li", stv680->vwidth, stv680->vheight, stv680->rawbufsize);
476
477         /* some default values */
478         stv680->bulk_in_endpointAddr = 0x82;
479         stv680->dropped = 0;
480         stv680->error = 0;
481         stv680->framecount = 0;
482         stv680->readcount = 0;
483         stv680->streaming = 0;
484         /* bright, white, colour, hue, contrast are set by software, not in stv0680 */
485         stv680->brightness = 32767;
486         stv680->chgbright = 0;
487         stv680->whiteness = 0;  /* only for greyscale */
488         stv680->colour = 32767;
489         stv680->contrast = 32767;
490         stv680->hue = 32767;
491         stv680->palette = STV_VIDEO_PALETTE;
492         stv680->depth = 24;     /* rgb24 bits */
493         if ((swapRGB_on == 0) && (swapRGB == 0))
494                 PDEBUG (1, "STV(i): swapRGB is (auto) OFF");
495         else if ((swapRGB_on == 0) && (swapRGB == 1))
496                 PDEBUG (1, "STV(i): swapRGB is (auto) ON");
497         else if (swapRGB_on == 1)
498                 PDEBUG (1, "STV(i): swapRGB is (forced) ON");
499         else if (swapRGB_on == -1)
500                 PDEBUG (1, "STV(i): swapRGB is (forced) OFF");
501         
502         if (stv_set_video_mode (stv680) < 0) {
503                 PDEBUG (0, "STV(e): Could not set video mode in stv_init");
504                 return -1;
505         }
506
507         return 0;
508 }
509
510 /***************** last of pencam  routines  *******************/
511
512 /****************************************************************************
513  *  sysfs
514  ***************************************************************************/
515 static inline struct usb_stv *cd_to_stv(struct class_device *cd)
516 {
517         struct video_device *vdev = to_video_device(cd);
518         return video_get_drvdata(vdev);
519 }
520
521 #define stv680_file(name, variable, field)                              \
522 static ssize_t show_##name(struct class_device *class_dev, char *buf)   \
523 {                                                                       \
524         struct video_device *vdev = to_video_device(class_dev);         \
525         struct usb_stv *stv = video_get_drvdata(vdev);                  \
526         return sprintf(buf, field, stv->variable);                      \
527 }                                                                       \
528 static CLASS_DEVICE_ATTR(name, S_IRUGO, show_##name, NULL);
529
530 stv680_file(model, camera_name, "%s\n");
531 stv680_file(in_use, user, "%d\n");
532 stv680_file(streaming, streaming, "%d\n");
533 stv680_file(palette, palette, "%i\n");
534 stv680_file(frames_total, readcount, "%d\n");
535 stv680_file(frames_read, framecount, "%d\n");
536 stv680_file(packets_dropped, dropped, "%d\n");
537 stv680_file(decoding_errors, error, "%d\n");
538
539 static void stv680_create_sysfs_files(struct video_device *vdev)
540 {
541         video_device_create_file(vdev, &class_device_attr_model);
542         video_device_create_file(vdev, &class_device_attr_in_use);
543         video_device_create_file(vdev, &class_device_attr_streaming);
544         video_device_create_file(vdev, &class_device_attr_palette);
545         video_device_create_file(vdev, &class_device_attr_frames_total);
546         video_device_create_file(vdev, &class_device_attr_frames_read);
547         video_device_create_file(vdev, &class_device_attr_packets_dropped);
548         video_device_create_file(vdev, &class_device_attr_decoding_errors);
549 }
550
551 static void stv680_remove_sysfs_files(struct video_device *vdev)
552 {
553         video_device_remove_file(vdev, &class_device_attr_model);
554         video_device_remove_file(vdev, &class_device_attr_in_use);
555         video_device_remove_file(vdev, &class_device_attr_streaming);
556         video_device_remove_file(vdev, &class_device_attr_palette);
557         video_device_remove_file(vdev, &class_device_attr_frames_total);
558         video_device_remove_file(vdev, &class_device_attr_frames_read);
559         video_device_remove_file(vdev, &class_device_attr_packets_dropped);
560         video_device_remove_file(vdev, &class_device_attr_decoding_errors);
561 }
562
563 /********************************************************************
564  * Camera control
565  *******************************************************************/
566
567 static int stv680_get_pict (struct usb_stv *stv680, struct video_picture *p)
568 {
569         /* This sets values for v4l interface. max/min = 65535/0  */
570
571         p->brightness = stv680->brightness;
572         p->whiteness = stv680->whiteness;       /* greyscale */
573         p->colour = stv680->colour;
574         p->contrast = stv680->contrast;
575         p->hue = stv680->hue;
576         p->palette = stv680->palette;
577         p->depth = stv680->depth;
578         return 0;
579 }
580
581 static int stv680_set_pict (struct usb_stv *stv680, struct video_picture *p)
582 {
583         /* See above stv680_get_pict  */
584
585         if (p->palette != STV_VIDEO_PALETTE) {
586                 PDEBUG (2, "STV(e): Palette set error in _set_pic");
587                 return 1;
588         }
589
590         if (stv680->brightness != p->brightness) {
591                 stv680->chgbright = 1;
592                 stv680->brightness = p->brightness;
593         } 
594
595         stv680->whiteness = p->whiteness;       /* greyscale */
596         stv680->colour = p->colour;
597         stv680->contrast = p->contrast;
598         stv680->hue = p->hue;
599         stv680->palette = p->palette;
600         stv680->depth = p->depth;
601
602         return 0;
603 }
604
605 static void stv680_video_irq (struct urb *urb, struct pt_regs *regs)
606 {
607         struct usb_stv *stv680 = urb->context;
608         int length = urb->actual_length;
609
610         if (length < stv680->rawbufsize)
611                 PDEBUG (2, "STV(i): Lost data in transfer: exp %li, got %i", stv680->rawbufsize, length);
612
613         /* ohoh... */
614         if (!stv680->streaming)
615                 return;
616
617         if (!stv680->udev) {
618                 PDEBUG (0, "STV(e): device vapourished in video_irq");
619                 return;
620         }
621
622         /* 0 sized packets happen if we are to fast, but sometimes the camera
623            keeps sending them forever...
624          */
625         if (length && !urb->status) {
626                 stv680->nullpackets = 0;
627                 switch (stv680->scratch[stv680->scratch_next].state) {
628                 case BUFFER_READY:
629                 case BUFFER_BUSY:
630                         stv680->dropped++;
631                         break;
632
633                 case BUFFER_UNUSED:
634                         memcpy (stv680->scratch[stv680->scratch_next].data,
635                                 (unsigned char *) urb->transfer_buffer, length);
636                         stv680->scratch[stv680->scratch_next].state = BUFFER_READY;
637                         stv680->scratch[stv680->scratch_next].length = length;
638                         if (waitqueue_active (&stv680->wq)) {
639                                 wake_up_interruptible (&stv680->wq);
640                         }
641                         stv680->scratch_overflow = 0;
642                         stv680->scratch_next++;
643                         if (stv680->scratch_next >= STV680_NUMSCRATCH)
644                                 stv680->scratch_next = 0;
645                         break;
646                 }               /* switch  */
647         } else {
648                 stv680->nullpackets++;
649                 if (stv680->nullpackets > STV680_MAX_NULLPACKETS) {
650                         if (waitqueue_active (&stv680->wq)) {
651                                 wake_up_interruptible (&stv680->wq);
652                         }
653                 }
654         }                       /*  if - else */
655
656         /* Resubmit urb for new data */
657         urb->status = 0;
658         urb->dev = stv680->udev;
659         if (usb_submit_urb (urb, GFP_ATOMIC))
660                 PDEBUG (0, "STV(e): urb burned down in video irq");
661         return;
662 }                               /*  _video_irq  */
663
664 static int stv680_start_stream (struct usb_stv *stv680)
665 {
666         struct urb *urb;
667         int err = 0, i;
668
669         stv680->streaming = 1;
670
671         /* Do some memory allocation */
672         for (i = 0; i < STV680_NUMFRAMES; i++) {
673                 stv680->frame[i].data = stv680->fbuf + i * stv680->maxframesize;
674                 stv680->frame[i].curpix = 0;
675         }
676         /* packet size = 4096  */
677         for (i = 0; i < STV680_NUMSBUF; i++) {
678                 stv680->sbuf[i].data = kmalloc (stv680->rawbufsize, GFP_KERNEL);
679                 if (stv680->sbuf[i].data == NULL) {
680                         PDEBUG (0, "STV(e): Could not kmalloc raw data buffer %i", i);
681                         return -1;
682                 }
683         }
684
685         stv680->scratch_next = 0;
686         stv680->scratch_use = 0;
687         stv680->scratch_overflow = 0;
688         for (i = 0; i < STV680_NUMSCRATCH; i++) {
689                 stv680->scratch[i].data = kmalloc (stv680->rawbufsize, GFP_KERNEL);
690                 if (stv680->scratch[i].data == NULL) {
691                         PDEBUG (0, "STV(e): Could not kmalloc raw scratch buffer %i", i);
692                         return -1;
693                 }
694                 stv680->scratch[i].state = BUFFER_UNUSED;
695         }
696
697         for (i = 0; i < STV680_NUMSBUF; i++) {
698                 urb = usb_alloc_urb (0, GFP_KERNEL);
699                 if (!urb)
700                         return -ENOMEM;
701
702                 /* sbuf is urb->transfer_buffer, later gets memcpyed to scratch */
703                 usb_fill_bulk_urb (urb, stv680->udev,
704                                    usb_rcvbulkpipe (stv680->udev, stv680->bulk_in_endpointAddr),
705                                    stv680->sbuf[i].data, stv680->rawbufsize,
706                                    stv680_video_irq, stv680);
707                 urb->timeout = PENCAM_TIMEOUT * 2;
708                 stv680->urb[i] = urb;
709                 err = usb_submit_urb (stv680->urb[i], GFP_KERNEL);
710                 if (err)
711                         PDEBUG (0, "STV(e): urb burned down in start stream");
712         }                       /* i STV680_NUMSBUF */
713
714         stv680->framecount = 0;
715         return 0;
716 }
717
718 static int stv680_stop_stream (struct usb_stv *stv680)
719 {
720         int i;
721
722         if (!stv680->streaming || !stv680->udev)
723                 return 1;
724
725         stv680->streaming = 0;
726
727         for (i = 0; i < STV680_NUMSBUF; i++)
728                 if (stv680->urb[i]) {
729                         usb_unlink_urb (stv680->urb[i]);
730                         usb_free_urb (stv680->urb[i]);
731                         stv680->urb[i] = NULL;
732                         kfree (stv680->sbuf[i].data);
733                 }
734         for (i = 0; i < STV680_NUMSCRATCH; i++) {
735                 kfree (stv680->scratch[i].data);
736                 stv680->scratch[i].data = NULL;
737         }
738
739         return 0;
740 }
741
742 static int stv680_set_size (struct usb_stv *stv680, int width, int height)
743 {
744         int wasstreaming = stv680->streaming;
745
746         /* Check to see if we need to change */
747         if ((stv680->vwidth == width) && (stv680->vheight == height))
748                 return 0;
749
750         PDEBUG (1, "STV(i): size request for %i x %i", width, height);
751         /* Check for a valid mode */
752         if ((!width || !height) || ((width & 1) || (height & 1))) {
753                 PDEBUG (1, "STV(e): set_size error: request: v.width = %i, v.height = %i  actual: stv.width = %i, stv.height = %i", width, height, stv680->vwidth, stv680->vheight);
754                 return 1;
755         }
756
757         if ((width < (stv680->maxwidth / 2)) || (height < (stv680->maxheight / 2))) {
758                 width = stv680->maxwidth / 2;
759                 height = stv680->maxheight / 2;
760         } else if ((width >= 158) && (width <= 166) && (stv680->QVGA == 1)) {
761                 width = 160;
762                 height = 120;
763         } else if ((width >= 172) && (width <= 180) && (stv680->CIF == 1)) {
764                 width = 176;
765                 height = 144;
766         } else if ((width >= 318) && (width <= 350) && (stv680->QVGA == 1)) {
767                 width = 320;
768                 height = 240;
769         } else if ((width >= 350) && (width <= 358) && (stv680->CIF == 1)) {
770                 width = 352;
771                 height = 288;
772         } else {
773                 PDEBUG (1, "STV(e): request for non-supported size: request: v.width = %i, v.height = %i  actual: stv.width = %i, stv.height = %i", width, height, stv680->vwidth, stv680->vheight);
774                 return 1;
775         }
776         
777         /* Stop a current stream and start it again at the new size */
778         if (wasstreaming)
779                 stv680_stop_stream (stv680);
780         stv680->vwidth = width;
781         stv680->vheight = height;
782         PDEBUG (1, "STV(i): size set to %i x %i", stv680->vwidth, stv680->vheight);
783         if (wasstreaming)
784                 stv680_start_stream (stv680);
785
786         return 0;
787 }
788
789 /**********************************************************************
790  * Video Decoding
791  **********************************************************************/
792
793 /*******  routines from the pencam program; hey, they work!  ********/
794
795 /*
796  * STV0680 Vision Camera Chipset Driver
797  * Copyright (C) 2000 Adam Harrison <adam@antispin.org> 
798 */
799
800 #define RED 0
801 #define GREEN 1
802 #define BLUE 2
803 #define AD(x, y, w) (((y)*(w)+(x))*3)
804
805 static void bayer_unshuffle (struct usb_stv *stv680, struct stv680_scratch *buffer)
806 {
807         int x, y, i;
808         int w = stv680->cwidth;
809         int vw = stv680->cwidth, vh = stv680->cheight;
810         unsigned int p = 0;
811         int colour = 0, bayer = 0;
812         unsigned char *raw = buffer->data;
813         struct stv680_frame *frame = &stv680->frame[stv680->curframe];
814         unsigned char *output = frame->data;
815         unsigned char *temp = frame->data;
816         int offset = buffer->offset;
817
818         if (frame->curpix == 0) {
819                 if (frame->grabstate == FRAME_READY) {
820                         frame->grabstate = FRAME_GRABBING;
821                 }
822         }
823         if (offset != frame->curpix) {  /* Regard frame as lost :( */
824                 frame->curpix = 0;
825                 stv680->error++;
826                 return;
827         }
828
829         if ((stv680->vwidth == 320) || (stv680->vwidth == 160)) {
830                 vw = 320;
831                 vh = 240;
832         }
833         if ((stv680->vwidth == 352) || (stv680->vwidth == 176)) {
834                 vw = 352;
835                 vh = 288;
836         }
837
838         memset (output, 0, 3 * vw * vh);        /* clear output matrix. */
839
840         for (y = 0; y < vh; y++) {
841                 for (x = 0; x < vw; x++) {
842                         if (x & 1)
843                                 p = *(raw + y * w + (x >> 1));
844                         else
845                                 p = *(raw + y * w + (x >> 1) + (w >> 1));
846
847                         if (y & 1)
848                                 bayer = 2;
849                         else
850                                 bayer = 0;
851                         if (x & 1)
852                                 bayer++;
853
854                         switch (bayer) {
855                         case 0:
856                         case 3:
857                                 colour = 1;
858                                 break;
859                         case 1:
860                                 colour = 0;
861                                 break;
862                         case 2:
863                                 colour = 2;
864                                 break;
865                         }
866                         i = (y * vw + x) * 3;   
867                         *(output + i + colour) = (unsigned char) p;
868                 }               /* for x */
869
870         }                       /* for y */
871
872         /****** gamma correction plus hardcoded white balance */
873         /* Thanks to Alexander Schwartx <alexander.schwartx@gmx.net> for this code.
874            Correction values red[], green[], blue[], are generated by 
875            (pow(i/256.0, GAMMA)*255.0)*white balanceRGB where GAMMA=0.55, 1<i<255. 
876            White balance (RGB)= 1.0, 1.17, 1.48. Values are calculated as double float and 
877            converted to unsigned char. Values are in stv680.h  */
878
879         for (y = 0; y < vh; y++) {
880                 for (x = 0; x < vw; x++) {
881                         i = (y * vw + x) * 3;
882                         *(output + i) = red[*(output + i)];
883                         *(output + i + 1) = green[*(output + i + 1)];
884                         *(output + i + 2) = blue[*(output + i + 2)];
885                 }
886         }
887
888         /******  bayer demosaic  ******/
889         for (y = 1; y < (vh - 1); y++) {
890                 for (x = 1; x < (vw - 1); x++) {        /* work out pixel type */
891                         if (y & 1)
892                                 bayer = 0;
893                         else
894                                 bayer = 2;
895                         if (!(x & 1))
896                                 bayer++;
897
898                         switch (bayer) {
899                         case 0: /* green. blue lr, red tb */
900                                 *(output + AD (x, y, vw) + BLUE) = ((int) *(output + AD (x - 1, y, vw) + BLUE) + (int) *(output + AD (x + 1, y, vw) + BLUE)) >> 1;
901                                 *(output + AD (x, y, vw) + RED) = ((int) *(output + AD (x, y - 1, vw) + RED) + (int) *(output + AD (x, y + 1, vw) + RED)) >> 1;
902                                 break;
903
904                         case 1: /* blue. green lrtb, red diagonals */
905                                 *(output + AD (x, y, vw) + GREEN) = ((int) *(output + AD (x - 1, y, vw) + GREEN) + (int) *(output + AD (x + 1, y, vw) + GREEN) + (int) *(output + AD (x, y - 1, vw) + GREEN) + (int) *(output + AD (x, y + 1, vw) + GREEN)) >> 2;
906                                 *(output + AD (x, y, vw) + RED) = ((int) *(output + AD (x - 1, y - 1, vw) + RED) + (int) *(output + AD (x - 1, y + 1, vw) + RED) + (int) *(output + AD (x + 1, y - 1, vw) + RED) + (int) *(output + AD (x + 1, y + 1, vw) + RED)) >> 2;
907                                 break;
908
909                         case 2: /* red. green lrtb, blue diagonals */
910                                 *(output + AD (x, y, vw) + GREEN) = ((int) *(output + AD (x - 1, y, vw) + GREEN) + (int) *(output + AD (x + 1, y, vw) + GREEN) + (int) *(output + AD (x, y - 1, vw) + GREEN) + (int) *(output + AD (x, y + 1, vw) + GREEN)) >> 2;
911                                 *(output + AD (x, y, vw) + BLUE) = ((int) *(output + AD (x - 1, y - 1, vw) + BLUE) + (int) *(output + AD (x + 1, y - 1, vw) + BLUE) + (int) *(output + AD (x - 1, y + 1, vw) + BLUE) + (int) *(output + AD (x + 1, y + 1, vw) + BLUE)) >> 2;
912                                 break;
913
914                         case 3: /* green. red lr, blue tb */
915                                 *(output + AD (x, y, vw) + RED) = ((int) *(output + AD (x - 1, y, vw) + RED) + (int) *(output + AD (x + 1, y, vw) + RED)) >> 1;
916                                 *(output + AD (x, y, vw) + BLUE) = ((int) *(output + AD (x, y - 1, vw) + BLUE) + (int) *(output + AD (x, y + 1, vw) + BLUE)) >> 1;
917                                 break;
918                         }       /* switch */
919                 }               /* for x */
920         }                       /* for y  - end demosaic  */
921
922         /* fix top and bottom row, left and right side */
923         i = vw * 3;
924         memcpy (output, (output + i), i);
925         memcpy ((output + (vh * i)), (output + ((vh - 1) * i)), i);
926         for (y = 0; y < vh; y++) {
927                 i = y * vw * 3;
928                 memcpy ((output + i), (output + i + 3), 3);
929                 memcpy ((output + i + (vw * 3)), (output + i + (vw - 1) * 3), 3);
930         }
931
932         /*  process all raw data, then trim to size if necessary */
933         if ((stv680->vwidth == 160) || (stv680->vwidth == 176))  {
934                 i = 0;
935                 for (y = 0; y < vh; y++) {
936                         if (!(y & 1)) {
937                                 for (x = 0; x < vw; x++) {
938                                         p = (y * vw + x) * 3;
939                                         if (!(x & 1)) {
940                                                 *(output + i) = *(output + p);
941                                                 *(output + i + 1) = *(output + p + 1);
942                                                 *(output + i + 2) = *(output + p + 2);
943                                                 i += 3;
944                                         }
945                                 }  /* for x */
946                         }
947                 }  /* for y */
948         }
949         /* reset to proper width */
950         if ((stv680->vwidth == 160)) {
951                 vw = 160;
952                 vh = 120;
953         }
954         if ((stv680->vwidth == 176)) {
955                 vw = 176;
956                 vh = 144;
957         }
958
959         /* output is RGB; some programs want BGR  */
960         /* swapRGB_on=0 -> program decides;  swapRGB_on=1, always swap */
961         /* swapRGB_on=-1, never swap */
962         if (((swapRGB == 1) && (swapRGB_on != -1)) || (swapRGB_on == 1)) {
963                 for (y = 0; y < vh; y++) {
964                         for (x = 0; x < vw; x++) {
965                                 i = (y * vw + x) * 3;
966                                 *(temp) = *(output + i);
967                                 *(output + i) = *(output + i + 2);
968                                 *(output + i + 2) = *(temp);
969                         }
970                 }
971         }
972         /* brightness */
973         if (stv680->chgbright == 1) {
974                 if (stv680->brightness >= 32767) {
975                         p = (stv680->brightness - 32767) / 256;
976                         for (x = 0; x < (vw * vh * 3); x++) {
977                                 if ((*(output + x) + (unsigned char) p) > 255)
978                                         *(output + x) = 255;
979                                 else
980                                         *(output + x) += (unsigned char) p;
981                         }       /* for */
982                 } else {
983                         p = (32767 - stv680->brightness) / 256;
984                         for (x = 0; x < (vw * vh * 3); x++) {
985                                 if ((unsigned char) p > *(output + x))
986                                         *(output + x) = 0;
987                                 else
988                                         *(output + x) -= (unsigned char) p;
989                         }       /* for */
990                 }               /* else */
991         }
992         /* if */
993         frame->curpix = 0;
994         frame->curlinepix = 0;
995         frame->grabstate = FRAME_DONE;
996         stv680->framecount++;
997         stv680->readcount++;
998         if (stv680->frame[(stv680->curframe + 1) & (STV680_NUMFRAMES - 1)].grabstate == FRAME_READY) {
999                 stv680->curframe = (stv680->curframe + 1) & (STV680_NUMFRAMES - 1);
1000         }
1001
1002 }                               /* bayer_unshuffle */
1003
1004 /*******  end routines from the pencam program  *********/
1005
1006 static int stv680_newframe (struct usb_stv *stv680, int framenr)
1007 {
1008         int errors = 0;
1009
1010         while (stv680->streaming && (stv680->frame[framenr].grabstate == FRAME_READY || stv680->frame[framenr].grabstate == FRAME_GRABBING)) {
1011                 if (!stv680->frame[framenr].curpix) {
1012                         errors++;
1013                 }
1014                 wait_event_interruptible (stv680->wq, (stv680->scratch[stv680->scratch_use].state == BUFFER_READY));
1015
1016                 if (stv680->nullpackets > STV680_MAX_NULLPACKETS) {
1017                         stv680->nullpackets = 0;
1018                         PDEBUG (2, "STV(i): too many null length packets, restarting capture");
1019                         stv680_stop_stream (stv680);
1020                         stv680_start_stream (stv680);
1021                 } else {
1022                         if (stv680->scratch[stv680->scratch_use].state != BUFFER_READY) {
1023                                 stv680->frame[framenr].grabstate = FRAME_ERROR;
1024                                 PDEBUG (2, "STV(e): FRAME_ERROR in _newframe");
1025                                 return -EIO;
1026                         }
1027                         stv680->scratch[stv680->scratch_use].state = BUFFER_BUSY;
1028
1029                         bayer_unshuffle (stv680, &stv680->scratch[stv680->scratch_use]);
1030
1031                         stv680->scratch[stv680->scratch_use].state = BUFFER_UNUSED;
1032                         stv680->scratch_use++;
1033                         if (stv680->scratch_use >= STV680_NUMSCRATCH)
1034                                 stv680->scratch_use = 0;
1035                         if (errors > STV680_MAX_ERRORS) {
1036                                 errors = 0;
1037                                 PDEBUG (2, "STV(i): too many errors, restarting capture");
1038                                 stv680_stop_stream (stv680);
1039                                 stv680_start_stream (stv680);
1040                         }
1041                 }               /* else */
1042         }                       /* while */
1043         return 0;
1044 }
1045
1046 /*********************************************************************
1047  * Video4Linux
1048  *********************************************************************/
1049
1050 static int stv_open (struct inode *inode, struct file *file)
1051 {
1052         struct video_device *dev = video_devdata(file);
1053         struct usb_stv *stv680 = video_get_drvdata(dev);
1054         int err = 0;
1055
1056         /* we are called with the BKL held */
1057         stv680->user = 1;
1058         err = stv_init (stv680);        /* main initialization routine for camera */
1059
1060         if (err >= 0) {
1061                 stv680->fbuf = rvmalloc (stv680->maxframesize * STV680_NUMFRAMES);
1062                 if (!stv680->fbuf) {
1063                         PDEBUG (0, "STV(e): Could not rvmalloc frame bufer");
1064                         err = -ENOMEM;
1065                 }
1066                 file->private_data = dev;
1067         }
1068         if (err)
1069                 stv680->user = 0;
1070
1071         return err;
1072 }
1073
1074 static int stv_close (struct inode *inode, struct file *file)
1075 {
1076         struct video_device *dev = file->private_data;
1077         struct usb_stv *stv680 = video_get_drvdata(dev);
1078         int i;
1079
1080         for (i = 0; i < STV680_NUMFRAMES; i++)
1081                 stv680->frame[i].grabstate = FRAME_UNUSED;
1082         if (stv680->streaming)
1083                 stv680_stop_stream (stv680);
1084
1085         if ((i = stv_stop_video (stv680)) < 0)
1086                 PDEBUG (1, "STV(e): stop_video failed in stv_close");
1087
1088         rvfree (stv680->fbuf, stv680->maxframesize * STV680_NUMFRAMES);
1089         stv680->user = 0;
1090
1091         if (stv680->removed) {
1092                 kfree (stv680);
1093                 stv680 = NULL;
1094                 PDEBUG (0, "STV(i): device unregistered");
1095         }
1096         file->private_data = NULL;
1097         return 0;
1098 }
1099
1100 static int stv680_do_ioctl (struct inode *inode, struct file *file,
1101                             unsigned int cmd, void *arg)
1102 {
1103         struct video_device *vdev = file->private_data;
1104         struct usb_stv *stv680 = video_get_drvdata(vdev);
1105
1106         if (!stv680->udev)
1107                 return -EIO;
1108
1109         switch (cmd) {
1110         case VIDIOCGCAP:{
1111                         struct video_capability *b = arg;
1112
1113                         strcpy (b->name, stv680->camera_name);
1114                         b->type = VID_TYPE_CAPTURE;
1115                         b->channels = 1;
1116                         b->audios = 0;
1117                         b->maxwidth = stv680->maxwidth;
1118                         b->maxheight = stv680->maxheight;
1119                         b->minwidth = stv680->maxwidth / 2;
1120                         b->minheight = stv680->maxheight / 2;
1121                         return 0;
1122                 }
1123         case VIDIOCGCHAN:{
1124                         struct video_channel *v = arg;
1125
1126                         if (v->channel != 0)
1127                                 return -EINVAL;
1128                         v->flags = 0;
1129                         v->tuners = 0;
1130                         v->type = VIDEO_TYPE_CAMERA;
1131                         strcpy (v->name, "STV Camera");
1132                         return 0;
1133                 }
1134         case VIDIOCSCHAN:{
1135                         struct video_channel *v = arg;
1136                         if (v->channel != 0)
1137                                 return -EINVAL;
1138                         return 0;
1139                 }
1140         case VIDIOCGPICT:{
1141                         struct video_picture *p = arg;
1142
1143                         stv680_get_pict (stv680, p);
1144                         return 0;
1145                 }
1146         case VIDIOCSPICT:{
1147                         struct video_picture *p = arg;
1148
1149                         if (stv680_set_pict (stv680, p))
1150                                 return -EINVAL;
1151                         return 0;
1152                 }
1153         case VIDIOCSWIN:{
1154                         struct video_window *vw = arg;
1155
1156                         if (vw->flags)
1157                                 return -EINVAL;
1158                         if (vw->clipcount)
1159                                 return -EINVAL;
1160                         if (vw->width != stv680->vwidth) {
1161                                 if (stv680_set_size (stv680, vw->width, vw->height)) {
1162                                         PDEBUG (2, "STV(e): failed (from user) set size in VIDIOCSWIN");
1163                                         return -EINVAL;
1164                                 }
1165                         }
1166                         return 0;
1167                 }
1168         case VIDIOCGWIN:{
1169                         struct video_window *vw = arg;
1170
1171                         vw->x = 0;      /* FIXME */
1172                         vw->y = 0;
1173                         vw->chromakey = 0;
1174                         vw->flags = 0;
1175                         vw->clipcount = 0;
1176                         vw->width = stv680->vwidth;
1177                         vw->height = stv680->vheight;
1178                         return 0;
1179                 }
1180         case VIDIOCGMBUF:{
1181                         struct video_mbuf *vm = arg;
1182                         int i;
1183
1184                         memset (vm, 0, sizeof (*vm));
1185                         vm->size = STV680_NUMFRAMES * stv680->maxframesize;
1186                         vm->frames = STV680_NUMFRAMES;
1187                         for (i = 0; i < STV680_NUMFRAMES; i++)
1188                                 vm->offsets[i] = stv680->maxframesize * i;
1189                         return 0;
1190                 }
1191         case VIDIOCMCAPTURE:{
1192                         struct video_mmap *vm = arg;
1193
1194                         if (vm->format != STV_VIDEO_PALETTE) {
1195                                 PDEBUG (2, "STV(i): VIDIOCMCAPTURE vm.format (%i) != VIDEO_PALETTE (%i)",
1196                                         vm->format, STV_VIDEO_PALETTE);
1197                                 if ((vm->format == 3) && (swapRGB_on == 0))  {
1198                                         PDEBUG (2, "STV(i): VIDIOCMCAPTURE swapRGB is (auto) ON");
1199                                         /* this may fix those apps (e.g., xawtv) that want BGR */
1200                                         swapRGB = 1;
1201                                 }
1202                                 return -EINVAL;
1203                         }
1204                         if (vm->frame >= STV680_NUMFRAMES) {
1205                                 PDEBUG (2, "STV(e): VIDIOCMCAPTURE vm.frame > NUMFRAMES");
1206                                 return -EINVAL;
1207                         }
1208                         if ((stv680->frame[vm->frame].grabstate == FRAME_ERROR)
1209                             || (stv680->frame[vm->frame].grabstate == FRAME_GRABBING)) {
1210                                 PDEBUG (2, "STV(e): VIDIOCMCAPTURE grabstate (%i) error",
1211                                         stv680->frame[vm->frame].grabstate);
1212                                 return -EBUSY;
1213                         }
1214                         /* Is this according to the v4l spec??? */
1215                         if (stv680->vwidth != vm->width) {
1216                                 if (stv680_set_size (stv680, vm->width, vm->height)) {
1217                                         PDEBUG (2, "STV(e): VIDIOCMCAPTURE set_size failed");
1218                                         return -EINVAL;
1219                                 }
1220                         }
1221                         stv680->frame[vm->frame].grabstate = FRAME_READY;
1222
1223                         if (!stv680->streaming)
1224                                 stv680_start_stream (stv680);
1225
1226                         return 0;
1227                 }
1228         case VIDIOCSYNC:{
1229                         int *frame = arg;
1230                         int ret = 0;
1231
1232                         if (*frame < 0 || *frame >= STV680_NUMFRAMES) {
1233                                 PDEBUG (2, "STV(e): Bad frame # in VIDIOCSYNC");
1234                                 return -EINVAL;
1235                         }
1236                         ret = stv680_newframe (stv680, *frame);
1237                         stv680->frame[*frame].grabstate = FRAME_UNUSED;
1238                         return ret;
1239                 }
1240         case VIDIOCGFBUF:{
1241                         struct video_buffer *vb = arg;
1242
1243                         memset (vb, 0, sizeof (*vb));
1244                         return 0;
1245                 }
1246         case VIDIOCKEY:
1247                 return 0;
1248         case VIDIOCCAPTURE:
1249                 {
1250                         PDEBUG (2, "STV(e): VIDIOCCAPTURE failed");
1251                         return -EINVAL;
1252                 }
1253         case VIDIOCSFBUF:
1254         case VIDIOCGTUNER:
1255         case VIDIOCSTUNER:
1256         case VIDIOCGFREQ:
1257         case VIDIOCSFREQ:
1258         case VIDIOCGAUDIO:
1259         case VIDIOCSAUDIO:
1260                 return -EINVAL;
1261         default:
1262                 return -ENOIOCTLCMD;
1263         }                       /* end switch */
1264
1265         return 0;
1266 }
1267
1268 static int stv680_ioctl(struct inode *inode, struct file *file,
1269                         unsigned int cmd, unsigned long arg)
1270 {
1271         return video_usercopy(inode, file, cmd, arg, stv680_do_ioctl);
1272 }
1273
1274 static int stv680_mmap (struct file *file, struct vm_area_struct *vma)
1275 {
1276         struct video_device *dev = file->private_data;
1277         struct usb_stv *stv680 = video_get_drvdata(dev);
1278         unsigned long start = vma->vm_start;
1279         unsigned long size  = vma->vm_end-vma->vm_start;
1280         unsigned long page, pos;
1281
1282         down (&stv680->lock);
1283
1284         if (stv680->udev == NULL) {
1285                 up (&stv680->lock);
1286                 return -EIO;
1287         }
1288         if (size > (((STV680_NUMFRAMES * stv680->maxframesize) + PAGE_SIZE - 1)
1289                     & ~(PAGE_SIZE - 1))) {
1290                 up (&stv680->lock);
1291                 return -EINVAL;
1292         }
1293         pos = (unsigned long) stv680->fbuf;
1294         while (size > 0) {
1295                 page = kvirt_to_pa (pos);
1296                 if (remap_page_range (vma, start, page, PAGE_SIZE, PAGE_SHARED)) {
1297                         up (&stv680->lock);
1298                         return -EAGAIN;
1299                 }
1300                 start += PAGE_SIZE;
1301                 pos += PAGE_SIZE;
1302                 if (size > PAGE_SIZE)
1303                         size -= PAGE_SIZE;
1304                 else
1305                         size = 0;
1306         }
1307         up (&stv680->lock);
1308
1309         return 0;
1310 }
1311
1312 static ssize_t stv680_read (struct file *file, char *buf,
1313                         size_t count, loff_t *ppos)
1314 {
1315         struct video_device *dev = file->private_data;
1316         unsigned long int realcount = count;
1317         int ret = 0;
1318         struct usb_stv *stv680 = video_get_drvdata(dev);
1319         unsigned long int i;
1320
1321         if (STV680_NUMFRAMES != 2) {
1322                 PDEBUG (0, "STV(e): STV680_NUMFRAMES needs to be 2!");
1323                 return -1;
1324         }
1325         if (stv680->udev == NULL)
1326                 return -EIO;
1327         if (realcount > (stv680->vwidth * stv680->vheight * 3))
1328                 realcount = stv680->vwidth * stv680->vheight * 3;
1329
1330         /* Shouldn't happen: */
1331         if (stv680->frame[0].grabstate == FRAME_GRABBING) {
1332                 PDEBUG (2, "STV(e): FRAME_GRABBING in stv680_read");
1333                 return -EBUSY;
1334         }
1335         stv680->frame[0].grabstate = FRAME_READY;
1336         stv680->frame[1].grabstate = FRAME_UNUSED;
1337         stv680->curframe = 0;
1338
1339         if (!stv680->streaming)
1340                 stv680_start_stream (stv680);
1341
1342         if (!stv680->streaming) {
1343                 ret = stv680_newframe (stv680, 0);      /* ret should = 0 */
1344         }
1345
1346         ret = stv680_newframe (stv680, 0);
1347
1348         if (!ret) {
1349                 if ((i = copy_to_user (buf, stv680->frame[0].data, realcount)) != 0) {
1350                         PDEBUG (2, "STV(e): copy_to_user frame 0 failed, ret count = %li", i);
1351                         return -EFAULT;
1352                 }
1353         } else {
1354                 realcount = ret;
1355         }
1356         stv680->frame[0].grabstate = FRAME_UNUSED;
1357         return realcount;
1358 }                               /* stv680_read */
1359
1360 static struct file_operations stv680_fops = {
1361         .owner =        THIS_MODULE,
1362         .open =         stv_open,
1363         .release =      stv_close,
1364         .read =         stv680_read,
1365         .mmap =         stv680_mmap,
1366         .ioctl =        stv680_ioctl,
1367         .llseek =       no_llseek,
1368 };
1369 static struct video_device stv680_template = {
1370         .owner =        THIS_MODULE,
1371         .name =         "STV0680 USB camera",
1372         .type =         VID_TYPE_CAPTURE,
1373         .hardware =     VID_HARDWARE_SE401,
1374         .fops =         &stv680_fops,
1375         .release =      video_device_release,
1376         .minor =        -1,
1377 };
1378
1379 static int stv680_probe (struct usb_interface *intf, const struct usb_device_id *id)
1380 {
1381         struct usb_device *dev = interface_to_usbdev(intf);
1382         struct usb_host_interface *interface;
1383         struct usb_stv *stv680 = NULL;
1384         char *camera_name = NULL;
1385         int retval = 0;
1386
1387         /* We don't handle multi-config cameras */
1388         if (dev->descriptor.bNumConfigurations != 1) {
1389                 PDEBUG (0, "STV(e): Number of Configurations != 1");
1390                 return -ENODEV;
1391         }
1392
1393         interface = &intf->altsetting[0];
1394         /* Is it a STV680? */
1395         if ((dev->descriptor.idVendor == USB_PENCAM_VENDOR_ID) && (dev->descriptor.idProduct == USB_PENCAM_PRODUCT_ID)) {
1396                 camera_name = "STV0680";
1397                 PDEBUG (0, "STV(i): STV0680 camera found.");
1398         } else {
1399                 PDEBUG (0, "STV(e): Vendor/Product ID do not match STV0680 values.");
1400                 PDEBUG (0, "STV(e): Check that the STV0680 camera is connected to the computer.");
1401                 retval = -ENODEV;
1402                 goto error;
1403         }
1404         /* We found one */
1405         if ((stv680 = kmalloc (sizeof (*stv680), GFP_KERNEL)) == NULL) {
1406                 PDEBUG (0, "STV(e): couldn't kmalloc stv680 struct.");
1407                 retval = -ENOMEM;
1408                 goto error;
1409         }
1410
1411         memset (stv680, 0, sizeof (*stv680));
1412
1413         stv680->udev = dev;
1414         stv680->camera_name = camera_name;
1415
1416         stv680->vdev = video_device_alloc();
1417         if (!stv680->vdev) {
1418                 retval = -ENOMEM;
1419                 goto error;
1420         }
1421         memcpy(stv680->vdev, &stv680_template, sizeof(stv680_template));
1422         stv680->vdev->dev = &intf->dev;
1423         video_set_drvdata(stv680->vdev, stv680);
1424
1425         memcpy (stv680->vdev->name, stv680->camera_name, strlen (stv680->camera_name));
1426         init_waitqueue_head (&stv680->wq);
1427         init_MUTEX (&stv680->lock);
1428         wmb ();
1429
1430         if (video_register_device (stv680->vdev, VFL_TYPE_GRABBER, video_nr) == -1) {
1431                 PDEBUG (0, "STV(e): video_register_device failed");
1432                 retval = -EIO;
1433                 goto error_vdev;
1434         }
1435         PDEBUG (0, "STV(i): registered new video device: video%d", stv680->vdev->minor);
1436
1437         usb_set_intfdata (intf, stv680);
1438         stv680_create_sysfs_files(stv680->vdev);
1439         return 0;
1440
1441 error_vdev:
1442         video_device_release(stv680->vdev);
1443 error:
1444         kfree(stv680);
1445         return retval;
1446 }
1447
1448 static inline void usb_stv680_remove_disconnected (struct usb_stv *stv680)
1449 {
1450         int i;
1451
1452         stv680->udev = NULL;
1453         stv680->frame[0].grabstate = FRAME_ERROR;
1454         stv680->frame[1].grabstate = FRAME_ERROR;
1455         stv680->streaming = 0;
1456
1457         wake_up_interruptible (&stv680->wq);
1458
1459         for (i = 0; i < STV680_NUMSBUF; i++)
1460                 if (stv680->urb[i]) {
1461                         usb_unlink_urb (stv680->urb[i]);
1462                         usb_free_urb (stv680->urb[i]);
1463                         stv680->urb[i] = NULL;
1464                         kfree (stv680->sbuf[i].data);
1465                 }
1466         for (i = 0; i < STV680_NUMSCRATCH; i++)
1467                 kfree (stv680->scratch[i].data);
1468         PDEBUG (0, "STV(i): %s disconnected", stv680->camera_name);
1469
1470         /* Free the memory */
1471         kfree (stv680);
1472 }
1473
1474 static void stv680_disconnect (struct usb_interface *intf)
1475 {
1476         struct usb_stv *stv680 = usb_get_intfdata (intf);
1477
1478         usb_set_intfdata (intf, NULL);
1479
1480         if (stv680) {
1481                 /* We don't want people trying to open up the device */
1482                 if (stv680->vdev) {
1483                         stv680_remove_sysfs_files(stv680->vdev);
1484                         video_unregister_device(stv680->vdev);
1485                         stv680->vdev = NULL;
1486                 }
1487                 if (!stv680->user) {
1488                         usb_stv680_remove_disconnected (stv680);
1489                 } else {
1490                         stv680->removed = 1;
1491                 }
1492         }
1493 }
1494
1495 static struct usb_driver stv680_driver = {
1496         .owner =        THIS_MODULE,
1497         .name =         "stv680",
1498         .probe =        stv680_probe,
1499         .disconnect =   stv680_disconnect,
1500         .id_table =     device_table
1501 };
1502
1503 /********************************************************************
1504  *  Module routines
1505  ********************************************************************/
1506
1507 static int __init usb_stv680_init (void)
1508 {
1509         if (usb_register (&stv680_driver) < 0) {
1510                 PDEBUG (0, "STV(e): Could not setup STV0680 driver");
1511                 return -1;
1512         }
1513         PDEBUG (0, "STV(i): usb camera driver version %s registering", DRIVER_VERSION);
1514
1515         info(DRIVER_DESC " " DRIVER_VERSION);
1516         return 0;
1517 }
1518
1519 static void __exit usb_stv680_exit (void)
1520 {
1521         usb_deregister (&stv680_driver);
1522         PDEBUG (0, "STV(i): driver deregistered");
1523 }
1524
1525 module_init (usb_stv680_init);
1526 module_exit (usb_stv680_exit);