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