Merge branch 'for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/ieee1394...
[linux-2.6] / drivers / media / video / usbvideo / konicawc.c
1 /*
2  * konicawc.c - konica webcam driver
3  *
4  * Author: Simon Evans <spse@secret.org.uk>
5  *
6  * Copyright (C) 2002 Simon Evans
7  *
8  * Licence: GPL
9  *
10  * Driver for USB webcams based on Konica chipset. This
11  * chipset is used in Intel YC76 camera.
12  *
13  */
14
15 #include <linux/kernel.h>
16 #include <linux/module.h>
17 #include <linux/init.h>
18 #include <linux/usb/input.h>
19
20 #include "usbvideo.h"
21
22 #define MAX_BRIGHTNESS  108
23 #define MAX_CONTRAST    108
24 #define MAX_SATURATION  108
25 #define MAX_SHARPNESS   108
26 #define MAX_WHITEBAL    372
27 #define MAX_SPEED       6
28
29
30 #define MAX_CAMERAS     1
31
32 #define DRIVER_VERSION  "v1.4"
33 #define DRIVER_DESC     "Konica Webcam driver"
34
35 enum ctrl_req {
36         SetWhitebal     = 0x01,
37         SetBrightness   = 0x02,
38         SetSharpness    = 0x03,
39         SetContrast     = 0x04,
40         SetSaturation   = 0x05,
41 };
42
43
44 enum frame_sizes {
45         SIZE_160X120    = 0,
46         SIZE_160X136    = 1,
47         SIZE_176X144    = 2,
48         SIZE_320X240    = 3,
49
50 };
51
52 #define MAX_FRAME_SIZE  SIZE_320X240
53
54 static struct usbvideo *cams;
55
56 #ifdef CONFIG_USB_DEBUG
57 static int debug;
58 #define DEBUG(n, format, arg...) \
59         if (n <= debug) {        \
60                 printk(KERN_DEBUG __FILE__ ":%s(): " format "\n", __func__ , ## arg); \
61         }
62 #else
63 #define DEBUG(n, arg...)
64 static const int debug;
65 #endif
66
67
68 /* Some default values for initial camera settings,
69    can be set by modprobe */
70
71 static int size;
72 static int speed = 6;           /* Speed (fps) 0 (slowest) to 6 (fastest) */
73 static int brightness = MAX_BRIGHTNESS/2;
74 static int contrast =   MAX_CONTRAST/2;
75 static int saturation = MAX_SATURATION/2;
76 static int sharpness =  MAX_SHARPNESS/2;
77 static int whitebal =   3*(MAX_WHITEBAL/4);
78
79 static const int spd_to_iface[] = { 1, 0, 3, 2, 4, 5, 6 };
80
81 /* These FPS speeds are from the windows config box. They are
82  * indexed on size (0-2) and speed (0-6). Divide by 3 to get the
83  * real fps.
84  */
85
86 static const int spd_to_fps[][7] = { { 24, 40, 48, 60, 72, 80, 100 },
87                                { 24, 40, 48, 60, 72, 80, 100 },
88                                { 18, 30, 36, 45, 54, 60, 75  },
89                                { 6,  10, 12, 15, 18, 21, 25  } };
90
91 struct cam_size {
92         u16     width;
93         u16     height;
94         u8      cmd;
95 };
96
97 static const struct cam_size camera_sizes[] = { { 160, 120, 0x7 },
98                                           { 160, 136, 0xa },
99                                           { 176, 144, 0x4 },
100                                           { 320, 240, 0x5 } };
101
102 struct konicawc {
103         u8 brightness;          /* camera uses 0 - 9, x11 for real value */
104         u8 contrast;            /* as above */
105         u8 saturation;          /* as above */
106         u8 sharpness;           /* as above */
107         u8 white_bal;           /* 0 - 33, x11 for real value */
108         u8 speed;               /* Stored as 0 - 6, used as index in spd_to_* (above) */
109         u8 size;                /* Frame Size */
110         int height;
111         int width;
112         struct urb *sts_urb[USBVIDEO_NUMSBUF];
113         u8 sts_buf[USBVIDEO_NUMSBUF][FRAMES_PER_DESC];
114         struct urb *last_data_urb;
115         int lastframe;
116         int cur_frame_size;     /* number of bytes in current frame size */
117         int maxline;            /* number of lines per frame */
118         int yplanesz;           /* Number of bytes in the Y plane */
119         unsigned int buttonsts:1;
120 #ifdef CONFIG_INPUT
121         struct input_dev *input;
122         char input_physname[64];
123 #endif
124 };
125
126
127 #define konicawc_set_misc(uvd, req, value, index)               konicawc_ctrl_msg(uvd, USB_DIR_OUT, req, value, index, NULL, 0)
128 #define konicawc_get_misc(uvd, req, value, index, buf, sz)      konicawc_ctrl_msg(uvd, USB_DIR_IN, req, value, index, buf, sz)
129 #define konicawc_set_value(uvd, value, index)                   konicawc_ctrl_msg(uvd, USB_DIR_OUT, 2, value, index, NULL, 0)
130
131
132 static int konicawc_ctrl_msg(struct uvd *uvd, u8 dir, u8 request, u16 value, u16 index, void *buf, int len)
133 {
134         int retval = usb_control_msg(uvd->dev,
135                 dir ? usb_rcvctrlpipe(uvd->dev, 0) : usb_sndctrlpipe(uvd->dev, 0),
136                     request, 0x40 | dir, value, index, buf, len, 1000);
137         return retval < 0 ? retval : 0;
138 }
139
140
141 static inline void konicawc_camera_on(struct uvd *uvd)
142 {
143         DEBUG(0, "camera on");
144         konicawc_set_misc(uvd, 0x2, 1, 0x0b);
145 }
146
147
148 static inline void konicawc_camera_off(struct uvd *uvd)
149 {
150         DEBUG(0, "camera off");
151         konicawc_set_misc(uvd, 0x2, 0, 0x0b);
152 }
153
154
155 static void konicawc_set_camera_size(struct uvd *uvd)
156 {
157         struct konicawc *cam = (struct konicawc *)uvd->user_data;
158
159         konicawc_set_misc(uvd, 0x2, camera_sizes[cam->size].cmd, 0x08);
160         cam->width = camera_sizes[cam->size].width;
161         cam->height = camera_sizes[cam->size].height;
162         cam->yplanesz = cam->height * cam->width;
163         cam->cur_frame_size = (cam->yplanesz * 3) / 2;
164         cam->maxline = cam->yplanesz / 256;
165         uvd->videosize = VIDEOSIZE(cam->width, cam->height);
166 }
167
168
169 static int konicawc_setup_on_open(struct uvd *uvd)
170 {
171         struct konicawc *cam = (struct konicawc *)uvd->user_data;
172
173         DEBUG(1, "setting brightness to %d (%d)", cam->brightness,
174             cam->brightness * 11);
175         konicawc_set_value(uvd, cam->brightness, SetBrightness);
176         DEBUG(1, "setting white balance to %d (%d)", cam->white_bal,
177             cam->white_bal * 11);
178         konicawc_set_value(uvd, cam->white_bal, SetWhitebal);
179         DEBUG(1, "setting contrast to %d (%d)", cam->contrast,
180             cam->contrast * 11);
181         konicawc_set_value(uvd, cam->contrast, SetContrast);
182         DEBUG(1, "setting saturation to %d (%d)", cam->saturation,
183             cam->saturation * 11);
184         konicawc_set_value(uvd, cam->saturation, SetSaturation);
185         DEBUG(1, "setting sharpness to %d (%d)", cam->sharpness,
186             cam->sharpness * 11);
187         konicawc_set_value(uvd, cam->sharpness, SetSharpness);
188         konicawc_set_camera_size(uvd);
189         cam->lastframe = -2;
190         cam->buttonsts = 0;
191         return 0;
192 }
193
194
195 static void konicawc_adjust_picture(struct uvd *uvd)
196 {
197         struct konicawc *cam = (struct konicawc *)uvd->user_data;
198
199         konicawc_camera_off(uvd);
200         DEBUG(1, "new brightness: %d", uvd->vpic.brightness);
201         uvd->vpic.brightness = (uvd->vpic.brightness > MAX_BRIGHTNESS) ? MAX_BRIGHTNESS : uvd->vpic.brightness;
202         if(cam->brightness != uvd->vpic.brightness / 11) {
203            cam->brightness = uvd->vpic.brightness / 11;
204            DEBUG(1, "setting brightness to %d (%d)", cam->brightness,
205                cam->brightness * 11);
206            konicawc_set_value(uvd, cam->brightness, SetBrightness);
207         }
208
209         DEBUG(1, "new contrast: %d", uvd->vpic.contrast);
210         uvd->vpic.contrast = (uvd->vpic.contrast > MAX_CONTRAST) ? MAX_CONTRAST : uvd->vpic.contrast;
211         if(cam->contrast != uvd->vpic.contrast / 11) {
212                 cam->contrast = uvd->vpic.contrast / 11;
213                 DEBUG(1, "setting contrast to %d (%d)", cam->contrast,
214                     cam->contrast * 11);
215                 konicawc_set_value(uvd, cam->contrast, SetContrast);
216         }
217         konicawc_camera_on(uvd);
218 }
219
220 #ifdef CONFIG_INPUT
221
222 static void konicawc_register_input(struct konicawc *cam, struct usb_device *dev)
223 {
224         struct input_dev *input_dev;
225         int error;
226
227         usb_make_path(dev, cam->input_physname, sizeof(cam->input_physname));
228         strncat(cam->input_physname, "/input0", sizeof(cam->input_physname));
229
230         cam->input = input_dev = input_allocate_device();
231         if (!input_dev) {
232                 warn("Not enough memory for camera's input device\n");
233                 return;
234         }
235
236         input_dev->name = "Konicawc snapshot button";
237         input_dev->phys = cam->input_physname;
238         usb_to_input_id(dev, &input_dev->id);
239         input_dev->dev.parent = &dev->dev;
240
241         input_dev->evbit[0] = BIT_MASK(EV_KEY);
242         input_dev->keybit[BIT_WORD(BTN_0)] = BIT_MASK(BTN_0);
243
244         error = input_register_device(cam->input);
245         if (error) {
246                 warn("Failed to register camera's input device, err: %d\n",
247                      error);
248                 input_free_device(cam->input);
249                 cam->input = NULL;
250         }
251 }
252
253 static void konicawc_unregister_input(struct konicawc *cam)
254 {
255         if (cam->input) {
256                 input_unregister_device(cam->input);
257                 cam->input = NULL;
258         }
259 }
260
261 static void konicawc_report_buttonstat(struct konicawc *cam)
262 {
263         if (cam->input) {
264                 input_report_key(cam->input, BTN_0, cam->buttonsts);
265                 input_sync(cam->input);
266         }
267 }
268
269 #else
270
271 static inline void konicawc_register_input(struct konicawc *cam, struct usb_device *dev) { }
272 static inline void konicawc_unregister_input(struct konicawc *cam) { }
273 static inline void konicawc_report_buttonstat(struct konicawc *cam) { }
274
275 #endif /* CONFIG_INPUT */
276
277 static int konicawc_compress_iso(struct uvd *uvd, struct urb *dataurb, struct urb *stsurb)
278 {
279         char *cdata;
280         int i, totlen = 0;
281         unsigned char *status = stsurb->transfer_buffer;
282         int keep = 0, discard = 0, bad = 0;
283         struct konicawc *cam = (struct konicawc *)uvd->user_data;
284
285         for (i = 0; i < dataurb->number_of_packets; i++) {
286                 int button = cam->buttonsts;
287                 unsigned char sts;
288                 int n = dataurb->iso_frame_desc[i].actual_length;
289                 int st = dataurb->iso_frame_desc[i].status;
290                 cdata = dataurb->transfer_buffer +
291                         dataurb->iso_frame_desc[i].offset;
292
293                 /* Detect and ignore errored packets */
294                 if (st < 0) {
295                         DEBUG(1, "Data error: packet=%d. len=%d. status=%d.",
296                               i, n, st);
297                         uvd->stats.iso_err_count++;
298                         continue;
299                 }
300
301                 /* Detect and ignore empty packets */
302                 if (n <= 0) {
303                         uvd->stats.iso_skip_count++;
304                         continue;
305                 }
306
307                 /* See what the status data said about the packet */
308                 sts = *(status+stsurb->iso_frame_desc[i].offset);
309
310                 /* sts: 0x80-0xff: frame start with frame number (ie 0-7f)
311                  * otherwise:
312                  * bit 0 0: keep packet
313                  *       1: drop packet (padding data)
314                  *
315                  * bit 4 0 button not clicked
316                  *       1 button clicked
317                  * button is used to `take a picture' (in software)
318                  */
319
320                 if(sts < 0x80) {
321                         button = !!(sts & 0x40);
322                         sts &= ~0x40;
323                 }
324
325                 /* work out the button status, but don't do
326                    anything with it for now */
327
328                 if(button != cam->buttonsts) {
329                         DEBUG(2, "button: %sclicked", button ? "" : "un");
330                         cam->buttonsts = button;
331                         konicawc_report_buttonstat(cam);
332                 }
333
334                 if(sts == 0x01) { /* drop frame */
335                         discard++;
336                         continue;
337                 }
338
339                 if((sts > 0x01) && (sts < 0x80)) {
340                         info("unknown status %2.2x", sts);
341                         bad++;
342                         continue;
343                 }
344                 if(!sts && cam->lastframe == -2) {
345                         DEBUG(2, "dropping frame looking for image start");
346                         continue;
347                 }
348
349                 keep++;
350                 if(sts & 0x80) { /* frame start */
351                         unsigned char marker[] = { 0, 0xff, 0, 0x00 };
352
353                         if(cam->lastframe == -2) {
354                                 DEBUG(2, "found initial image");
355                                 cam->lastframe = -1;
356                         }
357
358                         marker[3] = sts & 0x7F;
359                         RingQueue_Enqueue(&uvd->dp, marker, 4);
360                         totlen += 4;
361                 }
362
363                 totlen += n;    /* Little local accounting */
364                 RingQueue_Enqueue(&uvd->dp, cdata, n);
365         }
366         DEBUG(8, "finished: keep = %d discard = %d bad = %d added %d bytes",
367                     keep, discard, bad, totlen);
368         return totlen;
369 }
370
371
372 static void resubmit_urb(struct uvd *uvd, struct urb *urb)
373 {
374         int i, ret;
375         for (i = 0; i < FRAMES_PER_DESC; i++) {
376                 urb->iso_frame_desc[i].status = 0;
377         }
378         urb->dev = uvd->dev;
379         urb->status = 0;
380         ret = usb_submit_urb(urb, GFP_ATOMIC);
381         DEBUG(3, "submitting urb of length %d", urb->transfer_buffer_length);
382         if(ret)
383                 err("usb_submit_urb error (%d)", ret);
384
385 }
386
387
388 static void konicawc_isoc_irq(struct urb *urb)
389 {
390         struct uvd *uvd = urb->context;
391         struct konicawc *cam = (struct konicawc *)uvd->user_data;
392
393         /* We don't want to do anything if we are about to be removed! */
394         if (!CAMERA_IS_OPERATIONAL(uvd))
395                 return;
396
397         if (!uvd->streaming) {
398                 DEBUG(1, "Not streaming, but interrupt!");
399                 return;
400         }
401
402         DEBUG(3, "got frame %d len = %d buflen =%d", urb->start_frame, urb->actual_length, urb->transfer_buffer_length);
403
404         uvd->stats.urb_count++;
405
406         if (urb->transfer_buffer_length > 32) {
407                 cam->last_data_urb = urb;
408                 return;
409         }
410         /* Copy the data received into ring queue */
411         if(cam->last_data_urb) {
412                 int len = 0;
413                 if(urb->start_frame != cam->last_data_urb->start_frame)
414                         err("Lost sync on frames");
415                 else if (!urb->status && !cam->last_data_urb->status)
416                         len = konicawc_compress_iso(uvd, cam->last_data_urb, urb);
417
418                 resubmit_urb(uvd, cam->last_data_urb);
419                 resubmit_urb(uvd, urb);
420                 cam->last_data_urb = NULL;
421                 uvd->stats.urb_length = len;
422                 uvd->stats.data_count += len;
423                 if(len)
424                         RingQueue_WakeUpInterruptible(&uvd->dp);
425                 return;
426         }
427         return;
428 }
429
430
431 static int konicawc_start_data(struct uvd *uvd)
432 {
433         struct usb_device *dev = uvd->dev;
434         int i, errFlag;
435         struct konicawc *cam = (struct konicawc *)uvd->user_data;
436         int pktsz;
437         struct usb_interface *intf;
438         struct usb_host_interface *interface = NULL;
439
440         intf = usb_ifnum_to_if(dev, uvd->iface);
441         if (intf)
442                 interface = usb_altnum_to_altsetting(intf,
443                                 spd_to_iface[cam->speed]);
444         if (!interface)
445                 return -ENXIO;
446         pktsz = le16_to_cpu(interface->endpoint[1].desc.wMaxPacketSize);
447         DEBUG(1, "pktsz = %d", pktsz);
448         if (!CAMERA_IS_OPERATIONAL(uvd)) {
449                 err("Camera is not operational");
450                 return -EFAULT;
451         }
452         uvd->curframe = -1;
453         konicawc_camera_on(uvd);
454         /* Alternate interface 1 is is the biggest frame size */
455         i = usb_set_interface(dev, uvd->iface, uvd->ifaceAltActive);
456         if (i < 0) {
457                 err("usb_set_interface error");
458                 uvd->last_error = i;
459                 return -EBUSY;
460         }
461
462         /* We double buffer the Iso lists */
463         for (i=0; i < USBVIDEO_NUMSBUF; i++) {
464                 int j, k;
465                 struct urb *urb = uvd->sbuf[i].urb;
466                 urb->dev = dev;
467                 urb->context = uvd;
468                 urb->pipe = usb_rcvisocpipe(dev, uvd->video_endp);
469                 urb->interval = 1;
470                 urb->transfer_flags = URB_ISO_ASAP;
471                 urb->transfer_buffer = uvd->sbuf[i].data;
472                 urb->complete = konicawc_isoc_irq;
473                 urb->number_of_packets = FRAMES_PER_DESC;
474                 urb->transfer_buffer_length = pktsz * FRAMES_PER_DESC;
475                 for (j=k=0; j < FRAMES_PER_DESC; j++, k += pktsz) {
476                         urb->iso_frame_desc[j].offset = k;
477                         urb->iso_frame_desc[j].length = pktsz;
478                 }
479
480                 urb = cam->sts_urb[i];
481                 urb->dev = dev;
482                 urb->context = uvd;
483                 urb->pipe = usb_rcvisocpipe(dev, uvd->video_endp-1);
484                 urb->interval = 1;
485                 urb->transfer_flags = URB_ISO_ASAP;
486                 urb->transfer_buffer = cam->sts_buf[i];
487                 urb->complete = konicawc_isoc_irq;
488                 urb->number_of_packets = FRAMES_PER_DESC;
489                 urb->transfer_buffer_length = FRAMES_PER_DESC;
490                 for (j=0; j < FRAMES_PER_DESC; j++) {
491                         urb->iso_frame_desc[j].offset = j;
492                         urb->iso_frame_desc[j].length = 1;
493                 }
494         }
495
496         cam->last_data_urb = NULL;
497
498         /* Submit all URBs */
499         for (i=0; i < USBVIDEO_NUMSBUF; i++) {
500                 errFlag = usb_submit_urb(cam->sts_urb[i], GFP_KERNEL);
501                 if (errFlag)
502                         err("usb_submit_isoc(%d) ret %d", i, errFlag);
503
504                 errFlag = usb_submit_urb(uvd->sbuf[i].urb, GFP_KERNEL);
505                 if (errFlag)
506                         err ("usb_submit_isoc(%d) ret %d", i, errFlag);
507         }
508
509         uvd->streaming = 1;
510         DEBUG(1, "streaming=1 video_endp=$%02x", uvd->video_endp);
511         return 0;
512 }
513
514
515 static void konicawc_stop_data(struct uvd *uvd)
516 {
517         int i, j;
518         struct konicawc *cam;
519
520         if ((uvd == NULL) || (!uvd->streaming) || (uvd->dev == NULL))
521                 return;
522
523         konicawc_camera_off(uvd);
524         uvd->streaming = 0;
525         cam = (struct konicawc *)uvd->user_data;
526         cam->last_data_urb = NULL;
527
528         /* Unschedule all of the iso td's */
529         for (i=0; i < USBVIDEO_NUMSBUF; i++) {
530                 usb_kill_urb(uvd->sbuf[i].urb);
531                 usb_kill_urb(cam->sts_urb[i]);
532         }
533
534         if (!uvd->remove_pending) {
535                 /* Set packet size to 0 */
536                 j = usb_set_interface(uvd->dev, uvd->iface, uvd->ifaceAltInactive);
537                 if (j < 0) {
538                         err("usb_set_interface() error %d.", j);
539                         uvd->last_error = j;
540                 }
541         }
542 }
543
544
545 static void konicawc_process_isoc(struct uvd *uvd, struct usbvideo_frame *frame)
546 {
547         struct konicawc *cam = (struct konicawc *)uvd->user_data;
548         int maxline = cam->maxline;
549         int yplanesz = cam->yplanesz;
550
551         assert(frame != NULL);
552
553         DEBUG(5, "maxline = %d yplanesz = %d", maxline, yplanesz);
554         DEBUG(3, "Frame state = %d", frame->scanstate);
555
556         if(frame->scanstate == ScanState_Scanning) {
557                 int drop = 0;
558                 int curframe;
559                 int fdrops = 0;
560                 DEBUG(3, "Searching for marker, queue len = %d", RingQueue_GetLength(&uvd->dp));
561                 while(RingQueue_GetLength(&uvd->dp) >= 4) {
562                         if ((RING_QUEUE_PEEK(&uvd->dp, 0) == 0x00) &&
563                             (RING_QUEUE_PEEK(&uvd->dp, 1) == 0xff) &&
564                             (RING_QUEUE_PEEK(&uvd->dp, 2) == 0x00) &&
565                             (RING_QUEUE_PEEK(&uvd->dp, 3) < 0x80)) {
566                                 curframe = RING_QUEUE_PEEK(&uvd->dp, 3);
567                                 if(cam->lastframe >= 0) {
568                                         fdrops = (0x80 + curframe - cam->lastframe) & 0x7F;
569                                         fdrops--;
570                                         if(fdrops) {
571                                                 info("Dropped %d frames (%d -> %d)", fdrops,
572                                                      cam->lastframe, curframe);
573                                         }
574                                 }
575                                 cam->lastframe = curframe;
576                                 frame->curline = 0;
577                                 frame->scanstate = ScanState_Lines;
578                                 RING_QUEUE_DEQUEUE_BYTES(&uvd->dp, 4);
579                                 break;
580                         }
581                         RING_QUEUE_DEQUEUE_BYTES(&uvd->dp, 1);
582                         drop++;
583                 }
584                 if(drop)
585                         DEBUG(2, "dropped %d bytes looking for new frame", drop);
586         }
587
588         if(frame->scanstate == ScanState_Scanning)
589                 return;
590
591         /* Try to move data from queue into frame buffer
592          * We get data in blocks of 384 bytes made up of:
593          * 256 Y, 64 U, 64 V.
594          * This needs to be written out as a Y plane, a U plane and a V plane.
595          */
596
597         while ( frame->curline < maxline && (RingQueue_GetLength(&uvd->dp) >= 384)) {
598                 /* Y */
599                 RingQueue_Dequeue(&uvd->dp, frame->data + (frame->curline * 256), 256);
600                 /* U */
601                 RingQueue_Dequeue(&uvd->dp, frame->data + yplanesz + (frame->curline * 64), 64);
602                 /* V */
603                 RingQueue_Dequeue(&uvd->dp, frame->data + (5 * yplanesz)/4 + (frame->curline * 64), 64);
604                 frame->seqRead_Length += 384;
605                 frame->curline++;
606         }
607         /* See if we filled the frame */
608         if (frame->curline == maxline) {
609                 DEBUG(5, "got whole frame");
610
611                 frame->frameState = FrameState_Done_Hold;
612                 frame->curline = 0;
613                 uvd->curframe = -1;
614                 uvd->stats.frame_num++;
615         }
616 }
617
618
619 static int konicawc_find_fps(int size, int fps)
620 {
621         int i;
622
623         fps *= 3;
624         DEBUG(1, "konica_find_fps: size = %d fps = %d", size, fps);
625         if(fps <= spd_to_fps[size][0])
626                 return 0;
627
628         if(fps >= spd_to_fps[size][MAX_SPEED])
629                 return MAX_SPEED;
630
631         for(i = 0; i < MAX_SPEED; i++) {
632                 if((fps >= spd_to_fps[size][i]) && (fps <= spd_to_fps[size][i+1])) {
633                         DEBUG(2, "fps %d between %d and %d", fps, i, i+1);
634                         if( (fps - spd_to_fps[size][i]) < (spd_to_fps[size][i+1] - fps))
635                                 return i;
636                         else
637                                 return i+1;
638                 }
639         }
640         return MAX_SPEED+1;
641 }
642
643
644 static int konicawc_set_video_mode(struct uvd *uvd, struct video_window *vw)
645 {
646         struct konicawc *cam = (struct konicawc *)uvd->user_data;
647         int newspeed = cam->speed;
648         int newsize;
649         int x = vw->width;
650         int y = vw->height;
651         int fps = vw->flags;
652
653         if(x > 0 && y > 0) {
654                 DEBUG(2, "trying to find size %d,%d", x, y);
655                 for(newsize = 0; newsize <= MAX_FRAME_SIZE; newsize++) {
656                         if((camera_sizes[newsize].width == x) && (camera_sizes[newsize].height == y))
657                                 break;
658                 }
659         } else {
660                 newsize = cam->size;
661         }
662
663         if(newsize > MAX_FRAME_SIZE) {
664                 DEBUG(1, "couldn't find size %d,%d", x, y);
665                 return -EINVAL;
666         }
667
668         if(fps > 0) {
669                 DEBUG(1, "trying to set fps to %d", fps);
670                 newspeed = konicawc_find_fps(newsize, fps);
671                 DEBUG(1, "find_fps returned %d (%d)", newspeed, spd_to_fps[newsize][newspeed]);
672         }
673
674         if(newspeed > MAX_SPEED)
675                 return -EINVAL;
676
677         DEBUG(1, "setting size to %d speed to %d", newsize, newspeed);
678         if((newsize == cam->size) && (newspeed == cam->speed)) {
679                 DEBUG(1, "Nothing to do");
680                 return 0;
681         }
682         DEBUG(0, "setting to  %dx%d @ %d fps", camera_sizes[newsize].width,
683              camera_sizes[newsize].height, spd_to_fps[newsize][newspeed]/3);
684
685         konicawc_stop_data(uvd);
686         uvd->ifaceAltActive = spd_to_iface[newspeed];
687         DEBUG(1, "new interface = %d", uvd->ifaceAltActive);
688         cam->speed = newspeed;
689
690         if(cam->size != newsize) {
691                 cam->size = newsize;
692                 konicawc_set_camera_size(uvd);
693         }
694
695         /* Flush the input queue and clear any current frame in progress */
696
697         RingQueue_Flush(&uvd->dp);
698         cam->lastframe = -2;
699         if(uvd->curframe != -1) {
700                 uvd->frame[uvd->curframe].curline = 0;
701                 uvd->frame[uvd->curframe].seqRead_Length = 0;
702                 uvd->frame[uvd->curframe].seqRead_Index = 0;
703         }
704
705         konicawc_start_data(uvd);
706         return 0;
707 }
708
709
710 static int konicawc_calculate_fps(struct uvd *uvd)
711 {
712         struct konicawc *cam = uvd->user_data;
713         return spd_to_fps[cam->size][cam->speed]/3;
714 }
715
716
717 static void konicawc_configure_video(struct uvd *uvd)
718 {
719         struct konicawc *cam = (struct konicawc *)uvd->user_data;
720         u8 buf[2];
721
722         memset(&uvd->vpic, 0, sizeof(uvd->vpic));
723         memset(&uvd->vpic_old, 0x55, sizeof(uvd->vpic_old));
724
725         RESTRICT_TO_RANGE(brightness, 0, MAX_BRIGHTNESS);
726         RESTRICT_TO_RANGE(contrast, 0, MAX_CONTRAST);
727         RESTRICT_TO_RANGE(saturation, 0, MAX_SATURATION);
728         RESTRICT_TO_RANGE(sharpness, 0, MAX_SHARPNESS);
729         RESTRICT_TO_RANGE(whitebal, 0, MAX_WHITEBAL);
730
731         cam->brightness = brightness / 11;
732         cam->contrast = contrast / 11;
733         cam->saturation = saturation / 11;
734         cam->sharpness = sharpness / 11;
735         cam->white_bal = whitebal / 11;
736
737         uvd->vpic.colour = 108;
738         uvd->vpic.hue = 108;
739         uvd->vpic.brightness = brightness;
740         uvd->vpic.contrast = contrast;
741         uvd->vpic.whiteness = whitebal;
742         uvd->vpic.depth = 6;
743         uvd->vpic.palette = VIDEO_PALETTE_YUV420P;
744
745         memset(&uvd->vcap, 0, sizeof(uvd->vcap));
746         strcpy(uvd->vcap.name, "Konica Webcam");
747         uvd->vcap.type = VID_TYPE_CAPTURE;
748         uvd->vcap.channels = 1;
749         uvd->vcap.audios = 0;
750         uvd->vcap.minwidth = camera_sizes[SIZE_160X120].width;
751         uvd->vcap.minheight = camera_sizes[SIZE_160X120].height;
752         uvd->vcap.maxwidth = camera_sizes[SIZE_320X240].width;
753         uvd->vcap.maxheight = camera_sizes[SIZE_320X240].height;
754
755         memset(&uvd->vchan, 0, sizeof(uvd->vchan));
756         uvd->vchan.flags = 0 ;
757         uvd->vchan.tuners = 0;
758         uvd->vchan.channel = 0;
759         uvd->vchan.type = VIDEO_TYPE_CAMERA;
760         strcpy(uvd->vchan.name, "Camera");
761
762         /* Talk to device */
763         DEBUG(1, "device init");
764         if(!konicawc_get_misc(uvd, 0x3, 0, 0x10, buf, 2))
765                 DEBUG(2, "3,10 -> %2.2x %2.2x", buf[0], buf[1]);
766         if(!konicawc_get_misc(uvd, 0x3, 0, 0x10, buf, 2))
767                 DEBUG(2, "3,10 -> %2.2x %2.2x", buf[0], buf[1]);
768         if(konicawc_set_misc(uvd, 0x2, 0, 0xd))
769                 DEBUG(2, "2,0,d failed");
770         DEBUG(1, "setting initial values");
771 }
772
773 static int konicawc_probe(struct usb_interface *intf, const struct usb_device_id *devid)
774 {
775         struct usb_device *dev = interface_to_usbdev(intf);
776         struct uvd *uvd = NULL;
777         int ix, i, nas;
778         int actInterface=-1, inactInterface=-1, maxPS=0;
779         unsigned char video_ep = 0;
780
781         DEBUG(1, "konicawc_probe(%p)", intf);
782
783         /* We don't handle multi-config cameras */
784         if (dev->descriptor.bNumConfigurations != 1)
785                 return -ENODEV;
786
787         info("Konica Webcam (rev. 0x%04x)", le16_to_cpu(dev->descriptor.bcdDevice));
788         RESTRICT_TO_RANGE(speed, 0, MAX_SPEED);
789
790         /* Validate found interface: must have one ISO endpoint */
791         nas = intf->num_altsetting;
792         if (nas != 8) {
793                 err("Incorrect number of alternate settings (%d) for this camera!", nas);
794                 return -ENODEV;
795         }
796         /* Validate all alternate settings */
797         for (ix=0; ix < nas; ix++) {
798                 const struct usb_host_interface *interface;
799                 const struct usb_endpoint_descriptor *endpoint;
800
801                 interface = &intf->altsetting[ix];
802                 i = interface->desc.bAlternateSetting;
803                 if (interface->desc.bNumEndpoints != 2) {
804                         err("Interface %d. has %u. endpoints!",
805                             interface->desc.bInterfaceNumber,
806                             (unsigned)(interface->desc.bNumEndpoints));
807                         return -ENODEV;
808                 }
809                 endpoint = &interface->endpoint[1].desc;
810                 DEBUG(1, "found endpoint: addr: 0x%2.2x maxps = 0x%4.4x",
811                     endpoint->bEndpointAddress, le16_to_cpu(endpoint->wMaxPacketSize));
812                 if (video_ep == 0)
813                         video_ep = endpoint->bEndpointAddress;
814                 else if (video_ep != endpoint->bEndpointAddress) {
815                         err("Alternate settings have different endpoint addresses!");
816                         return -ENODEV;
817                 }
818                 if ((endpoint->bmAttributes & 0x03) != 0x01) {
819                         err("Interface %d. has non-ISO endpoint!",
820                             interface->desc.bInterfaceNumber);
821                         return -ENODEV;
822                 }
823                 if ((endpoint->bEndpointAddress & 0x80) == 0) {
824                         err("Interface %d. has ISO OUT endpoint!",
825                             interface->desc.bInterfaceNumber);
826                         return -ENODEV;
827                 }
828                 if (le16_to_cpu(endpoint->wMaxPacketSize) == 0) {
829                         if (inactInterface < 0)
830                                 inactInterface = i;
831                         else {
832                                 err("More than one inactive alt. setting!");
833                                 return -ENODEV;
834                         }
835                 } else {
836                         if (i == spd_to_iface[speed]) {
837                                 /* This one is the requested one */
838                                 actInterface = i;
839                         }
840                 }
841                 if (le16_to_cpu(endpoint->wMaxPacketSize) > maxPS)
842                         maxPS = le16_to_cpu(endpoint->wMaxPacketSize);
843         }
844         if(actInterface == -1) {
845                 err("Cant find required endpoint");
846                 return -ENODEV;
847         }
848
849         DEBUG(1, "Selecting requested active setting=%d. maxPS=%d.", actInterface, maxPS);
850
851         uvd = usbvideo_AllocateDevice(cams);
852         if (uvd != NULL) {
853                 struct konicawc *cam = (struct konicawc *)(uvd->user_data);
854                 /* Here uvd is a fully allocated uvd object */
855                 for(i = 0; i < USBVIDEO_NUMSBUF; i++) {
856                         cam->sts_urb[i] = usb_alloc_urb(FRAMES_PER_DESC, GFP_KERNEL);
857                         if(cam->sts_urb[i] == NULL) {
858                                 while(i--) {
859                                         usb_free_urb(cam->sts_urb[i]);
860                                 }
861                                 err("can't allocate urbs");
862                                 return -ENOMEM;
863                         }
864                 }
865                 cam->speed = speed;
866                 RESTRICT_TO_RANGE(size, SIZE_160X120, SIZE_320X240);
867                 cam->width = camera_sizes[size].width;
868                 cam->height = camera_sizes[size].height;
869                 cam->size = size;
870
871                 uvd->flags = 0;
872                 uvd->debug = debug;
873                 uvd->dev = dev;
874                 uvd->iface = intf->altsetting->desc.bInterfaceNumber;
875                 uvd->ifaceAltInactive = inactInterface;
876                 uvd->ifaceAltActive = actInterface;
877                 uvd->video_endp = video_ep;
878                 uvd->iso_packet_len = maxPS;
879                 uvd->paletteBits = 1L << VIDEO_PALETTE_YUV420P;
880                 uvd->defaultPalette = VIDEO_PALETTE_YUV420P;
881                 uvd->canvas = VIDEOSIZE(320, 240);
882                 uvd->videosize = VIDEOSIZE(cam->width, cam->height);
883
884                 /* Initialize konicawc specific data */
885                 konicawc_configure_video(uvd);
886
887                 i = usbvideo_RegisterVideoDevice(uvd);
888                 uvd->max_frame_size = (320 * 240 * 3)/2;
889                 if (i != 0) {
890                         err("usbvideo_RegisterVideoDevice() failed.");
891                         uvd = NULL;
892                 }
893
894                 konicawc_register_input(cam, dev);
895         }
896
897         if (uvd) {
898                 usb_set_intfdata (intf, uvd);
899                 return 0;
900         }
901         return -EIO;
902 }
903
904
905 static void konicawc_free_uvd(struct uvd *uvd)
906 {
907         int i;
908         struct konicawc *cam = (struct konicawc *)uvd->user_data;
909
910         konicawc_unregister_input(cam);
911
912         for (i = 0; i < USBVIDEO_NUMSBUF; i++) {
913                 usb_free_urb(cam->sts_urb[i]);
914                 cam->sts_urb[i] = NULL;
915         }
916 }
917
918
919 static struct usb_device_id id_table[] = {
920         { USB_DEVICE(0x04c8, 0x0720) }, /* Intel YC 76 */
921         { }  /* Terminating entry */
922 };
923
924
925 static int __init konicawc_init(void)
926 {
927         struct usbvideo_cb cbTbl;
928         info(DRIVER_DESC " " DRIVER_VERSION);
929         memset(&cbTbl, 0, sizeof(cbTbl));
930         cbTbl.probe = konicawc_probe;
931         cbTbl.setupOnOpen = konicawc_setup_on_open;
932         cbTbl.processData = konicawc_process_isoc;
933         cbTbl.getFPS = konicawc_calculate_fps;
934         cbTbl.setVideoMode = konicawc_set_video_mode;
935         cbTbl.startDataPump = konicawc_start_data;
936         cbTbl.stopDataPump = konicawc_stop_data;
937         cbTbl.adjustPicture = konicawc_adjust_picture;
938         cbTbl.userFree = konicawc_free_uvd;
939         return usbvideo_register(
940                 &cams,
941                 MAX_CAMERAS,
942                 sizeof(struct konicawc),
943                 "konicawc",
944                 &cbTbl,
945                 THIS_MODULE,
946                 id_table);
947 }
948
949
950 static void __exit konicawc_cleanup(void)
951 {
952         usbvideo_Deregister(&cams);
953 }
954
955
956 MODULE_DEVICE_TABLE(usb, id_table);
957
958 MODULE_LICENSE("GPL");
959 MODULE_AUTHOR("Simon Evans <spse@secret.org.uk>");
960 MODULE_DESCRIPTION(DRIVER_DESC);
961 module_param(speed, int, 0);
962 MODULE_PARM_DESC(speed, "Initial speed: 0 (slowest) - 6 (fastest)");
963 module_param(size, int, 0);
964 MODULE_PARM_DESC(size, "Initial Size 0: 160x120 1: 160x136 2: 176x144 3: 320x240");
965 module_param(brightness, int, 0);
966 MODULE_PARM_DESC(brightness, "Initial brightness 0 - 108");
967 module_param(contrast, int, 0);
968 MODULE_PARM_DESC(contrast, "Initial contrast 0 - 108");
969 module_param(saturation, int, 0);
970 MODULE_PARM_DESC(saturation, "Initial saturation 0 - 108");
971 module_param(sharpness, int, 0);
972 MODULE_PARM_DESC(sharpness, "Initial brightness 0 - 108");
973 module_param(whitebal, int, 0);
974 MODULE_PARM_DESC(whitebal, "Initial white balance 0 - 363");
975
976 #ifdef CONFIG_USB_DEBUG
977 module_param(debug, int, S_IRUGO | S_IWUSR);
978 MODULE_PARM_DESC(debug, "Debug level: 0-9 (default=0)");
979 #endif
980
981 module_init(konicawc_init);
982 module_exit(konicawc_cleanup);