usbvideo.c
上传用户:lgb322
上传日期:2013-02-24
资源大小:30529k
文件大小:64k
源码类别:

嵌入式Linux

开发平台:

Unix_Linux

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