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