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