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