usbvideo.c 58 KB

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