usbvideo.c 59 KB

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