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