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