V4L/DVB (8428): videodev: rename 'dev' to 'parent'
[firewire-audio.git] / drivers / media / video / usbvideo / usbvideo.c
blob7e6ab2910c138a2ead2bfc44d19f1c9e301df9b6
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 int usbvideo_v4l_ioctl(struct inode *inode, 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 inode *inode, 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 inode *inode, 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 info("Packet Statistics: Total=%lu. Empty=%lu. Usage=%lu%%",
472 allPackets, badPackets, percent);
473 if (uvd->iso_packet_len > 0) {
474 unsigned long allBytes, xferBytes;
475 char multiplier = ' ';
476 allBytes = allPackets * uvd->iso_packet_len;
477 xferBytes = uvd->stats.data_count;
478 assert(allBytes != 0);
479 if (xferBytes < (((unsigned long)-1)/100))
480 percent = (100 * xferBytes) / allBytes;
481 else
482 percent = xferBytes / (allBytes / 100);
483 /* Scale xferBytes for easy reading */
484 if (xferBytes > 10*1024) {
485 xferBytes /= 1024;
486 multiplier = 'K';
487 if (xferBytes > 10*1024) {
488 xferBytes /= 1024;
489 multiplier = 'M';
490 if (xferBytes > 10*1024) {
491 xferBytes /= 1024;
492 multiplier = 'G';
493 if (xferBytes > 10*1024) {
494 xferBytes /= 1024;
495 multiplier = 'T';
500 info("Transfer Statistics: Transferred=%lu%cB Usage=%lu%%",
501 xferBytes, multiplier, percent);
507 * usbvideo_TestPattern()
509 * Procedure forms a test pattern (yellow grid on blue background).
511 * Parameters:
512 * fullframe: if TRUE then entire frame is filled, otherwise the procedure
513 * continues from the current scanline.
514 * pmode 0: fill the frame with solid blue color (like on VCR or TV)
515 * 1: Draw a colored grid
517 * History:
518 * 01-Feb-2000 Created.
520 void usbvideo_TestPattern(struct uvd *uvd, int fullframe, int pmode)
522 struct usbvideo_frame *frame;
523 int num_cell = 0;
524 int scan_length = 0;
525 static int num_pass;
527 if (uvd == NULL) {
528 err("%s: uvd == NULL", __func__);
529 return;
531 if ((uvd->curframe < 0) || (uvd->curframe >= USBVIDEO_NUMFRAMES)) {
532 err("%s: uvd->curframe=%d.", __func__, uvd->curframe);
533 return;
536 /* Grab the current frame */
537 frame = &uvd->frame[uvd->curframe];
539 /* Optionally start at the beginning */
540 if (fullframe) {
541 frame->curline = 0;
542 frame->seqRead_Length = 0;
544 #if 0
545 { /* For debugging purposes only */
546 char tmp[20];
547 usbvideo_VideosizeToString(tmp, sizeof(tmp), frame->request);
548 info("testpattern: frame=%s", tmp);
550 #endif
551 /* Form every scan line */
552 for (; frame->curline < VIDEOSIZE_Y(frame->request); frame->curline++) {
553 int i;
554 unsigned char *f = frame->data +
555 (VIDEOSIZE_X(frame->request) * V4L_BYTES_PER_PIXEL * frame->curline);
556 for (i=0; i < VIDEOSIZE_X(frame->request); i++) {
557 unsigned char cb=0x80;
558 unsigned char cg = 0;
559 unsigned char cr = 0;
561 if (pmode == 1) {
562 if (frame->curline % 32 == 0)
563 cb = 0, cg = cr = 0xFF;
564 else if (i % 32 == 0) {
565 if (frame->curline % 32 == 1)
566 num_cell++;
567 cb = 0, cg = cr = 0xFF;
568 } else {
569 cb = ((num_cell*7) + num_pass) & 0xFF;
570 cg = ((num_cell*5) + num_pass*2) & 0xFF;
571 cr = ((num_cell*3) + num_pass*3) & 0xFF;
573 } else {
574 /* Just the blue screen */
577 *f++ = cb;
578 *f++ = cg;
579 *f++ = cr;
580 scan_length += 3;
584 frame->frameState = FrameState_Done;
585 frame->seqRead_Length += scan_length;
586 ++num_pass;
588 /* We do this unconditionally, regardless of FLAGS_OVERLAY_STATS */
589 usbvideo_OverlayStats(uvd, frame);
592 EXPORT_SYMBOL(usbvideo_TestPattern);
595 #ifdef DEBUG
597 * usbvideo_HexDump()
599 * A debugging tool. Prints hex dumps.
601 * History:
602 * 29-Jul-2000 Added printing of offsets.
604 void usbvideo_HexDump(const unsigned char *data, int len)
606 const int bytes_per_line = 32;
607 char tmp[128]; /* 32*3 + 5 */
608 int i, k;
610 for (i=k=0; len > 0; i++, len--) {
611 if (i > 0 && ((i % bytes_per_line) == 0)) {
612 printk("%s\n", tmp);
613 k=0;
615 if ((i % bytes_per_line) == 0)
616 k += sprintf(&tmp[k], "%04x: ", i);
617 k += sprintf(&tmp[k], "%02x ", data[i]);
619 if (k > 0)
620 printk("%s\n", tmp);
623 EXPORT_SYMBOL(usbvideo_HexDump);
625 #endif
627 /* ******************************************************************** */
629 /* XXX: this piece of crap really wants some error handling.. */
630 static int usbvideo_ClientIncModCount(struct uvd *uvd)
632 if (uvd == NULL) {
633 err("%s: uvd == NULL", __func__);
634 return -EINVAL;
636 if (uvd->handle == NULL) {
637 err("%s: uvd->handle == NULL", __func__);
638 return -EINVAL;
640 if (!try_module_get(uvd->handle->md_module)) {
641 err("%s: try_module_get() == 0", __func__);
642 return -ENODEV;
644 return 0;
647 static void usbvideo_ClientDecModCount(struct uvd *uvd)
649 if (uvd == NULL) {
650 err("%s: uvd == NULL", __func__);
651 return;
653 if (uvd->handle == NULL) {
654 err("%s: uvd->handle == NULL", __func__);
655 return;
657 if (uvd->handle->md_module == NULL) {
658 err("%s: uvd->handle->md_module == NULL", __func__);
659 return;
661 module_put(uvd->handle->md_module);
664 int usbvideo_register(
665 struct usbvideo **pCams,
666 const int num_cams,
667 const int num_extra,
668 const char *driverName,
669 const struct usbvideo_cb *cbTbl,
670 struct module *md,
671 const struct usb_device_id *id_table)
673 struct usbvideo *cams;
674 int i, base_size, result;
676 /* Check parameters for sanity */
677 if ((num_cams <= 0) || (pCams == NULL) || (cbTbl == NULL)) {
678 err("%s: Illegal call", __func__);
679 return -EINVAL;
682 /* Check registration callback - must be set! */
683 if (cbTbl->probe == NULL) {
684 err("%s: probe() is required!", __func__);
685 return -EINVAL;
688 base_size = num_cams * sizeof(struct uvd) + sizeof(struct usbvideo);
689 cams = kzalloc(base_size, GFP_KERNEL);
690 if (cams == NULL) {
691 err("Failed to allocate %d. bytes for usbvideo struct", base_size);
692 return -ENOMEM;
694 dbg("%s: Allocated $%p (%d. bytes) for %d. cameras",
695 __func__, cams, base_size, num_cams);
697 /* Copy callbacks, apply defaults for those that are not set */
698 memmove(&cams->cb, cbTbl, sizeof(cams->cb));
699 if (cams->cb.getFrame == NULL)
700 cams->cb.getFrame = usbvideo_GetFrame;
701 if (cams->cb.disconnect == NULL)
702 cams->cb.disconnect = usbvideo_Disconnect;
703 if (cams->cb.startDataPump == NULL)
704 cams->cb.startDataPump = usbvideo_StartDataPump;
705 if (cams->cb.stopDataPump == NULL)
706 cams->cb.stopDataPump = usbvideo_StopDataPump;
708 cams->num_cameras = num_cams;
709 cams->cam = (struct uvd *) &cams[1];
710 cams->md_module = md;
711 mutex_init(&cams->lock); /* to 1 == available */
713 for (i = 0; i < num_cams; i++) {
714 struct uvd *up = &cams->cam[i];
716 up->handle = cams;
718 /* Allocate user_data separately because of kmalloc's limits */
719 if (num_extra > 0) {
720 up->user_size = num_cams * num_extra;
721 up->user_data = kmalloc(up->user_size, GFP_KERNEL);
722 if (up->user_data == NULL) {
723 err("%s: Failed to allocate user_data (%d. bytes)",
724 __func__, up->user_size);
725 while (i) {
726 up = &cams->cam[--i];
727 kfree(up->user_data);
729 kfree(cams);
730 return -ENOMEM;
732 dbg("%s: Allocated cams[%d].user_data=$%p (%d. bytes)",
733 __func__, i, up->user_data, up->user_size);
738 * Register ourselves with USB stack.
740 strcpy(cams->drvName, (driverName != NULL) ? driverName : "Unknown");
741 cams->usbdrv.name = cams->drvName;
742 cams->usbdrv.probe = cams->cb.probe;
743 cams->usbdrv.disconnect = cams->cb.disconnect;
744 cams->usbdrv.id_table = id_table;
747 * Update global handle to usbvideo. This is very important
748 * because probe() can be called before usb_register() returns.
749 * If the handle is not yet updated then the probe() will fail.
751 *pCams = cams;
752 result = usb_register(&cams->usbdrv);
753 if (result) {
754 for (i = 0; i < num_cams; i++) {
755 struct uvd *up = &cams->cam[i];
756 kfree(up->user_data);
758 kfree(cams);
761 return result;
764 EXPORT_SYMBOL(usbvideo_register);
767 * usbvideo_Deregister()
769 * Procedure frees all usbvideo and user data structures. Be warned that
770 * if you had some dynamically allocated components in ->user field then
771 * you should free them before calling here.
773 void usbvideo_Deregister(struct usbvideo **pCams)
775 struct usbvideo *cams;
776 int i;
778 if (pCams == NULL) {
779 err("%s: pCams == NULL", __func__);
780 return;
782 cams = *pCams;
783 if (cams == NULL) {
784 err("%s: cams == NULL", __func__);
785 return;
788 dbg("%s: Deregistering %s driver.", __func__, cams->drvName);
789 usb_deregister(&cams->usbdrv);
791 dbg("%s: Deallocating cams=$%p (%d. cameras)", __func__, cams, cams->num_cameras);
792 for (i=0; i < cams->num_cameras; i++) {
793 struct uvd *up = &cams->cam[i];
794 int warning = 0;
796 if (up->user_data != NULL) {
797 if (up->user_size <= 0)
798 ++warning;
799 } else {
800 if (up->user_size > 0)
801 ++warning;
803 if (warning) {
804 err("%s: Warning: user_data=$%p user_size=%d.",
805 __func__, up->user_data, up->user_size);
806 } else {
807 dbg("%s: Freeing %d. $%p->user_data=$%p",
808 __func__, i, up, up->user_data);
809 kfree(up->user_data);
812 /* Whole array was allocated in one chunk */
813 dbg("%s: Freed %d uvd structures",
814 __func__, cams->num_cameras);
815 kfree(cams);
816 *pCams = NULL;
819 EXPORT_SYMBOL(usbvideo_Deregister);
822 * usbvideo_Disconnect()
824 * This procedure stops all driver activity. Deallocation of
825 * the interface-private structure (pointed by 'ptr') is done now
826 * (if we don't have any open files) or later, when those files
827 * are closed. After that driver should be removable.
829 * This code handles surprise removal. The uvd->user is a counter which
830 * increments on open() and decrements on close(). If we see here that
831 * this counter is not 0 then we have a client who still has us opened.
832 * We set uvd->remove_pending flag as early as possible, and after that
833 * all access to the camera will gracefully fail. These failures should
834 * prompt client to (eventually) close the video device, and then - in
835 * usbvideo_v4l_close() - we decrement uvd->uvd_used and usage counter.
837 * History:
838 * 22-Jan-2000 Added polling of MOD_IN_USE to delay removal until all users gone.
839 * 27-Jan-2000 Reworked to allow pending disconnects; see xxx_close()
840 * 24-May-2000 Corrected to prevent race condition (MOD_xxx_USE_COUNT).
841 * 19-Oct-2000 Moved to usbvideo module.
843 static void usbvideo_Disconnect(struct usb_interface *intf)
845 struct uvd *uvd = usb_get_intfdata (intf);
846 int i;
848 if (uvd == NULL) {
849 err("%s($%p): Illegal call.", __func__, intf);
850 return;
853 usb_set_intfdata (intf, NULL);
855 usbvideo_ClientIncModCount(uvd);
856 if (uvd->debug > 0)
857 info("%s(%p.)", __func__, intf);
859 mutex_lock(&uvd->lock);
860 uvd->remove_pending = 1; /* Now all ISO data will be ignored */
862 /* At this time we ask to cancel outstanding URBs */
863 GET_CALLBACK(uvd, stopDataPump)(uvd);
865 for (i=0; i < USBVIDEO_NUMSBUF; i++)
866 usb_free_urb(uvd->sbuf[i].urb);
868 usb_put_dev(uvd->dev);
869 uvd->dev = NULL; /* USB device is no more */
871 video_unregister_device(&uvd->vdev);
872 if (uvd->debug > 0)
873 info("%s: Video unregistered.", __func__);
875 if (uvd->user)
876 info("%s: In use, disconnect pending.", __func__);
877 else
878 usbvideo_CameraRelease(uvd);
879 mutex_unlock(&uvd->lock);
880 info("USB camera disconnected.");
882 usbvideo_ClientDecModCount(uvd);
886 * usbvideo_CameraRelease()
888 * This code does final release of uvd. This happens
889 * after the device is disconnected -and- all clients
890 * closed their files.
892 * History:
893 * 27-Jan-2000 Created.
895 static void usbvideo_CameraRelease(struct uvd *uvd)
897 if (uvd == NULL) {
898 err("%s: Illegal call", __func__);
899 return;
902 RingQueue_Free(&uvd->dp);
903 if (VALID_CALLBACK(uvd, userFree))
904 GET_CALLBACK(uvd, userFree)(uvd);
905 uvd->uvd_used = 0; /* This is atomic, no need to take mutex */
909 * usbvideo_find_struct()
911 * This code searches the array of preallocated (static) structures
912 * and returns index of the first one that isn't in use. Returns -1
913 * if there are no free structures.
915 * History:
916 * 27-Jan-2000 Created.
918 static int usbvideo_find_struct(struct usbvideo *cams)
920 int u, rv = -1;
922 if (cams == NULL) {
923 err("No usbvideo handle?");
924 return -1;
926 mutex_lock(&cams->lock);
927 for (u = 0; u < cams->num_cameras; u++) {
928 struct uvd *uvd = &cams->cam[u];
929 if (!uvd->uvd_used) /* This one is free */
931 uvd->uvd_used = 1; /* In use now */
932 mutex_init(&uvd->lock); /* to 1 == available */
933 uvd->dev = NULL;
934 rv = u;
935 break;
938 mutex_unlock(&cams->lock);
939 return rv;
942 static const struct file_operations usbvideo_fops = {
943 .owner = THIS_MODULE,
944 .open = usbvideo_v4l_open,
945 .release =usbvideo_v4l_close,
946 .read = usbvideo_v4l_read,
947 .mmap = usbvideo_v4l_mmap,
948 .ioctl = usbvideo_v4l_ioctl,
949 #ifdef CONFIG_COMPAT
950 .compat_ioctl = v4l_compat_ioctl32,
951 #endif
952 .llseek = no_llseek,
954 static const struct video_device usbvideo_template = {
955 .owner = THIS_MODULE,
956 .type = VID_TYPE_CAPTURE,
957 .fops = &usbvideo_fops,
960 struct uvd *usbvideo_AllocateDevice(struct usbvideo *cams)
962 int i, devnum;
963 struct uvd *uvd = NULL;
965 if (cams == NULL) {
966 err("No usbvideo handle?");
967 return NULL;
970 devnum = usbvideo_find_struct(cams);
971 if (devnum == -1) {
972 err("IBM USB camera driver: Too many devices!");
973 return NULL;
975 uvd = &cams->cam[devnum];
976 dbg("Device entry #%d. at $%p", devnum, uvd);
978 /* Not relying upon caller we increase module counter ourselves */
979 usbvideo_ClientIncModCount(uvd);
981 mutex_lock(&uvd->lock);
982 for (i=0; i < USBVIDEO_NUMSBUF; i++) {
983 uvd->sbuf[i].urb = usb_alloc_urb(FRAMES_PER_DESC, GFP_KERNEL);
984 if (uvd->sbuf[i].urb == NULL) {
985 err("usb_alloc_urb(%d.) failed.", FRAMES_PER_DESC);
986 uvd->uvd_used = 0;
987 uvd = NULL;
988 goto allocate_done;
991 uvd->user=0;
992 uvd->remove_pending = 0;
993 uvd->last_error = 0;
994 RingQueue_Initialize(&uvd->dp);
996 /* Initialize video device structure */
997 uvd->vdev = usbvideo_template;
998 sprintf(uvd->vdev.name, "%.20s USB Camera", cams->drvName);
1000 * The client is free to overwrite those because we
1001 * return control to the client's probe function right now.
1003 allocate_done:
1004 mutex_unlock(&uvd->lock);
1005 usbvideo_ClientDecModCount(uvd);
1006 return uvd;
1009 EXPORT_SYMBOL(usbvideo_AllocateDevice);
1011 int usbvideo_RegisterVideoDevice(struct uvd *uvd)
1013 char tmp1[20], tmp2[20]; /* Buffers for printing */
1015 if (uvd == NULL) {
1016 err("%s: Illegal call.", __func__);
1017 return -EINVAL;
1019 if (uvd->video_endp == 0) {
1020 info("%s: No video endpoint specified; data pump disabled.", __func__);
1022 if (uvd->paletteBits == 0) {
1023 err("%s: No palettes specified!", __func__);
1024 return -EINVAL;
1026 if (uvd->defaultPalette == 0) {
1027 info("%s: No default palette!", __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 info("%s: iface=%d. endpoint=$%02x paletteBits=$%08lx",
1037 __func__, uvd->iface, uvd->video_endp, uvd->paletteBits);
1039 if (uvd->dev == NULL) {
1040 err("%s: uvd->dev == NULL", __func__);
1041 return -EINVAL;
1043 uvd->vdev.parent = &uvd->dev->dev;
1044 if (video_register_device(&uvd->vdev, VFL_TYPE_GRABBER, video_nr) == -1) {
1045 err("%s: video_register_device failed", __func__);
1046 return -EPIPE;
1048 if (uvd->debug > 1) {
1049 info("%s: video_register_device() successful", __func__);
1052 info("%s on /dev/video%d: canvas=%s videosize=%s",
1053 (uvd->handle != NULL) ? uvd->handle->drvName : "???",
1054 uvd->vdev.minor, tmp2, tmp1);
1056 usb_get_dev(uvd->dev);
1057 return 0;
1060 EXPORT_SYMBOL(usbvideo_RegisterVideoDevice);
1062 /* ******************************************************************** */
1064 static int usbvideo_v4l_mmap(struct file *file, struct vm_area_struct *vma)
1066 struct uvd *uvd = file->private_data;
1067 unsigned long start = vma->vm_start;
1068 unsigned long size = vma->vm_end-vma->vm_start;
1069 unsigned long page, pos;
1071 if (!CAMERA_IS_OPERATIONAL(uvd))
1072 return -EFAULT;
1074 if (size > (((USBVIDEO_NUMFRAMES * uvd->max_frame_size) + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1)))
1075 return -EINVAL;
1077 pos = (unsigned long) uvd->fbuf;
1078 while (size > 0) {
1079 page = vmalloc_to_pfn((void *)pos);
1080 if (remap_pfn_range(vma, start, page, PAGE_SIZE, PAGE_SHARED))
1081 return -EAGAIN;
1083 start += PAGE_SIZE;
1084 pos += PAGE_SIZE;
1085 if (size > PAGE_SIZE)
1086 size -= PAGE_SIZE;
1087 else
1088 size = 0;
1091 return 0;
1095 * usbvideo_v4l_open()
1097 * This is part of Video 4 Linux API. The driver can be opened by one
1098 * client only (checks internal counter 'uvdser'). The procedure
1099 * then allocates buffers needed for video processing.
1101 * History:
1102 * 22-Jan-2000 Rewrote, moved scratch buffer allocation here. Now the
1103 * camera is also initialized here (once per connect), at
1104 * expense of V4L client (it waits on open() call).
1105 * 27-Jan-2000 Used USBVIDEO_NUMSBUF as number of URB buffers.
1106 * 24-May-2000 Corrected to prevent race condition (MOD_xxx_USE_COUNT).
1108 static int usbvideo_v4l_open(struct inode *inode, struct file *file)
1110 struct video_device *dev = video_devdata(file);
1111 struct uvd *uvd = (struct uvd *) dev;
1112 const int sb_size = FRAMES_PER_DESC * uvd->iso_packet_len;
1113 int i, errCode = 0;
1115 if (uvd->debug > 1)
1116 info("%s($%p)", __func__, dev);
1118 if (0 < usbvideo_ClientIncModCount(uvd))
1119 return -ENODEV;
1120 mutex_lock(&uvd->lock);
1122 if (uvd->user) {
1123 err("%s: Someone tried to open an already opened device!", __func__);
1124 errCode = -EBUSY;
1125 } else {
1126 /* Clear statistics */
1127 memset(&uvd->stats, 0, sizeof(uvd->stats));
1129 /* Clean pointers so we know if we allocated something */
1130 for (i=0; i < USBVIDEO_NUMSBUF; i++)
1131 uvd->sbuf[i].data = NULL;
1133 /* Allocate memory for the frame buffers */
1134 uvd->fbuf_size = USBVIDEO_NUMFRAMES * uvd->max_frame_size;
1135 uvd->fbuf = usbvideo_rvmalloc(uvd->fbuf_size);
1136 RingQueue_Allocate(&uvd->dp, RING_QUEUE_SIZE);
1137 if ((uvd->fbuf == NULL) ||
1138 (!RingQueue_IsAllocated(&uvd->dp))) {
1139 err("%s: Failed to allocate fbuf or dp", __func__);
1140 errCode = -ENOMEM;
1141 } else {
1142 /* Allocate all buffers */
1143 for (i=0; i < USBVIDEO_NUMFRAMES; i++) {
1144 uvd->frame[i].frameState = FrameState_Unused;
1145 uvd->frame[i].data = uvd->fbuf + i*(uvd->max_frame_size);
1147 * Set default sizes in case IOCTL (VIDIOCMCAPTURE)
1148 * is not used (using read() instead).
1150 uvd->frame[i].canvas = uvd->canvas;
1151 uvd->frame[i].seqRead_Index = 0;
1153 for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1154 uvd->sbuf[i].data = kmalloc(sb_size, GFP_KERNEL);
1155 if (uvd->sbuf[i].data == NULL) {
1156 errCode = -ENOMEM;
1157 break;
1161 if (errCode != 0) {
1162 /* Have to free all that memory */
1163 if (uvd->fbuf != NULL) {
1164 usbvideo_rvfree(uvd->fbuf, uvd->fbuf_size);
1165 uvd->fbuf = NULL;
1167 RingQueue_Free(&uvd->dp);
1168 for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1169 kfree(uvd->sbuf[i].data);
1170 uvd->sbuf[i].data = NULL;
1175 /* If so far no errors then we shall start the camera */
1176 if (errCode == 0) {
1177 /* Start data pump if we have valid endpoint */
1178 if (uvd->video_endp != 0)
1179 errCode = GET_CALLBACK(uvd, startDataPump)(uvd);
1180 if (errCode == 0) {
1181 if (VALID_CALLBACK(uvd, setupOnOpen)) {
1182 if (uvd->debug > 1)
1183 info("%s: setupOnOpen callback", __func__);
1184 errCode = GET_CALLBACK(uvd, setupOnOpen)(uvd);
1185 if (errCode < 0) {
1186 err("%s: setupOnOpen callback failed (%d.).",
1187 __func__, errCode);
1188 } else if (uvd->debug > 1) {
1189 info("%s: setupOnOpen callback successful", __func__);
1192 if (errCode == 0) {
1193 uvd->settingsAdjusted = 0;
1194 if (uvd->debug > 1)
1195 info("%s: Open succeeded.", __func__);
1196 uvd->user++;
1197 file->private_data = uvd;
1201 mutex_unlock(&uvd->lock);
1202 if (errCode != 0)
1203 usbvideo_ClientDecModCount(uvd);
1204 if (uvd->debug > 0)
1205 info("%s: Returning %d.", __func__, errCode);
1206 return errCode;
1210 * usbvideo_v4l_close()
1212 * This is part of Video 4 Linux API. The procedure
1213 * stops streaming and deallocates all buffers that were earlier
1214 * allocated in usbvideo_v4l_open().
1216 * History:
1217 * 22-Jan-2000 Moved scratch buffer deallocation here.
1218 * 27-Jan-2000 Used USBVIDEO_NUMSBUF as number of URB buffers.
1219 * 24-May-2000 Moved MOD_DEC_USE_COUNT outside of code that can sleep.
1221 static int usbvideo_v4l_close(struct inode *inode, struct file *file)
1223 struct video_device *dev = file->private_data;
1224 struct uvd *uvd = (struct uvd *) dev;
1225 int i;
1227 if (uvd->debug > 1)
1228 info("%s($%p)", __func__, dev);
1230 mutex_lock(&uvd->lock);
1231 GET_CALLBACK(uvd, stopDataPump)(uvd);
1232 usbvideo_rvfree(uvd->fbuf, uvd->fbuf_size);
1233 uvd->fbuf = NULL;
1234 RingQueue_Free(&uvd->dp);
1236 for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1237 kfree(uvd->sbuf[i].data);
1238 uvd->sbuf[i].data = NULL;
1241 #if USBVIDEO_REPORT_STATS
1242 usbvideo_ReportStatistics(uvd);
1243 #endif
1245 uvd->user--;
1246 if (uvd->remove_pending) {
1247 if (uvd->debug > 0)
1248 info("usbvideo_v4l_close: Final disconnect.");
1249 usbvideo_CameraRelease(uvd);
1251 mutex_unlock(&uvd->lock);
1252 usbvideo_ClientDecModCount(uvd);
1254 if (uvd->debug > 1)
1255 info("%s: Completed.", __func__);
1256 file->private_data = NULL;
1257 return 0;
1261 * usbvideo_v4l_ioctl()
1263 * This is part of Video 4 Linux API. The procedure handles ioctl() calls.
1265 * History:
1266 * 22-Jan-2000 Corrected VIDIOCSPICT to reject unsupported settings.
1268 static int usbvideo_v4l_do_ioctl(struct inode *inode, struct file *file,
1269 unsigned int cmd, void *arg)
1271 struct uvd *uvd = file->private_data;
1273 if (!CAMERA_IS_OPERATIONAL(uvd))
1274 return -EIO;
1276 switch (cmd) {
1277 case VIDIOCGCAP:
1279 struct video_capability *b = arg;
1280 *b = uvd->vcap;
1281 return 0;
1283 case VIDIOCGCHAN:
1285 struct video_channel *v = arg;
1286 *v = uvd->vchan;
1287 return 0;
1289 case VIDIOCSCHAN:
1291 struct video_channel *v = arg;
1292 if (v->channel != 0)
1293 return -EINVAL;
1294 return 0;
1296 case VIDIOCGPICT:
1298 struct video_picture *pic = arg;
1299 *pic = uvd->vpic;
1300 return 0;
1302 case VIDIOCSPICT:
1304 struct video_picture *pic = arg;
1306 * Use temporary 'video_picture' structure to preserve our
1307 * own settings (such as color depth, palette) that we
1308 * aren't allowing everyone (V4L client) to change.
1310 uvd->vpic.brightness = pic->brightness;
1311 uvd->vpic.hue = pic->hue;
1312 uvd->vpic.colour = pic->colour;
1313 uvd->vpic.contrast = pic->contrast;
1314 uvd->settingsAdjusted = 0; /* Will force new settings */
1315 return 0;
1317 case VIDIOCSWIN:
1319 struct video_window *vw = arg;
1321 if(VALID_CALLBACK(uvd, setVideoMode)) {
1322 return GET_CALLBACK(uvd, setVideoMode)(uvd, vw);
1325 if (vw->flags)
1326 return -EINVAL;
1327 if (vw->clipcount)
1328 return -EINVAL;
1329 if (vw->width != VIDEOSIZE_X(uvd->canvas))
1330 return -EINVAL;
1331 if (vw->height != VIDEOSIZE_Y(uvd->canvas))
1332 return -EINVAL;
1334 return 0;
1336 case VIDIOCGWIN:
1338 struct video_window *vw = arg;
1340 vw->x = 0;
1341 vw->y = 0;
1342 vw->width = VIDEOSIZE_X(uvd->videosize);
1343 vw->height = VIDEOSIZE_Y(uvd->videosize);
1344 vw->chromakey = 0;
1345 if (VALID_CALLBACK(uvd, getFPS))
1346 vw->flags = GET_CALLBACK(uvd, getFPS)(uvd);
1347 else
1348 vw->flags = 10; /* FIXME: do better! */
1349 return 0;
1351 case VIDIOCGMBUF:
1353 struct video_mbuf *vm = arg;
1354 int i;
1356 memset(vm, 0, sizeof(*vm));
1357 vm->size = uvd->max_frame_size * USBVIDEO_NUMFRAMES;
1358 vm->frames = USBVIDEO_NUMFRAMES;
1359 for(i = 0; i < USBVIDEO_NUMFRAMES; i++)
1360 vm->offsets[i] = i * uvd->max_frame_size;
1362 return 0;
1364 case VIDIOCMCAPTURE:
1366 struct video_mmap *vm = arg;
1368 if (uvd->debug >= 1) {
1369 info("VIDIOCMCAPTURE: frame=%d. size=%dx%d, format=%d.",
1370 vm->frame, vm->width, vm->height, vm->format);
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.
1385 if ((vm->width > VIDEOSIZE_X(uvd->canvas)) ||
1386 (vm->height > VIDEOSIZE_Y(uvd->canvas))) {
1387 if (uvd->debug > 0) {
1388 info("VIDIOCMCAPTURE: Size=%dx%d too large; "
1389 "allowed only up to %ldx%ld", vm->width, vm->height,
1390 VIDEOSIZE_X(uvd->canvas), VIDEOSIZE_Y(uvd->canvas));
1392 return -EINVAL;
1394 /* Check if the palette is supported */
1395 if (((1L << vm->format) & uvd->paletteBits) == 0) {
1396 if (uvd->debug > 0) {
1397 info("VIDIOCMCAPTURE: format=%d. not supported"
1398 " (paletteBits=$%08lx)",
1399 vm->format, uvd->paletteBits);
1401 return -EINVAL;
1403 if ((vm->frame < 0) || (vm->frame >= USBVIDEO_NUMFRAMES)) {
1404 err("VIDIOCMCAPTURE: vm.frame=%d. !E [0-%d]", vm->frame, USBVIDEO_NUMFRAMES-1);
1405 return -EINVAL;
1407 if (uvd->frame[vm->frame].frameState == FrameState_Grabbing) {
1408 /* Not an error - can happen */
1410 uvd->frame[vm->frame].request = VIDEOSIZE(vm->width, vm->height);
1411 uvd->frame[vm->frame].palette = vm->format;
1413 /* Mark it as ready */
1414 uvd->frame[vm->frame].frameState = FrameState_Ready;
1416 return usbvideo_NewFrame(uvd, vm->frame);
1418 case VIDIOCSYNC:
1420 int *frameNum = arg;
1421 int ret;
1423 if (*frameNum < 0 || *frameNum >= USBVIDEO_NUMFRAMES)
1424 return -EINVAL;
1426 if (uvd->debug >= 1)
1427 info("VIDIOCSYNC: syncing to frame %d.", *frameNum);
1428 if (uvd->flags & FLAGS_NO_DECODING)
1429 ret = usbvideo_GetFrame(uvd, *frameNum);
1430 else if (VALID_CALLBACK(uvd, getFrame)) {
1431 ret = GET_CALLBACK(uvd, getFrame)(uvd, *frameNum);
1432 if ((ret < 0) && (uvd->debug >= 1)) {
1433 err("VIDIOCSYNC: getFrame() returned %d.", ret);
1435 } else {
1436 err("VIDIOCSYNC: getFrame is not set");
1437 ret = -EFAULT;
1441 * The frame is in FrameState_Done_Hold state. Release it
1442 * right now because its data is already mapped into
1443 * the user space and it's up to the application to
1444 * make use of it until it asks for another frame.
1446 uvd->frame[*frameNum].frameState = FrameState_Unused;
1447 return ret;
1449 case VIDIOCGFBUF:
1451 struct video_buffer *vb = arg;
1453 memset(vb, 0, sizeof(*vb));
1454 return 0;
1456 case VIDIOCKEY:
1457 return 0;
1459 case VIDIOCCAPTURE:
1460 return -EINVAL;
1462 case VIDIOCSFBUF:
1464 case VIDIOCGTUNER:
1465 case VIDIOCSTUNER:
1467 case VIDIOCGFREQ:
1468 case VIDIOCSFREQ:
1470 case VIDIOCGAUDIO:
1471 case VIDIOCSAUDIO:
1472 return -EINVAL;
1474 default:
1475 return -ENOIOCTLCMD;
1477 return 0;
1480 static int usbvideo_v4l_ioctl(struct inode *inode, struct file *file,
1481 unsigned int cmd, unsigned long arg)
1483 return video_usercopy(inode, file, cmd, arg, usbvideo_v4l_do_ioctl);
1487 * usbvideo_v4l_read()
1489 * This is mostly boring stuff. We simply ask for a frame and when it
1490 * arrives copy all the video data from it into user space. There is
1491 * no obvious need to override this method.
1493 * History:
1494 * 20-Oct-2000 Created.
1495 * 01-Nov-2000 Added mutex (uvd->lock).
1497 static ssize_t usbvideo_v4l_read(struct file *file, char __user *buf,
1498 size_t count, loff_t *ppos)
1500 struct uvd *uvd = file->private_data;
1501 int noblock = file->f_flags & O_NONBLOCK;
1502 int frmx = -1, i;
1503 struct usbvideo_frame *frame;
1505 if (!CAMERA_IS_OPERATIONAL(uvd) || (buf == NULL))
1506 return -EFAULT;
1508 if (uvd->debug >= 1)
1509 info("%s: %Zd. bytes, noblock=%d.", __func__, count, noblock);
1511 mutex_lock(&uvd->lock);
1513 /* See if a frame is completed, then use it. */
1514 for(i = 0; i < USBVIDEO_NUMFRAMES; i++) {
1515 if ((uvd->frame[i].frameState == FrameState_Done) ||
1516 (uvd->frame[i].frameState == FrameState_Done_Hold) ||
1517 (uvd->frame[i].frameState == FrameState_Error)) {
1518 frmx = i;
1519 break;
1523 /* FIXME: If we don't start a frame here then who ever does? */
1524 if (noblock && (frmx == -1)) {
1525 count = -EAGAIN;
1526 goto read_done;
1530 * If no FrameState_Done, look for a FrameState_Grabbing state.
1531 * See if a frame is in process (grabbing), then use it.
1532 * We will need to wait until it becomes cooked, of course.
1534 if (frmx == -1) {
1535 for(i = 0; i < USBVIDEO_NUMFRAMES; i++) {
1536 if (uvd->frame[i].frameState == FrameState_Grabbing) {
1537 frmx = i;
1538 break;
1544 * If no frame is active, start one. We don't care which one
1545 * it will be, so #0 is as good as any.
1546 * In read access mode we don't have convenience of VIDIOCMCAPTURE
1547 * to specify the requested palette (video format) on per-frame
1548 * basis. This means that we have to return data in -some- format
1549 * and just hope that the client knows what to do with it.
1550 * The default format is configured in uvd->defaultPalette field
1551 * as one of VIDEO_PALETTE_xxx values. We stuff it into the new
1552 * frame and initiate the frame filling process.
1554 if (frmx == -1) {
1555 if (uvd->defaultPalette == 0) {
1556 err("%s: No default palette; don't know what to do!", __func__);
1557 count = -EFAULT;
1558 goto read_done;
1560 frmx = 0;
1562 * We have no per-frame control over video size.
1563 * Therefore we only can use whatever size was
1564 * specified as default.
1566 uvd->frame[frmx].request = uvd->videosize;
1567 uvd->frame[frmx].palette = uvd->defaultPalette;
1568 uvd->frame[frmx].frameState = FrameState_Ready;
1569 usbvideo_NewFrame(uvd, frmx);
1570 /* Now frame 0 is supposed to start filling... */
1574 * Get a pointer to the active frame. It is either previously
1575 * completed frame or frame in progress but not completed yet.
1577 frame = &uvd->frame[frmx];
1580 * Sit back & wait until the frame gets filled and postprocessed.
1581 * If we fail to get the picture [in time] then return the error.
1582 * In this call we specify that we want the frame to be waited for,
1583 * postprocessed and switched into FrameState_Done_Hold state. This
1584 * state is used to hold the frame as "fully completed" between
1585 * subsequent partial reads of the same frame.
1587 if (frame->frameState != FrameState_Done_Hold) {
1588 long rv = -EFAULT;
1589 if (uvd->flags & FLAGS_NO_DECODING)
1590 rv = usbvideo_GetFrame(uvd, frmx);
1591 else if (VALID_CALLBACK(uvd, getFrame))
1592 rv = GET_CALLBACK(uvd, getFrame)(uvd, frmx);
1593 else
1594 err("getFrame is not set");
1595 if ((rv != 0) || (frame->frameState != FrameState_Done_Hold)) {
1596 count = rv;
1597 goto read_done;
1602 * Copy bytes to user space. We allow for partial reads, which
1603 * means that the user application can request read less than
1604 * the full frame size. It is up to the application to issue
1605 * subsequent calls until entire frame is read.
1607 * First things first, make sure we don't copy more than we
1608 * have - even if the application wants more. That would be
1609 * a big security embarassment!
1611 if ((count + frame->seqRead_Index) > frame->seqRead_Length)
1612 count = frame->seqRead_Length - frame->seqRead_Index;
1615 * Copy requested amount of data to user space. We start
1616 * copying from the position where we last left it, which
1617 * will be zero for a new frame (not read before).
1619 if (copy_to_user(buf, frame->data + frame->seqRead_Index, count)) {
1620 count = -EFAULT;
1621 goto read_done;
1624 /* Update last read position */
1625 frame->seqRead_Index += count;
1626 if (uvd->debug >= 1) {
1627 err("%s: {copy} count used=%Zd, new seqRead_Index=%ld",
1628 __func__, count, frame->seqRead_Index);
1631 /* Finally check if the frame is done with and "release" it */
1632 if (frame->seqRead_Index >= frame->seqRead_Length) {
1633 /* All data has been read */
1634 frame->seqRead_Index = 0;
1636 /* Mark it as available to be used again. */
1637 uvd->frame[frmx].frameState = FrameState_Unused;
1638 if (usbvideo_NewFrame(uvd, (frmx + 1) % USBVIDEO_NUMFRAMES)) {
1639 err("%s: usbvideo_NewFrame failed.", __func__);
1642 read_done:
1643 mutex_unlock(&uvd->lock);
1644 return count;
1648 * Make all of the blocks of data contiguous
1650 static int usbvideo_CompressIsochronous(struct uvd *uvd, struct urb *urb)
1652 char *cdata;
1653 int i, totlen = 0;
1655 for (i = 0; i < urb->number_of_packets; i++) {
1656 int n = urb->iso_frame_desc[i].actual_length;
1657 int st = urb->iso_frame_desc[i].status;
1659 cdata = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
1661 /* Detect and ignore errored packets */
1662 if (st < 0) {
1663 if (uvd->debug >= 1)
1664 err("Data error: packet=%d. len=%d. status=%d.", i, n, st);
1665 uvd->stats.iso_err_count++;
1666 continue;
1669 /* Detect and ignore empty packets */
1670 if (n <= 0) {
1671 uvd->stats.iso_skip_count++;
1672 continue;
1674 totlen += n; /* Little local accounting */
1675 RingQueue_Enqueue(&uvd->dp, cdata, n);
1677 return totlen;
1680 static void usbvideo_IsocIrq(struct urb *urb)
1682 int i, ret, len;
1683 struct uvd *uvd = urb->context;
1685 /* We don't want to do anything if we are about to be removed! */
1686 if (!CAMERA_IS_OPERATIONAL(uvd))
1687 return;
1688 #if 0
1689 if (urb->actual_length > 0) {
1690 info("urb=$%p status=%d. errcount=%d. length=%d.",
1691 urb, urb->status, urb->error_count, urb->actual_length);
1692 } else {
1693 static int c = 0;
1694 if (c++ % 100 == 0)
1695 info("No Isoc data");
1697 #endif
1699 if (!uvd->streaming) {
1700 if (uvd->debug >= 1)
1701 info("Not streaming, but interrupt!");
1702 return;
1705 uvd->stats.urb_count++;
1706 if (urb->actual_length <= 0)
1707 goto urb_done_with;
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;
1715 /* Here we got some data */
1716 uvd->stats.data_count += len;
1717 RingQueue_WakeUpInterruptible(&uvd->dp);
1719 urb_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;
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;
1733 * usbvideo_StartDataPump()
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.
1740 static int usbvideo_StartDataPump(struct uvd *uvd)
1742 struct usb_device *dev = uvd->dev;
1743 int i, errFlag;
1745 if (uvd->debug > 1)
1746 info("%s($%p)", __func__, uvd);
1748 if (!CAMERA_IS_OPERATIONAL(uvd)) {
1749 err("%s: Camera is not operational", __func__);
1750 return -EFAULT;
1752 uvd->curframe = -1;
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;
1761 if (VALID_CALLBACK(uvd, videoStart))
1762 GET_CALLBACK(uvd, videoStart)(uvd);
1763 else
1764 err("%s: videoStart not set", __func__);
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;
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);
1792 uvd->streaming = 1;
1793 if (uvd->debug > 1)
1794 info("%s: streaming=1 video_endp=$%02x", __func__, uvd->video_endp);
1795 return 0;
1799 * usbvideo_StopDataPump()
1801 * This procedure stops streaming and deallocates URBs. Then it
1802 * activates zero-bandwidth alt. setting of the video interface.
1804 * History:
1805 * 22-Jan-2000 Corrected order of actions to work after surprise removal.
1806 * 27-Jan-2000 Used uvd->iface, uvd->ifaceAltInactive instead of hardcoded values.
1808 static void usbvideo_StopDataPump(struct uvd *uvd)
1810 int i, j;
1812 if ((uvd == NULL) || (!uvd->streaming) || (uvd->dev == NULL))
1813 return;
1815 if (uvd->debug > 1)
1816 info("%s($%p)", __func__, uvd);
1818 /* Unschedule all of the iso td's */
1819 for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1820 usb_kill_urb(uvd->sbuf[i].urb);
1822 if (uvd->debug > 1)
1823 info("%s: streaming=0", __func__);
1824 uvd->streaming = 0;
1826 if (!uvd->remove_pending) {
1827 /* Invoke minidriver's magic to stop the camera */
1828 if (VALID_CALLBACK(uvd, videoStop))
1829 GET_CALLBACK(uvd, videoStop)(uvd);
1830 else
1831 err("%s: videoStop not set", __func__);
1833 /* Set packet size to 0 */
1834 j = usb_set_interface(uvd->dev, uvd->iface, uvd->ifaceAltInactive);
1835 if (j < 0) {
1836 err("%s: usb_set_interface() error %d.", __func__, j);
1837 uvd->last_error = j;
1843 * usbvideo_NewFrame()
1845 * History:
1846 * 29-Mar-00 Added copying of previous frame into the current one.
1847 * 6-Aug-00 Added model 3 video sizes, removed redundant width, height.
1849 static int usbvideo_NewFrame(struct uvd *uvd, int framenum)
1851 struct usbvideo_frame *frame;
1852 int n;
1854 if (uvd->debug > 1)
1855 info("usbvideo_NewFrame($%p,%d.)", uvd, framenum);
1857 /* If we're not grabbing a frame right now and the other frame is */
1858 /* ready to be grabbed into, then use it instead */
1859 if (uvd->curframe != -1)
1860 return 0;
1862 /* If necessary we adjust picture settings between frames */
1863 if (!uvd->settingsAdjusted) {
1864 if (VALID_CALLBACK(uvd, adjustPicture))
1865 GET_CALLBACK(uvd, adjustPicture)(uvd);
1866 uvd->settingsAdjusted = 1;
1869 n = (framenum + 1) % USBVIDEO_NUMFRAMES;
1870 if (uvd->frame[n].frameState == FrameState_Ready)
1871 framenum = n;
1873 frame = &uvd->frame[framenum];
1875 frame->frameState = FrameState_Grabbing;
1876 frame->scanstate = ScanState_Scanning;
1877 frame->seqRead_Length = 0; /* Accumulated in xxx_parse_data() */
1878 frame->deinterlace = Deinterlace_None;
1879 frame->flags = 0; /* No flags yet, up to minidriver (or us) to set them */
1880 uvd->curframe = framenum;
1883 * Normally we would want to copy previous frame into the current one
1884 * before we even start filling it with data; this allows us to stop
1885 * filling at any moment; top portion of the frame will be new and
1886 * bottom portion will stay as it was in previous frame. If we don't
1887 * do that then missing chunks of video stream will result in flickering
1888 * portions of old data whatever it was before.
1890 * If we choose not to copy previous frame (to, for example, save few
1891 * bus cycles - the frame can be pretty large!) then we have an option
1892 * to clear the frame before using. If we experience losses in this
1893 * mode then missing picture will be black (no flickering).
1895 * Finally, if user chooses not to clean the current frame before
1896 * filling it with data then the old data will be visible if we fail
1897 * to refill entire frame with new data.
1899 if (!(uvd->flags & FLAGS_SEPARATE_FRAMES)) {
1900 /* This copies previous frame into this one to mask losses */
1901 int prev = (framenum - 1 + USBVIDEO_NUMFRAMES) % USBVIDEO_NUMFRAMES;
1902 memmove(frame->data, uvd->frame[prev].data, uvd->max_frame_size);
1903 } else {
1904 if (uvd->flags & FLAGS_CLEAN_FRAMES) {
1905 /* This provides a "clean" frame but slows things down */
1906 memset(frame->data, 0, uvd->max_frame_size);
1909 return 0;
1913 * usbvideo_CollectRawData()
1915 * This procedure can be used instead of 'processData' callback if you
1916 * only want to dump the raw data from the camera into the output
1917 * device (frame buffer). You can look at it with V4L client, but the
1918 * image will be unwatchable. The main purpose of this code and of the
1919 * mode FLAGS_NO_DECODING is debugging and capturing of datastreams from
1920 * new, unknown cameras. This procedure will be automatically invoked
1921 * instead of the specified callback handler when uvd->flags has bit
1922 * FLAGS_NO_DECODING set. Therefore, any regular build of any driver
1923 * based on usbvideo can use this feature at any time.
1925 static void usbvideo_CollectRawData(struct uvd *uvd, struct usbvideo_frame *frame)
1927 int n;
1929 assert(uvd != NULL);
1930 assert(frame != NULL);
1932 /* Try to move data from queue into frame buffer */
1933 n = RingQueue_GetLength(&uvd->dp);
1934 if (n > 0) {
1935 int m;
1936 /* See how much space we have left */
1937 m = uvd->max_frame_size - frame->seqRead_Length;
1938 if (n > m)
1939 n = m;
1940 /* Now move that much data into frame buffer */
1941 RingQueue_Dequeue(
1942 &uvd->dp,
1943 frame->data + frame->seqRead_Length,
1945 frame->seqRead_Length += m;
1947 /* See if we filled the frame */
1948 if (frame->seqRead_Length >= uvd->max_frame_size) {
1949 frame->frameState = FrameState_Done;
1950 uvd->curframe = -1;
1951 uvd->stats.frame_num++;
1955 static int usbvideo_GetFrame(struct uvd *uvd, int frameNum)
1957 struct usbvideo_frame *frame = &uvd->frame[frameNum];
1959 if (uvd->debug >= 2)
1960 info("%s($%p,%d.)", __func__, uvd, frameNum);
1962 switch (frame->frameState) {
1963 case FrameState_Unused:
1964 if (uvd->debug >= 2)
1965 info("%s: FrameState_Unused", __func__);
1966 return -EINVAL;
1967 case FrameState_Ready:
1968 case FrameState_Grabbing:
1969 case FrameState_Error:
1971 int ntries, signalPending;
1972 redo:
1973 if (!CAMERA_IS_OPERATIONAL(uvd)) {
1974 if (uvd->debug >= 2)
1975 info("%s: Camera is not operational (1)", __func__);
1976 return -EIO;
1978 ntries = 0;
1979 do {
1980 RingQueue_InterruptibleSleepOn(&uvd->dp);
1981 signalPending = signal_pending(current);
1982 if (!CAMERA_IS_OPERATIONAL(uvd)) {
1983 if (uvd->debug >= 2)
1984 info("%s: Camera is not operational (2)", __func__);
1985 return -EIO;
1987 assert(uvd->fbuf != NULL);
1988 if (signalPending) {
1989 if (uvd->debug >= 2)
1990 info("%s: Signal=$%08x", __func__, signalPending);
1991 if (uvd->flags & FLAGS_RETRY_VIDIOCSYNC) {
1992 usbvideo_TestPattern(uvd, 1, 0);
1993 uvd->curframe = -1;
1994 uvd->stats.frame_num++;
1995 if (uvd->debug >= 2)
1996 info("%s: Forced test pattern screen", __func__);
1997 return 0;
1998 } else {
1999 /* Standard answer: Interrupted! */
2000 if (uvd->debug >= 2)
2001 info("%s: Interrupted!", __func__);
2002 return -EINTR;
2004 } else {
2005 /* No signals - we just got new data in dp queue */
2006 if (uvd->flags & FLAGS_NO_DECODING)
2007 usbvideo_CollectRawData(uvd, frame);
2008 else if (VALID_CALLBACK(uvd, processData))
2009 GET_CALLBACK(uvd, processData)(uvd, frame);
2010 else
2011 err("%s: processData not set", __func__);
2013 } while (frame->frameState == FrameState_Grabbing);
2014 if (uvd->debug >= 2) {
2015 info("%s: Grabbing done; state=%d. (%lu. bytes)",
2016 __func__, frame->frameState, frame->seqRead_Length);
2018 if (frame->frameState == FrameState_Error) {
2019 int ret = usbvideo_NewFrame(uvd, frameNum);
2020 if (ret < 0) {
2021 err("%s: usbvideo_NewFrame() failed (%d.)", __func__, ret);
2022 return ret;
2024 goto redo;
2026 /* Note that we fall through to meet our destiny below */
2028 case FrameState_Done:
2030 * Do all necessary postprocessing of data prepared in
2031 * "interrupt" code and the collecting code above. The
2032 * frame gets marked as FrameState_Done by queue parsing code.
2033 * This status means that we collected enough data and
2034 * most likely processed it as we went through. However
2035 * the data may need postprocessing, such as deinterlacing
2036 * or picture adjustments implemented in software (horror!)
2038 * As soon as the frame becomes "final" it gets promoted to
2039 * FrameState_Done_Hold status where it will remain until the
2040 * caller consumed all the video data from the frame. Then
2041 * the empty shell of ex-frame is thrown out for dogs to eat.
2042 * But we, worried about pets, will recycle the frame!
2044 uvd->stats.frame_num++;
2045 if ((uvd->flags & FLAGS_NO_DECODING) == 0) {
2046 if (VALID_CALLBACK(uvd, postProcess))
2047 GET_CALLBACK(uvd, postProcess)(uvd, frame);
2048 if (frame->flags & USBVIDEO_FRAME_FLAG_SOFTWARE_CONTRAST)
2049 usbvideo_SoftwareContrastAdjustment(uvd, frame);
2051 frame->frameState = FrameState_Done_Hold;
2052 if (uvd->debug >= 2)
2053 info("%s: Entered FrameState_Done_Hold state.", __func__);
2054 return 0;
2056 case FrameState_Done_Hold:
2058 * We stay in this state indefinitely until someone external,
2059 * like ioctl() or read() call finishes digesting the frame
2060 * data. Then it will mark the frame as FrameState_Unused and
2061 * it will be released back into the wild to roam freely.
2063 if (uvd->debug >= 2)
2064 info("%s: FrameState_Done_Hold state.", __func__);
2065 return 0;
2068 /* Catch-all for other cases. We shall not be here. */
2069 err("%s: Invalid state %d.", __func__, frame->frameState);
2070 frame->frameState = FrameState_Unused;
2071 return 0;
2075 * usbvideo_DeinterlaceFrame()
2077 * This procedure deinterlaces the given frame. Some cameras produce
2078 * only half of scanlines - sometimes only even lines, sometimes only
2079 * odd lines. The deinterlacing method is stored in frame->deinterlace
2080 * variable.
2082 * Here we scan the frame vertically and replace missing scanlines with
2083 * average between surrounding ones - before and after. If we have no
2084 * line above then we just copy next line. Similarly, if we need to
2085 * create a last line then preceding line is used.
2087 void usbvideo_DeinterlaceFrame(struct uvd *uvd, struct usbvideo_frame *frame)
2089 if ((uvd == NULL) || (frame == NULL))
2090 return;
2092 if ((frame->deinterlace == Deinterlace_FillEvenLines) ||
2093 (frame->deinterlace == Deinterlace_FillOddLines))
2095 const int v4l_linesize = VIDEOSIZE_X(frame->request) * V4L_BYTES_PER_PIXEL;
2096 int i = (frame->deinterlace == Deinterlace_FillEvenLines) ? 0 : 1;
2098 for (; i < VIDEOSIZE_Y(frame->request); i += 2) {
2099 const unsigned char *fs1, *fs2;
2100 unsigned char *fd;
2101 int ip, in, j; /* Previous and next lines */
2104 * Need to average lines before and after 'i'.
2105 * If we go out of bounds seeking those lines then
2106 * we point back to existing line.
2108 ip = i - 1; /* First, get rough numbers */
2109 in = i + 1;
2111 /* Now validate */
2112 if (ip < 0)
2113 ip = in;
2114 if (in >= VIDEOSIZE_Y(frame->request))
2115 in = ip;
2117 /* Sanity check */
2118 if ((ip < 0) || (in < 0) ||
2119 (ip >= VIDEOSIZE_Y(frame->request)) ||
2120 (in >= VIDEOSIZE_Y(frame->request)))
2122 err("Error: ip=%d. in=%d. req.height=%ld.",
2123 ip, in, VIDEOSIZE_Y(frame->request));
2124 break;
2127 /* Now we need to average lines 'ip' and 'in' to produce line 'i' */
2128 fs1 = frame->data + (v4l_linesize * ip);
2129 fs2 = frame->data + (v4l_linesize * in);
2130 fd = frame->data + (v4l_linesize * i);
2132 /* Average lines around destination */
2133 for (j=0; j < v4l_linesize; j++) {
2134 fd[j] = (unsigned char)((((unsigned) fs1[j]) +
2135 ((unsigned)fs2[j])) >> 1);
2140 /* Optionally display statistics on the screen */
2141 if (uvd->flags & FLAGS_OVERLAY_STATS)
2142 usbvideo_OverlayStats(uvd, frame);
2145 EXPORT_SYMBOL(usbvideo_DeinterlaceFrame);
2148 * usbvideo_SoftwareContrastAdjustment()
2150 * This code adjusts the contrast of the frame, assuming RGB24 format.
2151 * As most software image processing, this job is CPU-intensive.
2152 * Get a camera that supports hardware adjustment!
2154 * History:
2155 * 09-Feb-2001 Created.
2157 static void usbvideo_SoftwareContrastAdjustment(struct uvd *uvd,
2158 struct usbvideo_frame *frame)
2160 int i, j, v4l_linesize;
2161 signed long adj;
2162 const int ccm = 128; /* Color correction median - see below */
2164 if ((uvd == NULL) || (frame == NULL)) {
2165 err("%s: Illegal call.", __func__);
2166 return;
2168 adj = (uvd->vpic.contrast - 0x8000) >> 8; /* -128..+127 = -ccm..+(ccm-1)*/
2169 RESTRICT_TO_RANGE(adj, -ccm, ccm+1);
2170 if (adj == 0) {
2171 /* In rare case of no adjustment */
2172 return;
2174 v4l_linesize = VIDEOSIZE_X(frame->request) * V4L_BYTES_PER_PIXEL;
2175 for (i=0; i < VIDEOSIZE_Y(frame->request); i++) {
2176 unsigned char *fd = frame->data + (v4l_linesize * i);
2177 for (j=0; j < v4l_linesize; j++) {
2178 signed long v = (signed long) fd[j];
2179 /* Magnify up to 2 times, reduce down to zero */
2180 v = 128 + ((ccm + adj) * (v - 128)) / ccm;
2181 RESTRICT_TO_RANGE(v, 0, 0xFF); /* Must flatten tails */
2182 fd[j] = (unsigned char) v;
2187 MODULE_LICENSE("GPL");