usbvideo.c 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234
  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 long usbvideo_v4l_ioctl(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 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 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 v4l2_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. };
  835. static const struct video_device usbvideo_template = {
  836. .fops = &usbvideo_fops,
  837. };
  838. struct uvd *usbvideo_AllocateDevice(struct usbvideo *cams)
  839. {
  840. int i, devnum;
  841. struct uvd *uvd = NULL;
  842. if (cams == NULL) {
  843. err("No usbvideo handle?");
  844. return NULL;
  845. }
  846. devnum = usbvideo_find_struct(cams);
  847. if (devnum == -1) {
  848. err("IBM USB camera driver: Too many devices!");
  849. return NULL;
  850. }
  851. uvd = &cams->cam[devnum];
  852. dbg("Device entry #%d. at $%p", devnum, uvd);
  853. /* Not relying upon caller we increase module counter ourselves */
  854. usbvideo_ClientIncModCount(uvd);
  855. mutex_lock(&uvd->lock);
  856. for (i=0; i < USBVIDEO_NUMSBUF; i++) {
  857. uvd->sbuf[i].urb = usb_alloc_urb(FRAMES_PER_DESC, GFP_KERNEL);
  858. if (uvd->sbuf[i].urb == NULL) {
  859. err("usb_alloc_urb(%d.) failed.", FRAMES_PER_DESC);
  860. uvd->uvd_used = 0;
  861. uvd = NULL;
  862. goto allocate_done;
  863. }
  864. }
  865. uvd->user=0;
  866. uvd->remove_pending = 0;
  867. uvd->last_error = 0;
  868. RingQueue_Initialize(&uvd->dp);
  869. /* Initialize video device structure */
  870. uvd->vdev = usbvideo_template;
  871. sprintf(uvd->vdev.name, "%.20s USB Camera", cams->drvName);
  872. /*
  873. * The client is free to overwrite those because we
  874. * return control to the client's probe function right now.
  875. */
  876. allocate_done:
  877. mutex_unlock(&uvd->lock);
  878. usbvideo_ClientDecModCount(uvd);
  879. return uvd;
  880. }
  881. EXPORT_SYMBOL(usbvideo_AllocateDevice);
  882. int usbvideo_RegisterVideoDevice(struct uvd *uvd)
  883. {
  884. char tmp1[20], tmp2[20]; /* Buffers for printing */
  885. if (uvd == NULL) {
  886. err("%s: Illegal call.", __func__);
  887. return -EINVAL;
  888. }
  889. if (uvd->video_endp == 0) {
  890. dev_info(&uvd->dev->dev,
  891. "%s: No video endpoint specified; data pump disabled.\n",
  892. __func__);
  893. }
  894. if (uvd->paletteBits == 0) {
  895. err("%s: No palettes specified!", __func__);
  896. return -EINVAL;
  897. }
  898. if (uvd->defaultPalette == 0) {
  899. dev_info(&uvd->dev->dev, "%s: No default palette!\n",
  900. __func__);
  901. }
  902. uvd->max_frame_size = VIDEOSIZE_X(uvd->canvas) *
  903. VIDEOSIZE_Y(uvd->canvas) * V4L_BYTES_PER_PIXEL;
  904. usbvideo_VideosizeToString(tmp1, sizeof(tmp1), uvd->videosize);
  905. usbvideo_VideosizeToString(tmp2, sizeof(tmp2), uvd->canvas);
  906. if (uvd->debug > 0) {
  907. dev_info(&uvd->dev->dev,
  908. "%s: iface=%d. endpoint=$%02x paletteBits=$%08lx\n",
  909. __func__, uvd->iface, uvd->video_endp,
  910. uvd->paletteBits);
  911. }
  912. if (uvd->dev == NULL) {
  913. err("%s: uvd->dev == NULL", __func__);
  914. return -EINVAL;
  915. }
  916. uvd->vdev.parent = &uvd->dev->dev;
  917. uvd->vdev.release = video_device_release_empty;
  918. if (video_register_device(&uvd->vdev, VFL_TYPE_GRABBER, video_nr) < 0) {
  919. err("%s: video_register_device failed", __func__);
  920. return -EPIPE;
  921. }
  922. if (uvd->debug > 1) {
  923. dev_info(&uvd->dev->dev,
  924. "%s: video_register_device() successful\n", __func__);
  925. }
  926. dev_info(&uvd->dev->dev, "%s on /dev/video%d: canvas=%s videosize=%s\n",
  927. (uvd->handle != NULL) ? uvd->handle->drvName : "???",
  928. uvd->vdev.num, 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 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. dev_info(&uvd->dev->dev, "%s($%p)\n", __func__, dev);
  980. if (usbvideo_ClientIncModCount(uvd) < 0)
  981. return -ENODEV;
  982. mutex_lock(&uvd->lock);
  983. if (uvd->user) {
  984. err("%s: Someone tried to open an already opened device!", __func__);
  985. errCode = -EBUSY;
  986. } else {
  987. /* Clear statistics */
  988. memset(&uvd->stats, 0, sizeof(uvd->stats));
  989. /* Clean pointers so we know if we allocated something */
  990. for (i=0; i < USBVIDEO_NUMSBUF; i++)
  991. uvd->sbuf[i].data = NULL;
  992. /* Allocate memory for the frame buffers */
  993. uvd->fbuf_size = USBVIDEO_NUMFRAMES * uvd->max_frame_size;
  994. uvd->fbuf = usbvideo_rvmalloc(uvd->fbuf_size);
  995. RingQueue_Allocate(&uvd->dp, RING_QUEUE_SIZE);
  996. if ((uvd->fbuf == NULL) ||
  997. (!RingQueue_IsAllocated(&uvd->dp))) {
  998. err("%s: Failed to allocate fbuf or dp", __func__);
  999. errCode = -ENOMEM;
  1000. } else {
  1001. /* Allocate all buffers */
  1002. for (i=0; i < USBVIDEO_NUMFRAMES; i++) {
  1003. uvd->frame[i].frameState = FrameState_Unused;
  1004. uvd->frame[i].data = uvd->fbuf + i*(uvd->max_frame_size);
  1005. /*
  1006. * Set default sizes in case IOCTL (VIDIOCMCAPTURE)
  1007. * is not used (using read() instead).
  1008. */
  1009. uvd->frame[i].canvas = uvd->canvas;
  1010. uvd->frame[i].seqRead_Index = 0;
  1011. }
  1012. for (i=0; i < USBVIDEO_NUMSBUF; i++) {
  1013. uvd->sbuf[i].data = kmalloc(sb_size, GFP_KERNEL);
  1014. if (uvd->sbuf[i].data == NULL) {
  1015. errCode = -ENOMEM;
  1016. break;
  1017. }
  1018. }
  1019. }
  1020. if (errCode != 0) {
  1021. /* Have to free all that memory */
  1022. if (uvd->fbuf != NULL) {
  1023. usbvideo_rvfree(uvd->fbuf, uvd->fbuf_size);
  1024. uvd->fbuf = NULL;
  1025. }
  1026. RingQueue_Free(&uvd->dp);
  1027. for (i=0; i < USBVIDEO_NUMSBUF; i++) {
  1028. kfree(uvd->sbuf[i].data);
  1029. uvd->sbuf[i].data = NULL;
  1030. }
  1031. }
  1032. }
  1033. /* If so far no errors then we shall start the camera */
  1034. if (errCode == 0) {
  1035. /* Start data pump if we have valid endpoint */
  1036. if (uvd->video_endp != 0)
  1037. errCode = GET_CALLBACK(uvd, startDataPump)(uvd);
  1038. if (errCode == 0) {
  1039. if (VALID_CALLBACK(uvd, setupOnOpen)) {
  1040. if (uvd->debug > 1)
  1041. dev_info(&uvd->dev->dev,
  1042. "%s: setupOnOpen callback\n",
  1043. __func__);
  1044. errCode = GET_CALLBACK(uvd, setupOnOpen)(uvd);
  1045. if (errCode < 0) {
  1046. err("%s: setupOnOpen callback failed (%d.).",
  1047. __func__, errCode);
  1048. } else if (uvd->debug > 1) {
  1049. dev_info(&uvd->dev->dev,
  1050. "%s: setupOnOpen callback successful\n",
  1051. __func__);
  1052. }
  1053. }
  1054. if (errCode == 0) {
  1055. uvd->settingsAdjusted = 0;
  1056. if (uvd->debug > 1)
  1057. dev_info(&uvd->dev->dev,
  1058. "%s: Open succeeded.\n",
  1059. __func__);
  1060. uvd->user++;
  1061. file->private_data = uvd;
  1062. }
  1063. }
  1064. }
  1065. mutex_unlock(&uvd->lock);
  1066. if (errCode != 0)
  1067. usbvideo_ClientDecModCount(uvd);
  1068. if (uvd->debug > 0)
  1069. dev_info(&uvd->dev->dev, "%s: Returning %d.\n", __func__,
  1070. errCode);
  1071. return errCode;
  1072. }
  1073. /*
  1074. * usbvideo_v4l_close()
  1075. *
  1076. * This is part of Video 4 Linux API. The procedure
  1077. * stops streaming and deallocates all buffers that were earlier
  1078. * allocated in usbvideo_v4l_open().
  1079. *
  1080. * History:
  1081. * 22-Jan-2000 Moved scratch buffer deallocation here.
  1082. * 27-Jan-2000 Used USBVIDEO_NUMSBUF as number of URB buffers.
  1083. * 24-May-2000 Moved MOD_DEC_USE_COUNT outside of code that can sleep.
  1084. */
  1085. static int usbvideo_v4l_close(struct file *file)
  1086. {
  1087. struct video_device *dev = file->private_data;
  1088. struct uvd *uvd = (struct uvd *) dev;
  1089. int i;
  1090. if (uvd->debug > 1)
  1091. dev_info(&uvd->dev->dev, "%s($%p)\n", __func__, dev);
  1092. mutex_lock(&uvd->lock);
  1093. GET_CALLBACK(uvd, stopDataPump)(uvd);
  1094. usbvideo_rvfree(uvd->fbuf, uvd->fbuf_size);
  1095. uvd->fbuf = NULL;
  1096. RingQueue_Free(&uvd->dp);
  1097. for (i=0; i < USBVIDEO_NUMSBUF; i++) {
  1098. kfree(uvd->sbuf[i].data);
  1099. uvd->sbuf[i].data = NULL;
  1100. }
  1101. #if USBVIDEO_REPORT_STATS
  1102. usbvideo_ReportStatistics(uvd);
  1103. #endif
  1104. uvd->user--;
  1105. if (uvd->remove_pending) {
  1106. if (uvd->debug > 0)
  1107. dev_info(&uvd->dev->dev, "%s: Final disconnect.\n",
  1108. __func__);
  1109. usbvideo_CameraRelease(uvd);
  1110. }
  1111. mutex_unlock(&uvd->lock);
  1112. usbvideo_ClientDecModCount(uvd);
  1113. if (uvd->debug > 1)
  1114. dev_info(&uvd->dev->dev, "%s: Completed.\n", __func__);
  1115. file->private_data = NULL;
  1116. return 0;
  1117. }
  1118. /*
  1119. * usbvideo_v4l_ioctl()
  1120. *
  1121. * This is part of Video 4 Linux API. The procedure handles ioctl() calls.
  1122. *
  1123. * History:
  1124. * 22-Jan-2000 Corrected VIDIOCSPICT to reject unsupported settings.
  1125. */
  1126. static long usbvideo_v4l_do_ioctl(struct file *file, unsigned int cmd, void *arg)
  1127. {
  1128. struct uvd *uvd = file->private_data;
  1129. if (!CAMERA_IS_OPERATIONAL(uvd))
  1130. return -EIO;
  1131. switch (cmd) {
  1132. case VIDIOCGCAP:
  1133. {
  1134. struct video_capability *b = arg;
  1135. *b = uvd->vcap;
  1136. return 0;
  1137. }
  1138. case VIDIOCGCHAN:
  1139. {
  1140. struct video_channel *v = arg;
  1141. *v = uvd->vchan;
  1142. return 0;
  1143. }
  1144. case VIDIOCSCHAN:
  1145. {
  1146. struct video_channel *v = arg;
  1147. if (v->channel != 0)
  1148. return -EINVAL;
  1149. return 0;
  1150. }
  1151. case VIDIOCGPICT:
  1152. {
  1153. struct video_picture *pic = arg;
  1154. *pic = uvd->vpic;
  1155. return 0;
  1156. }
  1157. case VIDIOCSPICT:
  1158. {
  1159. struct video_picture *pic = arg;
  1160. /*
  1161. * Use temporary 'video_picture' structure to preserve our
  1162. * own settings (such as color depth, palette) that we
  1163. * aren't allowing everyone (V4L client) to change.
  1164. */
  1165. uvd->vpic.brightness = pic->brightness;
  1166. uvd->vpic.hue = pic->hue;
  1167. uvd->vpic.colour = pic->colour;
  1168. uvd->vpic.contrast = pic->contrast;
  1169. uvd->settingsAdjusted = 0; /* Will force new settings */
  1170. return 0;
  1171. }
  1172. case VIDIOCSWIN:
  1173. {
  1174. struct video_window *vw = arg;
  1175. if(VALID_CALLBACK(uvd, setVideoMode)) {
  1176. return GET_CALLBACK(uvd, setVideoMode)(uvd, vw);
  1177. }
  1178. if (vw->flags)
  1179. return -EINVAL;
  1180. if (vw->clipcount)
  1181. return -EINVAL;
  1182. if (vw->width != VIDEOSIZE_X(uvd->canvas))
  1183. return -EINVAL;
  1184. if (vw->height != VIDEOSIZE_Y(uvd->canvas))
  1185. return -EINVAL;
  1186. return 0;
  1187. }
  1188. case VIDIOCGWIN:
  1189. {
  1190. struct video_window *vw = arg;
  1191. vw->x = 0;
  1192. vw->y = 0;
  1193. vw->width = VIDEOSIZE_X(uvd->videosize);
  1194. vw->height = VIDEOSIZE_Y(uvd->videosize);
  1195. vw->chromakey = 0;
  1196. if (VALID_CALLBACK(uvd, getFPS))
  1197. vw->flags = GET_CALLBACK(uvd, getFPS)(uvd);
  1198. else
  1199. vw->flags = 10; /* FIXME: do better! */
  1200. return 0;
  1201. }
  1202. case VIDIOCGMBUF:
  1203. {
  1204. struct video_mbuf *vm = arg;
  1205. int i;
  1206. memset(vm, 0, sizeof(*vm));
  1207. vm->size = uvd->max_frame_size * USBVIDEO_NUMFRAMES;
  1208. vm->frames = USBVIDEO_NUMFRAMES;
  1209. for(i = 0; i < USBVIDEO_NUMFRAMES; i++)
  1210. vm->offsets[i] = i * uvd->max_frame_size;
  1211. return 0;
  1212. }
  1213. case VIDIOCMCAPTURE:
  1214. {
  1215. struct video_mmap *vm = arg;
  1216. if (uvd->debug >= 1) {
  1217. dev_info(&uvd->dev->dev,
  1218. "VIDIOCMCAPTURE: frame=%d. size=%dx%d, format=%d.\n",
  1219. vm->frame, vm->width, vm->height, vm->format);
  1220. }
  1221. /*
  1222. * Check if the requested size is supported. If the requestor
  1223. * requests too big a frame then we may be tricked into accessing
  1224. * outside of own preallocated frame buffer (in uvd->frame).
  1225. * This will cause oops or a security hole. Theoretically, we
  1226. * could only clamp the size down to acceptable bounds, but then
  1227. * we'd need to figure out how to insert our smaller buffer into
  1228. * larger caller's buffer... this is not an easy question. So we
  1229. * here just flatly reject too large requests, assuming that the
  1230. * caller will resubmit with smaller size. Callers should know
  1231. * what size we support (returned by VIDIOCGCAP). However vidcat,
  1232. * for one, does not care and allows to ask for any size.
  1233. */
  1234. if ((vm->width > VIDEOSIZE_X(uvd->canvas)) ||
  1235. (vm->height > VIDEOSIZE_Y(uvd->canvas))) {
  1236. if (uvd->debug > 0) {
  1237. dev_info(&uvd->dev->dev,
  1238. "VIDIOCMCAPTURE: Size=%dx%d "
  1239. "too large; allowed only up "
  1240. "to %ldx%ld\n", vm->width,
  1241. vm->height,
  1242. VIDEOSIZE_X(uvd->canvas),
  1243. VIDEOSIZE_Y(uvd->canvas));
  1244. }
  1245. return -EINVAL;
  1246. }
  1247. /* Check if the palette is supported */
  1248. if (((1L << vm->format) & uvd->paletteBits) == 0) {
  1249. if (uvd->debug > 0) {
  1250. dev_info(&uvd->dev->dev,
  1251. "VIDIOCMCAPTURE: format=%d. "
  1252. "not supported "
  1253. "(paletteBits=$%08lx)\n",
  1254. vm->format, uvd->paletteBits);
  1255. }
  1256. return -EINVAL;
  1257. }
  1258. if ((vm->frame < 0) || (vm->frame >= USBVIDEO_NUMFRAMES)) {
  1259. err("VIDIOCMCAPTURE: vm.frame=%d. !E [0-%d]", vm->frame, USBVIDEO_NUMFRAMES-1);
  1260. return -EINVAL;
  1261. }
  1262. if (uvd->frame[vm->frame].frameState == FrameState_Grabbing) {
  1263. /* Not an error - can happen */
  1264. }
  1265. uvd->frame[vm->frame].request = VIDEOSIZE(vm->width, vm->height);
  1266. uvd->frame[vm->frame].palette = vm->format;
  1267. /* Mark it as ready */
  1268. uvd->frame[vm->frame].frameState = FrameState_Ready;
  1269. return usbvideo_NewFrame(uvd, vm->frame);
  1270. }
  1271. case VIDIOCSYNC:
  1272. {
  1273. int *frameNum = arg;
  1274. int ret;
  1275. if (*frameNum < 0 || *frameNum >= USBVIDEO_NUMFRAMES)
  1276. return -EINVAL;
  1277. if (uvd->debug >= 1)
  1278. dev_info(&uvd->dev->dev,
  1279. "VIDIOCSYNC: syncing to frame %d.\n",
  1280. *frameNum);
  1281. if (uvd->flags & FLAGS_NO_DECODING)
  1282. ret = usbvideo_GetFrame(uvd, *frameNum);
  1283. else if (VALID_CALLBACK(uvd, getFrame)) {
  1284. ret = GET_CALLBACK(uvd, getFrame)(uvd, *frameNum);
  1285. if ((ret < 0) && (uvd->debug >= 1)) {
  1286. err("VIDIOCSYNC: getFrame() returned %d.", ret);
  1287. }
  1288. } else {
  1289. err("VIDIOCSYNC: getFrame is not set");
  1290. ret = -EFAULT;
  1291. }
  1292. /*
  1293. * The frame is in FrameState_Done_Hold state. Release it
  1294. * right now because its data is already mapped into
  1295. * the user space and it's up to the application to
  1296. * make use of it until it asks for another frame.
  1297. */
  1298. uvd->frame[*frameNum].frameState = FrameState_Unused;
  1299. return ret;
  1300. }
  1301. case VIDIOCGFBUF:
  1302. {
  1303. struct video_buffer *vb = arg;
  1304. memset(vb, 0, sizeof(*vb));
  1305. return 0;
  1306. }
  1307. case VIDIOCKEY:
  1308. return 0;
  1309. case VIDIOCCAPTURE:
  1310. return -EINVAL;
  1311. case VIDIOCSFBUF:
  1312. case VIDIOCGTUNER:
  1313. case VIDIOCSTUNER:
  1314. case VIDIOCGFREQ:
  1315. case VIDIOCSFREQ:
  1316. case VIDIOCGAUDIO:
  1317. case VIDIOCSAUDIO:
  1318. return -EINVAL;
  1319. default:
  1320. return -ENOIOCTLCMD;
  1321. }
  1322. return 0;
  1323. }
  1324. static long usbvideo_v4l_ioctl(struct file *file,
  1325. unsigned int cmd, unsigned long arg)
  1326. {
  1327. return video_usercopy(file, cmd, arg, usbvideo_v4l_do_ioctl);
  1328. }
  1329. /*
  1330. * usbvideo_v4l_read()
  1331. *
  1332. * This is mostly boring stuff. We simply ask for a frame and when it
  1333. * arrives copy all the video data from it into user space. There is
  1334. * no obvious need to override this method.
  1335. *
  1336. * History:
  1337. * 20-Oct-2000 Created.
  1338. * 01-Nov-2000 Added mutex (uvd->lock).
  1339. */
  1340. static ssize_t usbvideo_v4l_read(struct file *file, char __user *buf,
  1341. size_t count, loff_t *ppos)
  1342. {
  1343. struct uvd *uvd = file->private_data;
  1344. int noblock = file->f_flags & O_NONBLOCK;
  1345. int frmx = -1, i;
  1346. struct usbvideo_frame *frame;
  1347. if (!CAMERA_IS_OPERATIONAL(uvd) || (buf == NULL))
  1348. return -EFAULT;
  1349. if (uvd->debug >= 1)
  1350. dev_info(&uvd->dev->dev,
  1351. "%s: %Zd. bytes, noblock=%d.\n",
  1352. __func__, count, noblock);
  1353. mutex_lock(&uvd->lock);
  1354. /* See if a frame is completed, then use it. */
  1355. for(i = 0; i < USBVIDEO_NUMFRAMES; i++) {
  1356. if ((uvd->frame[i].frameState == FrameState_Done) ||
  1357. (uvd->frame[i].frameState == FrameState_Done_Hold) ||
  1358. (uvd->frame[i].frameState == FrameState_Error)) {
  1359. frmx = i;
  1360. break;
  1361. }
  1362. }
  1363. /* FIXME: If we don't start a frame here then who ever does? */
  1364. if (noblock && (frmx == -1)) {
  1365. count = -EAGAIN;
  1366. goto read_done;
  1367. }
  1368. /*
  1369. * If no FrameState_Done, look for a FrameState_Grabbing state.
  1370. * See if a frame is in process (grabbing), then use it.
  1371. * We will need to wait until it becomes cooked, of course.
  1372. */
  1373. if (frmx == -1) {
  1374. for(i = 0; i < USBVIDEO_NUMFRAMES; i++) {
  1375. if (uvd->frame[i].frameState == FrameState_Grabbing) {
  1376. frmx = i;
  1377. break;
  1378. }
  1379. }
  1380. }
  1381. /*
  1382. * If no frame is active, start one. We don't care which one
  1383. * it will be, so #0 is as good as any.
  1384. * In read access mode we don't have convenience of VIDIOCMCAPTURE
  1385. * to specify the requested palette (video format) on per-frame
  1386. * basis. This means that we have to return data in -some- format
  1387. * and just hope that the client knows what to do with it.
  1388. * The default format is configured in uvd->defaultPalette field
  1389. * as one of VIDEO_PALETTE_xxx values. We stuff it into the new
  1390. * frame and initiate the frame filling process.
  1391. */
  1392. if (frmx == -1) {
  1393. if (uvd->defaultPalette == 0) {
  1394. err("%s: No default palette; don't know what to do!", __func__);
  1395. count = -EFAULT;
  1396. goto read_done;
  1397. }
  1398. frmx = 0;
  1399. /*
  1400. * We have no per-frame control over video size.
  1401. * Therefore we only can use whatever size was
  1402. * specified as default.
  1403. */
  1404. uvd->frame[frmx].request = uvd->videosize;
  1405. uvd->frame[frmx].palette = uvd->defaultPalette;
  1406. uvd->frame[frmx].frameState = FrameState_Ready;
  1407. usbvideo_NewFrame(uvd, frmx);
  1408. /* Now frame 0 is supposed to start filling... */
  1409. }
  1410. /*
  1411. * Get a pointer to the active frame. It is either previously
  1412. * completed frame or frame in progress but not completed yet.
  1413. */
  1414. frame = &uvd->frame[frmx];
  1415. /*
  1416. * Sit back & wait until the frame gets filled and postprocessed.
  1417. * If we fail to get the picture [in time] then return the error.
  1418. * In this call we specify that we want the frame to be waited for,
  1419. * postprocessed and switched into FrameState_Done_Hold state. This
  1420. * state is used to hold the frame as "fully completed" between
  1421. * subsequent partial reads of the same frame.
  1422. */
  1423. if (frame->frameState != FrameState_Done_Hold) {
  1424. long rv = -EFAULT;
  1425. if (uvd->flags & FLAGS_NO_DECODING)
  1426. rv = usbvideo_GetFrame(uvd, frmx);
  1427. else if (VALID_CALLBACK(uvd, getFrame))
  1428. rv = GET_CALLBACK(uvd, getFrame)(uvd, frmx);
  1429. else
  1430. err("getFrame is not set");
  1431. if ((rv != 0) || (frame->frameState != FrameState_Done_Hold)) {
  1432. count = rv;
  1433. goto read_done;
  1434. }
  1435. }
  1436. /*
  1437. * Copy bytes to user space. We allow for partial reads, which
  1438. * means that the user application can request read less than
  1439. * the full frame size. It is up to the application to issue
  1440. * subsequent calls until entire frame is read.
  1441. *
  1442. * First things first, make sure we don't copy more than we
  1443. * have - even if the application wants more. That would be
  1444. * a big security embarassment!
  1445. */
  1446. if ((count + frame->seqRead_Index) > frame->seqRead_Length)
  1447. count = frame->seqRead_Length - frame->seqRead_Index;
  1448. /*
  1449. * Copy requested amount of data to user space. We start
  1450. * copying from the position where we last left it, which
  1451. * will be zero for a new frame (not read before).
  1452. */
  1453. if (copy_to_user(buf, frame->data + frame->seqRead_Index, count)) {
  1454. count = -EFAULT;
  1455. goto read_done;
  1456. }
  1457. /* Update last read position */
  1458. frame->seqRead_Index += count;
  1459. if (uvd->debug >= 1) {
  1460. err("%s: {copy} count used=%Zd, new seqRead_Index=%ld",
  1461. __func__, count, frame->seqRead_Index);
  1462. }
  1463. /* Finally check if the frame is done with and "release" it */
  1464. if (frame->seqRead_Index >= frame->seqRead_Length) {
  1465. /* All data has been read */
  1466. frame->seqRead_Index = 0;
  1467. /* Mark it as available to be used again. */
  1468. uvd->frame[frmx].frameState = FrameState_Unused;
  1469. if (usbvideo_NewFrame(uvd, (frmx + 1) % USBVIDEO_NUMFRAMES)) {
  1470. err("%s: usbvideo_NewFrame failed.", __func__);
  1471. }
  1472. }
  1473. read_done:
  1474. mutex_unlock(&uvd->lock);
  1475. return count;
  1476. }
  1477. /*
  1478. * Make all of the blocks of data contiguous
  1479. */
  1480. static int usbvideo_CompressIsochronous(struct uvd *uvd, struct urb *urb)
  1481. {
  1482. char *cdata;
  1483. int i, totlen = 0;
  1484. for (i = 0; i < urb->number_of_packets; i++) {
  1485. int n = urb->iso_frame_desc[i].actual_length;
  1486. int st = urb->iso_frame_desc[i].status;
  1487. cdata = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
  1488. /* Detect and ignore errored packets */
  1489. if (st < 0) {
  1490. if (uvd->debug >= 1)
  1491. err("Data error: packet=%d. len=%d. status=%d.", i, n, st);
  1492. uvd->stats.iso_err_count++;
  1493. continue;
  1494. }
  1495. /* Detect and ignore empty packets */
  1496. if (n <= 0) {
  1497. uvd->stats.iso_skip_count++;
  1498. continue;
  1499. }
  1500. totlen += n; /* Little local accounting */
  1501. RingQueue_Enqueue(&uvd->dp, cdata, n);
  1502. }
  1503. return totlen;
  1504. }
  1505. static void usbvideo_IsocIrq(struct urb *urb)
  1506. {
  1507. int i, ret, len;
  1508. struct uvd *uvd = urb->context;
  1509. /* We don't want to do anything if we are about to be removed! */
  1510. if (!CAMERA_IS_OPERATIONAL(uvd))
  1511. return;
  1512. #if 0
  1513. if (urb->actual_length > 0) {
  1514. dev_info(&uvd->dev->dev,
  1515. "urb=$%p status=%d. errcount=%d. length=%d.\n",
  1516. urb, urb->status, urb->error_count,
  1517. urb->actual_length);
  1518. } else {
  1519. static int c = 0;
  1520. if (c++ % 100 == 0)
  1521. dev_info(&uvd->dev->dev, "No Isoc data\n");
  1522. }
  1523. #endif
  1524. if (!uvd->streaming) {
  1525. if (uvd->debug >= 1)
  1526. dev_info(&uvd->dev->dev,
  1527. "Not streaming, but interrupt!\n");
  1528. return;
  1529. }
  1530. uvd->stats.urb_count++;
  1531. if (urb->actual_length <= 0)
  1532. goto urb_done_with;
  1533. /* Copy the data received into ring queue */
  1534. len = usbvideo_CompressIsochronous(uvd, urb);
  1535. uvd->stats.urb_length = len;
  1536. if (len <= 0)
  1537. goto urb_done_with;
  1538. /* Here we got some data */
  1539. uvd->stats.data_count += len;
  1540. RingQueue_WakeUpInterruptible(&uvd->dp);
  1541. urb_done_with:
  1542. for (i = 0; i < FRAMES_PER_DESC; i++) {
  1543. urb->iso_frame_desc[i].status = 0;
  1544. urb->iso_frame_desc[i].actual_length = 0;
  1545. }
  1546. urb->status = 0;
  1547. urb->dev = uvd->dev;
  1548. ret = usb_submit_urb (urb, GFP_KERNEL);
  1549. if(ret)
  1550. err("usb_submit_urb error (%d)", ret);
  1551. return;
  1552. }
  1553. /*
  1554. * usbvideo_StartDataPump()
  1555. *
  1556. * History:
  1557. * 27-Jan-2000 Used ibmcam->iface, ibmcam->ifaceAltActive instead
  1558. * of hardcoded values. Simplified by using for loop,
  1559. * allowed any number of URBs.
  1560. */
  1561. static int usbvideo_StartDataPump(struct uvd *uvd)
  1562. {
  1563. struct usb_device *dev = uvd->dev;
  1564. int i, errFlag;
  1565. if (uvd->debug > 1)
  1566. dev_info(&uvd->dev->dev, "%s($%p)\n", __func__, uvd);
  1567. if (!CAMERA_IS_OPERATIONAL(uvd)) {
  1568. err("%s: Camera is not operational", __func__);
  1569. return -EFAULT;
  1570. }
  1571. uvd->curframe = -1;
  1572. /* Alternate interface 1 is is the biggest frame size */
  1573. i = usb_set_interface(dev, uvd->iface, uvd->ifaceAltActive);
  1574. if (i < 0) {
  1575. err("%s: usb_set_interface error", __func__);
  1576. uvd->last_error = i;
  1577. return -EBUSY;
  1578. }
  1579. if (VALID_CALLBACK(uvd, videoStart))
  1580. GET_CALLBACK(uvd, videoStart)(uvd);
  1581. else
  1582. err("%s: videoStart not set", __func__);
  1583. /* We double buffer the Iso lists */
  1584. for (i=0; i < USBVIDEO_NUMSBUF; i++) {
  1585. int j, k;
  1586. struct urb *urb = uvd->sbuf[i].urb;
  1587. urb->dev = dev;
  1588. urb->context = uvd;
  1589. urb->pipe = usb_rcvisocpipe(dev, uvd->video_endp);
  1590. urb->interval = 1;
  1591. urb->transfer_flags = URB_ISO_ASAP;
  1592. urb->transfer_buffer = uvd->sbuf[i].data;
  1593. urb->complete = usbvideo_IsocIrq;
  1594. urb->number_of_packets = FRAMES_PER_DESC;
  1595. urb->transfer_buffer_length = uvd->iso_packet_len * FRAMES_PER_DESC;
  1596. for (j=k=0; j < FRAMES_PER_DESC; j++, k += uvd->iso_packet_len) {
  1597. urb->iso_frame_desc[j].offset = k;
  1598. urb->iso_frame_desc[j].length = uvd->iso_packet_len;
  1599. }
  1600. }
  1601. /* Submit all URBs */
  1602. for (i=0; i < USBVIDEO_NUMSBUF; i++) {
  1603. errFlag = usb_submit_urb(uvd->sbuf[i].urb, GFP_KERNEL);
  1604. if (errFlag)
  1605. err("%s: usb_submit_isoc(%d) ret %d", __func__, i, errFlag);
  1606. }
  1607. uvd->streaming = 1;
  1608. if (uvd->debug > 1)
  1609. dev_info(&uvd->dev->dev,
  1610. "%s: streaming=1 video_endp=$%02x\n", __func__,
  1611. uvd->video_endp);
  1612. return 0;
  1613. }
  1614. /*
  1615. * usbvideo_StopDataPump()
  1616. *
  1617. * This procedure stops streaming and deallocates URBs. Then it
  1618. * activates zero-bandwidth alt. setting of the video interface.
  1619. *
  1620. * History:
  1621. * 22-Jan-2000 Corrected order of actions to work after surprise removal.
  1622. * 27-Jan-2000 Used uvd->iface, uvd->ifaceAltInactive instead of hardcoded values.
  1623. */
  1624. static void usbvideo_StopDataPump(struct uvd *uvd)
  1625. {
  1626. int i, j;
  1627. if ((uvd == NULL) || (!uvd->streaming) || (uvd->dev == NULL))
  1628. return;
  1629. if (uvd->debug > 1)
  1630. dev_info(&uvd->dev->dev, "%s($%p)\n", __func__, uvd);
  1631. /* Unschedule all of the iso td's */
  1632. for (i=0; i < USBVIDEO_NUMSBUF; i++) {
  1633. usb_kill_urb(uvd->sbuf[i].urb);
  1634. }
  1635. if (uvd->debug > 1)
  1636. dev_info(&uvd->dev->dev, "%s: streaming=0\n", __func__);
  1637. uvd->streaming = 0;
  1638. if (!uvd->remove_pending) {
  1639. /* Invoke minidriver's magic to stop the camera */
  1640. if (VALID_CALLBACK(uvd, videoStop))
  1641. GET_CALLBACK(uvd, videoStop)(uvd);
  1642. else
  1643. err("%s: videoStop not set", __func__);
  1644. /* Set packet size to 0 */
  1645. j = usb_set_interface(uvd->dev, uvd->iface, uvd->ifaceAltInactive);
  1646. if (j < 0) {
  1647. err("%s: usb_set_interface() error %d.", __func__, j);
  1648. uvd->last_error = j;
  1649. }
  1650. }
  1651. }
  1652. /*
  1653. * usbvideo_NewFrame()
  1654. *
  1655. * History:
  1656. * 29-Mar-00 Added copying of previous frame into the current one.
  1657. * 6-Aug-00 Added model 3 video sizes, removed redundant width, height.
  1658. */
  1659. static int usbvideo_NewFrame(struct uvd *uvd, int framenum)
  1660. {
  1661. struct usbvideo_frame *frame;
  1662. int n;
  1663. if (uvd->debug > 1)
  1664. dev_info(&uvd->dev->dev, "usbvideo_NewFrame($%p,%d.)\n", uvd,
  1665. framenum);
  1666. /* If we're not grabbing a frame right now and the other frame is */
  1667. /* ready to be grabbed into, then use it instead */
  1668. if (uvd->curframe != -1)
  1669. return 0;
  1670. /* If necessary we adjust picture settings between frames */
  1671. if (!uvd->settingsAdjusted) {
  1672. if (VALID_CALLBACK(uvd, adjustPicture))
  1673. GET_CALLBACK(uvd, adjustPicture)(uvd);
  1674. uvd->settingsAdjusted = 1;
  1675. }
  1676. n = (framenum + 1) % USBVIDEO_NUMFRAMES;
  1677. if (uvd->frame[n].frameState == FrameState_Ready)
  1678. framenum = n;
  1679. frame = &uvd->frame[framenum];
  1680. frame->frameState = FrameState_Grabbing;
  1681. frame->scanstate = ScanState_Scanning;
  1682. frame->seqRead_Length = 0; /* Accumulated in xxx_parse_data() */
  1683. frame->deinterlace = Deinterlace_None;
  1684. frame->flags = 0; /* No flags yet, up to minidriver (or us) to set them */
  1685. uvd->curframe = framenum;
  1686. /*
  1687. * Normally we would want to copy previous frame into the current one
  1688. * before we even start filling it with data; this allows us to stop
  1689. * filling at any moment; top portion of the frame will be new and
  1690. * bottom portion will stay as it was in previous frame. If we don't
  1691. * do that then missing chunks of video stream will result in flickering
  1692. * portions of old data whatever it was before.
  1693. *
  1694. * If we choose not to copy previous frame (to, for example, save few
  1695. * bus cycles - the frame can be pretty large!) then we have an option
  1696. * to clear the frame before using. If we experience losses in this
  1697. * mode then missing picture will be black (no flickering).
  1698. *
  1699. * Finally, if user chooses not to clean the current frame before
  1700. * filling it with data then the old data will be visible if we fail
  1701. * to refill entire frame with new data.
  1702. */
  1703. if (!(uvd->flags & FLAGS_SEPARATE_FRAMES)) {
  1704. /* This copies previous frame into this one to mask losses */
  1705. int prev = (framenum - 1 + USBVIDEO_NUMFRAMES) % USBVIDEO_NUMFRAMES;
  1706. memmove(frame->data, uvd->frame[prev].data, uvd->max_frame_size);
  1707. } else {
  1708. if (uvd->flags & FLAGS_CLEAN_FRAMES) {
  1709. /* This provides a "clean" frame but slows things down */
  1710. memset(frame->data, 0, uvd->max_frame_size);
  1711. }
  1712. }
  1713. return 0;
  1714. }
  1715. /*
  1716. * usbvideo_CollectRawData()
  1717. *
  1718. * This procedure can be used instead of 'processData' callback if you
  1719. * only want to dump the raw data from the camera into the output
  1720. * device (frame buffer). You can look at it with V4L client, but the
  1721. * image will be unwatchable. The main purpose of this code and of the
  1722. * mode FLAGS_NO_DECODING is debugging and capturing of datastreams from
  1723. * new, unknown cameras. This procedure will be automatically invoked
  1724. * instead of the specified callback handler when uvd->flags has bit
  1725. * FLAGS_NO_DECODING set. Therefore, any regular build of any driver
  1726. * based on usbvideo can use this feature at any time.
  1727. */
  1728. static void usbvideo_CollectRawData(struct uvd *uvd, struct usbvideo_frame *frame)
  1729. {
  1730. int n;
  1731. assert(uvd != NULL);
  1732. assert(frame != NULL);
  1733. /* Try to move data from queue into frame buffer */
  1734. n = RingQueue_GetLength(&uvd->dp);
  1735. if (n > 0) {
  1736. int m;
  1737. /* See how much space we have left */
  1738. m = uvd->max_frame_size - frame->seqRead_Length;
  1739. if (n > m)
  1740. n = m;
  1741. /* Now move that much data into frame buffer */
  1742. RingQueue_Dequeue(
  1743. &uvd->dp,
  1744. frame->data + frame->seqRead_Length,
  1745. m);
  1746. frame->seqRead_Length += m;
  1747. }
  1748. /* See if we filled the frame */
  1749. if (frame->seqRead_Length >= uvd->max_frame_size) {
  1750. frame->frameState = FrameState_Done;
  1751. uvd->curframe = -1;
  1752. uvd->stats.frame_num++;
  1753. }
  1754. }
  1755. static int usbvideo_GetFrame(struct uvd *uvd, int frameNum)
  1756. {
  1757. struct usbvideo_frame *frame = &uvd->frame[frameNum];
  1758. if (uvd->debug >= 2)
  1759. dev_info(&uvd->dev->dev, "%s($%p,%d.)\n", __func__, uvd,
  1760. frameNum);
  1761. switch (frame->frameState) {
  1762. case FrameState_Unused:
  1763. if (uvd->debug >= 2)
  1764. dev_info(&uvd->dev->dev, "%s: FrameState_Unused\n",
  1765. __func__);
  1766. return -EINVAL;
  1767. case FrameState_Ready:
  1768. case FrameState_Grabbing:
  1769. case FrameState_Error:
  1770. {
  1771. int ntries, signalPending;
  1772. redo:
  1773. if (!CAMERA_IS_OPERATIONAL(uvd)) {
  1774. if (uvd->debug >= 2)
  1775. dev_info(&uvd->dev->dev,
  1776. "%s: Camera is not operational (1)\n",
  1777. __func__);
  1778. return -EIO;
  1779. }
  1780. ntries = 0;
  1781. do {
  1782. RingQueue_InterruptibleSleepOn(&uvd->dp);
  1783. signalPending = signal_pending(current);
  1784. if (!CAMERA_IS_OPERATIONAL(uvd)) {
  1785. if (uvd->debug >= 2)
  1786. dev_info(&uvd->dev->dev,
  1787. "%s: Camera is not "
  1788. "operational (2)\n", __func__);
  1789. return -EIO;
  1790. }
  1791. assert(uvd->fbuf != NULL);
  1792. if (signalPending) {
  1793. if (uvd->debug >= 2)
  1794. dev_info(&uvd->dev->dev,
  1795. "%s: Signal=$%08x\n", __func__,
  1796. signalPending);
  1797. if (uvd->flags & FLAGS_RETRY_VIDIOCSYNC) {
  1798. usbvideo_TestPattern(uvd, 1, 0);
  1799. uvd->curframe = -1;
  1800. uvd->stats.frame_num++;
  1801. if (uvd->debug >= 2)
  1802. dev_info(&uvd->dev->dev,
  1803. "%s: Forced test "
  1804. "pattern screen\n",
  1805. __func__);
  1806. return 0;
  1807. } else {
  1808. /* Standard answer: Interrupted! */
  1809. if (uvd->debug >= 2)
  1810. dev_info(&uvd->dev->dev,
  1811. "%s: Interrupted!\n",
  1812. __func__);
  1813. return -EINTR;
  1814. }
  1815. } else {
  1816. /* No signals - we just got new data in dp queue */
  1817. if (uvd->flags & FLAGS_NO_DECODING)
  1818. usbvideo_CollectRawData(uvd, frame);
  1819. else if (VALID_CALLBACK(uvd, processData))
  1820. GET_CALLBACK(uvd, processData)(uvd, frame);
  1821. else
  1822. err("%s: processData not set", __func__);
  1823. }
  1824. } while (frame->frameState == FrameState_Grabbing);
  1825. if (uvd->debug >= 2) {
  1826. dev_info(&uvd->dev->dev,
  1827. "%s: Grabbing done; state=%d. (%lu. bytes)\n",
  1828. __func__, frame->frameState,
  1829. frame->seqRead_Length);
  1830. }
  1831. if (frame->frameState == FrameState_Error) {
  1832. int ret = usbvideo_NewFrame(uvd, frameNum);
  1833. if (ret < 0) {
  1834. err("%s: usbvideo_NewFrame() failed (%d.)", __func__, ret);
  1835. return ret;
  1836. }
  1837. goto redo;
  1838. }
  1839. /* Note that we fall through to meet our destiny below */
  1840. }
  1841. case FrameState_Done:
  1842. /*
  1843. * Do all necessary postprocessing of data prepared in
  1844. * "interrupt" code and the collecting code above. The
  1845. * frame gets marked as FrameState_Done by queue parsing code.
  1846. * This status means that we collected enough data and
  1847. * most likely processed it as we went through. However
  1848. * the data may need postprocessing, such as deinterlacing
  1849. * or picture adjustments implemented in software (horror!)
  1850. *
  1851. * As soon as the frame becomes "final" it gets promoted to
  1852. * FrameState_Done_Hold status where it will remain until the
  1853. * caller consumed all the video data from the frame. Then
  1854. * the empty shell of ex-frame is thrown out for dogs to eat.
  1855. * But we, worried about pets, will recycle the frame!
  1856. */
  1857. uvd->stats.frame_num++;
  1858. if ((uvd->flags & FLAGS_NO_DECODING) == 0) {
  1859. if (VALID_CALLBACK(uvd, postProcess))
  1860. GET_CALLBACK(uvd, postProcess)(uvd, frame);
  1861. if (frame->flags & USBVIDEO_FRAME_FLAG_SOFTWARE_CONTRAST)
  1862. usbvideo_SoftwareContrastAdjustment(uvd, frame);
  1863. }
  1864. frame->frameState = FrameState_Done_Hold;
  1865. if (uvd->debug >= 2)
  1866. dev_info(&uvd->dev->dev,
  1867. "%s: Entered FrameState_Done_Hold state.\n",
  1868. __func__);
  1869. return 0;
  1870. case FrameState_Done_Hold:
  1871. /*
  1872. * We stay in this state indefinitely until someone external,
  1873. * like ioctl() or read() call finishes digesting the frame
  1874. * data. Then it will mark the frame as FrameState_Unused and
  1875. * it will be released back into the wild to roam freely.
  1876. */
  1877. if (uvd->debug >= 2)
  1878. dev_info(&uvd->dev->dev,
  1879. "%s: FrameState_Done_Hold state.\n",
  1880. __func__);
  1881. return 0;
  1882. }
  1883. /* Catch-all for other cases. We shall not be here. */
  1884. err("%s: Invalid state %d.", __func__, frame->frameState);
  1885. frame->frameState = FrameState_Unused;
  1886. return 0;
  1887. }
  1888. /*
  1889. * usbvideo_DeinterlaceFrame()
  1890. *
  1891. * This procedure deinterlaces the given frame. Some cameras produce
  1892. * only half of scanlines - sometimes only even lines, sometimes only
  1893. * odd lines. The deinterlacing method is stored in frame->deinterlace
  1894. * variable.
  1895. *
  1896. * Here we scan the frame vertically and replace missing scanlines with
  1897. * average between surrounding ones - before and after. If we have no
  1898. * line above then we just copy next line. Similarly, if we need to
  1899. * create a last line then preceding line is used.
  1900. */
  1901. void usbvideo_DeinterlaceFrame(struct uvd *uvd, struct usbvideo_frame *frame)
  1902. {
  1903. if ((uvd == NULL) || (frame == NULL))
  1904. return;
  1905. if ((frame->deinterlace == Deinterlace_FillEvenLines) ||
  1906. (frame->deinterlace == Deinterlace_FillOddLines))
  1907. {
  1908. const int v4l_linesize = VIDEOSIZE_X(frame->request) * V4L_BYTES_PER_PIXEL;
  1909. int i = (frame->deinterlace == Deinterlace_FillEvenLines) ? 0 : 1;
  1910. for (; i < VIDEOSIZE_Y(frame->request); i += 2) {
  1911. const unsigned char *fs1, *fs2;
  1912. unsigned char *fd;
  1913. int ip, in, j; /* Previous and next lines */
  1914. /*
  1915. * Need to average lines before and after 'i'.
  1916. * If we go out of bounds seeking those lines then
  1917. * we point back to existing line.
  1918. */
  1919. ip = i - 1; /* First, get rough numbers */
  1920. in = i + 1;
  1921. /* Now validate */
  1922. if (ip < 0)
  1923. ip = in;
  1924. if (in >= VIDEOSIZE_Y(frame->request))
  1925. in = ip;
  1926. /* Sanity check */
  1927. if ((ip < 0) || (in < 0) ||
  1928. (ip >= VIDEOSIZE_Y(frame->request)) ||
  1929. (in >= VIDEOSIZE_Y(frame->request)))
  1930. {
  1931. err("Error: ip=%d. in=%d. req.height=%ld.",
  1932. ip, in, VIDEOSIZE_Y(frame->request));
  1933. break;
  1934. }
  1935. /* Now we need to average lines 'ip' and 'in' to produce line 'i' */
  1936. fs1 = frame->data + (v4l_linesize * ip);
  1937. fs2 = frame->data + (v4l_linesize * in);
  1938. fd = frame->data + (v4l_linesize * i);
  1939. /* Average lines around destination */
  1940. for (j=0; j < v4l_linesize; j++) {
  1941. fd[j] = (unsigned char)((((unsigned) fs1[j]) +
  1942. ((unsigned)fs2[j])) >> 1);
  1943. }
  1944. }
  1945. }
  1946. /* Optionally display statistics on the screen */
  1947. if (uvd->flags & FLAGS_OVERLAY_STATS)
  1948. usbvideo_OverlayStats(uvd, frame);
  1949. }
  1950. EXPORT_SYMBOL(usbvideo_DeinterlaceFrame);
  1951. /*
  1952. * usbvideo_SoftwareContrastAdjustment()
  1953. *
  1954. * This code adjusts the contrast of the frame, assuming RGB24 format.
  1955. * As most software image processing, this job is CPU-intensive.
  1956. * Get a camera that supports hardware adjustment!
  1957. *
  1958. * History:
  1959. * 09-Feb-2001 Created.
  1960. */
  1961. static void usbvideo_SoftwareContrastAdjustment(struct uvd *uvd,
  1962. struct usbvideo_frame *frame)
  1963. {
  1964. int i, j, v4l_linesize;
  1965. signed long adj;
  1966. const int ccm = 128; /* Color correction median - see below */
  1967. if ((uvd == NULL) || (frame == NULL)) {
  1968. err("%s: Illegal call.", __func__);
  1969. return;
  1970. }
  1971. adj = (uvd->vpic.contrast - 0x8000) >> 8; /* -128..+127 = -ccm..+(ccm-1)*/
  1972. RESTRICT_TO_RANGE(adj, -ccm, ccm+1);
  1973. if (adj == 0) {
  1974. /* In rare case of no adjustment */
  1975. return;
  1976. }
  1977. v4l_linesize = VIDEOSIZE_X(frame->request) * V4L_BYTES_PER_PIXEL;
  1978. for (i=0; i < VIDEOSIZE_Y(frame->request); i++) {
  1979. unsigned char *fd = frame->data + (v4l_linesize * i);
  1980. for (j=0; j < v4l_linesize; j++) {
  1981. signed long v = (signed long) fd[j];
  1982. /* Magnify up to 2 times, reduce down to zero */
  1983. v = 128 + ((ccm + adj) * (v - 128)) / ccm;
  1984. RESTRICT_TO_RANGE(v, 0, 0xFF); /* Must flatten tails */
  1985. fd[j] = (unsigned char) v;
  1986. }
  1987. }
  1988. }
  1989. MODULE_LICENSE("GPL");