V4L/DVB (4922): Add usbvision driver
[linux-2.6] / drivers / media / video / usbvision / usbvision-core.c
1 /*
2  * USB USBVISION Video device driver 0.9.8.3cvs (For Kernel 2.4.19-2.4.32 + 2.6.0-2.6.16)
3  *
4  * 
5  *
6  * Copyright (c) 1999-2005 Joerg Heckenbach <joerg@heckenbach-aw.de>
7  *
8  * This module is part of usbvision driver project.
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  *
24  * Let's call the version 0.... until compression decoding is completely
25  * implemented.
26  *
27  * This driver is written by Jose Ignacio Gijon and Joerg Heckenbach.
28  * It was based on USB CPiA driver written by Peter Pregler,
29  * Scott J. Bertin and Johannes Erdfelt
30  * Ideas are taken from bttv driver by Ralph Metzler, Marcus Metzler &
31  * Gerd Knorr and zoran 36120/36125 driver by Pauline Middelink
32  * Updates to driver completed by Dwaine P. Garden
33  *
34  * History:
35  *
36  * Mar. 2000 - 15.12.2000:  (0.0.0 - 0.2.0)
37  *     Several alpha drivers and the first beta.
38  *
39  * Since Dec. 2000:  (0.2.1) or (v2.1)
40  *     Code changes or updates by Dwaine Garden and every other person.
41  *
42  *     Added: New Hauppauge TV device  Vendor  ID: 0x0573
43  *                                     Product ID: 0x4D01
44  *            (Thanks to Giovanni Garberoglio)
45  *
46  *     Added: UK Hauppauge WinTV-USB   Vendor  ID: 0x0573
47  *                                     Product ID: 0x4D02
48  *            (Thanks to Derek Freeman-Jones)
49  *
50  * Feb, 2001 - Apr 08, 2001:  (0.3.0)
51  *     - Some fixes. Driver is now more stable.
52  *     - Scratch is organized as ring-buffer now for better performance
53  *     - DGA (overlay) is now supported.
54  *       !!!!Danger!!!! Clipping is not yet implemented. Your system will
55  *       crash if your video window leaves the screen!!!
56  *     - Max. Framesize is set to 320x240. There isn't more memory on the
57  *       nt1003 video device for the FIFO.
58  *     - Supported video palettes: RGB565, RGB555, RGB24, RGB32
59  *
60  *
61  * Apr 15, 2001:  (0.3.1-test...)
62  *     - Clipping is implemented
63  *     - NTSC is now coloured (Thanks to Dwaine Garden)
64  *     - Added SECAM colour detection in saa7111-new
65  *     - Added: French Hauppauge WinTV USB  Vendor ID: 0x0573
66  *                                          Product ID: 0x4D03
67  *              (Thanks to Julius Hrivnac)
68  *     - Added: US Hauppauge WINTV USB  Vendor ID: 0x0573
69  *                                      Product ID: 0x4D00
70  *              (Thanks to  Derrick J Brashear)
71  *     - Changes for adding new devices. There's now a table in usbvision.h.
72  *       Adding your devices data to the usbvision_device_data table is all
73  *       you need to add a new device.
74  *
75  * May 11, 2001: (0.3.2-test...) (Thanks to Derek Freeman-Jones)
76  *     - Support YUV422 raw format for people with hardware scaling.
77  *     - Only power on the device when opened (use option PowerOnAtOpen=0 to disable it).
78  *     - Turn off audio so we can listen to Line In.
79  *
80  * July 5, 2001 - (Patch the driver to run with Kernel 2.4.6)
81  *     - Fixed a problem with the number of parameters passed to video_register_device.
82  *
83  * July 6, 2001 - Added: HAUPPAUGE WINTV-USB FM USA Vendor  ID: 0x0573
84  *                                                      Product ID: 0x4D10
85  *       (Thanks to Braddock Gaskill)
86  *                Added: USBGear USBG-V1 resp. HAMA USB
87  *                                      Vendor  ID: 0x0573
88  *                                      Product ID: 0x0003
89  *       (Thanks to Bradley A. Singletary and Juergen Weigert)
90  *
91  * Jan 24, 2002 - (0.3.3-test...)
92  *     - Moved all global variables that are device specific the usb_usbvision struct
93  *     - Fixed the 64x48 unchangable image in xawtv when starting it with overlay
94  *     - Add VideoNorm and TunerType to the usb_device_data table
95  *     - Checked the audio channels and mute for HAUPPAUGE WinTV USB FM
96  *     - Implemented the power on when opening the device. But some software opens
97  *       the device several times when starting. So the i2c parts are just registered
98  *       by an open, when they become deregistered by the next close. You can speed
99  *       up tuner detection, when adding "options tuner addr=your_addr" to /etc/modules.conf
100  *     - Begin to resize the frame in width and height. So it will be possible to watch i.e.
101  *       384x288 pixels at 23 fps.
102  *
103  * Feb 10, 2002
104  *     - Added radio device
105  *
106  *
107  * Jul 30, 2002 - (Thanks Cameron Maxwell)
108  *     - Changes to usbvision.h --fixed usbvision device data structure, incorrectly had (0x0573, 0x4d21) for WinTV-USB II, should be 0x4d20.
109  *     - Changes for device WinTV-USB II (0x0573. 0x4D21).  It does not have a FM tuner.
110  *     - Added the real device HAUPPAUGE WINTV-USB II (PAL) to the device structure in usbvision.h.
111  *     - Changes to saa7113-new, the video is 8 bit data for the Phillips SAA7113 not 16bit like SAA7111.
112  *     - Tuned lots of setup registers for the Phillips SAA7113 video chipset.
113  *     - Changes to the supplied makefile. (Dwaine Garden) Still needs to be fixed so it will compile modules on different distrubutions.
114  *
115  *
116  * Aug 10, 2002 - (Thanks Mike Klinke)
117  *     - Changes to usbvision.txt -- Fixed instructions on the location to copy the contents of the tgz file.
118  *     - Added device WinTV-USB FM Model 621 (0x0573. 0x4D30). There is another device which carries the same name. Kept that device in the device structure.
119  *
120  * Aug 12, 2002 - Dwaine Garden
121  *     - Added the ability to read the NT100x chip for the MaxISOPacketLength and USB Bandwidth
122  *       Setting of the video device.
123  *     - Adjustments to the SAA7113H code for proper video output.
124  *     - Changes to usbvision.h, so all the devices with FM tuners are working.
125  *
126  * Feb 10, 2003 - Joerg Heckenbach
127  *     - fixed endian bug for Motorola PPC
128  *
129  * Feb 13, 2003 - Joerg Heckenbach
130  *     - fixed Vin_Reg setting and presetting from usbvision_device_data()
131  *
132  * Apr 19, 2003 - Dwaine Garden
133  *     - Fixed compiling errors under RedHat v9.0. from uvirt_to_kva and usbvision_mmap. (Thanks Cameron Maxwell)
134  *     - Changed pte_offset to pte_offset_kernel.
135  *     - Changed remap_page_range and added additional parameter to function.
136  *     - Change setup parameters for the D-Link V100 USB device
137  *     - Added a new device to the usbvision driver.  Pinnacle Studio PCTV USB (PAL) 0x2304 0x0110
138  *     - Screwed up the sourceforge.net cvs respository!  8*)
139  *
140  * Apr 22, 2002 - Dwaine Garden
141  *     - Added a new device to the usbvision driver. Dazzle DVC-80 (PAL) 0x07d0 0x0004. (Thanks Carl Anderson)
142  *     - Changes to some of the comments.
143  *
144  * June 06, 2002 - Ivan, Dwaine Garden
145  *     - Ivan updates for fine tuning device parameters without driver recompiling. (Ivan)
146  *     - Changes to some of the comments. (Dwaine Garden)
147  *     - Changes to the makefile - Better CPU settings. (Ivan)
148  *     - Changes to device Hauppauge WinTv-USB III (PAL) FM Model 568 - Fine tuning parameters (Ivan)
149  *
150  *
151  * Oct 16, 2003 - 0.9.0 - Joerg Heckenbach
152  *     - Implementation of the first part of the decompression algorithm for intra frames.
153  *       The resolution has to be 320x240. A dynamic adaption of compression deepth is
154  *       missing yet.
155  *
156  * Oct 22, 2003 - 0.9.1 - Joerg Heckenbach
157  *     - Implementation of the decompression algorithm for inter frames.
158  *       The resolution still has to be 320x240.
159  *
160  * Nov 2003 - Feb 2004 - 0.9.2 to 0.9.3 - Joerg Heckenbach
161  *     - Implement last unknown compressed block type. But color is still noisy.
162  *     - Finding criteria for adaptive compression adjustment.
163  *     - Porting to 2.6 kernels, but still working under 2.4
164  *
165  * Feb 04, 2004 - 0.9.4 Joerg Heckenbach
166  *     - Found bug in color decompression. Color is OK now.
167  *
168  * Feb 09, 2004 - 0.9.5 Joerg Heckenbach
169  *     - Add auto-recognition of chip type NT1003 or NT1004.
170  *     - Add adaptive compression adjustment.
171  *     - Patched saa7113 multiplexer switching (Thanks to Orlando F.S. Bordoni)
172  *
173  * Feb 24, 2004 - 0.9.6 Joerg Heckenbach
174  *     - Add a timer to wait before poweroff at close, to save start time in
175  *       some video applications
176  *
177  * Mar 4, 2004 - 0.9.6 Dwaine Garden
178  *     - Added device Global Village GV-007 (NTSC) to usbvision.h (Thanks to Abe Skolnik)
179  *     - Forgot to add this device to the driver. 8*)
180  *
181  * June 2, 2004 - 0.9.6 Dwaine Garden
182  *     - Fixed sourceforge.net cvs repository.
183  *     - Added #if LINUX_VERSION_CODE > KERNEL_VERSION(2,4,26) for .owner to help compiling under kernels 2.4.x which do not have the i2c v2.8.x updates.
184  *     - Added device Hauppauge WinTv-USB III (PAL) FM Model 597 to usbvision.h 
185  *
186  * July 1, 2004 -0.9.6 Dwaine Garden
187  *     - Patch was submitted by Hal Finkel to fix the problem with the tuner not working under kernel 2.6.7.
188  *     - Thanks Hal.....
189  *
190  * July 30, 2004 - 0.9.6 Dwaine Garden
191  *     - Patch was submitted by Tobias Diaz to fix Model ID mismatch in usbvision.h.
192  *     - Thanks.....
193  *
194  * August 12, 2004 - 0.9.6 Dwaine Garden
195  *     - Updated the readme file so people could install the driver under the configuration file for kernel 2.6.x recompiles.  Now people can use make xconfig!
196  *     - Added new device "Camtel Technology Corp TVB330-USB FM".
197  *     - Sourceforge.net CVS has been updated with all the changes.
198  *
199  * August 20, 2004 - 0.9.7 Dwaine Garden
200  *     - Added Device "Hauppauge USB Live Model 600"
201  *     - Fixed up all the devices which did not have a default tuner type in usbvision.h.  It's best guess, at least until someone with the device tells me otherwise.
202  *     - Sourceforge.net CVS has been updated with all the changes.
203  *     - Clean up the driver.
204  *
205  * September 13, 2004 - 0.9.8 Dwaine Garden
206  *     - Changed usbvision_muxsel to address the problem with black & white s-video output for NT1004 devices with saa7114 video decoder.  Thanks to Emmanuel for the patch and testing.
207  *     - Fixed up SECAM devices which could not properly output video.  Changes to usbmuxsel.  Thanks to Emmanuel for the patch and everyone with a SECAM device which help test.
208  *     - Removed some commented out code.  Clean up.
209  *     - Tried to fix up the annoying empty directories in the sourceforge.net cvs.   Fuck it up again.  8*(    
210  *
211  * November 15, 2004 - 0.9.8 Dwaine Garden
212  *     - Release new tar - 0.9.8 on sourceforge.net
213  *     - Added some new devices to usbvision.h WinTV USB Model 602 40201 Rev B282, Hauppague WinTV USB Model 602 40201 Rev B285
214  *     - Added better compatibility for 2.6.x kernels.
215  *     - Hardware full screen scaling in grabdisplay mode.
216  *     - Better support for sysfs.  More code to follow for both video device and radio device. Device information is located at /sys/class/video4linux/video0
217  *     - Added module_param so loaded module parameters are displayed in sysfs.  Driver parameters should show up in /sys/module/usbvision
218  *     - Adjusted the SAA7111 registers to match the 2.6.x kernel SAA7111 code. Thanks to the person which helped test.
219  *     - Changed to wait_event_interruptible. For all the people running Fedora 2.
220  *     - Added some screenshots of actual video captures on sourceforge.net.
221  *
222  * November 24, 2004 - 0.9.8.1cvs Dwaine Garden
223  *     - Added patch to check for palette and format in VIDIOCSPICT.  Helix Producer should work fine with the driver now.  Thanks Jason Simpson
224  *     - Two device description changes and two additions for the maintainer of usb.ids.
225  *
226  * December 2, 2004 - 0.9.8.1cvs Dwaine Garden
227  *     - Added patch for YUV420P and YUV422P video output.  Thanks to Alex Smith.
228  *     - Better support for mythtv.
229  *
230  * January 2, 2005 - 0.9.8.1cvs Dwaine Garden
231  *     - Setup that you can specify which device is used for video.  Default is auto detect next available device number eg.  /dev/videoX  
232  *     - Setup that you can specify which device is used for radio.  Default is auto detect next available device number eg.  /dev/radioX
233  *     - usb_unlink_urb() is deprecated for synchronous unlinks.  Using usb_kill_urb instead.
234  *     - usbvision_kvirt_to_pa is deprecated.  Removed.
235  *     - Changes are related to kernel changes for 2.6.10. (Fedora 4)
236  *
237  * February 2, 2005 - 0.9.8.1cvs Dwaine Garden
238  *     - Added a new device to usbvision.h Dazzle DVC 50.  Thanks to Luiz S.
239  *
240  * March 29, 2005 - 0.9.8.1cvs Dwaine Garden
241  *     - Fixed compile error with saa7113 under kernels 2.6.11+
242  *     - Added module parameter to help people with Black and White output with using s-video input.  Some cables and input device are wired differently.
243  *     - Removed the .id from the i2c usbvision template.  There was a change to the i2c with kernels 2.6.11+.
244  *
245  * April 9, 2005 - 0.9.8.1cvs Dwaine Garden
246  *     - Added in the 2.4 and 2.6 readme files the SwitchSVideoInput parameter information.  This will help people setup the right values for the parameter.
247  *       If your device experiences Black and White images with the S-Video Input.  Set this parameter to 1 when loading the module.
248  *     - Replaced the wrong 2.6 readme file.  I lost the right version.  Someone sent me the right version by e-mail.  Thanks.
249  *     - Released new module version on sourceforge.net.  So everyone can enjoy all the fixes and additional device support.
250  *
251  * April 20, 2005 - 0.9.8.2cvs Dwaine Garden
252  *     - Release lock in usbvision_v4l_read_done.  -Thanks to nplanel for the patch.
253  *     - Additional comments to the driver.
254  *     - Fixed some spelling mistakes.  8*)     
255  *
256  * April 23, 2005 - 0.9.8.2cvs Joerg Heckenbach
257  *     - Found bug in usbvision line counting. Now there should be no spurious lines in the image any longer.
258  *     - Swapped usbvision_register_video and usbvision_configure_video to fix problem with PowerOnAtOpen=0. 
259  *       Thanks to Erwan Velu
260  *
261  * April 26, 2005 - 0.9.8.2cvs Joerg Heckenbach
262  *     - Fixed problem with rmmod module and oppses. Replaced vfree(usbvision->overlay_base) with iounmap(usbvision->overlay_base).
263  *     - Added function usb_get_dev(dev) and ; To help with unloading the module multiple times without crashing. 
264  *       (Keep the reference count in kobjects correct)
265  *
266  * June 14, 2005 - 0.9.8.2cvs Dwaine
267  *     - Missed a change in saa7113.c for checking kernel version.  Added conditional if's.    
268  *
269  * June 15, 2005 - 0.9.8.2cvs Dwaine
270  *     - Added new device WinTV device VendorId 0573 and ProductId 4d29.    
271  *     - Hacked some support for newer NT1005 devices.  This devices only seem to have one configuration, not multiple configurations like the NT1004.
272  *
273  * June 29, 2005 - 0.9.8.2cvs Dwaine
274  *     - Added new device WinTV device VendorId 0573 and ProductId 4d37.   
275  *     - Because of the first empty entry in usbvision_table, modutils failed to create the necessary entries for modules.usbmap. 
276  *       This means hotplug won't work for usbvision.  Thanks to Gary Ng.  
277  *     - Sent an e-mail to the maintainer of usb.ids.  New devices identified need to be added.
278  *     - Fixed compile error with saa7113 under kernel 2.6.12.  
279  *
280  * July 6, 2005 - 0.9.8.2cvs Dwaine
281  *     - Patch submitted by Gary Ng for two additional procfs entries.  Device Input and Frequency setting.  
282  *
283  * July 12, 2005 - 0.9.8.2cvs Dwaine
284  *     - New tuner identified for some devices it's called TCL_MFPE05.  This tuner uses the same API as tuner 38 in tuner.c.
285  *     - Thanks to lynx31 for contacting Hauppage and asking them.
286  *     - I have no clue as to which devices use this new tuner, so people will have to contact me and tell me.  
287  *
288  * July 21, 2005 - 0.9.8.2cvs Dwaine
289  *     - Patched usbvision.c with missing ifdef kernversion statement so the module will compile with older kernels and v4l.
290  *     - Thanks to cipe007......
291  *
292  * May 19, 2006 - 0.9.8.3cvs Dwaine
293  *     - Patched usbvision.c and i2c-algo.c so they will compile with kernel 2.6.16
294  *     - Adjust device "Pinnacle Studio PCTV USB (PAL) FM" values in usbvision.h
295  *
296  * May 24, 2006 - 0.9.8.3cvs Dwaine
297  *     -Pinnacle Studio PCTV USB (NTSC) FM uses saa7111, not saa7113 like first thought.
298  *     -Updated usbvision.h
299  *
300  * Aug 15, 2006 - 0.9.8.3cvs Dwaine
301  *     -Added saa711x module into cvs, since the newer saa7115 module in newer kernels is v4l2.  The usbvision driver is only v4l.
302  *     -Updated makefile to put compiled modules into correct location.
303  *
304  * Aug 21, 2006 - 0.9.8.3cvs Dwaine
305  *     -Changed number of bytes for i2c write to 4 as per the NT100X spec sheet.  Thanks to Merlum for finding it.
306  *     -Remove the radio option for device Hauppauge WinTV USB device Model 40219 Rev E189.  This device does not have a FM radio.  Thanks to Shadwell.
307  *     -Added radio option for device Hauppauge WinTV USB device Model 40219 Rev E189 again.  Just got an e-mail indicating their device has one.  8*)
308  *   
309  * Aug 27, 2006 - 0.9.8.3cvs Dwaine
310  *     -Changed ifdef statement so the usbvision driver will compile with kernels at 2.6.12.
311  *     -Updated readme files for new updated tuner list for v4l devices.
312  *      
313  *
314  *
315  * TODO:
316  *     - use submit_urb for all setup packets
317  *     - Fix memory settings for nt1004. It is 4 times as big as the
318  *       nt1003 memory.
319  *     - Add audio on endpoint 3 for nt1004 chip.  Seems impossible, needs a codec interface.  Which one?
320  *     - Clean up the driver.
321  *     - optimization for performance.
322  *     - Add Videotext capability (VBI).  Working on it.....
323  *     - Check audio for other devices
324  *     - Add v4l2 interface
325  *
326  */
327
328 #include <linux/kernel.h>
329 #include <linux/sched.h>
330 #include <linux/list.h>
331 #include <linux/timer.h>
332 #include <linux/slab.h>
333 #include <linux/mm.h>
334 #include <linux/utsname.h>
335 #include <linux/highmem.h>
336 #include <linux/smp_lock.h>
337 #include <linux/videodev.h>
338 #include <linux/vmalloc.h>
339 #include <linux/module.h>
340 #include <linux/init.h>
341 #include <linux/spinlock.h>
342 #include <linux/usb.h>
343 #include <asm/io.h>
344 #include <linux/videodev2.h>
345 #include <linux/video_decoder.h>
346 #include <linux/i2c.h>
347 #include "usbvision-i2c.h"
348
349 #define USBVISION_DRIVER_VERSION_MAJOR 0
350 #define USBVISION_DRIVER_VERSION_MINOR 8
351 #define USBVISION_DRIVER_VERSION_PATCHLEVEL 0
352
353 #define USBVISION_VERSION __stringify(USBVISION_DRIVER_VERSION_MAJOR) "." __stringify(USBVISION_DRIVER_VERSION_MINOR) "." __stringify(USBVISION_DRIVER_VERSION_PATCHLEVEL) " " USBVISION_DRIVER_VERSION_COMMENT
354 #define USBVISION_DRIVER_VERSION KERNEL_VERSION(USBVISION_DRIVER_VERSION_MAJOR,USBVISION_DRIVER_VERSION_MINOR,USBVISION_DRIVER_VERSION_PATCHLEVEL)
355
356 #include <media/saa7115.h> 
357 #include <media/v4l2-common.h> 
358 #include <media/tuner.h>
359 #include <media/audiochip.h>
360
361         #include <linux/moduleparam.h>
362         #include <linux/workqueue.h>
363
364 #ifdef CONFIG_KMOD
365 #include <linux/kmod.h>
366 #endif
367
368 #include "usbvision.h"
369 #include "usbvision_ioctl.h"
370
371
372 #define DRIVER_VERSION "0.9.8.3cvs for Linux kernels 2.4.19-2.4.32 + 2.6.0-2.6.17, compiled at "__DATE__", "__TIME__
373 #define EMAIL "joerg@heckenbach-aw.de"
374 #define DRIVER_AUTHOR "Joerg Heckenbach <joerg@heckenbach-aw.de>, Dwaine Garden <DwaineGarden@rogers.com>"
375 #define DRIVER_DESC "USBVision USB Video Device Driver for Linux"
376 #define DRIVER_LICENSE "GPL"
377 #define DRIVER_ALIAS "USBVision"
378
379 #define ENABLE_HEXDUMP  0       /* Enable if you need it */
380
381
382 #define USBVISION_DEBUG         /* Turn on debug messages */
383
384 #ifdef USBVISION_DEBUG
385         #define PDEBUG(level, fmt, args...) \
386                 if (debug & (level)) info("[%s:%d] " fmt, __PRETTY_FUNCTION__, __LINE__ , ## args)
387 #else
388         #define PDEBUG(level, fmt, args...) do {} while(0)
389 #endif
390
391 #define DBG_IOCTL       1<<3
392 #define DBG_IO          1<<4
393 #define DBG_RIO         1<<5
394 #define DBG_HEADER      1<<7
395 #define DBG_PROBE       1<<8
396 #define DBG_IRQ         1<<9
397 #define DBG_ISOC        1<<10
398 #define DBG_PARSE       1<<11
399 #define DBG_SCRATCH     1<<12
400 #define DBG_FUNC        1<<13
401 #define DBG_I2C         1<<14
402
403 #define DEBUG(x...)                                                             /* General Debug */
404 #define IODEBUG(x...)                                                           /* Debug IO */
405 #define OVDEBUG(x...)                                                           /* Debug overlay */
406 #define MDEBUG(x...)                                                            /* Debug memory management */
407
408 //String operations
409 #define rmspace(str)    while(*str==' ') str++;
410 #define goto2next(str)  while(*str!=' ') str++; while(*str==' ') str++;
411
412
413 static int usbvision_nr = 0;                    // sequential number of usbvision device
414
415
416 static const int max_imgwidth = MAX_FRAME_WIDTH;
417 static const int max_imgheight = MAX_FRAME_HEIGHT;
418 static const int min_imgwidth = MIN_FRAME_WIDTH;
419 static const int min_imgheight = MIN_FRAME_HEIGHT;
420
421 #define FRAMERATE_MIN   0
422 #define FRAMERATE_MAX   31
423
424
425 enum {
426         ISOC_MODE_YUV422 = 0x03,
427         ISOC_MODE_YUV420 = 0x14,
428         ISOC_MODE_COMPRESS = 0x60,
429 };
430
431 /*
432  * The value of 'scratch_buf_size' affects quality of the picture
433  * in many ways. Shorter buffers may cause loss of data when client
434  * is too slow. Larger buffers are memory-consuming and take longer
435  * to work with. This setting can be adjusted, but the default value
436  * should be OK for most desktop users.
437  */
438 #define DEFAULT_SCRATCH_BUF_SIZE        (0x20000)               // 128kB memory scratch buffer
439 static const int scratch_buf_size = DEFAULT_SCRATCH_BUF_SIZE;
440
441 static int init_brightness = 128;       // Initalize the brightness of the video device
442 static int init_contrast = 192;         // Initalize the contrast of the video device
443 static int init_saturation = 128;       // Initalize the staturation mode of the video device
444 static int init_hue = 128;              // Initalize the Hue settings of the video device
445
446 // Function prototypes
447 static int usbvision_restart_isoc(struct usb_usbvision *usbvision);
448 static int usbvision_begin_streaming(struct usb_usbvision *usbvision);
449 static int usbvision_muxsel(struct usb_usbvision *usbvision, int channel, int norm);
450 static int usbvision_i2c_write(void *data, unsigned char addr, char *buf, short len);
451 static int usbvision_i2c_read(void *data, unsigned char addr, char *buf, short len);
452 static int usbvision_read_reg(struct usb_usbvision *usbvision, unsigned char reg);
453 static int usbvision_write_reg(struct usb_usbvision *usbvision, unsigned char reg, unsigned char value);
454 static int usbvision_request_intra (struct usb_usbvision *usbvision);
455 static int usbvision_unrequest_intra (struct usb_usbvision *usbvision);
456 static int usbvision_adjust_compression (struct usb_usbvision *usbvision);
457 static int usbvision_measure_bandwidth (struct usb_usbvision *usbvision);
458 static void usbvision_release(struct usb_usbvision *usbvision);
459 static int usbvision_set_input(struct usb_usbvision *usbvision); 
460 static int usbvision_set_output(struct usb_usbvision *usbvision, int width, int height); 
461 static void call_i2c_clients(struct usb_usbvision *usbvision, unsigned int cmd, void *arg); 
462
463
464 // Bit flags (options)
465 #define FLAGS_RETRY_VIDIOCSYNC          (1 << 0)
466 #define FLAGS_MONOCHROME                (1 << 1)
467 #define FLAGS_DISPLAY_HINTS             (1 << 2)
468 #define FLAGS_OSD_STATS                 (1 << 3)
469 #define FLAGS_FORCE_TESTPATTERN         (1 << 4)
470 #define FLAGS_SEPARATE_FRAMES           (1 << 5)
471 #define FLAGS_CLEAN_FRAMES              (1 << 6)
472
473 // Default initalization of device driver parameters
474 static int flags = 0;                                   // Set the default Overlay Display mode of the device driver
475 static int debug = 0;                                   // Set the default Debug Mode of the device driver
476 static int isocMode = ISOC_MODE_COMPRESS;               // Set the default format for ISOC endpoint
477 static int adjustCompression = 1;                       // Set the compression to be adaptive
478 static int dga = 1;                                     // Set the default Direct Graphic Access
479 static int PowerOnAtOpen = 1;                           // Set the default device to power on at startup
480 static int SwitchSVideoInput = 0;                       // To help people with Black and White output with using s-video input.  Some cables and input device are wired differently.
481 static int video_nr = -1;                               // Sequential Number of Video Device
482 static int radio_nr = -1;                               // Sequential Number of Radio Device
483 static int vbi_nr = -1;                                 // Sequential Number of VBI Device
484 static char *CustomDevice=NULL;                         // Set as nothing....
485
486 // Grab parameters for the device driver
487
488 #if defined(module_param)                               // Showing parameters under SYSFS
489 module_param(flags, int, 0444);
490 module_param(debug, int, 0444);
491 module_param(isocMode, int, 0444);
492 module_param(adjustCompression, int, 0444);
493 module_param(dga, int, 0444);
494 module_param(PowerOnAtOpen, int, 0444);
495 module_param(SwitchSVideoInput, int, 0444);
496 module_param(video_nr, int, 0444);
497 module_param(radio_nr, int, 0444);
498 module_param(vbi_nr, int, 0444);
499 module_param(CustomDevice, charp, 0444);
500 #else                                                   // Old Style
501 MODULE_PARM(flags, "i");                                // Grab the Overlay Display mode of the device driver
502 MODULE_PARM(debug, "i");                                // Grab the Debug Mode of the device driver
503 MODULE_PARM(isocMode, "i");                             // Grab the video format of the video device
504 MODULE_PARM(adjustCompression, "i");                    // Grab the compression to be adaptive
505 MODULE_PARM(dga, "i");                                  // Grab the Direct Graphic Access
506 MODULE_PARM(PowerOnAtOpen, "i");                        // Grab the device to power on at startup
507 MODULE_PARM(SwitchSVideoInput, "i");                    // To help people with Black and White output with using s-video input.  Some cables and input device are wired differently.
508 MODULE_PARM(video_nr, "i");                             // video_nr option allows to specify a certain /dev/videoX device (like /dev/video0 or /dev/video1 ...)                 
509 MODULE_PARM(radio_nr, "i");                             // radio_nr option allows to specify a certain /dev/radioX device (like /dev/radio0 or /dev/radio1 ...)
510 MODULE_PARM(vbi_nr, "i");                               // vbi_nr option allows to specify a certain /dev/vbiX device (like /dev/vbi0 or /dev/vbi1 ...)
511 MODULE_PARM(CustomDevice, "s");                         // .... CustomDevice
512 #endif
513
514 MODULE_PARM_DESC(flags, " Set the default Overlay Display mode of the device driver.  Default: 0 (Off)");
515 MODULE_PARM_DESC(debug, " Set the default Debug Mode of the device driver.  Default: 0 (Off)");
516 MODULE_PARM_DESC(isocMode, " Set the default format for ISOC endpoint.  Default: 0x60 (Compression On)");
517 MODULE_PARM_DESC(adjustCompression, " Set the ADPCM compression for the device.  Default: 1 (On)");
518 MODULE_PARM_DESC(dga, " Set the Direct Graphic Access for the device.  Default: 1 (On)");
519 MODULE_PARM_DESC(PowerOnAtOpen, " Set the default device to power on when device is opened.  Default: 1 (On)");
520 MODULE_PARM_DESC(SwitchSVideoInput, " Set the S-Video input.  Some cables and input device are wired differently. Default: 0 (Off)");
521 MODULE_PARM_DESC(video_nr, "Set video device number (/dev/videoX).  Default: -1 (autodetect)");
522 MODULE_PARM_DESC(radio_nr, "Set radio device number (/dev/radioX).  Default: -1 (autodetect)");
523 MODULE_PARM_DESC(vbi_nr, "Set vbi device number (/dev/vbiX).  Default: -1 (autodetect)");
524 MODULE_PARM_DESC(CustomDevice, " Define the fine tuning parameters for the device.  Default: null");
525
526
527 // Misc stuff
528 MODULE_AUTHOR(DRIVER_AUTHOR);
529 MODULE_DESCRIPTION(DRIVER_DESC);
530 MODULE_LICENSE(DRIVER_LICENSE);
531         MODULE_VERSION(DRIVER_VERSION);
532         MODULE_ALIAS(DRIVER_ALIAS); 
533
534 #ifdef MODULE
535 static unsigned int autoload = 1;
536 #else
537 static unsigned int autoload = 0;
538 #endif
539
540
541 /****************************************************************************************/
542 /* SYSFS Code - Copied from the stv680.c usb module.                                    */
543 /* Device information is located at /sys/class/video4linux/video0                       */
544 /* Device parameters information is located at /sys/module/usbvision                    */
545 /* Device USB Information is located at /sys/bus/usb/drivers/USBVision Video Grabber    */
546 /****************************************************************************************/
547
548
549 #define YES_NO(x) ((x) ? "Yes" : "No")
550
551 static inline struct usb_usbvision *cd_to_usbvision(struct class_device *cd)
552 {
553         struct video_device *vdev = to_video_device(cd);
554         return video_get_drvdata(vdev);
555 }
556
557 static ssize_t show_version(struct class_device *cd, char *buf)
558 {
559         return sprintf(buf, "%s\n", DRIVER_VERSION);
560
561 static CLASS_DEVICE_ATTR(version, S_IRUGO, show_version, NULL);
562
563 static ssize_t show_model(struct class_device *class_dev, char *buf)
564 {
565         struct video_device *vdev = to_video_device(class_dev); 
566         struct usb_usbvision *usbvision = video_get_drvdata(vdev);      
567         return sprintf(buf, "%s\n", usbvision_device_data[usbvision->DevModel].ModelString);
568
569 static CLASS_DEVICE_ATTR(model, S_IRUGO, show_model, NULL);
570
571 static ssize_t show_hue(struct class_device *class_dev, char *buf)
572 {
573         struct video_device *vdev = to_video_device(class_dev); 
574         struct usb_usbvision *usbvision = video_get_drvdata(vdev);      
575         return sprintf(buf, "%d\n", usbvision->hue >> 8);
576
577 static CLASS_DEVICE_ATTR(hue, S_IRUGO, show_hue, NULL);
578
579 static ssize_t show_contrast(struct class_device *class_dev, char *buf)
580 {
581         struct video_device *vdev = to_video_device(class_dev); 
582         struct usb_usbvision *usbvision = video_get_drvdata(vdev);      
583         return sprintf(buf, "%d\n", usbvision->contrast >> 8);
584
585 static CLASS_DEVICE_ATTR(contrast, S_IRUGO, show_contrast, NULL);
586
587 static ssize_t show_brightness(struct class_device *class_dev, char *buf)
588 {
589         struct video_device *vdev = to_video_device(class_dev); 
590         struct usb_usbvision *usbvision = video_get_drvdata(vdev);      
591         return sprintf(buf, "%d\n", usbvision->brightness >> 8);
592
593 static CLASS_DEVICE_ATTR(brightness, S_IRUGO, show_brightness, NULL);
594
595 static ssize_t show_saturation(struct class_device *class_dev, char *buf)
596 {
597         struct video_device *vdev = to_video_device(class_dev); 
598         struct usb_usbvision *usbvision = video_get_drvdata(vdev);      
599         return sprintf(buf, "%d\n", usbvision->saturation >> 8);
600
601 static CLASS_DEVICE_ATTR(saturation, S_IRUGO, show_saturation, NULL);
602
603 static ssize_t show_streaming(struct class_device *class_dev, char *buf)
604 {
605         struct video_device *vdev = to_video_device(class_dev); 
606         struct usb_usbvision *usbvision = video_get_drvdata(vdev);      
607         return sprintf(buf, "%s\n", YES_NO(usbvision->streaming));
608
609 static CLASS_DEVICE_ATTR(streaming, S_IRUGO, show_streaming, NULL);
610
611 static ssize_t show_overlay(struct class_device *class_dev, char *buf)
612 {
613         struct video_device *vdev = to_video_device(class_dev); 
614         struct usb_usbvision *usbvision = video_get_drvdata(vdev);      
615         return sprintf(buf, "%s\n", YES_NO(usbvision->overlay));
616
617 static CLASS_DEVICE_ATTR(overlay, S_IRUGO, show_overlay, NULL);
618
619 static ssize_t show_compression(struct class_device *class_dev, char *buf)
620 {
621         struct video_device *vdev = to_video_device(class_dev); 
622         struct usb_usbvision *usbvision = video_get_drvdata(vdev);      
623         return sprintf(buf, "%s\n", YES_NO(usbvision->isocMode==ISOC_MODE_COMPRESS));
624
625 static CLASS_DEVICE_ATTR(compression, S_IRUGO, show_compression, NULL);
626
627 static ssize_t show_device_bridge(struct class_device *class_dev, char *buf)
628 {
629         struct video_device *vdev = to_video_device(class_dev); 
630         struct usb_usbvision *usbvision = video_get_drvdata(vdev);      
631         return sprintf(buf, "%d\n", usbvision->bridgeType);
632
633 static CLASS_DEVICE_ATTR(bridge, S_IRUGO, show_device_bridge, NULL);
634
635 static void usbvision_create_sysfs(struct video_device *vdev)
636 {
637         if (vdev) {
638                 video_device_create_file(vdev, &class_device_attr_version);
639                 video_device_create_file(vdev, &class_device_attr_model);
640                 video_device_create_file(vdev, &class_device_attr_hue);
641                 video_device_create_file(vdev, &class_device_attr_contrast);
642                 video_device_create_file(vdev, &class_device_attr_brightness);
643                 video_device_create_file(vdev, &class_device_attr_saturation);
644                 video_device_create_file(vdev, &class_device_attr_streaming);
645                 video_device_create_file(vdev, &class_device_attr_overlay);
646                 video_device_create_file(vdev, &class_device_attr_compression);
647                 video_device_create_file(vdev, &class_device_attr_bridge);
648         }
649 }
650
651 static void usbvision_remove_sysfs(struct video_device *vdev)
652 {
653         if (vdev) {
654                 video_device_remove_file(vdev, &class_device_attr_version);
655                 video_device_remove_file(vdev, &class_device_attr_model);
656                 video_device_remove_file(vdev, &class_device_attr_hue);
657                 video_device_remove_file(vdev, &class_device_attr_contrast);
658                 video_device_remove_file(vdev, &class_device_attr_brightness);
659                 video_device_remove_file(vdev, &class_device_attr_saturation);
660                 video_device_remove_file(vdev, &class_device_attr_streaming);
661                 video_device_remove_file(vdev, &class_device_attr_overlay);
662                 video_device_remove_file(vdev, &class_device_attr_compression);
663                 video_device_remove_file(vdev, &class_device_attr_bridge);
664         }
665 }
666
667
668 /*******************************/
669 /* Memory management functions */
670 /*******************************/
671
672 /*
673  * Here we want the physical address of the memory.
674  * This is used when initializing the contents of the area.
675  */
676
677
678 void *usbvision_rvmalloc(unsigned long size)
679 {
680         void *mem;
681         unsigned long adr;
682
683         size = PAGE_ALIGN(size);
684         mem = vmalloc_32(size);
685         if (!mem)
686                 return NULL;
687
688         memset(mem, 0, size); /* Clear the ram out, no junk to the user */
689  adr = (unsigned long) mem;
690  while (size > 0) {
691   #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0)
692    mem_map_reserve(vmalloc_to_page((void *)adr));
693   #else
694    SetPageReserved(vmalloc_to_page((void *)adr));
695   #endif
696   adr += PAGE_SIZE;
697   size -= PAGE_SIZE;
698  }
699
700  return mem;
701 }
702
703 void usbvision_rvfree(void *mem, unsigned long size)
704 {
705  unsigned long adr;
706
707  if (!mem)
708   return;
709
710  adr = (unsigned long) mem;
711  while ((long) size > 0) {
712   #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0)
713    mem_map_unreserve(vmalloc_to_page((void *)adr));
714   #else
715    ClearPageReserved(vmalloc_to_page((void *)adr));
716   #endif
717   adr += PAGE_SIZE;
718   size -= PAGE_SIZE;
719  }
720  vfree(mem);
721 }
722
723
724
725
726
727
728 #if ENABLE_HEXDUMP
729 static void usbvision_hexdump(const unsigned char *data, int len)
730 {
731  char tmp[80];
732  int i, k;
733
734  for (i = k = 0; len > 0; i++, len--) {
735   if (i > 0 && (i % 16 == 0)) {
736    printk("%s\n", tmp);
737    k = 0;
738   }
739   k += sprintf(&tmp[k], "%02x ", data[i]);
740  }
741  if (k > 0)
742   printk("%s\n", tmp);
743 }
744 #endif
745
746
747 /* These procedures handle the scratch ring buffer */
748 int scratch_len(struct usb_usbvision *usbvision)    /*This returns the amount of data actually in the buffer */
749 {
750         int len = usbvision->scratch_write_ptr - usbvision->scratch_read_ptr;
751         if (len < 0) {
752                 len += scratch_buf_size;
753         }
754         PDEBUG(DBG_SCRATCH, "scratch_len() = %d\n", len);
755
756         return len;
757 }
758
759
760 /* This returns the free space left in the buffer */
761 int scratch_free(struct usb_usbvision *usbvision)
762 {
763         int free = usbvision->scratch_read_ptr - usbvision->scratch_write_ptr;
764         if (free <= 0) {
765                 free += scratch_buf_size;
766         }
767         if (free) {
768                 free -= 1;                                                      /* at least one byte in the buffer must */
769                                                                                 /* left blank, otherwise there is no chance to differ between full and empty */
770         }
771         PDEBUG(DBG_SCRATCH, "return %d\n", free);
772
773         return free;
774 }
775
776
777 void *debug_memcpy(void *dest, void *src, size_t len)
778 {
779         printk(KERN_DEBUG "memcpy(%p, %p, %d);\n", dest, src, len);
780         return memcpy(dest, src, len);
781 }
782
783
784 /* This puts data into the buffer */
785 int scratch_put(struct usb_usbvision *usbvision, unsigned char *data, int len)
786 {
787         int len_part;
788
789         if (usbvision->scratch_write_ptr + len < scratch_buf_size) {
790                 memcpy(usbvision->scratch + usbvision->scratch_write_ptr, data, len);
791                 usbvision->scratch_write_ptr += len;
792         }
793         else {
794                 len_part = scratch_buf_size - usbvision->scratch_write_ptr;
795                 memcpy(usbvision->scratch + usbvision->scratch_write_ptr, data, len_part);
796                 if (len == len_part) {
797                         usbvision->scratch_write_ptr = 0;                       /* just set write_ptr to zero */
798                 }
799                 else {
800                         memcpy(usbvision->scratch, data + len_part, len - len_part);
801                         usbvision->scratch_write_ptr = len - len_part;
802                 }
803         }
804
805         PDEBUG(DBG_SCRATCH, "len=%d, new write_ptr=%d\n", len, usbvision->scratch_write_ptr);
806
807         return len;
808 }
809
810 /* This marks the write_ptr as position of new frame header */
811 void scratch_mark_header(struct usb_usbvision *usbvision)
812 {
813         PDEBUG(DBG_SCRATCH, "header at write_ptr=%d\n", usbvision->scratch_headermarker_write_ptr);
814
815         usbvision->scratch_headermarker[usbvision->scratch_headermarker_write_ptr] =
816                                 usbvision->scratch_write_ptr;
817         usbvision->scratch_headermarker_write_ptr += 1;
818         usbvision->scratch_headermarker_write_ptr %= USBVISION_NUM_HEADERMARKER;
819 }
820
821 /* This gets data from the buffer at the given "ptr" position */
822 int scratch_get_extra(struct usb_usbvision *usbvision, unsigned char *data, int *ptr, int len)
823 {
824         int len_part;
825         if (*ptr + len < scratch_buf_size) {
826                 memcpy(data, usbvision->scratch + *ptr, len);
827                 *ptr += len;
828         }
829         else {
830                 len_part = scratch_buf_size - *ptr;
831                 memcpy(data, usbvision->scratch + *ptr, len_part);
832                 if (len == len_part) {
833                         *ptr = 0;                                                       /* just set the y_ptr to zero */
834                 }
835                 else {
836                         memcpy(data + len_part, usbvision->scratch, len - len_part);
837                         *ptr = len - len_part;
838                 }
839         }
840
841         PDEBUG(DBG_SCRATCH, "len=%d, new ptr=%d\n", len, *ptr);
842
843         return len;
844 }
845
846
847 /* This sets the scratch extra read pointer */
848 void scratch_set_extra_ptr(struct usb_usbvision *usbvision, int *ptr, int len)
849 {
850         *ptr = (usbvision->scratch_read_ptr + len)%scratch_buf_size;
851
852         PDEBUG(DBG_SCRATCH, "ptr=%d\n", *ptr);
853 }
854
855
856 /*This increments the scratch extra read pointer */
857 void scratch_inc_extra_ptr(int *ptr, int len)
858 {
859         *ptr = (*ptr + len) % scratch_buf_size;
860
861         PDEBUG(DBG_SCRATCH, "ptr=%d\n", *ptr);
862 }
863
864
865 /* This gets data from the buffer */
866 int scratch_get(struct usb_usbvision *usbvision, unsigned char *data, int len)
867 {
868         int len_part;
869         if (usbvision->scratch_read_ptr + len < scratch_buf_size) {
870                 memcpy(data, usbvision->scratch + usbvision->scratch_read_ptr, len);
871                 usbvision->scratch_read_ptr += len;
872         }
873         else {
874                 len_part = scratch_buf_size - usbvision->scratch_read_ptr;
875                 memcpy(data, usbvision->scratch + usbvision->scratch_read_ptr, len_part);
876                 if (len == len_part) {
877                         usbvision->scratch_read_ptr = 0;                                /* just set the read_ptr to zero */
878                 }
879                 else {
880                         memcpy(data + len_part, usbvision->scratch, len - len_part);
881                         usbvision->scratch_read_ptr = len - len_part;
882                 }
883         }
884
885         PDEBUG(DBG_SCRATCH, "len=%d, new read_ptr=%d\n", len, usbvision->scratch_read_ptr);
886
887         return len;
888 }
889
890
891 /* This sets read pointer to next header and returns it */
892 int scratch_get_header(struct usb_usbvision *usbvision,struct usbvision_frame_header *header)
893 {
894         int errCode = 0;
895
896         PDEBUG(DBG_SCRATCH, "from read_ptr=%d", usbvision->scratch_headermarker_read_ptr);
897
898         while (usbvision->scratch_headermarker_write_ptr -
899                 usbvision->scratch_headermarker_read_ptr != 0) {
900                 usbvision->scratch_read_ptr =
901                         usbvision->scratch_headermarker[usbvision->scratch_headermarker_read_ptr];
902                 usbvision->scratch_headermarker_read_ptr += 1;
903                 usbvision->scratch_headermarker_read_ptr %= USBVISION_NUM_HEADERMARKER;
904                 scratch_get(usbvision, (unsigned char *)header, USBVISION_HEADER_LENGTH);
905                 if ((header->magic_1 == USBVISION_MAGIC_1)
906                          && (header->magic_2 == USBVISION_MAGIC_2)
907                          && (header->headerLength == USBVISION_HEADER_LENGTH)) {
908                         errCode = USBVISION_HEADER_LENGTH;
909                         header->frameWidth  = header->frameWidthLo  + (header->frameWidthHi << 8);
910                         header->frameHeight = header->frameHeightLo + (header->frameHeightHi << 8);
911                         break;
912                 }
913         }
914
915         return errCode;
916 }
917
918
919 /*This removes len bytes of old data from the buffer */
920 void scratch_rm_old(struct usb_usbvision *usbvision, int len)
921 {
922
923         usbvision->scratch_read_ptr += len;
924         usbvision->scratch_read_ptr %= scratch_buf_size;
925         PDEBUG(DBG_SCRATCH, "read_ptr is now %d\n", usbvision->scratch_read_ptr);
926 }
927
928
929 /*This resets the buffer - kills all data in it too */
930 void scratch_reset(struct usb_usbvision *usbvision)
931 {
932         PDEBUG(DBG_SCRATCH, "\n");
933
934         usbvision->scratch_read_ptr = 0;
935         usbvision->scratch_write_ptr = 0;
936         usbvision->scratch_headermarker_read_ptr = 0;
937         usbvision->scratch_headermarker_write_ptr = 0;
938         usbvision->isocstate = IsocState_NoFrame;
939 }
940
941
942
943 /* Here comes the OVERLAY stuff */
944
945 /* Tell the interrupt handler what to to.  */
946 static
947 void usbvision_cap(struct usb_usbvision* usbvision, int on)
948 {
949         DEBUG(printk(KERN_DEBUG "usbvision_cap: overlay was %d, set it to %d\n", usbvision->overlay, on);)
950
951         if (on) {
952                 usbvision->overlay = 1;
953         }
954         else {
955                 usbvision->overlay = 0;
956         }
957 }
958
959
960
961
962 /* append a new clipregion to the vector of video_clips */
963 static
964 void usbvision_new_clip(struct v4l2_format* vf, struct v4l2_clip* vcp, int x, int y, int w, int h)
965 {
966         vcp[vf->fmt.win.clipcount].c.left = x;
967         vcp[vf->fmt.win.clipcount].c.top = y;
968         vcp[vf->fmt.win.clipcount].c.width = w;
969         vcp[vf->fmt.win.clipcount].c.height = h;
970         vf->fmt.win.clipcount++;
971 }
972
973
974 #define mark_pixel(x,y)  usbvision->clipmask[((x) + (y) * MAX_FRAME_WIDTH)/32] |= 0x00000001<<((x)%32)
975 #define clipped_pixel(index) usbvision->clipmask[(index)/32] & (0x00000001<<((index)%32))
976
977 static
978 void usbvision_built_overlay(struct usb_usbvision* usbvision, int count, struct v4l2_clip *vcp)
979 {
980         usbvision->overlay_win = usbvision->overlay_base +
981                 (signed int)usbvision->vid_win.fmt.win.w.left * usbvision->depth / 8 +
982                 (signed int)usbvision->vid_win.fmt.win.w.top * usbvision->vid_buf.fmt.bytesperline;
983
984                 IODEBUG(printk(KERN_DEBUG "built_overlay base=%p, win=%p, bpl=%d, clips=%d, size=%dx%d\n",
985                                         usbvision->overlay_base, usbvision->overlay_win,
986                                         usbvision->vid_buf.fmt.bytesperline, count,
987                                         usbvision->vid_win.fmt.win.w.width, usbvision->vid_win.fmt.win.w.height);)
988
989
990         /* Add here generation of clipping mask */
991 {
992         int x_start, x_end, y_start, y_end;
993         int clip_index, x, y;
994
995         memset(usbvision->clipmask, 0, USBVISION_CLIPMASK_SIZE);
996
997         OVDEBUG(printk(KERN_DEBUG "clips = %d\n", count);)
998
999         for(clip_index = 0; clip_index < count; clip_index++) {
1000                 OVDEBUG(printk(KERN_DEBUG "clip: %d,%d,%d,%d\n", vcp[clip_index].x,
1001                                 vcp[clip_index].y,
1002                                 vcp[clip_index].width,
1003                                 vcp[clip_index].height);)
1004
1005                 x_start = vcp[clip_index].c.left;
1006                 if(x_start >= (int)usbvision->vid_win.fmt.win.w.width) {
1007                         OVDEBUG(printk(KERN_DEBUG "x_start=%d\n", x_start);)
1008                         continue; //clipping window is right of overlay window
1009                 }
1010                 x_end   = x_start + vcp[clip_index].c.width;
1011                 if(x_end <= 0) {
1012                         OVDEBUG(printk(KERN_DEBUG "x_end=%d\n", x_end);)
1013                         continue; //clipping window is left of overlay window
1014                 }
1015
1016                 y_start = vcp[clip_index].c.top;
1017                 if(y_start >= (int)usbvision->vid_win.fmt.win.w.height) {
1018                         OVDEBUG(printk(KERN_DEBUG "y_start=%d\n", y_start);)
1019                         continue; //clipping window is below overlay window
1020                 }
1021                 y_end   = y_start + vcp[clip_index].c.height;
1022                 if(y_end <= 0) {
1023                         OVDEBUG(printk(KERN_DEBUG "y_end=%d\n", y_end);)
1024                         continue; //clipping window is above overlay window
1025                 }
1026
1027                 //clip the clipping window
1028                 if (x_start < 0) {
1029                         x_start = 0;
1030                 }
1031                 if (x_end > (int)usbvision->vid_win.fmt.win.w.width) {
1032                         x_end = (int)usbvision->vid_win.fmt.win.w.width;
1033                 }
1034                 if (y_start < 0) {
1035                         y_start = 0;
1036                 }
1037                 if (y_end > (int)usbvision->vid_win.fmt.win.w.height) {
1038                         y_end = (int)usbvision->vid_win.fmt.win.w.height;
1039                 }
1040
1041                 OVDEBUG(printk(KERN_DEBUG "clip_o: %d,%d,%d,%d\n", x_start,     y_start, x_end, y_end);)
1042
1043
1044
1045                 for(y = y_start; y < y_end; y++) {
1046                         for(x = x_start; x < x_end; x++) {
1047                                 mark_pixel(x,y);
1048                         }
1049                 }
1050         }
1051 }
1052
1053 }
1054
1055
1056
1057 void usbvision_osd_char(struct usb_usbvision *usbvision,
1058                         struct usbvision_frame *frame, int x, int y, int ch)
1059 {
1060         static const unsigned short digits[16] = {
1061                 0xF6DE,         /* 0 */
1062                 0x2492,         /* 1 */
1063                 0xE7CE,         /* 2 */
1064                 0xE79E,         /* 3 */
1065                 0xB792,         /* 4 */
1066                 0xF39E,         /* 5 */
1067                 0xF3DE,         /* 6 */
1068                 0xF492,         /* 7 */
1069                 0xF7DE,         /* 8 */
1070                 0xF79E,         /* 9 */
1071                 0x77DA,         /* a */
1072                 0xD75C,         /* b */
1073                 0xF24E,         /* c */
1074                 0xD6DC,         /* d */
1075                 0xF34E,         /* e */
1076                 0xF348          /* f */
1077         };
1078         unsigned short digit;
1079         int ix, iy;
1080
1081         if ((usbvision == NULL) || (frame == NULL))
1082                 return;
1083
1084         if (ch >= '0' && ch <= '9')
1085                 ch -= '0';
1086         else if (ch >= 'A' && ch <= 'F')
1087                 ch = 10 + (ch - 'A');
1088         else if (ch >= 'a' && ch <= 'f')
1089                 ch = 10 + (ch - 'a');
1090         else
1091                 return;
1092         digit = digits[ch];
1093
1094         for (iy = 0; iy < 5; iy++) {
1095                 for (ix = 0; ix < 3; ix++) {
1096                         if (digit & 0x8000) {
1097                         //      USBVISION_PUTPIXEL(frame, x + ix, y + iy,
1098                         //                      0xFF, 0xFF, 0xFF);
1099                         }
1100                         digit = digit << 1;
1101                 }
1102         }
1103 }
1104
1105
1106 void usbvision_osd_string(struct usb_usbvision *usbvision,
1107                           struct usbvision_frame *frame,
1108                           int x, int y, const char *str)
1109 {
1110         while (*str) {
1111                 usbvision_osd_char(usbvision, frame, x, y, *str);
1112                 str++;
1113                 x += 4;         /* 3 pixels character + 1 space */
1114         }
1115 }
1116
1117 /*
1118  * usb_usbvision_osd_stats()
1119  *
1120  * On screen display of important debugging information.
1121  *
1122  */
1123 void usbvision_osd_stats(struct usb_usbvision *usbvision,
1124                          struct usbvision_frame *frame)
1125 {
1126         const int y_diff = 8;
1127         char tmp[16];
1128         int x = 10;
1129         int y = 10;
1130
1131         sprintf(tmp, "%8x", usbvision->frame_num);
1132         usbvision_osd_string(usbvision, frame, x, y, tmp);
1133         y += y_diff;
1134
1135         sprintf(tmp, "%8lx", usbvision->isocUrbCount);
1136         usbvision_osd_string(usbvision, frame, x, y, tmp);
1137         y += y_diff;
1138
1139         sprintf(tmp, "%8lx", usbvision->urb_length);
1140         usbvision_osd_string(usbvision, frame, x, y, tmp);
1141         y += y_diff;
1142
1143         sprintf(tmp, "%8lx", usbvision->isocDataCount);
1144         usbvision_osd_string(usbvision, frame, x, y, tmp);
1145         y += y_diff;
1146
1147         sprintf(tmp, "%8lx", usbvision->header_count);
1148         usbvision_osd_string(usbvision, frame, x, y, tmp);
1149         y += y_diff;
1150
1151         sprintf(tmp, "%8lx", usbvision->scratch_ovf_count);
1152         usbvision_osd_string(usbvision, frame, x, y, tmp);
1153         y += y_diff;
1154
1155         sprintf(tmp, "%8lx", usbvision->isocSkipCount);
1156         usbvision_osd_string(usbvision, frame, x, y, tmp);
1157         y += y_diff;
1158
1159         sprintf(tmp, "%8lx", usbvision->isocErrCount);
1160         usbvision_osd_string(usbvision, frame, x, y, tmp);
1161         y += y_diff;
1162
1163         sprintf(tmp, "%8x", usbvision->saturation);
1164         usbvision_osd_string(usbvision, frame, x, y, tmp);
1165         y += y_diff;
1166
1167         sprintf(tmp, "%8x", usbvision->hue);
1168         usbvision_osd_string(usbvision, frame, x, y, tmp);
1169         y += y_diff;
1170
1171         sprintf(tmp, "%8x", usbvision->brightness >> 8);
1172         usbvision_osd_string(usbvision, frame, x, y, tmp);
1173         y += y_diff;
1174
1175         sprintf(tmp, "%8x", usbvision->contrast >> 12);
1176         usbvision_osd_string(usbvision, frame, x, y, tmp);
1177         y += y_diff;
1178
1179 }
1180
1181 /*
1182  * usbvision_testpattern()
1183  *
1184  * Procedure forms a test pattern (yellow grid on blue background).
1185  *
1186  * Parameters:
1187  * fullframe:   if TRUE then entire frame is filled, otherwise the procedure
1188  *              continues from the current scanline.
1189  * pmode        0: fill the frame with solid blue color (like on VCR or TV)
1190  *              1: Draw a colored grid
1191  *
1192  */
1193 void usbvision_testpattern(struct usb_usbvision *usbvision, int fullframe,
1194                         int pmode)
1195 {
1196         static const char proc[] = "usbvision_testpattern";
1197         struct usbvision_frame *frame;
1198         unsigned char *f;
1199         int num_cell = 0;
1200         int scan_length = 0;
1201         static int num_pass = 0;
1202
1203         if (usbvision == NULL) {
1204                 printk(KERN_ERR "%s: usbvision == NULL\n", proc);
1205                 return;
1206         }
1207         if ((usbvision->curFrameNum < 0)
1208             || (usbvision->curFrameNum >= USBVISION_NUMFRAMES)) {
1209                 printk(KERN_ERR "%s: usbvision->curFrameNum=%d.\n", proc,
1210                        usbvision->curFrameNum);
1211                 return;
1212         }
1213
1214         /* Grab the current frame */
1215         frame = &usbvision->frame[usbvision->curFrameNum];
1216
1217         /* Optionally start at the beginning */
1218         if (fullframe) {
1219                 frame->curline = 0;
1220                 frame->scanlength = 0;
1221         }
1222
1223         /* Form every scan line */
1224         for (; frame->curline < frame->frmheight; frame->curline++) {
1225                 int i;
1226
1227                 f = frame->data + (usbvision->curwidth * 3 * frame->curline);
1228                 for (i = 0; i < usbvision->curwidth; i++) {
1229                         unsigned char cb = 0x80;
1230                         unsigned char cg = 0;
1231                         unsigned char cr = 0;
1232
1233                         if (pmode == 1) {
1234                                 if (frame->curline % 32 == 0)
1235                                         cb = 0, cg = cr = 0xFF;
1236                                 else if (i % 32 == 0) {
1237                                         if (frame->curline % 32 == 1)
1238                                                 num_cell++;
1239                                         cb = 0, cg = cr = 0xFF;
1240                                 } else {
1241                                         cb =
1242                                             ((num_cell * 7) +
1243                                              num_pass) & 0xFF;
1244                                         cg =
1245                                             ((num_cell * 5) +
1246                                              num_pass * 2) & 0xFF;
1247                                         cr =
1248                                             ((num_cell * 3) +
1249                                              num_pass * 3) & 0xFF;
1250                                 }
1251                         } else {
1252                                 /* Just the blue screen */
1253                         }
1254
1255                         *f++ = cb;
1256                         *f++ = cg;
1257                         *f++ = cr;
1258                         scan_length += 3;
1259                 }
1260         }
1261
1262         frame->grabstate = FrameState_Done;
1263         frame->scanlength += scan_length;
1264         ++num_pass;
1265
1266         /* We do this unconditionally, regardless of FLAGS_OSD_STATS */
1267         usbvision_osd_stats(usbvision, frame);
1268 }
1269
1270 /*
1271  * Here comes the data parsing stuff that is run as interrupt
1272  */
1273
1274 /*
1275  * usbvision_find_header()
1276  *
1277  * Locate one of supported header markers in the scratch buffer.
1278  */
1279 static enum ParseState usbvision_find_header(struct usb_usbvision *usbvision)
1280 {
1281         struct usbvision_frame *frame;
1282         int foundHeader = 0;
1283
1284         if (usbvision->overlay) {
1285                 frame = &usbvision->overlay_frame;
1286         }
1287         else {
1288                 frame = &usbvision->frame[usbvision->curFrameNum];
1289         }
1290
1291         while (scratch_get_header(usbvision, &frame->isocHeader) == USBVISION_HEADER_LENGTH) {
1292                 // found header in scratch
1293                 PDEBUG(DBG_HEADER, "found header: 0x%02x%02x %d %d %d %d %#x 0x%02x %u %u",
1294                                 frame->isocHeader.magic_2,
1295                                 frame->isocHeader.magic_1,
1296                                 frame->isocHeader.headerLength,
1297                                 frame->isocHeader.frameNum,
1298                                 frame->isocHeader.framePhase,
1299                                 frame->isocHeader.frameLatency,
1300                                 frame->isocHeader.dataFormat,
1301                                 frame->isocHeader.formatParam,
1302                                 frame->isocHeader.frameWidth,
1303                                 frame->isocHeader.frameHeight);
1304
1305                 if (usbvision->requestIntra) {
1306                         if (frame->isocHeader.formatParam & 0x80) {
1307                                 foundHeader = 1;
1308                                 usbvision->lastIsocFrameNum = -1; // do not check for lost frames this time
1309                                 usbvision_unrequest_intra(usbvision);
1310                                 break;
1311                         }
1312                 }
1313                 else {
1314                         foundHeader = 1;
1315                         break;
1316                 }
1317         }
1318
1319         if (foundHeader) {
1320                 frame->frmwidth = frame->isocHeader.frameWidth * usbvision->stretch_width;
1321                 frame->frmheight = frame->isocHeader.frameHeight * usbvision->stretch_height;
1322                 frame->v4l2_linesize = (frame->frmwidth * frame->v4l2_format.depth)>> 3;
1323                 usbvision->curFrame = frame;
1324         }
1325         else { // no header found
1326                 PDEBUG(DBG_HEADER, "skipping scratch data, no header");
1327                 scratch_reset(usbvision);
1328                 return ParseState_EndParse;
1329         }
1330
1331         // found header
1332         if (frame->isocHeader.dataFormat==ISOC_MODE_COMPRESS) {
1333                 //check isocHeader.frameNum for lost frames
1334                 if (usbvision->lastIsocFrameNum >= 0) {
1335                         if (((usbvision->lastIsocFrameNum + 1) % 32) != frame->isocHeader.frameNum) {
1336                                 // unexpected frame drop: need to request new intra frame
1337                                 PDEBUG(DBG_HEADER, "Lost frame before %d on USB", frame->isocHeader.frameNum);
1338                                 usbvision_request_intra(usbvision);
1339                                 return ParseState_NextFrame;
1340                         }
1341                 }
1342                 usbvision->lastIsocFrameNum = frame->isocHeader.frameNum;
1343         }
1344         usbvision->header_count++;
1345         frame->scanstate = ScanState_Lines;
1346         frame->curline = 0;
1347
1348         if (flags & FLAGS_FORCE_TESTPATTERN) {
1349                 usbvision_testpattern(usbvision, 1, 1);
1350                 return ParseState_NextFrame;
1351         }
1352         return ParseState_Continue;
1353 }
1354
1355 static enum ParseState usbvision_parse_lines_422(struct usb_usbvision *usbvision,
1356                                            long *pcopylen)
1357 {
1358         volatile struct usbvision_frame *frame;
1359         unsigned char *f;
1360         int len;
1361         int i;
1362         unsigned char yuyv[4]={180, 128, 10, 128}; // YUV components
1363         unsigned char rv, gv, bv;       // RGB components
1364         int clipmask_index, bytes_per_pixel;
1365         int overlay = usbvision->overlay;
1366         int stretch_bytes, clipmask_add;
1367
1368         if (overlay) {
1369                 frame  = &usbvision->overlay_frame;
1370                 if (usbvision->overlay_base == NULL) {
1371                         //video_buffer is not set yet
1372                         return ParseState_NextFrame;
1373                 }
1374                 f = usbvision->overlay_win + frame->curline *
1375                         usbvision->vid_buf.fmt.bytesperline;
1376         }
1377         else {
1378                 frame  = &usbvision->frame[usbvision->curFrameNum];
1379                 f = frame->data + (frame->v4l2_linesize * frame->curline);
1380         }
1381
1382         /* Make sure there's enough data for the entire line */
1383         len = (frame->isocHeader.frameWidth * 2)+5;
1384         if (scratch_len(usbvision) < len) {
1385                 PDEBUG(DBG_PARSE, "out of data in line %d, need %u.\n", frame->curline, len);
1386                 return ParseState_Out;
1387         }
1388
1389         if ((frame->curline + 1) >= frame->frmheight) {
1390                 return ParseState_NextFrame;
1391         }
1392
1393         bytes_per_pixel = frame->v4l2_format.bytes_per_pixel;
1394         stretch_bytes = (usbvision->stretch_width - 1) * bytes_per_pixel;
1395         clipmask_index = frame->curline * MAX_FRAME_WIDTH;
1396         clipmask_add = usbvision->stretch_width;
1397
1398         for (i = 0; i < frame->frmwidth; i+=(2 * usbvision->stretch_width)) {
1399
1400                 scratch_get(usbvision, &yuyv[0], 4);
1401
1402                 if((overlay) && (clipped_pixel(clipmask_index))) {
1403                         f += bytes_per_pixel;
1404                 }
1405                 else if (frame->v4l2_format.format == V4L2_PIX_FMT_YUYV) {
1406                         *f++ = yuyv[0]; // Y
1407                         *f++ = yuyv[3]; // U
1408                 }
1409                 else {
1410
1411                         YUV_TO_RGB_BY_THE_BOOK(yuyv[0], yuyv[1], yuyv[3], rv, gv, bv);
1412                         switch (frame->v4l2_format.format) {
1413                                 case V4L2_PIX_FMT_RGB565:
1414                                         *f++ = (0x1F & (bv >> 3)) | (0xE0 & (gv << 3));
1415                                         *f++ = (0x07 & (gv >> 5)) | (0xF8 &  rv);
1416                                         break;
1417                                 case V4L2_PIX_FMT_RGB24:
1418                                         *f++ = bv;
1419                                         *f++ = gv;
1420                                         *f++ = rv;
1421                                         break;
1422                                 case V4L2_PIX_FMT_RGB32:
1423                                         *f++ = bv;
1424                                         *f++ = gv;
1425                                         *f++ = rv;
1426                                         f++;
1427                                         break;
1428                                 case V4L2_PIX_FMT_RGB555:
1429                                         *f++ = (0x1F & (bv >> 3)) | (0xE0 & (gv << 2));
1430                                         *f++ = (0x03 & (gv >> 6)) | (0x7C & (rv >> 1));
1431                                         break;
1432                         }
1433                 }
1434                 clipmask_index += clipmask_add;
1435                 f += stretch_bytes;
1436
1437                 if((overlay) && (clipped_pixel(clipmask_index))) {
1438                         f += bytes_per_pixel;
1439                 }
1440                 else if (frame->v4l2_format.format == V4L2_PIX_FMT_YUYV) {
1441                         *f++ = yuyv[2]; // Y
1442                         *f++ = yuyv[1]; // V
1443                 }
1444                 else {
1445
1446                         YUV_TO_RGB_BY_THE_BOOK(yuyv[2], yuyv[1], yuyv[3], rv, gv, bv);
1447                         switch (frame->v4l2_format.format) {
1448                                 case V4L2_PIX_FMT_RGB565:
1449                                         *f++ = (0x1F & (bv >> 3)) | (0xE0 & (gv << 3));
1450                                         *f++ = (0x07 & (gv >> 5)) | (0xF8 &  rv);
1451                                         break;
1452                                 case V4L2_PIX_FMT_RGB24:
1453                                         *f++ = bv;
1454                                         *f++ = gv;
1455                                         *f++ = rv;
1456                                         break;
1457                                 case V4L2_PIX_FMT_RGB32:
1458                                         *f++ = bv;
1459                                         *f++ = gv;
1460                                         *f++ = rv;
1461                                         f++;
1462                                         break;
1463                                 case V4L2_PIX_FMT_RGB555:
1464                                         *f++ = (0x1F & (bv >> 3)) | (0xE0 & (gv << 2));
1465                                         *f++ = (0x03 & (gv >> 6)) | (0x7C & (rv >> 1));
1466                                         break;
1467                         }
1468                 }
1469                 clipmask_index += clipmask_add;
1470                 f += stretch_bytes;
1471         }
1472
1473         frame->curline += usbvision->stretch_height;
1474         *pcopylen += frame->v4l2_linesize * usbvision->stretch_height;
1475
1476         if (frame->curline >= frame->frmheight) {
1477                 return ParseState_NextFrame;
1478         }
1479         else {
1480                 return ParseState_Continue;
1481         }
1482 }
1483
1484
1485 static int usbvision_decompress(struct usb_usbvision *usbvision,unsigned char *Compressed,
1486                                                                 unsigned char *Decompressed, int *StartPos,
1487                                                                 int *BlockTypeStartPos, int Len)
1488 {
1489         int RestPixel, Idx, MaxPos, Pos, ExtraPos, BlockLen, BlockTypePos, BlockTypeLen;
1490         unsigned char BlockByte, BlockCode, BlockType, BlockTypeByte, Integrator;
1491
1492         Integrator = 0;
1493         Pos = *StartPos;
1494         BlockTypePos = *BlockTypeStartPos;
1495         MaxPos = 396; //Pos + Len;
1496         ExtraPos = Pos;
1497         BlockLen = 0;
1498         BlockByte = 0;
1499         BlockCode = 0;
1500         BlockType = 0;
1501         BlockTypeByte = 0;
1502         BlockTypeLen = 0;
1503         RestPixel = Len;
1504
1505         for (Idx = 0; Idx < Len; Idx++) {
1506
1507                 if (BlockLen == 0) {
1508                         if (BlockTypeLen==0) {
1509                                 BlockTypeByte = Compressed[BlockTypePos];
1510                                 BlockTypePos++;
1511                                 BlockTypeLen = 4;
1512                         }
1513                         BlockType = (BlockTypeByte & 0xC0) >> 6;
1514
1515                         //statistic:
1516                         usbvision->ComprBlockTypes[BlockType]++;
1517
1518                         Pos = ExtraPos;
1519                         if (BlockType == 0) {
1520                                 if(RestPixel >= 24) {
1521                                         Idx += 23;
1522                                         RestPixel -= 24;
1523                                         Integrator = Decompressed[Idx];
1524                                 } else {
1525                                         Idx += RestPixel - 1;
1526                                         RestPixel = 0;
1527                                 }
1528                         } else {
1529                                 BlockCode = Compressed[Pos];
1530                                 Pos++;
1531                                 if (RestPixel >= 24) {
1532                                         BlockLen  = 24;
1533                                 } else {
1534                                         BlockLen = RestPixel;
1535                                 }
1536                                 RestPixel -= BlockLen;
1537                                 ExtraPos = Pos + (BlockLen / 4);
1538                         }
1539                         BlockTypeByte <<= 2;
1540                         BlockTypeLen -= 1;
1541                 }
1542                 if (BlockLen > 0) {
1543                         if ((BlockLen%4) == 0) {
1544                                 BlockByte = Compressed[Pos];
1545                                 Pos++;
1546                         }
1547                         if (BlockType == 1) { //inter Block
1548                                 Integrator = Decompressed[Idx];
1549                         }
1550                         switch (BlockByte & 0xC0) {
1551                                 case 0x03<<6:
1552                                         Integrator += Compressed[ExtraPos];
1553                                         ExtraPos++;
1554                                         break;
1555                                 case 0x02<<6:
1556                                         Integrator += BlockCode;
1557                                         break;
1558                                 case 0x00:
1559                                         Integrator -= BlockCode;
1560                                         break;
1561                         }
1562                         Decompressed[Idx] = Integrator;
1563                         BlockByte <<= 2;
1564                         BlockLen -= 1;
1565                 }
1566         }
1567         *StartPos = ExtraPos;
1568         *BlockTypeStartPos = BlockTypePos;
1569         return Idx;
1570 }
1571
1572
1573 /*
1574  * usbvision_parse_compress()
1575  *
1576  * Parse compressed frame from the scratch buffer, put
1577  * decoded RGB value into the current frame buffer and add the written
1578  * number of bytes (RGB) to the *pcopylen.
1579  *
1580  */
1581 static enum ParseState usbvision_parse_compress(struct usb_usbvision *usbvision,
1582                                            long *pcopylen)
1583 {
1584 #define USBVISION_STRIP_MAGIC           0x5A
1585 #define USBVISION_STRIP_LEN_MAX         400
1586 #define USBVISION_STRIP_HEADER_LEN      3
1587
1588         struct usbvision_frame *frame;
1589         unsigned char *f,*u = NULL ,*v = NULL;
1590         unsigned char StripData[USBVISION_STRIP_LEN_MAX];
1591         unsigned char StripHeader[USBVISION_STRIP_HEADER_LEN];
1592         int Idx, IdxEnd, StripLen, StripPtr, StartBlockPos, BlockPos, BlockTypePos;
1593         int clipmask_index, bytes_per_pixel, rc;
1594         int overlay = usbvision->overlay;
1595         int imageSize;
1596         unsigned char rv, gv, bv;
1597         static unsigned char *Y, *U, *V;
1598
1599         if (overlay) {
1600                 frame  = &usbvision->overlay_frame;
1601                 imageSize = frame->frmwidth * frame->frmheight; 
1602                 if (usbvision->overlay_base == NULL) {
1603                         //video_buffer is not set yet
1604                         return ParseState_NextFrame;
1605                 }
1606                 f = usbvision->overlay_win + frame->curline *
1607                         usbvision->vid_buf.fmt.bytesperline;
1608         }
1609         else {
1610                 frame  = &usbvision->frame[usbvision->curFrameNum];
1611                 imageSize = frame->frmwidth * frame->frmheight;                                 
1612                 if ( (frame->v4l2_format.format == V4L2_PIX_FMT_YUV422P) ||
1613                      (frame->v4l2_format.format == V4L2_PIX_FMT_YVU420) )
1614                 {       // this is a planar format 
1615                                                                        //... v4l2_linesize not used here.
1616                         f = frame->data + (frame->width * frame->curline);
1617                 } else 
1618                         f = frame->data + (frame->v4l2_linesize * frame->curline);
1619                 
1620                 if (frame->v4l2_format.format == V4L2_PIX_FMT_YUYV){ //initialise u and v pointers
1621                                                                  // get base of u and b planes add halfoffset
1622                         
1623                         u = frame->data 
1624                                 + imageSize     
1625                                 + (frame->frmwidth >>1) * frame->curline ;
1626                         v = u + (imageSize >>1 );
1627                         
1628                 } else if (frame->v4l2_format.format == V4L2_PIX_FMT_YVU420){
1629                         
1630                         v = frame->data + imageSize + ((frame->curline* (frame->width))>>2) ; 
1631                         u = v + (imageSize >>2) ;
1632                 }
1633         }
1634
1635         if (frame->curline == 0) {
1636                 usbvision_adjust_compression(usbvision);
1637         }
1638
1639         if (scratch_len(usbvision) < USBVISION_STRIP_HEADER_LEN) {
1640                 return ParseState_Out;
1641         }
1642
1643         //get strip header without changing the scratch_read_ptr
1644         scratch_set_extra_ptr(usbvision, &StripPtr, 0);
1645         scratch_get_extra(usbvision, &StripHeader[0], &StripPtr,
1646                                 USBVISION_STRIP_HEADER_LEN);
1647
1648         if (StripHeader[0] != USBVISION_STRIP_MAGIC) {
1649                 // wrong strip magic
1650                 usbvision->stripMagicErrors++;
1651                 return ParseState_NextFrame;
1652         }
1653
1654         if (frame->curline != (int)StripHeader[2]) {
1655                 //line number missmatch error
1656                 usbvision->stripLineNumberErrors++;
1657         }
1658
1659         StripLen = 2 * (unsigned int)StripHeader[1];
1660         if (StripLen > USBVISION_STRIP_LEN_MAX) {
1661                 // strip overrun
1662                 // I think this never happens
1663                 usbvision_request_intra(usbvision);
1664         }
1665
1666         if (scratch_len(usbvision) < StripLen) {
1667                 //there is not enough data for the strip
1668                 return ParseState_Out;
1669         }
1670
1671         if (usbvision->IntraFrameBuffer) {
1672                 Y = usbvision->IntraFrameBuffer + frame->frmwidth * frame->curline;
1673                 U = usbvision->IntraFrameBuffer + imageSize + (frame->frmwidth / 2) * (frame->curline / 2);
1674                 V = usbvision->IntraFrameBuffer + imageSize / 4 * 5 + (frame->frmwidth / 2) * (frame->curline / 2);
1675         }
1676         else {
1677                 return ParseState_NextFrame;
1678         }
1679
1680         bytes_per_pixel = frame->v4l2_format.bytes_per_pixel;
1681         clipmask_index = frame->curline * MAX_FRAME_WIDTH;
1682
1683         scratch_get(usbvision, StripData, StripLen);
1684
1685         IdxEnd = frame->frmwidth;
1686         BlockTypePos = USBVISION_STRIP_HEADER_LEN;
1687         StartBlockPos = BlockTypePos + (IdxEnd - 1) / 96 + (IdxEnd / 2 - 1) / 96 + 2;
1688         BlockPos = StartBlockPos;
1689
1690         usbvision->BlockPos = BlockPos;
1691
1692         if ((rc = usbvision_decompress(usbvision, StripData, Y, &BlockPos, &BlockTypePos, IdxEnd)) != IdxEnd) {
1693                 //return ParseState_Continue;
1694         }
1695         if (StripLen > usbvision->maxStripLen) {
1696                 usbvision->maxStripLen = StripLen;
1697         }
1698
1699         if (frame->curline%2) {
1700                 if ((rc = usbvision_decompress(usbvision, StripData, V, &BlockPos, &BlockTypePos, IdxEnd/2)) != IdxEnd/2) {
1701                 //return ParseState_Continue;
1702                 }
1703         }
1704         else {
1705                 if ((rc = usbvision_decompress(usbvision, StripData, U, &BlockPos, &BlockTypePos, IdxEnd/2)) != IdxEnd/2) {
1706                         //return ParseState_Continue;
1707                 }
1708         }
1709
1710         if (BlockPos > usbvision->comprBlockPos) {
1711                 usbvision->comprBlockPos = BlockPos;
1712         }
1713         if (BlockPos > StripLen) {
1714                 usbvision->stripLenErrors++;
1715         }
1716         
1717         for (Idx = 0; Idx < IdxEnd; Idx++) {
1718                 if((overlay) && (clipped_pixel(clipmask_index))) {
1719                         f += bytes_per_pixel;
1720                 }
1721                 else if(frame->v4l2_format.format == V4L2_PIX_FMT_YUYV) {
1722                         *f++ = Y[Idx];
1723                         *f++ = Idx & 0x01 ? U[Idx/2] : V[Idx/2];
1724                 }
1725                 else if(frame->v4l2_format.format == V4L2_PIX_FMT_YUV422P) {
1726                         *f++ = Y[Idx];
1727                         if ( Idx & 0x01)
1728                                 *u++ = U[Idx>>1] ;
1729                         else
1730                                 *v++ = V[Idx>>1];
1731                 }
1732                 else if (frame->v4l2_format.format == V4L2_PIX_FMT_YVU420) {
1733                         *f++ = Y [Idx];
1734                         if ( !((  Idx & 0x01  ) | (  frame->curline & 0x01  )) ){ 
1735                             
1736 /*                               only need do this for 1 in 4 pixels */
1737 /*                               intraframe buffer is YUV420 format */
1738
1739                                 *u++ = U[Idx >>1];
1740                                 *v++ = V[Idx >>1];
1741                         }
1742                         
1743                 }
1744                 else {
1745                         YUV_TO_RGB_BY_THE_BOOK(Y[Idx], U[Idx/2], V[Idx/2], rv, gv, bv);
1746                         switch (frame->v4l2_format.format) {
1747                                 case V4L2_PIX_FMT_GREY:
1748                                         *f++ = Y[Idx];
1749                                         break;
1750                                 case V4L2_PIX_FMT_RGB555:
1751                                         *f++ = (0x1F & (bv >> 3)) | (0xE0 & (gv << 2));
1752                                         *f++ = (0x03 & (gv >> 6)) | (0x7C & (rv >> 1));
1753                                         break;
1754                                 case V4L2_PIX_FMT_RGB565:
1755                                         *f++ = (0x1F & (bv >> 3)) | (0xE0 & (gv << 3));
1756                                         *f++ = (0x07 & (gv >> 5)) | (0xF8 &  rv);
1757                                         break;
1758                                 case V4L2_PIX_FMT_RGB24:
1759                                         *f++ = bv;
1760                                         *f++ = gv;
1761                                         *f++ = rv;
1762                                         break;
1763                                 case V4L2_PIX_FMT_RGB32:
1764                                         *f++ = bv;
1765                                         *f++ = gv;
1766                                         *f++ = rv;
1767                                         f++;
1768                                         break;
1769                         }
1770                 }
1771                 clipmask_index++;
1772         }
1773         /* Deal with non-integer no. of bytes for YUV420P */ 
1774         if (frame->v4l2_format.format != V4L2_PIX_FMT_YVU420 ) 
1775                 *pcopylen += frame->v4l2_linesize; 
1776         else 
1777                 *pcopylen += frame->curline & 0x01 ? frame->v4l2_linesize : frame->v4l2_linesize << 1;  
1778   
1779         frame->curline += 1;
1780
1781         if (frame->curline >= frame->frmheight) {
1782                 return ParseState_NextFrame;
1783         }
1784         else {
1785                 return ParseState_Continue;
1786         }
1787
1788 }
1789
1790
1791 /*
1792  * usbvision_parse_lines_420()
1793  *
1794  * Parse two lines from the scratch buffer, put
1795  * decoded RGB value into the current frame buffer and add the written
1796  * number of bytes (RGB) to the *pcopylen.
1797  *
1798  */
1799 static enum ParseState usbvision_parse_lines_420(struct usb_usbvision *usbvision,
1800                                            long *pcopylen)
1801 {
1802         struct usbvision_frame *frame;
1803         unsigned char *f_even = NULL, *f_odd = NULL;
1804         unsigned int pixel_per_line, block;
1805         int pixel, block_split;
1806         int y_ptr, u_ptr, v_ptr, y_odd_offset;
1807         const int   y_block_size = 128;
1808         const int  uv_block_size = 64;
1809         const int sub_block_size = 32;
1810         const int y_step[] = { 0, 0, 0, 2 },  y_step_size = 4;
1811         const int uv_step[]= { 0, 0, 0, 4 }, uv_step_size = 4;
1812         unsigned char y[2], u, v;       /* YUV components */
1813         int y_, u_, v_, vb, uvg, ur;
1814         int r_, g_, b_;                 /* RGB components */
1815         unsigned char g;
1816         int clipmask_even_index, clipmask_odd_index, bytes_per_pixel;
1817         int clipmask_add, stretch_bytes;
1818         int overlay = usbvision->overlay;
1819
1820         if (overlay) {
1821                 frame  = &usbvision->overlay_frame;
1822                 if (usbvision->overlay_base == NULL) {
1823                         //video_buffer is not set yet
1824                         return ParseState_NextFrame;
1825                 }
1826                 f_even = usbvision->overlay_win + frame->curline *
1827                          usbvision->vid_buf.fmt.bytesperline;
1828                 f_odd  = f_even + usbvision->vid_buf.fmt.bytesperline * usbvision->stretch_height;
1829         }
1830         else {
1831                 frame  = &usbvision->frame[usbvision->curFrameNum];
1832                 f_even = frame->data + (frame->v4l2_linesize * frame->curline);
1833                 f_odd  = f_even + frame->v4l2_linesize * usbvision->stretch_height;
1834         }
1835
1836         /* Make sure there's enough data for the entire line */
1837         /* In this mode usbvision transfer 3 bytes for every 2 pixels */
1838         /* I need two lines to decode the color */
1839         bytes_per_pixel = frame->v4l2_format.bytes_per_pixel;
1840         stretch_bytes = (usbvision->stretch_width - 1) * bytes_per_pixel;
1841         clipmask_even_index = frame->curline * MAX_FRAME_WIDTH;
1842         clipmask_odd_index  = clipmask_even_index + MAX_FRAME_WIDTH;
1843         clipmask_add = usbvision->stretch_width;
1844         pixel_per_line = frame->isocHeader.frameWidth;
1845
1846         if (scratch_len(usbvision) < (int)pixel_per_line * 3) {
1847                 //printk(KERN_DEBUG "out of data, need %d\n", len);
1848                 return ParseState_Out;
1849         }
1850
1851         if ((frame->curline + 1) >= frame->frmheight) {
1852                 return ParseState_NextFrame;
1853         }
1854
1855         block_split = (pixel_per_line%y_block_size) ? 1 : 0;    //are some blocks splitted into different lines?
1856
1857         y_odd_offset = (pixel_per_line / y_block_size) * (y_block_size + uv_block_size)
1858                         + block_split * uv_block_size;
1859
1860         scratch_set_extra_ptr(usbvision, &y_ptr, y_odd_offset);
1861         scratch_set_extra_ptr(usbvision, &u_ptr, y_block_size);
1862         scratch_set_extra_ptr(usbvision, &v_ptr, y_odd_offset
1863                         + (4 - block_split) * sub_block_size);
1864
1865         for (block = 0; block < (pixel_per_line / sub_block_size);
1866              block++) {
1867
1868
1869                 for (pixel = 0; pixel < sub_block_size; pixel +=2) {
1870                         scratch_get(usbvision, &y[0], 2);
1871                         scratch_get_extra(usbvision, &u, &u_ptr, 1);
1872                         scratch_get_extra(usbvision, &v, &v_ptr, 1);
1873
1874                         //I don't use the YUV_TO_RGB macro for better performance
1875                         v_ = v - 128;
1876                         u_ = u - 128;
1877                         vb =              132252 * v_;
1878                         uvg= -53281 * u_ - 25625 * v_;
1879                         ur = 104595 * u_;
1880
1881                         if((overlay) && (clipped_pixel(clipmask_even_index))) {
1882                                 f_even += bytes_per_pixel;
1883                         }
1884                         else if(frame->v4l2_format.format == V4L2_PIX_FMT_YUYV) {
1885                                 *f_even++ = y[0];
1886                                 *f_even++ = v;
1887                         }
1888                         else {
1889                                 y_ = 76284 * (y[0] - 16);
1890
1891                                 b_ = (y_ + vb) >> 16;
1892                                 g_ = (y_ + uvg)>> 16;
1893                                 r_ = (y_ + ur) >> 16;
1894
1895                                 switch (frame->v4l2_format.format) {
1896                                         case V4L2_PIX_FMT_RGB565:
1897                                                 g = LIMIT_RGB(g_);
1898                                                 *f_even++ = (0x1F & (LIMIT_RGB(b_) >> 3)) | (0xE0 & (g << 3));
1899                                                 *f_even++ = (0x07 & (          g   >> 5)) | (0xF8 & LIMIT_RGB(r_));
1900                                                 break;
1901                                         case V4L2_PIX_FMT_RGB24:
1902                                                 *f_even++ = LIMIT_RGB(b_);
1903                                                 *f_even++ = LIMIT_RGB(g_);
1904                                                 *f_even++ = LIMIT_RGB(r_);
1905                                                 break;
1906                                         case V4L2_PIX_FMT_RGB32:
1907                                                 *f_even++ = LIMIT_RGB(b_);
1908                                                 *f_even++ = LIMIT_RGB(g_);
1909                                                 *f_even++ = LIMIT_RGB(r_);
1910                                                 f_even++;
1911                                                 break;
1912                                         case V4L2_PIX_FMT_RGB555:
1913                                                 g = LIMIT_RGB(g_);
1914                                                 *f_even++ = (0x1F & (LIMIT_RGB(b_) >> 3)) | (0xE0 & (g << 2));
1915                                                 *f_even++ = (0x03 & (          g   >> 6)) |
1916                                                             (0x7C & (LIMIT_RGB(r_) >> 1));
1917                                                 break;
1918                                 }
1919                         }
1920                         clipmask_even_index += clipmask_add;
1921                         f_even += stretch_bytes;
1922
1923                         if((overlay) && (clipped_pixel(clipmask_even_index))) {
1924                                 f_even += bytes_per_pixel;
1925                         }
1926                         else if(frame->v4l2_format.format == V4L2_PIX_FMT_YUYV) {
1927                                 *f_even++ = y[1];
1928                                 *f_even++ = u;
1929                         }
1930                         else {
1931                                 y_ = 76284 * (y[1] - 16);
1932
1933                                 b_ = (y_ + vb) >> 16;
1934                                 g_ = (y_ + uvg)>> 16;
1935                                 r_ = (y_ + ur) >> 16;
1936
1937                                 switch (frame->v4l2_format.format) {
1938                                         case V4L2_PIX_FMT_RGB565:
1939                                                 g = LIMIT_RGB(g_);
1940                                                 *f_even++ = (0x1F & (LIMIT_RGB(b_) >> 3)) | (0xE0 & (g << 3));
1941                                                 *f_even++ = (0x07 & (          g   >> 5)) | (0xF8 & LIMIT_RGB(r_));
1942                                                 break;
1943                                         case V4L2_PIX_FMT_RGB24:
1944                                                 *f_even++ = LIMIT_RGB(b_);
1945                                                 *f_even++ = LIMIT_RGB(g_);
1946                                                 *f_even++ = LIMIT_RGB(r_);
1947                                                 break;
1948                                         case V4L2_PIX_FMT_RGB32:
1949                                                 *f_even++ = LIMIT_RGB(b_);
1950                                                 *f_even++ = LIMIT_RGB(g_);
1951                                                 *f_even++ = LIMIT_RGB(r_);
1952                                                 f_even++;
1953                                                 break;
1954                                         case V4L2_PIX_FMT_RGB555:
1955                                                 g = LIMIT_RGB(g_);
1956                                                 *f_even++ = (0x1F & (LIMIT_RGB(b_) >> 3)) | (0xE0 & (g << 2));
1957                                                 *f_even++ = (0x03 & (          g   >> 6)) |
1958                                                             (0x7C & (LIMIT_RGB(r_) >> 1));
1959                                                 break;
1960                                 }
1961                         }
1962                         clipmask_even_index += clipmask_add;
1963                         f_even += stretch_bytes;
1964
1965                         scratch_get_extra(usbvision, &y[0], &y_ptr, 2);
1966
1967                         if ((overlay) && (clipped_pixel(clipmask_odd_index))) {
1968                                 f_odd += bytes_per_pixel;
1969                         }
1970                         else if(frame->v4l2_format.format == V4L2_PIX_FMT_YUYV) {
1971                                 *f_odd++ = y[0];
1972                                 *f_odd++ = v;
1973                         }
1974                         else {
1975                                 y_ = 76284 * (y[0] - 16);
1976
1977                                 b_ = (y_ + vb) >> 16;
1978                                 g_ = (y_ + uvg)>> 16;
1979                                 r_ = (y_ + ur) >> 16;
1980
1981                                 switch (frame->v4l2_format.format) {
1982                                         case V4L2_PIX_FMT_RGB565:
1983                                                 g = LIMIT_RGB(g_);
1984                                                 *f_odd++ = (0x1F & (LIMIT_RGB(b_) >> 3)) | (0xE0 & (g << 3));
1985                                                 *f_odd++ = (0x07 & (          g   >> 5)) | (0xF8 & LIMIT_RGB(r_));
1986                                                 break;
1987                                         case V4L2_PIX_FMT_RGB24:
1988                                                 *f_odd++ = LIMIT_RGB(b_);
1989                                                 *f_odd++ = LIMIT_RGB(g_);
1990                                                 *f_odd++ = LIMIT_RGB(r_);
1991                                                 break;
1992                                         case V4L2_PIX_FMT_RGB32:
1993                                                 *f_odd++ = LIMIT_RGB(b_);
1994                                                 *f_odd++ = LIMIT_RGB(g_);
1995                                                 *f_odd++ = LIMIT_RGB(r_);
1996                                                 f_odd++;
1997                                                 break;
1998                                         case V4L2_PIX_FMT_RGB555:
1999                                                 g = LIMIT_RGB(g_);
2000                                                 *f_odd++ = (0x1F & (LIMIT_RGB(b_) >> 3)) | (0xE0 & (g << 2));
2001                                                 *f_odd++ = (0x03 & (          g   >> 6)) |
2002                                                            (0x7C & (LIMIT_RGB(r_) >> 1));
2003                                                 break;
2004                                 }
2005                         }
2006                         clipmask_odd_index += clipmask_add;
2007                         f_odd += stretch_bytes;
2008
2009                         if((overlay) && (clipped_pixel(clipmask_odd_index))) {
2010                                 f_odd += bytes_per_pixel;
2011                         }
2012                         else if(frame->v4l2_format.format == V4L2_PIX_FMT_YUYV) {
2013                                 *f_odd++ = y[1];
2014                                 *f_odd++ = u;
2015                         }
2016                         else {
2017                                 y_ = 76284 * (y[1] - 16);
2018
2019                                 b_ = (y_ + vb) >> 16;
2020                                 g_ = (y_ + uvg)>> 16;
2021                                 r_ = (y_ + ur) >> 16;
2022
2023                                 switch (frame->v4l2_format.format) {
2024                                         case V4L2_PIX_FMT_RGB565:
2025                                                 g = LIMIT_RGB(g_);
2026                                                 *f_odd++ = (0x1F & (LIMIT_RGB(b_) >> 3)) | (0xE0 & (g << 3));
2027                                                 *f_odd++ = (0x07 & (          g   >> 5)) | (0xF8 & LIMIT_RGB(r_));
2028                                                 break;
2029                                         case V4L2_PIX_FMT_RGB24:
2030                                                 *f_odd++ = LIMIT_RGB(b_);
2031                                                 *f_odd++ = LIMIT_RGB(g_);
2032                                                 *f_odd++ = LIMIT_RGB(r_);
2033                                                 break;
2034                                         case V4L2_PIX_FMT_RGB32:
2035                                                 *f_odd++ = LIMIT_RGB(b_);
2036                                                 *f_odd++ = LIMIT_RGB(g_);
2037                                                 *f_odd++ = LIMIT_RGB(r_);
2038                                                 f_odd++;
2039                                                 break;
2040                                         case V4L2_PIX_FMT_RGB555:
2041                                                 g = LIMIT_RGB(g_);
2042                                                 *f_odd++ = (0x1F & (LIMIT_RGB(b_) >> 3)) | (0xE0 & (g << 2));
2043                                                 *f_odd++ = (0x03 & (          g   >> 6)) |
2044                                                            (0x7C & (LIMIT_RGB(r_) >> 1));
2045                                                 break;
2046                                 }
2047                         }
2048                         clipmask_odd_index += clipmask_add;
2049                         f_odd += stretch_bytes;
2050                 }
2051
2052                 scratch_rm_old(usbvision,y_step[block % y_step_size] * sub_block_size);
2053                 scratch_inc_extra_ptr(&y_ptr, y_step[(block + 2 * block_split) % y_step_size]
2054                                 * sub_block_size);
2055                 scratch_inc_extra_ptr(&u_ptr, uv_step[block % uv_step_size]
2056                                 * sub_block_size);
2057                 scratch_inc_extra_ptr(&v_ptr, uv_step[(block + 2 * block_split) % uv_step_size]
2058                                 * sub_block_size);
2059         }
2060
2061         scratch_rm_old(usbvision, pixel_per_line * 3 / 2
2062                         + block_split * sub_block_size);
2063
2064         frame->curline += 2 * usbvision->stretch_height;
2065         *pcopylen += frame->v4l2_linesize * 2 * usbvision->stretch_height;
2066
2067         if (frame->curline >= frame->frmheight)
2068                 return ParseState_NextFrame;
2069         else
2070                 return ParseState_Continue;
2071 }
2072
2073 /*
2074  * usbvision_parse_data()
2075  *
2076  * Generic routine to parse the scratch buffer. It employs either
2077  * usbvision_find_header() or usbvision_parse_lines() to do most
2078  * of work.
2079  *
2080  */
2081 static void usbvision_parse_data(struct usb_usbvision *usbvision)
2082 {
2083         struct usbvision_frame *frame;
2084         enum ParseState newstate;
2085         long copylen = 0;
2086
2087         if (usbvision->overlay) {
2088                 frame = &usbvision->overlay_frame;
2089         }
2090         else {
2091                 frame = &usbvision->frame[usbvision->curFrameNum];
2092         }
2093
2094         PDEBUG(DBG_PARSE, "parsing len=%d\n", scratch_len(usbvision));
2095
2096
2097         while (1) {
2098
2099                 newstate = ParseState_Out;
2100                 if (scratch_len(usbvision)) {
2101                         if (frame->scanstate == ScanState_Scanning) {
2102                                 newstate = usbvision_find_header(usbvision);
2103                         }
2104                         else if (frame->scanstate == ScanState_Lines) {
2105                                 if (usbvision->isocMode == ISOC_MODE_YUV420) {
2106                                         newstate = usbvision_parse_lines_420(usbvision, &copylen);
2107                                 }
2108                                 else if (usbvision->isocMode == ISOC_MODE_YUV422) {
2109                                         newstate = usbvision_parse_lines_422(usbvision, &copylen);
2110                                 }
2111                                 else if (usbvision->isocMode == ISOC_MODE_COMPRESS) {
2112                                         newstate = usbvision_parse_compress(usbvision, &copylen);
2113                                 }
2114
2115                         }
2116                 }
2117                 if (newstate == ParseState_Continue) {
2118                         continue;
2119                 }
2120                 else if ((newstate == ParseState_NextFrame) || (newstate == ParseState_Out)) {
2121                         break;
2122                 }
2123                 else {
2124                         return; /* ParseState_EndParse */
2125                 }
2126         }
2127
2128         if (newstate == ParseState_NextFrame) {
2129                 frame->grabstate = FrameState_Done;
2130                 do_gettimeofday(&(frame->timestamp));
2131                 frame->sequence = usbvision->frame_num;
2132                 if (usbvision->overlay) {
2133                         frame->grabstate = FrameState_Grabbing;
2134                         frame->scanstate = ScanState_Scanning;
2135                         frame->scanlength = 0;
2136                         copylen = 0;
2137                 }
2138                 else {
2139                         usbvision->curFrameNum = -1;
2140                 }
2141                 usbvision->frame_num++;
2142
2143                 /* Optionally display statistics on the screen */
2144                 if (flags & FLAGS_OSD_STATS)
2145                         usbvision_osd_stats(usbvision, frame);
2146
2147                 /* This will cause the process to request another frame. */
2148                 if (waitqueue_active(&frame->wq)) {
2149                         wake_up_interruptible(&frame->wq);
2150                 }
2151         }
2152
2153         /* Update the frame's uncompressed length. */
2154         frame->scanlength += copylen;
2155 }
2156
2157
2158 /*
2159  * Make all of the blocks of data contiguous
2160  */
2161 static int usbvision_compress_isochronous(struct usb_usbvision *usbvision,
2162                                        struct urb *urb)
2163 {
2164         unsigned char *packet_data;
2165         int i, totlen = 0;
2166
2167         for (i = 0; i < urb->number_of_packets; i++) {
2168                 int packet_len = urb->iso_frame_desc[i].actual_length;
2169                 int packet_stat = urb->iso_frame_desc[i].status;
2170
2171                 packet_data = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
2172
2173                 /* Detect and ignore errored packets */
2174                 if (packet_stat) {      // packet_stat != 0 ?????????????
2175                         PDEBUG(DBG_ISOC, "data error: [%d] len=%d, status=%X", i, packet_len, packet_stat);
2176                         usbvision->isocErrCount++;
2177                         continue;
2178                 }
2179
2180                 /* Detect and ignore empty packets */
2181                 if (packet_len < 0) {
2182                         PDEBUG(DBG_ISOC, "error packet [%d]", i);
2183                         usbvision->isocSkipCount++;
2184                         continue;
2185                 }
2186                 else if (packet_len == 0) {     /* Frame end ????? */
2187                         PDEBUG(DBG_ISOC, "null packet [%d]", i);
2188                         usbvision->isocstate=IsocState_NoFrame;
2189                         usbvision->isocSkipCount++;
2190                         continue;
2191                 }
2192                 else if (packet_len > usbvision->isocPacketSize) {
2193                         PDEBUG(DBG_ISOC, "packet[%d] > isocPacketSize", i);
2194                         usbvision->isocSkipCount++;
2195                         continue;
2196                 }
2197
2198                 PDEBUG(DBG_ISOC, "packet ok [%d] len=%d", i, packet_len);
2199
2200                 if (usbvision->isocstate==IsocState_NoFrame) { //new frame begins
2201                         usbvision->isocstate=IsocState_InFrame;
2202                         scratch_mark_header(usbvision);
2203                         usbvision_measure_bandwidth(usbvision);
2204                         PDEBUG(DBG_ISOC, "packet with header");
2205                 }
2206
2207                 /*
2208                  * If usbvision continues to feed us with data but there is no
2209                  * consumption (if, for example, V4L client fell asleep) we
2210                  * may overflow the buffer. We have to move old data over to
2211                  * free room for new data. This is bad for old data. If we
2212                  * just drop new data then it's bad for new data... choose
2213                  * your favorite evil here.
2214                  */
2215                 if (scratch_free(usbvision) < packet_len) {
2216
2217                         usbvision->scratch_ovf_count++;
2218                         PDEBUG(DBG_ISOC, "scratch buf overflow! scr_len: %d, n: %d",
2219                                scratch_len(usbvision), packet_len);
2220                         scratch_rm_old(usbvision, packet_len - scratch_free(usbvision));
2221                 }
2222
2223                 /* Now we know that there is enough room in scratch buffer */
2224                 scratch_put(usbvision, packet_data, packet_len);
2225                 totlen += packet_len;
2226                 usbvision->isocDataCount += packet_len;
2227                 usbvision->isocPacketCount++;
2228         }
2229 #if ENABLE_HEXDUMP
2230         if (totlen > 0) {
2231                 static int foo = 0;
2232                 if (foo < 1) {
2233                         printk(KERN_DEBUG "+%d.\n", usbvision->scratchlen);
2234                         usbvision_hexdump(data0, (totlen > 64) ? 64 : totlen);
2235                         ++foo;
2236                 }
2237         }
2238 #endif
2239  return totlen;
2240 }
2241
2242 static void usbvision_isocIrq(struct urb *urb, struct pt_regs *regs)
2243 {
2244  int errCode = 0;
2245  int len;
2246  struct usb_usbvision *usbvision = urb->context;
2247  int i;
2248  unsigned long startTime = jiffies;
2249
2250  /* We don't want to do anything if we are about to be removed! */
2251  if (!USBVISION_IS_OPERATIONAL(usbvision))
2252   return;
2253
2254  if (!usbvision->streaming) {
2255   PDEBUG(DBG_IRQ, "oops, not streaming, but interrupt");
2256   return;
2257  }
2258
2259  /* Copy the data received into our scratch buffer */
2260  len = usbvision_compress_isochronous(usbvision, urb);
2261
2262  usbvision->isocUrbCount++;
2263  usbvision->urb_length = len;
2264
2265  for (i = 0; i < USBVISION_URB_FRAMES; i++) {
2266   urb->iso_frame_desc[i].status = 0;
2267   urb->iso_frame_desc[i].actual_length = 0;
2268  }
2269         urb->status = 0;
2270         urb->dev = usbvision->dev;
2271         errCode = usb_submit_urb (urb, GFP_ATOMIC);
2272
2273 /* Disable this warning.  By design of the driver. */
2274 //      if(errCode) {
2275 //              err("%s: usb_submit_urb failed: error %d", __FUNCTION__, errCode);
2276 //      }
2277
2278         /* If we collected enough data let's parse! */
2279         if (scratch_len(usbvision) > USBVISION_HEADER_LENGTH) { /* 12 == header_length */
2280                 /*If we don't have a frame we're current working on, complain */
2281                 if ((usbvision->curFrameNum >= 0) || (usbvision->overlay))
2282                         usbvision_parse_data(usbvision);
2283                 else {
2284                         PDEBUG(DBG_IRQ, "received data, but no one needs it");
2285                         scratch_reset(usbvision);
2286                 }
2287         }
2288         usbvision->timeInIrq += jiffies - startTime;
2289         return;
2290 }
2291
2292 /*************************************/
2293 /* Low level usbvision access functions */
2294 /*************************************/
2295
2296 /*
2297  * usbvision_read_reg()
2298  *
2299  * return  < 0 -> Error
2300  *        >= 0 -> Data
2301  */
2302
2303 static int usbvision_read_reg(struct usb_usbvision *usbvision, unsigned char reg)
2304 {
2305         int errCode = 0;
2306         unsigned char buffer[1];
2307
2308         if (!USBVISION_IS_OPERATIONAL(usbvision))
2309                 return -1;
2310
2311         errCode = usb_control_msg(usbvision->dev, usb_rcvctrlpipe(usbvision->dev, 1),
2312                                 USBVISION_OP_CODE,
2313                                 USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_ENDPOINT,
2314                                 0, (__u16) reg, buffer, 1, HZ);
2315
2316         if (errCode < 0) {
2317                 err("%s: failed: error %d", __FUNCTION__, errCode);
2318                 return errCode;
2319         }
2320         return buffer[0];
2321 }
2322
2323 /*
2324  * usbvision_write_reg()
2325  *
2326  * return 1 -> Reg written
2327  *        0 -> usbvision is not yet ready
2328  *       -1 -> Something went wrong
2329  */
2330
2331 static int usbvision_write_reg(struct usb_usbvision *usbvision, unsigned char reg,
2332                             unsigned char value)
2333 {
2334         int errCode = 0;
2335
2336         if (!USBVISION_IS_OPERATIONAL(usbvision))
2337                 return 0;
2338
2339         errCode = usb_control_msg(usbvision->dev, usb_sndctrlpipe(usbvision->dev, 1),
2340                                 USBVISION_OP_CODE,
2341                                 USB_DIR_OUT | USB_TYPE_VENDOR |
2342                                 USB_RECIP_ENDPOINT, 0, (__u16) reg, &value, 1, HZ);
2343
2344         if (errCode < 0) {
2345                 err("%s: failed: error %d", __FUNCTION__, errCode);
2346         }
2347         return errCode;
2348 }
2349
2350
2351 static void usbvision_ctrlUrb_complete(struct urb *urb, struct pt_regs *regs)
2352 {
2353         struct usb_usbvision *usbvision = (struct usb_usbvision *)urb->context;
2354
2355         PDEBUG(DBG_IRQ, "");
2356         usbvision->ctrlUrbBusy = 0;
2357         if (waitqueue_active(&usbvision->ctrlUrb_wq)) {
2358                 wake_up_interruptible(&usbvision->ctrlUrb_wq);
2359         }
2360 }
2361
2362
2363 static int usbvision_write_reg_irq(struct usb_usbvision *usbvision,int address,
2364                                                                         unsigned char *data, int len)
2365 {
2366         int errCode = 0;
2367
2368         PDEBUG(DBG_IRQ, "");
2369         if (len > 8) {
2370                 return -EFAULT;
2371         }
2372 //      down(&usbvision->ctrlUrbLock);
2373         if (usbvision->ctrlUrbBusy) {
2374 //              up(&usbvision->ctrlUrbLock);
2375                 return -EBUSY;
2376         }
2377         usbvision->ctrlUrbBusy = 1;
2378 //      up(&usbvision->ctrlUrbLock);
2379
2380         usbvision->ctrlUrbSetup.bRequestType = USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_ENDPOINT;
2381         usbvision->ctrlUrbSetup.bRequest     = USBVISION_OP_CODE;
2382         usbvision->ctrlUrbSetup.wValue       = 0;
2383         usbvision->ctrlUrbSetup.wIndex       = cpu_to_le16(address);
2384         usbvision->ctrlUrbSetup.wLength      = cpu_to_le16(len);
2385         usb_fill_control_urb (usbvision->ctrlUrb, usbvision->dev,
2386                                                         usb_sndctrlpipe(usbvision->dev, 1),
2387                                                         (unsigned char *)&usbvision->ctrlUrbSetup,
2388                                                         (void *)usbvision->ctrlUrbBuffer, len,
2389                                                         usbvision_ctrlUrb_complete,
2390                                                         (void *)usbvision);
2391
2392         memcpy(usbvision->ctrlUrbBuffer, data, len);
2393
2394         errCode = usb_submit_urb(usbvision->ctrlUrb, GFP_ATOMIC);
2395         if (errCode < 0) {
2396                 // error in usb_submit_urb()
2397                 usbvision->ctrlUrbBusy = 0;
2398         }
2399         PDEBUG(DBG_IRQ, "submit %d byte: error %d", len, errCode);
2400         return errCode;
2401 }
2402
2403
2404
2405
2406 static int usbvision_init_compression(struct usb_usbvision *usbvision)
2407 {
2408         int errCode = 0;
2409
2410         usbvision->lastIsocFrameNum = -1;
2411         usbvision->isocDataCount = 0;
2412         usbvision->isocPacketCount = 0;
2413         usbvision->isocSkipCount = 0;
2414         usbvision->comprLevel = 50;
2415         usbvision->lastComprLevel = -1;
2416         usbvision->isocUrbCount = 0;
2417         usbvision->requestIntra = 1;
2418         usbvision->isocMeasureBandwidthCount = 0;
2419
2420         return errCode;
2421 }
2422
2423 /* this function measures the used bandwidth since last call
2424  * return:    0 : no error
2425  * sets usedBandwidth to 1-100 : 1-100% of full bandwidth resp. to isocPacketSize
2426  */
2427 static int usbvision_measure_bandwidth (struct usb_usbvision *usbvision)
2428 {
2429         int errCode = 0;
2430
2431         if (usbvision->isocMeasureBandwidthCount < 2) { // this gives an average bandwidth of 3 frames
2432                 usbvision->isocMeasureBandwidthCount++;
2433                 return errCode;
2434         }
2435         if ((usbvision->isocPacketSize > 0) && (usbvision->isocPacketCount > 0)) {
2436                 usbvision->usedBandwidth = usbvision->isocDataCount /
2437                                         (usbvision->isocPacketCount + usbvision->isocSkipCount) *
2438                                         100 / usbvision->isocPacketSize;
2439         }
2440         usbvision->isocMeasureBandwidthCount = 0;
2441         usbvision->isocDataCount = 0;
2442         usbvision->isocPacketCount = 0;
2443         usbvision->isocSkipCount = 0;
2444         return errCode;
2445 }
2446
2447 static int usbvision_adjust_compression (struct usb_usbvision *usbvision)
2448 {
2449         int errCode = 0;
2450         unsigned char buffer[6];
2451
2452         PDEBUG(DBG_IRQ, "");
2453         if ((adjustCompression) && (usbvision->usedBandwidth > 0)) {
2454                 usbvision->comprLevel += (usbvision->usedBandwidth - 90) / 2;
2455                 RESTRICT_TO_RANGE(usbvision->comprLevel, 0, 100);
2456                 if (usbvision->comprLevel != usbvision->lastComprLevel) {
2457                         int distorsion;
2458                         if (usbvision->bridgeType == BRIDGE_NT1004 || usbvision->bridgeType == BRIDGE_NT1005) {
2459                                 buffer[0] = (unsigned char)(4 + 16 * usbvision->comprLevel / 100);      // PCM Threshold 1
2460                                 buffer[1] = (unsigned char)(4 + 8 * usbvision->comprLevel / 100);       // PCM Threshold 2
2461                                 distorsion = 7 + 248 * usbvision->comprLevel / 100;
2462                                 buffer[2] = (unsigned char)(distorsion & 0xFF);                         // Average distorsion Threshold (inter)
2463                                 buffer[3] = (unsigned char)(distorsion & 0xFF);                         // Average distorsion Threshold (intra)
2464                                 distorsion = 1 + 42 * usbvision->comprLevel / 100;
2465                                 buffer[4] = (unsigned char)(distorsion & 0xFF);                         // Maximum distorsion Threshold (inter)
2466                                 buffer[5] = (unsigned char)(distorsion & 0xFF);                         // Maximum distorsion Threshold (intra)
2467                         }
2468                         else { //BRIDGE_NT1003
2469                                 buffer[0] = (unsigned char)(4 + 16 * usbvision->comprLevel / 100);      // PCM threshold 1
2470                                 buffer[1] = (unsigned char)(4 + 8 * usbvision->comprLevel / 100);       // PCM threshold 2
2471                                 distorsion = 2 + 253 * usbvision->comprLevel / 100;
2472                                 buffer[2] = (unsigned char)(distorsion & 0xFF);                         // distorsion threshold bit0-7
2473                                 buffer[3] = 0;  //(unsigned char)((distorsion >> 8) & 0x0F);            // distorsion threshold bit 8-11
2474                                 distorsion = 0 + 43 * usbvision->comprLevel / 100;
2475                                 buffer[4] = (unsigned char)(distorsion & 0xFF);                         // maximum distorsion bit0-7
2476                                 buffer[5] = 0; //(unsigned char)((distorsion >> 8) & 0x01);             // maximum distorsion bit 8
2477                         }
2478                         errCode = usbvision_write_reg_irq(usbvision, USBVISION_PCM_THR1, buffer, 6);
2479                         if (errCode == 0){
2480                                 PDEBUG(DBG_IRQ, "new compr params %#02x %#02x %#02x %#02x %#02x %#02x", buffer[0],
2481                                                                 buffer[1], buffer[2], buffer[3], buffer[4], buffer[5]);
2482                                 usbvision->lastComprLevel = usbvision->comprLevel;
2483                         }
2484                 }
2485         }
2486         return errCode;
2487 }
2488
2489 static int usbvision_request_intra (struct usb_usbvision *usbvision)
2490 {
2491         int errCode = 0;
2492         unsigned char buffer[1];
2493
2494         PDEBUG(DBG_IRQ, "");
2495         usbvision->requestIntra = 1;
2496         buffer[0] = 1;
2497         usbvision_write_reg_irq(usbvision, USBVISION_FORCE_INTRA, buffer, 1);
2498         return errCode;
2499 }
2500
2501 static int usbvision_unrequest_intra (struct usb_usbvision *usbvision)
2502 {
2503         int errCode = 0;
2504         unsigned char buffer[1];
2505
2506         PDEBUG(DBG_IRQ, "");
2507         usbvision->requestIntra = 0;
2508         buffer[0] = 0;
2509         usbvision_write_reg_irq(usbvision, USBVISION_FORCE_INTRA, buffer, 1);
2510         return errCode;
2511 }
2512
2513 /* ----------------------------------------------------------------------- */
2514 /* I2C functions                                                           */
2515 /* ----------------------------------------------------------------------- */
2516
2517 static void call_i2c_clients(struct usb_usbvision *usbvision, unsigned int cmd,
2518                              void *arg)
2519 {
2520
2521         int i;
2522
2523         for (i = 0; i < USBVISION_I2C_CLIENTS_MAX; i++) {
2524                 if (NULL == usbvision->i2c_clients[i])
2525                         continue;
2526                 if (NULL == usbvision->i2c_clients[i]->driver->command)
2527                         continue;
2528                 usbvision->i2c_clients[i]->driver->command(usbvision->i2c_clients[i], cmd, arg);
2529         }
2530 }
2531
2532 static int attach_inform(struct i2c_client *client)
2533 {
2534         struct usb_usbvision *usbvision;
2535         struct tuner_setup tun_addr;
2536         int i;
2537         v4l2_std_id stdId;
2538
2539         #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0)
2540                 usbvision = (struct usb_usbvision *)client->adapter->data;
2541         #else
2542                 usbvision = (struct usb_usbvision *)i2c_get_adapdata(client->adapter);
2543         #endif
2544
2545         for (i = 0; i < USBVISION_I2C_CLIENTS_MAX; i++) {
2546                 if (usbvision->i2c_clients[i] == NULL ||
2547                     usbvision->i2c_clients[i]->driver->id ==
2548                     client->driver->id) {
2549                         usbvision->i2c_clients[i] = client;
2550                         break;
2551                 }
2552         }
2553         if ((usbvision->have_tuner) && (usbvision->tuner_type != -1)) {
2554                 tun_addr.mode_mask = T_ANALOG_TV;
2555                 tun_addr.type = usbvision->tuner_type;
2556                 tun_addr.addr = ADDR_UNSET;
2557                 client->driver->command(client,TUNER_SET_TYPE_ADDR, &tun_addr);
2558                 
2559                 call_i2c_clients(usbvision, VIDIOC_S_INPUT, &usbvision->input.index);
2560         }
2561         // FIXME : need to add a call VIDIOC_S_CTRL for each control
2562 /*      call_i2c_clients(usbvision, DECODER_SET_PICTURE, &usbvision->vpic); */
2563         stdId = usbvision->input.std;
2564         call_i2c_clients(usbvision, VIDIOC_S_STD, &stdId);
2565
2566         PDEBUG(DBG_I2C, "usbvision[%d] attaches %s", usbvision->nr, client->name);
2567
2568         return 0;
2569 }
2570
2571 static int detach_inform(struct i2c_client *client)
2572 {
2573         struct usb_usbvision *usbvision;
2574         int i;
2575
2576         #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0)
2577                 usbvision = (struct usb_usbvision *)client->adapter->data;
2578         #else
2579                 usbvision = (struct usb_usbvision *)i2c_get_adapdata(client->adapter);
2580         #endif
2581
2582         PDEBUG(DBG_I2C, "usbvision[%d] detaches %s", usbvision->nr, client->name);
2583         for (i = 0; i < USBVISION_I2C_CLIENTS_MAX; i++) {
2584                 if (NULL != usbvision->i2c_clients[i] &&
2585                     usbvision->i2c_clients[i]->driver->id ==
2586                     client->driver->id) {
2587                         usbvision->i2c_clients[i] = NULL;
2588                         break;
2589                 }
2590         }
2591         return 0;
2592 }
2593
2594 static int
2595 usbvision_i2c_read_max4(struct usb_usbvision *usbvision, unsigned char addr,
2596                      char *buf, short len)
2597 {
2598         int rc, retries;
2599
2600         for (retries = 5;;) {
2601                 rc = usbvision_write_reg(usbvision, USBVISION_SER_ADRS, addr);
2602                 if (rc < 0)
2603                         return rc;
2604
2605                 /* Initiate byte read cycle                    */
2606                 /* USBVISION_SER_CONT <- d0-d2 n. of bytes to r/w */
2607                 /*                    d3 0=Wr 1=Rd             */
2608                 rc = usbvision_write_reg(usbvision, USBVISION_SER_CONT,
2609                                       (len & 0x07) | 0x18);
2610                 if (rc < 0)
2611                         return rc;
2612
2613                 /* Test for Busy and ACK */
2614                 do {
2615                         /* USBVISION_SER_CONT -> d4 == 0 busy */
2616                         rc = usbvision_read_reg(usbvision, USBVISION_SER_CONT);
2617                 } while (rc > 0 && ((rc & 0x10) != 0)); /* Retry while busy */
2618                 if (rc < 0)
2619                         return rc;
2620
2621                 /* USBVISION_SER_CONT -> d5 == 1 Not ack */
2622                 if ((rc & 0x20) == 0)   /* Ack? */
2623                         break;
2624
2625                 /* I2C abort */
2626                 rc = usbvision_write_reg(usbvision, USBVISION_SER_CONT, 0x00);
2627                 if (rc < 0)
2628                         return rc;
2629
2630                 if (--retries < 0)
2631                         return -1;
2632         }
2633
2634         switch (len) {
2635         case 4:
2636                 buf[3] = usbvision_read_reg(usbvision, USBVISION_SER_DAT4);
2637         case 3:
2638                 buf[2] = usbvision_read_reg(usbvision, USBVISION_SER_DAT3);
2639         case 2:
2640                 buf[1] = usbvision_read_reg(usbvision, USBVISION_SER_DAT2);
2641         case 1:
2642                 buf[0] = usbvision_read_reg(usbvision, USBVISION_SER_DAT1);
2643                 break;
2644         default:
2645                 printk(KERN_ERR
2646                        "usbvision_i2c_read_max4: buffer length > 4\n");
2647         }
2648
2649         if (debug & DBG_I2C) {
2650                 int idx;
2651                 for (idx = 0; idx < len; idx++) {
2652                         PDEBUG(DBG_I2C, "read %x from address %x", (unsigned char)buf[idx], addr);
2653                 }
2654         }
2655         return len;
2656 }
2657
2658
2659 static int usbvision_i2c_write_max4(struct usb_usbvision *usbvision,
2660                                  unsigned char addr, const char *buf,
2661                                  short len)
2662 {
2663         int rc, retries;
2664         int i;
2665         unsigned char value[6];
2666         unsigned char ser_cont;
2667
2668         ser_cont = (len & 0x07) | 0x10;
2669
2670         value[0] = addr;
2671         value[1] = ser_cont;
2672         for (i = 0; i < len; i++)
2673                 value[i + 2] = buf[i];
2674
2675         for (retries = 5;;) {
2676                 rc = usb_control_msg(usbvision->dev,
2677                                      usb_sndctrlpipe(usbvision->dev, 1),
2678                                      USBVISION_OP_CODE,
2679                                      USB_DIR_OUT | USB_TYPE_VENDOR |
2680                                      USB_RECIP_ENDPOINT, 0,
2681                                      (__u16) USBVISION_SER_ADRS, value,
2682                                      len + 2, HZ);
2683
2684                 if (rc < 0)
2685                         return rc;
2686
2687                 rc = usbvision_write_reg(usbvision, USBVISION_SER_CONT,
2688                                       (len & 0x07) | 0x10);
2689                 if (rc < 0)
2690                         return rc;
2691
2692                 /* Test for Busy and ACK */
2693                 do {
2694                         rc = usbvision_read_reg(usbvision, USBVISION_SER_CONT);
2695                 } while (rc > 0 && ((rc & 0x10) != 0)); /* Retry while busy */
2696                 if (rc < 0)
2697                         return rc;
2698
2699                 if ((rc & 0x20) == 0)   /* Ack? */
2700                         break;
2701
2702                 /* I2C abort */
2703                 usbvision_write_reg(usbvision, USBVISION_SER_CONT, 0x00);
2704
2705                 if (--retries < 0)
2706                         return -1;
2707
2708         }
2709
2710         if (debug & DBG_I2C) {
2711                 int idx;
2712                 for (idx = 0; idx < len; idx++) {
2713                         PDEBUG(DBG_I2C, "wrote %x at address %x", (unsigned char)buf[idx], addr);
2714                 }
2715         }
2716         return len;
2717 }
2718
2719 static int usbvision_i2c_write(void *data, unsigned char addr, char *buf,
2720                             short len)
2721 {
2722         char *bufPtr = buf;
2723         int retval;
2724         int wrcount = 0;
2725         int count;
2726         int maxLen = 4;
2727         struct usb_usbvision *usbvision = (struct usb_usbvision *) data;
2728
2729         while (len > 0) {
2730                 count = (len > maxLen) ? maxLen : len;
2731                 retval = usbvision_i2c_write_max4(usbvision, addr, bufPtr, count);
2732                 if (retval > 0) {
2733                         len -= count;
2734                         bufPtr += count;
2735                         wrcount += count;
2736                 } else
2737                         return (retval < 0) ? retval : -EFAULT;
2738         }
2739         return wrcount;
2740 }
2741
2742 static int usbvision_i2c_read(void *data, unsigned char addr, char *buf,
2743                            short len)
2744 {
2745         char temp[4];
2746         int retval, i;
2747         int rdcount = 0;
2748         int count;
2749         struct usb_usbvision *usbvision = (struct usb_usbvision *) data;
2750
2751         while (len > 0) {
2752                 count = (len > 3) ? 4 : len;
2753                 retval = usbvision_i2c_read_max4(usbvision, addr, temp, count);
2754                 if (retval > 0) {
2755                         for (i = 0; i < len; i++)
2756                                 buf[rdcount + i] = temp[i];
2757                         len -= count;
2758                         rdcount += count;
2759                 } else
2760                         return (retval < 0) ? retval : -EFAULT;
2761         }
2762         return rdcount;
2763 }
2764
2765 static struct i2c_algo_usb_data i2c_algo_template = {
2766         .data           = NULL,
2767         .inb            = usbvision_i2c_read,
2768         .outb           = usbvision_i2c_write,
2769         .udelay         = 10,
2770         .mdelay         = 10,
2771         .timeout        = 100,
2772 };
2773
2774 static struct i2c_adapter i2c_adap_template = {
2775         .owner             = THIS_MODULE,
2776         .name              = "usbvision",
2777         .id                = I2C_HW_B_BT848, /* FIXME */
2778         .algo              = NULL,
2779         .algo_data         = NULL,
2780         .client_register   = attach_inform,
2781         .client_unregister = detach_inform,
2782 #if defined (I2C_ADAP_CLASS_TV_ANALOG)
2783         .class             = I2C_ADAP_CLASS_TV_ANALOG,
2784 #elif defined (I2C_CLASS_TV_ANALOG)
2785         .class             = I2C_CLASS_TV_ANALOG,
2786 #endif
2787 };
2788
2789 static struct i2c_client i2c_client_template = {
2790         .name           = "usbvision internal",
2791         .flags          = 0,
2792         .addr           = 0,
2793         .adapter        = NULL,
2794         .driver         = NULL,
2795 };
2796
2797 static int usbvision_init_i2c(struct usb_usbvision *usbvision)
2798 {
2799         memcpy(&usbvision->i2c_adap, &i2c_adap_template,
2800                sizeof(struct i2c_adapter));
2801         memcpy(&usbvision->i2c_algo, &i2c_algo_template,
2802                sizeof(struct i2c_algo_usb_data));
2803         memcpy(&usbvision->i2c_client, &i2c_client_template,
2804                sizeof(struct i2c_client));
2805
2806         sprintf(usbvision->i2c_adap.name + strlen(usbvision->i2c_adap.name),
2807                 " #%d", usbvision->vdev->minor & 0x1f);
2808         PDEBUG(DBG_I2C, "Adaptername: %s", usbvision->i2c_adap.name);
2809
2810         i2c_set_adapdata(&usbvision->i2c_adap, usbvision);
2811         i2c_set_clientdata(&usbvision->i2c_client, usbvision);
2812         i2c_set_algo_usb_data(&usbvision->i2c_algo, usbvision);
2813
2814         usbvision->i2c_adap.algo_data = &usbvision->i2c_algo;
2815         usbvision->i2c_client.adapter = &usbvision->i2c_adap;
2816
2817         if (usbvision_write_reg(usbvision, USBVISION_SER_MODE, USBVISION_IIC_LRNACK) < 0) {
2818                 printk(KERN_ERR "usbvision_init_i2c: can't wirte reg\n");
2819                 return -EBUSY;
2820         }
2821
2822 #ifdef CONFIG_KMOD
2823         /* Request the load of the i2c modules we need */
2824         if (autoload) {
2825                 switch (usbvision_device_data[usbvision->DevModel].Codec) {
2826                         case CODEC_SAA7113:
2827                                 request_module("saa7115");
2828                                 break;
2829                         case CODEC_SAA7111:
2830                                 request_module("saa7115");
2831                                 break;
2832                 }
2833                 if (usbvision_device_data[usbvision->DevModel].Tuner == 1) {
2834                         request_module("tuner");
2835                 }
2836         }
2837 #endif
2838
2839         usbvision->i2c_ok = usbvision_i2c_usb_add_bus(&usbvision->i2c_adap);
2840
2841         return usbvision->i2c_ok;
2842
2843 }
2844
2845
2846 /****************************/
2847 /* usbvision utility functions */
2848 /****************************/
2849
2850 static int usbvision_power_off(struct usb_usbvision *usbvision)
2851 {
2852         int errCode = 0;
2853
2854         PDEBUG(DBG_FUNC, "");
2855
2856         errCode = usbvision_write_reg(usbvision, USBVISION_PWR_REG, USBVISION_SSPND_EN);
2857         if (errCode == 1) {
2858                 usbvision->power = 0;
2859         }
2860         PDEBUG(DBG_FUNC, "%s: errCode %d", (errCode!=1)?"ERROR":"power is off", errCode);
2861         return errCode;
2862 }
2863
2864
2865 // to call usbvision_power_off from task queue
2866 static void call_usbvision_power_off(void *_usbvision)
2867 {
2868         struct usb_usbvision *usbvision = _usbvision;
2869
2870         PDEBUG(DBG_FUNC, "");
2871         down_interruptible(&usbvision->lock);
2872         if(usbvision->user == 0) {
2873                 usbvision_i2c_usb_del_bus(&usbvision->i2c_adap);
2874                 usbvision_power_off(usbvision);
2875                 usbvision->initialized = 0;
2876         }
2877         up(&usbvision->lock);
2878 }
2879
2880
2881 /*
2882  * usbvision_set_video_format()
2883  *
2884  */
2885 static int usbvision_set_video_format(struct usb_usbvision *usbvision, int format)
2886 {
2887         static const char proc[] = "usbvision_set_video_format";
2888         int rc;
2889         unsigned char value[2];
2890
2891         if (!USBVISION_IS_OPERATIONAL(usbvision))
2892                 return 0;
2893
2894         PDEBUG(DBG_FUNC, "isocMode %#02x", format);
2895
2896         if ((format != ISOC_MODE_YUV422)
2897             && (format != ISOC_MODE_YUV420)
2898             && (format != ISOC_MODE_COMPRESS)) {
2899                 printk(KERN_ERR "usbvision: unknown video format %02x, using default YUV420",
2900                        format);
2901                 format = ISOC_MODE_YUV420;
2902         }
2903         value[0] = 0x0A;  //TODO: See the effect of the filter
2904         value[1] = format;
2905         rc = usb_control_msg(usbvision->dev, usb_sndctrlpipe(usbvision->dev, 1),
2906                              USBVISION_OP_CODE,
2907                              USB_DIR_OUT | USB_TYPE_VENDOR |
2908                              USB_RECIP_ENDPOINT, 0,
2909                              (__u16) USBVISION_FILT_CONT, value, 2, HZ);
2910
2911         if (rc < 0) {
2912                 printk(KERN_ERR "%s: ERROR=%d. USBVISION stopped - "
2913                        "reconnect or reload driver.\n", proc, rc);
2914         }
2915         usbvision->isocMode = format;
2916         return rc;
2917 }
2918
2919 /*
2920  * usbvision_set_output()
2921  *
2922  */
2923
2924 static int usbvision_set_output(struct usb_usbvision *usbvision, int width,
2925                                   int height)
2926 {
2927         int errCode = 0;
2928         int UsbWidth, UsbHeight;
2929         unsigned int frameRate=0, frameDrop=0;
2930         unsigned char value[4];
2931
2932         if (!USBVISION_IS_OPERATIONAL(usbvision)) {
2933                 return 0;
2934         }
2935
2936         if (width > MAX_USB_WIDTH) {
2937                 UsbWidth = width / 2;
2938                 usbvision->stretch_width = 2;
2939         }
2940         else {
2941                 UsbWidth = width;
2942                 usbvision->stretch_width = 1;
2943         }
2944
2945         if (height > MAX_USB_HEIGHT) {
2946                 UsbHeight = height / 2;
2947                 usbvision->stretch_height = 2;
2948         }
2949         else {
2950                 UsbHeight = height;
2951                 usbvision->stretch_height = 1;
2952         }
2953
2954         RESTRICT_TO_RANGE(UsbWidth, MIN_FRAME_WIDTH, MAX_USB_WIDTH);
2955         UsbWidth &= ~(MIN_FRAME_WIDTH-1);
2956         RESTRICT_TO_RANGE(UsbHeight, MIN_FRAME_HEIGHT, MAX_USB_HEIGHT);
2957         UsbHeight &= ~(1);
2958
2959         PDEBUG(DBG_FUNC, "usb %dx%d; screen %dx%d; stretch %dx%d",
2960                                                 UsbWidth, UsbHeight, width, height,
2961                                                 usbvision->stretch_width, usbvision->stretch_height);
2962
2963         /* I'll not rewrite the same values */
2964         if ((UsbWidth != usbvision->curwidth) || (UsbHeight != usbvision->curheight)) {
2965                 value[0] = UsbWidth & 0xff;             //LSB
2966                 value[1] = (UsbWidth >> 8) & 0x03;      //MSB
2967                 value[2] = UsbHeight & 0xff;            //LSB
2968                 value[3] = (UsbHeight >> 8) & 0x03;     //MSB
2969
2970                 errCode = usb_control_msg(usbvision->dev, usb_sndctrlpipe(usbvision->dev, 1),
2971                              USBVISION_OP_CODE,
2972                              USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_ENDPOINT,
2973                                  0, (__u16) USBVISION_LXSIZE_O, value, 4, HZ);
2974
2975                 if (errCode < 0) {
2976                         err("%s failed: error %d", __FUNCTION__, errCode);
2977                         return errCode;
2978                 }
2979                 usbvision->curwidth = usbvision->stretch_width * UsbWidth;
2980                 usbvision->curheight = usbvision->stretch_height * UsbHeight;
2981         }
2982
2983         if (usbvision->isocMode == ISOC_MODE_YUV422) {
2984                 frameRate = (usbvision->isocPacketSize * 1000) / (UsbWidth * UsbHeight * 2);
2985         }
2986         else if (usbvision->isocMode == ISOC_MODE_YUV420) {
2987                 frameRate = (usbvision->isocPacketSize * 1000) / ((UsbWidth * UsbHeight * 12) / 8);
2988         }
2989         else {
2990                 frameRate = FRAMERATE_MAX;
2991         }
2992
2993         if (usbvision->input.std & V4L2_STD_625_50) {
2994                 frameDrop = frameRate * 32 / 25 - 1;
2995         }
2996         else if (usbvision->input.std & V4L2_STD_525_60) {
2997                 frameDrop = frameRate * 32 / 30 - 1;
2998         }
2999
3000         RESTRICT_TO_RANGE(frameDrop, FRAMERATE_MIN, FRAMERATE_MAX);
3001
3002         PDEBUG(DBG_FUNC, "frameRate %d fps, frameDrop %d", frameRate, frameDrop);
3003
3004         frameDrop = FRAMERATE_MAX;      // We can allow the maximum here, because dropping is controlled
3005
3006         /* frameDrop = 7; => framePhase = 1, 5, 9, 13, 17, 21, 25, 0, 4, 8, ...
3007                 => frameSkip = 4;
3008                 => frameRate = (7 + 1) * 25 / 32 = 200 / 32 = 6.25;
3009
3010            frameDrop = 9; => framePhase = 1, 5, 8, 11, 14, 17, 21, 24, 27, 1, 4, 8, ...
3011             => frameSkip = 4, 3, 3, 3, 3, 4, 3, 3, 3, 3, 4, ...
3012                 => frameRate = (9 + 1) * 25 / 32 = 250 / 32 = 7.8125;
3013         */
3014         errCode = usbvision_write_reg(usbvision, USBVISION_FRM_RATE, frameDrop);
3015         return errCode;
3016 }
3017
3018
3019 /*
3020  * usbvision_set_compress_params()
3021  *
3022  */
3023
3024 static int usbvision_set_compress_params(struct usb_usbvision *usbvision)
3025 {
3026         static const char proc[] = "usbvision_set_compresion_params: ";
3027         int rc;
3028         unsigned char value[6];
3029
3030         value[0] = 0x0F;    // Intra-Compression cycle
3031         value[1] = 0x01;    // Reg.45 one line per strip
3032         value[2] = 0x00;    // Reg.46 Force intra mode on all new frames
3033         value[3] = 0x00;    // Reg.47 FORCE_UP <- 0 normal operation (not force)
3034         value[4] = 0xA2;    // Reg.48 BUF_THR I'm not sure if this does something in not compressed mode.
3035         value[5] = 0x00;    // Reg.49 DVI_YUV This has nothing to do with compression
3036
3037         //catched values for NT1004
3038         // value[0] = 0xFF; // Never apply intra mode automatically
3039         // value[1] = 0xF1; // Use full frame height for virtual strip width; One line per strip
3040         // value[2] = 0x01; // Force intra mode on all new frames
3041         // value[3] = 0x00; // Strip size 400 Bytes; do not force up
3042         // value[4] = 0xA2; //
3043         if (!USBVISION_IS_OPERATIONAL(usbvision))
3044                 return 0;
3045
3046         rc = usb_control_msg(usbvision->dev, usb_sndctrlpipe(usbvision->dev, 1),
3047                              USBVISION_OP_CODE,
3048                              USB_DIR_OUT | USB_TYPE_VENDOR |
3049                              USB_RECIP_ENDPOINT, 0,
3050                              (__u16) USBVISION_INTRA_CYC, value, 5, HZ);
3051
3052         if (rc < 0) {
3053                 printk(KERN_ERR "%sERROR=%d. USBVISION stopped - "
3054                        "reconnect or reload driver.\n", proc, rc);
3055                 return rc;
3056         }
3057
3058         if (usbvision->bridgeType == BRIDGE_NT1004) {
3059                 value[0] =  20; // PCM Threshold 1
3060                 value[1] =  12; // PCM Threshold 2
3061                 value[2] = 255; // Distorsion Threshold inter
3062                 value[3] = 255; // Distorsion Threshold intra
3063                 value[4] =  43; // Max Distorsion inter
3064                 value[5] =  43; // Max Distorsion intra
3065         }
3066         else {
3067                 value[0] =  20; // PCM Threshold 1
3068                 value[1] =  12; // PCM Threshold 2
3069                 value[2] = 255; // Distorsion Threshold d7-d0
3070                 value[3] =   0; // Distorsion Threshold d11-d8
3071                 value[4] =  43; // Max Distorsion d7-d0
3072                 value[5] =   0; // Max Distorsion d8
3073         }
3074
3075         if (!USBVISION_IS_OPERATIONAL(usbvision))
3076                 return 0;
3077
3078         rc = usb_control_msg(usbvision->dev, usb_sndctrlpipe(usbvision->dev, 1),
3079                              USBVISION_OP_CODE,
3080                              USB_DIR_OUT | USB_TYPE_VENDOR |
3081                              USB_RECIP_ENDPOINT, 0,
3082                              (__u16) USBVISION_PCM_THR1, value, 6, HZ);
3083
3084         if (rc < 0) {
3085                 printk(KERN_ERR "%sERROR=%d. USBVISION stopped - "
3086                        "reconnect or reload driver.\n", proc, rc);
3087                 return rc;
3088         }
3089
3090
3091         return rc;
3092 }
3093
3094
3095 /*
3096  * usbvision_set_input()
3097  *
3098  * Set the input (saa711x, ...) size x y and other misc input params
3099  * I've no idea if this parameters are right
3100  *
3101  */
3102 static int usbvision_set_input(struct usb_usbvision *usbvision)
3103 {
3104         static const char proc[] = "usbvision_set_input: ";
3105         int rc;
3106         unsigned char value[8];
3107         unsigned char dvi_yuv_value;
3108
3109         if (!USBVISION_IS_OPERATIONAL(usbvision))
3110                 return 0;
3111
3112         /* Set input format expected from decoder*/
3113         if (usbvision_device_data[usbvision->DevModel].Vin_Reg1 >= 0) {
3114                 value[0] = usbvision_device_data[usbvision->DevModel].Vin_Reg1 & 0xff;
3115         } else if(usbvision_device_data[usbvision->DevModel].Codec == CODEC_SAA7113) {
3116                 /* SAA7113 uses 8 bit output */
3117                 value[0] = USBVISION_8_422_SYNC;
3118         } else {
3119                 /* I'm sure only about d2-d0 [010] 16 bit 4:2:2 usin sync pulses
3120                  * as that is how saa7111 is configured */
3121                 value[0] = USBVISION_16_422_SYNC;
3122                 /* | USBVISION_VSNC_POL | USBVISION_VCLK_POL);*/
3123         }
3124
3125         rc = usbvision_write_reg(usbvision, USBVISION_VIN_REG1, value[0]);
3126         if (rc < 0) {
3127                 printk(KERN_ERR "%sERROR=%d. USBVISION stopped - "
3128                        "reconnect or reload driver.\n", proc, rc);
3129                 return rc;
3130         }
3131
3132
3133         if (usbvision->input.std & V4L2_STD_PAL) {
3134                 value[0] = 0xC0;
3135                 value[1] = 0x02;        //0x02C0 -> 704 Input video line length
3136                 value[2] = 0x20;
3137                 value[3] = 0x01;        //0x0120 -> 288 Input video n. of lines
3138                 value[4] = 0x60;
3139                 value[5] = 0x00;        //0x0060 -> 96 Input video h offset
3140                 value[6] = 0x16;
3141                 value[7] = 0x00;        //0x0016 -> 22 Input video v offset
3142         } else if (usbvision->input.std & V4L2_STD_SECAM) {
3143                 value[0] = 0xC0;
3144                 value[1] = 0x02;        //0x02C0 -> 704 Input video line length
3145                 value[2] = 0x20;
3146                 value[3] = 0x01;        //0x0120 -> 288 Input video n. of lines
3147                 value[4] = 0x01;
3148                 value[5] = 0x00;        //0x0001 -> 01 Input video h offset
3149                 value[6] = 0x01;
3150                 value[7] = 0x00;        //0x0001 -> 01 Input video v offset
3151         } else {        /* V4L2_STD_NTSC */
3152                 value[0] = 0xD0;
3153                 value[1] = 0x02;        //0x02D0 -> 720 Input video line length
3154                 value[2] = 0xF0;
3155                 value[3] = 0x00;        //0x00F0 -> 240 Input video number of lines
3156                 value[4] = 0x50;
3157                 value[5] = 0x00;        //0x0050 -> 80 Input video h offset
3158                 value[6] = 0x10;
3159                 value[7] = 0x00;        //0x0010 -> 16 Input video v offset
3160         }
3161
3162         if (usbvision_device_data[usbvision->DevModel].X_Offset >= 0) {
3163                 value[4]=usbvision_device_data[usbvision->DevModel].X_Offset & 0xff;
3164                 value[5]=(usbvision_device_data[usbvision->DevModel].X_Offset & 0x0300) >> 8;
3165         }
3166
3167         if (usbvision_device_data[usbvision->DevModel].Y_Offset >= 0) {
3168                 value[6]=usbvision_device_data[usbvision->DevModel].Y_Offset & 0xff;
3169                 value[7]=(usbvision_device_data[usbvision->DevModel].Y_Offset & 0x0300) >> 8;
3170         }
3171
3172         rc = usb_control_msg(usbvision->dev, usb_sndctrlpipe(usbvision->dev, 1),
3173                              USBVISION_OP_CODE, /* USBVISION specific code */
3174                              USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_ENDPOINT, 0,
3175                              (__u16) USBVISION_LXSIZE_I, value, 8, HZ);
3176         if (rc < 0) {
3177                 printk(KERN_ERR "%sERROR=%d. USBVISION stopped - "
3178                        "reconnect or reload driver.\n", proc, rc);
3179                 return rc;
3180         }
3181
3182
3183         dvi_yuv_value = 0x00;   /* U comes after V, Ya comes after U/V, Yb comes after Yb */
3184
3185         if(usbvision_device_data[usbvision->DevModel].Dvi_yuv >= 0){
3186                 dvi_yuv_value = usbvision_device_data[usbvision->DevModel].Dvi_yuv & 0xff;
3187         }
3188         else if(usbvision_device_data[usbvision->DevModel].Codec == CODEC_SAA7113) {
3189         /* This changes as the fine sync control changes. Further investigation necessary */
3190                 dvi_yuv_value = 0x06;
3191         }
3192
3193         return (usbvision_write_reg(usbvision, USBVISION_DVI_YUV, dvi_yuv_value));
3194 }
3195
3196
3197 /*
3198  * usbvision_set_dram_settings()
3199  *
3200  * Set the buffer address needed by the usbvision dram to operate
3201  * This values has been taken with usbsnoop.
3202  *
3203  */
3204
3205 static int usbvision_set_dram_settings(struct usb_usbvision *usbvision)
3206 {
3207         int rc;
3208         unsigned char value[8];
3209
3210         if (usbvision->isocMode == ISOC_MODE_COMPRESS) {
3211                 value[0] = 0x42;
3212                 value[1] = 0x71;
3213                 value[2] = 0xff;
3214                 value[3] = 0x00;
3215                 value[4] = 0x98;
3216                 value[5] = 0xe0;
3217                 value[6] = 0x71;
3218                 value[7] = 0xff;
3219                 // UR:  0x0E200-0x3FFFF = 204288 Words (1 Word = 2 Byte)
3220                 // FDL: 0x00000-0x0E099 =  57498 Words
3221                 // VDW: 0x0E3FF-0x3FFFF
3222         }
3223         else {
3224                 value[0] = 0x42;
3225                 value[1] = 0x00;
3226                 value[2] = 0xff;
3227                 value[3] = 0x00;
3228                 value[4] = 0x00;
3229                 value[5] = 0x00;
3230                 value[6] = 0x00;
3231                 value[7] = 0xff;
3232         }
3233         /* These are the values of the address of the video buffer,
3234          * they have to be loaded into the USBVISION_DRM_PRM1-8
3235          *
3236          * Start address of video output buffer for read:       drm_prm1-2 -> 0x00000
3237          * End address of video output buffer for read:         drm_prm1-3 -> 0x1ffff
3238          * Start address of video frame delay buffer:           drm_prm1-4 -> 0x20000
3239          *    Only used in compressed mode
3240          * End address of video frame delay buffer:             drm_prm1-5-6 -> 0x3ffff
3241          *    Only used in compressed mode
3242          * Start address of video output buffer for write:      drm_prm1-7 -> 0x00000
3243          * End address of video output buffer for write:        drm_prm1-8 -> 0x1ffff
3244          */
3245
3246         if (!USBVISION_IS_OPERATIONAL(usbvision))
3247                 return 0;
3248
3249         rc = usb_control_msg(usbvision->dev, usb_sndctrlpipe(usbvision->dev, 1),
3250                              USBVISION_OP_CODE, /* USBVISION specific code */
3251                              USB_DIR_OUT | USB_TYPE_VENDOR |
3252                              USB_RECIP_ENDPOINT, 0,
3253                              (__u16) USBVISION_DRM_PRM1, value, 8, HZ);
3254
3255         if (rc < 0) {
3256                 err("%sERROR=%d", __FUNCTION__, rc);
3257                 return rc;
3258         }
3259
3260         /* Restart the video buffer logic */
3261         if ((rc = usbvision_write_reg(usbvision, USBVISION_DRM_CONT, USBVISION_RES_UR |
3262                                    USBVISION_RES_FDL | USBVISION_RES_VDW)) < 0)
3263                 return rc;
3264         rc = usbvision_write_reg(usbvision, USBVISION_DRM_CONT, 0x00);
3265
3266         return rc;
3267 }
3268
3269 /*
3270  * ()
3271  *
3272  * Power on the device, enables suspend-resume logic
3273  * &  reset the isoc End-Point
3274  *
3275  */
3276
3277 static int usbvision_power_on(struct usb_usbvision *usbvision)
3278 {
3279         int errCode = 0;
3280
3281         PDEBUG(DBG_FUNC, "");
3282
3283         usbvision_write_reg(usbvision, USBVISION_PWR_REG, USBVISION_SSPND_EN);
3284         usbvision_write_reg(usbvision, USBVISION_PWR_REG,
3285                          USBVISION_SSPND_EN | USBVISION_RES2);
3286         usbvision_write_reg(usbvision, USBVISION_PWR_REG,
3287                          USBVISION_SSPND_EN | USBVISION_PWR_VID);
3288         errCode = usbvision_write_reg(usbvision, USBVISION_PWR_REG,
3289                                                 USBVISION_SSPND_EN | USBVISION_PWR_VID | USBVISION_RES2);
3290         if (errCode == 1) {
3291                 usbvision->power = 1;
3292         }
3293         PDEBUG(DBG_FUNC, "%s: errCode %d", (errCode<0)?"ERROR":"power is on", errCode);
3294         return errCode;
3295 }
3296
3297
3298 static void usbvision_powerOffTimer(unsigned long data)
3299 {
3300         struct usb_usbvision *usbvision = (void *) data;
3301
3302         PDEBUG(DBG_FUNC, "");
3303         del_timer(&usbvision->powerOffTimer);
3304         INIT_WORK(&usbvision->powerOffWork, call_usbvision_power_off, usbvision);
3305         (void) schedule_work(&usbvision->powerOffWork);
3306         
3307 }
3308
3309
3310 /*
3311  * usbvision_begin_streaming()
3312  * Sure you have to put bit 7 to 0, if not incoming frames are droped, but no
3313  * idea about the rest
3314  */
3315 static int usbvision_begin_streaming(struct usb_usbvision *usbvision)
3316 {
3317         int errCode = 0;
3318
3319         if (usbvision->isocMode == ISOC_MODE_COMPRESS) {
3320                 usbvision_init_compression(usbvision);
3321         }
3322         errCode = usbvision_write_reg(usbvision, USBVISION_VIN_REG2, USBVISION_NOHVALID |
3323                                                                                 usbvision->Vin_Reg2_Preset);
3324         return errCode;
3325 }
3326
3327 /*
3328  * usbvision_restart_isoc()
3329  * Not sure yet if touching here PWR_REG make loose the config
3330  */
3331
3332 static int usbvision_restart_isoc(struct usb_usbvision *usbvision)
3333 {
3334         int ret;
3335
3336         if (
3337             (ret =
3338              usbvision_write_reg(usbvision, USBVISION_PWR_REG,
3339                               USBVISION_SSPND_EN | USBVISION_PWR_VID)) < 0)
3340                 return ret;
3341         if (
3342             (ret =
3343              usbvision_write_reg(usbvision, USBVISION_PWR_REG,
3344                               USBVISION_SSPND_EN | USBVISION_PWR_VID |
3345                               USBVISION_RES2)) < 0)
3346                 return ret;
3347         if (
3348             (ret =
3349              usbvision_write_reg(usbvision, USBVISION_VIN_REG2,
3350                               USBVISION_KEEP_BLANK | USBVISION_NOHVALID |
3351                                   usbvision->Vin_Reg2_Preset)) < 0) return ret;
3352
3353         /* TODO: schedule timeout */
3354         while ((usbvision_read_reg(usbvision, USBVISION_STATUS_REG) && 0x01) != 1);
3355
3356         return 0;
3357 }
3358
3359 static int usbvision_audio_on(struct usb_usbvision *usbvision)
3360 {
3361         if (usbvision_write_reg(usbvision, USBVISION_IOPIN_REG, usbvision->AudioChannel) < 0) {
3362                 printk(KERN_ERR "usbvision_audio_on: can't wirte reg\n");
3363                 return -1;
3364         }
3365         DEBUG(printk(KERN_DEBUG "usbvision_audio_on: channel %d\n", usbvision->AudioChannel));
3366         usbvision->AudioMute = 0;
3367         return 0;
3368 }
3369
3370 static int usbvision_audio_mute(struct usb_usbvision *usbvision)
3371 {
3372         if (usbvision_write_reg(usbvision, USBVISION_IOPIN_REG, 0x03) < 0) {
3373                 printk(KERN_ERR "usbvision_audio_mute: can't wirte reg\n");
3374                 return -1;
3375         }
3376         DEBUG(printk(KERN_DEBUG "usbvision_audio_mute: audio mute\n"));
3377         usbvision->AudioMute = 1;
3378         return 0;
3379 }
3380
3381 static int usbvision_audio_off(struct usb_usbvision *usbvision)
3382 {
3383         if (usbvision_write_reg(usbvision, USBVISION_IOPIN_REG, USBVISION_AUDIO_MUTE) < 0) {
3384                 printk(KERN_ERR "usbvision_audio_off: can't wirte reg\n");
3385                 return -1;
3386         }
3387         DEBUG(printk(KERN_DEBUG "usbvision_audio_off: audio off\n"));
3388         usbvision->AudioMute = 0;
3389         usbvision->AudioChannel = USBVISION_AUDIO_MUTE;
3390         return 0;
3391 }
3392
3393 static int usbvision_set_audio(struct usb_usbvision *usbvision, int AudioChannel)
3394 {
3395         if (!usbvision->AudioMute) {
3396                 if (usbvision_write_reg(usbvision, USBVISION_IOPIN_REG, AudioChannel) < 0) {
3397                         printk(KERN_ERR "usbvision_set_audio: can't write iopin register for audio switching\n");
3398                         return -1;
3399                 }
3400         }
3401         DEBUG(printk(KERN_DEBUG "usbvision_set_audio: channel %d\n", AudioChannel));
3402         usbvision->AudioChannel = AudioChannel;
3403         return 0;
3404 }
3405
3406 static int usbvision_setup(struct usb_usbvision *usbvision)
3407 {
3408         usbvision_set_video_format(usbvision, isocMode);
3409         usbvision_set_dram_settings(usbvision);
3410         usbvision_set_compress_params(usbvision);
3411         usbvision_set_input(usbvision);
3412         usbvision_set_output(usbvision, MAX_USB_WIDTH, MAX_USB_HEIGHT);
3413         usbvision_restart_isoc(usbvision);
3414         
3415         /* cosas del PCM */
3416         return USBVISION_IS_OPERATIONAL(usbvision);
3417 }
3418
3419
3420 /*
3421  * usbvision_init_isoc()
3422  *
3423  */
3424 static int usbvision_init_isoc(struct usb_usbvision *usbvision)
3425 {
3426         struct usb_device *dev = usbvision->dev;
3427         int bufIdx, errCode, regValue;
3428
3429         if (!USBVISION_IS_OPERATIONAL(usbvision))
3430                 return -EFAULT;
3431
3432         usbvision->curFrameNum = -1;
3433         scratch_reset(usbvision);
3434
3435         /* Alternate interface 1 is is the biggest frame size */
3436         errCode = usb_set_interface(dev, usbvision->iface, usbvision->ifaceAltActive);
3437         if (errCode < 0) {
3438                 usbvision->last_error = errCode;
3439                 return -EBUSY;
3440         }
3441
3442         regValue = (16 - usbvision_read_reg(usbvision, USBVISION_ALTER_REG)) & 0x0F;
3443         usbvision->isocPacketSize = (regValue == 0) ? 0 : (regValue * 64) - 1;
3444         PDEBUG(DBG_ISOC, "ISO Packet Length:%d", usbvision->isocPacketSize);
3445
3446         usbvision->usb_bandwidth = regValue >> 1;
3447         PDEBUG(DBG_ISOC, "USB Bandwidth Usage: %dMbit/Sec", usbvision->usb_bandwidth);
3448
3449
3450
3451         /* We double buffer the Iso lists */
3452
3453         for (bufIdx = 0; bufIdx < USBVISION_NUMSBUF; bufIdx++) {
3454                 int j, k;
3455                 struct urb *urb;
3456
3457                 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0)
3458                         urb = usb_alloc_urb(USBVISION_URB_FRAMES);
3459                 #else
3460                         urb = usb_alloc_urb(USBVISION_URB_FRAMES, GFP_KERNEL);
3461                 #endif
3462                 if (urb == NULL) {
3463                         err("%s: usb_alloc_urb() failed", __FUNCTION__);
3464                         return -ENOMEM;
3465                 }
3466                 usbvision->sbuf[bufIdx].urb = urb;
3467                 urb->dev = dev;
3468                 urb->context = usbvision;
3469                 urb->pipe = usb_rcvisocpipe(dev, usbvision->video_endp);
3470         #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0)
3471                 urb->transfer_flags = USB_ISO_ASAP;
3472         #else
3473                 urb->transfer_flags = URB_ISO_ASAP;
3474                 urb->interval = 1;
3475         #endif
3476                 urb->transfer_buffer = usbvision->sbuf[bufIdx].data;
3477                 urb->complete = usbvision_isocIrq;
3478                 urb->number_of_packets = USBVISION_URB_FRAMES;
3479                 urb->transfer_buffer_length =
3480                     usbvision->isocPacketSize * USBVISION_URB_FRAMES;
3481                 for (j = k = 0; j < USBVISION_URB_FRAMES; j++,
3482                      k += usbvision->isocPacketSize) {
3483                         urb->iso_frame_desc[j].offset = k;
3484                         urb->iso_frame_desc[j].length = usbvision->isocPacketSize;
3485                 }
3486         }
3487
3488
3489         /* Submit all URBs */
3490         for (bufIdx = 0; bufIdx < USBVISION_NUMSBUF; bufIdx++) {
3491                 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0)
3492                         errCode = usb_submit_urb(usbvision->sbuf[bufIdx].urb);
3493                 #else
3494                         errCode = usb_submit_urb(usbvision->sbuf[bufIdx].urb, GFP_KERNEL);
3495                 #endif
3496                 if (errCode) {
3497                         err("%s: usb_submit_urb(%d) failed: error %d", __FUNCTION__, bufIdx, errCode);
3498                 }
3499         }
3500
3501         usbvision->streaming = 1;
3502         PDEBUG(DBG_ISOC, "%s: streaming=1 usbvision->video_endp=$%02x", __FUNCTION__, usbvision->video_endp);
3503         return 0;
3504 }
3505
3506 /*
3507  * usbvision_stop_isoc()
3508  *
3509  * This procedure stops streaming and deallocates URBs. Then it
3510  * activates zero-bandwidth alt. setting of the video interface.
3511  *
3512  */
3513 static void usbvision_stop_isoc(struct usb_usbvision *usbvision)
3514 {
3515         int bufIdx, errCode, regValue;
3516
3517         if (!usbvision->streaming || (usbvision->dev == NULL))
3518                 return;
3519
3520         /* Unschedule all of the iso td's */
3521         for (bufIdx = 0; bufIdx < USBVISION_NUMSBUF; bufIdx++) {
3522                 usb_kill_urb(usbvision->sbuf[bufIdx].urb);
3523                 usb_free_urb(usbvision->sbuf[bufIdx].urb);
3524                 usbvision->sbuf[bufIdx].urb = NULL;
3525         }
3526
3527
3528         PDEBUG(DBG_ISOC, "%s: streaming=0\n", __FUNCTION__);
3529         usbvision->streaming = 0;
3530                         
3531
3532         if (!usbvision->remove_pending) {
3533
3534                 /* Set packet size to 0 */
3535                 errCode = usb_set_interface(usbvision->dev, usbvision->iface,
3536                                       usbvision->ifaceAltInactive);
3537                 if (errCode < 0) {
3538                         err("%s: usb_set_interface() failed: error %d", __FUNCTION__, errCode);
3539                         usbvision->last_error = errCode;
3540                 }
3541                 regValue = (16 - usbvision_read_reg(usbvision, USBVISION_ALTER_REG)) & 0x0F;
3542                 usbvision->isocPacketSize = (regValue == 0) ? 0 : (regValue * 64) - 1;
3543                 PDEBUG(DBG_ISOC, "ISO Packet Length:%d", usbvision->isocPacketSize);
3544
3545                 usbvision->usb_bandwidth = regValue >> 1;
3546                 PDEBUG(DBG_ISOC, "USB Bandwidth Usage: %dMbit/Sec", usbvision->usb_bandwidth);
3547         }
3548 }
3549
3550 /*
3551  * usbvision_new_frame()
3552  *
3553  */
3554 static int usbvision_new_frame(struct usb_usbvision *usbvision, int framenum)
3555 {
3556         struct usbvision_frame *frame;
3557         int n; //byhec  , width, height;
3558
3559         /* If we're not grabbing a frame right now and the other frame is */
3560         /*  ready to be grabbed into, then use it instead */
3561         if (usbvision->curFrameNum != -1)
3562                 return 0;
3563
3564         n = (framenum - 1 + USBVISION_NUMFRAMES) % USBVISION_NUMFRAMES;
3565         if (usbvision->frame[n].grabstate == FrameState_Ready)
3566                 framenum = n;
3567
3568         frame = &usbvision->frame[framenum];
3569
3570         frame->grabstate = FrameState_Grabbing;
3571         frame->scanstate = ScanState_Scanning;
3572         frame->scanlength = 0;  /* Accumulated in usbvision_parse_data() */
3573         usbvision->curFrameNum = framenum;
3574
3575         /*
3576          * Normally we would want to copy previous frame into the current one
3577          * before we even start filling it with data; this allows us to stop
3578          * filling at any moment; top portion of the frame will be new and
3579          * bottom portion will stay as it was in previous frame. If we don't
3580          * do that then missing chunks of video stream will result in flickering
3581          * portions of old data whatever it was before.
3582          *
3583          * If we choose not to copy previous frame (to, for example, save few
3584          * bus cycles - the frame can be pretty large!) then we have an option
3585          * to clear the frame before using. If we experience losses in this
3586          * mode then missing picture will be black (flickering).
3587          *
3588          * Finally, if user chooses not to clean the current frame before
3589          * filling it with data then the old data will be visible if we fail
3590          * to refill entire frame with new data.
3591          */
3592         if (!(flags & FLAGS_SEPARATE_FRAMES)) {
3593                 /* This copies previous frame into this one to mask losses */
3594                 memmove(frame->data, usbvision->frame[1 - framenum].data,
3595                         MAX_FRAME_SIZE);
3596         } else {
3597                 if (flags & FLAGS_CLEAN_FRAMES) {
3598                         /*This provides a "clean" frame but slows things down */
3599                         memset(frame->data, 0, MAX_FRAME_SIZE);
3600                 }
3601         }
3602         return 0;
3603 }
3604
3605 static int usbvision_muxsel(struct usb_usbvision *usbvision, int channel, int norm)
3606 {
3607         int mode[4];
3608         int audio[]= {1, 0, 0, 0};      
3609         struct v4l2_routing route;
3610         //channel 0 is TV with audiochannel 1 (tuner mono)
3611         //channel 1 is Composite with audio channel 0 (line in)
3612         //channel 2 is S-Video with audio channel 0 (line in)
3613         //channel 3 is additional video inputs to the device with audio channel 0 (line in)
3614
3615         RESTRICT_TO_RANGE(channel, 0, usbvision->video_inputs);
3616         /* set the new video norm */
3617         if (usbvision->input.std != norm) {
3618           v4l2_std_id video_command = norm;
3619
3620           route.input = SAA7115_COMPOSITE1;
3621           call_i2c_clients(usbvision, VIDIOC_INT_S_VIDEO_ROUTING,&route);
3622           call_i2c_clients(usbvision, VIDIOC_S_STD, &video_command);
3623           usbvision->input.std = norm;
3624           call_i2c_clients(usbvision, VIDIOC_S_INPUT, &usbvision->input.index); //set norm in tuner
3625         }
3626
3627         // set the new channel
3628         // Regular USB TV Tuners -> channel: 0 = Television, 1 = Composite, 2 = S-Video
3629         // Four video input devices -> channel: 0 = Chan White, 1 = Chan Green, 2 = Chan Yellow, 3 = Chan Red 
3630
3631         switch (usbvision_device_data[usbvision->DevModel].Codec) {
3632                 case CODEC_SAA7113:
3633                         if (SwitchSVideoInput) { // To handle problems with S-Video Input for some devices.  Use SwitchSVideoInput parameter when loading the module.
3634                                 mode[2] = 1;
3635                         }
3636                         else {
3637                                 mode[2] = 7;
3638                         }
3639                         if (usbvision_device_data[usbvision->DevModel].VideoChannels == 4) { 
3640                                 mode[0] = 0; mode[1] = 2; mode[3] = 3;  // Special for four input devices
3641                         }
3642                         else {  
3643                                 mode[0] = 0; mode[1] = 2; //modes for regular saa7113 devices
3644                         }
3645                         break;
3646                 case CODEC_SAA7111:
3647                         mode[0] = 0; mode[1] = 1; mode[2] = 7; //modes for saa7111
3648                         break;
3649                 default:
3650                         mode[0] = 0; mode[1] = 1; mode[2] = 7; //default modes
3651         }
3652         route.input = mode[channel];
3653         call_i2c_clients(usbvision, VIDIOC_INT_S_VIDEO_ROUTING,&route);
3654         usbvision->channel = channel;
3655         usbvision_set_audio(usbvision, audio[channel]);
3656         return 0;
3657 }
3658
3659
3660 /*
3661  * usbvision_open()
3662  *
3663  * This is part of Video 4 Linux API. The driver can be opened by one
3664  * client only (checks internal counter 'usbvision->user'). The procedure
3665  * then allocates buffers needed for video processing.
3666  *
3667  */
3668 static int usbvision_v4l2_open(struct inode *inode, struct file *file)
3669 {
3670         struct video_device *dev = video_devdata(file);
3671         struct usb_usbvision *usbvision = (struct usb_usbvision *) video_get_drvdata(dev);
3672         const int sb_size = USBVISION_URB_FRAMES * USBVISION_MAX_ISOC_PACKET_SIZE;
3673         int i, errCode = 0;
3674
3675         PDEBUG(DBG_IO, "open");
3676
3677
3678         if (timer_pending(&usbvision->powerOffTimer)) {
3679                 del_timer(&usbvision->powerOffTimer);
3680         }
3681
3682         if (usbvision->user)
3683                 errCode = -EBUSY;
3684         else {
3685                 /* Clean pointers so we know if we allocated something */
3686                 for (i = 0; i < USBVISION_NUMSBUF; i++)
3687                         usbvision->sbuf[i].data = NULL;
3688
3689                 /* Allocate memory for the frame buffers */
3690                 usbvision->max_frame_size = MAX_FRAME_SIZE;
3691                 usbvision->fbuf_size = USBVISION_NUMFRAMES * usbvision->max_frame_size;
3692                 usbvision->fbuf = usbvision_rvmalloc(usbvision->fbuf_size);
3693                 usbvision->scratch = vmalloc(scratch_buf_size);
3694                 scratch_reset(usbvision);
3695                 if ((usbvision->fbuf == NULL) || (usbvision->scratch == NULL)) {
3696                         err("%s: unable to allocate %d bytes for fbuf and %d bytes for scratch",
3697                                         __FUNCTION__, usbvision->fbuf_size, scratch_buf_size);
3698                         errCode = -ENOMEM;
3699                 }
3700                 else {
3701                         /* Allocate all buffers */
3702                         for (i = 0; i < USBVISION_NUMFRAMES; i++) {
3703                                 usbvision->frame[i].grabstate = FrameState_Unused;
3704                                 usbvision->frame[i].data = usbvision->fbuf +
3705                                     i * MAX_FRAME_SIZE;
3706                                 /*
3707                                  * Set default sizes in case IOCTL
3708                                  * (VIDIOCMCAPTURE)
3709                                  * is not used (using read() instead).
3710                                  */
3711                                 usbvision->stretch_width = 1;
3712                                 usbvision->stretch_height = 1;
3713                                 usbvision->frame[i].width = usbvision->curwidth;
3714                                 usbvision->frame[i].height = usbvision->curheight;
3715                                 usbvision->frame[i].bytes_read = 0;
3716                         }
3717                         if (dga) { //set default for DGA
3718                                 usbvision->overlay_frame.grabstate = FrameState_Unused;
3719                                 usbvision->overlay_frame.scanstate = ScanState_Scanning;
3720                                 usbvision->overlay_frame.data = NULL;
3721                                 usbvision->overlay_frame.width = usbvision->curwidth;
3722                                 usbvision->overlay_frame.height = usbvision->curheight;
3723                                 usbvision->overlay_frame.bytes_read = 0;
3724                         }
3725                         for (i = 0; i < USBVISION_NUMSBUF; i++) {
3726                                 usbvision->sbuf[i].data = kzalloc(sb_size, GFP_KERNEL);
3727                                 if (usbvision->sbuf[i].data == NULL) {
3728                                         err("%s: unable to allocate %d bytes for sbuf", __FUNCTION__, sb_size);
3729                                         errCode = -ENOMEM;
3730                                         break;
3731                                 }
3732                         }
3733                 }
3734                 if ((!errCode) && (usbvision->isocMode==ISOC_MODE_COMPRESS)) {
3735                         int IFB_size = MAX_FRAME_WIDTH * MAX_FRAME_HEIGHT * 3 / 2;
3736                         usbvision->IntraFrameBuffer = vmalloc(IFB_size);
3737                         if (usbvision->IntraFrameBuffer == NULL) {
3738                                 err("%s: unable to allocate %d for compr. frame buffer", __FUNCTION__, IFB_size);
3739                                 errCode = -ENOMEM;
3740                         }
3741                         
3742                 }
3743                 if (errCode) {
3744                         /* Have to free all that memory */
3745                         if (usbvision->fbuf != NULL) {
3746                                 usbvision_rvfree(usbvision->fbuf, usbvision->fbuf_size);
3747                                 usbvision->fbuf = NULL;
3748                         }
3749                         if (usbvision->scratch != NULL) {
3750                                 vfree(usbvision->scratch);
3751                                 usbvision->scratch = NULL;
3752                         }
3753                         for (i = 0; i < USBVISION_NUMSBUF; i++) {
3754                                 if (usbvision->sbuf[i].data != NULL) {
3755                                         kfree(usbvision->sbuf[i].data);
3756                                         usbvision->sbuf[i].data = NULL;
3757                                 }
3758                         }
3759                         if (usbvision->IntraFrameBuffer != NULL) {
3760                                 vfree(usbvision->IntraFrameBuffer);
3761                                 usbvision->IntraFrameBuffer = NULL;
3762                         }
3763                 }
3764         }
3765
3766         /* If so far no errors then we shall start the camera */
3767         if (!errCode) {
3768                 down(&usbvision->lock);
3769                 if (usbvision->power == 0) {
3770                         usbvision_power_on(usbvision);
3771                         usbvision_init_i2c(usbvision);
3772                 }
3773
3774                 /* Send init sequence only once, it's large! */
3775                 if (!usbvision->initialized) {
3776                         int setup_ok = 0;
3777                         setup_ok = usbvision_setup(usbvision);
3778                         if (setup_ok)
3779                                 usbvision->initialized = 1;
3780                         else
3781                                 errCode = -EBUSY;
3782                 }
3783
3784                 if (!errCode) {
3785                         usbvision_begin_streaming(usbvision);
3786                         errCode = usbvision_init_isoc(usbvision);
3787                         usbvision->user++;
3788                 }
3789                 else {
3790                         if (PowerOnAtOpen) {
3791                                 usbvision_i2c_usb_del_bus(&usbvision->i2c_adap);
3792                                 usbvision_power_off(usbvision);
3793                                 usbvision->initialized = 0;
3794                         }
3795                 }
3796                 up(&usbvision->lock);
3797         }
3798
3799         if (errCode) {
3800         }
3801
3802         PDEBUG(DBG_IO, "success");
3803         return errCode;
3804 }
3805
3806 /*
3807  * usbvision_v4l2_close()
3808  *
3809  * This is part of Video 4 Linux API. The procedure
3810  * stops streaming and deallocates all buffers that were earlier
3811  * allocated in usbvision_v4l2_open().
3812  *
3813  */
3814 static int usbvision_v4l2_close(struct inode *inode, struct file *file)
3815 {
3816         struct video_device *dev = video_devdata(file);
3817         struct usb_usbvision *usbvision = (struct usb_usbvision *) video_get_drvdata(dev);
3818         int i;
3819
3820         PDEBUG(DBG_IO, "close");
3821         down(&usbvision->lock);
3822
3823         usbvision_audio_off(usbvision);
3824         usbvision_restart_isoc(usbvision);
3825         usbvision_stop_isoc(usbvision);
3826
3827         if (usbvision->IntraFrameBuffer != NULL) {
3828                 vfree(usbvision->IntraFrameBuffer);
3829                 usbvision->IntraFrameBuffer = NULL;
3830         }
3831
3832         usbvision_rvfree(usbvision->fbuf, usbvision->fbuf_size);
3833         vfree(usbvision->scratch);
3834         for (i = 0; i < USBVISION_NUMSBUF; i++)
3835                 kfree(usbvision->sbuf[i].data);
3836
3837         usbvision->user--;
3838
3839         if (PowerOnAtOpen) {
3840                 mod_timer(&usbvision->powerOffTimer, jiffies + USBVISION_POWEROFF_TIME);
3841                 usbvision->initialized = 0;
3842         }
3843
3844         up(&usbvision->lock);
3845
3846         if (usbvision->remove_pending) {
3847                 info("%s: Final disconnect", __FUNCTION__);
3848                 usbvision_release(usbvision);
3849         }
3850
3851         PDEBUG(DBG_IO, "success");
3852
3853
3854         return 0;
3855 }
3856
3857
3858 /*
3859  * usbvision_ioctl()
3860  *
3861  * This is part of Video 4 Linux API. The procedure handles ioctl() calls.
3862  *
3863  */
3864 static int usbvision_v4l2_do_ioctl(struct inode *inode, struct file *file,
3865                                  unsigned int cmd, void *arg)
3866 {
3867         struct video_device *dev = video_devdata(file);
3868         struct usb_usbvision *usbvision = (struct usb_usbvision *) video_get_drvdata(dev);
3869
3870         if (!USBVISION_IS_OPERATIONAL(usbvision))
3871                 return -EFAULT;
3872
3873         switch (cmd) {
3874                 case UVIOCSREG:
3875                 {
3876                         struct usbvision_reg *usbvision_reg = arg;
3877                         int errCode;
3878
3879                         errCode = usbvision_write_reg(usbvision, usbvision_reg->addr, usbvision_reg->value);
3880
3881                         if (errCode < 0) {
3882                                 err("%s: UVIOCSREG failed: error %d", __FUNCTION__, errCode);
3883                         }
3884                         else {
3885                                 PDEBUG(DBG_IOCTL, "UVIOCSREG addr=0x%02X, value=0x%02X",
3886                                                         usbvision_reg->addr, usbvision_reg->value);
3887                                 errCode = 0;
3888                         }
3889                         return errCode;
3890                 }
3891                 case UVIOCGREG:
3892                 {
3893                         struct usbvision_reg *usbvision_reg = arg;
3894                         int errCode;
3895
3896                         errCode = usbvision_read_reg(usbvision, usbvision_reg->addr);
3897
3898                         if (errCode < 0) {
3899                                 err("%s: UVIOCGREG failed: error %d", __FUNCTION__, errCode);
3900                         }
3901                         else {
3902                                 usbvision_reg->value=(unsigned char)errCode;
3903                                 PDEBUG(DBG_IOCTL, "UVIOCGREG addr=0x%02X, value=0x%02X",
3904                                                         usbvision_reg->addr, usbvision_reg->value);
3905                                 errCode = 0; // No error
3906                         }
3907                         return errCode;
3908                 }
3909                 case VIDIOC_QUERYCAP:
3910                 {
3911                         struct v4l2_capability *vc=arg;
3912                         *vc = usbvision->vcap;
3913                         PDEBUG(DBG_IOCTL, "VIDIOC_QUERYCAP");
3914                         return 0;
3915                 }
3916                 case VIDIOC_ENUMINPUT:
3917                 {
3918                         struct v4l2_input *vi = arg;
3919                         int chan;
3920
3921                         if ((vi->index >= usbvision->video_inputs) || (vi->index < 0) )
3922                                 return -EINVAL;
3923                         if (usbvision->have_tuner) {
3924                                 chan = vi->index;
3925                         }
3926                         else {
3927                                 chan = vi->index + 1; //skip Television string
3928                         }
3929                         switch(chan) {
3930                                 case 0:
3931                                         if (usbvision_device_data[usbvision->DevModel].VideoChannels == 4) {
3932                                                 strcpy(vi->name, "White Video Input");
3933                                         } 
3934                                         else {  
3935                                                 strcpy(vi->name, "Television");
3936                                                 vi->type = V4L2_INPUT_TYPE_TUNER;
3937                                                 vi->audioset = 1;
3938                                                 vi->tuner = chan;
3939                                                 vi->std = V4L2_STD_PAL | V4L2_STD_NTSC | V4L2_STD_SECAM;
3940                                         }
3941                                         break;
3942                                 case 1:
3943                                         vi->type = V4L2_INPUT_TYPE_CAMERA;
3944                                         if (usbvision_device_data[usbvision->DevModel].VideoChannels == 4) {
3945                                                 strcpy(vi->name, "Green Video Input");
3946                                         } 
3947                                         else {  
3948                                                 strcpy(vi->name, "Composite Video Input");
3949                                         }
3950                                         vi->std = V4L2_STD_PAL;
3951                                         break;
3952                                 case 2:
3953                                         vi->type = V4L2_INPUT_TYPE_CAMERA;
3954                                         if (usbvision_device_data[usbvision->DevModel].VideoChannels == 4) {
3955                                                 strcpy(vi->name, "Yellow Video Input");
3956                                         } 
3957                                         else {  
3958                                         strcpy(vi->name, "S-Video Input");
3959                                         }
3960                                         vi->std = V4L2_STD_PAL;
3961                                         break;
3962                                 case 3:
3963                                         vi->type = V4L2_INPUT_TYPE_CAMERA;
3964                                         strcpy(vi->name, "Red Video Input");
3965                                         vi->std = V4L2_STD_PAL;
3966                                         break; 
3967                         }
3968                         PDEBUG(DBG_IOCTL, "VIDIOC_ENUMINPUT name=%s:%d tuners=%d type=%d norm=%x", vi->name, vi->index, vi->tuner,vi->type,(int)vi->std);
3969                         return 0;
3970                 }
3971                 case VIDIOC_ENUMSTD:
3972                 {
3973                         struct v4l2_standard *vs = arg;
3974                         switch(vs->index) {
3975                         case 0:
3976                                 vs->id = V4L2_STD_PAL;
3977                                 strcpy(vs->name,"PAL");
3978                                 vs->frameperiod.numerator   = 1;
3979                                 vs->frameperiod.denominator = 25;
3980                                 vs->framelines              = 625;
3981                                 break;
3982                         case 1:
3983                                 vs->id = V4L2_STD_NTSC;
3984                                 strcpy(vs->name,"NTSC");
3985                                 vs->frameperiod.numerator   = 1001;
3986                                 vs->frameperiod.denominator = 30000;
3987                                 vs->framelines              = 525;
3988                                 break;
3989                         case 2:
3990                                 vs->id = V4L2_STD_SECAM;
3991                                 strcpy(vs->name,"SECAM");
3992                                 vs->frameperiod.numerator   = 1;
3993                                 vs->frameperiod.denominator = 25;
3994                                 vs->framelines              = 625;
3995                                 break;
3996                         default:
3997                                 return -EINVAL;
3998                         }
3999                         return 0;
4000                 }
4001                 case VIDIOC_G_INPUT:
4002                 {
4003                         int *input = arg;
4004                         *input = usbvision->input.index;
4005                         return 0;
4006                 }
4007                 case VIDIOC_S_INPUT:
4008                 {
4009                         int *input = arg;
4010                         if ((*input >= usbvision->video_inputs) || (*input < 0) )
4011                                 return -EINVAL;
4012                         usbvision->input.index = *input;
4013
4014                         down(&usbvision->lock);
4015                         usbvision_muxsel(usbvision, usbvision->input.index, usbvision->input.std);
4016                         usbvision_set_input(usbvision);
4017                         usbvision_set_output(usbvision, usbvision->curwidth, usbvision->curheight);
4018                         up(&usbvision->lock);
4019                         return 0;
4020                 }
4021                 case VIDIOC_G_STD:
4022                 {
4023                         v4l2_std_id *std = arg;
4024                         *std = usbvision->input.std;
4025                         PDEBUG(DBG_IOCTL, "VIDIOC_G_STD std_id=%x", (unsigned)*std);
4026                         return 0;
4027                 }
4028                 case VIDIOC_S_STD:
4029                 {
4030                         v4l2_std_id *std = arg;
4031
4032                         down(&usbvision->lock);
4033                         usbvision_muxsel(usbvision, usbvision->input.index, *std);
4034                         usbvision_set_input(usbvision);
4035                         usbvision_set_output(usbvision, usbvision->curwidth, usbvision->curheight);
4036                         up(&usbvision->lock);
4037
4038                         usbvision->input.std = *std;
4039                         PDEBUG(DBG_IOCTL, "VIDIOC_S_STD std_id=%x", (unsigned)*std);
4040                         return 0;
4041                 }
4042                 case VIDIOC_G_TUNER:
4043                 {
4044                         struct v4l2_tuner *vt = arg;
4045                         struct v4l2_tuner status;
4046
4047                         if (!usbvision->have_tuner || vt->index)        // Only tuner 0
4048                                 return -EINVAL;
4049                         strcpy(vt->name, "Television");
4050                         vt->type = V4L2_TUNER_ANALOG_TV;
4051                         vt->capability = V4L2_TUNER_CAP_NORM;
4052                         vt->rangelow = 0;
4053                         vt->rangehigh = ~0;
4054                         vt->audmode = V4L2_TUNER_MODE_MONO;
4055                         vt->rxsubchans = V4L2_TUNER_SUB_MONO;
4056                         call_i2c_clients(usbvision,VIDIOC_G_TUNER,&status);
4057                         vt->signal = status.signal;
4058
4059                         PDEBUG(DBG_IOCTL, "VIDIOC_G_TUNER");
4060                         return 0;
4061                 }
4062                 case VIDIOC_S_TUNER:
4063                 {
4064                         struct v4l2_tuner *vt = arg;
4065
4066                         // Only no or one tuner for now
4067                         if (!usbvision->have_tuner || vt->index)
4068                                 return -EINVAL;
4069                         // FIXME     vt->audmode Radio mode (STEREO/MONO/...)
4070                         // vt->reserved Radio freq
4071                         // usbvision_muxsel(usbvision, vt->index, vt->mode);
4072                         PDEBUG(DBG_IOCTL, "VIDIOC_S_TUNER");
4073                         return 0;
4074                 }
4075                 case VIDIOC_G_FREQUENCY:
4076                 {
4077                         struct v4l2_frequency *freq = arg;
4078                         freq->tuner = 0; // Only one tuner
4079                         freq->type = V4L2_TUNER_ANALOG_TV;
4080                         freq->frequency = usbvision->freq;
4081                         PDEBUG(DBG_IOCTL, "VIDIOC_G_FREQUENCY freq=0x%X", (unsigned)freq->frequency);
4082                         return 0;
4083                 }
4084                 case VIDIOC_S_FREQUENCY:
4085                 {
4086                         struct v4l2_frequency *freq = arg;
4087                         usbvision->freq = freq->frequency;
4088                         call_i2c_clients(usbvision, cmd, freq);
4089                         PDEBUG(DBG_IOCTL, "VIDIOC_S_FREQUENCY freq=0x%X", (unsigned)freq->frequency);
4090                         return 0;
4091                 }
4092                 case VIDIOC_G_AUDIO:
4093                 {
4094                         struct v4l2_audio *v = arg;
4095                         memset(v,0, sizeof(v));
4096                         strcpy(v->name, "TV");
4097                         PDEBUG(DBG_IOCTL, "VIDIOC_G_AUDIO");
4098                         // FIXME: no more processings ???
4099                         return 0;
4100                 }
4101                 case VIDIOC_S_AUDIO:
4102                 {
4103                         struct v4l2_audio *v = arg;
4104                         if(v->index) {
4105                                 return -EINVAL;
4106                         }
4107                         PDEBUG(DBG_IOCTL, "VIDIOC_S_AUDIO");
4108                         // FIXME: void function ???
4109                         return 0;
4110                 }
4111                 case VIDIOC_QUERYCTRL:
4112                 {
4113                         struct v4l2_queryctrl *qc = arg;
4114                         switch(qc->id) {
4115                         case V4L2_CID_BRIGHTNESS:
4116                         case V4L2_CID_HUE:
4117                         case V4L2_CID_SATURATION:
4118                         case V4L2_CID_CONTRAST:
4119                         case V4L2_CID_AUDIO_VOLUME:
4120                         case V4L2_CID_AUDIO_MUTE:
4121                                 return v4l2_ctrl_query_fill_std(qc);
4122                                 break;
4123                         default:
4124                                 return -EINVAL;
4125                         }
4126                         return 0;
4127                 }
4128                 case VIDIOC_G_CTRL:
4129                 {
4130                         struct v4l2_control *ctrl = arg;
4131
4132                         switch (ctrl->id) {
4133                         case V4L2_CID_BRIGHTNESS:
4134                                 ctrl->value = usbvision->brightness;
4135                                 break;
4136                         case V4L2_CID_CONTRAST:
4137                                 ctrl->value = usbvision->contrast;
4138                                 break;
4139                         case V4L2_CID_SATURATION:
4140                                 ctrl->value = usbvision->saturation;
4141                                 break;
4142                         case V4L2_CID_HUE:
4143                                 ctrl->value = usbvision->hue;
4144                                 break;
4145                         case V4L2_CID_AUDIO_VOLUME:
4146                                 /*      ctrl->value = usbvision->volume; */
4147                                 break;
4148                         case V4L2_CID_AUDIO_MUTE:
4149                                 ctrl->value = usbvision->AudioMute;
4150                                 break;
4151                         default:
4152                                 return -EINVAL;
4153                         }
4154                         PDEBUG(DBG_IOCTL, "VIDIOC_G_CTRL id=%x value=%x",ctrl->id,ctrl->value);
4155                         return 0;
4156                 }
4157                 case VIDIOC_S_CTRL:
4158                 {
4159                         struct v4l2_control *ctrl = arg;
4160                         PDEBUG(DBG_IOCTL, "VIDIOC_S_CTRL id=%x value=%x",ctrl->id,ctrl->value);
4161                         call_i2c_clients(usbvision, VIDIOC_S_CTRL, ctrl);
4162                         return 0;
4163                 }
4164                 case VIDIOC_REQBUFS:
4165                 {
4166                         struct v4l2_requestbuffers *vr = arg;
4167                         // FIXME : normally we allocate the requested number of buffers.
4168                         // this driver allocates statically the buffers.
4169                         vr->count = 2;
4170                         if(vr->memory != V4L2_MEMORY_MMAP)
4171                                 return -EINVAL;
4172                         return 0;
4173                 }
4174                 case VIDIOC_QUERYBUF:
4175                 {
4176                         struct v4l2_buffer *vb = arg;
4177                         struct usbvision_frame *frame;
4178
4179                         // FIXME : works only on VIDEO_CAPTURE MODE, MMAP.
4180                         if(vb->type != V4L2_CAP_VIDEO_CAPTURE) {
4181                                 return -EINVAL;
4182                         }
4183                         if(vb->index>1)  {
4184                                 return -EINVAL;
4185                         }
4186                         vb->flags = 0;
4187                         frame = &usbvision->frame[vb->index];
4188                         if(frame->grabstate == FrameState_Grabbing)
4189                                 vb->flags |= V4L2_BUF_FLAG_QUEUED;
4190                         if(frame->grabstate >= FrameState_Done)
4191                                 vb->flags |= V4L2_BUF_FLAG_DONE;
4192                         if(frame->grabstate == FrameState_Unused)
4193                                 vb->flags |= V4L2_BUF_FLAG_MAPPED;
4194                         vb->memory = V4L2_MEMORY_MMAP;
4195                         if(vb->index == 0) {
4196                                 vb->m.offset = 0;
4197                         }
4198                         else {
4199                                 vb->m.offset = MAX_FRAME_SIZE;
4200                         }
4201                         vb->length = MAX_FRAME_SIZE;
4202                         vb->timestamp = usbvision->frame[vb->index].timestamp;
4203                         vb->sequence = usbvision->frame_num;
4204                         return 0;
4205                 }
4206                 case VIDIOC_QBUF: // VIDIOCMCAPTURE + VIDIOCSYNC
4207                 {
4208                         struct v4l2_buffer *vb = arg;
4209                         struct usbvision_frame *frame;
4210
4211                         // FIXME : works only on VIDEO_CAPTURE MODE, MMAP.
4212                         if(vb->type != V4L2_CAP_VIDEO_CAPTURE) {
4213                                 return -EINVAL;
4214                         }
4215                         if(vb->index>1)  {
4216                                 return -EINVAL;
4217                         }
4218
4219                         frame = &usbvision->frame[vb->index];
4220
4221                         if (frame->grabstate == FrameState_Grabbing) {
4222                                 return -EBUSY;
4223                         }
4224
4225                         usbvision_set_output(usbvision, usbvision->curwidth, usbvision->curheight);
4226
4227                         /* Mark it as ready */
4228                         frame->grabstate = FrameState_Ready;
4229                         vb->flags &= ~V4L2_BUF_FLAG_DONE;
4230
4231                         /* set v4l2_format index */
4232                         frame->v4l2_format = usbvision->palette;
4233
4234                         return usbvision_new_frame(usbvision, vb->index);
4235                 }
4236                 case VIDIOC_DQBUF:
4237                 {
4238                         struct v4l2_buffer *vb = arg;
4239                         int errCode = 0;
4240
4241                         DECLARE_WAITQUEUE(wait, current);
4242                         // FIXME : not the proper way to get the last filled frame
4243                         vb->index=-1;
4244                         if(usbvision->curFrameNum != -1) vb->index=usbvision->curFrameNum;
4245                         else {
4246                                 if(usbvision->frame[1].grabstate >= FrameState_Done)
4247                                         vb->index = 1;
4248                                 else if(usbvision->frame[0].grabstate >= FrameState_Done)
4249                                         vb->index = 0;
4250                                 // If no FRAME_DONE, look for a FRAME_GRABBING state.
4251                                 // See if a frame is in process (grabbing), then use it.
4252                                 if (vb->index == -1) {
4253                                         if (usbvision->frame[1].grabstate == FrameState_Grabbing)
4254                                                 vb->index = 1;
4255                                         else if (usbvision->frame[0].grabstate == FrameState_Grabbing)
4256                                                 vb->index = 0;
4257                                 }
4258                         }
4259                         if (vb->index == -1)
4260                                 return -EINVAL;
4261
4262                         PDEBUG(DBG_IOCTL, "VIDIOC_DQBUF frame=%d, grabstate=%d",
4263                                        vb->index, usbvision->frame[vb->index].grabstate);
4264
4265                         switch (usbvision->frame[vb->index].grabstate) {
4266                         case FrameState_Unused:
4267                                 errCode = -EINVAL;
4268                                 break;
4269                         case FrameState_Grabbing:
4270                                 add_wait_queue(&usbvision->frame[vb->index].wq, &wait);
4271                                 current->state = TASK_INTERRUPTIBLE;
4272                                 while (usbvision->frame[vb->index].grabstate == FrameState_Grabbing) {
4273                                         schedule();
4274                                         if (signal_pending(current)) {
4275                                                 remove_wait_queue(&usbvision->frame[vb->index].wq, &wait);
4276                                                 current->state = TASK_RUNNING;
4277                                                 return -EINTR;
4278                                         }
4279                                 }
4280                                 remove_wait_queue(&usbvision->frame[vb->index].wq, &wait);
4281                                 current->state = TASK_RUNNING;
4282                         case FrameState_Ready:
4283                         case FrameState_Error:
4284                         case FrameState_Done:
4285                                 errCode = (usbvision->frame[vb->index].grabstate == FrameState_Error) ? -EIO : 0;
4286                                 vb->memory = V4L2_MEMORY_MMAP;
4287                                 vb->flags = V4L2_BUF_FLAG_MAPPED | V4L2_BUF_FLAG_QUEUED | V4L2_BUF_FLAG_DONE;
4288                                 vb->sequence = usbvision->frame[vb->index].sequence;
4289                                 usbvision->frame[vb->index].grabstate = FrameState_Unused;
4290                                 break;
4291                         }
4292
4293                         usbvision->frame[vb->index].grabstate = FrameState_Unused;
4294                         return errCode;
4295                 }
4296                 case VIDIOC_STREAMON:
4297                 {
4298                         int b=V4L2_BUF_TYPE_VIDEO_CAPTURE;
4299                         call_i2c_clients(usbvision,VIDIOC_STREAMON , &b);      
4300                         return 0;
4301                 }
4302                 case VIDIOC_STREAMOFF:
4303                 {
4304                         int b=V4L2_BUF_TYPE_VIDEO_CAPTURE;
4305                         down(&usbvision->lock);
4306                         // Stop all video streamings
4307                         call_i2c_clients(usbvision,VIDIOC_STREAMOFF , &b);
4308                         usbvision->frame_num = -1;
4309                         usbvision->frame[0].grabstate = FrameState_Unused;
4310                         usbvision->frame[1].grabstate = FrameState_Unused;
4311                         up(&usbvision->lock);
4312                         return 0;
4313                 }
4314                 case VIDIOC_G_FBUF:
4315                 {
4316                         struct v4l2_framebuffer *vb = arg;
4317
4318                         if (dga) {
4319                                 *vb = usbvision->vid_buf;
4320                         }
4321                         else {
4322                                 memset(vb, 0, sizeof(vb)); //dga not supported, not used
4323                         }
4324                         PDEBUG(DBG_IOCTL, "VIDIOC_G_FBUF base=%p, width=%d, height=%d, pixelformat=%d, bpl=%d",
4325                                vb->base, vb->fmt.width, vb->fmt.height, vb->fmt.pixelformat,vb->fmt.bytesperline);
4326                         return 0;
4327                 }
4328                 case VIDIOC_S_FBUF:
4329                 {
4330                         struct v4l2_framebuffer *vb = arg;
4331                         int formatIdx;
4332
4333                         if (dga == 0) {
4334                                 return -EINVAL;
4335                         }
4336
4337                         if(!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_ADMIN)) {
4338                                 return -EPERM;
4339                         }
4340
4341                         PDEBUG(DBG_IOCTL, "VIDIOC_S_FBUF base=%p, width=%d, height=%d, pixelformat=%d, bpl=%d",
4342                                vb->base, vb->fmt.width, vb->fmt.height, vb->fmt.pixelformat,vb->fmt.bytesperline);
4343
4344                         for (formatIdx=0; formatIdx <= USBVISION_SUPPORTED_PALETTES; formatIdx++) {
4345                                 if (formatIdx == USBVISION_SUPPORTED_PALETTES) {
4346                                         return -EINVAL; // no matching video_format
4347                                 }
4348                                 if ((vb->fmt.pixelformat == usbvision_v4l2_format[formatIdx].format) &&
4349                                     (usbvision_v4l2_format[formatIdx].supported)) {
4350                                         break; //found matching video_format
4351                                 }
4352                         }
4353
4354                         if (vb->fmt.bytesperline<1) {
4355                                 return -EINVAL;
4356                         }
4357                         if (usbvision->overlay) {
4358                                 return -EBUSY;
4359                         }
4360                         down(&usbvision->lock);
4361                         if (usbvision->overlay_base) {
4362                                 iounmap(usbvision->overlay_base);
4363                                 usbvision->vid_buf_valid = 0;
4364                         }
4365                         usbvision->overlay_base = ioremap((ulong)vb->base, vb->fmt.height * vb->fmt.bytesperline);
4366                         if (usbvision->overlay_base) {
4367                                 usbvision->vid_buf_valid = 1;
4368                         }
4369                         usbvision->vid_buf = *vb;
4370                         usbvision->overlay_frame.v4l2_format = usbvision_v4l2_format[formatIdx];
4371                         up(&usbvision->lock);
4372                         return 0;
4373                 }
4374                 case VIDIOC_ENUM_FMT:
4375                 {
4376                         struct v4l2_fmtdesc *vfd = arg;
4377                         if ( (dga == 0) &&
4378                              (vfd->type == V4L2_BUF_TYPE_VIDEO_OVERLAY) &&
4379                              (usbvision->palette.format != V4L2_PIX_FMT_YVU420) &&
4380                              (usbvision->palette.format != V4L2_PIX_FMT_YUV422P) ) { 
4381                                 return -EINVAL;
4382                         }
4383                         if(vfd->index>=USBVISION_SUPPORTED_PALETTES-1) {
4384                                 return -EINVAL;
4385                         }
4386                         vfd->flags = 0;
4387                         strcpy(vfd->description,usbvision_v4l2_format[vfd->index].desc);
4388                         vfd->pixelformat = usbvision_v4l2_format[vfd->index].format;
4389                         return 0;
4390                 }
4391                 case VIDIOC_G_FMT:
4392                 {
4393                         struct v4l2_format *vf = arg;
4394       
4395                         if ( (dga == 0) &&
4396                              (vf->type == V4L2_BUF_TYPE_VIDEO_OVERLAY) &&
4397                              (usbvision->palette.format != V4L2_PIX_FMT_YVU420) &&
4398                              (usbvision->palette.format != V4L2_PIX_FMT_YUV422P) ) { 
4399                                 return -EINVAL;
4400                         }
4401                         down(&usbvision->lock);
4402                         *vf = usbvision->vid_win;
4403                         up(&usbvision->lock);
4404                         PDEBUG(DBG_IOCTL, "VIDIOC_G_FMT x=%d, y=%d, w=%d, h=%d, chroma=%x, clips=%d",
4405                                vf->fmt.win.w.left, vf->fmt.win.w.top, vf->fmt.win.w.width, vf->fmt.win.w.height, vf->fmt.win.chromakey, vf->fmt.win.clipcount);
4406                         return 0;
4407                 }
4408                 case VIDIOC_S_FMT:
4409                 {
4410                         struct v4l2_format *vf = arg;
4411                         struct v4l2_clip *vc=NULL;
4412                         int on,formatIdx;
4413
4414                         if ( (dga == 0) &&
4415                              (vf->type == V4L2_BUF_TYPE_VIDEO_OVERLAY) &&
4416                              (usbvision->palette.format != V4L2_PIX_FMT_YVU420) &&
4417                              (usbvision->palette.format != V4L2_PIX_FMT_YUV422P) ) { 
4418                                 return -EINVAL;
4419                         }
4420                         if(vf->type == V4L2_BUF_TYPE_VIDEO_OVERLAY) {
4421                                 if (vf->fmt.win.clipcount>256) {
4422                                         return -EDOM;   /* Too many clips! */
4423                                 }
4424                                 // Do every clips.
4425                                 vc = vmalloc(sizeof(struct v4l2_clip)*(vf->fmt.win.clipcount+4));
4426                                 if (vc == NULL) {
4427                                         return -ENOMEM;
4428                                 }
4429                                 if (vf->fmt.win.clipcount && copy_from_user(vc,vf->fmt.win.clips,sizeof(struct v4l2_clip)*vf->fmt.win.clipcount)) {
4430                                         return -EFAULT;
4431                                 }
4432                                 on = usbvision->overlay;        // Save overlay state
4433                                 if (on) {
4434                                         usbvision_cap(usbvision, 0);
4435                                 }
4436
4437                                 // strange, it seems xawtv sometimes calls us with 0
4438                                 // width and/or height. Ignore these values
4439                                 if (vf->fmt.win.w.left == 0) {
4440                                         vf->fmt.win.w.left = usbvision->vid_win.fmt.win.w.left;
4441                                 }
4442                                 if (vf->fmt.win.w.top == 0) {
4443                                         vf->fmt.win.w.top = usbvision->vid_win.fmt.win.w.top;
4444                                 }
4445
4446                                 // by now we are committed to the new data...
4447                                 down(&usbvision->lock);
4448                                 RESTRICT_TO_RANGE(vf->fmt.win.w.width, MIN_FRAME_WIDTH, MAX_FRAME_WIDTH);
4449                                 RESTRICT_TO_RANGE(vf->fmt.win.w.height, MIN_FRAME_HEIGHT, MAX_FRAME_HEIGHT);
4450                                 usbvision->vid_win = *vf;
4451                                 usbvision->overlay_frame.width = vf->fmt.win.w.width;
4452                                 usbvision->overlay_frame.height = vf->fmt.win.w.height;
4453                                 usbvision_set_output(usbvision, vf->fmt.win.w.width, vf->fmt.win.w.height);
4454                                 up(&usbvision->lock);
4455
4456                                 // Impose display clips
4457                                 if (vf->fmt.win.w.left+vf->fmt.win.w.width > (unsigned int)usbvision->vid_buf.fmt.width) {
4458                                         usbvision_new_clip(vf, vc, usbvision->vid_buf.fmt.width-vf->fmt.win.w.left, 0, vf->fmt.win.w.width-1, vf->fmt.win.w.height-1);
4459                                 }
4460                                 if (vf->fmt.win.w.top+vf->fmt.win.w.height > (unsigned int)usbvision->vid_buf.fmt.height) {
4461                                         usbvision_new_clip(vf, vc, 0, usbvision->vid_buf.fmt.height-vf->fmt.win.w.top, vf->fmt.win.w.width-1, vf->fmt.win.w.height-1);
4462                                 }
4463
4464                                 // built the requested clipping zones
4465                                 usbvision_built_overlay(usbvision, vf->fmt.win.clipcount, vc);
4466                                 vfree(vc);
4467
4468                                 // restore overlay state
4469                                 if (on) {
4470                                         usbvision_cap(usbvision, 1);
4471                                 }
4472                                 usbvision->vid_win_valid = 1;
4473                                 PDEBUG(DBG_IOCTL, "VIDIOC_S_FMT overlay x=%d, y=%d, w=%d, h=%d, chroma=%x, clips=%d",
4474                                        vf->fmt.win.w.left, vf->fmt.win.w.top, vf->fmt.win.w.width, vf->fmt.win.w.height, vf->fmt.win.chromakey, vf->fmt.win.clipcount);
4475                         }
4476                         else {
4477                                 /* Find requested format in available ones */
4478                                 for(formatIdx=0;formatIdx<USBVISION_SUPPORTED_PALETTES;formatIdx++) {
4479                                         if(vf->fmt.pix.pixelformat == usbvision_v4l2_format[formatIdx].format) {
4480                                                 usbvision->palette = usbvision_v4l2_format[formatIdx];
4481                                                 break;
4482                                         }
4483                                 }
4484                                 /* robustness */
4485                                 if(formatIdx == USBVISION_SUPPORTED_PALETTES) {
4486                                         return -EINVAL;
4487                                 }
4488                                 usbvision->vid_win.fmt.pix.pixelformat = vf->fmt.pix.pixelformat;
4489                                 usbvision->vid_win.fmt.pix.width = vf->fmt.pix.width; //Image width in pixels.
4490                                 usbvision->vid_win.fmt.pix.height = vf->fmt.pix.height; // Image height in pixels.
4491
4492                                 // by now we are committed to the new data...
4493                                 down(&usbvision->lock);
4494                                 RESTRICT_TO_RANGE(vf->fmt.pix.width, MIN_FRAME_WIDTH, MAX_FRAME_WIDTH);
4495                                 RESTRICT_TO_RANGE(vf->fmt.pix.height, MIN_FRAME_HEIGHT, MAX_FRAME_HEIGHT);
4496                                 usbvision->vid_win = *vf;
4497                                 usbvision_set_output(usbvision, vf->fmt.pix.width, vf->fmt.pix.height);
4498                                 up(&usbvision->lock);
4499
4500                                 usbvision->vid_win_valid = 1;
4501                                 PDEBUG(DBG_IOCTL, "VIDIOC_S_FMT grabdisplay w=%d, h=%d, ",
4502                                        vf->fmt.pix.width, vf->fmt.pix.height);
4503                         }
4504                         return 0;
4505                 }
4506                 case VIDIOC_OVERLAY:
4507                 {
4508                         int *v = arg;
4509       
4510                         if ( (dga == 0) &&
4511                              (usbvision->palette.format != V4L2_PIX_FMT_YVU420) &&
4512                              (usbvision->palette.format != V4L2_PIX_FMT_YUV422P) ) { 
4513                                 PDEBUG(DBG_IOCTL, "VIDIOC_OVERLAY  DGA disabled");
4514                                 return -EINVAL;
4515                         }
4516
4517                         if (*v == 0) {
4518                                 usbvision_cap(usbvision, 0);
4519                         }
4520                         else {
4521                                 // are VIDIOCSFBUF and VIDIOCSWIN done?
4522                                 if ((usbvision->vid_buf_valid == 0) || (usbvision->vid_win_valid == 0)) {
4523                                         PDEBUG(DBG_IOCTL, "VIDIOC_OVERLAY  vid_buf_valid %d; vid_win_valid %d",
4524                                                usbvision->vid_buf_valid, usbvision->vid_win_valid);
4525                                         return -EINVAL;
4526                                 }
4527                                 usbvision_cap(usbvision, 1);
4528                         }
4529                         PDEBUG(DBG_IOCTL, "VIDIOC_OVERLAY %s", (*v)?"on":"off");
4530                         return 0;
4531                 }
4532                 default:
4533                         return -ENOIOCTLCMD;
4534         }
4535         return 0;
4536 }
4537
4538 static int usbvision_v4l2_ioctl(struct inode *inode, struct file *file,
4539                        unsigned int cmd, unsigned long arg)
4540 {
4541         return video_usercopy(inode, file, cmd, arg, usbvision_v4l2_do_ioctl);
4542 }
4543
4544
4545 static ssize_t usbvision_v4l2_read(struct file *file, char *buf,
4546                       size_t count, loff_t *ppos)
4547 {
4548         struct video_device *dev = video_devdata(file);
4549         struct usb_usbvision *usbvision = (struct usb_usbvision *) video_get_drvdata(dev);
4550         int noblock = file->f_flags & O_NONBLOCK;
4551
4552         int frmx = -1;
4553         int rc = 0;
4554         struct usbvision_frame *frame;
4555
4556         PDEBUG(DBG_IO, "%s: %ld bytes, noblock=%d", __FUNCTION__, (unsigned long)count, noblock);
4557
4558         if (!USBVISION_IS_OPERATIONAL(usbvision) || (buf == NULL))
4559                 return -EFAULT;
4560
4561         down(&usbvision->lock);
4562         //code for testing compression
4563         if (usbvision->isocMode == ISOC_MODE_COMPRESS) {
4564           usbvision->frame[0].v4l2_format = usbvision_v4l2_format[0]; //V4L2_PIX_FMT_GREY;
4565           usbvision->frame[1].v4l2_format = usbvision_v4l2_format[0]; // V4L2_PIX_FMT_GREY;
4566         }
4567
4568         // See if a frame is completed, then use it.
4569         if (usbvision->frame[0].grabstate >= FrameState_Done) // _Done or _Error
4570                 frmx = 0;
4571         else if (usbvision->frame[1].grabstate >= FrameState_Done)// _Done or _Error
4572                 frmx = 1;
4573
4574         if (noblock && (frmx == -1)) {
4575                 count = -EAGAIN;
4576                 goto usbvision_v4l2_read_done;
4577         }
4578
4579         // If no FRAME_DONE, look for a FRAME_GRABBING state.
4580         // See if a frame is in process (grabbing), then use it.
4581         if (frmx == -1) {
4582                 if (usbvision->frame[0].grabstate == FrameState_Grabbing)
4583                         frmx = 0;
4584                 else if (usbvision->frame[1].grabstate == FrameState_Grabbing)
4585                         frmx = 1;
4586         }
4587
4588         // If no frame is active, start one.
4589         if (frmx == -1)
4590                 usbvision_new_frame(usbvision, frmx = 0);
4591
4592         frame = &usbvision->frame[frmx];
4593
4594       restart:
4595         if (!USBVISION_IS_OPERATIONAL(usbvision)) {
4596                 count = -EIO;
4597                 goto usbvision_v4l2_read_done;
4598         }
4599         PDEBUG(DBG_IO, "Waiting frame grabbing");
4600         rc = wait_event_interruptible(frame->wq, (frame->grabstate == FrameState_Done) || 
4601                                                  (frame->grabstate == FrameState_Error));
4602         if (rc) {
4603                 goto usbvision_v4l2_read_done;
4604         }
4605
4606         if (frame->grabstate == FrameState_Error) {
4607                 frame->bytes_read = 0;
4608                 if (usbvision_new_frame(usbvision, frmx)) {
4609                         err("%s: usbvision_new_frame() failed", __FUNCTION__);
4610                 }
4611                 goto restart;
4612         }
4613
4614         PDEBUG(DBG_IO, "%s: frmx=%d, bytes_read=%ld, scanlength=%ld", __FUNCTION__,
4615                        frmx, frame->bytes_read, frame->scanlength);
4616
4617         /* copy bytes to user space; we allow for partials reads */
4618         if ((count + frame->bytes_read) > (unsigned long)frame->scanlength)
4619                 count = frame->scanlength - frame->bytes_read;
4620
4621         if (copy_to_user(buf, frame->data + frame->bytes_read, count)) {
4622                 count = -EFAULT;
4623                 goto usbvision_v4l2_read_done;
4624         }
4625
4626         frame->bytes_read += count;
4627         PDEBUG(DBG_IO, "%s: {copy} count used=%ld, new bytes_read=%ld", __FUNCTION__,
4628                        (unsigned long)count, frame->bytes_read);
4629
4630         if (frame->bytes_read >= frame->scanlength) {// All data has been read
4631                 frame->bytes_read = 0;
4632
4633                 /* Mark it as available to be used again. */
4634                 usbvision->frame[frmx].grabstate = FrameState_Unused;
4635                 if (usbvision_new_frame(usbvision, frmx ? 0 : 1))
4636                         err("%s: usbvision_new_frame() failed", __FUNCTION__);
4637         }
4638
4639 usbvision_v4l2_read_done:
4640         up(&usbvision->lock);
4641         return count;
4642 }
4643
4644 static int usbvision_v4l2_mmap(struct file *file, struct vm_area_struct *vma)
4645 {
4646         struct video_device *dev = video_devdata(file);
4647         struct usb_usbvision *usbvision = (struct usb_usbvision *) video_get_drvdata(dev);
4648         unsigned long start = vma->vm_start;
4649         unsigned long size  = vma->vm_end-vma->vm_start;
4650
4651         unsigned long page, pos;
4652
4653         if (!USBVISION_IS_OPERATIONAL(usbvision))
4654                 return -EFAULT;
4655
4656         if (size > (((USBVISION_NUMFRAMES * usbvision->max_frame_size) + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1)))
4657                 return -EINVAL;
4658
4659         pos = (unsigned long) usbvision->fbuf;
4660         while (size > 0) {
4661                 
4662 // Really ugly....
4663         #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,10)                           //Compatibility for 2.6.10+ kernels
4664                 page = vmalloc_to_pfn((void *)pos);
4665                 if (remap_pfn_range(vma, start, page, PAGE_SIZE, PAGE_SHARED)) { 
4666                         return -EAGAIN;
4667                 }
4668         #else                                                                      //Compatibility for 2.6.0 - 2.6.9 kernels
4669                 page = usbvision_kvirt_to_pa(pos);
4670                 if (remap_page_range(vma, start, page, PAGE_SIZE, PAGE_SHARED)) {
4671                         return -EAGAIN;
4672                 }
4673         #endif
4674                 start += PAGE_SIZE;
4675                 pos += PAGE_SIZE;
4676                 if (size > PAGE_SIZE)
4677                         size -= PAGE_SIZE;
4678                 else
4679                         size = 0;
4680         }
4681
4682         return 0;
4683 }
4684
4685
4686 /*
4687  * Here comes the stuff for radio on usbvision based devices
4688  *
4689  */
4690 static int usbvision_radio_open(struct inode *inode, struct file *file)
4691 {
4692         struct video_device *dev = video_devdata(file);
4693         struct usb_usbvision *usbvision = (struct usb_usbvision *) video_get_drvdata(dev);
4694         struct v4l2_frequency freq;
4695         int errCode = 0;
4696
4697         PDEBUG(DBG_RIO, "%s:", __FUNCTION__);
4698
4699         down(&usbvision->lock);
4700
4701         if (usbvision->user) {
4702                 err("%s: Someone tried to open an already opened USBVision Radio!", __FUNCTION__);
4703                 errCode = -EBUSY;
4704         }
4705         else {
4706                 if(PowerOnAtOpen) {
4707                         if (timer_pending(&usbvision->powerOffTimer)) {
4708                                 del_timer(&usbvision->powerOffTimer);
4709                         }
4710                         if (usbvision->power == 0) {
4711                                 usbvision_power_on(usbvision);
4712                                 usbvision_init_i2c(usbvision);
4713                         }
4714                 }
4715
4716                 // If so far no errors then we shall start the radio
4717                 usbvision->radio = 1;
4718                 call_i2c_clients(usbvision,AUDC_SET_RADIO,&usbvision->tuner_type);
4719                 freq.frequency = 1517; //SWR3 @ 94.8MHz
4720                 call_i2c_clients(usbvision, VIDIOC_S_FREQUENCY, &freq);
4721                 usbvision_set_audio(usbvision, USBVISION_AUDIO_RADIO);
4722                 usbvision->user++;
4723         }
4724
4725         if (errCode) {
4726                 if (PowerOnAtOpen) {
4727                         usbvision_i2c_usb_del_bus(&usbvision->i2c_adap);
4728                         usbvision_power_off(usbvision);
4729                         usbvision->initialized = 0;
4730                 }
4731         }
4732         up(&usbvision->lock);
4733         return errCode;
4734 }
4735
4736
4737 static int usbvision_radio_close(struct inode *inode, struct file *file)
4738 {
4739         struct video_device *dev = video_devdata(file);
4740         struct usb_usbvision *usbvision = (struct usb_usbvision *) video_get_drvdata(dev);
4741         int errCode = 0;
4742
4743         PDEBUG(DBG_RIO, "");
4744
4745         down(&usbvision->lock);
4746
4747         usbvision_audio_off(usbvision);
4748         usbvision->radio=0;
4749         usbvision->user--;
4750
4751         if (PowerOnAtOpen) {
4752                 mod_timer(&usbvision->powerOffTimer, jiffies + USBVISION_POWEROFF_TIME);
4753                 usbvision->initialized = 0;
4754         }
4755
4756         up(&usbvision->lock);
4757
4758         if (usbvision->remove_pending) {
4759                 info("%s: Final disconnect", __FUNCTION__);
4760                 usbvision_release(usbvision);
4761         }
4762
4763
4764         PDEBUG(DBG_RIO, "success");
4765
4766         return errCode;
4767 }
4768
4769 static int usbvision_do_radio_ioctl(struct inode *inode, struct file *file,
4770                                  unsigned int cmd, void *arg)
4771 {
4772         struct video_device *dev = video_devdata(file);
4773         struct usb_usbvision *usbvision = (struct usb_usbvision *) video_get_drvdata(dev);
4774
4775         if (!USBVISION_IS_OPERATIONAL(usbvision))
4776                 return -EIO;
4777
4778         switch (cmd) {
4779                 /***************************
4780                  * V4L2 IOCTLs             *
4781                  ***************************/
4782                 case VIDIOC_QUERYCAP:
4783                 {
4784                         struct v4l2_capability *vc=arg;
4785                         memset(vc, 0, sizeof(struct v4l2_capability));
4786                         strcpy(vc->driver,"usbvision radio");
4787                         strcpy(vc->card,usbvision->vcap.card);
4788                         strcpy(vc->bus_info,"usb");
4789                         vc->version = USBVISION_DRIVER_VERSION;             /* version */
4790                         vc->capabilities = V4L2_CAP_TUNER;          /* capabilities */
4791                         PDEBUG(DBG_RIO, "%s: VIDIOC_QUERYCAP", __FUNCTION__);
4792                         return 0;
4793                 }
4794                 case VIDIOC_QUERYCTRL:
4795                 {
4796                         struct v4l2_queryctrl *qc = arg;
4797                         switch(qc->id)
4798                                 {
4799                                 case V4L2_CID_AUDIO_VOLUME:
4800                                 case V4L2_CID_AUDIO_MUTE:
4801                                         return v4l2_ctrl_query_fill_std(qc);
4802                                         break;
4803                                 default:
4804                                         return -EINVAL;
4805                                 }
4806                         return 0;
4807                 }
4808                 case VIDIOC_G_CTRL:
4809                 {
4810                         struct v4l2_control *ctrl = arg;
4811                         PDEBUG(DBG_IOCTL, "VIDIOC_G_CTRL id=%x value=%x",ctrl->id,ctrl->value);
4812                         switch(ctrl->id) {
4813                         case V4L2_CID_AUDIO_VOLUME:
4814                                 /*      ctrl->value = usbvision->volume; */
4815                                 break;
4816                         case V4L2_CID_AUDIO_MUTE:
4817                                 ctrl->value = usbvision->AudioMute;
4818                                 break;
4819                         default:
4820                                 return -EINVAL;
4821                         }
4822                         return 0;
4823                 }
4824                 case VIDIOC_S_CTRL:
4825                 {
4826                         struct v4l2_control *ctrl = arg;
4827                         call_i2c_clients(usbvision, VIDIOC_S_CTRL, ctrl);
4828
4829                         PDEBUG(DBG_RIO, "%s: VIDIOC_S_CTRL id=%x value=%x", __FUNCTION__,ctrl->id,ctrl->value);
4830                         return 0;
4831                 }
4832                 case VIDIOC_G_TUNER:
4833                 {
4834                         struct v4l2_tuner *vt = arg;
4835
4836                         if (!usbvision->have_tuner || vt->index)        // Only tuner 0
4837                                 return -EINVAL;
4838                         strcpy(vt->name, "Radio");
4839                         vt->type = V4L2_TUNER_RADIO;
4840                         vt->capability = V4L2_TUNER_CAP_STEREO;
4841                         // japan:          76.0 MHz -  89.9 MHz
4842                         // western europe: 87.5 MHz - 108.0 MHz
4843                         // russia:         65.0 MHz - 108.0 MHz
4844                         vt->rangelow = (int)(65*16);;
4845                         vt->rangehigh = (int)(108*16);
4846                         vt->audmode = V4L2_TUNER_MODE_STEREO;
4847                         vt->rxsubchans = V4L2_TUNER_SUB_STEREO;
4848                         call_i2c_clients(usbvision,VIDIOC_G_TUNER,&vt);
4849
4850                         PDEBUG(DBG_RIO, "%s: VIDIOC_G_TUNER signal=%d", __FUNCTION__, vt->signal);
4851                         return 0;
4852                 }
4853                 case VIDIOC_S_TUNER:
4854                 {
4855                         struct v4l2_tuner *vt = arg;
4856
4857                         // Only channel 0 has a tuner
4858                         if((vt->index) || (usbvision->channel)) {
4859                                 return -EINVAL;
4860                         }
4861                         PDEBUG(DBG_RIO, "%s: VIDIOC_S_TUNER", __FUNCTION__);
4862                         return 0;
4863                 }
4864                 case VIDIOC_G_AUDIO:
4865                 {
4866                         struct v4l2_audio *va = arg;
4867                         memset(va,0, sizeof(va));
4868                         va->capability = V4L2_AUDCAP_STEREO;
4869                         strcpy(va->name, "Radio");
4870                         PDEBUG(DBG_IOCTL, "VIDIOC_G_AUDIO");
4871                         return 0;
4872                 }
4873                 case VIDIOC_S_AUDIO:
4874                 {
4875                         struct v4l2_audio *v = arg;
4876                         if(v->index) {
4877                                 return -EINVAL;
4878                         }
4879                         PDEBUG(DBG_IOCTL, "VIDIOC_S_AUDIO");
4880                         // FIXME: void function ???
4881                         return 0;
4882                 }
4883                 case VIDIOC_G_FREQUENCY:
4884                 {
4885                         struct v4l2_frequency *freq = arg;
4886                         freq->tuner = 0; // Only one tuner
4887                         freq->type = V4L2_TUNER_RADIO;
4888                         freq->frequency = usbvision->freq;
4889                         PDEBUG(DBG_RIO, "VIDIOC_G_FREQUENCY freq=0x%X", (unsigned)freq->frequency);
4890                         return 0;
4891                 }
4892                 case VIDIOC_S_FREQUENCY:
4893                 {
4894                         struct v4l2_frequency *freq = arg;
4895                         usbvision->freq = freq->frequency;
4896                         call_i2c_clients(usbvision, cmd, freq);
4897                         PDEBUG(DBG_RIO, "VIDIOC_S_FREQUENCY freq=0x%X", (unsigned)freq->frequency);
4898                         return 0;
4899                 }
4900
4901                 /***************************
4902                  * V4L1 IOCTLs             *
4903                  ***************************/
4904                 case VIDIOCGCAP:
4905                 {
4906                         struct video_capability *vc = arg;
4907
4908                         memset(vc, 0, sizeof(struct video_capability));
4909                         strcpy(vc->name,usbvision->vcap.card);
4910                         vc->type = VID_TYPE_TUNER;
4911                         vc->channels = 1;
4912                         vc->audios = 1;
4913                         PDEBUG(DBG_RIO, "%s: VIDIOCGCAP", __FUNCTION__);
4914                         return 0;
4915                 }
4916                 case VIDIOCGTUNER:
4917                 {
4918                         struct video_tuner *vt = arg;
4919
4920                         if((vt->tuner) || (usbvision->channel)) {       /* Only tuner 0 */
4921                                 return -EINVAL;
4922                         }
4923                         strcpy(vt->name, "Radio");
4924                         // japan:          76.0 MHz -  89.9 MHz
4925                         // western europe: 87.5 MHz - 108.0 MHz
4926                         // russia:         65.0 MHz - 108.0 MHz
4927                         vt->rangelow=(int)(65*16);
4928                         vt->rangehigh=(int)(108*16);
4929                         vt->flags= 0;
4930                         vt->mode = 0;
4931                         call_i2c_clients(usbvision,cmd,vt);
4932                         PDEBUG(DBG_RIO, "%s: VIDIOCGTUNER signal=%d", __FUNCTION__, vt->signal);
4933                         return 0;
4934                 }
4935                 case VIDIOCSTUNER:
4936                 {
4937                         struct video_tuner *vt = arg;
4938
4939                         // Only channel 0 has a tuner
4940                         if((vt->tuner) || (usbvision->channel)) {
4941                                 return -EINVAL;
4942                         }
4943                         PDEBUG(DBG_RIO, "%s: VIDIOCSTUNER", __FUNCTION__);
4944                         return 0;
4945                 }
4946                 case VIDIOCGAUDIO:
4947                 {
4948                         struct video_audio *va = arg;
4949                         memset(va,0, sizeof(struct video_audio));
4950                         call_i2c_clients(usbvision, cmd, va);
4951                         va->flags|=VIDEO_AUDIO_MUTABLE;
4952                         va->volume=1;
4953                         va->step=1;
4954                         strcpy(va->name, "Radio");
4955                         PDEBUG(DBG_RIO, "%s: VIDIOCGAUDIO", __FUNCTION__);
4956                         return 0;
4957                 }
4958                 case VIDIOCSAUDIO:
4959                 {
4960                         struct video_audio *va = arg;
4961                         if(va->audio) {
4962                                 return -EINVAL;
4963                         }
4964
4965                         if(va->flags & VIDEO_AUDIO_MUTE) {
4966                                 if (usbvision_audio_mute(usbvision)) {
4967                                         return -EFAULT;
4968                                 }
4969                         }
4970                         else {
4971                                 if (usbvision_audio_on(usbvision)) {
4972                                         return -EFAULT;
4973                                 }
4974                         }
4975                         PDEBUG(DBG_RIO, "%s: VIDIOCSAUDIO flags=0x%x)", __FUNCTION__, va->flags);
4976                         return 0;
4977                 }
4978                 case VIDIOCGFREQ:
4979                 {
4980                         unsigned long *freq = arg;
4981
4982                         *freq = usbvision->freq;
4983                         PDEBUG(DBG_RIO, "%s: VIDIOCGFREQ freq = %ld00 kHz", __FUNCTION__, (*freq * 10)>>4);
4984                         return 0;
4985                 }
4986                 case VIDIOCSFREQ:
4987                 {
4988                         unsigned long *freq = arg;
4989
4990                         usbvision->freq = *freq;
4991                         call_i2c_clients(usbvision, cmd, freq);
4992                         PDEBUG(DBG_RIO, "%s: VIDIOCSFREQ freq = %ld00 kHz", __FUNCTION__, (*freq * 10)>>4);
4993                         return 0;
4994                 }
4995                 default:
4996                 {
4997                         PDEBUG(DBG_RIO, "%s: Unknown command %x", __FUNCTION__, cmd);
4998                         return -ENOIOCTLCMD;
4999                 }
5000         }
5001         return 0;
5002 }
5003
5004
5005 static int usbvision_radio_ioctl(struct inode *inode, struct file *file,
5006                        unsigned int cmd, unsigned long arg)
5007 {
5008         return video_usercopy(inode, file, cmd, arg, usbvision_do_radio_ioctl);
5009 }
5010
5011
5012 /*
5013  * Here comes the stuff for vbi on usbvision based devices
5014  *
5015  */
5016 static int usbvision_vbi_open(struct inode *inode, struct file *file)
5017 {
5018         struct video_device *dev = video_devdata(file);
5019         struct usb_usbvision *usbvision = (struct usb_usbvision *) video_get_drvdata(dev);
5020         unsigned long freq;
5021         int errCode = 0;
5022
5023         PDEBUG(DBG_RIO, "%s:", __FUNCTION__);
5024
5025         down(&usbvision->lock);
5026
5027         if (usbvision->user) {
5028                 err("%s: Someone tried to open an already opened USBVision VBI!", __FUNCTION__);
5029                 errCode = -EBUSY;
5030         }
5031         else {
5032                 if(PowerOnAtOpen) {
5033                         if (timer_pending(&usbvision->powerOffTimer)) {
5034                                 del_timer(&usbvision->powerOffTimer);
5035                         }
5036                         if (usbvision->power == 0) {
5037                                 usbvision_power_on(usbvision);
5038                                 usbvision_init_i2c(usbvision);
5039                         }
5040                 }
5041
5042                 // If so far no errors then we shall start the vbi device
5043                 //usbvision->vbi = 1;
5044                 call_i2c_clients(usbvision,AUDC_SET_RADIO,&usbvision->tuner_type);
5045                 freq = 1517; //SWR3 @ 94.8MHz
5046                 call_i2c_clients(usbvision, VIDIOCSFREQ, &freq);
5047                 usbvision_set_audio(usbvision, USBVISION_AUDIO_RADIO);
5048                 usbvision->user++;
5049         }
5050
5051         if (errCode) {
5052                 if (PowerOnAtOpen) {
5053                         usbvision_i2c_usb_del_bus(&usbvision->i2c_adap);
5054                         usbvision_power_off(usbvision);
5055                         usbvision->initialized = 0;
5056                 }
5057         }
5058         up(&usbvision->lock);
5059         return errCode;
5060 }
5061
5062 static int usbvision_vbi_close(struct inode *inode, struct file *file)
5063 {
5064         struct video_device *dev = video_devdata(file);
5065         struct usb_usbvision *usbvision = (struct usb_usbvision *) video_get_drvdata(dev);
5066         int errCode = 0;
5067
5068         PDEBUG(DBG_RIO, "");
5069
5070         down(&usbvision->lock);
5071
5072         usbvision_audio_off(usbvision);
5073         usbvision->vbi=0;
5074         usbvision->user--;
5075
5076         if (PowerOnAtOpen) {
5077                 mod_timer(&usbvision->powerOffTimer, jiffies + USBVISION_POWEROFF_TIME);
5078                 usbvision->initialized = 0;
5079         }
5080
5081         up(&usbvision->lock);
5082
5083         if (usbvision->remove_pending) {
5084                 info("%s: Final disconnect", __FUNCTION__);
5085                 usbvision_release(usbvision);
5086         }
5087
5088
5089         PDEBUG(DBG_RIO, "success");
5090
5091         return errCode;
5092 }
5093
5094 static int usbvision_do_vbi_ioctl(struct inode *inode, struct file *file,
5095                                  unsigned int cmd, void *arg)
5096 {
5097         struct video_device *dev = video_devdata(file);
5098         struct usb_usbvision *usbvision = (struct usb_usbvision *) video_get_drvdata(dev);
5099
5100         if (!USBVISION_IS_OPERATIONAL(usbvision))
5101                 return -EIO;
5102
5103         switch (cmd) {
5104                 case VIDIOC_QUERYCAP:
5105                 {
5106                         struct v4l2_capability *vc=arg;
5107                         memset(vc, 0, sizeof(struct v4l2_capability));
5108                         strcpy(vc->driver,"usbvision vbi");
5109                         strcpy(vc->card,usbvision->vcap.card);
5110                         strcpy(vc->bus_info,"usb");
5111                         vc->version = USBVISION_DRIVER_VERSION;             /* version */
5112                         vc->capabilities = V4L2_CAP_VBI_CAPTURE;            /* capabilities */
5113                         PDEBUG(DBG_RIO, "%s: VIDIOC_QUERYCAP", __FUNCTION__);
5114                         return 0;
5115                 }
5116                 case VIDIOCGTUNER:
5117                 {
5118                         struct video_tuner *vt = arg;
5119
5120                         if((vt->tuner) || (usbvision->channel)) {       /* Only tuner 0 */
5121                                 return -EINVAL;
5122                         }
5123                         strcpy(vt->name, "vbi");
5124                         // japan:          76.0 MHz -  89.9 MHz
5125                         // western europe: 87.5 MHz - 108.0 MHz
5126                         // russia:         65.0 MHz - 108.0 MHz
5127                         vt->rangelow=(int)(65*16);
5128                         vt->rangehigh=(int)(108*16);
5129                         vt->flags= 0;
5130                         vt->mode = 0;
5131                         call_i2c_clients(usbvision,cmd,vt);
5132                         PDEBUG(DBG_RIO, "%s: VIDIOCGTUNER signal=%d", __FUNCTION__, vt->signal);
5133                         return 0;
5134                 }
5135                 case VIDIOCSTUNER:
5136                 {
5137                         struct video_tuner *vt = arg;
5138
5139                         // Only channel 0 has a tuner
5140                         if((vt->tuner) || (usbvision->channel)) {
5141                                 return -EINVAL;
5142                         }
5143                         PDEBUG(DBG_RIO, "%s: VIDIOCSTUNER", __FUNCTION__);
5144                         return 0;
5145                 }
5146                 case VIDIOCGAUDIO:
5147                 {
5148                         struct video_audio *va = arg;
5149                         memset(va,0, sizeof(struct video_audio));
5150                         call_i2c_clients(usbvision, cmd, va);
5151                         va->flags|=VIDEO_AUDIO_MUTABLE;
5152                         va->volume=1;
5153                         va->step=1;
5154                         strcpy(va->name, "vbi");
5155                         PDEBUG(DBG_RIO, "%s: VIDIOCGAUDIO", __FUNCTION__);
5156                         return 0;
5157                 }
5158                 case VIDIOCSAUDIO:
5159                 {
5160                         struct video_audio *va = arg;
5161                         if(va->audio) {
5162                                 return -EINVAL;
5163                         }
5164
5165                         if(va->flags & VIDEO_AUDIO_MUTE) {
5166                                 if (usbvision_audio_mute(usbvision)) {
5167                                         return -EFAULT;
5168                                 }
5169                         }
5170                         else {
5171                                 if (usbvision_audio_on(usbvision)) {
5172                                         return -EFAULT;
5173                                 }
5174                         }
5175                         PDEBUG(DBG_RIO, "%s: VIDIOCSAUDIO flags=0x%x)", __FUNCTION__, va->flags);
5176                         return 0;
5177                 }
5178                 case VIDIOCGFREQ:
5179                 {
5180                         unsigned long *freq = arg;
5181
5182                         *freq = usbvision->freq;
5183                         PDEBUG(DBG_RIO, "%s: VIDIOCGFREQ freq = %ld00 kHz", __FUNCTION__, (*freq * 10)>>4);
5184                         return 0;
5185                 }
5186                 case VIDIOCSFREQ:
5187                 {
5188                         unsigned long *freq = arg;
5189
5190                         usbvision->freq = *freq;
5191                         call_i2c_clients(usbvision, cmd, freq);
5192                         PDEBUG(DBG_RIO, "%s: VIDIOCSFREQ freq = %ld00 kHz", __FUNCTION__, (*freq * 10)>>4);
5193                         return 0;
5194                 }
5195                 default:
5196                 {
5197                         PDEBUG(DBG_RIO, "%s: Unknown command %d", __FUNCTION__, cmd);
5198                         return -ENOIOCTLCMD;
5199                 }
5200         }
5201         return 0;
5202 }
5203
5204 static int usbvision_vbi_ioctl(struct inode *inode, struct file *file,
5205                        unsigned int cmd, unsigned long arg)
5206 {
5207         return video_usercopy(inode, file, cmd, arg, usbvision_do_vbi_ioctl);
5208 }
5209
5210
5211
5212 static void usbvision_configure_video(struct usb_usbvision *usbvision)
5213 {
5214         int model;
5215
5216         if (usbvision == NULL)
5217                 return;
5218                 
5219         model = usbvision->DevModel;
5220
5221         RESTRICT_TO_RANGE(init_brightness, 0, 255);
5222         RESTRICT_TO_RANGE(init_contrast, 0, 255);
5223         RESTRICT_TO_RANGE(init_saturation, 0, 255);
5224         RESTRICT_TO_RANGE(init_hue, 0, 255);
5225         
5226         usbvision->saturation = init_saturation << 8;
5227         usbvision->hue = init_hue << 8;
5228         usbvision->brightness = init_brightness << 8;
5229         usbvision->contrast = init_contrast << 8;
5230         usbvision->depth = 24;
5231         usbvision->palette = usbvision_v4l2_format[2]; // V4L2_PIX_FMT_RGB24;
5232
5233         if (usbvision_device_data[usbvision->DevModel].Vin_Reg2 >= 0) {
5234                 usbvision->Vin_Reg2_Preset = usbvision_device_data[usbvision->DevModel].Vin_Reg2 & 0xff;
5235         } else {
5236                 usbvision->Vin_Reg2_Preset = 0;
5237         }
5238
5239         memset(&usbvision->vcap, 0, sizeof(usbvision->vcap));
5240         strcpy(usbvision->vcap.driver, "USBVision");
5241         usbvision->vcap.capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE | V4L2_CAP_STREAMING |
5242                 (dga ? (V4L2_FBUF_CAP_LIST_CLIPPING | V4L2_CAP_VIDEO_OVERLAY) : 0) |
5243                 (usbvision->have_tuner ? V4L2_CAP_TUNER : 0);
5244         usbvision->vcap.version = USBVISION_DRIVER_VERSION;         /* version */
5245
5246         usbvision->video_inputs = usbvision_device_data[model].VideoChannels;
5247
5248         memset(&usbvision->input, 0, sizeof(usbvision->input));
5249         usbvision->input.tuner = 0;
5250         usbvision->input.type = V4L2_INPUT_TYPE_TUNER|VIDEO_TYPE_CAMERA;
5251         usbvision->input.std = usbvision_device_data[model].VideoNorm;
5252
5253         /* This should be here to make i2c clients to be able to register */
5254         usbvision_audio_off(usbvision); //first switch off audio
5255         if (!PowerOnAtOpen) {
5256                 usbvision_power_on(usbvision);  //and then power up the noisy tuner
5257                 usbvision_init_i2c(usbvision);
5258         }
5259 }
5260
5261 //
5262 // Video registration stuff
5263 //
5264
5265 // Video template
5266 static struct file_operations usbvision_fops = {
5267   #if LINUX_VERSION_CODE > KERNEL_VERSION(2,4,31)
5268         .owner             = THIS_MODULE,
5269   #endif
5270         .open           = usbvision_v4l2_open,
5271         .release        = usbvision_v4l2_close,
5272         .read           = usbvision_v4l2_read,
5273         .mmap           = usbvision_v4l2_mmap,
5274         .ioctl          = usbvision_v4l2_ioctl,
5275         .llseek         = no_llseek,
5276 };
5277 static struct video_device usbvision_video_template = {
5278   #if LINUX_VERSION_CODE > KERNEL_VERSION(2,4,31)
5279         .owner             = THIS_MODULE,
5280   #endif
5281         .type           = VID_TYPE_TUNER | VID_TYPE_CAPTURE,
5282         .hardware       = VID_HARDWARE_USBVISION,
5283         .fops           = &usbvision_fops,
5284   #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
5285         .name           = "usbvision-video",
5286         .release        = video_device_release,
5287   #endif
5288         .minor          = -1,
5289 };
5290
5291
5292 // Radio template
5293 static struct file_operations usbvision_radio_fops = {
5294   #if LINUX_VERSION_CODE > KERNEL_VERSION(2,4,31)
5295         .owner             = THIS_MODULE,
5296   #endif
5297         .open           = usbvision_radio_open,
5298         .release        = usbvision_radio_close,
5299         .ioctl          = usbvision_radio_ioctl,
5300         .llseek         = no_llseek,
5301 };
5302
5303 static struct video_device usbvision_radio_template=
5304 {
5305   #if LINUX_VERSION_CODE > KERNEL_VERSION(2,4,31)
5306         .owner             = THIS_MODULE,
5307   #endif
5308         .type           = VID_TYPE_TUNER,
5309         .hardware       = VID_HARDWARE_USBVISION,
5310         .fops           = &usbvision_radio_fops,
5311   #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
5312         .release        = video_device_release,
5313         .name           = "usbvision-radio",
5314   #endif
5315         .minor          = -1,
5316 };
5317
5318
5319 // vbi template
5320 static struct file_operations usbvision_vbi_fops = {
5321   #if LINUX_VERSION_CODE > KERNEL_VERSION(2,4,31)
5322         .owner             = THIS_MODULE,
5323   #endif
5324         .open           = usbvision_vbi_open,
5325         .release        = usbvision_vbi_close,
5326         .ioctl          = usbvision_vbi_ioctl,
5327         .llseek         = no_llseek,
5328 };
5329
5330 static struct video_device usbvision_vbi_template=
5331 {
5332   #if LINUX_VERSION_CODE > KERNEL_VERSION(2,4,31)
5333         .owner             = THIS_MODULE,
5334   #endif
5335         .type           = VID_TYPE_TUNER,
5336         .hardware       = VID_HARDWARE_USBVISION,
5337         .fops           = &usbvision_vbi_fops,
5338   #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
5339         .release        = video_device_release,
5340         .name           = "usbvision-vbi",
5341   #endif
5342         .minor          = -1,
5343 };
5344
5345
5346 static struct video_device *usbvision_vdev_init(struct usb_usbvision *usbvision,
5347                                         struct video_device *vdev_template,
5348                                         char *name)
5349 {
5350         struct usb_device *usb_dev = usbvision->dev;
5351         struct video_device *vdev;
5352
5353         if (usb_dev == NULL) {
5354                 err("%s: usbvision->dev is not set", __FUNCTION__);
5355                 return NULL;
5356         }
5357
5358         vdev = video_device_alloc();
5359         if (NULL == vdev) {
5360                 return NULL;
5361         }
5362         *vdev = *vdev_template;
5363 //      vdev->minor   = -1;
5364         vdev->dev     = &usb_dev->dev;
5365         snprintf(vdev->name, sizeof(vdev->name), "%s", name);
5366         video_set_drvdata(vdev, usbvision);
5367         return vdev;
5368 }
5369
5370 // unregister video4linux devices
5371 static void usbvision_unregister_video(struct usb_usbvision *usbvision)
5372 {
5373         // vbi Device:
5374         if (usbvision->vbi) {
5375                 PDEBUG(DBG_PROBE, "unregister /dev/vbi%d [v4l2]", usbvision->vbi->minor & 0x1f);
5376                 if (usbvision->vbi->minor != -1) {
5377                         video_unregister_device(usbvision->vbi);
5378                 }
5379                 else {
5380                         video_device_release(usbvision->vbi);
5381                 }
5382                 usbvision->vbi = NULL;
5383         }
5384         
5385         // Radio Device:
5386         if (usbvision->rdev) {
5387                 PDEBUG(DBG_PROBE, "unregister /dev/radio%d [v4l2]", usbvision->rdev->minor & 0x1f);
5388                 if (usbvision->rdev->minor != -1) {
5389                         video_unregister_device(usbvision->rdev);
5390                 }
5391                 else {
5392                         video_device_release(usbvision->rdev);
5393                 }
5394                 usbvision->rdev = NULL;
5395         }
5396
5397         // Video Device:
5398         if (usbvision->vdev) {
5399                 PDEBUG(DBG_PROBE, "unregister /dev/video%d [v4l2]", usbvision->vdev->minor & 0x1f);
5400                 if (usbvision->vdev->minor != -1) {
5401                         video_unregister_device(usbvision->vdev);
5402                 }
5403                 else {
5404                         video_device_release(usbvision->vdev);
5405                 }
5406                 usbvision->vdev = NULL;
5407         }
5408 }
5409
5410 // register video4linux devices
5411 static int __devinit usbvision_register_video(struct usb_usbvision *usbvision)
5412 {
5413         // Video Device:
5414         usbvision->vdev = usbvision_vdev_init(usbvision, &usbvision_video_template, "USBVision Video");
5415         if (usbvision->vdev == NULL) {
5416                 goto err_exit;
5417         }
5418         if (video_register_device(usbvision->vdev, VFL_TYPE_GRABBER, video_nr)<0) {
5419                 goto err_exit;
5420         }
5421         info("USBVision[%d]: registered USBVision Video device /dev/video%d [v4l2]", usbvision->nr,usbvision->vdev->minor & 0x1f);
5422
5423         // Radio Device:
5424         if (usbvision_device_data[usbvision->DevModel].Radio) {
5425                 // usbvision has radio
5426                 usbvision->rdev = usbvision_vdev_init(usbvision, &usbvision_radio_template, "USBVision Radio");
5427                 if (usbvision->rdev == NULL) {
5428                         goto err_exit;
5429                 }
5430                 if (video_register_device(usbvision->rdev, VFL_TYPE_RADIO, radio_nr)<0) {
5431                         goto err_exit;
5432                 }
5433                 info("USBVision[%d]: registered USBVision Radio device /dev/radio%d [v4l2]", usbvision->nr, usbvision->rdev->minor & 0x1f);
5434         }
5435         // vbi Device: 
5436         if (usbvision_device_data[usbvision->DevModel].vbi) {
5437                 usbvision->vbi = usbvision_vdev_init(usbvision, &usbvision_vbi_template, "USBVision VBI");
5438                 if (usbvision->vdev == NULL) {
5439                         goto err_exit;
5440                 }
5441                 if (video_register_device(usbvision->vbi, VFL_TYPE_VBI, vbi_nr)<0) {
5442                         goto err_exit;
5443                 }
5444                 info("USBVision[%d]: registered USBVision VBI device /dev/vbi%d [v4l2] (Not Working Yet!)", usbvision->nr,usbvision->vbi->minor & 0x1f);
5445         }
5446         // all done
5447         return 0;
5448
5449  err_exit:
5450         err("USBVision[%d]: video_register_device() failed", usbvision->nr);
5451         usbvision_unregister_video(usbvision);
5452         return -1;
5453 }
5454
5455 /*
5456  * usbvision_alloc()
5457  *
5458  * This code allocates the struct usb_usbvision. It is filled with default values.
5459  *
5460  * Returns NULL on error, a pointer to usb_usbvision else.
5461  *
5462  */
5463 static struct usb_usbvision *usbvision_alloc(struct usb_device *dev)
5464 {
5465         struct usb_usbvision *usbvision;
5466         int FrameIdx;
5467
5468         if ((usbvision = kzalloc(sizeof(struct usb_usbvision), GFP_KERNEL)) == NULL) {
5469                 goto err_exit;
5470         }
5471
5472         usbvision->dev = dev;
5473
5474         for (FrameIdx = 0; FrameIdx < USBVISION_NUMFRAMES; FrameIdx++) {
5475                 init_waitqueue_head(&usbvision->frame[FrameIdx].wq);
5476         }
5477         init_waitqueue_head(&usbvision->overlay_frame.wq);
5478         init_MUTEX(&usbvision->lock);   /* to 1 == available */
5479
5480         // prepare control urb for control messages during interrupts
5481         usbvision->ctrlUrb = usb_alloc_urb(USBVISION_URB_FRAMES, GFP_KERNEL);
5482         if (usbvision->ctrlUrb == NULL) {
5483                 goto err_exit;
5484         }
5485         init_waitqueue_head(&usbvision->ctrlUrb_wq);
5486         init_MUTEX(&usbvision->ctrlUrbLock);
5487
5488         init_timer(&usbvision->powerOffTimer);
5489         usbvision->powerOffTimer.data = (long) usbvision;
5490         usbvision->powerOffTimer.function = usbvision_powerOffTimer;
5491
5492         return usbvision;
5493
5494 err_exit:
5495         if (usbvision && usbvision->ctrlUrb) {
5496                 usb_free_urb(usbvision->ctrlUrb);
5497         }
5498         if (usbvision) {
5499                 kfree(usbvision);
5500         }
5501         return NULL;
5502 }
5503
5504 /*
5505  * usbvision_release()
5506  *
5507  * This code does final release of struct usb_usbvision. This happens
5508  * after the device is disconnected -and- all clients closed their files.
5509  *
5510  */
5511 static void usbvision_release(struct usb_usbvision *usbvision)
5512 {
5513         PDEBUG(DBG_PROBE, "");
5514
5515         down(&usbvision->lock);
5516
5517         if (timer_pending(&usbvision->powerOffTimer)) {
5518                 del_timer(&usbvision->powerOffTimer);
5519         }
5520
5521         usbvision->usbvision_used = 0;
5522         usbvision->initialized = 0;
5523
5524         up(&usbvision->lock);
5525
5526         usbvision_remove_sysfs(usbvision->vdev);
5527         usbvision_unregister_video(usbvision);
5528         if(dga) {
5529                 if (usbvision->overlay_base) {
5530                         iounmap(usbvision->overlay_base);
5531                 }
5532         }
5533
5534         if (usbvision->ctrlUrb) {
5535                 usb_free_urb(usbvision->ctrlUrb);
5536         }
5537
5538         kfree(usbvision);
5539
5540         PDEBUG(DBG_PROBE, "success");
5541 }
5542
5543
5544 /*
5545  * usbvision_probe()
5546  *
5547  * This procedure queries device descriptor and accepts the interface
5548  * if it looks like USBVISION video device
5549  *
5550  */
5551 static int __devinit usbvision_probe(struct usb_interface *intf, const struct usb_device_id *devid)
5552 {
5553         struct usb_device *dev = interface_to_usbdev(intf);
5554         __u8 ifnum = intf->altsetting->desc.bInterfaceNumber;
5555         const struct usb_host_interface *interface;
5556         struct usb_usbvision *usbvision = NULL;
5557         const struct usb_endpoint_descriptor *endpoint;
5558         int model;
5559
5560         PDEBUG(DBG_PROBE, "VID=%#04x, PID=%#04x, ifnum=%u",
5561                                         dev->descriptor.idVendor, dev->descriptor.idProduct, ifnum);
5562
5563         /* Is it an USBVISION video dev? */
5564         model = 0;
5565         for(model = 0; usbvision_device_data[model].idVendor; model++) {
5566                 if (le16_to_cpu(dev->descriptor.idVendor) != usbvision_device_data[model].idVendor) { 
5567                         continue;
5568                 }
5569                 if (le16_to_cpu(dev->descriptor.idProduct) != usbvision_device_data[model].idProduct) { 
5570                         continue;
5571                 }
5572
5573                 info("%s: %s found", __FUNCTION__, usbvision_device_data[model].ModelString);
5574                 break;
5575         }
5576
5577         if (usbvision_device_data[model].idVendor == 0) {
5578                 return -ENODEV; //no matching device
5579         }
5580         if (usbvision_device_data[model].Interface >= 0) {
5581                 interface = &dev->actconfig->interface[usbvision_device_data[model].Interface]->altsetting[0];
5582         }
5583         else {
5584                 interface = &dev->actconfig->interface[ifnum]->altsetting[0];
5585         }
5586         endpoint = &interface->endpoint[1].desc;
5587         if ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_ISOC) {
5588                 err("%s: interface %d. has non-ISO endpoint!", __FUNCTION__, ifnum);
5589                 err("%s: Endpoint attribures %d", __FUNCTION__, endpoint->bmAttributes);
5590                 return -ENODEV;
5591         }
5592         if ((endpoint->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT) {
5593                 err("%s: interface %d. has ISO OUT endpoint!", __FUNCTION__, ifnum);
5594                 return -ENODEV;
5595         }
5596
5597         usb_get_dev(dev);
5598         
5599         if ((usbvision = usbvision_alloc(dev)) == NULL) {
5600                 err("%s: couldn't allocate USBVision struct", __FUNCTION__);
5601                 return -ENOMEM;
5602         }
5603         if (dev->descriptor.bNumConfigurations > 1) {
5604                 usbvision->bridgeType = BRIDGE_NT1004;
5605         }
5606         else if (usbvision_device_data[model].ModelString == "Dazzle Fusion Model DVC-90 Rev 1 (SECAM)") {
5607                 usbvision->bridgeType = BRIDGE_NT1005;
5608         }               
5609         else {
5610                 usbvision->bridgeType = BRIDGE_NT1003;
5611         }
5612         PDEBUG(DBG_PROBE, "bridgeType %d", usbvision->bridgeType);
5613
5614         down(&usbvision->lock);
5615
5616         usbvision->nr = usbvision_nr++;
5617
5618         usbvision->have_tuner = usbvision_device_data[model].Tuner;
5619         if (usbvision->have_tuner) {
5620                 usbvision->tuner_type = usbvision_device_data[model].TunerType;
5621         }
5622
5623         usbvision->DevModel = model;
5624         usbvision->remove_pending = 0;
5625         usbvision->last_error = 0;
5626         usbvision->iface = ifnum;
5627         usbvision->ifaceAltInactive = 0;
5628         usbvision->ifaceAltActive = 1;
5629         usbvision->video_endp = endpoint->bEndpointAddress;
5630         usbvision->isocPacketSize = 0;
5631         usbvision->usb_bandwidth = 0;
5632         usbvision->user = 0;
5633
5634         usbvision_register_video(usbvision);
5635         usbvision_configure_video(usbvision);
5636         up(&usbvision->lock);
5637
5638
5639         usb_set_intfdata (intf, usbvision);
5640         usbvision_create_sysfs(usbvision->vdev);        
5641
5642         PDEBUG(DBG_PROBE, "success");
5643         return 0;
5644 }
5645
5646
5647 /*
5648  * usbvision_disconnect()
5649  *
5650  * This procedure stops all driver activity, deallocates interface-private
5651  * structure (pointed by 'ptr') and after that driver should be removable
5652  * with no ill consequences.
5653  *
5654  */
5655 static void __devexit usbvision_disconnect(struct usb_interface *intf)
5656 {
5657         struct usb_usbvision *usbvision = usb_get_intfdata(intf);
5658
5659         PDEBUG(DBG_PROBE, "");
5660
5661         if (usbvision == NULL) {
5662                 err("%s: usb_get_intfdata() failed", __FUNCTION__);
5663                 return;
5664         }
5665         usb_set_intfdata (intf, NULL);
5666
5667         down(&usbvision->lock);
5668
5669         // At this time we ask to cancel outstanding URBs
5670         usbvision_stop_isoc(usbvision);
5671
5672         if (usbvision->power) {
5673                 usbvision_i2c_usb_del_bus(&usbvision->i2c_adap);
5674                 usbvision_power_off(usbvision);
5675         }
5676         usbvision->remove_pending = 1;  // Now all ISO data will be ignored
5677
5678         usb_put_dev(usbvision->dev);
5679         usbvision->dev = NULL;  // USB device is no more
5680
5681         up(&usbvision->lock);
5682
5683         if (usbvision->user) {
5684                 info("%s: In use, disconnect pending", __FUNCTION__);
5685         }
5686         else {
5687                 usbvision_release(usbvision);
5688         }
5689
5690         PDEBUG(DBG_PROBE, "success");
5691
5692 }
5693
5694 MODULE_DEVICE_TABLE (usb, usbvision_table);
5695
5696 static struct usb_driver usbvision_driver = {
5697         .name           = "usbvision",
5698         .id_table       = usbvision_table,
5699         .probe          = usbvision_probe,
5700         .disconnect     = usbvision_disconnect
5701 };
5702
5703 /*
5704  * customdevice_process()
5705  *
5706  * This procedure preprocesses CustomDevice parameter if any
5707  *
5708  */
5709 void customdevice_process(void)
5710 {
5711         usbvision_device_data[0]=usbvision_device_data[1];
5712         usbvision_table[0]=usbvision_table[1];
5713
5714         if(CustomDevice)
5715         {
5716                 char *parse=CustomDevice;
5717         
5718                 PDEBUG(DBG_PROBE, "CustomDevide=%s", CustomDevice);
5719
5720                 /*format is CustomDevice="0x0573 0x4D31 0 7113 3 PAL 1 1 1 5 -1 -1 -1 -1 -1"
5721                 usbvision_device_data[0].idVendor;
5722                 usbvision_device_data[0].idProduct;
5723                 usbvision_device_data[0].Interface;
5724                 usbvision_device_data[0].Codec;
5725                 usbvision_device_data[0].VideoChannels;
5726                 usbvision_device_data[0].VideoNorm;
5727                 usbvision_device_data[0].AudioChannels;
5728                 usbvision_device_data[0].Radio;
5729                 usbvision_device_data[0].Tuner;
5730                 usbvision_device_data[0].TunerType;
5731                 usbvision_device_data[0].Vin_Reg1;
5732                 usbvision_device_data[0].Vin_Reg2;
5733                 usbvision_device_data[0].X_Offset;
5734                 usbvision_device_data[0].Y_Offset;
5735                 usbvision_device_data[0].Dvi_yuv;
5736                 usbvision_device_data[0].ModelString;
5737                 */
5738                 
5739                 rmspace(parse);
5740                 usbvision_device_data[0].ModelString="USBVISION Custom Device";
5741
5742                 parse+=2;
5743                 sscanf(parse,"%x",&usbvision_device_data[0].idVendor);
5744                 goto2next(parse);
5745                 PDEBUG(DBG_PROBE, "idVendor=0x%.4X", usbvision_device_data[0].idVendor);
5746                 parse+=2;
5747                 sscanf(parse,"%x",&usbvision_device_data[0].idProduct);
5748                 goto2next(parse);
5749                 PDEBUG(DBG_PROBE, "idProduct=0x%.4X", usbvision_device_data[0].idProduct);
5750                 sscanf(parse,"%d",&usbvision_device_data[0].Interface);
5751                 goto2next(parse);
5752                 PDEBUG(DBG_PROBE, "Interface=%d", usbvision_device_data[0].Interface);
5753                 sscanf(parse,"%d",&usbvision_device_data[0].Codec);
5754                 goto2next(parse);
5755                 PDEBUG(DBG_PROBE, "Codec=%d", usbvision_device_data[0].Codec);
5756                 sscanf(parse,"%d",&usbvision_device_data[0].VideoChannels);
5757                 goto2next(parse);
5758                 PDEBUG(DBG_PROBE, "VideoChannels=%d", usbvision_device_data[0].VideoChannels);
5759
5760                 switch(*parse)
5761                 {
5762                         case 'P':
5763                                 PDEBUG(DBG_PROBE, "VideoNorm=PAL");
5764                                 usbvision_device_data[0].VideoNorm=VIDEO_MODE_PAL;
5765                                 break;
5766
5767                         case 'S':
5768                                 PDEBUG(DBG_PROBE, "VideoNorm=SECAM");
5769                                 usbvision_device_data[0].VideoNorm=VIDEO_MODE_SECAM;
5770                                 break;
5771
5772                         case 'N':
5773                                 PDEBUG(DBG_PROBE, "VideoNorm=NTSC");
5774                                 usbvision_device_data[0].VideoNorm=VIDEO_MODE_NTSC;
5775                                 break;
5776
5777                         default:
5778                                 PDEBUG(DBG_PROBE, "VideoNorm=PAL (by default)");
5779                                 usbvision_device_data[0].VideoNorm=VIDEO_MODE_PAL;
5780                                 break;
5781                 }
5782                 goto2next(parse);
5783
5784                 sscanf(parse,"%d",&usbvision_device_data[0].AudioChannels);
5785                 goto2next(parse);
5786                 PDEBUG(DBG_PROBE, "AudioChannels=%d", usbvision_device_data[0].AudioChannels);
5787                 sscanf(parse,"%d",&usbvision_device_data[0].Radio);
5788                 goto2next(parse);
5789                 PDEBUG(DBG_PROBE, "Radio=%d", usbvision_device_data[0].Radio);
5790                 sscanf(parse,"%d",&usbvision_device_data[0].Tuner);
5791                 goto2next(parse);
5792                 PDEBUG(DBG_PROBE, "Tuner=%d", usbvision_device_data[0].Tuner);
5793                 sscanf(parse,"%d",&usbvision_device_data[0].TunerType);
5794                 goto2next(parse);
5795                 PDEBUG(DBG_PROBE, "TunerType=%d", usbvision_device_data[0].TunerType);
5796                 sscanf(parse,"%d",&usbvision_device_data[0].Vin_Reg1);
5797                 goto2next(parse);
5798                 PDEBUG(DBG_PROBE, "Vin_Reg1=%d", usbvision_device_data[0].Vin_Reg1);
5799                 sscanf(parse,"%d",&usbvision_device_data[0].Vin_Reg2);
5800                 goto2next(parse);
5801                 PDEBUG(DBG_PROBE, "Vin_Reg2=%d", usbvision_device_data[0].Vin_Reg2);
5802                 sscanf(parse,"%d",&usbvision_device_data[0].X_Offset);
5803                 goto2next(parse);
5804                 PDEBUG(DBG_PROBE, "X_Offset=%d", usbvision_device_data[0].X_Offset);
5805                 sscanf(parse,"%d",&usbvision_device_data[0].Y_Offset);
5806                 goto2next(parse);
5807                 PDEBUG(DBG_PROBE, "Y_Offset=%d", usbvision_device_data[0].Y_Offset);
5808                 sscanf(parse,"%d",&usbvision_device_data[0].Dvi_yuv);
5809                 PDEBUG(DBG_PROBE, "Dvi_yuv=%d", usbvision_device_data[0].Dvi_yuv);
5810
5811                 //add to usbvision_table also
5812                 usbvision_table[0].match_flags=USB_DEVICE_ID_MATCH_DEVICE;
5813                 usbvision_table[0].idVendor=usbvision_device_data[0].idVendor;
5814                 usbvision_table[0].idProduct=usbvision_device_data[0].idProduct;
5815
5816         }
5817 }
5818
5819
5820
5821 /*
5822  * usbvision_init()
5823  *
5824  * This code is run to initialize the driver.
5825  *
5826  */
5827 static int __init usbvision_init(void)
5828 {
5829         int errCode;
5830
5831         PDEBUG(DBG_PROBE, "");
5832
5833         PDEBUG(DBG_IOCTL, "IOCTL   debugging is enabled");
5834         PDEBUG(DBG_IO,  "IO      debugging is enabled");
5835         PDEBUG(DBG_RIO,  "RIO     debugging is enabled");
5836         PDEBUG(DBG_HEADER, "HEADER  debugging is enabled");
5837         PDEBUG(DBG_PROBE, "PROBE   debugging is enabled");
5838         PDEBUG(DBG_IRQ,  "IRQ     debugging is enabled");
5839         PDEBUG(DBG_ISOC, "ISOC    debugging is enabled");
5840         PDEBUG(DBG_PARSE, "PARSE   debugging is enabled");
5841         PDEBUG(DBG_SCRATCH, "SCRATCH debugging is enabled");
5842         PDEBUG(DBG_FUNC, "FUNC    debugging is enabled");
5843         PDEBUG(DBG_I2C,  "I2C     debugging is enabled");
5844
5845         /* disable planar mode support unless compression enabled */ 
5846         if (isocMode != ISOC_MODE_COMPRESS ) { 
5847                 // FIXME : not the right way to set supported flag
5848                 usbvision_v4l2_format[6].supported = 0; // V4L2_PIX_FMT_YVU420
5849                 usbvision_v4l2_format[7].supported = 0; // V4L2_PIX_FMT_YUV422P
5850         } 
5851
5852         customdevice_process();
5853
5854         errCode = usb_register(&usbvision_driver);
5855
5856         if (errCode == 0) {
5857                 info(DRIVER_DESC " : " DRIVER_VERSION);
5858                 PDEBUG(DBG_PROBE, "success");
5859         }
5860         return errCode;
5861 }
5862
5863 static void __exit usbvision_exit(void)
5864 {
5865  PDEBUG(DBG_PROBE, "");
5866
5867  usb_deregister(&usbvision_driver);
5868  PDEBUG(DBG_PROBE, "success");
5869 }
5870
5871 module_init(usbvision_init);
5872 module_exit(usbvision_exit);
5873
5874 /*
5875  * Overrides for Emacs so that we follow Linus's tabbing style.
5876  * ---------------------------------------------------------------------------
5877  * Local variables:
5878  * c-basic-offset: 8
5879  * End:
5880  */