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)
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>
23 #include <linux/smp_lock.h>
24 #include <linux/vmalloc.h>
25 #include <linux/init.h>
26 #include <linux/spinlock.h>
33 #define virt_to_page(v) MAP_NR(v) /* Kernels 2.2.x */
36 static int video_nr = -1;
37 module_param(video_nr, int, 0);
42 static void usbvideo_Disconnect(struct usb_interface *intf);
43 static void usbvideo_CameraRelease(struct uvd *uvd);
45 static int usbvideo_v4l_ioctl(struct inode *inode, struct file *file,
46 unsigned int cmd, unsigned long arg);
47 static int usbvideo_v4l_mmap(struct file *file, struct vm_area_struct *vma);
48 static int usbvideo_v4l_open(struct inode *inode, struct file *file);
49 static ssize_t usbvideo_v4l_read(struct file *file, char __user *buf,
50 size_t count, loff_t *ppos);
51 static int usbvideo_v4l_close(struct inode *inode, struct file *file);
53 static int usbvideo_StartDataPump(struct uvd *uvd);
54 static void usbvideo_StopDataPump(struct uvd *uvd);
55 static int usbvideo_GetFrame(struct uvd *uvd, int frameNum);
56 static int usbvideo_NewFrame(struct uvd *uvd, int framenum);
57 static void usbvideo_SoftwareContrastAdjustment(struct uvd *uvd,
58 struct usbvideo_frame *frame);
60 /*******************************/
61 /* Memory management functions */
62 /*******************************/
65 * Here we want the physical address of the memory.
66 * This is used when initializing the contents of the area.
68 unsigned long usbvideo_kvirt_to_pa(unsigned long adr)
70 unsigned long kva, ret;
72 kva = (unsigned long) page_address(vmalloc_to_page((void *)adr));
73 kva |= adr & (PAGE_SIZE-1); /* restore the offset */
78 static void *usbvideo_rvmalloc(unsigned long size)
83 size = PAGE_ALIGN(size);
84 mem = vmalloc_32(size);
88 memset(mem, 0, size); /* Clear the ram out, no junk to the user */
89 adr = (unsigned long) mem;
91 SetPageReserved(vmalloc_to_page((void *)adr));
99 static void usbvideo_rvfree(void *mem, unsigned long size)
106 adr = (unsigned long) mem;
107 while ((long) size > 0) {
108 ClearPageReserved(vmalloc_to_page((void *)adr));
115 static void RingQueue_Initialize(struct RingQueue *rq)
118 init_waitqueue_head(&rq->wqh);
121 static void RingQueue_Allocate(struct RingQueue *rq, int rqLen)
123 /* Make sure the requested size is a power of 2 and
124 round up if necessary. This allows index wrapping
125 using masks rather than modulo */
133 if(rqLen != 1 << (i-1))
138 rq->queue = usbvideo_rvmalloc(rq->length);
139 assert(rq->queue != NULL);
142 static int RingQueue_IsAllocated(const struct RingQueue *rq)
146 return (rq->queue != NULL) && (rq->length > 0);
149 static void RingQueue_Free(struct RingQueue *rq)
152 if (RingQueue_IsAllocated(rq)) {
153 usbvideo_rvfree(rq->queue, rq->length);
159 int RingQueue_Dequeue(struct RingQueue *rq, unsigned char *dst, int len)
166 rql = RingQueue_GetLength(rq);
170 /* Clip requested length to available data */
175 if(rq->ri > rq->wi) {
176 /* Read data from tail */
177 int read = (toread < (rq->length - rq->ri)) ? toread : rq->length - rq->ri;
178 memcpy(dst, rq->queue + rq->ri, read);
181 rq->ri = (rq->ri + read) & (rq->length-1);
184 /* Read data from head */
185 memcpy(dst, rq->queue + rq->ri, toread);
186 rq->ri = (rq->ri + toread) & (rq->length-1);
191 EXPORT_SYMBOL(RingQueue_Dequeue);
193 int RingQueue_Enqueue(struct RingQueue *rq, const unsigned char *cdata, int n)
198 assert(cdata != NULL);
199 assert(rq->length > 0);
203 /* Calculate the largest chunk that fits the tail of the ring */
204 q_avail = rq->length - rq->wi;
207 q_avail = rq->length;
214 memcpy(rq->queue + rq->wi, cdata, m);
215 RING_QUEUE_ADVANCE_INDEX(rq, wi, m);
223 EXPORT_SYMBOL(RingQueue_Enqueue);
225 static void RingQueue_InterruptibleSleepOn(struct RingQueue *rq)
228 interruptible_sleep_on(&rq->wqh);
231 void RingQueue_WakeUpInterruptible(struct RingQueue *rq)
234 if (waitqueue_active(&rq->wqh))
235 wake_up_interruptible(&rq->wqh);
238 EXPORT_SYMBOL(RingQueue_WakeUpInterruptible);
240 void RingQueue_Flush(struct RingQueue *rq)
247 EXPORT_SYMBOL(RingQueue_Flush);
251 * usbvideo_VideosizeToString()
253 * This procedure converts given videosize value to readable string.
256 * 07-Aug-2000 Created.
257 * 19-Oct-2000 Reworked for usbvideo module.
259 static void usbvideo_VideosizeToString(char *buf, int bufLen, videosize_t vs)
264 n = 1 + sprintf(tmp, "%ldx%ld", VIDEOSIZE_X(vs), VIDEOSIZE_Y(vs));
265 assert(n < sizeof(tmp));
266 if ((buf == NULL) || (bufLen < n))
267 err("usbvideo_VideosizeToString: buffer is too small.");
269 memmove(buf, tmp, n);
273 * usbvideo_OverlayChar()
276 * 01-Feb-2000 Created.
278 static void usbvideo_OverlayChar(struct uvd *uvd, struct usbvideo_frame *frame,
279 int x, int y, int ch)
281 static const unsigned short digits[16] = {
299 unsigned short digit;
302 if ((uvd == NULL) || (frame == NULL))
305 if (ch >= '0' && ch <= '9')
307 else if (ch >= 'A' && ch <= 'F')
308 ch = 10 + (ch - 'A');
309 else if (ch >= 'a' && ch <= 'f')
310 ch = 10 + (ch - 'a');
315 for (iy=0; iy < 5; iy++) {
316 for (ix=0; ix < 3; ix++) {
317 if (digit & 0x8000) {
318 if (uvd->paletteBits & (1L << VIDEO_PALETTE_RGB24)) {
319 /* TODO */ RGB24_PUTPIXEL(frame, x+ix, y+iy, 0xFF, 0xFF, 0xFF);
328 * usbvideo_OverlayString()
331 * 01-Feb-2000 Created.
333 static void usbvideo_OverlayString(struct uvd *uvd, struct usbvideo_frame *frame,
334 int x, int y, const char *str)
337 usbvideo_OverlayChar(uvd, frame, x, y, *str);
339 x += 4; /* 3 pixels character + 1 space */
344 * usbvideo_OverlayStats()
346 * Overlays important debugging information.
349 * 01-Feb-2000 Created.
351 static void usbvideo_OverlayStats(struct uvd *uvd, struct usbvideo_frame *frame)
353 const int y_diff = 8;
356 long i, j, barLength;
357 const int qi_x1 = 60, qi_y1 = 10;
358 const int qi_x2 = VIDEOSIZE_X(frame->request) - 10, qi_h = 10;
360 /* Call the user callback, see if we may proceed after that */
361 if (VALID_CALLBACK(uvd, overlayHook)) {
362 if (GET_CALLBACK(uvd, overlayHook)(uvd, frame) < 0)
367 * We draw a (mostly) hollow rectangle with qi_xxx coordinates.
368 * Left edge symbolizes the queue index 0; right edge symbolizes
369 * the full capacity of the queue.
371 barLength = qi_x2 - qi_x1 - 2;
372 if ((barLength > 10) && (uvd->paletteBits & (1L << VIDEO_PALETTE_RGB24))) {
373 /* TODO */ long u_lo, u_hi, q_used;
374 long m_ri, m_wi, m_lo, m_hi;
377 * Determine fill zones (used areas of the queue):
378 * 0 xxxxxxx u_lo ...... uvd->dp.ri xxxxxxxx u_hi ..... uvd->dp.length
380 * if u_lo < 0 then there is no first filler.
383 q_used = RingQueue_GetLength(&uvd->dp);
384 if ((uvd->dp.ri + q_used) >= uvd->dp.length) {
385 u_hi = uvd->dp.length;
386 u_lo = (q_used + uvd->dp.ri) & (uvd->dp.length-1);
388 u_hi = (q_used + uvd->dp.ri);
392 /* Convert byte indices into screen units */
393 m_ri = qi_x1 + ((barLength * uvd->dp.ri) / uvd->dp.length);
394 m_wi = qi_x1 + ((barLength * uvd->dp.wi) / uvd->dp.length);
395 m_lo = (u_lo > 0) ? (qi_x1 + ((barLength * u_lo) / uvd->dp.length)) : -1;
396 m_hi = qi_x1 + ((barLength * u_hi) / uvd->dp.length);
398 for (j=qi_y1; j < (qi_y1 + qi_h); j++) {
399 for (i=qi_x1; i < qi_x2; i++) {
400 /* Draw border lines */
401 if ((j == qi_y1) || (j == (qi_y1 + qi_h - 1)) ||
402 (i == qi_x1) || (i == (qi_x2 - 1))) {
403 RGB24_PUTPIXEL(frame, i, j, 0xFF, 0xFF, 0xFF);
406 /* For all other points the Y coordinate does not matter */
407 if ((i >= m_ri) && (i <= (m_ri + 3))) {
408 RGB24_PUTPIXEL(frame, i, j, 0x00, 0xFF, 0x00);
409 } else if ((i >= m_wi) && (i <= (m_wi + 3))) {
410 RGB24_PUTPIXEL(frame, i, j, 0xFF, 0x00, 0x00);
411 } else if ((i < m_lo) || ((i > m_ri) && (i < m_hi)))
412 RGB24_PUTPIXEL(frame, i, j, 0x00, 0x00, 0xFF);
417 sprintf(tmp, "%8lx", uvd->stats.frame_num);
418 usbvideo_OverlayString(uvd, frame, x, y, tmp);
421 sprintf(tmp, "%8lx", uvd->stats.urb_count);
422 usbvideo_OverlayString(uvd, frame, x, y, tmp);
425 sprintf(tmp, "%8lx", uvd->stats.urb_length);
426 usbvideo_OverlayString(uvd, frame, x, y, tmp);
429 sprintf(tmp, "%8lx", uvd->stats.data_count);
430 usbvideo_OverlayString(uvd, frame, x, y, tmp);
433 sprintf(tmp, "%8lx", uvd->stats.header_count);
434 usbvideo_OverlayString(uvd, frame, x, y, tmp);
437 sprintf(tmp, "%8lx", uvd->stats.iso_skip_count);
438 usbvideo_OverlayString(uvd, frame, x, y, tmp);
441 sprintf(tmp, "%8lx", uvd->stats.iso_err_count);
442 usbvideo_OverlayString(uvd, frame, x, y, tmp);
445 sprintf(tmp, "%8x", uvd->vpic.colour);
446 usbvideo_OverlayString(uvd, frame, x, y, tmp);
449 sprintf(tmp, "%8x", uvd->vpic.hue);
450 usbvideo_OverlayString(uvd, frame, x, y, tmp);
453 sprintf(tmp, "%8x", uvd->vpic.brightness >> 8);
454 usbvideo_OverlayString(uvd, frame, x, y, tmp);
457 sprintf(tmp, "%8x", uvd->vpic.contrast >> 12);
458 usbvideo_OverlayString(uvd, frame, x, y, tmp);
461 sprintf(tmp, "%8d", uvd->vpic.whiteness >> 8);
462 usbvideo_OverlayString(uvd, frame, x, y, tmp);
467 * usbvideo_ReportStatistics()
469 * This procedure prints packet and transfer statistics.
472 * 14-Jan-2000 Corrected default multiplier.
474 static void usbvideo_ReportStatistics(const struct uvd *uvd)
476 if ((uvd != NULL) && (uvd->stats.urb_count > 0)) {
477 unsigned long allPackets, badPackets, goodPackets, percent;
478 allPackets = uvd->stats.urb_count * CAMERA_URB_FRAMES;
479 badPackets = uvd->stats.iso_skip_count + uvd->stats.iso_err_count;
480 goodPackets = allPackets - badPackets;
481 /* Calculate percentage wisely, remember integer limits */
482 assert(allPackets != 0);
483 if (goodPackets < (((unsigned long)-1)/100))
484 percent = (100 * goodPackets) / allPackets;
486 percent = goodPackets / (allPackets / 100);
487 info("Packet Statistics: Total=%lu. Empty=%lu. Usage=%lu%%",
488 allPackets, badPackets, percent);
489 if (uvd->iso_packet_len > 0) {
490 unsigned long allBytes, xferBytes;
491 char multiplier = ' ';
492 allBytes = allPackets * uvd->iso_packet_len;
493 xferBytes = uvd->stats.data_count;
494 assert(allBytes != 0);
495 if (xferBytes < (((unsigned long)-1)/100))
496 percent = (100 * xferBytes) / allBytes;
498 percent = xferBytes / (allBytes / 100);
499 /* Scale xferBytes for easy reading */
500 if (xferBytes > 10*1024) {
503 if (xferBytes > 10*1024) {
506 if (xferBytes > 10*1024) {
509 if (xferBytes > 10*1024) {
516 info("Transfer Statistics: Transferred=%lu%cB Usage=%lu%%",
517 xferBytes, multiplier, percent);
523 * usbvideo_DrawLine()
525 * A standard implementation of Bresenham's line drawing algorithm.
526 * This procedure is provided primarily for debugging or demo
529 void usbvideo_DrawLine(
530 struct usbvideo_frame *frame,
533 unsigned char cr, unsigned char cg, unsigned char cb)
535 int i, dx, dy, np, d;
536 int dinc1, dinc2, x, xinc1, xinc2, y, yinc1, yinc2;
538 if ((dx = x2 - x1) < 0)
540 if ((dy = y2 - y1) < 0)
546 dinc2 = (dy - dx) << 1;
555 dinc2 = (dx - dy) << 1;
561 /* Make sure x and y move in the right directions */
570 for (i=0, x=x1, y=y1; i < np; i++) {
571 if (frame->palette == VIDEO_PALETTE_RGB24) {
572 /* TODO */ RGB24_PUTPIXEL(frame, x, y, cr, cg, cb);
586 EXPORT_SYMBOL(usbvideo_DrawLine);
589 * usbvideo_TestPattern()
591 * Procedure forms a test pattern (yellow grid on blue background).
594 * fullframe: if TRUE then entire frame is filled, otherwise the procedure
595 * continues from the current scanline.
596 * pmode 0: fill the frame with solid blue color (like on VCR or TV)
597 * 1: Draw a colored grid
600 * 01-Feb-2000 Created.
602 void usbvideo_TestPattern(struct uvd *uvd, int fullframe, int pmode)
604 struct usbvideo_frame *frame;
607 static int num_pass = 0;
610 err("%s: uvd == NULL", __FUNCTION__);
613 if ((uvd->curframe < 0) || (uvd->curframe >= USBVIDEO_NUMFRAMES)) {
614 err("%s: uvd->curframe=%d.", __FUNCTION__, uvd->curframe);
618 /* Grab the current frame */
619 frame = &uvd->frame[uvd->curframe];
621 /* Optionally start at the beginning */
624 frame->seqRead_Length = 0;
627 { /* For debugging purposes only */
629 usbvideo_VideosizeToString(tmp, sizeof(tmp), frame->request);
630 info("testpattern: frame=%s", tmp);
633 /* Form every scan line */
634 for (; frame->curline < VIDEOSIZE_Y(frame->request); frame->curline++) {
636 unsigned char *f = frame->data +
637 (VIDEOSIZE_X(frame->request) * V4L_BYTES_PER_PIXEL * frame->curline);
638 for (i=0; i < VIDEOSIZE_X(frame->request); i++) {
639 unsigned char cb=0x80;
640 unsigned char cg = 0;
641 unsigned char cr = 0;
644 if (frame->curline % 32 == 0)
645 cb = 0, cg = cr = 0xFF;
646 else if (i % 32 == 0) {
647 if (frame->curline % 32 == 1)
649 cb = 0, cg = cr = 0xFF;
651 cb = ((num_cell*7) + num_pass) & 0xFF;
652 cg = ((num_cell*5) + num_pass*2) & 0xFF;
653 cr = ((num_cell*3) + num_pass*3) & 0xFF;
656 /* Just the blue screen */
666 frame->frameState = FrameState_Done;
667 frame->seqRead_Length += scan_length;
670 /* We do this unconditionally, regardless of FLAGS_OVERLAY_STATS */
671 usbvideo_OverlayStats(uvd, frame);
674 EXPORT_SYMBOL(usbvideo_TestPattern);
679 * A debugging tool. Prints hex dumps.
682 * 29-Jul-2000 Added printing of offsets.
684 void usbvideo_HexDump(const unsigned char *data, int len)
686 const int bytes_per_line = 32;
687 char tmp[128]; /* 32*3 + 5 */
690 for (i=k=0; len > 0; i++, len--) {
691 if (i > 0 && ((i % bytes_per_line) == 0)) {
695 if ((i % bytes_per_line) == 0)
696 k += sprintf(&tmp[k], "%04x: ", i);
697 k += sprintf(&tmp[k], "%02x ", data[i]);
703 EXPORT_SYMBOL(usbvideo_HexDump);
706 void usbvideo_SayAndWait(const char *what)
708 wait_queue_head_t wq;
709 init_waitqueue_head(&wq);
710 info("Say: %s", what);
711 interruptible_sleep_on_timeout (&wq, HZ*3); /* Timeout */
714 EXPORT_SYMBOL(usbvideo_SayAndWait);
716 /* ******************************************************************** */
718 /* XXX: this piece of crap really wants some error handling.. */
719 static void usbvideo_ClientIncModCount(struct uvd *uvd)
722 err("%s: uvd == NULL", __FUNCTION__);
725 if (uvd->handle == NULL) {
726 err("%s: uvd->handle == NULL", __FUNCTION__);
729 if (uvd->handle->md_module == NULL) {
730 err("%s: uvd->handle->md_module == NULL", __FUNCTION__);
733 if (!try_module_get(uvd->handle->md_module)) {
734 err("%s: try_module_get() == 0", __FUNCTION__);
739 static void usbvideo_ClientDecModCount(struct uvd *uvd)
742 err("%s: uvd == NULL", __FUNCTION__);
745 if (uvd->handle == NULL) {
746 err("%s: uvd->handle == NULL", __FUNCTION__);
749 if (uvd->handle->md_module == NULL) {
750 err("%s: uvd->handle->md_module == NULL", __FUNCTION__);
753 module_put(uvd->handle->md_module);
756 int usbvideo_register(
757 struct usbvideo **pCams,
760 const char *driverName,
761 const struct usbvideo_cb *cbTbl,
763 const struct usb_device_id *id_table)
765 struct usbvideo *cams;
766 int i, base_size, result;
768 /* Check parameters for sanity */
769 if ((num_cams <= 0) || (pCams == NULL) || (cbTbl == NULL)) {
770 err("%s: Illegal call", __FUNCTION__);
774 /* Check registration callback - must be set! */
775 if (cbTbl->probe == NULL) {
776 err("%s: probe() is required!", __FUNCTION__);
780 base_size = num_cams * sizeof(struct uvd) + sizeof(struct usbvideo);
781 cams = (struct usbvideo *) kmalloc(base_size, GFP_KERNEL);
783 err("Failed to allocate %d. bytes for usbvideo struct", base_size);
786 dbg("%s: Allocated $%p (%d. bytes) for %d. cameras",
787 __FUNCTION__, cams, base_size, num_cams);
788 memset(cams, 0, base_size);
790 /* Copy callbacks, apply defaults for those that are not set */
791 memmove(&cams->cb, cbTbl, sizeof(cams->cb));
792 if (cams->cb.getFrame == NULL)
793 cams->cb.getFrame = usbvideo_GetFrame;
794 if (cams->cb.disconnect == NULL)
795 cams->cb.disconnect = usbvideo_Disconnect;
796 if (cams->cb.startDataPump == NULL)
797 cams->cb.startDataPump = usbvideo_StartDataPump;
798 if (cams->cb.stopDataPump == NULL)
799 cams->cb.stopDataPump = usbvideo_StopDataPump;
801 cams->num_cameras = num_cams;
802 cams->cam = (struct uvd *) &cams[1];
803 cams->md_module = md;
804 if (cams->md_module == NULL)
805 warn("%s: module == NULL!", __FUNCTION__);
806 init_MUTEX(&cams->lock); /* to 1 == available */
808 for (i = 0; i < num_cams; i++) {
809 struct uvd *up = &cams->cam[i];
813 /* Allocate user_data separately because of kmalloc's limits */
815 up->user_size = num_cams * num_extra;
816 up->user_data = (char *) kmalloc(up->user_size, GFP_KERNEL);
817 if (up->user_data == NULL) {
818 err("%s: Failed to allocate user_data (%d. bytes)",
819 __FUNCTION__, up->user_size);
821 up = &cams->cam[--i];
822 kfree(up->user_data);
827 dbg("%s: Allocated cams[%d].user_data=$%p (%d. bytes)",
828 __FUNCTION__, i, up->user_data, up->user_size);
833 * Register ourselves with USB stack.
835 strcpy(cams->drvName, (driverName != NULL) ? driverName : "Unknown");
836 cams->usbdrv.name = cams->drvName;
837 cams->usbdrv.probe = cams->cb.probe;
838 cams->usbdrv.disconnect = cams->cb.disconnect;
839 cams->usbdrv.id_table = id_table;
842 * Update global handle to usbvideo. This is very important
843 * because probe() can be called before usb_register() returns.
844 * If the handle is not yet updated then the probe() will fail.
847 result = usb_register(&cams->usbdrv);
849 for (i = 0; i < num_cams; i++) {
850 struct uvd *up = &cams->cam[i];
851 kfree(up->user_data);
859 EXPORT_SYMBOL(usbvideo_register);
862 * usbvideo_Deregister()
864 * Procedure frees all usbvideo and user data structures. Be warned that
865 * if you had some dynamically allocated components in ->user field then
866 * you should free them before calling here.
868 void usbvideo_Deregister(struct usbvideo **pCams)
870 struct usbvideo *cams;
874 err("%s: pCams == NULL", __FUNCTION__);
879 err("%s: cams == NULL", __FUNCTION__);
883 dbg("%s: Deregistering %s driver.", __FUNCTION__, cams->drvName);
884 usb_deregister(&cams->usbdrv);
886 dbg("%s: Deallocating cams=$%p (%d. cameras)", __FUNCTION__, cams, cams->num_cameras);
887 for (i=0; i < cams->num_cameras; i++) {
888 struct uvd *up = &cams->cam[i];
891 if (up->user_data != NULL) {
892 if (up->user_size <= 0)
895 if (up->user_size > 0)
899 err("%s: Warning: user_data=$%p user_size=%d.",
900 __FUNCTION__, up->user_data, up->user_size);
902 dbg("%s: Freeing %d. $%p->user_data=$%p",
903 __FUNCTION__, i, up, up->user_data);
904 kfree(up->user_data);
907 /* Whole array was allocated in one chunk */
908 dbg("%s: Freed %d uvd structures",
909 __FUNCTION__, cams->num_cameras);
914 EXPORT_SYMBOL(usbvideo_Deregister);
917 * usbvideo_Disconnect()
919 * This procedure stops all driver activity. Deallocation of
920 * the interface-private structure (pointed by 'ptr') is done now
921 * (if we don't have any open files) or later, when those files
922 * are closed. After that driver should be removable.
924 * This code handles surprise removal. The uvd->user is a counter which
925 * increments on open() and decrements on close(). If we see here that
926 * this counter is not 0 then we have a client who still has us opened.
927 * We set uvd->remove_pending flag as early as possible, and after that
928 * all access to the camera will gracefully fail. These failures should
929 * prompt client to (eventually) close the video device, and then - in
930 * usbvideo_v4l_close() - we decrement uvd->uvd_used and usage counter.
933 * 22-Jan-2000 Added polling of MOD_IN_USE to delay removal until all users gone.
934 * 27-Jan-2000 Reworked to allow pending disconnects; see xxx_close()
935 * 24-May-2000 Corrected to prevent race condition (MOD_xxx_USE_COUNT).
936 * 19-Oct-2000 Moved to usbvideo module.
938 static void usbvideo_Disconnect(struct usb_interface *intf)
940 struct uvd *uvd = usb_get_intfdata (intf);
944 err("%s($%p): Illegal call.", __FUNCTION__, intf);
948 usb_set_intfdata (intf, NULL);
950 usbvideo_ClientIncModCount(uvd);
952 info("%s(%p.)", __FUNCTION__, intf);
955 uvd->remove_pending = 1; /* Now all ISO data will be ignored */
957 /* At this time we ask to cancel outstanding URBs */
958 GET_CALLBACK(uvd, stopDataPump)(uvd);
960 for (i=0; i < USBVIDEO_NUMSBUF; i++)
961 usb_free_urb(uvd->sbuf[i].urb);
963 usb_put_dev(uvd->dev);
964 uvd->dev = NULL; /* USB device is no more */
966 video_unregister_device(&uvd->vdev);
968 info("%s: Video unregistered.", __FUNCTION__);
971 info("%s: In use, disconnect pending.", __FUNCTION__);
973 usbvideo_CameraRelease(uvd);
975 info("USB camera disconnected.");
977 usbvideo_ClientDecModCount(uvd);
981 * usbvideo_CameraRelease()
983 * This code does final release of uvd. This happens
984 * after the device is disconnected -and- all clients
985 * closed their files.
988 * 27-Jan-2000 Created.
990 static void usbvideo_CameraRelease(struct uvd *uvd)
993 err("%s: Illegal call", __FUNCTION__);
997 RingQueue_Free(&uvd->dp);
998 if (VALID_CALLBACK(uvd, userFree))
999 GET_CALLBACK(uvd, userFree)(uvd);
1000 uvd->uvd_used = 0; /* This is atomic, no need to take mutex */
1004 * usbvideo_find_struct()
1006 * This code searches the array of preallocated (static) structures
1007 * and returns index of the first one that isn't in use. Returns -1
1008 * if there are no free structures.
1011 * 27-Jan-2000 Created.
1013 static int usbvideo_find_struct(struct usbvideo *cams)
1018 err("No usbvideo handle?");
1022 for (u = 0; u < cams->num_cameras; u++) {
1023 struct uvd *uvd = &cams->cam[u];
1024 if (!uvd->uvd_used) /* This one is free */
1026 uvd->uvd_used = 1; /* In use now */
1027 init_MUTEX(&uvd->lock); /* to 1 == available */
1037 static struct file_operations usbvideo_fops = {
1038 .owner = THIS_MODULE,
1039 .open = usbvideo_v4l_open,
1040 .release =usbvideo_v4l_close,
1041 .read = usbvideo_v4l_read,
1042 .mmap = usbvideo_v4l_mmap,
1043 .ioctl = usbvideo_v4l_ioctl,
1044 .llseek = no_llseek,
1046 static struct video_device usbvideo_template = {
1047 .owner = THIS_MODULE,
1048 .type = VID_TYPE_CAPTURE,
1049 .hardware = VID_HARDWARE_CPIA,
1050 .fops = &usbvideo_fops,
1053 struct uvd *usbvideo_AllocateDevice(struct usbvideo *cams)
1056 struct uvd *uvd = NULL;
1059 err("No usbvideo handle?");
1063 devnum = usbvideo_find_struct(cams);
1065 err("IBM USB camera driver: Too many devices!");
1068 uvd = &cams->cam[devnum];
1069 dbg("Device entry #%d. at $%p", devnum, uvd);
1071 /* Not relying upon caller we increase module counter ourselves */
1072 usbvideo_ClientIncModCount(uvd);
1075 for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1076 uvd->sbuf[i].urb = usb_alloc_urb(FRAMES_PER_DESC, GFP_KERNEL);
1077 if (uvd->sbuf[i].urb == NULL) {
1078 err("usb_alloc_urb(%d.) failed.", FRAMES_PER_DESC);
1085 uvd->remove_pending = 0;
1086 uvd->last_error = 0;
1087 RingQueue_Initialize(&uvd->dp);
1089 /* Initialize video device structure */
1090 uvd->vdev = usbvideo_template;
1091 sprintf(uvd->vdev.name, "%.20s USB Camera", cams->drvName);
1093 * The client is free to overwrite those because we
1094 * return control to the client's probe function right now.
1098 usbvideo_ClientDecModCount(uvd);
1102 EXPORT_SYMBOL(usbvideo_AllocateDevice);
1104 int usbvideo_RegisterVideoDevice(struct uvd *uvd)
1106 char tmp1[20], tmp2[20]; /* Buffers for printing */
1109 err("%s: Illegal call.", __FUNCTION__);
1112 if (uvd->video_endp == 0) {
1113 info("%s: No video endpoint specified; data pump disabled.", __FUNCTION__);
1115 if (uvd->paletteBits == 0) {
1116 err("%s: No palettes specified!", __FUNCTION__);
1119 if (uvd->defaultPalette == 0) {
1120 info("%s: No default palette!", __FUNCTION__);
1123 uvd->max_frame_size = VIDEOSIZE_X(uvd->canvas) *
1124 VIDEOSIZE_Y(uvd->canvas) * V4L_BYTES_PER_PIXEL;
1125 usbvideo_VideosizeToString(tmp1, sizeof(tmp1), uvd->videosize);
1126 usbvideo_VideosizeToString(tmp2, sizeof(tmp2), uvd->canvas);
1128 if (uvd->debug > 0) {
1129 info("%s: iface=%d. endpoint=$%02x paletteBits=$%08lx",
1130 __FUNCTION__, uvd->iface, uvd->video_endp, uvd->paletteBits);
1132 if (video_register_device(&uvd->vdev, VFL_TYPE_GRABBER, video_nr) == -1) {
1133 err("%s: video_register_device failed", __FUNCTION__);
1136 if (uvd->debug > 1) {
1137 info("%s: video_register_device() successful", __FUNCTION__);
1139 if (uvd->dev == NULL) {
1140 err("%s: uvd->dev == NULL", __FUNCTION__);
1144 info("%s on /dev/video%d: canvas=%s videosize=%s",
1145 (uvd->handle != NULL) ? uvd->handle->drvName : "???",
1146 uvd->vdev.minor, tmp2, tmp1);
1148 usb_get_dev(uvd->dev);
1152 EXPORT_SYMBOL(usbvideo_RegisterVideoDevice);
1154 /* ******************************************************************** */
1156 static int usbvideo_v4l_mmap(struct file *file, struct vm_area_struct *vma)
1158 struct uvd *uvd = file->private_data;
1159 unsigned long start = vma->vm_start;
1160 unsigned long size = vma->vm_end-vma->vm_start;
1161 unsigned long page, pos;
1163 if (!CAMERA_IS_OPERATIONAL(uvd))
1166 if (size > (((USBVIDEO_NUMFRAMES * uvd->max_frame_size) + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1)))
1169 pos = (unsigned long) uvd->fbuf;
1171 page = usbvideo_kvirt_to_pa(pos);
1172 if (remap_page_range(vma, start, page, PAGE_SIZE, PAGE_SHARED))
1177 if (size > PAGE_SIZE)
1187 * usbvideo_v4l_open()
1189 * This is part of Video 4 Linux API. The driver can be opened by one
1190 * client only (checks internal counter 'uvdser'). The procedure
1191 * then allocates buffers needed for video processing.
1194 * 22-Jan-2000 Rewrote, moved scratch buffer allocation here. Now the
1195 * camera is also initialized here (once per connect), at
1196 * expense of V4L client (it waits on open() call).
1197 * 27-Jan-2000 Used USBVIDEO_NUMSBUF as number of URB buffers.
1198 * 24-May-2000 Corrected to prevent race condition (MOD_xxx_USE_COUNT).
1200 static int usbvideo_v4l_open(struct inode *inode, struct file *file)
1202 struct video_device *dev = video_devdata(file);
1203 struct uvd *uvd = (struct uvd *) dev;
1204 const int sb_size = FRAMES_PER_DESC * uvd->iso_packet_len;
1208 info("%s($%p)", __FUNCTION__, dev);
1210 usbvideo_ClientIncModCount(uvd);
1214 err("%s: Someone tried to open an already opened device!", __FUNCTION__);
1217 /* Clear statistics */
1218 memset(&uvd->stats, 0, sizeof(uvd->stats));
1220 /* Clean pointers so we know if we allocated something */
1221 for (i=0; i < USBVIDEO_NUMSBUF; i++)
1222 uvd->sbuf[i].data = NULL;
1224 /* Allocate memory for the frame buffers */
1225 uvd->fbuf_size = USBVIDEO_NUMFRAMES * uvd->max_frame_size;
1226 uvd->fbuf = usbvideo_rvmalloc(uvd->fbuf_size);
1227 RingQueue_Allocate(&uvd->dp, RING_QUEUE_SIZE);
1228 if ((uvd->fbuf == NULL) ||
1229 (!RingQueue_IsAllocated(&uvd->dp))) {
1230 err("%s: Failed to allocate fbuf or dp", __FUNCTION__);
1233 /* Allocate all buffers */
1234 for (i=0; i < USBVIDEO_NUMFRAMES; i++) {
1235 uvd->frame[i].frameState = FrameState_Unused;
1236 uvd->frame[i].data = uvd->fbuf + i*(uvd->max_frame_size);
1238 * Set default sizes in case IOCTL (VIDIOCMCAPTURE)
1239 * is not used (using read() instead).
1241 uvd->frame[i].canvas = uvd->canvas;
1242 uvd->frame[i].seqRead_Index = 0;
1244 for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1245 uvd->sbuf[i].data = kmalloc(sb_size, GFP_KERNEL);
1246 if (uvd->sbuf[i].data == NULL) {
1253 /* Have to free all that memory */
1254 if (uvd->fbuf != NULL) {
1255 usbvideo_rvfree(uvd->fbuf, uvd->fbuf_size);
1258 RingQueue_Free(&uvd->dp);
1259 for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1260 if (uvd->sbuf[i].data != NULL) {
1261 kfree (uvd->sbuf[i].data);
1262 uvd->sbuf[i].data = NULL;
1268 /* If so far no errors then we shall start the camera */
1270 /* Start data pump if we have valid endpoint */
1271 if (uvd->video_endp != 0)
1272 errCode = GET_CALLBACK(uvd, startDataPump)(uvd);
1274 if (VALID_CALLBACK(uvd, setupOnOpen)) {
1276 info("%s: setupOnOpen callback", __FUNCTION__);
1277 errCode = GET_CALLBACK(uvd, setupOnOpen)(uvd);
1279 err("%s: setupOnOpen callback failed (%d.).",
1280 __FUNCTION__, errCode);
1281 } else if (uvd->debug > 1) {
1282 info("%s: setupOnOpen callback successful", __FUNCTION__);
1286 uvd->settingsAdjusted = 0;
1288 info("%s: Open succeeded.", __FUNCTION__);
1290 file->private_data = uvd;
1296 usbvideo_ClientDecModCount(uvd);
1298 info("%s: Returning %d.", __FUNCTION__, errCode);
1303 * usbvideo_v4l_close()
1305 * This is part of Video 4 Linux API. The procedure
1306 * stops streaming and deallocates all buffers that were earlier
1307 * allocated in usbvideo_v4l_open().
1310 * 22-Jan-2000 Moved scratch buffer deallocation here.
1311 * 27-Jan-2000 Used USBVIDEO_NUMSBUF as number of URB buffers.
1312 * 24-May-2000 Moved MOD_DEC_USE_COUNT outside of code that can sleep.
1314 static int usbvideo_v4l_close(struct inode *inode, struct file *file)
1316 struct video_device *dev = file->private_data;
1317 struct uvd *uvd = (struct uvd *) dev;
1321 info("%s($%p)", __FUNCTION__, dev);
1324 GET_CALLBACK(uvd, stopDataPump)(uvd);
1325 usbvideo_rvfree(uvd->fbuf, uvd->fbuf_size);
1327 RingQueue_Free(&uvd->dp);
1329 for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1330 kfree(uvd->sbuf[i].data);
1331 uvd->sbuf[i].data = NULL;
1334 #if USBVIDEO_REPORT_STATS
1335 usbvideo_ReportStatistics(uvd);
1339 if (uvd->remove_pending) {
1341 info("usbvideo_v4l_close: Final disconnect.");
1342 usbvideo_CameraRelease(uvd);
1345 usbvideo_ClientDecModCount(uvd);
1348 info("%s: Completed.", __FUNCTION__);
1349 file->private_data = NULL;
1354 * usbvideo_v4l_ioctl()
1356 * This is part of Video 4 Linux API. The procedure handles ioctl() calls.
1359 * 22-Jan-2000 Corrected VIDIOCSPICT to reject unsupported settings.
1361 static int usbvideo_v4l_do_ioctl(struct inode *inode, struct file *file,
1362 unsigned int cmd, void *arg)
1364 struct uvd *uvd = file->private_data;
1366 if (!CAMERA_IS_OPERATIONAL(uvd))
1372 struct video_capability *b = arg;
1378 struct video_channel *v = arg;
1384 struct video_channel *v = arg;
1385 if (v->channel != 0)
1391 struct video_picture *pic = arg;
1397 struct video_picture *pic = arg;
1399 * Use temporary 'video_picture' structure to preserve our
1400 * own settings (such as color depth, palette) that we
1401 * aren't allowing everyone (V4L client) to change.
1403 uvd->vpic.brightness = pic->brightness;
1404 uvd->vpic.hue = pic->hue;
1405 uvd->vpic.colour = pic->colour;
1406 uvd->vpic.contrast = pic->contrast;
1407 uvd->settingsAdjusted = 0; /* Will force new settings */
1412 struct video_window *vw = arg;
1414 if(VALID_CALLBACK(uvd, setVideoMode)) {
1415 return GET_CALLBACK(uvd, setVideoMode)(uvd, vw);
1422 if (vw->width != VIDEOSIZE_X(uvd->canvas))
1424 if (vw->height != VIDEOSIZE_Y(uvd->canvas))
1431 struct video_window *vw = arg;
1435 vw->width = VIDEOSIZE_X(uvd->videosize);
1436 vw->height = VIDEOSIZE_Y(uvd->videosize);
1438 if (VALID_CALLBACK(uvd, getFPS))
1439 vw->flags = GET_CALLBACK(uvd, getFPS)(uvd);
1441 vw->flags = 10; /* FIXME: do better! */
1446 struct video_mbuf *vm = arg;
1449 memset(vm, 0, sizeof(*vm));
1450 vm->size = uvd->max_frame_size * USBVIDEO_NUMFRAMES;
1451 vm->frames = USBVIDEO_NUMFRAMES;
1452 for(i = 0; i < USBVIDEO_NUMFRAMES; i++)
1453 vm->offsets[i] = i * uvd->max_frame_size;
1457 case VIDIOCMCAPTURE:
1459 struct video_mmap *vm = arg;
1461 if (uvd->debug >= 1) {
1462 info("VIDIOCMCAPTURE: frame=%d. size=%dx%d, format=%d.",
1463 vm->frame, vm->width, vm->height, vm->format);
1466 * Check if the requested size is supported. If the requestor
1467 * requests too big a frame then we may be tricked into accessing
1468 * outside of own preallocated frame buffer (in uvd->frame).
1469 * This will cause oops or a security hole. Theoretically, we
1470 * could only clamp the size down to acceptable bounds, but then
1471 * we'd need to figure out how to insert our smaller buffer into
1472 * larger caller's buffer... this is not an easy question. So we
1473 * here just flatly reject too large requests, assuming that the
1474 * caller will resubmit with smaller size. Callers should know
1475 * what size we support (returned by VIDIOCGCAP). However vidcat,
1476 * for one, does not care and allows to ask for any size.
1478 if ((vm->width > VIDEOSIZE_X(uvd->canvas)) ||
1479 (vm->height > VIDEOSIZE_Y(uvd->canvas))) {
1480 if (uvd->debug > 0) {
1481 info("VIDIOCMCAPTURE: Size=%dx%d too large; "
1482 "allowed only up to %ldx%ld", vm->width, vm->height,
1483 VIDEOSIZE_X(uvd->canvas), VIDEOSIZE_Y(uvd->canvas));
1487 /* Check if the palette is supported */
1488 if (((1L << vm->format) & uvd->paletteBits) == 0) {
1489 if (uvd->debug > 0) {
1490 info("VIDIOCMCAPTURE: format=%d. not supported"
1491 " (paletteBits=$%08lx)",
1492 vm->format, uvd->paletteBits);
1496 if ((vm->frame < 0) || (vm->frame >= USBVIDEO_NUMFRAMES)) {
1497 err("VIDIOCMCAPTURE: vm.frame=%d. !E [0-%d]", vm->frame, USBVIDEO_NUMFRAMES-1);
1500 if (uvd->frame[vm->frame].frameState == FrameState_Grabbing) {
1501 /* Not an error - can happen */
1503 uvd->frame[vm->frame].request = VIDEOSIZE(vm->width, vm->height);
1504 uvd->frame[vm->frame].palette = vm->format;
1506 /* Mark it as ready */
1507 uvd->frame[vm->frame].frameState = FrameState_Ready;
1509 return usbvideo_NewFrame(uvd, vm->frame);
1513 int *frameNum = arg;
1516 if (*frameNum < 0 || *frameNum >= USBVIDEO_NUMFRAMES)
1519 if (uvd->debug >= 1)
1520 info("VIDIOCSYNC: syncing to frame %d.", *frameNum);
1521 if (uvd->flags & FLAGS_NO_DECODING)
1522 ret = usbvideo_GetFrame(uvd, *frameNum);
1523 else if (VALID_CALLBACK(uvd, getFrame)) {
1524 ret = GET_CALLBACK(uvd, getFrame)(uvd, *frameNum);
1525 if ((ret < 0) && (uvd->debug >= 1)) {
1526 err("VIDIOCSYNC: getFrame() returned %d.", ret);
1529 err("VIDIOCSYNC: getFrame is not set");
1534 * The frame is in FrameState_Done_Hold state. Release it
1535 * right now because its data is already mapped into
1536 * the user space and it's up to the application to
1537 * make use of it until it asks for another frame.
1539 uvd->frame[*frameNum].frameState = FrameState_Unused;
1544 struct video_buffer *vb = arg;
1546 memset(vb, 0, sizeof(*vb));
1568 return -ENOIOCTLCMD;
1573 static int usbvideo_v4l_ioctl(struct inode *inode, struct file *file,
1574 unsigned int cmd, unsigned long arg)
1576 return video_usercopy(inode, file, cmd, arg, usbvideo_v4l_do_ioctl);
1580 * usbvideo_v4l_read()
1582 * This is mostly boring stuff. We simply ask for a frame and when it
1583 * arrives copy all the video data from it into user space. There is
1584 * no obvious need to override this method.
1587 * 20-Oct-2000 Created.
1588 * 01-Nov-2000 Added mutex (uvd->lock).
1590 static ssize_t usbvideo_v4l_read(struct file *file, char __user *buf,
1591 size_t count, loff_t *ppos)
1593 struct uvd *uvd = file->private_data;
1594 int noblock = file->f_flags & O_NONBLOCK;
1596 struct usbvideo_frame *frame;
1598 if (!CAMERA_IS_OPERATIONAL(uvd) || (buf == NULL))
1601 if (uvd->debug >= 1)
1602 info("%s: %Zd. bytes, noblock=%d.", __FUNCTION__, count, noblock);
1606 /* See if a frame is completed, then use it. */
1607 for(i = 0; i < USBVIDEO_NUMFRAMES; i++) {
1608 if ((uvd->frame[i].frameState == FrameState_Done) ||
1609 (uvd->frame[i].frameState == FrameState_Done_Hold) ||
1610 (uvd->frame[i].frameState == FrameState_Error)) {
1616 /* FIXME: If we don't start a frame here then who ever does? */
1617 if (noblock && (frmx == -1)) {
1623 * If no FrameState_Done, look for a FrameState_Grabbing state.
1624 * See if a frame is in process (grabbing), then use it.
1625 * We will need to wait until it becomes cooked, of course.
1628 for(i = 0; i < USBVIDEO_NUMFRAMES; i++) {
1629 if (uvd->frame[i].frameState == FrameState_Grabbing) {
1637 * If no frame is active, start one. We don't care which one
1638 * it will be, so #0 is as good as any.
1639 * In read access mode we don't have convenience of VIDIOCMCAPTURE
1640 * to specify the requested palette (video format) on per-frame
1641 * basis. This means that we have to return data in -some- format
1642 * and just hope that the client knows what to do with it.
1643 * The default format is configured in uvd->defaultPalette field
1644 * as one of VIDEO_PALETTE_xxx values. We stuff it into the new
1645 * frame and initiate the frame filling process.
1648 if (uvd->defaultPalette == 0) {
1649 err("%s: No default palette; don't know what to do!", __FUNCTION__);
1655 * We have no per-frame control over video size.
1656 * Therefore we only can use whatever size was
1657 * specified as default.
1659 uvd->frame[frmx].request = uvd->videosize;
1660 uvd->frame[frmx].palette = uvd->defaultPalette;
1661 uvd->frame[frmx].frameState = FrameState_Ready;
1662 usbvideo_NewFrame(uvd, frmx);
1663 /* Now frame 0 is supposed to start filling... */
1667 * Get a pointer to the active frame. It is either previously
1668 * completed frame or frame in progress but not completed yet.
1670 frame = &uvd->frame[frmx];
1673 * Sit back & wait until the frame gets filled and postprocessed.
1674 * If we fail to get the picture [in time] then return the error.
1675 * In this call we specify that we want the frame to be waited for,
1676 * postprocessed and switched into FrameState_Done_Hold state. This
1677 * state is used to hold the frame as "fully completed" between
1678 * subsequent partial reads of the same frame.
1680 if (frame->frameState != FrameState_Done_Hold) {
1682 if (uvd->flags & FLAGS_NO_DECODING)
1683 rv = usbvideo_GetFrame(uvd, frmx);
1684 else if (VALID_CALLBACK(uvd, getFrame))
1685 rv = GET_CALLBACK(uvd, getFrame)(uvd, frmx);
1687 err("getFrame is not set");
1688 if ((rv != 0) || (frame->frameState != FrameState_Done_Hold)) {
1695 * Copy bytes to user space. We allow for partial reads, which
1696 * means that the user application can request read less than
1697 * the full frame size. It is up to the application to issue
1698 * subsequent calls until entire frame is read.
1700 * First things first, make sure we don't copy more than we
1701 * have - even if the application wants more. That would be
1702 * a big security embarassment!
1704 if ((count + frame->seqRead_Index) > frame->seqRead_Length)
1705 count = frame->seqRead_Length - frame->seqRead_Index;
1708 * Copy requested amount of data to user space. We start
1709 * copying from the position where we last left it, which
1710 * will be zero for a new frame (not read before).
1712 if (copy_to_user(buf, frame->data + frame->seqRead_Index, count)) {
1717 /* Update last read position */
1718 frame->seqRead_Index += count;
1719 if (uvd->debug >= 1) {
1720 err("%s: {copy} count used=%Zd, new seqRead_Index=%ld",
1721 __FUNCTION__, count, frame->seqRead_Index);
1724 /* Finally check if the frame is done with and "release" it */
1725 if (frame->seqRead_Index >= frame->seqRead_Length) {
1726 /* All data has been read */
1727 frame->seqRead_Index = 0;
1729 /* Mark it as available to be used again. */
1730 uvd->frame[frmx].frameState = FrameState_Unused;
1731 if (usbvideo_NewFrame(uvd, (frmx + 1) % USBVIDEO_NUMFRAMES)) {
1732 err("%s: usbvideo_NewFrame failed.", __FUNCTION__);
1741 * Make all of the blocks of data contiguous
1743 static int usbvideo_CompressIsochronous(struct uvd *uvd, struct urb *urb)
1748 for (i = 0; i < urb->number_of_packets; i++) {
1749 int n = urb->iso_frame_desc[i].actual_length;
1750 int st = urb->iso_frame_desc[i].status;
1752 cdata = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
1754 /* Detect and ignore errored packets */
1756 if (uvd->debug >= 1)
1757 err("Data error: packet=%d. len=%d. status=%d.", i, n, st);
1758 uvd->stats.iso_err_count++;
1762 /* Detect and ignore empty packets */
1764 uvd->stats.iso_skip_count++;
1767 totlen += n; /* Little local accounting */
1768 RingQueue_Enqueue(&uvd->dp, cdata, n);
1773 static void usbvideo_IsocIrq(struct urb *urb, struct pt_regs *regs)
1776 struct uvd *uvd = urb->context;
1778 /* We don't want to do anything if we are about to be removed! */
1779 if (!CAMERA_IS_OPERATIONAL(uvd))
1782 if (urb->actual_length > 0) {
1783 info("urb=$%p status=%d. errcount=%d. length=%d.",
1784 urb, urb->status, urb->error_count, urb->actual_length);
1788 info("No Isoc data");
1792 if (!uvd->streaming) {
1793 if (uvd->debug >= 1)
1794 info("Not streaming, but interrupt!");
1798 uvd->stats.urb_count++;
1799 if (urb->actual_length <= 0)
1802 /* Copy the data received into ring queue */
1803 len = usbvideo_CompressIsochronous(uvd, urb);
1804 uvd->stats.urb_length = len;
1808 /* Here we got some data */
1809 uvd->stats.data_count += len;
1810 RingQueue_WakeUpInterruptible(&uvd->dp);
1813 for (i = 0; i < FRAMES_PER_DESC; i++) {
1814 urb->iso_frame_desc[i].status = 0;
1815 urb->iso_frame_desc[i].actual_length = 0;
1818 urb->dev = uvd->dev;
1819 ret = usb_submit_urb (urb, GFP_KERNEL);
1821 err("usb_submit_urb error (%d)", ret);
1826 * usbvideo_StartDataPump()
1829 * 27-Jan-2000 Used ibmcam->iface, ibmcam->ifaceAltActive instead
1830 * of hardcoded values. Simplified by using for loop,
1831 * allowed any number of URBs.
1833 static int usbvideo_StartDataPump(struct uvd *uvd)
1835 struct usb_device *dev = uvd->dev;
1839 info("%s($%p)", __FUNCTION__, uvd);
1841 if (!CAMERA_IS_OPERATIONAL(uvd)) {
1842 err("%s: Camera is not operational", __FUNCTION__);
1847 /* Alternate interface 1 is is the biggest frame size */
1848 i = usb_set_interface(dev, uvd->iface, uvd->ifaceAltActive);
1850 err("%s: usb_set_interface error", __FUNCTION__);
1851 uvd->last_error = i;
1854 if (VALID_CALLBACK(uvd, videoStart))
1855 GET_CALLBACK(uvd, videoStart)(uvd);
1857 err("%s: videoStart not set", __FUNCTION__);
1859 /* We double buffer the Iso lists */
1860 for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1862 struct urb *urb = uvd->sbuf[i].urb;
1865 urb->pipe = usb_rcvisocpipe(dev, uvd->video_endp);
1867 urb->transfer_flags = URB_ISO_ASAP;
1868 urb->transfer_buffer = uvd->sbuf[i].data;
1869 urb->complete = usbvideo_IsocIrq;
1870 urb->number_of_packets = FRAMES_PER_DESC;
1871 urb->transfer_buffer_length = uvd->iso_packet_len * FRAMES_PER_DESC;
1872 for (j=k=0; j < FRAMES_PER_DESC; j++, k += uvd->iso_packet_len) {
1873 urb->iso_frame_desc[j].offset = k;
1874 urb->iso_frame_desc[j].length = uvd->iso_packet_len;
1878 /* Submit all URBs */
1879 for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1880 errFlag = usb_submit_urb(uvd->sbuf[i].urb, GFP_KERNEL);
1882 err("%s: usb_submit_isoc(%d) ret %d", __FUNCTION__, i, errFlag);
1887 info("%s: streaming=1 video_endp=$%02x", __FUNCTION__, uvd->video_endp);
1892 * usbvideo_StopDataPump()
1894 * This procedure stops streaming and deallocates URBs. Then it
1895 * activates zero-bandwidth alt. setting of the video interface.
1898 * 22-Jan-2000 Corrected order of actions to work after surprise removal.
1899 * 27-Jan-2000 Used uvd->iface, uvd->ifaceAltInactive instead of hardcoded values.
1901 static void usbvideo_StopDataPump(struct uvd *uvd)
1906 info("%s($%p)", __FUNCTION__, uvd);
1908 if ((uvd == NULL) || (!uvd->streaming) || (uvd->dev == NULL))
1911 /* Unschedule all of the iso td's */
1912 for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1913 j = usb_unlink_urb(uvd->sbuf[i].urb);
1915 err("%s: usb_unlink_urb() error %d.", __FUNCTION__, j);
1918 info("%s: streaming=0", __FUNCTION__);
1921 if (!uvd->remove_pending) {
1922 /* Invoke minidriver's magic to stop the camera */
1923 if (VALID_CALLBACK(uvd, videoStop))
1924 GET_CALLBACK(uvd, videoStop)(uvd);
1926 err("%s: videoStop not set", __FUNCTION__);
1928 /* Set packet size to 0 */
1929 j = usb_set_interface(uvd->dev, uvd->iface, uvd->ifaceAltInactive);
1931 err("%s: usb_set_interface() error %d.", __FUNCTION__, j);
1932 uvd->last_error = j;
1938 * usbvideo_NewFrame()
1941 * 29-Mar-00 Added copying of previous frame into the current one.
1942 * 6-Aug-00 Added model 3 video sizes, removed redundant width, height.
1944 static int usbvideo_NewFrame(struct uvd *uvd, int framenum)
1946 struct usbvideo_frame *frame;
1950 info("usbvideo_NewFrame($%p,%d.)", uvd, framenum);
1952 /* If we're not grabbing a frame right now and the other frame is */
1953 /* ready to be grabbed into, then use it instead */
1954 if (uvd->curframe != -1)
1957 /* If necessary we adjust picture settings between frames */
1958 if (!uvd->settingsAdjusted) {
1959 if (VALID_CALLBACK(uvd, adjustPicture))
1960 GET_CALLBACK(uvd, adjustPicture)(uvd);
1961 uvd->settingsAdjusted = 1;
1964 n = (framenum + 1) % USBVIDEO_NUMFRAMES;
1965 if (uvd->frame[n].frameState == FrameState_Ready)
1968 frame = &uvd->frame[framenum];
1970 frame->frameState = FrameState_Grabbing;
1971 frame->scanstate = ScanState_Scanning;
1972 frame->seqRead_Length = 0; /* Accumulated in xxx_parse_data() */
1973 frame->deinterlace = Deinterlace_None;
1974 frame->flags = 0; /* No flags yet, up to minidriver (or us) to set them */
1975 uvd->curframe = framenum;
1978 * Normally we would want to copy previous frame into the current one
1979 * before we even start filling it with data; this allows us to stop
1980 * filling at any moment; top portion of the frame will be new and
1981 * bottom portion will stay as it was in previous frame. If we don't
1982 * do that then missing chunks of video stream will result in flickering
1983 * portions of old data whatever it was before.
1985 * If we choose not to copy previous frame (to, for example, save few
1986 * bus cycles - the frame can be pretty large!) then we have an option
1987 * to clear the frame before using. If we experience losses in this
1988 * mode then missing picture will be black (no flickering).
1990 * Finally, if user chooses not to clean the current frame before
1991 * filling it with data then the old data will be visible if we fail
1992 * to refill entire frame with new data.
1994 if (!(uvd->flags & FLAGS_SEPARATE_FRAMES)) {
1995 /* This copies previous frame into this one to mask losses */
1996 int prev = (framenum - 1 + USBVIDEO_NUMFRAMES) % USBVIDEO_NUMFRAMES;
1997 memmove(frame->data, uvd->frame[prev].data, uvd->max_frame_size);
1999 if (uvd->flags & FLAGS_CLEAN_FRAMES) {
2000 /* This provides a "clean" frame but slows things down */
2001 memset(frame->data, 0, uvd->max_frame_size);
2008 * usbvideo_CollectRawData()
2010 * This procedure can be used instead of 'processData' callback if you
2011 * only want to dump the raw data from the camera into the output
2012 * device (frame buffer). You can look at it with V4L client, but the
2013 * image will be unwatchable. The main purpose of this code and of the
2014 * mode FLAGS_NO_DECODING is debugging and capturing of datastreams from
2015 * new, unknown cameras. This procedure will be automatically invoked
2016 * instead of the specified callback handler when uvd->flags has bit
2017 * FLAGS_NO_DECODING set. Therefore, any regular build of any driver
2018 * based on usbvideo can use this feature at any time.
2020 static void usbvideo_CollectRawData(struct uvd *uvd, struct usbvideo_frame *frame)
2024 assert(uvd != NULL);
2025 assert(frame != NULL);
2027 /* Try to move data from queue into frame buffer */
2028 n = RingQueue_GetLength(&uvd->dp);
2031 /* See how much space we have left */
2032 m = uvd->max_frame_size - frame->seqRead_Length;
2035 /* Now move that much data into frame buffer */
2038 frame->data + frame->seqRead_Length,
2040 frame->seqRead_Length += m;
2042 /* See if we filled the frame */
2043 if (frame->seqRead_Length >= uvd->max_frame_size) {
2044 frame->frameState = FrameState_Done;
2046 uvd->stats.frame_num++;
2050 static int usbvideo_GetFrame(struct uvd *uvd, int frameNum)
2052 struct usbvideo_frame *frame = &uvd->frame[frameNum];
2054 if (uvd->debug >= 2)
2055 info("%s($%p,%d.)", __FUNCTION__, uvd, frameNum);
2057 switch (frame->frameState) {
2058 case FrameState_Unused:
2059 if (uvd->debug >= 2)
2060 info("%s: FrameState_Unused", __FUNCTION__);
2062 case FrameState_Ready:
2063 case FrameState_Grabbing:
2064 case FrameState_Error:
2066 int ntries, signalPending;
2068 if (!CAMERA_IS_OPERATIONAL(uvd)) {
2069 if (uvd->debug >= 2)
2070 info("%s: Camera is not operational (1)", __FUNCTION__);
2075 RingQueue_InterruptibleSleepOn(&uvd->dp);
2076 signalPending = signal_pending(current);
2077 if (!CAMERA_IS_OPERATIONAL(uvd)) {
2078 if (uvd->debug >= 2)
2079 info("%s: Camera is not operational (2)", __FUNCTION__);
2082 assert(uvd->fbuf != NULL);
2083 if (signalPending) {
2084 if (uvd->debug >= 2)
2085 info("%s: Signal=$%08x", __FUNCTION__, signalPending);
2086 if (uvd->flags & FLAGS_RETRY_VIDIOCSYNC) {
2087 usbvideo_TestPattern(uvd, 1, 0);
2089 uvd->stats.frame_num++;
2090 if (uvd->debug >= 2)
2091 info("%s: Forced test pattern screen", __FUNCTION__);
2094 /* Standard answer: Interrupted! */
2095 if (uvd->debug >= 2)
2096 info("%s: Interrupted!", __FUNCTION__);
2100 /* No signals - we just got new data in dp queue */
2101 if (uvd->flags & FLAGS_NO_DECODING)
2102 usbvideo_CollectRawData(uvd, frame);
2103 else if (VALID_CALLBACK(uvd, processData))
2104 GET_CALLBACK(uvd, processData)(uvd, frame);
2106 err("%s: processData not set", __FUNCTION__);
2108 } while (frame->frameState == FrameState_Grabbing);
2109 if (uvd->debug >= 2) {
2110 info("%s: Grabbing done; state=%d. (%lu. bytes)",
2111 __FUNCTION__, frame->frameState, frame->seqRead_Length);
2113 if (frame->frameState == FrameState_Error) {
2114 int ret = usbvideo_NewFrame(uvd, frameNum);
2116 err("%s: usbvideo_NewFrame() failed (%d.)", __FUNCTION__, ret);
2121 /* Note that we fall through to meet our destiny below */
2123 case FrameState_Done:
2125 * Do all necessary postprocessing of data prepared in
2126 * "interrupt" code and the collecting code above. The
2127 * frame gets marked as FrameState_Done by queue parsing code.
2128 * This status means that we collected enough data and
2129 * most likely processed it as we went through. However
2130 * the data may need postprocessing, such as deinterlacing
2131 * or picture adjustments implemented in software (horror!)
2133 * As soon as the frame becomes "final" it gets promoted to
2134 * FrameState_Done_Hold status where it will remain until the
2135 * caller consumed all the video data from the frame. Then
2136 * the empty shell of ex-frame is thrown out for dogs to eat.
2137 * But we, worried about pets, will recycle the frame!
2139 uvd->stats.frame_num++;
2140 if ((uvd->flags & FLAGS_NO_DECODING) == 0) {
2141 if (VALID_CALLBACK(uvd, postProcess))
2142 GET_CALLBACK(uvd, postProcess)(uvd, frame);
2143 if (frame->flags & USBVIDEO_FRAME_FLAG_SOFTWARE_CONTRAST)
2144 usbvideo_SoftwareContrastAdjustment(uvd, frame);
2146 frame->frameState = FrameState_Done_Hold;
2147 if (uvd->debug >= 2)
2148 info("%s: Entered FrameState_Done_Hold state.", __FUNCTION__);
2151 case FrameState_Done_Hold:
2153 * We stay in this state indefinitely until someone external,
2154 * like ioctl() or read() call finishes digesting the frame
2155 * data. Then it will mark the frame as FrameState_Unused and
2156 * it will be released back into the wild to roam freely.
2158 if (uvd->debug >= 2)
2159 info("%s: FrameState_Done_Hold state.", __FUNCTION__);
2163 /* Catch-all for other cases. We shall not be here. */
2164 err("%s: Invalid state %d.", __FUNCTION__, frame->frameState);
2165 frame->frameState = FrameState_Unused;
2170 * usbvideo_DeinterlaceFrame()
2172 * This procedure deinterlaces the given frame. Some cameras produce
2173 * only half of scanlines - sometimes only even lines, sometimes only
2174 * odd lines. The deinterlacing method is stored in frame->deinterlace
2177 * Here we scan the frame vertically and replace missing scanlines with
2178 * average between surrounding ones - before and after. If we have no
2179 * line above then we just copy next line. Similarly, if we need to
2180 * create a last line then preceding line is used.
2182 void usbvideo_DeinterlaceFrame(struct uvd *uvd, struct usbvideo_frame *frame)
2184 if ((uvd == NULL) || (frame == NULL))
2187 if ((frame->deinterlace == Deinterlace_FillEvenLines) ||
2188 (frame->deinterlace == Deinterlace_FillOddLines))
2190 const int v4l_linesize = VIDEOSIZE_X(frame->request) * V4L_BYTES_PER_PIXEL;
2191 int i = (frame->deinterlace == Deinterlace_FillEvenLines) ? 0 : 1;
2193 for (; i < VIDEOSIZE_Y(frame->request); i += 2) {
2194 const unsigned char *fs1, *fs2;
2196 int ip, in, j; /* Previous and next lines */
2199 * Need to average lines before and after 'i'.
2200 * If we go out of bounds seeking those lines then
2201 * we point back to existing line.
2203 ip = i - 1; /* First, get rough numbers */
2209 if (in >= VIDEOSIZE_Y(frame->request))
2213 if ((ip < 0) || (in < 0) ||
2214 (ip >= VIDEOSIZE_Y(frame->request)) ||
2215 (in >= VIDEOSIZE_Y(frame->request)))
2217 err("Error: ip=%d. in=%d. req.height=%ld.",
2218 ip, in, VIDEOSIZE_Y(frame->request));
2222 /* Now we need to average lines 'ip' and 'in' to produce line 'i' */
2223 fs1 = frame->data + (v4l_linesize * ip);
2224 fs2 = frame->data + (v4l_linesize * in);
2225 fd = frame->data + (v4l_linesize * i);
2227 /* Average lines around destination */
2228 for (j=0; j < v4l_linesize; j++) {
2229 fd[j] = (unsigned char)((((unsigned) fs1[j]) +
2230 ((unsigned)fs2[j])) >> 1);
2235 /* Optionally display statistics on the screen */
2236 if (uvd->flags & FLAGS_OVERLAY_STATS)
2237 usbvideo_OverlayStats(uvd, frame);
2240 EXPORT_SYMBOL(usbvideo_DeinterlaceFrame);
2243 * usbvideo_SoftwareContrastAdjustment()
2245 * This code adjusts the contrast of the frame, assuming RGB24 format.
2246 * As most software image processing, this job is CPU-intensive.
2247 * Get a camera that supports hardware adjustment!
2250 * 09-Feb-2001 Created.
2252 static void usbvideo_SoftwareContrastAdjustment(struct uvd *uvd,
2253 struct usbvideo_frame *frame)
2255 int i, j, v4l_linesize;
2257 const int ccm = 128; /* Color correction median - see below */
2259 if ((uvd == NULL) || (frame == NULL)) {
2260 err("%s: Illegal call.", __FUNCTION__);
2263 adj = (uvd->vpic.contrast - 0x8000) >> 8; /* -128..+127 = -ccm..+(ccm-1)*/
2264 RESTRICT_TO_RANGE(adj, -ccm, ccm+1);
2266 /* In rare case of no adjustment */
2269 v4l_linesize = VIDEOSIZE_X(frame->request) * V4L_BYTES_PER_PIXEL;
2270 for (i=0; i < VIDEOSIZE_Y(frame->request); i++) {
2271 unsigned char *fd = frame->data + (v4l_linesize * i);
2272 for (j=0; j < v4l_linesize; j++) {
2273 signed long v = (signed long) fd[j];
2274 /* Magnify up to 2 times, reduce down to zero */
2275 v = 128 + ((ccm + adj) * (v - 128)) / ccm;
2276 RESTRICT_TO_RANGE(v, 0, 0xFF); /* Must flatten tails */
2277 fd[j] = (unsigned char) v;
2282 MODULE_LICENSE("GPL");