OMAP3 SRF: Generic shared resource f/w
[linux-ginger.git] / drivers / media / video / usbvideo / usbvideo.c
blobdea8b321fb4a5b983f35da9f56fa6a83a22c1895
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.
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.
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.
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>
27 #include <asm/io.h>
29 #include "usbvideo.h"
31 #if defined(MAP_NR)
32 #define virt_to_page(v) MAP_NR(v) /* Kernels 2.2.x */
33 #endif
35 static int video_nr = -1;
36 module_param(video_nr, int, 0);
39 * Local prototypes.
41 static void usbvideo_Disconnect(struct usb_interface *intf);
42 static void usbvideo_CameraRelease(struct uvd *uvd);
44 static long usbvideo_v4l_ioctl(struct file *file,
45 unsigned int cmd, unsigned long arg);
46 static int usbvideo_v4l_mmap(struct file *file, struct vm_area_struct *vma);
47 static int usbvideo_v4l_open(struct file *file);
48 static ssize_t usbvideo_v4l_read(struct file *file, char __user *buf,
49 size_t count, loff_t *ppos);
50 static int usbvideo_v4l_close(struct file *file);
52 static int usbvideo_StartDataPump(struct uvd *uvd);
53 static void usbvideo_StopDataPump(struct uvd *uvd);
54 static int usbvideo_GetFrame(struct uvd *uvd, int frameNum);
55 static int usbvideo_NewFrame(struct uvd *uvd, int framenum);
56 static void usbvideo_SoftwareContrastAdjustment(struct uvd *uvd,
57 struct usbvideo_frame *frame);
59 /*******************************/
60 /* Memory management functions */
61 /*******************************/
62 static void *usbvideo_rvmalloc(unsigned long size)
64 void *mem;
65 unsigned long adr;
67 size = PAGE_ALIGN(size);
68 mem = vmalloc_32(size);
69 if (!mem)
70 return NULL;
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;
80 return mem;
83 static void usbvideo_rvfree(void *mem, unsigned long size)
85 unsigned long adr;
87 if (!mem)
88 return;
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;
96 vfree(mem);
99 static void RingQueue_Initialize(struct RingQueue *rq)
101 assert(rq != NULL);
102 init_waitqueue_head(&rq->wqh);
105 static void RingQueue_Allocate(struct RingQueue *rq, int rqLen)
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 */
111 int i = 1;
112 assert(rq != NULL);
113 assert(rqLen > 0);
115 while(rqLen >> i)
116 i++;
117 if(rqLen != 1 << (i-1))
118 rqLen = 1 << i;
120 rq->length = rqLen;
121 rq->ri = rq->wi = 0;
122 rq->queue = usbvideo_rvmalloc(rq->length);
123 assert(rq->queue != NULL);
126 static int RingQueue_IsAllocated(const struct RingQueue *rq)
128 if (rq == NULL)
129 return 0;
130 return (rq->queue != NULL) && (rq->length > 0);
133 static void RingQueue_Free(struct RingQueue *rq)
135 assert(rq != NULL);
136 if (RingQueue_IsAllocated(rq)) {
137 usbvideo_rvfree(rq->queue, rq->length);
138 rq->queue = NULL;
139 rq->length = 0;
143 int RingQueue_Dequeue(struct RingQueue *rq, unsigned char *dst, int len)
145 int rql, toread;
147 assert(rq != NULL);
148 assert(dst != NULL);
150 rql = RingQueue_GetLength(rq);
151 if(!rql)
152 return 0;
154 /* Clip requested length to available data */
155 if(len > rql)
156 len = rql;
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);
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);
172 return len;
175 EXPORT_SYMBOL(RingQueue_Dequeue);
177 int RingQueue_Enqueue(struct RingQueue *rq, const unsigned char *cdata, int n)
179 int enqueued = 0;
181 assert(rq != NULL);
182 assert(cdata != NULL);
183 assert(rq->length > 0);
184 while (n > 0) {
185 int m, q_avail;
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;
193 m = n;
194 assert(q_avail > 0);
195 if (m > q_avail)
196 m = q_avail;
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;
204 return enqueued;
207 EXPORT_SYMBOL(RingQueue_Enqueue);
209 static void RingQueue_InterruptibleSleepOn(struct RingQueue *rq)
211 assert(rq != NULL);
212 interruptible_sleep_on(&rq->wqh);
215 void RingQueue_WakeUpInterruptible(struct RingQueue *rq)
217 assert(rq != NULL);
218 if (waitqueue_active(&rq->wqh))
219 wake_up_interruptible(&rq->wqh);
222 EXPORT_SYMBOL(RingQueue_WakeUpInterruptible);
224 void RingQueue_Flush(struct RingQueue *rq)
226 assert(rq != NULL);
227 rq->ri = 0;
228 rq->wi = 0;
231 EXPORT_SYMBOL(RingQueue_Flush);
235 * usbvideo_VideosizeToString()
237 * This procedure converts given videosize value to readable string.
239 * History:
240 * 07-Aug-2000 Created.
241 * 19-Oct-2000 Reworked for usbvideo module.
243 static void usbvideo_VideosizeToString(char *buf, int bufLen, videosize_t vs)
245 char tmp[40];
246 int n;
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);
257 * usbvideo_OverlayChar()
259 * History:
260 * 01-Feb-2000 Created.
262 static void usbvideo_OverlayChar(struct uvd *uvd, struct usbvideo_frame *frame,
263 int x, int y, int ch)
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 */
283 unsigned short digit;
284 int ix, iy;
286 if ((uvd == NULL) || (frame == NULL))
287 return;
289 if (ch >= '0' && ch <= '9')
290 ch -= '0';
291 else if (ch >= 'A' && ch <= 'F')
292 ch = 10 + (ch - 'A');
293 else if (ch >= 'a' && ch <= 'f')
294 ch = 10 + (ch - 'a');
295 else
296 return;
297 digit = digits[ch];
299 for (iy=0; iy < 5; iy++) {
300 for (ix=0; ix < 3; ix++) {
301 if (digit & 0x8000) {
302 if (uvd->paletteBits & (1L << VIDEO_PALETTE_RGB24)) {
303 /* TODO */ RGB24_PUTPIXEL(frame, x+ix, y+iy, 0xFF, 0xFF, 0xFF);
306 digit = digit << 1;
312 * usbvideo_OverlayString()
314 * History:
315 * 01-Feb-2000 Created.
317 static void usbvideo_OverlayString(struct uvd *uvd, struct usbvideo_frame *frame,
318 int x, int y, const char *str)
320 while (*str) {
321 usbvideo_OverlayChar(uvd, frame, x, y, *str);
322 str++;
323 x += 4; /* 3 pixels character + 1 space */
328 * usbvideo_OverlayStats()
330 * Overlays important debugging information.
332 * History:
333 * 01-Feb-2000 Created.
335 static void usbvideo_OverlayStats(struct uvd *uvd, struct usbvideo_frame *frame)
337 const int y_diff = 8;
338 char tmp[16];
339 int x = 10, y=10;
340 long i, j, barLength;
341 const int qi_x1 = 60, qi_y1 = 10;
342 const int qi_x2 = VIDEOSIZE_X(frame->request) - 10, qi_h = 10;
344 /* Call the user callback, see if we may proceed after that */
345 if (VALID_CALLBACK(uvd, overlayHook)) {
346 if (GET_CALLBACK(uvd, overlayHook)(uvd, frame) < 0)
347 return;
351 * We draw a (mostly) hollow rectangle with qi_xxx coordinates.
352 * Left edge symbolizes the queue index 0; right edge symbolizes
353 * the full capacity of the queue.
355 barLength = qi_x2 - qi_x1 - 2;
356 if ((barLength > 10) && (uvd->paletteBits & (1L << VIDEO_PALETTE_RGB24))) {
357 /* TODO */ long u_lo, u_hi, q_used;
358 long m_ri, m_wi, m_lo, m_hi;
361 * Determine fill zones (used areas of the queue):
362 * 0 xxxxxxx u_lo ...... uvd->dp.ri xxxxxxxx u_hi ..... uvd->dp.length
364 * if u_lo < 0 then there is no first filler.
367 q_used = RingQueue_GetLength(&uvd->dp);
368 if ((uvd->dp.ri + q_used) >= uvd->dp.length) {
369 u_hi = uvd->dp.length;
370 u_lo = (q_used + uvd->dp.ri) & (uvd->dp.length-1);
371 } else {
372 u_hi = (q_used + uvd->dp.ri);
373 u_lo = -1;
376 /* Convert byte indices into screen units */
377 m_ri = qi_x1 + ((barLength * uvd->dp.ri) / uvd->dp.length);
378 m_wi = qi_x1 + ((barLength * uvd->dp.wi) / uvd->dp.length);
379 m_lo = (u_lo > 0) ? (qi_x1 + ((barLength * u_lo) / uvd->dp.length)) : -1;
380 m_hi = qi_x1 + ((barLength * u_hi) / uvd->dp.length);
382 for (j=qi_y1; j < (qi_y1 + qi_h); j++) {
383 for (i=qi_x1; i < qi_x2; i++) {
384 /* Draw border lines */
385 if ((j == qi_y1) || (j == (qi_y1 + qi_h - 1)) ||
386 (i == qi_x1) || (i == (qi_x2 - 1))) {
387 RGB24_PUTPIXEL(frame, i, j, 0xFF, 0xFF, 0xFF);
388 continue;
390 /* For all other points the Y coordinate does not matter */
391 if ((i >= m_ri) && (i <= (m_ri + 3))) {
392 RGB24_PUTPIXEL(frame, i, j, 0x00, 0xFF, 0x00);
393 } else if ((i >= m_wi) && (i <= (m_wi + 3))) {
394 RGB24_PUTPIXEL(frame, i, j, 0xFF, 0x00, 0x00);
395 } else if ((i < m_lo) || ((i > m_ri) && (i < m_hi)))
396 RGB24_PUTPIXEL(frame, i, j, 0x00, 0x00, 0xFF);
401 sprintf(tmp, "%8lx", uvd->stats.frame_num);
402 usbvideo_OverlayString(uvd, frame, x, y, tmp);
403 y += y_diff;
405 sprintf(tmp, "%8lx", uvd->stats.urb_count);
406 usbvideo_OverlayString(uvd, frame, x, y, tmp);
407 y += y_diff;
409 sprintf(tmp, "%8lx", uvd->stats.urb_length);
410 usbvideo_OverlayString(uvd, frame, x, y, tmp);
411 y += y_diff;
413 sprintf(tmp, "%8lx", uvd->stats.data_count);
414 usbvideo_OverlayString(uvd, frame, x, y, tmp);
415 y += y_diff;
417 sprintf(tmp, "%8lx", uvd->stats.header_count);
418 usbvideo_OverlayString(uvd, frame, x, y, tmp);
419 y += y_diff;
421 sprintf(tmp, "%8lx", uvd->stats.iso_skip_count);
422 usbvideo_OverlayString(uvd, frame, x, y, tmp);
423 y += y_diff;
425 sprintf(tmp, "%8lx", uvd->stats.iso_err_count);
426 usbvideo_OverlayString(uvd, frame, x, y, tmp);
427 y += y_diff;
429 sprintf(tmp, "%8x", uvd->vpic.colour);
430 usbvideo_OverlayString(uvd, frame, x, y, tmp);
431 y += y_diff;
433 sprintf(tmp, "%8x", uvd->vpic.hue);
434 usbvideo_OverlayString(uvd, frame, x, y, tmp);
435 y += y_diff;
437 sprintf(tmp, "%8x", uvd->vpic.brightness >> 8);
438 usbvideo_OverlayString(uvd, frame, x, y, tmp);
439 y += y_diff;
441 sprintf(tmp, "%8x", uvd->vpic.contrast >> 12);
442 usbvideo_OverlayString(uvd, frame, x, y, tmp);
443 y += y_diff;
445 sprintf(tmp, "%8d", uvd->vpic.whiteness >> 8);
446 usbvideo_OverlayString(uvd, frame, x, y, tmp);
447 y += y_diff;
451 * usbvideo_ReportStatistics()
453 * This procedure prints packet and transfer statistics.
455 * History:
456 * 14-Jan-2000 Corrected default multiplier.
458 static void usbvideo_ReportStatistics(const struct uvd *uvd)
460 if ((uvd != NULL) && (uvd->stats.urb_count > 0)) {
461 unsigned long allPackets, badPackets, goodPackets, percent;
462 allPackets = uvd->stats.urb_count * CAMERA_URB_FRAMES;
463 badPackets = uvd->stats.iso_skip_count + uvd->stats.iso_err_count;
464 goodPackets = allPackets - badPackets;
465 /* Calculate percentage wisely, remember integer limits */
466 assert(allPackets != 0);
467 if (goodPackets < (((unsigned long)-1)/100))
468 percent = (100 * goodPackets) / allPackets;
469 else
470 percent = goodPackets / (allPackets / 100);
471 dev_info(&uvd->dev->dev,
472 "Packet Statistics: Total=%lu. Empty=%lu. Usage=%lu%%\n",
473 allPackets, badPackets, percent);
474 if (uvd->iso_packet_len > 0) {
475 unsigned long allBytes, xferBytes;
476 char multiplier = ' ';
477 allBytes = allPackets * uvd->iso_packet_len;
478 xferBytes = uvd->stats.data_count;
479 assert(allBytes != 0);
480 if (xferBytes < (((unsigned long)-1)/100))
481 percent = (100 * xferBytes) / allBytes;
482 else
483 percent = xferBytes / (allBytes / 100);
484 /* Scale xferBytes for easy reading */
485 if (xferBytes > 10*1024) {
486 xferBytes /= 1024;
487 multiplier = 'K';
488 if (xferBytes > 10*1024) {
489 xferBytes /= 1024;
490 multiplier = 'M';
491 if (xferBytes > 10*1024) {
492 xferBytes /= 1024;
493 multiplier = 'G';
494 if (xferBytes > 10*1024) {
495 xferBytes /= 1024;
496 multiplier = 'T';
501 dev_info(&uvd->dev->dev,
502 "Transfer Statistics: Transferred=%lu%cB Usage=%lu%%\n",
503 xferBytes, multiplier, percent);
509 * usbvideo_TestPattern()
511 * Procedure forms a test pattern (yellow grid on blue background).
513 * Parameters:
514 * fullframe: if TRUE then entire frame is filled, otherwise the procedure
515 * continues from the current scanline.
516 * pmode 0: fill the frame with solid blue color (like on VCR or TV)
517 * 1: Draw a colored grid
519 * History:
520 * 01-Feb-2000 Created.
522 void usbvideo_TestPattern(struct uvd *uvd, int fullframe, int pmode)
524 struct usbvideo_frame *frame;
525 int num_cell = 0;
526 int scan_length = 0;
527 static int num_pass;
529 if (uvd == NULL) {
530 err("%s: uvd == NULL", __func__);
531 return;
533 if ((uvd->curframe < 0) || (uvd->curframe >= USBVIDEO_NUMFRAMES)) {
534 err("%s: uvd->curframe=%d.", __func__, uvd->curframe);
535 return;
538 /* Grab the current frame */
539 frame = &uvd->frame[uvd->curframe];
541 /* Optionally start at the beginning */
542 if (fullframe) {
543 frame->curline = 0;
544 frame->seqRead_Length = 0;
546 #if 0
547 { /* For debugging purposes only */
548 char tmp[20];
549 usbvideo_VideosizeToString(tmp, sizeof(tmp), frame->request);
550 dev_info(&uvd->dev->dev, "testpattern: frame=%s\n", tmp);
552 #endif
553 /* Form every scan line */
554 for (; frame->curline < VIDEOSIZE_Y(frame->request); frame->curline++) {
555 int i;
556 unsigned char *f = frame->data +
557 (VIDEOSIZE_X(frame->request) * V4L_BYTES_PER_PIXEL * frame->curline);
558 for (i=0; i < VIDEOSIZE_X(frame->request); i++) {
559 unsigned char cb=0x80;
560 unsigned char cg = 0;
561 unsigned char cr = 0;
563 if (pmode == 1) {
564 if (frame->curline % 32 == 0)
565 cb = 0, cg = cr = 0xFF;
566 else if (i % 32 == 0) {
567 if (frame->curline % 32 == 1)
568 num_cell++;
569 cb = 0, cg = cr = 0xFF;
570 } else {
571 cb = ((num_cell*7) + num_pass) & 0xFF;
572 cg = ((num_cell*5) + num_pass*2) & 0xFF;
573 cr = ((num_cell*3) + num_pass*3) & 0xFF;
575 } else {
576 /* Just the blue screen */
579 *f++ = cb;
580 *f++ = cg;
581 *f++ = cr;
582 scan_length += 3;
586 frame->frameState = FrameState_Done;
587 frame->seqRead_Length += scan_length;
588 ++num_pass;
590 /* We do this unconditionally, regardless of FLAGS_OVERLAY_STATS */
591 usbvideo_OverlayStats(uvd, frame);
594 EXPORT_SYMBOL(usbvideo_TestPattern);
597 #ifdef DEBUG
599 * usbvideo_HexDump()
601 * A debugging tool. Prints hex dumps.
603 * History:
604 * 29-Jul-2000 Added printing of offsets.
606 void usbvideo_HexDump(const unsigned char *data, int len)
608 const int bytes_per_line = 32;
609 char tmp[128]; /* 32*3 + 5 */
610 int i, k;
612 for (i=k=0; len > 0; i++, len--) {
613 if (i > 0 && ((i % bytes_per_line) == 0)) {
614 printk("%s\n", tmp);
615 k=0;
617 if ((i % bytes_per_line) == 0)
618 k += sprintf(&tmp[k], "%04x: ", i);
619 k += sprintf(&tmp[k], "%02x ", data[i]);
621 if (k > 0)
622 printk("%s\n", tmp);
625 EXPORT_SYMBOL(usbvideo_HexDump);
627 #endif
629 /* ******************************************************************** */
631 /* XXX: this piece of crap really wants some error handling.. */
632 static int usbvideo_ClientIncModCount(struct uvd *uvd)
634 if (uvd == NULL) {
635 err("%s: uvd == NULL", __func__);
636 return -EINVAL;
638 if (uvd->handle == NULL) {
639 err("%s: uvd->handle == NULL", __func__);
640 return -EINVAL;
642 if (!try_module_get(uvd->handle->md_module)) {
643 err("%s: try_module_get() == 0", __func__);
644 return -ENODEV;
646 return 0;
649 static void usbvideo_ClientDecModCount(struct uvd *uvd)
651 if (uvd == NULL) {
652 err("%s: uvd == NULL", __func__);
653 return;
655 if (uvd->handle == NULL) {
656 err("%s: uvd->handle == NULL", __func__);
657 return;
659 if (uvd->handle->md_module == NULL) {
660 err("%s: uvd->handle->md_module == NULL", __func__);
661 return;
663 module_put(uvd->handle->md_module);
666 int usbvideo_register(
667 struct usbvideo **pCams,
668 const int num_cams,
669 const int num_extra,
670 const char *driverName,
671 const struct usbvideo_cb *cbTbl,
672 struct module *md,
673 const struct usb_device_id *id_table)
675 struct usbvideo *cams;
676 int i, base_size, result;
678 /* Check parameters for sanity */
679 if ((num_cams <= 0) || (pCams == NULL) || (cbTbl == NULL)) {
680 err("%s: Illegal call", __func__);
681 return -EINVAL;
684 /* Check registration callback - must be set! */
685 if (cbTbl->probe == NULL) {
686 err("%s: probe() is required!", __func__);
687 return -EINVAL;
690 base_size = num_cams * sizeof(struct uvd) + sizeof(struct usbvideo);
691 cams = kzalloc(base_size, GFP_KERNEL);
692 if (cams == NULL) {
693 err("Failed to allocate %d. bytes for usbvideo struct", base_size);
694 return -ENOMEM;
696 dbg("%s: Allocated $%p (%d. bytes) for %d. cameras",
697 __func__, cams, base_size, num_cams);
699 /* Copy callbacks, apply defaults for those that are not set */
700 memmove(&cams->cb, cbTbl, sizeof(cams->cb));
701 if (cams->cb.getFrame == NULL)
702 cams->cb.getFrame = usbvideo_GetFrame;
703 if (cams->cb.disconnect == NULL)
704 cams->cb.disconnect = usbvideo_Disconnect;
705 if (cams->cb.startDataPump == NULL)
706 cams->cb.startDataPump = usbvideo_StartDataPump;
707 if (cams->cb.stopDataPump == NULL)
708 cams->cb.stopDataPump = usbvideo_StopDataPump;
710 cams->num_cameras = num_cams;
711 cams->cam = (struct uvd *) &cams[1];
712 cams->md_module = md;
713 mutex_init(&cams->lock); /* to 1 == available */
715 for (i = 0; i < num_cams; i++) {
716 struct uvd *up = &cams->cam[i];
718 up->handle = cams;
720 /* Allocate user_data separately because of kmalloc's limits */
721 if (num_extra > 0) {
722 up->user_size = num_cams * num_extra;
723 up->user_data = kmalloc(up->user_size, GFP_KERNEL);
724 if (up->user_data == NULL) {
725 err("%s: Failed to allocate user_data (%d. bytes)",
726 __func__, up->user_size);
727 while (i) {
728 up = &cams->cam[--i];
729 kfree(up->user_data);
731 kfree(cams);
732 return -ENOMEM;
734 dbg("%s: Allocated cams[%d].user_data=$%p (%d. bytes)",
735 __func__, i, up->user_data, up->user_size);
740 * Register ourselves with USB stack.
742 strcpy(cams->drvName, (driverName != NULL) ? driverName : "Unknown");
743 cams->usbdrv.name = cams->drvName;
744 cams->usbdrv.probe = cams->cb.probe;
745 cams->usbdrv.disconnect = cams->cb.disconnect;
746 cams->usbdrv.id_table = id_table;
749 * Update global handle to usbvideo. This is very important
750 * because probe() can be called before usb_register() returns.
751 * If the handle is not yet updated then the probe() will fail.
753 *pCams = cams;
754 result = usb_register(&cams->usbdrv);
755 if (result) {
756 for (i = 0; i < num_cams; i++) {
757 struct uvd *up = &cams->cam[i];
758 kfree(up->user_data);
760 kfree(cams);
763 return result;
766 EXPORT_SYMBOL(usbvideo_register);
769 * usbvideo_Deregister()
771 * Procedure frees all usbvideo and user data structures. Be warned that
772 * if you had some dynamically allocated components in ->user field then
773 * you should free them before calling here.
775 void usbvideo_Deregister(struct usbvideo **pCams)
777 struct usbvideo *cams;
778 int i;
780 if (pCams == NULL) {
781 err("%s: pCams == NULL", __func__);
782 return;
784 cams = *pCams;
785 if (cams == NULL) {
786 err("%s: cams == NULL", __func__);
787 return;
790 dbg("%s: Deregistering %s driver.", __func__, cams->drvName);
791 usb_deregister(&cams->usbdrv);
793 dbg("%s: Deallocating cams=$%p (%d. cameras)", __func__, cams, cams->num_cameras);
794 for (i=0; i < cams->num_cameras; i++) {
795 struct uvd *up = &cams->cam[i];
796 int warning = 0;
798 if (up->user_data != NULL) {
799 if (up->user_size <= 0)
800 ++warning;
801 } else {
802 if (up->user_size > 0)
803 ++warning;
805 if (warning) {
806 err("%s: Warning: user_data=$%p user_size=%d.",
807 __func__, up->user_data, up->user_size);
808 } else {
809 dbg("%s: Freeing %d. $%p->user_data=$%p",
810 __func__, i, up, up->user_data);
811 kfree(up->user_data);
814 /* Whole array was allocated in one chunk */
815 dbg("%s: Freed %d uvd structures",
816 __func__, cams->num_cameras);
817 kfree(cams);
818 *pCams = NULL;
821 EXPORT_SYMBOL(usbvideo_Deregister);
824 * usbvideo_Disconnect()
826 * This procedure stops all driver activity. Deallocation of
827 * the interface-private structure (pointed by 'ptr') is done now
828 * (if we don't have any open files) or later, when those files
829 * are closed. After that driver should be removable.
831 * This code handles surprise removal. The uvd->user is a counter which
832 * increments on open() and decrements on close(). If we see here that
833 * this counter is not 0 then we have a client who still has us opened.
834 * We set uvd->remove_pending flag as early as possible, and after that
835 * all access to the camera will gracefully fail. These failures should
836 * prompt client to (eventually) close the video device, and then - in
837 * usbvideo_v4l_close() - we decrement uvd->uvd_used and usage counter.
839 * History:
840 * 22-Jan-2000 Added polling of MOD_IN_USE to delay removal until all users gone.
841 * 27-Jan-2000 Reworked to allow pending disconnects; see xxx_close()
842 * 24-May-2000 Corrected to prevent race condition (MOD_xxx_USE_COUNT).
843 * 19-Oct-2000 Moved to usbvideo module.
845 static void usbvideo_Disconnect(struct usb_interface *intf)
847 struct uvd *uvd = usb_get_intfdata (intf);
848 int i;
850 if (uvd == NULL) {
851 err("%s($%p): Illegal call.", __func__, intf);
852 return;
855 usb_set_intfdata (intf, NULL);
857 usbvideo_ClientIncModCount(uvd);
858 if (uvd->debug > 0)
859 dev_info(&intf->dev, "%s(%p.)\n", __func__, intf);
861 mutex_lock(&uvd->lock);
862 uvd->remove_pending = 1; /* Now all ISO data will be ignored */
864 /* At this time we ask to cancel outstanding URBs */
865 GET_CALLBACK(uvd, stopDataPump)(uvd);
867 for (i=0; i < USBVIDEO_NUMSBUF; i++)
868 usb_free_urb(uvd->sbuf[i].urb);
870 usb_put_dev(uvd->dev);
871 uvd->dev = NULL; /* USB device is no more */
873 video_unregister_device(&uvd->vdev);
874 if (uvd->debug > 0)
875 dev_info(&intf->dev, "%s: Video unregistered.\n", __func__);
877 if (uvd->user)
878 dev_info(&intf->dev, "%s: In use, disconnect pending.\n",
879 __func__);
880 else
881 usbvideo_CameraRelease(uvd);
882 mutex_unlock(&uvd->lock);
883 dev_info(&intf->dev, "USB camera disconnected.\n");
885 usbvideo_ClientDecModCount(uvd);
889 * usbvideo_CameraRelease()
891 * This code does final release of uvd. This happens
892 * after the device is disconnected -and- all clients
893 * closed their files.
895 * History:
896 * 27-Jan-2000 Created.
898 static void usbvideo_CameraRelease(struct uvd *uvd)
900 if (uvd == NULL) {
901 err("%s: Illegal call", __func__);
902 return;
905 RingQueue_Free(&uvd->dp);
906 if (VALID_CALLBACK(uvd, userFree))
907 GET_CALLBACK(uvd, userFree)(uvd);
908 uvd->uvd_used = 0; /* This is atomic, no need to take mutex */
912 * usbvideo_find_struct()
914 * This code searches the array of preallocated (static) structures
915 * and returns index of the first one that isn't in use. Returns -1
916 * if there are no free structures.
918 * History:
919 * 27-Jan-2000 Created.
921 static int usbvideo_find_struct(struct usbvideo *cams)
923 int u, rv = -1;
925 if (cams == NULL) {
926 err("No usbvideo handle?");
927 return -1;
929 mutex_lock(&cams->lock);
930 for (u = 0; u < cams->num_cameras; u++) {
931 struct uvd *uvd = &cams->cam[u];
932 if (!uvd->uvd_used) /* This one is free */
934 uvd->uvd_used = 1; /* In use now */
935 mutex_init(&uvd->lock); /* to 1 == available */
936 uvd->dev = NULL;
937 rv = u;
938 break;
941 mutex_unlock(&cams->lock);
942 return rv;
945 static const struct v4l2_file_operations usbvideo_fops = {
946 .owner = THIS_MODULE,
947 .open = usbvideo_v4l_open,
948 .release =usbvideo_v4l_close,
949 .read = usbvideo_v4l_read,
950 .mmap = usbvideo_v4l_mmap,
951 .ioctl = usbvideo_v4l_ioctl,
953 static const struct video_device usbvideo_template = {
954 .fops = &usbvideo_fops,
957 struct uvd *usbvideo_AllocateDevice(struct usbvideo *cams)
959 int i, devnum;
960 struct uvd *uvd = NULL;
962 if (cams == NULL) {
963 err("No usbvideo handle?");
964 return NULL;
967 devnum = usbvideo_find_struct(cams);
968 if (devnum == -1) {
969 err("IBM USB camera driver: Too many devices!");
970 return NULL;
972 uvd = &cams->cam[devnum];
973 dbg("Device entry #%d. at $%p", devnum, uvd);
975 /* Not relying upon caller we increase module counter ourselves */
976 usbvideo_ClientIncModCount(uvd);
978 mutex_lock(&uvd->lock);
979 for (i=0; i < USBVIDEO_NUMSBUF; i++) {
980 uvd->sbuf[i].urb = usb_alloc_urb(FRAMES_PER_DESC, GFP_KERNEL);
981 if (uvd->sbuf[i].urb == NULL) {
982 err("usb_alloc_urb(%d.) failed.", FRAMES_PER_DESC);
983 uvd->uvd_used = 0;
984 uvd = NULL;
985 goto allocate_done;
988 uvd->user=0;
989 uvd->remove_pending = 0;
990 uvd->last_error = 0;
991 RingQueue_Initialize(&uvd->dp);
993 /* Initialize video device structure */
994 uvd->vdev = usbvideo_template;
995 sprintf(uvd->vdev.name, "%.20s USB Camera", cams->drvName);
997 * The client is free to overwrite those because we
998 * return control to the client's probe function right now.
1000 allocate_done:
1001 mutex_unlock(&uvd->lock);
1002 usbvideo_ClientDecModCount(uvd);
1003 return uvd;
1006 EXPORT_SYMBOL(usbvideo_AllocateDevice);
1008 int usbvideo_RegisterVideoDevice(struct uvd *uvd)
1010 char tmp1[20], tmp2[20]; /* Buffers for printing */
1012 if (uvd == NULL) {
1013 err("%s: Illegal call.", __func__);
1014 return -EINVAL;
1016 if (uvd->video_endp == 0) {
1017 dev_info(&uvd->dev->dev,
1018 "%s: No video endpoint specified; data pump disabled.\n",
1019 __func__);
1021 if (uvd->paletteBits == 0) {
1022 err("%s: No palettes specified!", __func__);
1023 return -EINVAL;
1025 if (uvd->defaultPalette == 0) {
1026 dev_info(&uvd->dev->dev, "%s: No default palette!\n",
1027 __func__);
1030 uvd->max_frame_size = VIDEOSIZE_X(uvd->canvas) *
1031 VIDEOSIZE_Y(uvd->canvas) * V4L_BYTES_PER_PIXEL;
1032 usbvideo_VideosizeToString(tmp1, sizeof(tmp1), uvd->videosize);
1033 usbvideo_VideosizeToString(tmp2, sizeof(tmp2), uvd->canvas);
1035 if (uvd->debug > 0) {
1036 dev_info(&uvd->dev->dev,
1037 "%s: iface=%d. endpoint=$%02x paletteBits=$%08lx\n",
1038 __func__, uvd->iface, uvd->video_endp,
1039 uvd->paletteBits);
1041 if (uvd->dev == NULL) {
1042 err("%s: uvd->dev == NULL", __func__);
1043 return -EINVAL;
1045 uvd->vdev.parent = &uvd->dev->dev;
1046 uvd->vdev.release = video_device_release_empty;
1047 if (video_register_device(&uvd->vdev, VFL_TYPE_GRABBER, video_nr) < 0) {
1048 err("%s: video_register_device failed", __func__);
1049 return -EPIPE;
1051 if (uvd->debug > 1) {
1052 dev_info(&uvd->dev->dev,
1053 "%s: video_register_device() successful\n", __func__);
1056 dev_info(&uvd->dev->dev, "%s on /dev/video%d: canvas=%s videosize=%s\n",
1057 (uvd->handle != NULL) ? uvd->handle->drvName : "???",
1058 uvd->vdev.num, tmp2, tmp1);
1060 usb_get_dev(uvd->dev);
1061 return 0;
1064 EXPORT_SYMBOL(usbvideo_RegisterVideoDevice);
1066 /* ******************************************************************** */
1068 static int usbvideo_v4l_mmap(struct file *file, struct vm_area_struct *vma)
1070 struct uvd *uvd = file->private_data;
1071 unsigned long start = vma->vm_start;
1072 unsigned long size = vma->vm_end-vma->vm_start;
1073 unsigned long page, pos;
1075 if (!CAMERA_IS_OPERATIONAL(uvd))
1076 return -EFAULT;
1078 if (size > (((USBVIDEO_NUMFRAMES * uvd->max_frame_size) + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1)))
1079 return -EINVAL;
1081 pos = (unsigned long) uvd->fbuf;
1082 while (size > 0) {
1083 page = vmalloc_to_pfn((void *)pos);
1084 if (remap_pfn_range(vma, start, page, PAGE_SIZE, PAGE_SHARED))
1085 return -EAGAIN;
1087 start += PAGE_SIZE;
1088 pos += PAGE_SIZE;
1089 if (size > PAGE_SIZE)
1090 size -= PAGE_SIZE;
1091 else
1092 size = 0;
1095 return 0;
1099 * usbvideo_v4l_open()
1101 * This is part of Video 4 Linux API. The driver can be opened by one
1102 * client only (checks internal counter 'uvdser'). The procedure
1103 * then allocates buffers needed for video processing.
1105 * History:
1106 * 22-Jan-2000 Rewrote, moved scratch buffer allocation here. Now the
1107 * camera is also initialized here (once per connect), at
1108 * expense of V4L client (it waits on open() call).
1109 * 27-Jan-2000 Used USBVIDEO_NUMSBUF as number of URB buffers.
1110 * 24-May-2000 Corrected to prevent race condition (MOD_xxx_USE_COUNT).
1112 static int usbvideo_v4l_open(struct file *file)
1114 struct video_device *dev = video_devdata(file);
1115 struct uvd *uvd = (struct uvd *) dev;
1116 const int sb_size = FRAMES_PER_DESC * uvd->iso_packet_len;
1117 int i, errCode = 0;
1119 if (uvd->debug > 1)
1120 dev_info(&uvd->dev->dev, "%s($%p)\n", __func__, dev);
1122 if (usbvideo_ClientIncModCount(uvd) < 0)
1123 return -ENODEV;
1124 mutex_lock(&uvd->lock);
1126 if (uvd->user) {
1127 err("%s: Someone tried to open an already opened device!", __func__);
1128 errCode = -EBUSY;
1129 } else {
1130 /* Clear statistics */
1131 memset(&uvd->stats, 0, sizeof(uvd->stats));
1133 /* Clean pointers so we know if we allocated something */
1134 for (i=0; i < USBVIDEO_NUMSBUF; i++)
1135 uvd->sbuf[i].data = NULL;
1137 /* Allocate memory for the frame buffers */
1138 uvd->fbuf_size = USBVIDEO_NUMFRAMES * uvd->max_frame_size;
1139 uvd->fbuf = usbvideo_rvmalloc(uvd->fbuf_size);
1140 RingQueue_Allocate(&uvd->dp, RING_QUEUE_SIZE);
1141 if ((uvd->fbuf == NULL) ||
1142 (!RingQueue_IsAllocated(&uvd->dp))) {
1143 err("%s: Failed to allocate fbuf or dp", __func__);
1144 errCode = -ENOMEM;
1145 } else {
1146 /* Allocate all buffers */
1147 for (i=0; i < USBVIDEO_NUMFRAMES; i++) {
1148 uvd->frame[i].frameState = FrameState_Unused;
1149 uvd->frame[i].data = uvd->fbuf + i*(uvd->max_frame_size);
1151 * Set default sizes in case IOCTL (VIDIOCMCAPTURE)
1152 * is not used (using read() instead).
1154 uvd->frame[i].canvas = uvd->canvas;
1155 uvd->frame[i].seqRead_Index = 0;
1157 for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1158 uvd->sbuf[i].data = kmalloc(sb_size, GFP_KERNEL);
1159 if (uvd->sbuf[i].data == NULL) {
1160 errCode = -ENOMEM;
1161 break;
1165 if (errCode != 0) {
1166 /* Have to free all that memory */
1167 if (uvd->fbuf != NULL) {
1168 usbvideo_rvfree(uvd->fbuf, uvd->fbuf_size);
1169 uvd->fbuf = NULL;
1171 RingQueue_Free(&uvd->dp);
1172 for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1173 kfree(uvd->sbuf[i].data);
1174 uvd->sbuf[i].data = NULL;
1179 /* If so far no errors then we shall start the camera */
1180 if (errCode == 0) {
1181 /* Start data pump if we have valid endpoint */
1182 if (uvd->video_endp != 0)
1183 errCode = GET_CALLBACK(uvd, startDataPump)(uvd);
1184 if (errCode == 0) {
1185 if (VALID_CALLBACK(uvd, setupOnOpen)) {
1186 if (uvd->debug > 1)
1187 dev_info(&uvd->dev->dev,
1188 "%s: setupOnOpen callback\n",
1189 __func__);
1190 errCode = GET_CALLBACK(uvd, setupOnOpen)(uvd);
1191 if (errCode < 0) {
1192 err("%s: setupOnOpen callback failed (%d.).",
1193 __func__, errCode);
1194 } else if (uvd->debug > 1) {
1195 dev_info(&uvd->dev->dev,
1196 "%s: setupOnOpen callback successful\n",
1197 __func__);
1200 if (errCode == 0) {
1201 uvd->settingsAdjusted = 0;
1202 if (uvd->debug > 1)
1203 dev_info(&uvd->dev->dev,
1204 "%s: Open succeeded.\n",
1205 __func__);
1206 uvd->user++;
1207 file->private_data = uvd;
1211 mutex_unlock(&uvd->lock);
1212 if (errCode != 0)
1213 usbvideo_ClientDecModCount(uvd);
1214 if (uvd->debug > 0)
1215 dev_info(&uvd->dev->dev, "%s: Returning %d.\n", __func__,
1216 errCode);
1217 return errCode;
1221 * usbvideo_v4l_close()
1223 * This is part of Video 4 Linux API. The procedure
1224 * stops streaming and deallocates all buffers that were earlier
1225 * allocated in usbvideo_v4l_open().
1227 * History:
1228 * 22-Jan-2000 Moved scratch buffer deallocation here.
1229 * 27-Jan-2000 Used USBVIDEO_NUMSBUF as number of URB buffers.
1230 * 24-May-2000 Moved MOD_DEC_USE_COUNT outside of code that can sleep.
1232 static int usbvideo_v4l_close(struct file *file)
1234 struct video_device *dev = file->private_data;
1235 struct uvd *uvd = (struct uvd *) dev;
1236 int i;
1238 if (uvd->debug > 1)
1239 dev_info(&uvd->dev->dev, "%s($%p)\n", __func__, dev);
1241 mutex_lock(&uvd->lock);
1242 GET_CALLBACK(uvd, stopDataPump)(uvd);
1243 usbvideo_rvfree(uvd->fbuf, uvd->fbuf_size);
1244 uvd->fbuf = NULL;
1245 RingQueue_Free(&uvd->dp);
1247 for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1248 kfree(uvd->sbuf[i].data);
1249 uvd->sbuf[i].data = NULL;
1252 #if USBVIDEO_REPORT_STATS
1253 usbvideo_ReportStatistics(uvd);
1254 #endif
1256 uvd->user--;
1257 if (uvd->remove_pending) {
1258 if (uvd->debug > 0)
1259 dev_info(&uvd->dev->dev, "%s: Final disconnect.\n",
1260 __func__);
1261 usbvideo_CameraRelease(uvd);
1263 mutex_unlock(&uvd->lock);
1264 usbvideo_ClientDecModCount(uvd);
1266 if (uvd->debug > 1)
1267 dev_info(&uvd->dev->dev, "%s: Completed.\n", __func__);
1268 file->private_data = NULL;
1269 return 0;
1273 * usbvideo_v4l_ioctl()
1275 * This is part of Video 4 Linux API. The procedure handles ioctl() calls.
1277 * History:
1278 * 22-Jan-2000 Corrected VIDIOCSPICT to reject unsupported settings.
1280 static long usbvideo_v4l_do_ioctl(struct file *file, unsigned int cmd, void *arg)
1282 struct uvd *uvd = file->private_data;
1284 if (!CAMERA_IS_OPERATIONAL(uvd))
1285 return -EIO;
1287 switch (cmd) {
1288 case VIDIOCGCAP:
1290 struct video_capability *b = arg;
1291 *b = uvd->vcap;
1292 return 0;
1294 case VIDIOCGCHAN:
1296 struct video_channel *v = arg;
1297 *v = uvd->vchan;
1298 return 0;
1300 case VIDIOCSCHAN:
1302 struct video_channel *v = arg;
1303 if (v->channel != 0)
1304 return -EINVAL;
1305 return 0;
1307 case VIDIOCGPICT:
1309 struct video_picture *pic = arg;
1310 *pic = uvd->vpic;
1311 return 0;
1313 case VIDIOCSPICT:
1315 struct video_picture *pic = arg;
1317 * Use temporary 'video_picture' structure to preserve our
1318 * own settings (such as color depth, palette) that we
1319 * aren't allowing everyone (V4L client) to change.
1321 uvd->vpic.brightness = pic->brightness;
1322 uvd->vpic.hue = pic->hue;
1323 uvd->vpic.colour = pic->colour;
1324 uvd->vpic.contrast = pic->contrast;
1325 uvd->settingsAdjusted = 0; /* Will force new settings */
1326 return 0;
1328 case VIDIOCSWIN:
1330 struct video_window *vw = arg;
1332 if(VALID_CALLBACK(uvd, setVideoMode)) {
1333 return GET_CALLBACK(uvd, setVideoMode)(uvd, vw);
1336 if (vw->flags)
1337 return -EINVAL;
1338 if (vw->clipcount)
1339 return -EINVAL;
1340 if (vw->width != VIDEOSIZE_X(uvd->canvas))
1341 return -EINVAL;
1342 if (vw->height != VIDEOSIZE_Y(uvd->canvas))
1343 return -EINVAL;
1345 return 0;
1347 case VIDIOCGWIN:
1349 struct video_window *vw = arg;
1351 vw->x = 0;
1352 vw->y = 0;
1353 vw->width = VIDEOSIZE_X(uvd->videosize);
1354 vw->height = VIDEOSIZE_Y(uvd->videosize);
1355 vw->chromakey = 0;
1356 if (VALID_CALLBACK(uvd, getFPS))
1357 vw->flags = GET_CALLBACK(uvd, getFPS)(uvd);
1358 else
1359 vw->flags = 10; /* FIXME: do better! */
1360 return 0;
1362 case VIDIOCGMBUF:
1364 struct video_mbuf *vm = arg;
1365 int i;
1367 memset(vm, 0, sizeof(*vm));
1368 vm->size = uvd->max_frame_size * USBVIDEO_NUMFRAMES;
1369 vm->frames = USBVIDEO_NUMFRAMES;
1370 for(i = 0; i < USBVIDEO_NUMFRAMES; i++)
1371 vm->offsets[i] = i * uvd->max_frame_size;
1373 return 0;
1375 case VIDIOCMCAPTURE:
1377 struct video_mmap *vm = arg;
1379 if (uvd->debug >= 1) {
1380 dev_info(&uvd->dev->dev,
1381 "VIDIOCMCAPTURE: frame=%d. size=%dx%d, format=%d.\n",
1382 vm->frame, vm->width, vm->height, vm->format);
1385 * Check if the requested size is supported. If the requestor
1386 * requests too big a frame then we may be tricked into accessing
1387 * outside of own preallocated frame buffer (in uvd->frame).
1388 * This will cause oops or a security hole. Theoretically, we
1389 * could only clamp the size down to acceptable bounds, but then
1390 * we'd need to figure out how to insert our smaller buffer into
1391 * larger caller's buffer... this is not an easy question. So we
1392 * here just flatly reject too large requests, assuming that the
1393 * caller will resubmit with smaller size. Callers should know
1394 * what size we support (returned by VIDIOCGCAP). However vidcat,
1395 * for one, does not care and allows to ask for any size.
1397 if ((vm->width > VIDEOSIZE_X(uvd->canvas)) ||
1398 (vm->height > VIDEOSIZE_Y(uvd->canvas))) {
1399 if (uvd->debug > 0) {
1400 dev_info(&uvd->dev->dev,
1401 "VIDIOCMCAPTURE: Size=%dx%d "
1402 "too large; allowed only up "
1403 "to %ldx%ld\n", vm->width,
1404 vm->height,
1405 VIDEOSIZE_X(uvd->canvas),
1406 VIDEOSIZE_Y(uvd->canvas));
1408 return -EINVAL;
1410 /* Check if the palette is supported */
1411 if (((1L << vm->format) & uvd->paletteBits) == 0) {
1412 if (uvd->debug > 0) {
1413 dev_info(&uvd->dev->dev,
1414 "VIDIOCMCAPTURE: format=%d. "
1415 "not supported "
1416 "(paletteBits=$%08lx)\n",
1417 vm->format, uvd->paletteBits);
1419 return -EINVAL;
1421 if ((vm->frame < 0) || (vm->frame >= USBVIDEO_NUMFRAMES)) {
1422 err("VIDIOCMCAPTURE: vm.frame=%d. !E [0-%d]", vm->frame, USBVIDEO_NUMFRAMES-1);
1423 return -EINVAL;
1425 if (uvd->frame[vm->frame].frameState == FrameState_Grabbing) {
1426 /* Not an error - can happen */
1428 uvd->frame[vm->frame].request = VIDEOSIZE(vm->width, vm->height);
1429 uvd->frame[vm->frame].palette = vm->format;
1431 /* Mark it as ready */
1432 uvd->frame[vm->frame].frameState = FrameState_Ready;
1434 return usbvideo_NewFrame(uvd, vm->frame);
1436 case VIDIOCSYNC:
1438 int *frameNum = arg;
1439 int ret;
1441 if (*frameNum < 0 || *frameNum >= USBVIDEO_NUMFRAMES)
1442 return -EINVAL;
1444 if (uvd->debug >= 1)
1445 dev_info(&uvd->dev->dev,
1446 "VIDIOCSYNC: syncing to frame %d.\n",
1447 *frameNum);
1448 if (uvd->flags & FLAGS_NO_DECODING)
1449 ret = usbvideo_GetFrame(uvd, *frameNum);
1450 else if (VALID_CALLBACK(uvd, getFrame)) {
1451 ret = GET_CALLBACK(uvd, getFrame)(uvd, *frameNum);
1452 if ((ret < 0) && (uvd->debug >= 1)) {
1453 err("VIDIOCSYNC: getFrame() returned %d.", ret);
1455 } else {
1456 err("VIDIOCSYNC: getFrame is not set");
1457 ret = -EFAULT;
1461 * The frame is in FrameState_Done_Hold state. Release it
1462 * right now because its data is already mapped into
1463 * the user space and it's up to the application to
1464 * make use of it until it asks for another frame.
1466 uvd->frame[*frameNum].frameState = FrameState_Unused;
1467 return ret;
1469 case VIDIOCGFBUF:
1471 struct video_buffer *vb = arg;
1473 memset(vb, 0, sizeof(*vb));
1474 return 0;
1476 case VIDIOCKEY:
1477 return 0;
1479 case VIDIOCCAPTURE:
1480 return -EINVAL;
1482 case VIDIOCSFBUF:
1484 case VIDIOCGTUNER:
1485 case VIDIOCSTUNER:
1487 case VIDIOCGFREQ:
1488 case VIDIOCSFREQ:
1490 case VIDIOCGAUDIO:
1491 case VIDIOCSAUDIO:
1492 return -EINVAL;
1494 default:
1495 return -ENOIOCTLCMD;
1497 return 0;
1500 static long usbvideo_v4l_ioctl(struct file *file,
1501 unsigned int cmd, unsigned long arg)
1503 return video_usercopy(file, cmd, arg, usbvideo_v4l_do_ioctl);
1507 * usbvideo_v4l_read()
1509 * This is mostly boring stuff. We simply ask for a frame and when it
1510 * arrives copy all the video data from it into user space. There is
1511 * no obvious need to override this method.
1513 * History:
1514 * 20-Oct-2000 Created.
1515 * 01-Nov-2000 Added mutex (uvd->lock).
1517 static ssize_t usbvideo_v4l_read(struct file *file, char __user *buf,
1518 size_t count, loff_t *ppos)
1520 struct uvd *uvd = file->private_data;
1521 int noblock = file->f_flags & O_NONBLOCK;
1522 int frmx = -1, i;
1523 struct usbvideo_frame *frame;
1525 if (!CAMERA_IS_OPERATIONAL(uvd) || (buf == NULL))
1526 return -EFAULT;
1528 if (uvd->debug >= 1)
1529 dev_info(&uvd->dev->dev,
1530 "%s: %Zd. bytes, noblock=%d.\n",
1531 __func__, count, noblock);
1533 mutex_lock(&uvd->lock);
1535 /* See if a frame is completed, then use it. */
1536 for(i = 0; i < USBVIDEO_NUMFRAMES; i++) {
1537 if ((uvd->frame[i].frameState == FrameState_Done) ||
1538 (uvd->frame[i].frameState == FrameState_Done_Hold) ||
1539 (uvd->frame[i].frameState == FrameState_Error)) {
1540 frmx = i;
1541 break;
1545 /* FIXME: If we don't start a frame here then who ever does? */
1546 if (noblock && (frmx == -1)) {
1547 count = -EAGAIN;
1548 goto read_done;
1552 * If no FrameState_Done, look for a FrameState_Grabbing state.
1553 * See if a frame is in process (grabbing), then use it.
1554 * We will need to wait until it becomes cooked, of course.
1556 if (frmx == -1) {
1557 for(i = 0; i < USBVIDEO_NUMFRAMES; i++) {
1558 if (uvd->frame[i].frameState == FrameState_Grabbing) {
1559 frmx = i;
1560 break;
1566 * If no frame is active, start one. We don't care which one
1567 * it will be, so #0 is as good as any.
1568 * In read access mode we don't have convenience of VIDIOCMCAPTURE
1569 * to specify the requested palette (video format) on per-frame
1570 * basis. This means that we have to return data in -some- format
1571 * and just hope that the client knows what to do with it.
1572 * The default format is configured in uvd->defaultPalette field
1573 * as one of VIDEO_PALETTE_xxx values. We stuff it into the new
1574 * frame and initiate the frame filling process.
1576 if (frmx == -1) {
1577 if (uvd->defaultPalette == 0) {
1578 err("%s: No default palette; don't know what to do!", __func__);
1579 count = -EFAULT;
1580 goto read_done;
1582 frmx = 0;
1584 * We have no per-frame control over video size.
1585 * Therefore we only can use whatever size was
1586 * specified as default.
1588 uvd->frame[frmx].request = uvd->videosize;
1589 uvd->frame[frmx].palette = uvd->defaultPalette;
1590 uvd->frame[frmx].frameState = FrameState_Ready;
1591 usbvideo_NewFrame(uvd, frmx);
1592 /* Now frame 0 is supposed to start filling... */
1596 * Get a pointer to the active frame. It is either previously
1597 * completed frame or frame in progress but not completed yet.
1599 frame = &uvd->frame[frmx];
1602 * Sit back & wait until the frame gets filled and postprocessed.
1603 * If we fail to get the picture [in time] then return the error.
1604 * In this call we specify that we want the frame to be waited for,
1605 * postprocessed and switched into FrameState_Done_Hold state. This
1606 * state is used to hold the frame as "fully completed" between
1607 * subsequent partial reads of the same frame.
1609 if (frame->frameState != FrameState_Done_Hold) {
1610 long rv = -EFAULT;
1611 if (uvd->flags & FLAGS_NO_DECODING)
1612 rv = usbvideo_GetFrame(uvd, frmx);
1613 else if (VALID_CALLBACK(uvd, getFrame))
1614 rv = GET_CALLBACK(uvd, getFrame)(uvd, frmx);
1615 else
1616 err("getFrame is not set");
1617 if ((rv != 0) || (frame->frameState != FrameState_Done_Hold)) {
1618 count = rv;
1619 goto read_done;
1624 * Copy bytes to user space. We allow for partial reads, which
1625 * means that the user application can request read less than
1626 * the full frame size. It is up to the application to issue
1627 * subsequent calls until entire frame is read.
1629 * First things first, make sure we don't copy more than we
1630 * have - even if the application wants more. That would be
1631 * a big security embarassment!
1633 if ((count + frame->seqRead_Index) > frame->seqRead_Length)
1634 count = frame->seqRead_Length - frame->seqRead_Index;
1637 * Copy requested amount of data to user space. We start
1638 * copying from the position where we last left it, which
1639 * will be zero for a new frame (not read before).
1641 if (copy_to_user(buf, frame->data + frame->seqRead_Index, count)) {
1642 count = -EFAULT;
1643 goto read_done;
1646 /* Update last read position */
1647 frame->seqRead_Index += count;
1648 if (uvd->debug >= 1) {
1649 err("%s: {copy} count used=%Zd, new seqRead_Index=%ld",
1650 __func__, count, frame->seqRead_Index);
1653 /* Finally check if the frame is done with and "release" it */
1654 if (frame->seqRead_Index >= frame->seqRead_Length) {
1655 /* All data has been read */
1656 frame->seqRead_Index = 0;
1658 /* Mark it as available to be used again. */
1659 uvd->frame[frmx].frameState = FrameState_Unused;
1660 if (usbvideo_NewFrame(uvd, (frmx + 1) % USBVIDEO_NUMFRAMES)) {
1661 err("%s: usbvideo_NewFrame failed.", __func__);
1664 read_done:
1665 mutex_unlock(&uvd->lock);
1666 return count;
1670 * Make all of the blocks of data contiguous
1672 static int usbvideo_CompressIsochronous(struct uvd *uvd, struct urb *urb)
1674 char *cdata;
1675 int i, totlen = 0;
1677 for (i = 0; i < urb->number_of_packets; i++) {
1678 int n = urb->iso_frame_desc[i].actual_length;
1679 int st = urb->iso_frame_desc[i].status;
1681 cdata = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
1683 /* Detect and ignore errored packets */
1684 if (st < 0) {
1685 if (uvd->debug >= 1)
1686 err("Data error: packet=%d. len=%d. status=%d.", i, n, st);
1687 uvd->stats.iso_err_count++;
1688 continue;
1691 /* Detect and ignore empty packets */
1692 if (n <= 0) {
1693 uvd->stats.iso_skip_count++;
1694 continue;
1696 totlen += n; /* Little local accounting */
1697 RingQueue_Enqueue(&uvd->dp, cdata, n);
1699 return totlen;
1702 static void usbvideo_IsocIrq(struct urb *urb)
1704 int i, ret, len;
1705 struct uvd *uvd = urb->context;
1707 /* We don't want to do anything if we are about to be removed! */
1708 if (!CAMERA_IS_OPERATIONAL(uvd))
1709 return;
1710 #if 0
1711 if (urb->actual_length > 0) {
1712 dev_info(&uvd->dev->dev,
1713 "urb=$%p status=%d. errcount=%d. length=%d.\n",
1714 urb, urb->status, urb->error_count,
1715 urb->actual_length);
1716 } else {
1717 static int c = 0;
1718 if (c++ % 100 == 0)
1719 dev_info(&uvd->dev->dev, "No Isoc data\n");
1721 #endif
1723 if (!uvd->streaming) {
1724 if (uvd->debug >= 1)
1725 dev_info(&uvd->dev->dev,
1726 "Not streaming, but interrupt!\n");
1727 return;
1730 uvd->stats.urb_count++;
1731 if (urb->actual_length <= 0)
1732 goto urb_done_with;
1734 /* Copy the data received into ring queue */
1735 len = usbvideo_CompressIsochronous(uvd, urb);
1736 uvd->stats.urb_length = len;
1737 if (len <= 0)
1738 goto urb_done_with;
1740 /* Here we got some data */
1741 uvd->stats.data_count += len;
1742 RingQueue_WakeUpInterruptible(&uvd->dp);
1744 urb_done_with:
1745 for (i = 0; i < FRAMES_PER_DESC; i++) {
1746 urb->iso_frame_desc[i].status = 0;
1747 urb->iso_frame_desc[i].actual_length = 0;
1749 urb->status = 0;
1750 urb->dev = uvd->dev;
1751 ret = usb_submit_urb (urb, GFP_KERNEL);
1752 if(ret)
1753 err("usb_submit_urb error (%d)", ret);
1754 return;
1758 * usbvideo_StartDataPump()
1760 * History:
1761 * 27-Jan-2000 Used ibmcam->iface, ibmcam->ifaceAltActive instead
1762 * of hardcoded values. Simplified by using for loop,
1763 * allowed any number of URBs.
1765 static int usbvideo_StartDataPump(struct uvd *uvd)
1767 struct usb_device *dev = uvd->dev;
1768 int i, errFlag;
1770 if (uvd->debug > 1)
1771 dev_info(&uvd->dev->dev, "%s($%p)\n", __func__, uvd);
1773 if (!CAMERA_IS_OPERATIONAL(uvd)) {
1774 err("%s: Camera is not operational", __func__);
1775 return -EFAULT;
1777 uvd->curframe = -1;
1779 /* Alternate interface 1 is is the biggest frame size */
1780 i = usb_set_interface(dev, uvd->iface, uvd->ifaceAltActive);
1781 if (i < 0) {
1782 err("%s: usb_set_interface error", __func__);
1783 uvd->last_error = i;
1784 return -EBUSY;
1786 if (VALID_CALLBACK(uvd, videoStart))
1787 GET_CALLBACK(uvd, videoStart)(uvd);
1788 else
1789 err("%s: videoStart not set", __func__);
1791 /* We double buffer the Iso lists */
1792 for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1793 int j, k;
1794 struct urb *urb = uvd->sbuf[i].urb;
1795 urb->dev = dev;
1796 urb->context = uvd;
1797 urb->pipe = usb_rcvisocpipe(dev, uvd->video_endp);
1798 urb->interval = 1;
1799 urb->transfer_flags = URB_ISO_ASAP;
1800 urb->transfer_buffer = uvd->sbuf[i].data;
1801 urb->complete = usbvideo_IsocIrq;
1802 urb->number_of_packets = FRAMES_PER_DESC;
1803 urb->transfer_buffer_length = uvd->iso_packet_len * FRAMES_PER_DESC;
1804 for (j=k=0; j < FRAMES_PER_DESC; j++, k += uvd->iso_packet_len) {
1805 urb->iso_frame_desc[j].offset = k;
1806 urb->iso_frame_desc[j].length = uvd->iso_packet_len;
1810 /* Submit all URBs */
1811 for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1812 errFlag = usb_submit_urb(uvd->sbuf[i].urb, GFP_KERNEL);
1813 if (errFlag)
1814 err("%s: usb_submit_isoc(%d) ret %d", __func__, i, errFlag);
1817 uvd->streaming = 1;
1818 if (uvd->debug > 1)
1819 dev_info(&uvd->dev->dev,
1820 "%s: streaming=1 video_endp=$%02x\n", __func__,
1821 uvd->video_endp);
1822 return 0;
1826 * usbvideo_StopDataPump()
1828 * This procedure stops streaming and deallocates URBs. Then it
1829 * activates zero-bandwidth alt. setting of the video interface.
1831 * History:
1832 * 22-Jan-2000 Corrected order of actions to work after surprise removal.
1833 * 27-Jan-2000 Used uvd->iface, uvd->ifaceAltInactive instead of hardcoded values.
1835 static void usbvideo_StopDataPump(struct uvd *uvd)
1837 int i, j;
1839 if ((uvd == NULL) || (!uvd->streaming) || (uvd->dev == NULL))
1840 return;
1842 if (uvd->debug > 1)
1843 dev_info(&uvd->dev->dev, "%s($%p)\n", __func__, uvd);
1845 /* Unschedule all of the iso td's */
1846 for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1847 usb_kill_urb(uvd->sbuf[i].urb);
1849 if (uvd->debug > 1)
1850 dev_info(&uvd->dev->dev, "%s: streaming=0\n", __func__);
1851 uvd->streaming = 0;
1853 if (!uvd->remove_pending) {
1854 /* Invoke minidriver's magic to stop the camera */
1855 if (VALID_CALLBACK(uvd, videoStop))
1856 GET_CALLBACK(uvd, videoStop)(uvd);
1857 else
1858 err("%s: videoStop not set", __func__);
1860 /* Set packet size to 0 */
1861 j = usb_set_interface(uvd->dev, uvd->iface, uvd->ifaceAltInactive);
1862 if (j < 0) {
1863 err("%s: usb_set_interface() error %d.", __func__, j);
1864 uvd->last_error = j;
1870 * usbvideo_NewFrame()
1872 * History:
1873 * 29-Mar-00 Added copying of previous frame into the current one.
1874 * 6-Aug-00 Added model 3 video sizes, removed redundant width, height.
1876 static int usbvideo_NewFrame(struct uvd *uvd, int framenum)
1878 struct usbvideo_frame *frame;
1879 int n;
1881 if (uvd->debug > 1)
1882 dev_info(&uvd->dev->dev, "usbvideo_NewFrame($%p,%d.)\n", uvd,
1883 framenum);
1885 /* If we're not grabbing a frame right now and the other frame is */
1886 /* ready to be grabbed into, then use it instead */
1887 if (uvd->curframe != -1)
1888 return 0;
1890 /* If necessary we adjust picture settings between frames */
1891 if (!uvd->settingsAdjusted) {
1892 if (VALID_CALLBACK(uvd, adjustPicture))
1893 GET_CALLBACK(uvd, adjustPicture)(uvd);
1894 uvd->settingsAdjusted = 1;
1897 n = (framenum + 1) % USBVIDEO_NUMFRAMES;
1898 if (uvd->frame[n].frameState == FrameState_Ready)
1899 framenum = n;
1901 frame = &uvd->frame[framenum];
1903 frame->frameState = FrameState_Grabbing;
1904 frame->scanstate = ScanState_Scanning;
1905 frame->seqRead_Length = 0; /* Accumulated in xxx_parse_data() */
1906 frame->deinterlace = Deinterlace_None;
1907 frame->flags = 0; /* No flags yet, up to minidriver (or us) to set them */
1908 uvd->curframe = framenum;
1911 * Normally we would want to copy previous frame into the current one
1912 * before we even start filling it with data; this allows us to stop
1913 * filling at any moment; top portion of the frame will be new and
1914 * bottom portion will stay as it was in previous frame. If we don't
1915 * do that then missing chunks of video stream will result in flickering
1916 * portions of old data whatever it was before.
1918 * If we choose not to copy previous frame (to, for example, save few
1919 * bus cycles - the frame can be pretty large!) then we have an option
1920 * to clear the frame before using. If we experience losses in this
1921 * mode then missing picture will be black (no flickering).
1923 * Finally, if user chooses not to clean the current frame before
1924 * filling it with data then the old data will be visible if we fail
1925 * to refill entire frame with new data.
1927 if (!(uvd->flags & FLAGS_SEPARATE_FRAMES)) {
1928 /* This copies previous frame into this one to mask losses */
1929 int prev = (framenum - 1 + USBVIDEO_NUMFRAMES) % USBVIDEO_NUMFRAMES;
1930 memmove(frame->data, uvd->frame[prev].data, uvd->max_frame_size);
1931 } else {
1932 if (uvd->flags & FLAGS_CLEAN_FRAMES) {
1933 /* This provides a "clean" frame but slows things down */
1934 memset(frame->data, 0, uvd->max_frame_size);
1937 return 0;
1941 * usbvideo_CollectRawData()
1943 * This procedure can be used instead of 'processData' callback if you
1944 * only want to dump the raw data from the camera into the output
1945 * device (frame buffer). You can look at it with V4L client, but the
1946 * image will be unwatchable. The main purpose of this code and of the
1947 * mode FLAGS_NO_DECODING is debugging and capturing of datastreams from
1948 * new, unknown cameras. This procedure will be automatically invoked
1949 * instead of the specified callback handler when uvd->flags has bit
1950 * FLAGS_NO_DECODING set. Therefore, any regular build of any driver
1951 * based on usbvideo can use this feature at any time.
1953 static void usbvideo_CollectRawData(struct uvd *uvd, struct usbvideo_frame *frame)
1955 int n;
1957 assert(uvd != NULL);
1958 assert(frame != NULL);
1960 /* Try to move data from queue into frame buffer */
1961 n = RingQueue_GetLength(&uvd->dp);
1962 if (n > 0) {
1963 int m;
1964 /* See how much space we have left */
1965 m = uvd->max_frame_size - frame->seqRead_Length;
1966 if (n > m)
1967 n = m;
1968 /* Now move that much data into frame buffer */
1969 RingQueue_Dequeue(
1970 &uvd->dp,
1971 frame->data + frame->seqRead_Length,
1973 frame->seqRead_Length += m;
1975 /* See if we filled the frame */
1976 if (frame->seqRead_Length >= uvd->max_frame_size) {
1977 frame->frameState = FrameState_Done;
1978 uvd->curframe = -1;
1979 uvd->stats.frame_num++;
1983 static int usbvideo_GetFrame(struct uvd *uvd, int frameNum)
1985 struct usbvideo_frame *frame = &uvd->frame[frameNum];
1987 if (uvd->debug >= 2)
1988 dev_info(&uvd->dev->dev, "%s($%p,%d.)\n", __func__, uvd,
1989 frameNum);
1991 switch (frame->frameState) {
1992 case FrameState_Unused:
1993 if (uvd->debug >= 2)
1994 dev_info(&uvd->dev->dev, "%s: FrameState_Unused\n",
1995 __func__);
1996 return -EINVAL;
1997 case FrameState_Ready:
1998 case FrameState_Grabbing:
1999 case FrameState_Error:
2001 int ntries, signalPending;
2002 redo:
2003 if (!CAMERA_IS_OPERATIONAL(uvd)) {
2004 if (uvd->debug >= 2)
2005 dev_info(&uvd->dev->dev,
2006 "%s: Camera is not operational (1)\n",
2007 __func__);
2008 return -EIO;
2010 ntries = 0;
2011 do {
2012 RingQueue_InterruptibleSleepOn(&uvd->dp);
2013 signalPending = signal_pending(current);
2014 if (!CAMERA_IS_OPERATIONAL(uvd)) {
2015 if (uvd->debug >= 2)
2016 dev_info(&uvd->dev->dev,
2017 "%s: Camera is not "
2018 "operational (2)\n", __func__);
2019 return -EIO;
2021 assert(uvd->fbuf != NULL);
2022 if (signalPending) {
2023 if (uvd->debug >= 2)
2024 dev_info(&uvd->dev->dev,
2025 "%s: Signal=$%08x\n", __func__,
2026 signalPending);
2027 if (uvd->flags & FLAGS_RETRY_VIDIOCSYNC) {
2028 usbvideo_TestPattern(uvd, 1, 0);
2029 uvd->curframe = -1;
2030 uvd->stats.frame_num++;
2031 if (uvd->debug >= 2)
2032 dev_info(&uvd->dev->dev,
2033 "%s: Forced test "
2034 "pattern screen\n",
2035 __func__);
2036 return 0;
2037 } else {
2038 /* Standard answer: Interrupted! */
2039 if (uvd->debug >= 2)
2040 dev_info(&uvd->dev->dev,
2041 "%s: Interrupted!\n",
2042 __func__);
2043 return -EINTR;
2045 } else {
2046 /* No signals - we just got new data in dp queue */
2047 if (uvd->flags & FLAGS_NO_DECODING)
2048 usbvideo_CollectRawData(uvd, frame);
2049 else if (VALID_CALLBACK(uvd, processData))
2050 GET_CALLBACK(uvd, processData)(uvd, frame);
2051 else
2052 err("%s: processData not set", __func__);
2054 } while (frame->frameState == FrameState_Grabbing);
2055 if (uvd->debug >= 2) {
2056 dev_info(&uvd->dev->dev,
2057 "%s: Grabbing done; state=%d. (%lu. bytes)\n",
2058 __func__, frame->frameState,
2059 frame->seqRead_Length);
2061 if (frame->frameState == FrameState_Error) {
2062 int ret = usbvideo_NewFrame(uvd, frameNum);
2063 if (ret < 0) {
2064 err("%s: usbvideo_NewFrame() failed (%d.)", __func__, ret);
2065 return ret;
2067 goto redo;
2069 /* Note that we fall through to meet our destiny below */
2071 case FrameState_Done:
2073 * Do all necessary postprocessing of data prepared in
2074 * "interrupt" code and the collecting code above. The
2075 * frame gets marked as FrameState_Done by queue parsing code.
2076 * This status means that we collected enough data and
2077 * most likely processed it as we went through. However
2078 * the data may need postprocessing, such as deinterlacing
2079 * or picture adjustments implemented in software (horror!)
2081 * As soon as the frame becomes "final" it gets promoted to
2082 * FrameState_Done_Hold status where it will remain until the
2083 * caller consumed all the video data from the frame. Then
2084 * the empty shell of ex-frame is thrown out for dogs to eat.
2085 * But we, worried about pets, will recycle the frame!
2087 uvd->stats.frame_num++;
2088 if ((uvd->flags & FLAGS_NO_DECODING) == 0) {
2089 if (VALID_CALLBACK(uvd, postProcess))
2090 GET_CALLBACK(uvd, postProcess)(uvd, frame);
2091 if (frame->flags & USBVIDEO_FRAME_FLAG_SOFTWARE_CONTRAST)
2092 usbvideo_SoftwareContrastAdjustment(uvd, frame);
2094 frame->frameState = FrameState_Done_Hold;
2095 if (uvd->debug >= 2)
2096 dev_info(&uvd->dev->dev,
2097 "%s: Entered FrameState_Done_Hold state.\n",
2098 __func__);
2099 return 0;
2101 case FrameState_Done_Hold:
2103 * We stay in this state indefinitely until someone external,
2104 * like ioctl() or read() call finishes digesting the frame
2105 * data. Then it will mark the frame as FrameState_Unused and
2106 * it will be released back into the wild to roam freely.
2108 if (uvd->debug >= 2)
2109 dev_info(&uvd->dev->dev,
2110 "%s: FrameState_Done_Hold state.\n",
2111 __func__);
2112 return 0;
2115 /* Catch-all for other cases. We shall not be here. */
2116 err("%s: Invalid state %d.", __func__, frame->frameState);
2117 frame->frameState = FrameState_Unused;
2118 return 0;
2122 * usbvideo_DeinterlaceFrame()
2124 * This procedure deinterlaces the given frame. Some cameras produce
2125 * only half of scanlines - sometimes only even lines, sometimes only
2126 * odd lines. The deinterlacing method is stored in frame->deinterlace
2127 * variable.
2129 * Here we scan the frame vertically and replace missing scanlines with
2130 * average between surrounding ones - before and after. If we have no
2131 * line above then we just copy next line. Similarly, if we need to
2132 * create a last line then preceding line is used.
2134 void usbvideo_DeinterlaceFrame(struct uvd *uvd, struct usbvideo_frame *frame)
2136 if ((uvd == NULL) || (frame == NULL))
2137 return;
2139 if ((frame->deinterlace == Deinterlace_FillEvenLines) ||
2140 (frame->deinterlace == Deinterlace_FillOddLines))
2142 const int v4l_linesize = VIDEOSIZE_X(frame->request) * V4L_BYTES_PER_PIXEL;
2143 int i = (frame->deinterlace == Deinterlace_FillEvenLines) ? 0 : 1;
2145 for (; i < VIDEOSIZE_Y(frame->request); i += 2) {
2146 const unsigned char *fs1, *fs2;
2147 unsigned char *fd;
2148 int ip, in, j; /* Previous and next lines */
2151 * Need to average lines before and after 'i'.
2152 * If we go out of bounds seeking those lines then
2153 * we point back to existing line.
2155 ip = i - 1; /* First, get rough numbers */
2156 in = i + 1;
2158 /* Now validate */
2159 if (ip < 0)
2160 ip = in;
2161 if (in >= VIDEOSIZE_Y(frame->request))
2162 in = ip;
2164 /* Sanity check */
2165 if ((ip < 0) || (in < 0) ||
2166 (ip >= VIDEOSIZE_Y(frame->request)) ||
2167 (in >= VIDEOSIZE_Y(frame->request)))
2169 err("Error: ip=%d. in=%d. req.height=%ld.",
2170 ip, in, VIDEOSIZE_Y(frame->request));
2171 break;
2174 /* Now we need to average lines 'ip' and 'in' to produce line 'i' */
2175 fs1 = frame->data + (v4l_linesize * ip);
2176 fs2 = frame->data + (v4l_linesize * in);
2177 fd = frame->data + (v4l_linesize * i);
2179 /* Average lines around destination */
2180 for (j=0; j < v4l_linesize; j++) {
2181 fd[j] = (unsigned char)((((unsigned) fs1[j]) +
2182 ((unsigned)fs2[j])) >> 1);
2187 /* Optionally display statistics on the screen */
2188 if (uvd->flags & FLAGS_OVERLAY_STATS)
2189 usbvideo_OverlayStats(uvd, frame);
2192 EXPORT_SYMBOL(usbvideo_DeinterlaceFrame);
2195 * usbvideo_SoftwareContrastAdjustment()
2197 * This code adjusts the contrast of the frame, assuming RGB24 format.
2198 * As most software image processing, this job is CPU-intensive.
2199 * Get a camera that supports hardware adjustment!
2201 * History:
2202 * 09-Feb-2001 Created.
2204 static void usbvideo_SoftwareContrastAdjustment(struct uvd *uvd,
2205 struct usbvideo_frame *frame)
2207 int i, j, v4l_linesize;
2208 signed long adj;
2209 const int ccm = 128; /* Color correction median - see below */
2211 if ((uvd == NULL) || (frame == NULL)) {
2212 err("%s: Illegal call.", __func__);
2213 return;
2215 adj = (uvd->vpic.contrast - 0x8000) >> 8; /* -128..+127 = -ccm..+(ccm-1)*/
2216 RESTRICT_TO_RANGE(adj, -ccm, ccm+1);
2217 if (adj == 0) {
2218 /* In rare case of no adjustment */
2219 return;
2221 v4l_linesize = VIDEOSIZE_X(frame->request) * V4L_BYTES_PER_PIXEL;
2222 for (i=0; i < VIDEOSIZE_Y(frame->request); i++) {
2223 unsigned char *fd = frame->data + (v4l_linesize * i);
2224 for (j=0; j < v4l_linesize; j++) {
2225 signed long v = (signed long) fd[j];
2226 /* Magnify up to 2 times, reduce down to zero */
2227 v = 128 + ((ccm + adj) * (v - 128)) / ccm;
2228 RESTRICT_TO_RANGE(v, 0, 0xFF); /* Must flatten tails */
2229 fd[j] = (unsigned char) v;
2234 MODULE_LICENSE("GPL");