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