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