1/* 2 * This program is free software; you can redistribute it and/or modify 3 * it under the terms of the GNU General Public License as published by 4 * the Free Software Foundation; either version 2, or (at your option) 5 * any later version. 6 * 7 * This program is distributed in the hope that it will be useful, 8 * but WITHOUT ANY WARRANTY; without even the implied warranty of 9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 * GNU General Public License for more details. 11 * 12 * You should have received a copy of the GNU General Public License 13 * along with this program; if not, write to the Free Software 14 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 15 */ 16 17#include <linux/kernel.h> 18#include <linux/sched.h> 19#include <linux/list.h> 20#include <linux/slab.h> 21#include <linux/module.h> 22#include <linux/mm.h> 23#include <linux/vmalloc.h> 24#include <linux/init.h> 25#include <linux/spinlock.h> 26 27#include <asm/io.h> 28 29#include "usbvideo.h" 30 31#if defined(MAP_NR) 32#define virt_to_page(v) MAP_NR(v) /* Kernels 2.2.x */ 33#endif 34 35static int video_nr = -1; 36module_param(video_nr, int, 0); 37 38/* 39 * Local prototypes. 40 */ 41static void usbvideo_Disconnect(struct usb_interface *intf); 42static void usbvideo_CameraRelease(struct uvd *uvd); 43 44static long usbvideo_v4l_ioctl(struct file *file, 45 unsigned int cmd, unsigned long arg); 46static int usbvideo_v4l_mmap(struct file *file, struct vm_area_struct *vma); 47static int usbvideo_v4l_open(struct file *file); 48static ssize_t usbvideo_v4l_read(struct file *file, char __user *buf, 49 size_t count, loff_t *ppos); 50static int usbvideo_v4l_close(struct file *file); 51 52static int usbvideo_StartDataPump(struct uvd *uvd); 53static void usbvideo_StopDataPump(struct uvd *uvd); 54static int usbvideo_GetFrame(struct uvd *uvd, int frameNum); 55static int usbvideo_NewFrame(struct uvd *uvd, int framenum); 56static void usbvideo_SoftwareContrastAdjustment(struct uvd *uvd, 57 struct usbvideo_frame *frame); 58 59/*******************************/ 60/* Memory management functions */ 61/*******************************/ 62static void *usbvideo_rvmalloc(unsigned long size) 63{ 64 void *mem; 65 unsigned long adr; 66 67 size = PAGE_ALIGN(size); 68 mem = vmalloc_32(size); 69 if (!mem) 70 return NULL; 71 72 memset(mem, 0, size); /* Clear the ram out, no junk to the user */ 73 adr = (unsigned long) mem; 74 while (size > 0) { 75 SetPageReserved(vmalloc_to_page((void *)adr)); 76 adr += PAGE_SIZE; 77 size -= PAGE_SIZE; 78 } 79 80 return mem; 81} 82 83static void usbvideo_rvfree(void *mem, unsigned long size) 84{ 85 unsigned long adr; 86 87 if (!mem) 88 return; 89 90 adr = (unsigned long) mem; 91 while ((long) size > 0) { 92 ClearPageReserved(vmalloc_to_page((void *)adr)); 93 adr += PAGE_SIZE; 94 size -= PAGE_SIZE; 95 } 96 vfree(mem); 97} 98 99static void RingQueue_Initialize(struct RingQueue *rq) 100{ 101 assert(rq != NULL); 102 init_waitqueue_head(&rq->wqh); 103} 104 105static void RingQueue_Allocate(struct RingQueue *rq, int rqLen) 106{ 107 /* Make sure the requested size is a power of 2 and 108 round up if necessary. This allows index wrapping 109 using masks rather than modulo */ 110 111 int i = 1; 112 assert(rq != NULL); 113 assert(rqLen > 0); 114 115 while(rqLen >> i) 116 i++; 117 if(rqLen != 1 << (i-1)) 118 rqLen = 1 << i; 119 120 rq->length = rqLen; 121 rq->ri = rq->wi = 0; 122 rq->queue = usbvideo_rvmalloc(rq->length); 123 assert(rq->queue != NULL); 124} 125 126static int RingQueue_IsAllocated(const struct RingQueue *rq) 127{ 128 if (rq == NULL) 129 return 0; 130 return (rq->queue != NULL) && (rq->length > 0); 131} 132 133static void RingQueue_Free(struct RingQueue *rq) 134{ 135 assert(rq != NULL); 136 if (RingQueue_IsAllocated(rq)) { 137 usbvideo_rvfree(rq->queue, rq->length); 138 rq->queue = NULL; 139 rq->length = 0; 140 } 141} 142 143int RingQueue_Dequeue(struct RingQueue *rq, unsigned char *dst, int len) 144{ 145 int rql, toread; 146 147 assert(rq != NULL); 148 assert(dst != NULL); 149 150 rql = RingQueue_GetLength(rq); 151 if(!rql) 152 return 0; 153 154 /* Clip requested length to available data */ 155 if(len > rql) 156 len = rql; 157 158 toread = len; 159 if(rq->ri > rq->wi) { 160 /* Read data from tail */ 161 int read = (toread < (rq->length - rq->ri)) ? toread : rq->length - rq->ri; 162 memcpy(dst, rq->queue + rq->ri, read); 163 toread -= read; 164 dst += read; 165 rq->ri = (rq->ri + read) & (rq->length-1); 166 } 167 if(toread) { 168 /* Read data from head */ 169 memcpy(dst, rq->queue + rq->ri, toread); 170 rq->ri = (rq->ri + toread) & (rq->length-1); 171 } 172 return len; 173} 174 175EXPORT_SYMBOL(RingQueue_Dequeue); 176 177int RingQueue_Enqueue(struct RingQueue *rq, const unsigned char *cdata, int n) 178{ 179 int enqueued = 0; 180 181 assert(rq != NULL); 182 assert(cdata != NULL); 183 assert(rq->length > 0); 184 while (n > 0) { 185 int m, q_avail; 186 187 /* Calculate the largest chunk that fits the tail of the ring */ 188 q_avail = rq->length - rq->wi; 189 if (q_avail <= 0) { 190 rq->wi = 0; 191 q_avail = rq->length; 192 } 193 m = n; 194 assert(q_avail > 0); 195 if (m > q_avail) 196 m = q_avail; 197 198 memcpy(rq->queue + rq->wi, cdata, m); 199 RING_QUEUE_ADVANCE_INDEX(rq, wi, m); 200 cdata += m; 201 enqueued += m; 202 n -= m; 203 } 204 return enqueued; 205} 206 207EXPORT_SYMBOL(RingQueue_Enqueue); 208 209static void RingQueue_InterruptibleSleepOn(struct RingQueue *rq) 210{ 211 assert(rq != NULL); 212 interruptible_sleep_on(&rq->wqh); 213} 214 215void RingQueue_WakeUpInterruptible(struct RingQueue *rq) 216{ 217 assert(rq != NULL); 218 if (waitqueue_active(&rq->wqh)) 219 wake_up_interruptible(&rq->wqh); 220} 221 222EXPORT_SYMBOL(RingQueue_WakeUpInterruptible); 223 224void RingQueue_Flush(struct RingQueue *rq) 225{ 226 assert(rq != NULL); 227 rq->ri = 0; 228 rq->wi = 0; 229} 230 231EXPORT_SYMBOL(RingQueue_Flush); 232 233 234/* 235 * usbvideo_VideosizeToString() 236 * 237 * This procedure converts given videosize value to readable string. 238 * 239 * History: 240 * 07-Aug-2000 Created. 241 * 19-Oct-2000 Reworked for usbvideo module. 242 */ 243static void usbvideo_VideosizeToString(char *buf, int bufLen, videosize_t vs) 244{ 245 char tmp[40]; 246 int n; 247 248 n = 1 + sprintf(tmp, "%ldx%ld", VIDEOSIZE_X(vs), VIDEOSIZE_Y(vs)); 249 assert(n < sizeof(tmp)); 250 if ((buf == NULL) || (bufLen < n)) 251 err("usbvideo_VideosizeToString: buffer is too small."); 252 else 253 memmove(buf, tmp, n); 254} 255 256/* 257 * usbvideo_OverlayChar() 258 * 259 * History: 260 * 01-Feb-2000 Created. 261 */ 262static void usbvideo_OverlayChar(struct uvd *uvd, struct usbvideo_frame *frame, 263 int x, int y, int ch) 264{ 265 static const unsigned short digits[16] = { 266 0xF6DE, /* 0 */ 267 0x2492, /* 1 */ 268 0xE7CE, /* 2 */ 269 0xE79E, /* 3 */ 270 0xB792, /* 4 */ 271 0xF39E, /* 5 */ 272 0xF3DE, /* 6 */ 273 0xF492, /* 7 */ 274 0xF7DE, /* 8 */ 275 0xF79E, /* 9 */ 276 0x77DA, /* a */ 277 0xD75C, /* b */ 278 0xF24E, /* c */ 279 0xD6DC, /* d */ 280 0xF34E, /* e */ 281 0xF348 /* f */ 282 }; 283 unsigned short digit; 284 int ix, iy; 285 int value; 286 287 if ((uvd == NULL) || (frame == NULL)) 288 return; 289 290 value = hex_to_bin(ch); 291 if (value < 0) 292 return; 293 digit = digits[value]; 294 295 for (iy=0; iy < 5; iy++) { 296 for (ix=0; ix < 3; ix++) { 297 if (digit & 0x8000) { 298 if (uvd->paletteBits & (1L << VIDEO_PALETTE_RGB24)) { 299/* TODO */ RGB24_PUTPIXEL(frame, x+ix, y+iy, 0xFF, 0xFF, 0xFF); 300 } 301 } 302 digit = digit << 1; 303 } 304 } 305} 306 307/* 308 * usbvideo_OverlayString() 309 * 310 * History: 311 * 01-Feb-2000 Created. 312 */ 313static void usbvideo_OverlayString(struct uvd *uvd, struct usbvideo_frame *frame, 314 int x, int y, const char *str) 315{ 316 while (*str) { 317 usbvideo_OverlayChar(uvd, frame, x, y, *str); 318 str++; 319 x += 4; /* 3 pixels character + 1 space */ 320 } 321} 322 323/* 324 * usbvideo_OverlayStats() 325 * 326 * Overlays important debugging information. 327 * 328 * History: 329 * 01-Feb-2000 Created. 330 */ 331static void usbvideo_OverlayStats(struct uvd *uvd, struct usbvideo_frame *frame) 332{ 333 const int y_diff = 8; 334 char tmp[16]; 335 int x = 10, y=10; 336 long i, j, barLength; 337 const int qi_x1 = 60, qi_y1 = 10; 338 const int qi_x2 = VIDEOSIZE_X(frame->request) - 10, qi_h = 10; 339 340 /* Call the user callback, see if we may proceed after that */ 341 if (VALID_CALLBACK(uvd, overlayHook)) { 342 if (GET_CALLBACK(uvd, overlayHook)(uvd, frame) < 0) 343 return; 344 } 345 346 /* 347 * We draw a (mostly) hollow rectangle with qi_xxx coordinates. 348 * Left edge symbolizes the queue index 0; right edge symbolizes 349 * the full capacity of the queue. 350 */ 351 barLength = qi_x2 - qi_x1 - 2; 352 if ((barLength > 10) && (uvd->paletteBits & (1L << VIDEO_PALETTE_RGB24))) { 353/* TODO */ long u_lo, u_hi, q_used; 354 long m_ri, m_wi, m_lo, m_hi; 355 356 /* 357 * Determine fill zones (used areas of the queue): 358 * 0 xxxxxxx u_lo ...... uvd->dp.ri xxxxxxxx u_hi ..... uvd->dp.length 359 * 360 * if u_lo < 0 then there is no first filler. 361 */ 362 363 q_used = RingQueue_GetLength(&uvd->dp); 364 if ((uvd->dp.ri + q_used) >= uvd->dp.length) { 365 u_hi = uvd->dp.length; 366 u_lo = (q_used + uvd->dp.ri) & (uvd->dp.length-1); 367 } else { 368 u_hi = (q_used + uvd->dp.ri); 369 u_lo = -1; 370 } 371 372 /* Convert byte indices into screen units */ 373 m_ri = qi_x1 + ((barLength * uvd->dp.ri) / uvd->dp.length); 374 m_wi = qi_x1 + ((barLength * uvd->dp.wi) / uvd->dp.length); 375 m_lo = (u_lo > 0) ? (qi_x1 + ((barLength * u_lo) / uvd->dp.length)) : -1; 376 m_hi = qi_x1 + ((barLength * u_hi) / uvd->dp.length); 377 378 for (j=qi_y1; j < (qi_y1 + qi_h); j++) { 379 for (i=qi_x1; i < qi_x2; i++) { 380 /* Draw border lines */ 381 if ((j == qi_y1) || (j == (qi_y1 + qi_h - 1)) || 382 (i == qi_x1) || (i == (qi_x2 - 1))) { 383 RGB24_PUTPIXEL(frame, i, j, 0xFF, 0xFF, 0xFF); 384 continue; 385 } 386 /* For all other points the Y coordinate does not matter */ 387 if ((i >= m_ri) && (i <= (m_ri + 3))) { 388 RGB24_PUTPIXEL(frame, i, j, 0x00, 0xFF, 0x00); 389 } else if ((i >= m_wi) && (i <= (m_wi + 3))) { 390 RGB24_PUTPIXEL(frame, i, j, 0xFF, 0x00, 0x00); 391 } else if ((i < m_lo) || ((i > m_ri) && (i < m_hi))) 392 RGB24_PUTPIXEL(frame, i, j, 0x00, 0x00, 0xFF); 393 } 394 } 395 } 396 397 sprintf(tmp, "%8lx", uvd->stats.frame_num); 398 usbvideo_OverlayString(uvd, frame, x, y, tmp); 399 y += y_diff; 400 401 sprintf(tmp, "%8lx", uvd->stats.urb_count); 402 usbvideo_OverlayString(uvd, frame, x, y, tmp); 403 y += y_diff; 404 405 sprintf(tmp, "%8lx", uvd->stats.urb_length); 406 usbvideo_OverlayString(uvd, frame, x, y, tmp); 407 y += y_diff; 408 409 sprintf(tmp, "%8lx", uvd->stats.data_count); 410 usbvideo_OverlayString(uvd, frame, x, y, tmp); 411 y += y_diff; 412 413 sprintf(tmp, "%8lx", uvd->stats.header_count); 414 usbvideo_OverlayString(uvd, frame, x, y, tmp); 415 y += y_diff; 416 417 sprintf(tmp, "%8lx", uvd->stats.iso_skip_count); 418 usbvideo_OverlayString(uvd, frame, x, y, tmp); 419 y += y_diff; 420 421 sprintf(tmp, "%8lx", uvd->stats.iso_err_count); 422 usbvideo_OverlayString(uvd, frame, x, y, tmp); 423 y += y_diff; 424 425 sprintf(tmp, "%8x", uvd->vpic.colour); 426 usbvideo_OverlayString(uvd, frame, x, y, tmp); 427 y += y_diff; 428 429 sprintf(tmp, "%8x", uvd->vpic.hue); 430 usbvideo_OverlayString(uvd, frame, x, y, tmp); 431 y += y_diff; 432 433 sprintf(tmp, "%8x", uvd->vpic.brightness >> 8); 434 usbvideo_OverlayString(uvd, frame, x, y, tmp); 435 y += y_diff; 436 437 sprintf(tmp, "%8x", uvd->vpic.contrast >> 12); 438 usbvideo_OverlayString(uvd, frame, x, y, tmp); 439 y += y_diff; 440 441 sprintf(tmp, "%8d", uvd->vpic.whiteness >> 8); 442 usbvideo_OverlayString(uvd, frame, x, y, tmp); 443 y += y_diff; 444} 445 446/* 447 * usbvideo_ReportStatistics() 448 * 449 * This procedure prints packet and transfer statistics. 450 * 451 * History: 452 * 14-Jan-2000 Corrected default multiplier. 453 */ 454static void usbvideo_ReportStatistics(const struct uvd *uvd) 455{ 456 if ((uvd != NULL) && (uvd->stats.urb_count > 0)) { 457 unsigned long allPackets, badPackets, goodPackets, percent; 458 allPackets = uvd->stats.urb_count * CAMERA_URB_FRAMES; 459 badPackets = uvd->stats.iso_skip_count + uvd->stats.iso_err_count; 460 goodPackets = allPackets - badPackets; 461 /* Calculate percentage wisely, remember integer limits */ 462 assert(allPackets != 0); 463 if (goodPackets < (((unsigned long)-1)/100)) 464 percent = (100 * goodPackets) / allPackets; 465 else 466 percent = goodPackets / (allPackets / 100); 467 dev_info(&uvd->dev->dev, 468 "Packet Statistics: Total=%lu. Empty=%lu. Usage=%lu%%\n", 469 allPackets, badPackets, percent); 470 if (uvd->iso_packet_len > 0) { 471 unsigned long allBytes, xferBytes; 472 char multiplier = ' '; 473 allBytes = allPackets * uvd->iso_packet_len; 474 xferBytes = uvd->stats.data_count; 475 assert(allBytes != 0); 476 if (xferBytes < (((unsigned long)-1)/100)) 477 percent = (100 * xferBytes) / allBytes; 478 else 479 percent = xferBytes / (allBytes / 100); 480 /* Scale xferBytes for easy reading */ 481 if (xferBytes > 10*1024) { 482 xferBytes /= 1024; 483 multiplier = 'K'; 484 if (xferBytes > 10*1024) { 485 xferBytes /= 1024; 486 multiplier = 'M'; 487 if (xferBytes > 10*1024) { 488 xferBytes /= 1024; 489 multiplier = 'G'; 490 if (xferBytes > 10*1024) { 491 xferBytes /= 1024; 492 multiplier = 'T'; 493 } 494 } 495 } 496 } 497 dev_info(&uvd->dev->dev, 498 "Transfer Statistics: Transferred=%lu%cB Usage=%lu%%\n", 499 xferBytes, multiplier, percent); 500 } 501 } 502} 503 504/* 505 * usbvideo_TestPattern() 506 * 507 * Procedure forms a test pattern (yellow grid on blue background). 508 * 509 * Parameters: 510 * fullframe: if TRUE then entire frame is filled, otherwise the procedure 511 * continues from the current scanline. 512 * pmode 0: fill the frame with solid blue color (like on VCR or TV) 513 * 1: Draw a colored grid 514 * 515 * History: 516 * 01-Feb-2000 Created. 517 */ 518void usbvideo_TestPattern(struct uvd *uvd, int fullframe, int pmode) 519{ 520 struct usbvideo_frame *frame; 521 int num_cell = 0; 522 int scan_length = 0; 523 static int num_pass; 524 525 if (uvd == NULL) { 526 err("%s: uvd == NULL", __func__); 527 return; 528 } 529 if ((uvd->curframe < 0) || (uvd->curframe >= USBVIDEO_NUMFRAMES)) { 530 err("%s: uvd->curframe=%d.", __func__, uvd->curframe); 531 return; 532 } 533 534 /* Grab the current frame */ 535 frame = &uvd->frame[uvd->curframe]; 536 537 /* Optionally start at the beginning */ 538 if (fullframe) { 539 frame->curline = 0; 540 frame->seqRead_Length = 0; 541 } 542 /* Form every scan line */ 543 for (; frame->curline < VIDEOSIZE_Y(frame->request); frame->curline++) { 544 int i; 545 unsigned char *f = frame->data + 546 (VIDEOSIZE_X(frame->request) * V4L_BYTES_PER_PIXEL * frame->curline); 547 for (i=0; i < VIDEOSIZE_X(frame->request); i++) { 548 unsigned char cb=0x80; 549 unsigned char cg = 0; 550 unsigned char cr = 0; 551 552 if (pmode == 1) { 553 if (frame->curline % 32 == 0) 554 cb = 0, cg = cr = 0xFF; 555 else if (i % 32 == 0) { 556 if (frame->curline % 32 == 1) 557 num_cell++; 558 cb = 0, cg = cr = 0xFF; 559 } else { 560 cb = ((num_cell*7) + num_pass) & 0xFF; 561 cg = ((num_cell*5) + num_pass*2) & 0xFF; 562 cr = ((num_cell*3) + num_pass*3) & 0xFF; 563 } 564 } else { 565 /* Just the blue screen */ 566 } 567 568 *f++ = cb; 569 *f++ = cg; 570 *f++ = cr; 571 scan_length += 3; 572 } 573 } 574 575 frame->frameState = FrameState_Done; 576 frame->seqRead_Length += scan_length; 577 ++num_pass; 578 579 /* We do this unconditionally, regardless of FLAGS_OVERLAY_STATS */ 580 usbvideo_OverlayStats(uvd, frame); 581} 582 583EXPORT_SYMBOL(usbvideo_TestPattern); 584 585 586#ifdef DEBUG 587/* 588 * usbvideo_HexDump() 589 * 590 * A debugging tool. Prints hex dumps. 591 * 592 * History: 593 * 29-Jul-2000 Added printing of offsets. 594 */ 595void usbvideo_HexDump(const unsigned char *data, int len) 596{ 597 const int bytes_per_line = 32; 598 char tmp[128]; /* 32*3 + 5 */ 599 int i, k; 600 601 for (i=k=0; len > 0; i++, len--) { 602 if (i > 0 && ((i % bytes_per_line) == 0)) { 603 printk("%s\n", tmp); 604 k=0; 605 } 606 if ((i % bytes_per_line) == 0) 607 k += sprintf(&tmp[k], "%04x: ", i); 608 k += sprintf(&tmp[k], "%02x ", data[i]); 609 } 610 if (k > 0) 611 printk("%s\n", tmp); 612} 613 614EXPORT_SYMBOL(usbvideo_HexDump); 615 616#endif 617 618/* ******************************************************************** */ 619 620static int usbvideo_ClientIncModCount(struct uvd *uvd) 621{ 622 if (uvd == NULL) { 623 err("%s: uvd == NULL", __func__); 624 return -EINVAL; 625 } 626 if (uvd->handle == NULL) { 627 err("%s: uvd->handle == NULL", __func__); 628 return -EINVAL; 629 } 630 if (!try_module_get(uvd->handle->md_module)) { 631 err("%s: try_module_get() == 0", __func__); 632 return -ENODEV; 633 } 634 return 0; 635} 636 637static void usbvideo_ClientDecModCount(struct uvd *uvd) 638{ 639 if (uvd == NULL) { 640 err("%s: uvd == NULL", __func__); 641 return; 642 } 643 if (uvd->handle == NULL) { 644 err("%s: uvd->handle == NULL", __func__); 645 return; 646 } 647 if (uvd->handle->md_module == NULL) { 648 err("%s: uvd->handle->md_module == NULL", __func__); 649 return; 650 } 651 module_put(uvd->handle->md_module); 652} 653 654int usbvideo_register( 655 struct usbvideo **pCams, 656 const int num_cams, 657 const int num_extra, 658 const char *driverName, 659 const struct usbvideo_cb *cbTbl, 660 struct module *md, 661 const struct usb_device_id *id_table) 662{ 663 struct usbvideo *cams; 664 int i, base_size, result; 665 666 /* Check parameters for sanity */ 667 if ((num_cams <= 0) || (pCams == NULL) || (cbTbl == NULL)) { 668 err("%s: Illegal call", __func__); 669 return -EINVAL; 670 } 671 672 /* Check registration callback - must be set! */ 673 if (cbTbl->probe == NULL) { 674 err("%s: probe() is required!", __func__); 675 return -EINVAL; 676 } 677 678 base_size = num_cams * sizeof(struct uvd) + sizeof(struct usbvideo); 679 cams = kzalloc(base_size, GFP_KERNEL); 680 if (cams == NULL) { 681 err("Failed to allocate %d. bytes for usbvideo struct", base_size); 682 return -ENOMEM; 683 } 684 dbg("%s: Allocated $%p (%d. bytes) for %d. cameras", 685 __func__, cams, base_size, num_cams); 686 687 /* Copy callbacks, apply defaults for those that are not set */ 688 memmove(&cams->cb, cbTbl, sizeof(cams->cb)); 689 if (cams->cb.getFrame == NULL) 690 cams->cb.getFrame = usbvideo_GetFrame; 691 if (cams->cb.disconnect == NULL) 692 cams->cb.disconnect = usbvideo_Disconnect; 693 if (cams->cb.startDataPump == NULL) 694 cams->cb.startDataPump = usbvideo_StartDataPump; 695 if (cams->cb.stopDataPump == NULL) 696 cams->cb.stopDataPump = usbvideo_StopDataPump; 697 698 cams->num_cameras = num_cams; 699 cams->cam = (struct uvd *) &cams[1]; 700 cams->md_module = md; 701 mutex_init(&cams->lock); /* to 1 == available */ 702 703 for (i = 0; i < num_cams; i++) { 704 struct uvd *up = &cams->cam[i]; 705 706 up->handle = cams; 707 708 /* Allocate user_data separately because of kmalloc's limits */ 709 if (num_extra > 0) { 710 up->user_size = num_cams * num_extra; 711 up->user_data = kmalloc(up->user_size, GFP_KERNEL); 712 if (up->user_data == NULL) { 713 err("%s: Failed to allocate user_data (%d. bytes)", 714 __func__, up->user_size); 715 while (i) { 716 up = &cams->cam[--i]; 717 kfree(up->user_data); 718 } 719 kfree(cams); 720 return -ENOMEM; 721 } 722 dbg("%s: Allocated cams[%d].user_data=$%p (%d. bytes)", 723 __func__, i, up->user_data, up->user_size); 724 } 725 } 726 727 /* 728 * Register ourselves with USB stack. 729 */ 730 strcpy(cams->drvName, (driverName != NULL) ? driverName : "Unknown"); 731 cams->usbdrv.name = cams->drvName; 732 cams->usbdrv.probe = cams->cb.probe; 733 cams->usbdrv.disconnect = cams->cb.disconnect; 734 cams->usbdrv.id_table = id_table; 735 736 /* 737 * Update global handle to usbvideo. This is very important 738 * because probe() can be called before usb_register() returns. 739 * If the handle is not yet updated then the probe() will fail. 740 */ 741 *pCams = cams; 742 result = usb_register(&cams->usbdrv); 743 if (result) { 744 for (i = 0; i < num_cams; i++) { 745 struct uvd *up = &cams->cam[i]; 746 kfree(up->user_data); 747 } 748 kfree(cams); 749 } 750 751 return result; 752} 753 754EXPORT_SYMBOL(usbvideo_register); 755 756/* 757 * usbvideo_Deregister() 758 * 759 * Procedure frees all usbvideo and user data structures. Be warned that 760 * if you had some dynamically allocated components in ->user field then 761 * you should free them before calling here. 762 */ 763void usbvideo_Deregister(struct usbvideo **pCams) 764{ 765 struct usbvideo *cams; 766 int i; 767 768 if (pCams == NULL) { 769 err("%s: pCams == NULL", __func__); 770 return; 771 } 772 cams = *pCams; 773 if (cams == NULL) { 774 err("%s: cams == NULL", __func__); 775 return; 776 } 777 778 dbg("%s: Deregistering %s driver.", __func__, cams->drvName); 779 usb_deregister(&cams->usbdrv); 780 781 dbg("%s: Deallocating cams=$%p (%d. cameras)", __func__, cams, cams->num_cameras); 782 for (i=0; i < cams->num_cameras; i++) { 783 struct uvd *up = &cams->cam[i]; 784 int warning = 0; 785 786 if (up->user_data != NULL) { 787 if (up->user_size <= 0) 788 ++warning; 789 } else { 790 if (up->user_size > 0) 791 ++warning; 792 } 793 if (warning) { 794 err("%s: Warning: user_data=$%p user_size=%d.", 795 __func__, up->user_data, up->user_size); 796 } else { 797 dbg("%s: Freeing %d. $%p->user_data=$%p", 798 __func__, i, up, up->user_data); 799 kfree(up->user_data); 800 } 801 } 802 /* Whole array was allocated in one chunk */ 803 dbg("%s: Freed %d uvd structures", 804 __func__, cams->num_cameras); 805 kfree(cams); 806 *pCams = NULL; 807} 808 809EXPORT_SYMBOL(usbvideo_Deregister); 810 811/* 812 * usbvideo_Disconnect() 813 * 814 * This procedure stops all driver activity. Deallocation of 815 * the interface-private structure (pointed by 'ptr') is done now 816 * (if we don't have any open files) or later, when those files 817 * are closed. After that driver should be removable. 818 * 819 * This code handles surprise removal. The uvd->user is a counter which 820 * increments on open() and decrements on close(). If we see here that 821 * this counter is not 0 then we have a client who still has us opened. 822 * We set uvd->remove_pending flag as early as possible, and after that 823 * all access to the camera will gracefully fail. These failures should 824 * prompt client to (eventually) close the video device, and then - in 825 * usbvideo_v4l_close() - we decrement uvd->uvd_used and usage counter. 826 * 827 * History: 828 * 22-Jan-2000 Added polling of MOD_IN_USE to delay removal until all users gone. 829 * 27-Jan-2000 Reworked to allow pending disconnects; see xxx_close() 830 * 24-May-2000 Corrected to prevent race condition (MOD_xxx_USE_COUNT). 831 * 19-Oct-2000 Moved to usbvideo module. 832 */ 833static void usbvideo_Disconnect(struct usb_interface *intf) 834{ 835 struct uvd *uvd = usb_get_intfdata (intf); 836 int i; 837 838 if (uvd == NULL) { 839 err("%s($%p): Illegal call.", __func__, intf); 840 return; 841 } 842 843 usb_set_intfdata (intf, NULL); 844 845 usbvideo_ClientIncModCount(uvd); 846 if (uvd->debug > 0) 847 dev_info(&intf->dev, "%s(%p.)\n", __func__, intf); 848 849 mutex_lock(&uvd->lock); 850 uvd->remove_pending = 1; /* Now all ISO data will be ignored */ 851 852 /* At this time we ask to cancel outstanding URBs */ 853 GET_CALLBACK(uvd, stopDataPump)(uvd); 854 855 for (i=0; i < USBVIDEO_NUMSBUF; i++) 856 usb_free_urb(uvd->sbuf[i].urb); 857 858 usb_put_dev(uvd->dev); 859 uvd->dev = NULL; /* USB device is no more */ 860 861 video_unregister_device(&uvd->vdev); 862 if (uvd->debug > 0) 863 dev_info(&intf->dev, "%s: Video unregistered.\n", __func__); 864 865 if (uvd->user) 866 dev_info(&intf->dev, "%s: In use, disconnect pending.\n", 867 __func__); 868 else 869 usbvideo_CameraRelease(uvd); 870 mutex_unlock(&uvd->lock); 871 dev_info(&intf->dev, "USB camera disconnected.\n"); 872 873 usbvideo_ClientDecModCount(uvd); 874} 875 876/* 877 * usbvideo_CameraRelease() 878 * 879 * This code does final release of uvd. This happens 880 * after the device is disconnected -and- all clients 881 * closed their files. 882 * 883 * History: 884 * 27-Jan-2000 Created. 885 */ 886static void usbvideo_CameraRelease(struct uvd *uvd) 887{ 888 if (uvd == NULL) { 889 err("%s: Illegal call", __func__); 890 return; 891 } 892 893 RingQueue_Free(&uvd->dp); 894 if (VALID_CALLBACK(uvd, userFree)) 895 GET_CALLBACK(uvd, userFree)(uvd); 896 uvd->uvd_used = 0; /* This is atomic, no need to take mutex */ 897} 898 899/* 900 * usbvideo_find_struct() 901 * 902 * This code searches the array of preallocated (static) structures 903 * and returns index of the first one that isn't in use. Returns -1 904 * if there are no free structures. 905 * 906 * History: 907 * 27-Jan-2000 Created. 908 */ 909static int usbvideo_find_struct(struct usbvideo *cams) 910{ 911 int u, rv = -1; 912 913 if (cams == NULL) { 914 err("No usbvideo handle?"); 915 return -1; 916 } 917 mutex_lock(&cams->lock); 918 for (u = 0; u < cams->num_cameras; u++) { 919 struct uvd *uvd = &cams->cam[u]; 920 if (!uvd->uvd_used) /* This one is free */ 921 { 922 uvd->uvd_used = 1; /* In use now */ 923 mutex_init(&uvd->lock); /* to 1 == available */ 924 uvd->dev = NULL; 925 rv = u; 926 break; 927 } 928 } 929 mutex_unlock(&cams->lock); 930 return rv; 931} 932 933static const struct v4l2_file_operations usbvideo_fops = { 934 .owner = THIS_MODULE, 935 .open = usbvideo_v4l_open, 936 .release =usbvideo_v4l_close, 937 .read = usbvideo_v4l_read, 938 .mmap = usbvideo_v4l_mmap, 939 .ioctl = usbvideo_v4l_ioctl, 940}; 941static const struct video_device usbvideo_template = { 942 .fops = &usbvideo_fops, 943}; 944 945struct uvd *usbvideo_AllocateDevice(struct usbvideo *cams) 946{ 947 int i, devnum; 948 struct uvd *uvd = NULL; 949 950 if (cams == NULL) { 951 err("No usbvideo handle?"); 952 return NULL; 953 } 954 955 devnum = usbvideo_find_struct(cams); 956 if (devnum == -1) { 957 err("IBM USB camera driver: Too many devices!"); 958 return NULL; 959 } 960 uvd = &cams->cam[devnum]; 961 dbg("Device entry #%d. at $%p", devnum, uvd); 962 963 /* Not relying upon caller we increase module counter ourselves */ 964 usbvideo_ClientIncModCount(uvd); 965 966 mutex_lock(&uvd->lock); 967 for (i=0; i < USBVIDEO_NUMSBUF; i++) { 968 uvd->sbuf[i].urb = usb_alloc_urb(FRAMES_PER_DESC, GFP_KERNEL); 969 if (uvd->sbuf[i].urb == NULL) { 970 err("usb_alloc_urb(%d.) failed.", FRAMES_PER_DESC); 971 uvd->uvd_used = 0; 972 uvd = NULL; 973 goto allocate_done; 974 } 975 } 976 uvd->user=0; 977 uvd->remove_pending = 0; 978 uvd->last_error = 0; 979 RingQueue_Initialize(&uvd->dp); 980 981 /* Initialize video device structure */ 982 uvd->vdev = usbvideo_template; 983 sprintf(uvd->vdev.name, "%.20s USB Camera", cams->drvName); 984 /* 985 * The client is free to overwrite those because we 986 * return control to the client's probe function right now. 987 */ 988allocate_done: 989 mutex_unlock(&uvd->lock); 990 usbvideo_ClientDecModCount(uvd); 991 return uvd; 992} 993 994EXPORT_SYMBOL(usbvideo_AllocateDevice); 995 996int usbvideo_RegisterVideoDevice(struct uvd *uvd) 997{ 998 char tmp1[20], tmp2[20]; /* Buffers for printing */ 999 1000 if (uvd == NULL) { 1001 err("%s: Illegal call.", __func__); 1002 return -EINVAL; 1003 } 1004 if (uvd->video_endp == 0) { 1005 dev_info(&uvd->dev->dev, 1006 "%s: No video endpoint specified; data pump disabled.\n", 1007 __func__); 1008 } 1009 if (uvd->paletteBits == 0) { 1010 err("%s: No palettes specified!", __func__); 1011 return -EINVAL; 1012 } 1013 if (uvd->defaultPalette == 0) { 1014 dev_info(&uvd->dev->dev, "%s: No default palette!\n", 1015 __func__); 1016 } 1017 1018 uvd->max_frame_size = VIDEOSIZE_X(uvd->canvas) * 1019 VIDEOSIZE_Y(uvd->canvas) * V4L_BYTES_PER_PIXEL; 1020 usbvideo_VideosizeToString(tmp1, sizeof(tmp1), uvd->videosize); 1021 usbvideo_VideosizeToString(tmp2, sizeof(tmp2), uvd->canvas); 1022 1023 if (uvd->debug > 0) { 1024 dev_info(&uvd->dev->dev, 1025 "%s: iface=%d. endpoint=$%02x paletteBits=$%08lx\n", 1026 __func__, uvd->iface, uvd->video_endp, 1027 uvd->paletteBits); 1028 } 1029 if (uvd->dev == NULL) { 1030 err("%s: uvd->dev == NULL", __func__); 1031 return -EINVAL; 1032 } 1033 uvd->vdev.parent = &uvd->dev->dev; 1034 uvd->vdev.release = video_device_release_empty; 1035 if (video_register_device(&uvd->vdev, VFL_TYPE_GRABBER, video_nr) < 0) { 1036 err("%s: video_register_device failed", __func__); 1037 return -EPIPE; 1038 } 1039 if (uvd->debug > 1) { 1040 dev_info(&uvd->dev->dev, 1041 "%s: video_register_device() successful\n", __func__); 1042 } 1043 1044 dev_info(&uvd->dev->dev, "%s on %s: canvas=%s videosize=%s\n", 1045 (uvd->handle != NULL) ? uvd->handle->drvName : "???", 1046 video_device_node_name(&uvd->vdev), tmp2, tmp1); 1047 1048 usb_get_dev(uvd->dev); 1049 return 0; 1050} 1051 1052EXPORT_SYMBOL(usbvideo_RegisterVideoDevice); 1053 1054/* ******************************************************************** */ 1055 1056static int usbvideo_v4l_mmap(struct file *file, struct vm_area_struct *vma) 1057{ 1058 struct uvd *uvd = file->private_data; 1059 unsigned long start = vma->vm_start; 1060 unsigned long size = vma->vm_end-vma->vm_start; 1061 unsigned long page, pos; 1062 1063 if (!CAMERA_IS_OPERATIONAL(uvd)) 1064 return -EFAULT; 1065 1066 if (size > (((USBVIDEO_NUMFRAMES * uvd->max_frame_size) + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1))) 1067 return -EINVAL; 1068 1069 pos = (unsigned long) uvd->fbuf; 1070 while (size > 0) { 1071 page = vmalloc_to_pfn((void *)pos); 1072 if (remap_pfn_range(vma, start, page, PAGE_SIZE, PAGE_SHARED)) 1073 return -EAGAIN; 1074 1075 start += PAGE_SIZE; 1076 pos += PAGE_SIZE; 1077 if (size > PAGE_SIZE) 1078 size -= PAGE_SIZE; 1079 else 1080 size = 0; 1081 } 1082 1083 return 0; 1084} 1085 1086/* 1087 * usbvideo_v4l_open() 1088 * 1089 * This is part of Video 4 Linux API. The driver can be opened by one 1090 * client only (checks internal counter 'uvdser'). The procedure 1091 * then allocates buffers needed for video processing. 1092 * 1093 * History: 1094 * 22-Jan-2000 Rewrote, moved scratch buffer allocation here. Now the 1095 * camera is also initialized here (once per connect), at 1096 * expense of V4L client (it waits on open() call). 1097 * 27-Jan-2000 Used USBVIDEO_NUMSBUF as number of URB buffers. 1098 * 24-May-2000 Corrected to prevent race condition (MOD_xxx_USE_COUNT). 1099 */ 1100static int usbvideo_v4l_open(struct file *file) 1101{ 1102 struct video_device *dev = video_devdata(file); 1103 struct uvd *uvd = (struct uvd *) dev; 1104 const int sb_size = FRAMES_PER_DESC * uvd->iso_packet_len; 1105 int i, errCode = 0; 1106 1107 if (uvd->debug > 1) 1108 dev_info(&uvd->dev->dev, "%s($%p)\n", __func__, dev); 1109 1110 if (usbvideo_ClientIncModCount(uvd) < 0) 1111 return -ENODEV; 1112 mutex_lock(&uvd->lock); 1113 1114 if (uvd->user) { 1115 err("%s: Someone tried to open an already opened device!", __func__); 1116 errCode = -EBUSY; 1117 } else { 1118 /* Clear statistics */ 1119 memset(&uvd->stats, 0, sizeof(uvd->stats)); 1120 1121 /* Clean pointers so we know if we allocated something */ 1122 for (i=0; i < USBVIDEO_NUMSBUF; i++) 1123 uvd->sbuf[i].data = NULL; 1124 1125 /* Allocate memory for the frame buffers */ 1126 uvd->fbuf_size = USBVIDEO_NUMFRAMES * uvd->max_frame_size; 1127 uvd->fbuf = usbvideo_rvmalloc(uvd->fbuf_size); 1128 RingQueue_Allocate(&uvd->dp, RING_QUEUE_SIZE); 1129 if ((uvd->fbuf == NULL) || 1130 (!RingQueue_IsAllocated(&uvd->dp))) { 1131 err("%s: Failed to allocate fbuf or dp", __func__); 1132 errCode = -ENOMEM; 1133 } else { 1134 /* Allocate all buffers */ 1135 for (i=0; i < USBVIDEO_NUMFRAMES; i++) { 1136 uvd->frame[i].frameState = FrameState_Unused; 1137 uvd->frame[i].data = uvd->fbuf + i*(uvd->max_frame_size); 1138 /* 1139 * Set default sizes in case IOCTL (VIDIOCMCAPTURE) 1140 * is not used (using read() instead). 1141 */ 1142 uvd->frame[i].canvas = uvd->canvas; 1143 uvd->frame[i].seqRead_Index = 0; 1144 } 1145 for (i=0; i < USBVIDEO_NUMSBUF; i++) { 1146 uvd->sbuf[i].data = kmalloc(sb_size, GFP_KERNEL); 1147 if (uvd->sbuf[i].data == NULL) { 1148 errCode = -ENOMEM; 1149 break; 1150 } 1151 } 1152 } 1153 if (errCode != 0) { 1154 /* Have to free all that memory */ 1155 if (uvd->fbuf != NULL) { 1156 usbvideo_rvfree(uvd->fbuf, uvd->fbuf_size); 1157 uvd->fbuf = NULL; 1158 } 1159 RingQueue_Free(&uvd->dp); 1160 for (i=0; i < USBVIDEO_NUMSBUF; i++) { 1161 kfree(uvd->sbuf[i].data); 1162 uvd->sbuf[i].data = NULL; 1163 } 1164 } 1165 } 1166 1167 /* If so far no errors then we shall start the camera */ 1168 if (errCode == 0) { 1169 /* Start data pump if we have valid endpoint */ 1170 if (uvd->video_endp != 0) 1171 errCode = GET_CALLBACK(uvd, startDataPump)(uvd); 1172 if (errCode == 0) { 1173 if (VALID_CALLBACK(uvd, setupOnOpen)) { 1174 if (uvd->debug > 1) 1175 dev_info(&uvd->dev->dev, 1176 "%s: setupOnOpen callback\n", 1177 __func__); 1178 errCode = GET_CALLBACK(uvd, setupOnOpen)(uvd); 1179 if (errCode < 0) { 1180 err("%s: setupOnOpen callback failed (%d.).", 1181 __func__, errCode); 1182 } else if (uvd->debug > 1) { 1183 dev_info(&uvd->dev->dev, 1184 "%s: setupOnOpen callback successful\n", 1185 __func__); 1186 } 1187 } 1188 if (errCode == 0) { 1189 uvd->settingsAdjusted = 0; 1190 if (uvd->debug > 1) 1191 dev_info(&uvd->dev->dev, 1192 "%s: Open succeeded.\n", 1193 __func__); 1194 uvd->user++; 1195 file->private_data = uvd; 1196 } 1197 } 1198 } 1199 mutex_unlock(&uvd->lock); 1200 if (errCode != 0) 1201 usbvideo_ClientDecModCount(uvd); 1202 if (uvd->debug > 0) 1203 dev_info(&uvd->dev->dev, "%s: Returning %d.\n", __func__, 1204 errCode); 1205 return errCode; 1206} 1207 1208/* 1209 * usbvideo_v4l_close() 1210 * 1211 * This is part of Video 4 Linux API. The procedure 1212 * stops streaming and deallocates all buffers that were earlier 1213 * allocated in usbvideo_v4l_open(). 1214 * 1215 * History: 1216 * 22-Jan-2000 Moved scratch buffer deallocation here. 1217 * 27-Jan-2000 Used USBVIDEO_NUMSBUF as number of URB buffers. 1218 * 24-May-2000 Moved MOD_DEC_USE_COUNT outside of code that can sleep. 1219 */ 1220static int usbvideo_v4l_close(struct file *file) 1221{ 1222 struct video_device *dev = file->private_data; 1223 struct uvd *uvd = (struct uvd *) dev; 1224 int i; 1225 1226 if (uvd->debug > 1) 1227 dev_info(&uvd->dev->dev, "%s($%p)\n", __func__, dev); 1228 1229 mutex_lock(&uvd->lock); 1230 GET_CALLBACK(uvd, stopDataPump)(uvd); 1231 usbvideo_rvfree(uvd->fbuf, uvd->fbuf_size); 1232 uvd->fbuf = NULL; 1233 RingQueue_Free(&uvd->dp); 1234 1235 for (i=0; i < USBVIDEO_NUMSBUF; i++) { 1236 kfree(uvd->sbuf[i].data); 1237 uvd->sbuf[i].data = NULL; 1238 } 1239 1240#if USBVIDEO_REPORT_STATS 1241 usbvideo_ReportStatistics(uvd); 1242#endif 1243 1244 uvd->user--; 1245 if (uvd->remove_pending) { 1246 if (uvd->debug > 0) 1247 dev_info(&uvd->dev->dev, "%s: Final disconnect.\n", 1248 __func__); 1249 usbvideo_CameraRelease(uvd); 1250 } 1251 mutex_unlock(&uvd->lock); 1252 usbvideo_ClientDecModCount(uvd); 1253 1254 if (uvd->debug > 1) 1255 dev_info(&uvd->dev->dev, "%s: Completed.\n", __func__); 1256 file->private_data = NULL; 1257 return 0; 1258} 1259 1260/* 1261 * usbvideo_v4l_ioctl() 1262 * 1263 * This is part of Video 4 Linux API. The procedure handles ioctl() calls. 1264 * 1265 * History: 1266 * 22-Jan-2000 Corrected VIDIOCSPICT to reject unsupported settings. 1267 */ 1268static long usbvideo_v4l_do_ioctl(struct file *file, unsigned int cmd, void *arg) 1269{ 1270 struct uvd *uvd = file->private_data; 1271 1272 if (!CAMERA_IS_OPERATIONAL(uvd)) 1273 return -EIO; 1274 1275 switch (cmd) { 1276 case VIDIOCGCAP: 1277 { 1278 struct video_capability *b = arg; 1279 *b = uvd->vcap; 1280 return 0; 1281 } 1282 case VIDIOCGCHAN: 1283 { 1284 struct video_channel *v = arg; 1285 *v = uvd->vchan; 1286 return 0; 1287 } 1288 case VIDIOCSCHAN: 1289 { 1290 struct video_channel *v = arg; 1291 if (v->channel != 0) 1292 return -EINVAL; 1293 return 0; 1294 } 1295 case VIDIOCGPICT: 1296 { 1297 struct video_picture *pic = arg; 1298 *pic = uvd->vpic; 1299 return 0; 1300 } 1301 case VIDIOCSPICT: 1302 { 1303 struct video_picture *pic = arg; 1304 /* 1305 * Use temporary 'video_picture' structure to preserve our 1306 * own settings (such as color depth, palette) that we 1307 * aren't allowing everyone (V4L client) to change. 1308 */ 1309 uvd->vpic.brightness = pic->brightness; 1310 uvd->vpic.hue = pic->hue; 1311 uvd->vpic.colour = pic->colour; 1312 uvd->vpic.contrast = pic->contrast; 1313 uvd->settingsAdjusted = 0; /* Will force new settings */ 1314 return 0; 1315 } 1316 case VIDIOCSWIN: 1317 { 1318 struct video_window *vw = arg; 1319 1320 if(VALID_CALLBACK(uvd, setVideoMode)) { 1321 return GET_CALLBACK(uvd, setVideoMode)(uvd, vw); 1322 } 1323 1324 if (vw->flags) 1325 return -EINVAL; 1326 if (vw->clipcount) 1327 return -EINVAL; 1328 if (vw->width != VIDEOSIZE_X(uvd->canvas)) 1329 return -EINVAL; 1330 if (vw->height != VIDEOSIZE_Y(uvd->canvas)) 1331 return -EINVAL; 1332 1333 return 0; 1334 } 1335 case VIDIOCGWIN: 1336 { 1337 struct video_window *vw = arg; 1338 1339 vw->x = 0; 1340 vw->y = 0; 1341 vw->width = VIDEOSIZE_X(uvd->videosize); 1342 vw->height = VIDEOSIZE_Y(uvd->videosize); 1343 vw->chromakey = 0; 1344 if (VALID_CALLBACK(uvd, getFPS)) 1345 vw->flags = GET_CALLBACK(uvd, getFPS)(uvd); 1346 else 1347 vw->flags = 10; 1348 return 0; 1349 } 1350 case VIDIOCGMBUF: 1351 { 1352 struct video_mbuf *vm = arg; 1353 int i; 1354 1355 memset(vm, 0, sizeof(*vm)); 1356 vm->size = uvd->max_frame_size * USBVIDEO_NUMFRAMES; 1357 vm->frames = USBVIDEO_NUMFRAMES; 1358 for(i = 0; i < USBVIDEO_NUMFRAMES; i++) 1359 vm->offsets[i] = i * uvd->max_frame_size; 1360 1361 return 0; 1362 } 1363 case VIDIOCMCAPTURE: 1364 { 1365 struct video_mmap *vm = arg; 1366 1367 if (uvd->debug >= 1) { 1368 dev_info(&uvd->dev->dev, 1369 "VIDIOCMCAPTURE: frame=%d. size=%dx%d, format=%d.\n", 1370 vm->frame, vm->width, vm->height, vm->format); 1371 } 1372 /* 1373 * Check if the requested size is supported. If the requestor 1374 * requests too big a frame then we may be tricked into accessing 1375 * outside of own preallocated frame buffer (in uvd->frame). 1376 * This will cause oops or a security hole. Theoretically, we 1377 * could only clamp the size down to acceptable bounds, but then 1378 * we'd need to figure out how to insert our smaller buffer into 1379 * larger caller's buffer... this is not an easy question. So we 1380 * here just flatly reject too large requests, assuming that the 1381 * caller will resubmit with smaller size. Callers should know 1382 * what size we support (returned by VIDIOCGCAP). However vidcat, 1383 * for one, does not care and allows to ask for any size. 1384 */ 1385 if ((vm->width > VIDEOSIZE_X(uvd->canvas)) || 1386 (vm->height > VIDEOSIZE_Y(uvd->canvas))) { 1387 if (uvd->debug > 0) { 1388 dev_info(&uvd->dev->dev, 1389 "VIDIOCMCAPTURE: Size=%dx%d " 1390 "too large; allowed only up " 1391 "to %ldx%ld\n", vm->width, 1392 vm->height, 1393 VIDEOSIZE_X(uvd->canvas), 1394 VIDEOSIZE_Y(uvd->canvas)); 1395 } 1396 return -EINVAL; 1397 } 1398 /* Check if the palette is supported */ 1399 if (((1L << vm->format) & uvd->paletteBits) == 0) { 1400 if (uvd->debug > 0) { 1401 dev_info(&uvd->dev->dev, 1402 "VIDIOCMCAPTURE: format=%d. " 1403 "not supported " 1404 "(paletteBits=$%08lx)\n", 1405 vm->format, uvd->paletteBits); 1406 } 1407 return -EINVAL; 1408 } 1409 if ((vm->frame < 0) || (vm->frame >= USBVIDEO_NUMFRAMES)) { 1410 err("VIDIOCMCAPTURE: vm.frame=%d. !E [0-%d]", vm->frame, USBVIDEO_NUMFRAMES-1); 1411 return -EINVAL; 1412 } 1413 if (uvd->frame[vm->frame].frameState == FrameState_Grabbing) { 1414 /* Not an error - can happen */ 1415 } 1416 uvd->frame[vm->frame].request = VIDEOSIZE(vm->width, vm->height); 1417 uvd->frame[vm->frame].palette = vm->format; 1418 1419 /* Mark it as ready */ 1420 uvd->frame[vm->frame].frameState = FrameState_Ready; 1421 1422 return usbvideo_NewFrame(uvd, vm->frame); 1423 } 1424 case VIDIOCSYNC: 1425 { 1426 int *frameNum = arg; 1427 int ret; 1428 1429 if (*frameNum < 0 || *frameNum >= USBVIDEO_NUMFRAMES) 1430 return -EINVAL; 1431 1432 if (uvd->debug >= 1) 1433 dev_info(&uvd->dev->dev, 1434 "VIDIOCSYNC: syncing to frame %d.\n", 1435 *frameNum); 1436 if (uvd->flags & FLAGS_NO_DECODING) 1437 ret = usbvideo_GetFrame(uvd, *frameNum); 1438 else if (VALID_CALLBACK(uvd, getFrame)) { 1439 ret = GET_CALLBACK(uvd, getFrame)(uvd, *frameNum); 1440 if ((ret < 0) && (uvd->debug >= 1)) { 1441 err("VIDIOCSYNC: getFrame() returned %d.", ret); 1442 } 1443 } else { 1444 err("VIDIOCSYNC: getFrame is not set"); 1445 ret = -EFAULT; 1446 } 1447 1448 /* 1449 * The frame is in FrameState_Done_Hold state. Release it 1450 * right now because its data is already mapped into 1451 * the user space and it's up to the application to 1452 * make use of it until it asks for another frame. 1453 */ 1454 uvd->frame[*frameNum].frameState = FrameState_Unused; 1455 return ret; 1456 } 1457 case VIDIOCGFBUF: 1458 { 1459 struct video_buffer *vb = arg; 1460 1461 memset(vb, 0, sizeof(*vb)); 1462 return 0; 1463 } 1464 case VIDIOCKEY: 1465 return 0; 1466 1467 case VIDIOCCAPTURE: 1468 return -EINVAL; 1469 1470 case VIDIOCSFBUF: 1471 1472 case VIDIOCGTUNER: 1473 case VIDIOCSTUNER: 1474 1475 case VIDIOCGFREQ: 1476 case VIDIOCSFREQ: 1477 1478 case VIDIOCGAUDIO: 1479 case VIDIOCSAUDIO: 1480 return -EINVAL; 1481 1482 default: 1483 return -ENOIOCTLCMD; 1484 } 1485 return 0; 1486} 1487 1488static long usbvideo_v4l_ioctl(struct file *file, 1489 unsigned int cmd, unsigned long arg) 1490{ 1491 return video_usercopy(file, cmd, arg, usbvideo_v4l_do_ioctl); 1492} 1493 1494/* 1495 * usbvideo_v4l_read() 1496 * 1497 * This is mostly boring stuff. We simply ask for a frame and when it 1498 * arrives copy all the video data from it into user space. There is 1499 * no obvious need to override this method. 1500 * 1501 * History: 1502 * 20-Oct-2000 Created. 1503 * 01-Nov-2000 Added mutex (uvd->lock). 1504 */ 1505static ssize_t usbvideo_v4l_read(struct file *file, char __user *buf, 1506 size_t count, loff_t *ppos) 1507{ 1508 struct uvd *uvd = file->private_data; 1509 int noblock = file->f_flags & O_NONBLOCK; 1510 int frmx = -1, i; 1511 struct usbvideo_frame *frame; 1512 1513 if (!CAMERA_IS_OPERATIONAL(uvd) || (buf == NULL)) 1514 return -EFAULT; 1515 1516 if (uvd->debug >= 1) 1517 dev_info(&uvd->dev->dev, 1518 "%s: %Zd. bytes, noblock=%d.\n", 1519 __func__, count, noblock); 1520 1521 mutex_lock(&uvd->lock); 1522 1523 /* See if a frame is completed, then use it. */ 1524 for(i = 0; i < USBVIDEO_NUMFRAMES; i++) { 1525 if ((uvd->frame[i].frameState == FrameState_Done) || 1526 (uvd->frame[i].frameState == FrameState_Done_Hold) || 1527 (uvd->frame[i].frameState == FrameState_Error)) { 1528 frmx = i; 1529 break; 1530 } 1531 } 1532 1533 if (noblock && (frmx == -1)) { 1534 count = -EAGAIN; 1535 goto read_done; 1536 } 1537 1538 /* 1539 * If no FrameState_Done, look for a FrameState_Grabbing state. 1540 * See if a frame is in process (grabbing), then use it. 1541 * We will need to wait until it becomes cooked, of course. 1542 */ 1543 if (frmx == -1) { 1544 for(i = 0; i < USBVIDEO_NUMFRAMES; i++) { 1545 if (uvd->frame[i].frameState == FrameState_Grabbing) { 1546 frmx = i; 1547 break; 1548 } 1549 } 1550 } 1551 1552 /* 1553 * If no frame is active, start one. We don't care which one 1554 * it will be, so #0 is as good as any. 1555 * In read access mode we don't have convenience of VIDIOCMCAPTURE 1556 * to specify the requested palette (video format) on per-frame 1557 * basis. This means that we have to return data in -some- format 1558 * and just hope that the client knows what to do with it. 1559 * The default format is configured in uvd->defaultPalette field 1560 * as one of VIDEO_PALETTE_xxx values. We stuff it into the new 1561 * frame and initiate the frame filling process. 1562 */ 1563 if (frmx == -1) { 1564 if (uvd->defaultPalette == 0) { 1565 err("%s: No default palette; don't know what to do!", __func__); 1566 count = -EFAULT; 1567 goto read_done; 1568 } 1569 frmx = 0; 1570 /* 1571 * We have no per-frame control over video size. 1572 * Therefore we only can use whatever size was 1573 * specified as default. 1574 */ 1575 uvd->frame[frmx].request = uvd->videosize; 1576 uvd->frame[frmx].palette = uvd->defaultPalette; 1577 uvd->frame[frmx].frameState = FrameState_Ready; 1578 usbvideo_NewFrame(uvd, frmx); 1579 /* Now frame 0 is supposed to start filling... */ 1580 } 1581 1582 /* 1583 * Get a pointer to the active frame. It is either previously 1584 * completed frame or frame in progress but not completed yet. 1585 */ 1586 frame = &uvd->frame[frmx]; 1587 1588 /* 1589 * Sit back & wait until the frame gets filled and postprocessed. 1590 * If we fail to get the picture [in time] then return the error. 1591 * In this call we specify that we want the frame to be waited for, 1592 * postprocessed and switched into FrameState_Done_Hold state. This 1593 * state is used to hold the frame as "fully completed" between 1594 * subsequent partial reads of the same frame. 1595 */ 1596 if (frame->frameState != FrameState_Done_Hold) { 1597 long rv = -EFAULT; 1598 if (uvd->flags & FLAGS_NO_DECODING) 1599 rv = usbvideo_GetFrame(uvd, frmx); 1600 else if (VALID_CALLBACK(uvd, getFrame)) 1601 rv = GET_CALLBACK(uvd, getFrame)(uvd, frmx); 1602 else 1603 err("getFrame is not set"); 1604 if ((rv != 0) || (frame->frameState != FrameState_Done_Hold)) { 1605 count = rv; 1606 goto read_done; 1607 } 1608 } 1609 1610 /* 1611 * Copy bytes to user space. We allow for partial reads, which 1612 * means that the user application can request read less than 1613 * the full frame size. It is up to the application to issue 1614 * subsequent calls until entire frame is read. 1615 * 1616 * First things first, make sure we don't copy more than we 1617 * have - even if the application wants more. That would be 1618 * a big security embarassment! 1619 */ 1620 if ((count + frame->seqRead_Index) > frame->seqRead_Length) 1621 count = frame->seqRead_Length - frame->seqRead_Index; 1622 1623 /* 1624 * Copy requested amount of data to user space. We start 1625 * copying from the position where we last left it, which 1626 * will be zero for a new frame (not read before). 1627 */ 1628 if (copy_to_user(buf, frame->data + frame->seqRead_Index, count)) { 1629 count = -EFAULT; 1630 goto read_done; 1631 } 1632 1633 /* Update last read position */ 1634 frame->seqRead_Index += count; 1635 if (uvd->debug >= 1) { 1636 err("%s: {copy} count used=%Zd, new seqRead_Index=%ld", 1637 __func__, count, frame->seqRead_Index); 1638 } 1639 1640 /* Finally check if the frame is done with and "release" it */ 1641 if (frame->seqRead_Index >= frame->seqRead_Length) { 1642 /* All data has been read */ 1643 frame->seqRead_Index = 0; 1644 1645 /* Mark it as available to be used again. */ 1646 uvd->frame[frmx].frameState = FrameState_Unused; 1647 if (usbvideo_NewFrame(uvd, (frmx + 1) % USBVIDEO_NUMFRAMES)) { 1648 err("%s: usbvideo_NewFrame failed.", __func__); 1649 } 1650 } 1651read_done: 1652 mutex_unlock(&uvd->lock); 1653 return count; 1654} 1655 1656/* 1657 * Make all of the blocks of data contiguous 1658 */ 1659static int usbvideo_CompressIsochronous(struct uvd *uvd, struct urb *urb) 1660{ 1661 char *cdata; 1662 int i, totlen = 0; 1663 1664 for (i = 0; i < urb->number_of_packets; i++) { 1665 int n = urb->iso_frame_desc[i].actual_length; 1666 int st = urb->iso_frame_desc[i].status; 1667 1668 cdata = urb->transfer_buffer + urb->iso_frame_desc[i].offset; 1669 1670 /* Detect and ignore errored packets */ 1671 if (st < 0) { 1672 if (uvd->debug >= 1) 1673 err("Data error: packet=%d. len=%d. status=%d.", i, n, st); 1674 uvd->stats.iso_err_count++; 1675 continue; 1676 } 1677 1678 /* Detect and ignore empty packets */ 1679 if (n <= 0) { 1680 uvd->stats.iso_skip_count++; 1681 continue; 1682 } 1683 totlen += n; /* Little local accounting */ 1684 RingQueue_Enqueue(&uvd->dp, cdata, n); 1685 } 1686 return totlen; 1687} 1688 1689static void usbvideo_IsocIrq(struct urb *urb) 1690{ 1691 int i, ret, len; 1692 struct uvd *uvd = urb->context; 1693 1694 /* We don't want to do anything if we are about to be removed! */ 1695 if (!CAMERA_IS_OPERATIONAL(uvd)) 1696 return; 1697 1698 if (!uvd->streaming) { 1699 if (uvd->debug >= 1) 1700 dev_info(&uvd->dev->dev, 1701 "Not streaming, but interrupt!\n"); 1702 return; 1703 } 1704 1705 uvd->stats.urb_count++; 1706 if (urb->actual_length <= 0) 1707 goto urb_done_with; 1708 1709 /* Copy the data received into ring queue */ 1710 len = usbvideo_CompressIsochronous(uvd, urb); 1711 uvd->stats.urb_length = len; 1712 if (len <= 0) 1713 goto urb_done_with; 1714 1715 /* Here we got some data */ 1716 uvd->stats.data_count += len; 1717 RingQueue_WakeUpInterruptible(&uvd->dp); 1718 1719urb_done_with: 1720 for (i = 0; i < FRAMES_PER_DESC; i++) { 1721 urb->iso_frame_desc[i].status = 0; 1722 urb->iso_frame_desc[i].actual_length = 0; 1723 } 1724 urb->status = 0; 1725 urb->dev = uvd->dev; 1726 ret = usb_submit_urb (urb, GFP_KERNEL); 1727 if(ret) 1728 err("usb_submit_urb error (%d)", ret); 1729 return; 1730} 1731 1732/* 1733 * usbvideo_StartDataPump() 1734 * 1735 * History: 1736 * 27-Jan-2000 Used ibmcam->iface, ibmcam->ifaceAltActive instead 1737 * of hardcoded values. Simplified by using for loop, 1738 * allowed any number of URBs. 1739 */ 1740static int usbvideo_StartDataPump(struct uvd *uvd) 1741{ 1742 struct usb_device *dev = uvd->dev; 1743 int i, errFlag; 1744 1745 if (uvd->debug > 1) 1746 dev_info(&uvd->dev->dev, "%s($%p)\n", __func__, uvd); 1747 1748 if (!CAMERA_IS_OPERATIONAL(uvd)) { 1749 err("%s: Camera is not operational", __func__); 1750 return -EFAULT; 1751 } 1752 uvd->curframe = -1; 1753 1754 /* Alternate interface 1 is is the biggest frame size */ 1755 i = usb_set_interface(dev, uvd->iface, uvd->ifaceAltActive); 1756 if (i < 0) { 1757 err("%s: usb_set_interface error", __func__); 1758 uvd->last_error = i; 1759 return -EBUSY; 1760 } 1761 if (VALID_CALLBACK(uvd, videoStart)) 1762 GET_CALLBACK(uvd, videoStart)(uvd); 1763 else 1764 err("%s: videoStart not set", __func__); 1765 1766 /* We double buffer the Iso lists */ 1767 for (i=0; i < USBVIDEO_NUMSBUF; i++) { 1768 int j, k; 1769 struct urb *urb = uvd->sbuf[i].urb; 1770 urb->dev = dev; 1771 urb->context = uvd; 1772 urb->pipe = usb_rcvisocpipe(dev, uvd->video_endp); 1773 urb->interval = 1; 1774 urb->transfer_flags = URB_ISO_ASAP; 1775 urb->transfer_buffer = uvd->sbuf[i].data; 1776 urb->complete = usbvideo_IsocIrq; 1777 urb->number_of_packets = FRAMES_PER_DESC; 1778 urb->transfer_buffer_length = uvd->iso_packet_len * FRAMES_PER_DESC; 1779 for (j=k=0; j < FRAMES_PER_DESC; j++, k += uvd->iso_packet_len) { 1780 urb->iso_frame_desc[j].offset = k; 1781 urb->iso_frame_desc[j].length = uvd->iso_packet_len; 1782 } 1783 } 1784 1785 /* Submit all URBs */ 1786 for (i=0; i < USBVIDEO_NUMSBUF; i++) { 1787 errFlag = usb_submit_urb(uvd->sbuf[i].urb, GFP_KERNEL); 1788 if (errFlag) 1789 err("%s: usb_submit_isoc(%d) ret %d", __func__, i, errFlag); 1790 } 1791 1792 uvd->streaming = 1; 1793 if (uvd->debug > 1) 1794 dev_info(&uvd->dev->dev, 1795 "%s: streaming=1 video_endp=$%02x\n", __func__, 1796 uvd->video_endp); 1797 return 0; 1798} 1799 1800/* 1801 * usbvideo_StopDataPump() 1802 * 1803 * This procedure stops streaming and deallocates URBs. Then it 1804 * activates zero-bandwidth alt. setting of the video interface. 1805 * 1806 * History: 1807 * 22-Jan-2000 Corrected order of actions to work after surprise removal. 1808 * 27-Jan-2000 Used uvd->iface, uvd->ifaceAltInactive instead of hardcoded values. 1809 */ 1810static void usbvideo_StopDataPump(struct uvd *uvd) 1811{ 1812 int i, j; 1813 1814 if ((uvd == NULL) || (!uvd->streaming) || (uvd->dev == NULL)) 1815 return; 1816 1817 if (uvd->debug > 1) 1818 dev_info(&uvd->dev->dev, "%s($%p)\n", __func__, uvd); 1819 1820 /* Unschedule all of the iso td's */ 1821 for (i=0; i < USBVIDEO_NUMSBUF; i++) { 1822 usb_kill_urb(uvd->sbuf[i].urb); 1823 } 1824 if (uvd->debug > 1) 1825 dev_info(&uvd->dev->dev, "%s: streaming=0\n", __func__); 1826 uvd->streaming = 0; 1827 1828 if (!uvd->remove_pending) { 1829 /* Invoke minidriver's magic to stop the camera */ 1830 if (VALID_CALLBACK(uvd, videoStop)) 1831 GET_CALLBACK(uvd, videoStop)(uvd); 1832 else 1833 err("%s: videoStop not set", __func__); 1834 1835 /* Set packet size to 0 */ 1836 j = usb_set_interface(uvd->dev, uvd->iface, uvd->ifaceAltInactive); 1837 if (j < 0) { 1838 err("%s: usb_set_interface() error %d.", __func__, j); 1839 uvd->last_error = j; 1840 } 1841 } 1842} 1843 1844/* 1845 * usbvideo_NewFrame() 1846 * 1847 * History: 1848 * 29-Mar-00 Added copying of previous frame into the current one. 1849 * 6-Aug-00 Added model 3 video sizes, removed redundant width, height. 1850 */ 1851static int usbvideo_NewFrame(struct uvd *uvd, int framenum) 1852{ 1853 struct usbvideo_frame *frame; 1854 int n; 1855 1856 if (uvd->debug > 1) 1857 dev_info(&uvd->dev->dev, "usbvideo_NewFrame($%p,%d.)\n", uvd, 1858 framenum); 1859 1860 /* If we're not grabbing a frame right now and the other frame is */ 1861 /* ready to be grabbed into, then use it instead */ 1862 if (uvd->curframe != -1) 1863 return 0; 1864 1865 /* If necessary we adjust picture settings between frames */ 1866 if (!uvd->settingsAdjusted) { 1867 if (VALID_CALLBACK(uvd, adjustPicture)) 1868 GET_CALLBACK(uvd, adjustPicture)(uvd); 1869 uvd->settingsAdjusted = 1; 1870 } 1871 1872 n = (framenum + 1) % USBVIDEO_NUMFRAMES; 1873 if (uvd->frame[n].frameState == FrameState_Ready) 1874 framenum = n; 1875 1876 frame = &uvd->frame[framenum]; 1877 1878 frame->frameState = FrameState_Grabbing; 1879 frame->scanstate = ScanState_Scanning; 1880 frame->seqRead_Length = 0; /* Accumulated in xxx_parse_data() */ 1881 frame->deinterlace = Deinterlace_None; 1882 frame->flags = 0; /* No flags yet, up to minidriver (or us) to set them */ 1883 uvd->curframe = framenum; 1884 1885 /* 1886 * Normally we would want to copy previous frame into the current one 1887 * before we even start filling it with data; this allows us to stop 1888 * filling at any moment; top portion of the frame will be new and 1889 * bottom portion will stay as it was in previous frame. If we don't 1890 * do that then missing chunks of video stream will result in flickering 1891 * portions of old data whatever it was before. 1892 * 1893 * If we choose not to copy previous frame (to, for example, save few 1894 * bus cycles - the frame can be pretty large!) then we have an option 1895 * to clear the frame before using. If we experience losses in this 1896 * mode then missing picture will be black (no flickering). 1897 * 1898 * Finally, if user chooses not to clean the current frame before 1899 * filling it with data then the old data will be visible if we fail 1900 * to refill entire frame with new data. 1901 */ 1902 if (!(uvd->flags & FLAGS_SEPARATE_FRAMES)) { 1903 /* This copies previous frame into this one to mask losses */ 1904 int prev = (framenum - 1 + USBVIDEO_NUMFRAMES) % USBVIDEO_NUMFRAMES; 1905 memmove(frame->data, uvd->frame[prev].data, uvd->max_frame_size); 1906 } else { 1907 if (uvd->flags & FLAGS_CLEAN_FRAMES) { 1908 /* This provides a "clean" frame but slows things down */ 1909 memset(frame->data, 0, uvd->max_frame_size); 1910 } 1911 } 1912 return 0; 1913} 1914 1915/* 1916 * usbvideo_CollectRawData() 1917 * 1918 * This procedure can be used instead of 'processData' callback if you 1919 * only want to dump the raw data from the camera into the output 1920 * device (frame buffer). You can look at it with V4L client, but the 1921 * image will be unwatchable. The main purpose of this code and of the 1922 * mode FLAGS_NO_DECODING is debugging and capturing of datastreams from 1923 * new, unknown cameras. This procedure will be automatically invoked 1924 * instead of the specified callback handler when uvd->flags has bit 1925 * FLAGS_NO_DECODING set. Therefore, any regular build of any driver 1926 * based on usbvideo can use this feature at any time. 1927 */ 1928static void usbvideo_CollectRawData(struct uvd *uvd, struct usbvideo_frame *frame) 1929{ 1930 int n; 1931 1932 assert(uvd != NULL); 1933 assert(frame != NULL); 1934 1935 /* Try to move data from queue into frame buffer */ 1936 n = RingQueue_GetLength(&uvd->dp); 1937 if (n > 0) { 1938 int m; 1939 /* See how much space we have left */ 1940 m = uvd->max_frame_size - frame->seqRead_Length; 1941 if (n > m) 1942 n = m; 1943 /* Now move that much data into frame buffer */ 1944 RingQueue_Dequeue( 1945 &uvd->dp, 1946 frame->data + frame->seqRead_Length, 1947 m); 1948 frame->seqRead_Length += m; 1949 } 1950 /* See if we filled the frame */ 1951 if (frame->seqRead_Length >= uvd->max_frame_size) { 1952 frame->frameState = FrameState_Done; 1953 uvd->curframe = -1; 1954 uvd->stats.frame_num++; 1955 } 1956} 1957 1958static int usbvideo_GetFrame(struct uvd *uvd, int frameNum) 1959{ 1960 struct usbvideo_frame *frame = &uvd->frame[frameNum]; 1961 1962 if (uvd->debug >= 2) 1963 dev_info(&uvd->dev->dev, "%s($%p,%d.)\n", __func__, uvd, 1964 frameNum); 1965 1966 switch (frame->frameState) { 1967 case FrameState_Unused: 1968 if (uvd->debug >= 2) 1969 dev_info(&uvd->dev->dev, "%s: FrameState_Unused\n", 1970 __func__); 1971 return -EINVAL; 1972 case FrameState_Ready: 1973 case FrameState_Grabbing: 1974 case FrameState_Error: 1975 { 1976 int ntries, signalPending; 1977 redo: 1978 if (!CAMERA_IS_OPERATIONAL(uvd)) { 1979 if (uvd->debug >= 2) 1980 dev_info(&uvd->dev->dev, 1981 "%s: Camera is not operational (1)\n", 1982 __func__); 1983 return -EIO; 1984 } 1985 ntries = 0; 1986 do { 1987 RingQueue_InterruptibleSleepOn(&uvd->dp); 1988 signalPending = signal_pending(current); 1989 if (!CAMERA_IS_OPERATIONAL(uvd)) { 1990 if (uvd->debug >= 2) 1991 dev_info(&uvd->dev->dev, 1992 "%s: Camera is not " 1993 "operational (2)\n", __func__); 1994 return -EIO; 1995 } 1996 assert(uvd->fbuf != NULL); 1997 if (signalPending) { 1998 if (uvd->debug >= 2) 1999 dev_info(&uvd->dev->dev, 2000 "%s: Signal=$%08x\n", __func__, 2001 signalPending); 2002 if (uvd->flags & FLAGS_RETRY_VIDIOCSYNC) { 2003 usbvideo_TestPattern(uvd, 1, 0); 2004 uvd->curframe = -1; 2005 uvd->stats.frame_num++; 2006 if (uvd->debug >= 2) 2007 dev_info(&uvd->dev->dev, 2008 "%s: Forced test " 2009 "pattern screen\n", 2010 __func__); 2011 return 0; 2012 } else { 2013 /* Standard answer: Interrupted! */ 2014 if (uvd->debug >= 2) 2015 dev_info(&uvd->dev->dev, 2016 "%s: Interrupted!\n", 2017 __func__); 2018 return -EINTR; 2019 } 2020 } else { 2021 /* No signals - we just got new data in dp queue */ 2022 if (uvd->flags & FLAGS_NO_DECODING) 2023 usbvideo_CollectRawData(uvd, frame); 2024 else if (VALID_CALLBACK(uvd, processData)) 2025 GET_CALLBACK(uvd, processData)(uvd, frame); 2026 else 2027 err("%s: processData not set", __func__); 2028 } 2029 } while (frame->frameState == FrameState_Grabbing); 2030 if (uvd->debug >= 2) { 2031 dev_info(&uvd->dev->dev, 2032 "%s: Grabbing done; state=%d. (%lu. bytes)\n", 2033 __func__, frame->frameState, 2034 frame->seqRead_Length); 2035 } 2036 if (frame->frameState == FrameState_Error) { 2037 int ret = usbvideo_NewFrame(uvd, frameNum); 2038 if (ret < 0) { 2039 err("%s: usbvideo_NewFrame() failed (%d.)", __func__, ret); 2040 return ret; 2041 } 2042 goto redo; 2043 } 2044 /* Note that we fall through to meet our destiny below */ 2045 } 2046 case FrameState_Done: 2047 /* 2048 * Do all necessary postprocessing of data prepared in 2049 * "interrupt" code and the collecting code above. The 2050 * frame gets marked as FrameState_Done by queue parsing code. 2051 * This status means that we collected enough data and 2052 * most likely processed it as we went through. However 2053 * the data may need postprocessing, such as deinterlacing 2054 * or picture adjustments implemented in software (horror!) 2055 * 2056 * As soon as the frame becomes "final" it gets promoted to 2057 * FrameState_Done_Hold status where it will remain until the 2058 * caller consumed all the video data from the frame. Then 2059 * the empty shell of ex-frame is thrown out for dogs to eat. 2060 * But we, worried about pets, will recycle the frame! 2061 */ 2062 uvd->stats.frame_num++; 2063 if ((uvd->flags & FLAGS_NO_DECODING) == 0) { 2064 if (VALID_CALLBACK(uvd, postProcess)) 2065 GET_CALLBACK(uvd, postProcess)(uvd, frame); 2066 if (frame->flags & USBVIDEO_FRAME_FLAG_SOFTWARE_CONTRAST) 2067 usbvideo_SoftwareContrastAdjustment(uvd, frame); 2068 } 2069 frame->frameState = FrameState_Done_Hold; 2070 if (uvd->debug >= 2) 2071 dev_info(&uvd->dev->dev, 2072 "%s: Entered FrameState_Done_Hold state.\n", 2073 __func__); 2074 return 0; 2075 2076 case FrameState_Done_Hold: 2077 /* 2078 * We stay in this state indefinitely until someone external, 2079 * like ioctl() or read() call finishes digesting the frame 2080 * data. Then it will mark the frame as FrameState_Unused and 2081 * it will be released back into the wild to roam freely. 2082 */ 2083 if (uvd->debug >= 2) 2084 dev_info(&uvd->dev->dev, 2085 "%s: FrameState_Done_Hold state.\n", 2086 __func__); 2087 return 0; 2088 } 2089 2090 /* Catch-all for other cases. We shall not be here. */ 2091 err("%s: Invalid state %d.", __func__, frame->frameState); 2092 frame->frameState = FrameState_Unused; 2093 return 0; 2094} 2095 2096/* 2097 * usbvideo_DeinterlaceFrame() 2098 * 2099 * This procedure deinterlaces the given frame. Some cameras produce 2100 * only half of scanlines - sometimes only even lines, sometimes only 2101 * odd lines. The deinterlacing method is stored in frame->deinterlace 2102 * variable. 2103 * 2104 * Here we scan the frame vertically and replace missing scanlines with 2105 * average between surrounding ones - before and after. If we have no 2106 * line above then we just copy next line. Similarly, if we need to 2107 * create a last line then preceding line is used. 2108 */ 2109void usbvideo_DeinterlaceFrame(struct uvd *uvd, struct usbvideo_frame *frame) 2110{ 2111 if ((uvd == NULL) || (frame == NULL)) 2112 return; 2113 2114 if ((frame->deinterlace == Deinterlace_FillEvenLines) || 2115 (frame->deinterlace == Deinterlace_FillOddLines)) 2116 { 2117 const int v4l_linesize = VIDEOSIZE_X(frame->request) * V4L_BYTES_PER_PIXEL; 2118 int i = (frame->deinterlace == Deinterlace_FillEvenLines) ? 0 : 1; 2119 2120 for (; i < VIDEOSIZE_Y(frame->request); i += 2) { 2121 const unsigned char *fs1, *fs2; 2122 unsigned char *fd; 2123 int ip, in, j; /* Previous and next lines */ 2124 2125 /* 2126 * Need to average lines before and after 'i'. 2127 * If we go out of bounds seeking those lines then 2128 * we point back to existing line. 2129 */ 2130 ip = i - 1; /* First, get rough numbers */ 2131 in = i + 1; 2132 2133 /* Now validate */ 2134 if (ip < 0) 2135 ip = in; 2136 if (in >= VIDEOSIZE_Y(frame->request)) 2137 in = ip; 2138 2139 /* Sanity check */ 2140 if ((ip < 0) || (in < 0) || 2141 (ip >= VIDEOSIZE_Y(frame->request)) || 2142 (in >= VIDEOSIZE_Y(frame->request))) 2143 { 2144 err("Error: ip=%d. in=%d. req.height=%ld.", 2145 ip, in, VIDEOSIZE_Y(frame->request)); 2146 break; 2147 } 2148 2149 /* Now we need to average lines 'ip' and 'in' to produce line 'i' */ 2150 fs1 = frame->data + (v4l_linesize * ip); 2151 fs2 = frame->data + (v4l_linesize * in); 2152 fd = frame->data + (v4l_linesize * i); 2153 2154 /* Average lines around destination */ 2155 for (j=0; j < v4l_linesize; j++) { 2156 fd[j] = (unsigned char)((((unsigned) fs1[j]) + 2157 ((unsigned)fs2[j])) >> 1); 2158 } 2159 } 2160 } 2161 2162 /* Optionally display statistics on the screen */ 2163 if (uvd->flags & FLAGS_OVERLAY_STATS) 2164 usbvideo_OverlayStats(uvd, frame); 2165} 2166 2167EXPORT_SYMBOL(usbvideo_DeinterlaceFrame); 2168 2169/* 2170 * usbvideo_SoftwareContrastAdjustment() 2171 * 2172 * This code adjusts the contrast of the frame, assuming RGB24 format. 2173 * As most software image processing, this job is CPU-intensive. 2174 * Get a camera that supports hardware adjustment! 2175 * 2176 * History: 2177 * 09-Feb-2001 Created. 2178 */ 2179static void usbvideo_SoftwareContrastAdjustment(struct uvd *uvd, 2180 struct usbvideo_frame *frame) 2181{ 2182 int i, j, v4l_linesize; 2183 signed long adj; 2184 const int ccm = 128; /* Color correction median - see below */ 2185 2186 if ((uvd == NULL) || (frame == NULL)) { 2187 err("%s: Illegal call.", __func__); 2188 return; 2189 } 2190 adj = (uvd->vpic.contrast - 0x8000) >> 8; /* -128..+127 = -ccm..+(ccm-1)*/ 2191 RESTRICT_TO_RANGE(adj, -ccm, ccm+1); 2192 if (adj == 0) { 2193 /* In rare case of no adjustment */ 2194 return; 2195 } 2196 v4l_linesize = VIDEOSIZE_X(frame->request) * V4L_BYTES_PER_PIXEL; 2197 for (i=0; i < VIDEOSIZE_Y(frame->request); i++) { 2198 unsigned char *fd = frame->data + (v4l_linesize * i); 2199 for (j=0; j < v4l_linesize; j++) { 2200 signed long v = (signed long) fd[j]; 2201 /* Magnify up to 2 times, reduce down to zero */ 2202 v = 128 + ((ccm + adj) * (v - 128)) / ccm; 2203 RESTRICT_TO_RANGE(v, 0, 0xFF); /* Must flatten tails */ 2204 fd[j] = (unsigned char) v; 2205 } 2206 } 2207} 2208 2209MODULE_LICENSE("GPL"); 2210