usbvideo.c 58 KB

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