Merge master.kernel.org:/pub/scm/linux/kernel/git/davej/agpgart
[linux-2.6] / drivers / media / video / usbvision / usbvision-core.c
1 /*
2  * usbvision-core.c - driver for NT100x USB video capture devices
3  *
4  *
5  * Copyright (c) 1999-2005 Joerg Heckenbach <joerg@heckenbach-aw.de>
6  *                         Dwaine Garden <dwainegarden@rogers.com>
7  *
8  * This module is part of usbvision driver project.
9  * Updates to driver completed by Dwaine P. Garden
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24  */
25
26 #include <linux/kernel.h>
27 #include <linux/list.h>
28 #include <linux/timer.h>
29 #include <linux/slab.h>
30 #include <linux/mm.h>
31 #include <linux/utsname.h>
32 #include <linux/highmem.h>
33 #include <linux/smp_lock.h>
34 #include <linux/videodev.h>
35 #include <linux/vmalloc.h>
36 #include <linux/module.h>
37 #include <linux/init.h>
38 #include <linux/spinlock.h>
39 #include <asm/io.h>
40 #include <linux/videodev2.h>
41 #include <linux/video_decoder.h>
42 #include <linux/i2c.h>
43
44 #include <media/saa7115.h>
45 #include <media/v4l2-common.h>
46 #include <media/tuner.h>
47 #include <media/audiochip.h>
48
49 #include <linux/moduleparam.h>
50 #include <linux/workqueue.h>
51
52 #ifdef CONFIG_KMOD
53 #include <linux/kmod.h>
54 #endif
55
56 #include "usbvision.h"
57
58 static unsigned int core_debug = 0;
59 module_param(core_debug,int,0644);
60 MODULE_PARM_DESC(core_debug,"enable debug messages [core]");
61
62 static unsigned int force_testpattern = 0;
63 module_param(force_testpattern,int,0644);
64 MODULE_PARM_DESC(force_testpattern,"enable test pattern display [core]");
65
66 static int adjustCompression = 1;                       // Set the compression to be adaptive
67 module_param(adjustCompression, int, 0444);
68 MODULE_PARM_DESC(adjustCompression, " Set the ADPCM compression for the device.  Default: 1 (On)");
69
70 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.
71 module_param(SwitchSVideoInput, int, 0444);
72 MODULE_PARM_DESC(SwitchSVideoInput, " Set the S-Video input.  Some cables and input device are wired differently. Default: 0 (Off)");
73
74 #define ENABLE_HEXDUMP  0       /* Enable if you need it */
75
76
77 #ifdef USBVISION_DEBUG
78         #define PDEBUG(level, fmt, args...) \
79                 if (core_debug & (level)) info("[%s:%d] " fmt, __PRETTY_FUNCTION__, __LINE__ , ## args)
80 #else
81         #define PDEBUG(level, fmt, args...) do {} while(0)
82 #endif
83
84 #define DBG_HEADER      1<<0
85 #define DBG_IRQ         1<<1
86 #define DBG_ISOC        1<<2
87 #define DBG_PARSE       1<<3
88 #define DBG_SCRATCH     1<<4
89 #define DBG_FUNC        1<<5
90
91 static const int max_imgwidth = MAX_FRAME_WIDTH;
92 static const int max_imgheight = MAX_FRAME_HEIGHT;
93 static const int min_imgwidth = MIN_FRAME_WIDTH;
94 static const int min_imgheight = MIN_FRAME_HEIGHT;
95
96 /* The value of 'scratch_buf_size' affects quality of the picture
97  * in many ways. Shorter buffers may cause loss of data when client
98  * is too slow. Larger buffers are memory-consuming and take longer
99  * to work with. This setting can be adjusted, but the default value
100  * should be OK for most desktop users.
101  */
102 #define DEFAULT_SCRATCH_BUF_SIZE        (0x20000)               // 128kB memory scratch buffer
103 static const int scratch_buf_size = DEFAULT_SCRATCH_BUF_SIZE;
104
105 // Function prototypes
106 static int usbvision_request_intra (struct usb_usbvision *usbvision);
107 static int usbvision_unrequest_intra (struct usb_usbvision *usbvision);
108 static int usbvision_adjust_compression (struct usb_usbvision *usbvision);
109 static int usbvision_measure_bandwidth (struct usb_usbvision *usbvision);
110
111 /*******************************/
112 /* Memory management functions */
113 /*******************************/
114
115 /*
116  * Here we want the physical address of the memory.
117  * This is used when initializing the contents of the area.
118  */
119
120 static void *usbvision_rvmalloc(unsigned long size)
121 {
122         void *mem;
123         unsigned long adr;
124
125         size = PAGE_ALIGN(size);
126         mem = vmalloc_32(size);
127         if (!mem)
128                 return NULL;
129
130         memset(mem, 0, size); /* Clear the ram out, no junk to the user */
131         adr = (unsigned long) mem;
132         while (size > 0) {
133                 SetPageReserved(vmalloc_to_page((void *)adr));
134                 adr += PAGE_SIZE;
135                 size -= PAGE_SIZE;
136         }
137
138         return mem;
139 }
140
141 void usbvision_rvfree(void *mem, unsigned long size)
142 {
143         unsigned long adr;
144
145         if (!mem)
146                 return;
147
148         size = PAGE_ALIGN(size);
149
150         adr = (unsigned long) mem;
151         while ((long) size > 0) {
152                 ClearPageReserved(vmalloc_to_page((void *)adr));
153                 adr += PAGE_SIZE;
154                 size -= PAGE_SIZE;
155         }
156
157         vfree(mem);
158 }
159
160
161
162 #if ENABLE_HEXDUMP
163 static void usbvision_hexdump(const unsigned char *data, int len)
164 {
165         char tmp[80];
166         int i, k;
167
168         for (i = k = 0; len > 0; i++, len--) {
169                 if (i > 0 && (i % 16 == 0)) {
170                         printk("%s\n", tmp);
171                         k = 0;
172                 }
173                 k += sprintf(&tmp[k], "%02x ", data[i]);
174         }
175         if (k > 0)
176                 printk("%s\n", tmp);
177 }
178 #endif
179
180 /********************************
181  * scratch ring buffer handling
182  ********************************/
183 static int scratch_len(struct usb_usbvision *usbvision)    /*This returns the amount of data actually in the buffer */
184 {
185         int len = usbvision->scratch_write_ptr - usbvision->scratch_read_ptr;
186         if (len < 0) {
187                 len += scratch_buf_size;
188         }
189         PDEBUG(DBG_SCRATCH, "scratch_len() = %d\n", len);
190
191         return len;
192 }
193
194
195 /* This returns the free space left in the buffer */
196 static int scratch_free(struct usb_usbvision *usbvision)
197 {
198         int free = usbvision->scratch_read_ptr - usbvision->scratch_write_ptr;
199         if (free <= 0) {
200                 free += scratch_buf_size;
201         }
202         if (free) {
203                 free -= 1;                                                      /* at least one byte in the buffer must */
204                                                                                 /* left blank, otherwise there is no chance to differ between full and empty */
205         }
206         PDEBUG(DBG_SCRATCH, "return %d\n", free);
207
208         return free;
209 }
210
211
212 /* This puts data into the buffer */
213 static int scratch_put(struct usb_usbvision *usbvision, unsigned char *data,
214                        int len)
215 {
216         int len_part;
217
218         if (usbvision->scratch_write_ptr + len < scratch_buf_size) {
219                 memcpy(usbvision->scratch + usbvision->scratch_write_ptr, data, len);
220                 usbvision->scratch_write_ptr += len;
221         }
222         else {
223                 len_part = scratch_buf_size - usbvision->scratch_write_ptr;
224                 memcpy(usbvision->scratch + usbvision->scratch_write_ptr, data, len_part);
225                 if (len == len_part) {
226                         usbvision->scratch_write_ptr = 0;                       /* just set write_ptr to zero */
227                 }
228                 else {
229                         memcpy(usbvision->scratch, data + len_part, len - len_part);
230                         usbvision->scratch_write_ptr = len - len_part;
231                 }
232         }
233
234         PDEBUG(DBG_SCRATCH, "len=%d, new write_ptr=%d\n", len, usbvision->scratch_write_ptr);
235
236         return len;
237 }
238
239 /* This marks the write_ptr as position of new frame header */
240 static void scratch_mark_header(struct usb_usbvision *usbvision)
241 {
242         PDEBUG(DBG_SCRATCH, "header at write_ptr=%d\n", usbvision->scratch_headermarker_write_ptr);
243
244         usbvision->scratch_headermarker[usbvision->scratch_headermarker_write_ptr] =
245                                 usbvision->scratch_write_ptr;
246         usbvision->scratch_headermarker_write_ptr += 1;
247         usbvision->scratch_headermarker_write_ptr %= USBVISION_NUM_HEADERMARKER;
248 }
249
250 /* This gets data from the buffer at the given "ptr" position */
251 static int scratch_get_extra(struct usb_usbvision *usbvision,
252                              unsigned char *data, int *ptr, int len)
253 {
254         int len_part;
255         if (*ptr + len < scratch_buf_size) {
256                 memcpy(data, usbvision->scratch + *ptr, len);
257                 *ptr += len;
258         }
259         else {
260                 len_part = scratch_buf_size - *ptr;
261                 memcpy(data, usbvision->scratch + *ptr, len_part);
262                 if (len == len_part) {
263                         *ptr = 0;                                                       /* just set the y_ptr to zero */
264                 }
265                 else {
266                         memcpy(data + len_part, usbvision->scratch, len - len_part);
267                         *ptr = len - len_part;
268                 }
269         }
270
271         PDEBUG(DBG_SCRATCH, "len=%d, new ptr=%d\n", len, *ptr);
272
273         return len;
274 }
275
276
277 /* This sets the scratch extra read pointer */
278 static void scratch_set_extra_ptr(struct usb_usbvision *usbvision, int *ptr,
279                                   int len)
280 {
281         *ptr = (usbvision->scratch_read_ptr + len)%scratch_buf_size;
282
283         PDEBUG(DBG_SCRATCH, "ptr=%d\n", *ptr);
284 }
285
286
287 /*This increments the scratch extra read pointer */
288 static void scratch_inc_extra_ptr(int *ptr, int len)
289 {
290         *ptr = (*ptr + len) % scratch_buf_size;
291
292         PDEBUG(DBG_SCRATCH, "ptr=%d\n", *ptr);
293 }
294
295
296 /* This gets data from the buffer */
297 static int scratch_get(struct usb_usbvision *usbvision, unsigned char *data,
298                        int len)
299 {
300         int len_part;
301         if (usbvision->scratch_read_ptr + len < scratch_buf_size) {
302                 memcpy(data, usbvision->scratch + usbvision->scratch_read_ptr, len);
303                 usbvision->scratch_read_ptr += len;
304         }
305         else {
306                 len_part = scratch_buf_size - usbvision->scratch_read_ptr;
307                 memcpy(data, usbvision->scratch + usbvision->scratch_read_ptr, len_part);
308                 if (len == len_part) {
309                         usbvision->scratch_read_ptr = 0;                                /* just set the read_ptr to zero */
310                 }
311                 else {
312                         memcpy(data + len_part, usbvision->scratch, len - len_part);
313                         usbvision->scratch_read_ptr = len - len_part;
314                 }
315         }
316
317         PDEBUG(DBG_SCRATCH, "len=%d, new read_ptr=%d\n", len, usbvision->scratch_read_ptr);
318
319         return len;
320 }
321
322
323 /* This sets read pointer to next header and returns it */
324 static int scratch_get_header(struct usb_usbvision *usbvision,
325                               struct usbvision_frame_header *header)
326 {
327         int errCode = 0;
328
329         PDEBUG(DBG_SCRATCH, "from read_ptr=%d", usbvision->scratch_headermarker_read_ptr);
330
331         while (usbvision->scratch_headermarker_write_ptr -
332                 usbvision->scratch_headermarker_read_ptr != 0) {
333                 usbvision->scratch_read_ptr =
334                         usbvision->scratch_headermarker[usbvision->scratch_headermarker_read_ptr];
335                 usbvision->scratch_headermarker_read_ptr += 1;
336                 usbvision->scratch_headermarker_read_ptr %= USBVISION_NUM_HEADERMARKER;
337                 scratch_get(usbvision, (unsigned char *)header, USBVISION_HEADER_LENGTH);
338                 if ((header->magic_1 == USBVISION_MAGIC_1)
339                          && (header->magic_2 == USBVISION_MAGIC_2)
340                          && (header->headerLength == USBVISION_HEADER_LENGTH)) {
341                         errCode = USBVISION_HEADER_LENGTH;
342                         header->frameWidth  = header->frameWidthLo  + (header->frameWidthHi << 8);
343                         header->frameHeight = header->frameHeightLo + (header->frameHeightHi << 8);
344                         break;
345                 }
346         }
347
348         return errCode;
349 }
350
351
352 /*This removes len bytes of old data from the buffer */
353 static void scratch_rm_old(struct usb_usbvision *usbvision, int len)
354 {
355
356         usbvision->scratch_read_ptr += len;
357         usbvision->scratch_read_ptr %= scratch_buf_size;
358         PDEBUG(DBG_SCRATCH, "read_ptr is now %d\n", usbvision->scratch_read_ptr);
359 }
360
361
362 /*This resets the buffer - kills all data in it too */
363 static void scratch_reset(struct usb_usbvision *usbvision)
364 {
365         PDEBUG(DBG_SCRATCH, "\n");
366
367         usbvision->scratch_read_ptr = 0;
368         usbvision->scratch_write_ptr = 0;
369         usbvision->scratch_headermarker_read_ptr = 0;
370         usbvision->scratch_headermarker_write_ptr = 0;
371         usbvision->isocstate = IsocState_NoFrame;
372 }
373
374 int usbvision_scratch_alloc(struct usb_usbvision *usbvision)
375 {
376         usbvision->scratch = vmalloc_32(scratch_buf_size);
377         scratch_reset(usbvision);
378         if(usbvision->scratch == NULL) {
379                 err("%s: unable to allocate %d bytes for scratch",
380                     __FUNCTION__, scratch_buf_size);
381                 return -ENOMEM;
382         }
383         return 0;
384 }
385
386 void usbvision_scratch_free(struct usb_usbvision *usbvision)
387 {
388         if (usbvision->scratch != NULL) {
389                 vfree(usbvision->scratch);
390                 usbvision->scratch = NULL;
391         }
392 }
393
394 /*
395  * usbvision_testpattern()
396  *
397  * Procedure forms a test pattern (yellow grid on blue background).
398  *
399  * Parameters:
400  * fullframe:   if TRUE then entire frame is filled, otherwise the procedure
401  *              continues from the current scanline.
402  * pmode        0: fill the frame with solid blue color (like on VCR or TV)
403  *              1: Draw a colored grid
404  *
405  */
406 static void usbvision_testpattern(struct usb_usbvision *usbvision,
407                                   int fullframe, int pmode)
408 {
409         static const char proc[] = "usbvision_testpattern";
410         struct usbvision_frame *frame;
411         unsigned char *f;
412         int num_cell = 0;
413         int scan_length = 0;
414         static int num_pass = 0;
415
416         if (usbvision == NULL) {
417                 printk(KERN_ERR "%s: usbvision == NULL\n", proc);
418                 return;
419         }
420         if (usbvision->curFrame == NULL) {
421                 printk(KERN_ERR "%s: usbvision->curFrame is NULL.\n", proc);
422                 return;
423         }
424
425         /* Grab the current frame */
426         frame = usbvision->curFrame;
427
428         /* Optionally start at the beginning */
429         if (fullframe) {
430                 frame->curline = 0;
431                 frame->scanlength = 0;
432         }
433
434         /* Form every scan line */
435         for (; frame->curline < frame->frmheight; frame->curline++) {
436                 int i;
437
438                 f = frame->data + (usbvision->curwidth * 3 * frame->curline);
439                 for (i = 0; i < usbvision->curwidth; i++) {
440                         unsigned char cb = 0x80;
441                         unsigned char cg = 0;
442                         unsigned char cr = 0;
443
444                         if (pmode == 1) {
445                                 if (frame->curline % 32 == 0)
446                                         cb = 0, cg = cr = 0xFF;
447                                 else if (i % 32 == 0) {
448                                         if (frame->curline % 32 == 1)
449                                                 num_cell++;
450                                         cb = 0, cg = cr = 0xFF;
451                                 } else {
452                                         cb =
453                                             ((num_cell * 7) +
454                                              num_pass) & 0xFF;
455                                         cg =
456                                             ((num_cell * 5) +
457                                              num_pass * 2) & 0xFF;
458                                         cr =
459                                             ((num_cell * 3) +
460                                              num_pass * 3) & 0xFF;
461                                 }
462                         } else {
463                                 /* Just the blue screen */
464                         }
465
466                         *f++ = cb;
467                         *f++ = cg;
468                         *f++ = cr;
469                         scan_length += 3;
470                 }
471         }
472
473         frame->grabstate = FrameState_Done;
474         frame->scanlength += scan_length;
475         ++num_pass;
476
477 }
478
479 /*
480  * usbvision_decompress_alloc()
481  *
482  * allocates intermediate buffer for decompression
483  */
484 int usbvision_decompress_alloc(struct usb_usbvision *usbvision)
485 {
486         int IFB_size = MAX_FRAME_WIDTH * MAX_FRAME_HEIGHT * 3 / 2;
487         usbvision->IntraFrameBuffer = vmalloc_32(IFB_size);
488         if (usbvision->IntraFrameBuffer == NULL) {
489                 err("%s: unable to allocate %d for compr. frame buffer", __FUNCTION__, IFB_size);
490                 return -ENOMEM;
491         }
492         return 0;
493 }
494
495 /*
496  * usbvision_decompress_free()
497  *
498  * frees intermediate buffer for decompression
499  */
500 void usbvision_decompress_free(struct usb_usbvision *usbvision)
501 {
502         if (usbvision->IntraFrameBuffer != NULL) {
503                 vfree(usbvision->IntraFrameBuffer);
504                 usbvision->IntraFrameBuffer = NULL;
505         }
506 }
507
508 /************************************************************
509  * Here comes the data parsing stuff that is run as interrupt
510  ************************************************************/
511 /*
512  * usbvision_find_header()
513  *
514  * Locate one of supported header markers in the scratch buffer.
515  */
516 static enum ParseState usbvision_find_header(struct usb_usbvision *usbvision)
517 {
518         struct usbvision_frame *frame;
519         int foundHeader = 0;
520
521         frame = usbvision->curFrame;
522
523         while (scratch_get_header(usbvision, &frame->isocHeader) == USBVISION_HEADER_LENGTH) {
524                 // found header in scratch
525                 PDEBUG(DBG_HEADER, "found header: 0x%02x%02x %d %d %d %d %#x 0x%02x %u %u",
526                                 frame->isocHeader.magic_2,
527                                 frame->isocHeader.magic_1,
528                                 frame->isocHeader.headerLength,
529                                 frame->isocHeader.frameNum,
530                                 frame->isocHeader.framePhase,
531                                 frame->isocHeader.frameLatency,
532                                 frame->isocHeader.dataFormat,
533                                 frame->isocHeader.formatParam,
534                                 frame->isocHeader.frameWidth,
535                                 frame->isocHeader.frameHeight);
536
537                 if (usbvision->requestIntra) {
538                         if (frame->isocHeader.formatParam & 0x80) {
539                                 foundHeader = 1;
540                                 usbvision->lastIsocFrameNum = -1; // do not check for lost frames this time
541                                 usbvision_unrequest_intra(usbvision);
542                                 break;
543                         }
544                 }
545                 else {
546                         foundHeader = 1;
547                         break;
548                 }
549         }
550
551         if (foundHeader) {
552                 frame->frmwidth = frame->isocHeader.frameWidth * usbvision->stretch_width;
553                 frame->frmheight = frame->isocHeader.frameHeight * usbvision->stretch_height;
554                 frame->v4l2_linesize = (frame->frmwidth * frame->v4l2_format.depth)>> 3;
555         }
556         else { // no header found
557                 PDEBUG(DBG_HEADER, "skipping scratch data, no header");
558                 scratch_reset(usbvision);
559                 return ParseState_EndParse;
560         }
561
562         // found header
563         if (frame->isocHeader.dataFormat==ISOC_MODE_COMPRESS) {
564                 //check isocHeader.frameNum for lost frames
565                 if (usbvision->lastIsocFrameNum >= 0) {
566                         if (((usbvision->lastIsocFrameNum + 1) % 32) != frame->isocHeader.frameNum) {
567                                 // unexpected frame drop: need to request new intra frame
568                                 PDEBUG(DBG_HEADER, "Lost frame before %d on USB", frame->isocHeader.frameNum);
569                                 usbvision_request_intra(usbvision);
570                                 return ParseState_NextFrame;
571                         }
572                 }
573                 usbvision->lastIsocFrameNum = frame->isocHeader.frameNum;
574         }
575         usbvision->header_count++;
576         frame->scanstate = ScanState_Lines;
577         frame->curline = 0;
578
579         if (force_testpattern) {
580                 usbvision_testpattern(usbvision, 1, 1);
581                 return ParseState_NextFrame;
582         }
583         return ParseState_Continue;
584 }
585
586 static enum ParseState usbvision_parse_lines_422(struct usb_usbvision *usbvision,
587                                            long *pcopylen)
588 {
589         volatile struct usbvision_frame *frame;
590         unsigned char *f;
591         int len;
592         int i;
593         unsigned char yuyv[4]={180, 128, 10, 128}; // YUV components
594         unsigned char rv, gv, bv;       // RGB components
595         int clipmask_index, bytes_per_pixel;
596         int stretch_bytes, clipmask_add;
597
598         frame  = usbvision->curFrame;
599         f = frame->data + (frame->v4l2_linesize * frame->curline);
600
601         /* Make sure there's enough data for the entire line */
602         len = (frame->isocHeader.frameWidth * 2)+5;
603         if (scratch_len(usbvision) < len) {
604                 PDEBUG(DBG_PARSE, "out of data in line %d, need %u.\n", frame->curline, len);
605                 return ParseState_Out;
606         }
607
608         if ((frame->curline + 1) >= frame->frmheight) {
609                 return ParseState_NextFrame;
610         }
611
612         bytes_per_pixel = frame->v4l2_format.bytes_per_pixel;
613         stretch_bytes = (usbvision->stretch_width - 1) * bytes_per_pixel;
614         clipmask_index = frame->curline * MAX_FRAME_WIDTH;
615         clipmask_add = usbvision->stretch_width;
616
617         for (i = 0; i < frame->frmwidth; i+=(2 * usbvision->stretch_width)) {
618
619                 scratch_get(usbvision, &yuyv[0], 4);
620
621                 if (frame->v4l2_format.format == V4L2_PIX_FMT_YUYV) {
622                         *f++ = yuyv[0]; // Y
623                         *f++ = yuyv[3]; // U
624                 }
625                 else {
626
627                         YUV_TO_RGB_BY_THE_BOOK(yuyv[0], yuyv[1], yuyv[3], rv, gv, bv);
628                         switch (frame->v4l2_format.format) {
629                                 case V4L2_PIX_FMT_RGB565:
630                                         *f++ = (0x1F & (bv >> 3)) | (0xE0 & (gv << 3));
631                                         *f++ = (0x07 & (gv >> 5)) | (0xF8 &  rv);
632                                         break;
633                                 case V4L2_PIX_FMT_RGB24:
634                                         *f++ = bv;
635                                         *f++ = gv;
636                                         *f++ = rv;
637                                         break;
638                                 case V4L2_PIX_FMT_RGB32:
639                                         *f++ = bv;
640                                         *f++ = gv;
641                                         *f++ = rv;
642                                         f++;
643                                         break;
644                                 case V4L2_PIX_FMT_RGB555:
645                                         *f++ = (0x1F & (bv >> 3)) | (0xE0 & (gv << 2));
646                                         *f++ = (0x03 & (gv >> 6)) | (0x7C & (rv >> 1));
647                                         break;
648                         }
649                 }
650                 clipmask_index += clipmask_add;
651                 f += stretch_bytes;
652
653                 if (frame->v4l2_format.format == V4L2_PIX_FMT_YUYV) {
654                         *f++ = yuyv[2]; // Y
655                         *f++ = yuyv[1]; // V
656                 }
657                 else {
658
659                         YUV_TO_RGB_BY_THE_BOOK(yuyv[2], yuyv[1], yuyv[3], rv, gv, bv);
660                         switch (frame->v4l2_format.format) {
661                                 case V4L2_PIX_FMT_RGB565:
662                                         *f++ = (0x1F & (bv >> 3)) | (0xE0 & (gv << 3));
663                                         *f++ = (0x07 & (gv >> 5)) | (0xF8 &  rv);
664                                         break;
665                                 case V4L2_PIX_FMT_RGB24:
666                                         *f++ = bv;
667                                         *f++ = gv;
668                                         *f++ = rv;
669                                         break;
670                                 case V4L2_PIX_FMT_RGB32:
671                                         *f++ = bv;
672                                         *f++ = gv;
673                                         *f++ = rv;
674                                         f++;
675                                         break;
676                                 case V4L2_PIX_FMT_RGB555:
677                                         *f++ = (0x1F & (bv >> 3)) | (0xE0 & (gv << 2));
678                                         *f++ = (0x03 & (gv >> 6)) | (0x7C & (rv >> 1));
679                                         break;
680                         }
681                 }
682                 clipmask_index += clipmask_add;
683                 f += stretch_bytes;
684         }
685
686         frame->curline += usbvision->stretch_height;
687         *pcopylen += frame->v4l2_linesize * usbvision->stretch_height;
688
689         if (frame->curline >= frame->frmheight) {
690                 return ParseState_NextFrame;
691         }
692         else {
693                 return ParseState_Continue;
694         }
695 }
696
697 /* The decompression routine  */
698 static int usbvision_decompress(struct usb_usbvision *usbvision,unsigned char *Compressed,
699                                                                 unsigned char *Decompressed, int *StartPos,
700                                                                 int *BlockTypeStartPos, int Len)
701 {
702         int RestPixel, Idx, MaxPos, Pos, ExtraPos, BlockLen, BlockTypePos, BlockTypeLen;
703         unsigned char BlockByte, BlockCode, BlockType, BlockTypeByte, Integrator;
704
705         Integrator = 0;
706         Pos = *StartPos;
707         BlockTypePos = *BlockTypeStartPos;
708         MaxPos = 396; //Pos + Len;
709         ExtraPos = Pos;
710         BlockLen = 0;
711         BlockByte = 0;
712         BlockCode = 0;
713         BlockType = 0;
714         BlockTypeByte = 0;
715         BlockTypeLen = 0;
716         RestPixel = Len;
717
718         for (Idx = 0; Idx < Len; Idx++) {
719
720                 if (BlockLen == 0) {
721                         if (BlockTypeLen==0) {
722                                 BlockTypeByte = Compressed[BlockTypePos];
723                                 BlockTypePos++;
724                                 BlockTypeLen = 4;
725                         }
726                         BlockType = (BlockTypeByte & 0xC0) >> 6;
727
728                         //statistic:
729                         usbvision->ComprBlockTypes[BlockType]++;
730
731                         Pos = ExtraPos;
732                         if (BlockType == 0) {
733                                 if(RestPixel >= 24) {
734                                         Idx += 23;
735                                         RestPixel -= 24;
736                                         Integrator = Decompressed[Idx];
737                                 } else {
738                                         Idx += RestPixel - 1;
739                                         RestPixel = 0;
740                                 }
741                         } else {
742                                 BlockCode = Compressed[Pos];
743                                 Pos++;
744                                 if (RestPixel >= 24) {
745                                         BlockLen  = 24;
746                                 } else {
747                                         BlockLen = RestPixel;
748                                 }
749                                 RestPixel -= BlockLen;
750                                 ExtraPos = Pos + (BlockLen / 4);
751                         }
752                         BlockTypeByte <<= 2;
753                         BlockTypeLen -= 1;
754                 }
755                 if (BlockLen > 0) {
756                         if ((BlockLen%4) == 0) {
757                                 BlockByte = Compressed[Pos];
758                                 Pos++;
759                         }
760                         if (BlockType == 1) { //inter Block
761                                 Integrator = Decompressed[Idx];
762                         }
763                         switch (BlockByte & 0xC0) {
764                                 case 0x03<<6:
765                                         Integrator += Compressed[ExtraPos];
766                                         ExtraPos++;
767                                         break;
768                                 case 0x02<<6:
769                                         Integrator += BlockCode;
770                                         break;
771                                 case 0x00:
772                                         Integrator -= BlockCode;
773                                         break;
774                         }
775                         Decompressed[Idx] = Integrator;
776                         BlockByte <<= 2;
777                         BlockLen -= 1;
778                 }
779         }
780         *StartPos = ExtraPos;
781         *BlockTypeStartPos = BlockTypePos;
782         return Idx;
783 }
784
785
786 /*
787  * usbvision_parse_compress()
788  *
789  * Parse compressed frame from the scratch buffer, put
790  * decoded RGB value into the current frame buffer and add the written
791  * number of bytes (RGB) to the *pcopylen.
792  *
793  */
794 static enum ParseState usbvision_parse_compress(struct usb_usbvision *usbvision,
795                                            long *pcopylen)
796 {
797 #define USBVISION_STRIP_MAGIC           0x5A
798 #define USBVISION_STRIP_LEN_MAX         400
799 #define USBVISION_STRIP_HEADER_LEN      3
800
801         struct usbvision_frame *frame;
802         unsigned char *f,*u = NULL ,*v = NULL;
803         unsigned char StripData[USBVISION_STRIP_LEN_MAX];
804         unsigned char StripHeader[USBVISION_STRIP_HEADER_LEN];
805         int Idx, IdxEnd, StripLen, StripPtr, StartBlockPos, BlockPos, BlockTypePos;
806         int clipmask_index, bytes_per_pixel, rc;
807         int imageSize;
808         unsigned char rv, gv, bv;
809         static unsigned char *Y, *U, *V;
810
811         frame  = usbvision->curFrame;
812         imageSize = frame->frmwidth * frame->frmheight;
813         if ( (frame->v4l2_format.format == V4L2_PIX_FMT_YUV422P) ||
814              (frame->v4l2_format.format == V4L2_PIX_FMT_YVU420) ) {       // this is a planar format
815                 //... v4l2_linesize not used here.
816                 f = frame->data + (frame->width * frame->curline);
817         } else
818                 f = frame->data + (frame->v4l2_linesize * frame->curline);
819
820         if (frame->v4l2_format.format == V4L2_PIX_FMT_YUYV){ //initialise u and v pointers
821                 // get base of u and b planes add halfoffset
822
823                 u = frame->data
824                         + imageSize
825                         + (frame->frmwidth >>1) * frame->curline ;
826                 v = u + (imageSize >>1 );
827
828         } else if (frame->v4l2_format.format == V4L2_PIX_FMT_YVU420){
829
830                 v = frame->data + imageSize + ((frame->curline* (frame->width))>>2) ;
831                 u = v + (imageSize >>2) ;
832         }
833
834         if (frame->curline == 0) {
835                 usbvision_adjust_compression(usbvision);
836         }
837
838         if (scratch_len(usbvision) < USBVISION_STRIP_HEADER_LEN) {
839                 return ParseState_Out;
840         }
841
842         //get strip header without changing the scratch_read_ptr
843         scratch_set_extra_ptr(usbvision, &StripPtr, 0);
844         scratch_get_extra(usbvision, &StripHeader[0], &StripPtr,
845                                 USBVISION_STRIP_HEADER_LEN);
846
847         if (StripHeader[0] != USBVISION_STRIP_MAGIC) {
848                 // wrong strip magic
849                 usbvision->stripMagicErrors++;
850                 return ParseState_NextFrame;
851         }
852
853         if (frame->curline != (int)StripHeader[2]) {
854                 //line number missmatch error
855                 usbvision->stripLineNumberErrors++;
856         }
857
858         StripLen = 2 * (unsigned int)StripHeader[1];
859         if (StripLen > USBVISION_STRIP_LEN_MAX) {
860                 // strip overrun
861                 // I think this never happens
862                 usbvision_request_intra(usbvision);
863         }
864
865         if (scratch_len(usbvision) < StripLen) {
866                 //there is not enough data for the strip
867                 return ParseState_Out;
868         }
869
870         if (usbvision->IntraFrameBuffer) {
871                 Y = usbvision->IntraFrameBuffer + frame->frmwidth * frame->curline;
872                 U = usbvision->IntraFrameBuffer + imageSize + (frame->frmwidth / 2) * (frame->curline / 2);
873                 V = usbvision->IntraFrameBuffer + imageSize / 4 * 5 + (frame->frmwidth / 2) * (frame->curline / 2);
874         }
875         else {
876                 return ParseState_NextFrame;
877         }
878
879         bytes_per_pixel = frame->v4l2_format.bytes_per_pixel;
880         clipmask_index = frame->curline * MAX_FRAME_WIDTH;
881
882         scratch_get(usbvision, StripData, StripLen);
883
884         IdxEnd = frame->frmwidth;
885         BlockTypePos = USBVISION_STRIP_HEADER_LEN;
886         StartBlockPos = BlockTypePos + (IdxEnd - 1) / 96 + (IdxEnd / 2 - 1) / 96 + 2;
887         BlockPos = StartBlockPos;
888
889         usbvision->BlockPos = BlockPos;
890
891         if ((rc = usbvision_decompress(usbvision, StripData, Y, &BlockPos, &BlockTypePos, IdxEnd)) != IdxEnd) {
892                 //return ParseState_Continue;
893         }
894         if (StripLen > usbvision->maxStripLen) {
895                 usbvision->maxStripLen = StripLen;
896         }
897
898         if (frame->curline%2) {
899                 if ((rc = usbvision_decompress(usbvision, StripData, V, &BlockPos, &BlockTypePos, IdxEnd/2)) != IdxEnd/2) {
900                 //return ParseState_Continue;
901                 }
902         }
903         else {
904                 if ((rc = usbvision_decompress(usbvision, StripData, U, &BlockPos, &BlockTypePos, IdxEnd/2)) != IdxEnd/2) {
905                         //return ParseState_Continue;
906                 }
907         }
908
909         if (BlockPos > usbvision->comprBlockPos) {
910                 usbvision->comprBlockPos = BlockPos;
911         }
912         if (BlockPos > StripLen) {
913                 usbvision->stripLenErrors++;
914         }
915
916         for (Idx = 0; Idx < IdxEnd; Idx++) {
917                 if(frame->v4l2_format.format == V4L2_PIX_FMT_YUYV) {
918                         *f++ = Y[Idx];
919                         *f++ = Idx & 0x01 ? U[Idx/2] : V[Idx/2];
920                 }
921                 else if(frame->v4l2_format.format == V4L2_PIX_FMT_YUV422P) {
922                         *f++ = Y[Idx];
923                         if ( Idx & 0x01)
924                                 *u++ = U[Idx>>1] ;
925                         else
926                                 *v++ = V[Idx>>1];
927                 }
928                 else if (frame->v4l2_format.format == V4L2_PIX_FMT_YVU420) {
929                         *f++ = Y [Idx];
930                         if ( !((  Idx & 0x01  ) | (  frame->curline & 0x01  )) ){
931
932 /*                               only need do this for 1 in 4 pixels */
933 /*                               intraframe buffer is YUV420 format */
934
935                                 *u++ = U[Idx >>1];
936                                 *v++ = V[Idx >>1];
937                         }
938
939                 }
940                 else {
941                         YUV_TO_RGB_BY_THE_BOOK(Y[Idx], U[Idx/2], V[Idx/2], rv, gv, bv);
942                         switch (frame->v4l2_format.format) {
943                                 case V4L2_PIX_FMT_GREY:
944                                         *f++ = Y[Idx];
945                                         break;
946                                 case V4L2_PIX_FMT_RGB555:
947                                         *f++ = (0x1F & (bv >> 3)) | (0xE0 & (gv << 2));
948                                         *f++ = (0x03 & (gv >> 6)) | (0x7C & (rv >> 1));
949                                         break;
950                                 case V4L2_PIX_FMT_RGB565:
951                                         *f++ = (0x1F & (bv >> 3)) | (0xE0 & (gv << 3));
952                                         *f++ = (0x07 & (gv >> 5)) | (0xF8 &  rv);
953                                         break;
954                                 case V4L2_PIX_FMT_RGB24:
955                                         *f++ = bv;
956                                         *f++ = gv;
957                                         *f++ = rv;
958                                         break;
959                                 case V4L2_PIX_FMT_RGB32:
960                                         *f++ = bv;
961                                         *f++ = gv;
962                                         *f++ = rv;
963                                         f++;
964                                         break;
965                         }
966                 }
967                 clipmask_index++;
968         }
969         /* Deal with non-integer no. of bytes for YUV420P */
970         if (frame->v4l2_format.format != V4L2_PIX_FMT_YVU420 )
971                 *pcopylen += frame->v4l2_linesize;
972         else
973                 *pcopylen += frame->curline & 0x01 ? frame->v4l2_linesize : frame->v4l2_linesize << 1;
974
975         frame->curline += 1;
976
977         if (frame->curline >= frame->frmheight) {
978                 return ParseState_NextFrame;
979         }
980         else {
981                 return ParseState_Continue;
982         }
983
984 }
985
986
987 /*
988  * usbvision_parse_lines_420()
989  *
990  * Parse two lines from the scratch buffer, put
991  * decoded RGB value into the current frame buffer and add the written
992  * number of bytes (RGB) to the *pcopylen.
993  *
994  */
995 static enum ParseState usbvision_parse_lines_420(struct usb_usbvision *usbvision,
996                                            long *pcopylen)
997 {
998         struct usbvision_frame *frame;
999         unsigned char *f_even = NULL, *f_odd = NULL;
1000         unsigned int pixel_per_line, block;
1001         int pixel, block_split;
1002         int y_ptr, u_ptr, v_ptr, y_odd_offset;
1003         const int   y_block_size = 128;
1004         const int  uv_block_size = 64;
1005         const int sub_block_size = 32;
1006         const int y_step[] = { 0, 0, 0, 2 },  y_step_size = 4;
1007         const int uv_step[]= { 0, 0, 0, 4 }, uv_step_size = 4;
1008         unsigned char y[2], u, v;       /* YUV components */
1009         int y_, u_, v_, vb, uvg, ur;
1010         int r_, g_, b_;                 /* RGB components */
1011         unsigned char g;
1012         int clipmask_even_index, clipmask_odd_index, bytes_per_pixel;
1013         int clipmask_add, stretch_bytes;
1014
1015         frame  = usbvision->curFrame;
1016         f_even = frame->data + (frame->v4l2_linesize * frame->curline);
1017         f_odd  = f_even + frame->v4l2_linesize * usbvision->stretch_height;
1018
1019         /* Make sure there's enough data for the entire line */
1020         /* In this mode usbvision transfer 3 bytes for every 2 pixels */
1021         /* I need two lines to decode the color */
1022         bytes_per_pixel = frame->v4l2_format.bytes_per_pixel;
1023         stretch_bytes = (usbvision->stretch_width - 1) * bytes_per_pixel;
1024         clipmask_even_index = frame->curline * MAX_FRAME_WIDTH;
1025         clipmask_odd_index  = clipmask_even_index + MAX_FRAME_WIDTH;
1026         clipmask_add = usbvision->stretch_width;
1027         pixel_per_line = frame->isocHeader.frameWidth;
1028
1029         if (scratch_len(usbvision) < (int)pixel_per_line * 3) {
1030                 //printk(KERN_DEBUG "out of data, need %d\n", len);
1031                 return ParseState_Out;
1032         }
1033
1034         if ((frame->curline + 1) >= frame->frmheight) {
1035                 return ParseState_NextFrame;
1036         }
1037
1038         block_split = (pixel_per_line%y_block_size) ? 1 : 0;    //are some blocks splitted into different lines?
1039
1040         y_odd_offset = (pixel_per_line / y_block_size) * (y_block_size + uv_block_size)
1041                         + block_split * uv_block_size;
1042
1043         scratch_set_extra_ptr(usbvision, &y_ptr, y_odd_offset);
1044         scratch_set_extra_ptr(usbvision, &u_ptr, y_block_size);
1045         scratch_set_extra_ptr(usbvision, &v_ptr, y_odd_offset
1046                         + (4 - block_split) * sub_block_size);
1047
1048         for (block = 0; block < (pixel_per_line / sub_block_size);
1049              block++) {
1050
1051
1052                 for (pixel = 0; pixel < sub_block_size; pixel +=2) {
1053                         scratch_get(usbvision, &y[0], 2);
1054                         scratch_get_extra(usbvision, &u, &u_ptr, 1);
1055                         scratch_get_extra(usbvision, &v, &v_ptr, 1);
1056
1057                         //I don't use the YUV_TO_RGB macro for better performance
1058                         v_ = v - 128;
1059                         u_ = u - 128;
1060                         vb =              132252 * v_;
1061                         uvg= -53281 * u_ - 25625 * v_;
1062                         ur = 104595 * u_;
1063
1064                         if(frame->v4l2_format.format == V4L2_PIX_FMT_YUYV) {
1065                                 *f_even++ = y[0];
1066                                 *f_even++ = v;
1067                         }
1068                         else {
1069                                 y_ = 76284 * (y[0] - 16);
1070
1071                                 b_ = (y_ + vb) >> 16;
1072                                 g_ = (y_ + uvg)>> 16;
1073                                 r_ = (y_ + ur) >> 16;
1074
1075                                 switch (frame->v4l2_format.format) {
1076                                         case V4L2_PIX_FMT_RGB565:
1077                                                 g = LIMIT_RGB(g_);
1078                                                 *f_even++ = (0x1F & (LIMIT_RGB(b_) >> 3)) | (0xE0 & (g << 3));
1079                                                 *f_even++ = (0x07 & (          g   >> 5)) | (0xF8 & LIMIT_RGB(r_));
1080                                                 break;
1081                                         case V4L2_PIX_FMT_RGB24:
1082                                                 *f_even++ = LIMIT_RGB(b_);
1083                                                 *f_even++ = LIMIT_RGB(g_);
1084                                                 *f_even++ = LIMIT_RGB(r_);
1085                                                 break;
1086                                         case V4L2_PIX_FMT_RGB32:
1087                                                 *f_even++ = LIMIT_RGB(b_);
1088                                                 *f_even++ = LIMIT_RGB(g_);
1089                                                 *f_even++ = LIMIT_RGB(r_);
1090                                                 f_even++;
1091                                                 break;
1092                                         case V4L2_PIX_FMT_RGB555:
1093                                                 g = LIMIT_RGB(g_);
1094                                                 *f_even++ = (0x1F & (LIMIT_RGB(b_) >> 3)) | (0xE0 & (g << 2));
1095                                                 *f_even++ = (0x03 & (          g   >> 6)) |
1096                                                             (0x7C & (LIMIT_RGB(r_) >> 1));
1097                                                 break;
1098                                 }
1099                         }
1100                         clipmask_even_index += clipmask_add;
1101                         f_even += stretch_bytes;
1102
1103                         if(frame->v4l2_format.format == V4L2_PIX_FMT_YUYV) {
1104                                 *f_even++ = y[1];
1105                                 *f_even++ = u;
1106                         }
1107                         else {
1108                                 y_ = 76284 * (y[1] - 16);
1109
1110                                 b_ = (y_ + vb) >> 16;
1111                                 g_ = (y_ + uvg)>> 16;
1112                                 r_ = (y_ + ur) >> 16;
1113
1114                                 switch (frame->v4l2_format.format) {
1115                                         case V4L2_PIX_FMT_RGB565:
1116                                                 g = LIMIT_RGB(g_);
1117                                                 *f_even++ = (0x1F & (LIMIT_RGB(b_) >> 3)) | (0xE0 & (g << 3));
1118                                                 *f_even++ = (0x07 & (          g   >> 5)) | (0xF8 & LIMIT_RGB(r_));
1119                                                 break;
1120                                         case V4L2_PIX_FMT_RGB24:
1121                                                 *f_even++ = LIMIT_RGB(b_);
1122                                                 *f_even++ = LIMIT_RGB(g_);
1123                                                 *f_even++ = LIMIT_RGB(r_);
1124                                                 break;
1125                                         case V4L2_PIX_FMT_RGB32:
1126                                                 *f_even++ = LIMIT_RGB(b_);
1127                                                 *f_even++ = LIMIT_RGB(g_);
1128                                                 *f_even++ = LIMIT_RGB(r_);
1129                                                 f_even++;
1130                                                 break;
1131                                         case V4L2_PIX_FMT_RGB555:
1132                                                 g = LIMIT_RGB(g_);
1133                                                 *f_even++ = (0x1F & (LIMIT_RGB(b_) >> 3)) | (0xE0 & (g << 2));
1134                                                 *f_even++ = (0x03 & (          g   >> 6)) |
1135                                                             (0x7C & (LIMIT_RGB(r_) >> 1));
1136                                                 break;
1137                                 }
1138                         }
1139                         clipmask_even_index += clipmask_add;
1140                         f_even += stretch_bytes;
1141
1142                         scratch_get_extra(usbvision, &y[0], &y_ptr, 2);
1143
1144                         if(frame->v4l2_format.format == V4L2_PIX_FMT_YUYV) {
1145                                 *f_odd++ = y[0];
1146                                 *f_odd++ = v;
1147                         }
1148                         else {
1149                                 y_ = 76284 * (y[0] - 16);
1150
1151                                 b_ = (y_ + vb) >> 16;
1152                                 g_ = (y_ + uvg)>> 16;
1153                                 r_ = (y_ + ur) >> 16;
1154
1155                                 switch (frame->v4l2_format.format) {
1156                                         case V4L2_PIX_FMT_RGB565:
1157                                                 g = LIMIT_RGB(g_);
1158                                                 *f_odd++ = (0x1F & (LIMIT_RGB(b_) >> 3)) | (0xE0 & (g << 3));
1159                                                 *f_odd++ = (0x07 & (          g   >> 5)) | (0xF8 & LIMIT_RGB(r_));
1160                                                 break;
1161                                         case V4L2_PIX_FMT_RGB24:
1162                                                 *f_odd++ = LIMIT_RGB(b_);
1163                                                 *f_odd++ = LIMIT_RGB(g_);
1164                                                 *f_odd++ = LIMIT_RGB(r_);
1165                                                 break;
1166                                         case V4L2_PIX_FMT_RGB32:
1167                                                 *f_odd++ = LIMIT_RGB(b_);
1168                                                 *f_odd++ = LIMIT_RGB(g_);
1169                                                 *f_odd++ = LIMIT_RGB(r_);
1170                                                 f_odd++;
1171                                                 break;
1172                                         case V4L2_PIX_FMT_RGB555:
1173                                                 g = LIMIT_RGB(g_);
1174                                                 *f_odd++ = (0x1F & (LIMIT_RGB(b_) >> 3)) | (0xE0 & (g << 2));
1175                                                 *f_odd++ = (0x03 & (          g   >> 6)) |
1176                                                            (0x7C & (LIMIT_RGB(r_) >> 1));
1177                                                 break;
1178                                 }
1179                         }
1180                         clipmask_odd_index += clipmask_add;
1181                         f_odd += stretch_bytes;
1182
1183                         if(frame->v4l2_format.format == V4L2_PIX_FMT_YUYV) {
1184                                 *f_odd++ = y[1];
1185                                 *f_odd++ = u;
1186                         }
1187                         else {
1188                                 y_ = 76284 * (y[1] - 16);
1189
1190                                 b_ = (y_ + vb) >> 16;
1191                                 g_ = (y_ + uvg)>> 16;
1192                                 r_ = (y_ + ur) >> 16;
1193
1194                                 switch (frame->v4l2_format.format) {
1195                                         case V4L2_PIX_FMT_RGB565:
1196                                                 g = LIMIT_RGB(g_);
1197                                                 *f_odd++ = (0x1F & (LIMIT_RGB(b_) >> 3)) | (0xE0 & (g << 3));
1198                                                 *f_odd++ = (0x07 & (          g   >> 5)) | (0xF8 & LIMIT_RGB(r_));
1199                                                 break;
1200                                         case V4L2_PIX_FMT_RGB24:
1201                                                 *f_odd++ = LIMIT_RGB(b_);
1202                                                 *f_odd++ = LIMIT_RGB(g_);
1203                                                 *f_odd++ = LIMIT_RGB(r_);
1204                                                 break;
1205                                         case V4L2_PIX_FMT_RGB32:
1206                                                 *f_odd++ = LIMIT_RGB(b_);
1207                                                 *f_odd++ = LIMIT_RGB(g_);
1208                                                 *f_odd++ = LIMIT_RGB(r_);
1209                                                 f_odd++;
1210                                                 break;
1211                                         case V4L2_PIX_FMT_RGB555:
1212                                                 g = LIMIT_RGB(g_);
1213                                                 *f_odd++ = (0x1F & (LIMIT_RGB(b_) >> 3)) | (0xE0 & (g << 2));
1214                                                 *f_odd++ = (0x03 & (          g   >> 6)) |
1215                                                            (0x7C & (LIMIT_RGB(r_) >> 1));
1216                                                 break;
1217                                 }
1218                         }
1219                         clipmask_odd_index += clipmask_add;
1220                         f_odd += stretch_bytes;
1221                 }
1222
1223                 scratch_rm_old(usbvision,y_step[block % y_step_size] * sub_block_size);
1224                 scratch_inc_extra_ptr(&y_ptr, y_step[(block + 2 * block_split) % y_step_size]
1225                                 * sub_block_size);
1226                 scratch_inc_extra_ptr(&u_ptr, uv_step[block % uv_step_size]
1227                                 * sub_block_size);
1228                 scratch_inc_extra_ptr(&v_ptr, uv_step[(block + 2 * block_split) % uv_step_size]
1229                                 * sub_block_size);
1230         }
1231
1232         scratch_rm_old(usbvision, pixel_per_line * 3 / 2
1233                         + block_split * sub_block_size);
1234
1235         frame->curline += 2 * usbvision->stretch_height;
1236         *pcopylen += frame->v4l2_linesize * 2 * usbvision->stretch_height;
1237
1238         if (frame->curline >= frame->frmheight)
1239                 return ParseState_NextFrame;
1240         else
1241                 return ParseState_Continue;
1242 }
1243
1244 /*
1245  * usbvision_parse_data()
1246  *
1247  * Generic routine to parse the scratch buffer. It employs either
1248  * usbvision_find_header() or usbvision_parse_lines() to do most
1249  * of work.
1250  *
1251  */
1252 static void usbvision_parse_data(struct usb_usbvision *usbvision)
1253 {
1254         struct usbvision_frame *frame;
1255         enum ParseState newstate;
1256         long copylen = 0;
1257         unsigned long lock_flags;
1258
1259         frame = usbvision->curFrame;
1260
1261         PDEBUG(DBG_PARSE, "parsing len=%d\n", scratch_len(usbvision));
1262
1263         while (1) {
1264
1265                 newstate = ParseState_Out;
1266                 if (scratch_len(usbvision)) {
1267                         if (frame->scanstate == ScanState_Scanning) {
1268                                 newstate = usbvision_find_header(usbvision);
1269                         }
1270                         else if (frame->scanstate == ScanState_Lines) {
1271                                 if (usbvision->isocMode == ISOC_MODE_YUV420) {
1272                                         newstate = usbvision_parse_lines_420(usbvision, &copylen);
1273                                 }
1274                                 else if (usbvision->isocMode == ISOC_MODE_YUV422) {
1275                                         newstate = usbvision_parse_lines_422(usbvision, &copylen);
1276                                 }
1277                                 else if (usbvision->isocMode == ISOC_MODE_COMPRESS) {
1278                                         newstate = usbvision_parse_compress(usbvision, &copylen);
1279                                 }
1280
1281                         }
1282                 }
1283                 if (newstate == ParseState_Continue) {
1284                         continue;
1285                 }
1286                 else if ((newstate == ParseState_NextFrame) || (newstate == ParseState_Out)) {
1287                         break;
1288                 }
1289                 else {
1290                         return; /* ParseState_EndParse */
1291                 }
1292         }
1293
1294         if (newstate == ParseState_NextFrame) {
1295                 frame->grabstate = FrameState_Done;
1296                 do_gettimeofday(&(frame->timestamp));
1297                 frame->sequence = usbvision->frame_num;
1298
1299                 spin_lock_irqsave(&usbvision->queue_lock, lock_flags);
1300                 list_move_tail(&(frame->frame), &usbvision->outqueue);
1301                 usbvision->curFrame = NULL;
1302                 spin_unlock_irqrestore(&usbvision->queue_lock, lock_flags);
1303
1304                 usbvision->frame_num++;
1305
1306                 /* This will cause the process to request another frame. */
1307                 if (waitqueue_active(&usbvision->wait_frame)) {
1308                         PDEBUG(DBG_PARSE, "Wake up !");
1309                         wake_up_interruptible(&usbvision->wait_frame);
1310                 }
1311         }
1312         else
1313                 frame->grabstate = FrameState_Grabbing;
1314
1315
1316         /* Update the frame's uncompressed length. */
1317         frame->scanlength += copylen;
1318 }
1319
1320
1321 /*
1322  * Make all of the blocks of data contiguous
1323  */
1324 static int usbvision_compress_isochronous(struct usb_usbvision *usbvision,
1325                                           struct urb *urb)
1326 {
1327         unsigned char *packet_data;
1328         int i, totlen = 0;
1329
1330         for (i = 0; i < urb->number_of_packets; i++) {
1331                 int packet_len = urb->iso_frame_desc[i].actual_length;
1332                 int packet_stat = urb->iso_frame_desc[i].status;
1333
1334                 packet_data = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
1335
1336                 /* Detect and ignore errored packets */
1337                 if (packet_stat) {      // packet_stat != 0 ?????????????
1338                         PDEBUG(DBG_ISOC, "data error: [%d] len=%d, status=%X", i, packet_len, packet_stat);
1339                         usbvision->isocErrCount++;
1340                         continue;
1341                 }
1342
1343                 /* Detect and ignore empty packets */
1344                 if (packet_len < 0) {
1345                         PDEBUG(DBG_ISOC, "error packet [%d]", i);
1346                         usbvision->isocSkipCount++;
1347                         continue;
1348                 }
1349                 else if (packet_len == 0) {     /* Frame end ????? */
1350                         PDEBUG(DBG_ISOC, "null packet [%d]", i);
1351                         usbvision->isocstate=IsocState_NoFrame;
1352                         usbvision->isocSkipCount++;
1353                         continue;
1354                 }
1355                 else if (packet_len > usbvision->isocPacketSize) {
1356                         PDEBUG(DBG_ISOC, "packet[%d] > isocPacketSize", i);
1357                         usbvision->isocSkipCount++;
1358                         continue;
1359                 }
1360
1361                 PDEBUG(DBG_ISOC, "packet ok [%d] len=%d", i, packet_len);
1362
1363                 if (usbvision->isocstate==IsocState_NoFrame) { //new frame begins
1364                         usbvision->isocstate=IsocState_InFrame;
1365                         scratch_mark_header(usbvision);
1366                         usbvision_measure_bandwidth(usbvision);
1367                         PDEBUG(DBG_ISOC, "packet with header");
1368                 }
1369
1370                 /*
1371                  * If usbvision continues to feed us with data but there is no
1372                  * consumption (if, for example, V4L client fell asleep) we
1373                  * may overflow the buffer. We have to move old data over to
1374                  * free room for new data. This is bad for old data. If we
1375                  * just drop new data then it's bad for new data... choose
1376                  * your favorite evil here.
1377                  */
1378                 if (scratch_free(usbvision) < packet_len) {
1379
1380                         usbvision->scratch_ovf_count++;
1381                         PDEBUG(DBG_ISOC, "scratch buf overflow! scr_len: %d, n: %d",
1382                                scratch_len(usbvision), packet_len);
1383                         scratch_rm_old(usbvision, packet_len - scratch_free(usbvision));
1384                 }
1385
1386                 /* Now we know that there is enough room in scratch buffer */
1387                 scratch_put(usbvision, packet_data, packet_len);
1388                 totlen += packet_len;
1389                 usbvision->isocDataCount += packet_len;
1390                 usbvision->isocPacketCount++;
1391         }
1392 #if ENABLE_HEXDUMP
1393         if (totlen > 0) {
1394                 static int foo = 0;
1395                 if (foo < 1) {
1396                         printk(KERN_DEBUG "+%d.\n", usbvision->scratchlen);
1397                         usbvision_hexdump(data0, (totlen > 64) ? 64 : totlen);
1398                         ++foo;
1399                 }
1400         }
1401 #endif
1402  return totlen;
1403 }
1404
1405 static void usbvision_isocIrq(struct urb *urb)
1406 {
1407         int errCode = 0;
1408         int len;
1409         struct usb_usbvision *usbvision = urb->context;
1410         int i;
1411         unsigned long startTime = jiffies;
1412         struct usbvision_frame **f;
1413
1414         /* We don't want to do anything if we are about to be removed! */
1415         if (!USBVISION_IS_OPERATIONAL(usbvision))
1416                 return;
1417
1418         f = &usbvision->curFrame;
1419
1420         /* Manage streaming interruption */
1421         if (usbvision->streaming == Stream_Interrupt) {
1422                 usbvision->streaming = Stream_Idle;
1423                 if ((*f)) {
1424                         (*f)->grabstate = FrameState_Ready;
1425                         (*f)->scanstate = ScanState_Scanning;
1426                 }
1427                 PDEBUG(DBG_IRQ, "stream interrupted");
1428                 wake_up_interruptible(&usbvision->wait_stream);
1429         }
1430
1431         /* Copy the data received into our scratch buffer */
1432         len = usbvision_compress_isochronous(usbvision, urb);
1433
1434         usbvision->isocUrbCount++;
1435         usbvision->urb_length = len;
1436
1437         if (usbvision->streaming == Stream_On) {
1438
1439                 /* If we collected enough data let's parse! */
1440                 if (scratch_len(usbvision) > USBVISION_HEADER_LENGTH) { /* 12 == header_length */
1441                         /*If we don't have a frame we're current working on, complain */
1442                         if(!list_empty(&(usbvision->inqueue))) {
1443                                 if (!(*f)) {
1444                                         (*f) = list_entry(usbvision->inqueue.next,struct usbvision_frame, frame);
1445                                 }
1446                                 usbvision_parse_data(usbvision);
1447                         }
1448                         else {
1449                                 PDEBUG(DBG_IRQ, "received data, but no one needs it");
1450                                 scratch_reset(usbvision);
1451                         }
1452                 }
1453         }
1454         else {
1455                 PDEBUG(DBG_IRQ, "received data, but no one needs it");
1456                 scratch_reset(usbvision);
1457         }
1458
1459         usbvision->timeInIrq += jiffies - startTime;
1460
1461         for (i = 0; i < USBVISION_URB_FRAMES; i++) {
1462                 urb->iso_frame_desc[i].status = 0;
1463                 urb->iso_frame_desc[i].actual_length = 0;
1464         }
1465
1466         urb->status = 0;
1467         urb->dev = usbvision->dev;
1468         errCode = usb_submit_urb (urb, GFP_ATOMIC);
1469
1470         /* Disable this warning.  By design of the driver. */
1471         //      if(errCode) {
1472         //              err("%s: usb_submit_urb failed: error %d", __FUNCTION__, errCode);
1473         //      }
1474
1475         return;
1476 }
1477
1478 /*************************************/
1479 /* Low level usbvision access functions */
1480 /*************************************/
1481
1482 /*
1483  * usbvision_read_reg()
1484  *
1485  * return  < 0 -> Error
1486  *        >= 0 -> Data
1487  */
1488
1489 int usbvision_read_reg(struct usb_usbvision *usbvision, unsigned char reg)
1490 {
1491         int errCode = 0;
1492         unsigned char buffer[1];
1493
1494         if (!USBVISION_IS_OPERATIONAL(usbvision))
1495                 return -1;
1496
1497         errCode = usb_control_msg(usbvision->dev, usb_rcvctrlpipe(usbvision->dev, 1),
1498                                 USBVISION_OP_CODE,
1499                                 USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_ENDPOINT,
1500                                 0, (__u16) reg, buffer, 1, HZ);
1501
1502         if (errCode < 0) {
1503                 err("%s: failed: error %d", __FUNCTION__, errCode);
1504                 return errCode;
1505         }
1506         return buffer[0];
1507 }
1508
1509 /*
1510  * usbvision_write_reg()
1511  *
1512  * return 1 -> Reg written
1513  *        0 -> usbvision is not yet ready
1514  *       -1 -> Something went wrong
1515  */
1516
1517 int usbvision_write_reg(struct usb_usbvision *usbvision, unsigned char reg,
1518                             unsigned char value)
1519 {
1520         int errCode = 0;
1521
1522         if (!USBVISION_IS_OPERATIONAL(usbvision))
1523                 return 0;
1524
1525         errCode = usb_control_msg(usbvision->dev, usb_sndctrlpipe(usbvision->dev, 1),
1526                                 USBVISION_OP_CODE,
1527                                 USB_DIR_OUT | USB_TYPE_VENDOR |
1528                                 USB_RECIP_ENDPOINT, 0, (__u16) reg, &value, 1, HZ);
1529
1530         if (errCode < 0) {
1531                 err("%s: failed: error %d", __FUNCTION__, errCode);
1532         }
1533         return errCode;
1534 }
1535
1536
1537 static void usbvision_ctrlUrb_complete(struct urb *urb)
1538 {
1539         struct usb_usbvision *usbvision = (struct usb_usbvision *)urb->context;
1540
1541         PDEBUG(DBG_IRQ, "");
1542         usbvision->ctrlUrbBusy = 0;
1543         if (waitqueue_active(&usbvision->ctrlUrb_wq)) {
1544                 wake_up_interruptible(&usbvision->ctrlUrb_wq);
1545         }
1546 }
1547
1548
1549 static int usbvision_write_reg_irq(struct usb_usbvision *usbvision,int address,
1550                                                                         unsigned char *data, int len)
1551 {
1552         int errCode = 0;
1553
1554         PDEBUG(DBG_IRQ, "");
1555         if (len > 8) {
1556                 return -EFAULT;
1557         }
1558 //      down(&usbvision->ctrlUrbLock);
1559         if (usbvision->ctrlUrbBusy) {
1560 //              up(&usbvision->ctrlUrbLock);
1561                 return -EBUSY;
1562         }
1563         usbvision->ctrlUrbBusy = 1;
1564 //      up(&usbvision->ctrlUrbLock);
1565
1566         usbvision->ctrlUrbSetup.bRequestType = USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_ENDPOINT;
1567         usbvision->ctrlUrbSetup.bRequest     = USBVISION_OP_CODE;
1568         usbvision->ctrlUrbSetup.wValue       = 0;
1569         usbvision->ctrlUrbSetup.wIndex       = cpu_to_le16(address);
1570         usbvision->ctrlUrbSetup.wLength      = cpu_to_le16(len);
1571         usb_fill_control_urb (usbvision->ctrlUrb, usbvision->dev,
1572                                                         usb_sndctrlpipe(usbvision->dev, 1),
1573                                                         (unsigned char *)&usbvision->ctrlUrbSetup,
1574                                                         (void *)usbvision->ctrlUrbBuffer, len,
1575                                                         usbvision_ctrlUrb_complete,
1576                                                         (void *)usbvision);
1577
1578         memcpy(usbvision->ctrlUrbBuffer, data, len);
1579
1580         errCode = usb_submit_urb(usbvision->ctrlUrb, GFP_ATOMIC);
1581         if (errCode < 0) {
1582                 // error in usb_submit_urb()
1583                 usbvision->ctrlUrbBusy = 0;
1584         }
1585         PDEBUG(DBG_IRQ, "submit %d byte: error %d", len, errCode);
1586         return errCode;
1587 }
1588
1589
1590 static int usbvision_init_compression(struct usb_usbvision *usbvision)
1591 {
1592         int errCode = 0;
1593
1594         usbvision->lastIsocFrameNum = -1;
1595         usbvision->isocDataCount = 0;
1596         usbvision->isocPacketCount = 0;
1597         usbvision->isocSkipCount = 0;
1598         usbvision->comprLevel = 50;
1599         usbvision->lastComprLevel = -1;
1600         usbvision->isocUrbCount = 0;
1601         usbvision->requestIntra = 1;
1602         usbvision->isocMeasureBandwidthCount = 0;
1603
1604         return errCode;
1605 }
1606
1607 /* this function measures the used bandwidth since last call
1608  * return:    0 : no error
1609  * sets usedBandwidth to 1-100 : 1-100% of full bandwidth resp. to isocPacketSize
1610  */
1611 static int usbvision_measure_bandwidth (struct usb_usbvision *usbvision)
1612 {
1613         int errCode = 0;
1614
1615         if (usbvision->isocMeasureBandwidthCount < 2) { // this gives an average bandwidth of 3 frames
1616                 usbvision->isocMeasureBandwidthCount++;
1617                 return errCode;
1618         }
1619         if ((usbvision->isocPacketSize > 0) && (usbvision->isocPacketCount > 0)) {
1620                 usbvision->usedBandwidth = usbvision->isocDataCount /
1621                                         (usbvision->isocPacketCount + usbvision->isocSkipCount) *
1622                                         100 / usbvision->isocPacketSize;
1623         }
1624         usbvision->isocMeasureBandwidthCount = 0;
1625         usbvision->isocDataCount = 0;
1626         usbvision->isocPacketCount = 0;
1627         usbvision->isocSkipCount = 0;
1628         return errCode;
1629 }
1630
1631 static int usbvision_adjust_compression (struct usb_usbvision *usbvision)
1632 {
1633         int errCode = 0;
1634         unsigned char buffer[6];
1635
1636         PDEBUG(DBG_IRQ, "");
1637         if ((adjustCompression) && (usbvision->usedBandwidth > 0)) {
1638                 usbvision->comprLevel += (usbvision->usedBandwidth - 90) / 2;
1639                 RESTRICT_TO_RANGE(usbvision->comprLevel, 0, 100);
1640                 if (usbvision->comprLevel != usbvision->lastComprLevel) {
1641                         int distorsion;
1642                         if (usbvision->bridgeType == BRIDGE_NT1004 || usbvision->bridgeType == BRIDGE_NT1005) {
1643                                 buffer[0] = (unsigned char)(4 + 16 * usbvision->comprLevel / 100);      // PCM Threshold 1
1644                                 buffer[1] = (unsigned char)(4 + 8 * usbvision->comprLevel / 100);       // PCM Threshold 2
1645                                 distorsion = 7 + 248 * usbvision->comprLevel / 100;
1646                                 buffer[2] = (unsigned char)(distorsion & 0xFF);                         // Average distorsion Threshold (inter)
1647                                 buffer[3] = (unsigned char)(distorsion & 0xFF);                         // Average distorsion Threshold (intra)
1648                                 distorsion = 1 + 42 * usbvision->comprLevel / 100;
1649                                 buffer[4] = (unsigned char)(distorsion & 0xFF);                         // Maximum distorsion Threshold (inter)
1650                                 buffer[5] = (unsigned char)(distorsion & 0xFF);                         // Maximum distorsion Threshold (intra)
1651                         }
1652                         else { //BRIDGE_NT1003
1653                                 buffer[0] = (unsigned char)(4 + 16 * usbvision->comprLevel / 100);      // PCM threshold 1
1654                                 buffer[1] = (unsigned char)(4 + 8 * usbvision->comprLevel / 100);       // PCM threshold 2
1655                                 distorsion = 2 + 253 * usbvision->comprLevel / 100;
1656                                 buffer[2] = (unsigned char)(distorsion & 0xFF);                         // distorsion threshold bit0-7
1657                                 buffer[3] = 0;  //(unsigned char)((distorsion >> 8) & 0x0F);            // distorsion threshold bit 8-11
1658                                 distorsion = 0 + 43 * usbvision->comprLevel / 100;
1659                                 buffer[4] = (unsigned char)(distorsion & 0xFF);                         // maximum distorsion bit0-7
1660                                 buffer[5] = 0; //(unsigned char)((distorsion >> 8) & 0x01);             // maximum distorsion bit 8
1661                         }
1662                         errCode = usbvision_write_reg_irq(usbvision, USBVISION_PCM_THR1, buffer, 6);
1663                         if (errCode == 0){
1664                                 PDEBUG(DBG_IRQ, "new compr params %#02x %#02x %#02x %#02x %#02x %#02x", buffer[0],
1665                                                                 buffer[1], buffer[2], buffer[3], buffer[4], buffer[5]);
1666                                 usbvision->lastComprLevel = usbvision->comprLevel;
1667                         }
1668                 }
1669         }
1670         return errCode;
1671 }
1672
1673 static int usbvision_request_intra (struct usb_usbvision *usbvision)
1674 {
1675         int errCode = 0;
1676         unsigned char buffer[1];
1677
1678         PDEBUG(DBG_IRQ, "");
1679         usbvision->requestIntra = 1;
1680         buffer[0] = 1;
1681         usbvision_write_reg_irq(usbvision, USBVISION_FORCE_INTRA, buffer, 1);
1682         return errCode;
1683 }
1684
1685 static int usbvision_unrequest_intra (struct usb_usbvision *usbvision)
1686 {
1687         int errCode = 0;
1688         unsigned char buffer[1];
1689
1690         PDEBUG(DBG_IRQ, "");
1691         usbvision->requestIntra = 0;
1692         buffer[0] = 0;
1693         usbvision_write_reg_irq(usbvision, USBVISION_FORCE_INTRA, buffer, 1);
1694         return errCode;
1695 }
1696
1697 /*******************************
1698  * usbvision utility functions
1699  *******************************/
1700
1701 int usbvision_power_off(struct usb_usbvision *usbvision)
1702 {
1703         int errCode = 0;
1704
1705         PDEBUG(DBG_FUNC, "");
1706
1707         errCode = usbvision_write_reg(usbvision, USBVISION_PWR_REG, USBVISION_SSPND_EN);
1708         if (errCode == 1) {
1709                 usbvision->power = 0;
1710         }
1711         PDEBUG(DBG_FUNC, "%s: errCode %d", (errCode!=1)?"ERROR":"power is off", errCode);
1712         return errCode;
1713 }
1714
1715 /*
1716  * usbvision_set_video_format()
1717  *
1718  */
1719 static int usbvision_set_video_format(struct usb_usbvision *usbvision, int format)
1720 {
1721         static const char proc[] = "usbvision_set_video_format";
1722         int rc;
1723         unsigned char value[2];
1724
1725         if (!USBVISION_IS_OPERATIONAL(usbvision))
1726                 return 0;
1727
1728         PDEBUG(DBG_FUNC, "isocMode %#02x", format);
1729
1730         if ((format != ISOC_MODE_YUV422)
1731             && (format != ISOC_MODE_YUV420)
1732             && (format != ISOC_MODE_COMPRESS)) {
1733                 printk(KERN_ERR "usbvision: unknown video format %02x, using default YUV420",
1734                        format);
1735                 format = ISOC_MODE_YUV420;
1736         }
1737         value[0] = 0x0A;  //TODO: See the effect of the filter
1738         value[1] = format;
1739         rc = usb_control_msg(usbvision->dev, usb_sndctrlpipe(usbvision->dev, 1),
1740                              USBVISION_OP_CODE,
1741                              USB_DIR_OUT | USB_TYPE_VENDOR |
1742                              USB_RECIP_ENDPOINT, 0,
1743                              (__u16) USBVISION_FILT_CONT, value, 2, HZ);
1744
1745         if (rc < 0) {
1746                 printk(KERN_ERR "%s: ERROR=%d. USBVISION stopped - "
1747                        "reconnect or reload driver.\n", proc, rc);
1748         }
1749         usbvision->isocMode = format;
1750         return rc;
1751 }
1752
1753 /*
1754  * usbvision_set_output()
1755  *
1756  */
1757
1758 int usbvision_set_output(struct usb_usbvision *usbvision, int width,
1759                          int height)
1760 {
1761         int errCode = 0;
1762         int UsbWidth, UsbHeight;
1763         unsigned int frameRate=0, frameDrop=0;
1764         unsigned char value[4];
1765
1766         if (!USBVISION_IS_OPERATIONAL(usbvision)) {
1767                 return 0;
1768         }
1769
1770         if (width > MAX_USB_WIDTH) {
1771                 UsbWidth = width / 2;
1772                 usbvision->stretch_width = 2;
1773         }
1774         else {
1775                 UsbWidth = width;
1776                 usbvision->stretch_width = 1;
1777         }
1778
1779         if (height > MAX_USB_HEIGHT) {
1780                 UsbHeight = height / 2;
1781                 usbvision->stretch_height = 2;
1782         }
1783         else {
1784                 UsbHeight = height;
1785                 usbvision->stretch_height = 1;
1786         }
1787
1788         RESTRICT_TO_RANGE(UsbWidth, MIN_FRAME_WIDTH, MAX_USB_WIDTH);
1789         UsbWidth &= ~(MIN_FRAME_WIDTH-1);
1790         RESTRICT_TO_RANGE(UsbHeight, MIN_FRAME_HEIGHT, MAX_USB_HEIGHT);
1791         UsbHeight &= ~(1);
1792
1793         PDEBUG(DBG_FUNC, "usb %dx%d; screen %dx%d; stretch %dx%d",
1794                                                 UsbWidth, UsbHeight, width, height,
1795                                                 usbvision->stretch_width, usbvision->stretch_height);
1796
1797         /* I'll not rewrite the same values */
1798         if ((UsbWidth != usbvision->curwidth) || (UsbHeight != usbvision->curheight)) {
1799                 value[0] = UsbWidth & 0xff;             //LSB
1800                 value[1] = (UsbWidth >> 8) & 0x03;      //MSB
1801                 value[2] = UsbHeight & 0xff;            //LSB
1802                 value[3] = (UsbHeight >> 8) & 0x03;     //MSB
1803
1804                 errCode = usb_control_msg(usbvision->dev, usb_sndctrlpipe(usbvision->dev, 1),
1805                              USBVISION_OP_CODE,
1806                              USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_ENDPOINT,
1807                                  0, (__u16) USBVISION_LXSIZE_O, value, 4, HZ);
1808
1809                 if (errCode < 0) {
1810                         err("%s failed: error %d", __FUNCTION__, errCode);
1811                         return errCode;
1812                 }
1813                 usbvision->curwidth = usbvision->stretch_width * UsbWidth;
1814                 usbvision->curheight = usbvision->stretch_height * UsbHeight;
1815         }
1816
1817         if (usbvision->isocMode == ISOC_MODE_YUV422) {
1818                 frameRate = (usbvision->isocPacketSize * 1000) / (UsbWidth * UsbHeight * 2);
1819         }
1820         else if (usbvision->isocMode == ISOC_MODE_YUV420) {
1821                 frameRate = (usbvision->isocPacketSize * 1000) / ((UsbWidth * UsbHeight * 12) / 8);
1822         }
1823         else {
1824                 frameRate = FRAMERATE_MAX;
1825         }
1826
1827         if (usbvision->tvnorm->id & V4L2_STD_625_50) {
1828                 frameDrop = frameRate * 32 / 25 - 1;
1829         }
1830         else if (usbvision->tvnorm->id & V4L2_STD_525_60) {
1831                 frameDrop = frameRate * 32 / 30 - 1;
1832         }
1833
1834         RESTRICT_TO_RANGE(frameDrop, FRAMERATE_MIN, FRAMERATE_MAX);
1835
1836         PDEBUG(DBG_FUNC, "frameRate %d fps, frameDrop %d", frameRate, frameDrop);
1837
1838         frameDrop = FRAMERATE_MAX;      // We can allow the maximum here, because dropping is controlled
1839
1840         /* frameDrop = 7; => framePhase = 1, 5, 9, 13, 17, 21, 25, 0, 4, 8, ...
1841                 => frameSkip = 4;
1842                 => frameRate = (7 + 1) * 25 / 32 = 200 / 32 = 6.25;
1843
1844            frameDrop = 9; => framePhase = 1, 5, 8, 11, 14, 17, 21, 24, 27, 1, 4, 8, ...
1845             => frameSkip = 4, 3, 3, 3, 3, 4, 3, 3, 3, 3, 4, ...
1846                 => frameRate = (9 + 1) * 25 / 32 = 250 / 32 = 7.8125;
1847         */
1848         errCode = usbvision_write_reg(usbvision, USBVISION_FRM_RATE, frameDrop);
1849         return errCode;
1850 }
1851
1852
1853 /*
1854  * usbvision_frames_alloc
1855  * allocate the maximum frames this driver can manage
1856  */
1857 int usbvision_frames_alloc(struct usb_usbvision *usbvision)
1858 {
1859         int i;
1860
1861         /* Allocate memory for the frame buffers */
1862         usbvision->max_frame_size = MAX_FRAME_SIZE;
1863         usbvision->fbuf_size = USBVISION_NUMFRAMES * usbvision->max_frame_size;
1864         usbvision->fbuf = usbvision_rvmalloc(usbvision->fbuf_size);
1865
1866         if(usbvision->fbuf == NULL) {
1867                 err("%s: unable to allocate %d bytes for fbuf ",
1868                     __FUNCTION__, usbvision->fbuf_size);
1869                 return -ENOMEM;
1870         }
1871         spin_lock_init(&usbvision->queue_lock);
1872         init_waitqueue_head(&usbvision->wait_frame);
1873         init_waitqueue_head(&usbvision->wait_stream);
1874
1875         /* Allocate all buffers */
1876         for (i = 0; i < USBVISION_NUMFRAMES; i++) {
1877                 usbvision->frame[i].index = i;
1878                 usbvision->frame[i].grabstate = FrameState_Unused;
1879                 usbvision->frame[i].data = usbvision->fbuf +
1880                         i * usbvision->max_frame_size;
1881                 /*
1882                  * Set default sizes for read operation.
1883                  */
1884                 usbvision->stretch_width = 1;
1885                 usbvision->stretch_height = 1;
1886                 usbvision->frame[i].width = usbvision->curwidth;
1887                 usbvision->frame[i].height = usbvision->curheight;
1888                 usbvision->frame[i].bytes_read = 0;
1889         }
1890         return 0;
1891 }
1892
1893 /*
1894  * usbvision_frames_free
1895  * frees memory allocated for the frames
1896  */
1897 void usbvision_frames_free(struct usb_usbvision *usbvision)
1898 {
1899         /* Have to free all that memory */
1900         if (usbvision->fbuf != NULL) {
1901                 usbvision_rvfree(usbvision->fbuf, usbvision->fbuf_size);
1902                 usbvision->fbuf = NULL;
1903         }
1904 }
1905 /*
1906  * usbvision_empty_framequeues()
1907  * prepare queues for incoming and outgoing frames
1908  */
1909 void usbvision_empty_framequeues(struct usb_usbvision *usbvision)
1910 {
1911         u32 i;
1912
1913         INIT_LIST_HEAD(&(usbvision->inqueue));
1914         INIT_LIST_HEAD(&(usbvision->outqueue));
1915
1916         for (i = 0; i < USBVISION_NUMFRAMES; i++) {
1917                 usbvision->frame[i].grabstate = FrameState_Unused;
1918                 usbvision->frame[i].bytes_read = 0;
1919         }
1920 }
1921
1922 /*
1923  * usbvision_stream_interrupt()
1924  * stops streaming
1925  */
1926 int usbvision_stream_interrupt(struct usb_usbvision *usbvision)
1927 {
1928         int ret = 0;
1929
1930         /* stop reading from the device */
1931
1932         usbvision->streaming = Stream_Interrupt;
1933         ret = wait_event_timeout(usbvision->wait_stream,
1934                                  (usbvision->streaming == Stream_Idle),
1935                                  msecs_to_jiffies(USBVISION_NUMSBUF*USBVISION_URB_FRAMES));
1936         return ret;
1937 }
1938
1939 /*
1940  * usbvision_set_compress_params()
1941  *
1942  */
1943
1944 static int usbvision_set_compress_params(struct usb_usbvision *usbvision)
1945 {
1946         static const char proc[] = "usbvision_set_compresion_params: ";
1947         int rc;
1948         unsigned char value[6];
1949
1950         value[0] = 0x0F;    // Intra-Compression cycle
1951         value[1] = 0x01;    // Reg.45 one line per strip
1952         value[2] = 0x00;    // Reg.46 Force intra mode on all new frames
1953         value[3] = 0x00;    // Reg.47 FORCE_UP <- 0 normal operation (not force)
1954         value[4] = 0xA2;    // Reg.48 BUF_THR I'm not sure if this does something in not compressed mode.
1955         value[5] = 0x00;    // Reg.49 DVI_YUV This has nothing to do with compression
1956
1957         //catched values for NT1004
1958         // value[0] = 0xFF; // Never apply intra mode automatically
1959         // value[1] = 0xF1; // Use full frame height for virtual strip width; One line per strip
1960         // value[2] = 0x01; // Force intra mode on all new frames
1961         // value[3] = 0x00; // Strip size 400 Bytes; do not force up
1962         // value[4] = 0xA2; //
1963         if (!USBVISION_IS_OPERATIONAL(usbvision))
1964                 return 0;
1965
1966         rc = usb_control_msg(usbvision->dev, usb_sndctrlpipe(usbvision->dev, 1),
1967                              USBVISION_OP_CODE,
1968                              USB_DIR_OUT | USB_TYPE_VENDOR |
1969                              USB_RECIP_ENDPOINT, 0,
1970                              (__u16) USBVISION_INTRA_CYC, value, 5, HZ);
1971
1972         if (rc < 0) {
1973                 printk(KERN_ERR "%sERROR=%d. USBVISION stopped - "
1974                        "reconnect or reload driver.\n", proc, rc);
1975                 return rc;
1976         }
1977
1978         if (usbvision->bridgeType == BRIDGE_NT1004) {
1979                 value[0] =  20; // PCM Threshold 1
1980                 value[1] =  12; // PCM Threshold 2
1981                 value[2] = 255; // Distorsion Threshold inter
1982                 value[3] = 255; // Distorsion Threshold intra
1983                 value[4] =  43; // Max Distorsion inter
1984                 value[5] =  43; // Max Distorsion intra
1985         }
1986         else {
1987                 value[0] =  20; // PCM Threshold 1
1988                 value[1] =  12; // PCM Threshold 2
1989                 value[2] = 255; // Distorsion Threshold d7-d0
1990                 value[3] =   0; // Distorsion Threshold d11-d8
1991                 value[4] =  43; // Max Distorsion d7-d0
1992                 value[5] =   0; // Max Distorsion d8
1993         }
1994
1995         if (!USBVISION_IS_OPERATIONAL(usbvision))
1996                 return 0;
1997
1998         rc = usb_control_msg(usbvision->dev, usb_sndctrlpipe(usbvision->dev, 1),
1999                              USBVISION_OP_CODE,
2000                              USB_DIR_OUT | USB_TYPE_VENDOR |
2001                              USB_RECIP_ENDPOINT, 0,
2002                              (__u16) USBVISION_PCM_THR1, value, 6, HZ);
2003
2004         if (rc < 0) {
2005                 printk(KERN_ERR "%sERROR=%d. USBVISION stopped - "
2006                        "reconnect or reload driver.\n", proc, rc);
2007                 return rc;
2008         }
2009
2010
2011         return rc;
2012 }
2013
2014
2015 /*
2016  * usbvision_set_input()
2017  *
2018  * Set the input (saa711x, ...) size x y and other misc input params
2019  * I've no idea if this parameters are right
2020  *
2021  */
2022 int usbvision_set_input(struct usb_usbvision *usbvision)
2023 {
2024         static const char proc[] = "usbvision_set_input: ";
2025         int rc;
2026         unsigned char value[8];
2027         unsigned char dvi_yuv_value;
2028
2029         if (!USBVISION_IS_OPERATIONAL(usbvision))
2030                 return 0;
2031
2032         /* Set input format expected from decoder*/
2033         if (usbvision_device_data[usbvision->DevModel].Vin_Reg1 >= 0) {
2034                 value[0] = usbvision_device_data[usbvision->DevModel].Vin_Reg1 & 0xff;
2035         } else if(usbvision_device_data[usbvision->DevModel].Codec == CODEC_SAA7113) {
2036                 /* SAA7113 uses 8 bit output */
2037                 value[0] = USBVISION_8_422_SYNC;
2038         } else {
2039                 /* I'm sure only about d2-d0 [010] 16 bit 4:2:2 usin sync pulses
2040                  * as that is how saa7111 is configured */
2041                 value[0] = USBVISION_16_422_SYNC;
2042                 /* | USBVISION_VSNC_POL | USBVISION_VCLK_POL);*/
2043         }
2044
2045         rc = usbvision_write_reg(usbvision, USBVISION_VIN_REG1, value[0]);
2046         if (rc < 0) {
2047                 printk(KERN_ERR "%sERROR=%d. USBVISION stopped - "
2048                        "reconnect or reload driver.\n", proc, rc);
2049                 return rc;
2050         }
2051
2052
2053         if (usbvision->tvnorm->id & V4L2_STD_PAL) {
2054                 value[0] = 0xC0;
2055                 value[1] = 0x02;        //0x02C0 -> 704 Input video line length
2056                 value[2] = 0x20;
2057                 value[3] = 0x01;        //0x0120 -> 288 Input video n. of lines
2058                 value[4] = 0x60;
2059                 value[5] = 0x00;        //0x0060 -> 96 Input video h offset
2060                 value[6] = 0x16;
2061                 value[7] = 0x00;        //0x0016 -> 22 Input video v offset
2062         } else if (usbvision->tvnorm->id & V4L2_STD_SECAM) {
2063                 value[0] = 0xC0;
2064                 value[1] = 0x02;        //0x02C0 -> 704 Input video line length
2065                 value[2] = 0x20;
2066                 value[3] = 0x01;        //0x0120 -> 288 Input video n. of lines
2067                 value[4] = 0x01;
2068                 value[5] = 0x00;        //0x0001 -> 01 Input video h offset
2069                 value[6] = 0x01;
2070                 value[7] = 0x00;        //0x0001 -> 01 Input video v offset
2071         } else {        /* V4L2_STD_NTSC */
2072                 value[0] = 0xD0;
2073                 value[1] = 0x02;        //0x02D0 -> 720 Input video line length
2074                 value[2] = 0xF0;
2075                 value[3] = 0x00;        //0x00F0 -> 240 Input video number of lines
2076                 value[4] = 0x50;
2077                 value[5] = 0x00;        //0x0050 -> 80 Input video h offset
2078                 value[6] = 0x10;
2079                 value[7] = 0x00;        //0x0010 -> 16 Input video v offset
2080         }
2081
2082         if (usbvision_device_data[usbvision->DevModel].X_Offset >= 0) {
2083                 value[4]=usbvision_device_data[usbvision->DevModel].X_Offset & 0xff;
2084                 value[5]=(usbvision_device_data[usbvision->DevModel].X_Offset & 0x0300) >> 8;
2085         }
2086
2087         if (usbvision_device_data[usbvision->DevModel].Y_Offset >= 0) {
2088                 value[6]=usbvision_device_data[usbvision->DevModel].Y_Offset & 0xff;
2089                 value[7]=(usbvision_device_data[usbvision->DevModel].Y_Offset & 0x0300) >> 8;
2090         }
2091
2092         rc = usb_control_msg(usbvision->dev, usb_sndctrlpipe(usbvision->dev, 1),
2093                              USBVISION_OP_CODE, /* USBVISION specific code */
2094                              USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_ENDPOINT, 0,
2095                              (__u16) USBVISION_LXSIZE_I, value, 8, HZ);
2096         if (rc < 0) {
2097                 printk(KERN_ERR "%sERROR=%d. USBVISION stopped - "
2098                        "reconnect or reload driver.\n", proc, rc);
2099                 return rc;
2100         }
2101
2102
2103         dvi_yuv_value = 0x00;   /* U comes after V, Ya comes after U/V, Yb comes after Yb */
2104
2105         if(usbvision_device_data[usbvision->DevModel].Dvi_yuv >= 0){
2106                 dvi_yuv_value = usbvision_device_data[usbvision->DevModel].Dvi_yuv & 0xff;
2107         }
2108         else if(usbvision_device_data[usbvision->DevModel].Codec == CODEC_SAA7113) {
2109         /* This changes as the fine sync control changes. Further investigation necessary */
2110                 dvi_yuv_value = 0x06;
2111         }
2112
2113         return (usbvision_write_reg(usbvision, USBVISION_DVI_YUV, dvi_yuv_value));
2114 }
2115
2116
2117 /*
2118  * usbvision_set_dram_settings()
2119  *
2120  * Set the buffer address needed by the usbvision dram to operate
2121  * This values has been taken with usbsnoop.
2122  *
2123  */
2124
2125 static int usbvision_set_dram_settings(struct usb_usbvision *usbvision)
2126 {
2127         int rc;
2128         unsigned char value[8];
2129
2130         if (usbvision->isocMode == ISOC_MODE_COMPRESS) {
2131                 value[0] = 0x42;
2132                 value[1] = 0x71;
2133                 value[2] = 0xff;
2134                 value[3] = 0x00;
2135                 value[4] = 0x98;
2136                 value[5] = 0xe0;
2137                 value[6] = 0x71;
2138                 value[7] = 0xff;
2139                 // UR:  0x0E200-0x3FFFF = 204288 Words (1 Word = 2 Byte)
2140                 // FDL: 0x00000-0x0E099 =  57498 Words
2141                 // VDW: 0x0E3FF-0x3FFFF
2142         }
2143         else {
2144                 value[0] = 0x42;
2145                 value[1] = 0x00;
2146                 value[2] = 0xff;
2147                 value[3] = 0x00;
2148                 value[4] = 0x00;
2149                 value[5] = 0x00;
2150                 value[6] = 0x00;
2151                 value[7] = 0xff;
2152         }
2153         /* These are the values of the address of the video buffer,
2154          * they have to be loaded into the USBVISION_DRM_PRM1-8
2155          *
2156          * Start address of video output buffer for read:       drm_prm1-2 -> 0x00000
2157          * End address of video output buffer for read:         drm_prm1-3 -> 0x1ffff
2158          * Start address of video frame delay buffer:           drm_prm1-4 -> 0x20000
2159          *    Only used in compressed mode
2160          * End address of video frame delay buffer:             drm_prm1-5-6 -> 0x3ffff
2161          *    Only used in compressed mode
2162          * Start address of video output buffer for write:      drm_prm1-7 -> 0x00000
2163          * End address of video output buffer for write:        drm_prm1-8 -> 0x1ffff
2164          */
2165
2166         if (!USBVISION_IS_OPERATIONAL(usbvision))
2167                 return 0;
2168
2169         rc = usb_control_msg(usbvision->dev, usb_sndctrlpipe(usbvision->dev, 1),
2170                              USBVISION_OP_CODE, /* USBVISION specific code */
2171                              USB_DIR_OUT | USB_TYPE_VENDOR |
2172                              USB_RECIP_ENDPOINT, 0,
2173                              (__u16) USBVISION_DRM_PRM1, value, 8, HZ);
2174
2175         if (rc < 0) {
2176                 err("%sERROR=%d", __FUNCTION__, rc);
2177                 return rc;
2178         }
2179
2180         /* Restart the video buffer logic */
2181         if ((rc = usbvision_write_reg(usbvision, USBVISION_DRM_CONT, USBVISION_RES_UR |
2182                                    USBVISION_RES_FDL | USBVISION_RES_VDW)) < 0)
2183                 return rc;
2184         rc = usbvision_write_reg(usbvision, USBVISION_DRM_CONT, 0x00);
2185
2186         return rc;
2187 }
2188
2189 /*
2190  * ()
2191  *
2192  * Power on the device, enables suspend-resume logic
2193  * &  reset the isoc End-Point
2194  *
2195  */
2196
2197 int usbvision_power_on(struct usb_usbvision *usbvision)
2198 {
2199         int errCode = 0;
2200
2201         PDEBUG(DBG_FUNC, "");
2202
2203         usbvision_write_reg(usbvision, USBVISION_PWR_REG, USBVISION_SSPND_EN);
2204         usbvision_write_reg(usbvision, USBVISION_PWR_REG,
2205                          USBVISION_SSPND_EN | USBVISION_RES2);
2206
2207         usbvision_write_reg(usbvision, USBVISION_PWR_REG,
2208                          USBVISION_SSPND_EN | USBVISION_PWR_VID);
2209         errCode = usbvision_write_reg(usbvision, USBVISION_PWR_REG,
2210                                                 USBVISION_SSPND_EN | USBVISION_PWR_VID | USBVISION_RES2);
2211         if (errCode == 1) {
2212                 usbvision->power = 1;
2213         }
2214         PDEBUG(DBG_FUNC, "%s: errCode %d", (errCode<0)?"ERROR":"power is on", errCode);
2215         return errCode;
2216 }
2217
2218
2219 /*
2220  * usbvision timer stuff
2221  */
2222
2223 // to call usbvision_power_off from task queue
2224 static void call_usbvision_power_off(struct work_struct *work)
2225 {
2226         struct usb_usbvision *usbvision = container_of(work, struct usb_usbvision, powerOffWork);
2227
2228         PDEBUG(DBG_FUNC, "");
2229         down_interruptible(&usbvision->lock);
2230         if(usbvision->user == 0) {
2231                 usbvision_i2c_usb_del_bus(&usbvision->i2c_adap);
2232
2233                 usbvision_power_off(usbvision);
2234                 usbvision->initialized = 0;
2235         }
2236         up(&usbvision->lock);
2237 }
2238
2239 static void usbvision_powerOffTimer(unsigned long data)
2240 {
2241         struct usb_usbvision *usbvision = (void *) data;
2242
2243         PDEBUG(DBG_FUNC, "");
2244         del_timer(&usbvision->powerOffTimer);
2245         INIT_WORK(&usbvision->powerOffWork, call_usbvision_power_off);
2246         (void) schedule_work(&usbvision->powerOffWork);
2247
2248 }
2249
2250 void usbvision_init_powerOffTimer(struct usb_usbvision *usbvision)
2251 {
2252         init_timer(&usbvision->powerOffTimer);
2253         usbvision->powerOffTimer.data = (long) usbvision;
2254         usbvision->powerOffTimer.function = usbvision_powerOffTimer;
2255 }
2256
2257 void usbvision_set_powerOffTimer(struct usb_usbvision *usbvision)
2258 {
2259         mod_timer(&usbvision->powerOffTimer, jiffies + USBVISION_POWEROFF_TIME);
2260 }
2261
2262 void usbvision_reset_powerOffTimer(struct usb_usbvision *usbvision)
2263 {
2264         if (timer_pending(&usbvision->powerOffTimer)) {
2265                 del_timer(&usbvision->powerOffTimer);
2266         }
2267 }
2268
2269 /*
2270  * usbvision_begin_streaming()
2271  * Sure you have to put bit 7 to 0, if not incoming frames are droped, but no
2272  * idea about the rest
2273  */
2274 int usbvision_begin_streaming(struct usb_usbvision *usbvision)
2275 {
2276         int errCode = 0;
2277
2278         if (usbvision->isocMode == ISOC_MODE_COMPRESS) {
2279                 usbvision_init_compression(usbvision);
2280         }
2281         errCode = usbvision_write_reg(usbvision, USBVISION_VIN_REG2, USBVISION_NOHVALID |
2282                                                                                 usbvision->Vin_Reg2_Preset);
2283         return errCode;
2284 }
2285
2286 /*
2287  * usbvision_restart_isoc()
2288  * Not sure yet if touching here PWR_REG make loose the config
2289  */
2290
2291 int usbvision_restart_isoc(struct usb_usbvision *usbvision)
2292 {
2293         int ret;
2294
2295         if (
2296             (ret =
2297              usbvision_write_reg(usbvision, USBVISION_PWR_REG,
2298                               USBVISION_SSPND_EN | USBVISION_PWR_VID)) < 0)
2299                 return ret;
2300         if (
2301             (ret =
2302              usbvision_write_reg(usbvision, USBVISION_PWR_REG,
2303                               USBVISION_SSPND_EN | USBVISION_PWR_VID |
2304                               USBVISION_RES2)) < 0)
2305                 return ret;
2306         if (
2307             (ret =
2308              usbvision_write_reg(usbvision, USBVISION_VIN_REG2,
2309                               USBVISION_KEEP_BLANK | USBVISION_NOHVALID |
2310                                   usbvision->Vin_Reg2_Preset)) < 0) return ret;
2311
2312         /* TODO: schedule timeout */
2313         while ((usbvision_read_reg(usbvision, USBVISION_STATUS_REG) & 0x01) != 1);
2314
2315         return 0;
2316 }
2317
2318 int usbvision_audio_off(struct usb_usbvision *usbvision)
2319 {
2320         if (usbvision_write_reg(usbvision, USBVISION_IOPIN_REG, USBVISION_AUDIO_MUTE) < 0) {
2321                 printk(KERN_ERR "usbvision_audio_off: can't wirte reg\n");
2322                 return -1;
2323         }
2324         usbvision->AudioMute = 0;
2325         usbvision->AudioChannel = USBVISION_AUDIO_MUTE;
2326         return 0;
2327 }
2328
2329 int usbvision_set_audio(struct usb_usbvision *usbvision, int AudioChannel)
2330 {
2331         if (!usbvision->AudioMute) {
2332                 if (usbvision_write_reg(usbvision, USBVISION_IOPIN_REG, AudioChannel) < 0) {
2333                         printk(KERN_ERR "usbvision_set_audio: can't write iopin register for audio switching\n");
2334                         return -1;
2335                 }
2336         }
2337         usbvision->AudioChannel = AudioChannel;
2338         return 0;
2339 }
2340
2341 int usbvision_setup(struct usb_usbvision *usbvision,int format)
2342 {
2343         usbvision_set_video_format(usbvision, format);
2344         usbvision_set_dram_settings(usbvision);
2345         usbvision_set_compress_params(usbvision);
2346         usbvision_set_input(usbvision);
2347         usbvision_set_output(usbvision, MAX_USB_WIDTH, MAX_USB_HEIGHT);
2348         usbvision_restart_isoc(usbvision);
2349
2350         /* cosas del PCM */
2351         return USBVISION_IS_OPERATIONAL(usbvision);
2352 }
2353
2354 /*
2355  * usbvision_init_isoc()
2356  *
2357  */
2358 int usbvision_init_isoc(struct usb_usbvision *usbvision)
2359 {
2360         struct usb_device *dev = usbvision->dev;
2361         int bufIdx, errCode, regValue;
2362         const int sb_size = USBVISION_URB_FRAMES * USBVISION_MAX_ISOC_PACKET_SIZE;
2363
2364         if (!USBVISION_IS_OPERATIONAL(usbvision))
2365                 return -EFAULT;
2366
2367         usbvision->curFrame = NULL;
2368         scratch_reset(usbvision);
2369
2370         /* Alternate interface 1 is is the biggest frame size */
2371         errCode = usb_set_interface(dev, usbvision->iface, usbvision->ifaceAltActive);
2372         if (errCode < 0) {
2373                 usbvision->last_error = errCode;
2374                 return -EBUSY;
2375         }
2376
2377         regValue = (16 - usbvision_read_reg(usbvision, USBVISION_ALTER_REG)) & 0x0F;
2378         usbvision->isocPacketSize = (regValue == 0) ? 0 : (regValue * 64) - 1;
2379         PDEBUG(DBG_ISOC, "ISO Packet Length:%d", usbvision->isocPacketSize);
2380
2381         usbvision->usb_bandwidth = regValue >> 1;
2382         PDEBUG(DBG_ISOC, "USB Bandwidth Usage: %dMbit/Sec", usbvision->usb_bandwidth);
2383
2384
2385
2386         /* We double buffer the Iso lists */
2387
2388         for (bufIdx = 0; bufIdx < USBVISION_NUMSBUF; bufIdx++) {
2389                 int j, k;
2390                 struct urb *urb;
2391
2392                 urb = usb_alloc_urb(USBVISION_URB_FRAMES, GFP_KERNEL);
2393                 if (urb == NULL) {
2394                         err("%s: usb_alloc_urb() failed", __FUNCTION__);
2395                         return -ENOMEM;
2396                 }
2397                 usbvision->sbuf[bufIdx].urb = urb;
2398                 usbvision->sbuf[bufIdx].data = usb_buffer_alloc(usbvision->dev, sb_size, GFP_KERNEL,&urb->transfer_dma);
2399                 urb->dev = dev;
2400                 urb->context = usbvision;
2401                 urb->pipe = usb_rcvisocpipe(dev, usbvision->video_endp);
2402                 urb->transfer_flags = URB_ISO_ASAP;
2403                 urb->interval = 1;
2404                 urb->transfer_buffer = usbvision->sbuf[bufIdx].data;
2405                 urb->complete = usbvision_isocIrq;
2406                 urb->number_of_packets = USBVISION_URB_FRAMES;
2407                 urb->transfer_buffer_length =
2408                     usbvision->isocPacketSize * USBVISION_URB_FRAMES;
2409                 for (j = k = 0; j < USBVISION_URB_FRAMES; j++,
2410                      k += usbvision->isocPacketSize) {
2411                         urb->iso_frame_desc[j].offset = k;
2412                         urb->iso_frame_desc[j].length = usbvision->isocPacketSize;
2413                 }
2414         }
2415
2416
2417         /* Submit all URBs */
2418         for (bufIdx = 0; bufIdx < USBVISION_NUMSBUF; bufIdx++) {
2419                         errCode = usb_submit_urb(usbvision->sbuf[bufIdx].urb, GFP_KERNEL);
2420                 if (errCode) {
2421                         err("%s: usb_submit_urb(%d) failed: error %d", __FUNCTION__, bufIdx, errCode);
2422                 }
2423         }
2424
2425         usbvision->streaming = Stream_Idle;
2426         PDEBUG(DBG_ISOC, "%s: streaming=1 usbvision->video_endp=$%02x", __FUNCTION__, usbvision->video_endp);
2427         return 0;
2428 }
2429
2430 /*
2431  * usbvision_stop_isoc()
2432  *
2433  * This procedure stops streaming and deallocates URBs. Then it
2434  * activates zero-bandwidth alt. setting of the video interface.
2435  *
2436  */
2437 void usbvision_stop_isoc(struct usb_usbvision *usbvision)
2438 {
2439         int bufIdx, errCode, regValue;
2440         const int sb_size = USBVISION_URB_FRAMES * USBVISION_MAX_ISOC_PACKET_SIZE;
2441
2442         if ((usbvision->streaming == Stream_Off) || (usbvision->dev == NULL))
2443                 return;
2444
2445         /* Unschedule all of the iso td's */
2446         for (bufIdx = 0; bufIdx < USBVISION_NUMSBUF; bufIdx++) {
2447                 usb_kill_urb(usbvision->sbuf[bufIdx].urb);
2448                 if (usbvision->sbuf[bufIdx].data){
2449                         usb_buffer_free(usbvision->dev,
2450                                         sb_size,
2451                                         usbvision->sbuf[bufIdx].data,
2452                                         usbvision->sbuf[bufIdx].urb->transfer_dma);
2453                 }
2454                 usb_free_urb(usbvision->sbuf[bufIdx].urb);
2455                 usbvision->sbuf[bufIdx].urb = NULL;
2456         }
2457
2458
2459         PDEBUG(DBG_ISOC, "%s: streaming=Stream_Off\n", __FUNCTION__);
2460         usbvision->streaming = Stream_Off;
2461
2462         if (!usbvision->remove_pending) {
2463
2464                 /* Set packet size to 0 */
2465                 errCode = usb_set_interface(usbvision->dev, usbvision->iface,
2466                                       usbvision->ifaceAltInactive);
2467                 if (errCode < 0) {
2468                         err("%s: usb_set_interface() failed: error %d", __FUNCTION__, errCode);
2469                         usbvision->last_error = errCode;
2470                 }
2471                 regValue = (16 - usbvision_read_reg(usbvision, USBVISION_ALTER_REG)) & 0x0F;
2472                 usbvision->isocPacketSize = (regValue == 0) ? 0 : (regValue * 64) - 1;
2473                 PDEBUG(DBG_ISOC, "ISO Packet Length:%d", usbvision->isocPacketSize);
2474
2475                 usbvision->usb_bandwidth = regValue >> 1;
2476                 PDEBUG(DBG_ISOC, "USB Bandwidth Usage: %dMbit/Sec", usbvision->usb_bandwidth);
2477         }
2478 }
2479
2480 int usbvision_muxsel(struct usb_usbvision *usbvision, int channel)
2481 {
2482         int mode[4];
2483         int audio[]= {1, 0, 0, 0};
2484         struct v4l2_routing route;
2485         //channel 0 is TV with audiochannel 1 (tuner mono)
2486         //channel 1 is Composite with audio channel 0 (line in)
2487         //channel 2 is S-Video with audio channel 0 (line in)
2488         //channel 3 is additional video inputs to the device with audio channel 0 (line in)
2489
2490         RESTRICT_TO_RANGE(channel, 0, usbvision->video_inputs);
2491         usbvision->ctl_input = channel;
2492           route.input = SAA7115_COMPOSITE1;
2493           call_i2c_clients(usbvision, VIDIOC_INT_S_VIDEO_ROUTING,&route);
2494           call_i2c_clients(usbvision, VIDIOC_S_INPUT, &usbvision->ctl_input);
2495
2496         // set the new channel
2497         // Regular USB TV Tuners -> channel: 0 = Television, 1 = Composite, 2 = S-Video
2498         // Four video input devices -> channel: 0 = Chan White, 1 = Chan Green, 2 = Chan Yellow, 3 = Chan Red
2499
2500         switch (usbvision_device_data[usbvision->DevModel].Codec) {
2501                 case CODEC_SAA7113:
2502                         if (SwitchSVideoInput) { // To handle problems with S-Video Input for some devices.  Use SwitchSVideoInput parameter when loading the module.
2503                                 mode[2] = 1;
2504                         }
2505                         else {
2506                                 mode[2] = 7;
2507                         }
2508                         if (usbvision_device_data[usbvision->DevModel].VideoChannels == 4) {
2509                                 mode[0] = 0; mode[1] = 2; mode[3] = 3;  // Special for four input devices
2510                         }
2511                         else {
2512                                 mode[0] = 0; mode[1] = 2; //modes for regular saa7113 devices
2513                         }
2514                         break;
2515                 case CODEC_SAA7111:
2516                         mode[0] = 0; mode[1] = 1; mode[2] = 7; //modes for saa7111
2517                         break;
2518                 default:
2519                         mode[0] = 0; mode[1] = 1; mode[2] = 7; //default modes
2520         }
2521         route.input = mode[channel];
2522         call_i2c_clients(usbvision, VIDIOC_INT_S_VIDEO_ROUTING,&route);
2523         usbvision->channel = channel;
2524         usbvision_set_audio(usbvision, audio[channel]);
2525         return 0;
2526 }
2527
2528 /*
2529  * Overrides for Emacs so that we follow Linus's tabbing style.
2530  * ---------------------------------------------------------------------------
2531  * Local variables:
2532  * c-basic-offset: 8
2533  * End:
2534  */