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