usbvideo.c 59 KB

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