usbvideo.c 58 KB

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