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