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