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