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