usbvideo.c 58 KB

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