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