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