3f401fbd0ecc675391bd16e6421df43ddd660468
[sfrench/cifs-2.6.git] / drivers / media / usb / cpia2 / cpia2_v4l.c
1 /****************************************************************************
2  *
3  *  Filename: cpia2_v4l.c
4  *
5  *  Copyright 2001, STMicrolectronics, Inc.
6  *      Contact:  steve.miller@st.com
7  *  Copyright 2001,2005, Scott J. Bertin <scottbertin@yahoo.com>
8  *
9  *  Description:
10  *     This is a USB driver for CPia2 based video cameras.
11  *     The infrastructure of this driver is based on the cpia usb driver by
12  *     Jochen Scharrlach and Johannes Erdfeldt.
13  *
14  *  This program is free software; you can redistribute it and/or modify
15  *  it under the terms of the GNU General Public License as published by
16  *  the Free Software Foundation; either version 2 of the License, or
17  *  (at your option) any later version.
18  *
19  *  This program is distributed in the hope that it will be useful,
20  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
21  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  *  GNU General Public License for more details.
23  *
24  *  Stripped of 2.4 stuff ready for main kernel submit by
25  *              Alan Cox <alan@lxorguk.ukuu.org.uk>
26  ****************************************************************************/
27
28 #define CPIA_VERSION "3.0.1"
29
30 #include <linux/module.h>
31 #include <linux/time.h>
32 #include <linux/sched.h>
33 #include <linux/slab.h>
34 #include <linux/init.h>
35 #include <linux/videodev2.h>
36 #include <linux/stringify.h>
37 #include <media/v4l2-ioctl.h>
38 #include <media/v4l2-event.h>
39
40 #include "cpia2.h"
41
42 static int video_nr = -1;
43 module_param(video_nr, int, 0);
44 MODULE_PARM_DESC(video_nr, "video device to register (0=/dev/video0, etc)");
45
46 static int buffer_size = 68 * 1024;
47 module_param(buffer_size, int, 0);
48 MODULE_PARM_DESC(buffer_size, "Size for each frame buffer in bytes (default 68k)");
49
50 static int num_buffers = 3;
51 module_param(num_buffers, int, 0);
52 MODULE_PARM_DESC(num_buffers, "Number of frame buffers (1-"
53                  __stringify(VIDEO_MAX_FRAME) ", default 3)");
54
55 static int alternate = DEFAULT_ALT;
56 module_param(alternate, int, 0);
57 MODULE_PARM_DESC(alternate, "USB Alternate (" __stringify(USBIF_ISO_1) "-"
58                  __stringify(USBIF_ISO_6) ", default "
59                  __stringify(DEFAULT_ALT) ")");
60
61 static int flicker_mode;
62 module_param(flicker_mode, int, 0);
63 MODULE_PARM_DESC(flicker_mode, "Flicker frequency (0 (disabled), " __stringify(50) " or "
64                  __stringify(60) ", default 0)");
65
66 MODULE_AUTHOR("Steve Miller (STMicroelectronics) <steve.miller@st.com>");
67 MODULE_DESCRIPTION("V4L-driver for STMicroelectronics CPiA2 based cameras");
68 MODULE_SUPPORTED_DEVICE("video");
69 MODULE_LICENSE("GPL");
70 MODULE_VERSION(CPIA_VERSION);
71
72 #define ABOUT "V4L-Driver for Vision CPiA2 based cameras"
73 #define CPIA2_CID_USB_ALT (V4L2_CID_USER_BASE | 0xf000)
74
75 /******************************************************************************
76  *
77  *  cpia2_open
78  *
79  *****************************************************************************/
80 static int cpia2_open(struct file *file)
81 {
82         struct camera_data *cam = video_drvdata(file);
83         int retval;
84
85         if (mutex_lock_interruptible(&cam->v4l2_lock))
86                 return -ERESTARTSYS;
87         retval = v4l2_fh_open(file);
88         if (retval)
89                 goto open_unlock;
90
91         if (v4l2_fh_is_singular_file(file)) {
92                 if (cpia2_allocate_buffers(cam)) {
93                         v4l2_fh_release(file);
94                         retval = -ENOMEM;
95                         goto open_unlock;
96                 }
97
98                 /* reset the camera */
99                 if (cpia2_reset_camera(cam) < 0) {
100                         v4l2_fh_release(file);
101                         retval = -EIO;
102                         goto open_unlock;
103                 }
104
105                 cam->APP_len = 0;
106                 cam->COM_len = 0;
107         }
108
109         cpia2_dbg_dump_registers(cam);
110 open_unlock:
111         mutex_unlock(&cam->v4l2_lock);
112         return retval;
113 }
114
115 /******************************************************************************
116  *
117  *  cpia2_close
118  *
119  *****************************************************************************/
120 static int cpia2_close(struct file *file)
121 {
122         struct video_device *dev = video_devdata(file);
123         struct camera_data *cam = video_get_drvdata(dev);
124
125         mutex_lock(&cam->v4l2_lock);
126         if (video_is_registered(&cam->vdev) && v4l2_fh_is_singular_file(file)) {
127                 cpia2_usb_stream_stop(cam);
128
129                 /* save camera state for later open */
130                 cpia2_save_camera_state(cam);
131
132                 cpia2_set_low_power(cam);
133                 cpia2_free_buffers(cam);
134         }
135
136         if (cam->stream_fh == file->private_data) {
137                 cam->stream_fh = NULL;
138                 cam->mmapped = 0;
139         }
140         mutex_unlock(&cam->v4l2_lock);
141         return v4l2_fh_release(file);
142 }
143
144 /******************************************************************************
145  *
146  *  cpia2_v4l_read
147  *
148  *****************************************************************************/
149 static ssize_t cpia2_v4l_read(struct file *file, char __user *buf, size_t count,
150                               loff_t *off)
151 {
152         struct camera_data *cam = video_drvdata(file);
153         int noblock = file->f_flags&O_NONBLOCK;
154         ssize_t ret;
155
156         if(!cam)
157                 return -EINVAL;
158
159         if (mutex_lock_interruptible(&cam->v4l2_lock))
160                 return -ERESTARTSYS;
161         ret = cpia2_read(cam, buf, count, noblock);
162         mutex_unlock(&cam->v4l2_lock);
163         return ret;
164 }
165
166
167 /******************************************************************************
168  *
169  *  cpia2_v4l_poll
170  *
171  *****************************************************************************/
172 static __poll_t cpia2_v4l_poll(struct file *filp, struct poll_table_struct *wait)
173 {
174         struct camera_data *cam = video_drvdata(filp);
175         __poll_t res;
176
177         mutex_lock(&cam->v4l2_lock);
178         res = cpia2_poll(cam, filp, wait);
179         mutex_unlock(&cam->v4l2_lock);
180         return res;
181 }
182
183
184 static int sync(struct camera_data *cam, int frame_nr)
185 {
186         struct framebuf *frame = &cam->buffers[frame_nr];
187
188         while (1) {
189                 if (frame->status == FRAME_READY)
190                         return 0;
191
192                 if (!cam->streaming) {
193                         frame->status = FRAME_READY;
194                         frame->length = 0;
195                         return 0;
196                 }
197
198                 mutex_unlock(&cam->v4l2_lock);
199                 wait_event_interruptible(cam->wq_stream,
200                                          !cam->streaming ||
201                                          frame->status == FRAME_READY);
202                 mutex_lock(&cam->v4l2_lock);
203                 if (signal_pending(current))
204                         return -ERESTARTSYS;
205                 if (!video_is_registered(&cam->vdev))
206                         return -ENOTTY;
207         }
208 }
209
210 /******************************************************************************
211  *
212  *  ioctl_querycap
213  *
214  *  V4L2 device capabilities
215  *
216  *****************************************************************************/
217
218 static int cpia2_querycap(struct file *file, void *fh, struct v4l2_capability *vc)
219 {
220         struct camera_data *cam = video_drvdata(file);
221
222         strscpy(vc->driver, "cpia2", sizeof(vc->driver));
223
224         if (cam->params.pnp_id.product == 0x151)
225                 strscpy(vc->card, "QX5 Microscope", sizeof(vc->card));
226         else
227                 strscpy(vc->card, "CPiA2 Camera", sizeof(vc->card));
228         switch (cam->params.pnp_id.device_type) {
229         case DEVICE_STV_672:
230                 strcat(vc->card, " (672/");
231                 break;
232         case DEVICE_STV_676:
233                 strcat(vc->card, " (676/");
234                 break;
235         default:
236                 strcat(vc->card, " (XXX/");
237                 break;
238         }
239         switch (cam->params.version.sensor_flags) {
240         case CPIA2_VP_SENSOR_FLAGS_404:
241                 strcat(vc->card, "404)");
242                 break;
243         case CPIA2_VP_SENSOR_FLAGS_407:
244                 strcat(vc->card, "407)");
245                 break;
246         case CPIA2_VP_SENSOR_FLAGS_409:
247                 strcat(vc->card, "409)");
248                 break;
249         case CPIA2_VP_SENSOR_FLAGS_410:
250                 strcat(vc->card, "410)");
251                 break;
252         case CPIA2_VP_SENSOR_FLAGS_500:
253                 strcat(vc->card, "500)");
254                 break;
255         default:
256                 strcat(vc->card, "XXX)");
257                 break;
258         }
259
260         if (usb_make_path(cam->dev, vc->bus_info, sizeof(vc->bus_info)) <0)
261                 memset(vc->bus_info,0, sizeof(vc->bus_info));
262
263         vc->device_caps = V4L2_CAP_VIDEO_CAPTURE |
264                            V4L2_CAP_READWRITE |
265                            V4L2_CAP_STREAMING;
266         vc->capabilities = vc->device_caps |
267                            V4L2_CAP_DEVICE_CAPS;
268
269         return 0;
270 }
271
272 /******************************************************************************
273  *
274  *  ioctl_input
275  *
276  *  V4L2 input get/set/enumerate
277  *
278  *****************************************************************************/
279
280 static int cpia2_enum_input(struct file *file, void *fh, struct v4l2_input *i)
281 {
282         if (i->index)
283                 return -EINVAL;
284         strscpy(i->name, "Camera", sizeof(i->name));
285         i->type = V4L2_INPUT_TYPE_CAMERA;
286         return 0;
287 }
288
289 static int cpia2_g_input(struct file *file, void *fh, unsigned int *i)
290 {
291         *i = 0;
292         return 0;
293 }
294
295 static int cpia2_s_input(struct file *file, void *fh, unsigned int i)
296 {
297         return i ? -EINVAL : 0;
298 }
299
300 /******************************************************************************
301  *
302  *  ioctl_enum_fmt
303  *
304  *  V4L2 format enumerate
305  *
306  *****************************************************************************/
307
308 static int cpia2_enum_fmt_vid_cap(struct file *file, void *fh,
309                                             struct v4l2_fmtdesc *f)
310 {
311         int index = f->index;
312
313         if (index < 0 || index > 1)
314                return -EINVAL;
315
316         memset(f, 0, sizeof(*f));
317         f->index = index;
318         f->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
319         f->flags = V4L2_FMT_FLAG_COMPRESSED;
320         switch(index) {
321         case 0:
322                 strscpy(f->description, "MJPEG", sizeof(f->description));
323                 f->pixelformat = V4L2_PIX_FMT_MJPEG;
324                 break;
325         case 1:
326                 strscpy(f->description, "JPEG", sizeof(f->description));
327                 f->pixelformat = V4L2_PIX_FMT_JPEG;
328                 break;
329         default:
330                 return -EINVAL;
331         }
332
333         return 0;
334 }
335
336 /******************************************************************************
337  *
338  *  ioctl_try_fmt
339  *
340  *  V4L2 format try
341  *
342  *****************************************************************************/
343
344 static int cpia2_try_fmt_vid_cap(struct file *file, void *fh,
345                                           struct v4l2_format *f)
346 {
347         struct camera_data *cam = video_drvdata(file);
348
349         if (f->fmt.pix.pixelformat != V4L2_PIX_FMT_MJPEG &&
350             f->fmt.pix.pixelformat != V4L2_PIX_FMT_JPEG)
351                return -EINVAL;
352
353         f->fmt.pix.field = V4L2_FIELD_NONE;
354         f->fmt.pix.bytesperline = 0;
355         f->fmt.pix.sizeimage = cam->frame_size;
356         f->fmt.pix.colorspace = V4L2_COLORSPACE_JPEG;
357         f->fmt.pix.priv = 0;
358
359         switch (cpia2_match_video_size(f->fmt.pix.width, f->fmt.pix.height)) {
360         case VIDEOSIZE_VGA:
361                 f->fmt.pix.width = 640;
362                 f->fmt.pix.height = 480;
363                 break;
364         case VIDEOSIZE_CIF:
365                 f->fmt.pix.width = 352;
366                 f->fmt.pix.height = 288;
367                 break;
368         case VIDEOSIZE_QVGA:
369                 f->fmt.pix.width = 320;
370                 f->fmt.pix.height = 240;
371                 break;
372         case VIDEOSIZE_288_216:
373                 f->fmt.pix.width = 288;
374                 f->fmt.pix.height = 216;
375                 break;
376         case VIDEOSIZE_256_192:
377                 f->fmt.pix.width = 256;
378                 f->fmt.pix.height = 192;
379                 break;
380         case VIDEOSIZE_224_168:
381                 f->fmt.pix.width = 224;
382                 f->fmt.pix.height = 168;
383                 break;
384         case VIDEOSIZE_192_144:
385                 f->fmt.pix.width = 192;
386                 f->fmt.pix.height = 144;
387                 break;
388         case VIDEOSIZE_QCIF:
389         default:
390                 f->fmt.pix.width = 176;
391                 f->fmt.pix.height = 144;
392                 break;
393         }
394
395         return 0;
396 }
397
398 /******************************************************************************
399  *
400  *  ioctl_set_fmt
401  *
402  *  V4L2 format set
403  *
404  *****************************************************************************/
405
406 static int cpia2_s_fmt_vid_cap(struct file *file, void *_fh,
407                                         struct v4l2_format *f)
408 {
409         struct camera_data *cam = video_drvdata(file);
410         int err, frame;
411
412         err = cpia2_try_fmt_vid_cap(file, _fh, f);
413         if(err != 0)
414                 return err;
415
416         cam->pixelformat = f->fmt.pix.pixelformat;
417
418         /* NOTE: This should be set to 1 for MJPEG, but some apps don't handle
419          * the missing Huffman table properly. */
420         cam->params.compression.inhibit_htables = 0;
421                 /*f->fmt.pix.pixelformat == V4L2_PIX_FMT_MJPEG;*/
422
423         /* we set the video window to something smaller or equal to what
424          * is requested by the user???
425          */
426         DBG("Requested width = %d, height = %d\n",
427             f->fmt.pix.width, f->fmt.pix.height);
428         if (f->fmt.pix.width != cam->width ||
429             f->fmt.pix.height != cam->height) {
430                 cam->width = f->fmt.pix.width;
431                 cam->height = f->fmt.pix.height;
432                 cam->params.roi.width = f->fmt.pix.width;
433                 cam->params.roi.height = f->fmt.pix.height;
434                 cpia2_set_format(cam);
435         }
436
437         for (frame = 0; frame < cam->num_frames; ++frame) {
438                 if (cam->buffers[frame].status == FRAME_READING)
439                         if ((err = sync(cam, frame)) < 0)
440                                 return err;
441
442                 cam->buffers[frame].status = FRAME_EMPTY;
443         }
444
445         return 0;
446 }
447
448 /******************************************************************************
449  *
450  *  ioctl_get_fmt
451  *
452  *  V4L2 format get
453  *
454  *****************************************************************************/
455
456 static int cpia2_g_fmt_vid_cap(struct file *file, void *fh,
457                                         struct v4l2_format *f)
458 {
459         struct camera_data *cam = video_drvdata(file);
460
461         f->fmt.pix.width = cam->width;
462         f->fmt.pix.height = cam->height;
463         f->fmt.pix.pixelformat = cam->pixelformat;
464         f->fmt.pix.field = V4L2_FIELD_NONE;
465         f->fmt.pix.bytesperline = 0;
466         f->fmt.pix.sizeimage = cam->frame_size;
467         f->fmt.pix.colorspace = V4L2_COLORSPACE_JPEG;
468         f->fmt.pix.priv = 0;
469
470         return 0;
471 }
472
473 /******************************************************************************
474  *
475  *  ioctl_cropcap
476  *
477  *  V4L2 query cropping capabilities
478  *  NOTE: cropping is currently disabled
479  *
480  *****************************************************************************/
481
482 static int cpia2_cropcap(struct file *file, void *fh, struct v4l2_cropcap *c)
483 {
484         struct camera_data *cam = video_drvdata(file);
485
486         if (c->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
487                return -EINVAL;
488
489         c->bounds.left = 0;
490         c->bounds.top = 0;
491         c->bounds.width = cam->width;
492         c->bounds.height = cam->height;
493         c->defrect.left = 0;
494         c->defrect.top = 0;
495         c->defrect.width = cam->width;
496         c->defrect.height = cam->height;
497         c->pixelaspect.numerator = 1;
498         c->pixelaspect.denominator = 1;
499
500         return 0;
501 }
502
503 struct framerate_info {
504         int value;
505         struct v4l2_fract period;
506 };
507
508 static const struct framerate_info framerate_controls[] = {
509         { CPIA2_VP_FRAMERATE_6_25, { 4, 25 } },
510         { CPIA2_VP_FRAMERATE_7_5,  { 2, 15 } },
511         { CPIA2_VP_FRAMERATE_12_5, { 2, 25 } },
512         { CPIA2_VP_FRAMERATE_15,   { 1, 15 } },
513         { CPIA2_VP_FRAMERATE_25,   { 1, 25 } },
514         { CPIA2_VP_FRAMERATE_30,   { 1, 30 } },
515 };
516
517 static int cpia2_g_parm(struct file *file, void *fh, struct v4l2_streamparm *p)
518 {
519         struct camera_data *cam = video_drvdata(file);
520         struct v4l2_captureparm *cap = &p->parm.capture;
521         int i;
522
523         if (p->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
524                 return -EINVAL;
525
526         cap->capability = V4L2_CAP_TIMEPERFRAME;
527         cap->readbuffers = cam->num_frames;
528         for (i = 0; i < ARRAY_SIZE(framerate_controls); i++)
529                 if (cam->params.vp_params.frame_rate == framerate_controls[i].value) {
530                         cap->timeperframe = framerate_controls[i].period;
531                         break;
532                 }
533         return 0;
534 }
535
536 static int cpia2_s_parm(struct file *file, void *fh, struct v4l2_streamparm *p)
537 {
538         struct camera_data *cam = video_drvdata(file);
539         struct v4l2_captureparm *cap = &p->parm.capture;
540         struct v4l2_fract tpf = cap->timeperframe;
541         int max = ARRAY_SIZE(framerate_controls) - 1;
542         int ret;
543         int i;
544
545         ret = cpia2_g_parm(file, fh, p);
546         if (ret || !tpf.denominator || !tpf.numerator)
547                 return ret;
548
549         /* Maximum 15 fps for this model */
550         if (cam->params.pnp_id.device_type == DEVICE_STV_672 &&
551             cam->params.version.sensor_flags == CPIA2_VP_SENSOR_FLAGS_500)
552                 max -= 2;
553         for (i = 0; i <= max; i++) {
554                 struct v4l2_fract f1 = tpf;
555                 struct v4l2_fract f2 = framerate_controls[i].period;
556
557                 f1.numerator *= f2.denominator;
558                 f2.numerator *= f1.denominator;
559                 if (f1.numerator >= f2.numerator)
560                         break;
561         }
562         if (i > max)
563                 i = max;
564         cap->timeperframe = framerate_controls[i].period;
565         return cpia2_set_fps(cam, framerate_controls[i].value);
566 }
567
568 static const struct {
569         u32 width;
570         u32 height;
571 } cpia2_framesizes[] = {
572         { 640, 480 },
573         { 352, 288 },
574         { 320, 240 },
575         { 288, 216 },
576         { 256, 192 },
577         { 224, 168 },
578         { 192, 144 },
579         { 176, 144 },
580 };
581
582 static int cpia2_enum_framesizes(struct file *file, void *fh,
583                                          struct v4l2_frmsizeenum *fsize)
584 {
585
586         if (fsize->pixel_format != V4L2_PIX_FMT_MJPEG &&
587             fsize->pixel_format != V4L2_PIX_FMT_JPEG)
588                 return -EINVAL;
589         if (fsize->index >= ARRAY_SIZE(cpia2_framesizes))
590                 return -EINVAL;
591         fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
592         fsize->discrete.width = cpia2_framesizes[fsize->index].width;
593         fsize->discrete.height = cpia2_framesizes[fsize->index].height;
594
595         return 0;
596 }
597
598 static int cpia2_enum_frameintervals(struct file *file, void *fh,
599                                            struct v4l2_frmivalenum *fival)
600 {
601         struct camera_data *cam = video_drvdata(file);
602         int max = ARRAY_SIZE(framerate_controls) - 1;
603         int i;
604
605         if (fival->pixel_format != V4L2_PIX_FMT_MJPEG &&
606             fival->pixel_format != V4L2_PIX_FMT_JPEG)
607                 return -EINVAL;
608
609         /* Maximum 15 fps for this model */
610         if (cam->params.pnp_id.device_type == DEVICE_STV_672 &&
611             cam->params.version.sensor_flags == CPIA2_VP_SENSOR_FLAGS_500)
612                 max -= 2;
613         if (fival->index > max)
614                 return -EINVAL;
615         for (i = 0; i < ARRAY_SIZE(cpia2_framesizes); i++)
616                 if (fival->width == cpia2_framesizes[i].width &&
617                     fival->height == cpia2_framesizes[i].height)
618                         break;
619         if (i == ARRAY_SIZE(cpia2_framesizes))
620                 return -EINVAL;
621         fival->type = V4L2_FRMIVAL_TYPE_DISCRETE;
622         fival->discrete = framerate_controls[fival->index].period;
623         return 0;
624 }
625
626 /******************************************************************************
627  *
628  *  ioctl_s_ctrl
629  *
630  *  V4L2 set the value of a control variable
631  *
632  *****************************************************************************/
633
634 static int cpia2_s_ctrl(struct v4l2_ctrl *ctrl)
635 {
636         struct camera_data *cam =
637                 container_of(ctrl->handler, struct camera_data, hdl);
638         static const int flicker_table[] = {
639                 NEVER_FLICKER,
640                 FLICKER_50,
641                 FLICKER_60,
642         };
643
644         DBG("Set control id:%d, value:%d\n", ctrl->id, ctrl->val);
645
646         switch (ctrl->id) {
647         case V4L2_CID_BRIGHTNESS:
648                 cpia2_set_brightness(cam, ctrl->val);
649                 break;
650         case V4L2_CID_CONTRAST:
651                 cpia2_set_contrast(cam, ctrl->val);
652                 break;
653         case V4L2_CID_SATURATION:
654                 cpia2_set_saturation(cam, ctrl->val);
655                 break;
656         case V4L2_CID_HFLIP:
657                 cpia2_set_property_mirror(cam, ctrl->val);
658                 break;
659         case V4L2_CID_VFLIP:
660                 cpia2_set_property_flip(cam, ctrl->val);
661                 break;
662         case V4L2_CID_POWER_LINE_FREQUENCY:
663                 return cpia2_set_flicker_mode(cam, flicker_table[ctrl->val]);
664         case V4L2_CID_ILLUMINATORS_1:
665                 return cpia2_set_gpio(cam, (cam->top_light->val << 6) |
666                                            (cam->bottom_light->val << 7));
667         case V4L2_CID_JPEG_ACTIVE_MARKER:
668                 cam->params.compression.inhibit_htables =
669                         !(ctrl->val & V4L2_JPEG_ACTIVE_MARKER_DHT);
670                 break;
671         case V4L2_CID_JPEG_COMPRESSION_QUALITY:
672                 cam->params.vc_params.quality = ctrl->val;
673                 break;
674         case CPIA2_CID_USB_ALT:
675                 cam->params.camera_state.stream_mode = ctrl->val;
676                 break;
677         default:
678                 return -EINVAL;
679         }
680
681         return 0;
682 }
683
684 /******************************************************************************
685  *
686  *  ioctl_g_jpegcomp
687  *
688  *  V4L2 get the JPEG compression parameters
689  *
690  *****************************************************************************/
691
692 static int cpia2_g_jpegcomp(struct file *file, void *fh, struct v4l2_jpegcompression *parms)
693 {
694         struct camera_data *cam = video_drvdata(file);
695
696         memset(parms, 0, sizeof(*parms));
697
698         parms->quality = 80; // TODO: Can this be made meaningful?
699
700         parms->jpeg_markers = V4L2_JPEG_MARKER_DQT | V4L2_JPEG_MARKER_DRI;
701         if(!cam->params.compression.inhibit_htables) {
702                 parms->jpeg_markers |= V4L2_JPEG_MARKER_DHT;
703         }
704
705         parms->APPn = cam->APPn;
706         parms->APP_len = cam->APP_len;
707         if(cam->APP_len > 0) {
708                 memcpy(parms->APP_data, cam->APP_data, cam->APP_len);
709                 parms->jpeg_markers |= V4L2_JPEG_MARKER_APP;
710         }
711
712         parms->COM_len = cam->COM_len;
713         if(cam->COM_len > 0) {
714                 memcpy(parms->COM_data, cam->COM_data, cam->COM_len);
715                 parms->jpeg_markers |= JPEG_MARKER_COM;
716         }
717
718         DBG("G_JPEGCOMP APP_len:%d COM_len:%d\n",
719             parms->APP_len, parms->COM_len);
720
721         return 0;
722 }
723
724 /******************************************************************************
725  *
726  *  ioctl_s_jpegcomp
727  *
728  *  V4L2 set the JPEG compression parameters
729  *  NOTE: quality and some jpeg_markers are ignored.
730  *
731  *****************************************************************************/
732
733 static int cpia2_s_jpegcomp(struct file *file, void *fh,
734                 const struct v4l2_jpegcompression *parms)
735 {
736         struct camera_data *cam = video_drvdata(file);
737
738         DBG("S_JPEGCOMP APP_len:%d COM_len:%d\n",
739             parms->APP_len, parms->COM_len);
740
741         cam->params.compression.inhibit_htables =
742                 !(parms->jpeg_markers & V4L2_JPEG_MARKER_DHT);
743
744         if(parms->APP_len != 0) {
745                 if(parms->APP_len > 0 &&
746                    parms->APP_len <= sizeof(cam->APP_data) &&
747                    parms->APPn >= 0 && parms->APPn <= 15) {
748                         cam->APPn = parms->APPn;
749                         cam->APP_len = parms->APP_len;
750                         memcpy(cam->APP_data, parms->APP_data, parms->APP_len);
751                 } else {
752                         LOG("Bad APPn Params n=%d len=%d\n",
753                             parms->APPn, parms->APP_len);
754                         return -EINVAL;
755                 }
756         } else {
757                 cam->APP_len = 0;
758         }
759
760         if(parms->COM_len != 0) {
761                 if(parms->COM_len > 0 &&
762                    parms->COM_len <= sizeof(cam->COM_data)) {
763                         cam->COM_len = parms->COM_len;
764                         memcpy(cam->COM_data, parms->COM_data, parms->COM_len);
765                 } else {
766                         LOG("Bad COM_len=%d\n", parms->COM_len);
767                         return -EINVAL;
768                 }
769         }
770
771         return 0;
772 }
773
774 /******************************************************************************
775  *
776  *  ioctl_reqbufs
777  *
778  *  V4L2 Initiate memory mapping.
779  *  NOTE: The user's request is ignored. For now the buffers are fixed.
780  *
781  *****************************************************************************/
782
783 static int cpia2_reqbufs(struct file *file, void *fh, struct v4l2_requestbuffers *req)
784 {
785         struct camera_data *cam = video_drvdata(file);
786
787         if(req->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
788            req->memory != V4L2_MEMORY_MMAP)
789                 return -EINVAL;
790
791         DBG("REQBUFS requested:%d returning:%d\n", req->count, cam->num_frames);
792         req->count = cam->num_frames;
793         memset(&req->reserved, 0, sizeof(req->reserved));
794
795         return 0;
796 }
797
798 /******************************************************************************
799  *
800  *  ioctl_querybuf
801  *
802  *  V4L2 Query memory buffer status.
803  *
804  *****************************************************************************/
805
806 static int cpia2_querybuf(struct file *file, void *fh, struct v4l2_buffer *buf)
807 {
808         struct camera_data *cam = video_drvdata(file);
809
810         if(buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
811            buf->index >= cam->num_frames)
812                 return -EINVAL;
813
814         buf->m.offset = cam->buffers[buf->index].data - cam->frame_buffer;
815         buf->length = cam->frame_size;
816
817         buf->memory = V4L2_MEMORY_MMAP;
818
819         if(cam->mmapped)
820                 buf->flags = V4L2_BUF_FLAG_MAPPED;
821         else
822                 buf->flags = 0;
823
824         buf->flags |= V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
825
826         switch (cam->buffers[buf->index].status) {
827         case FRAME_EMPTY:
828         case FRAME_ERROR:
829         case FRAME_READING:
830                 buf->bytesused = 0;
831                 buf->flags = V4L2_BUF_FLAG_QUEUED;
832                 break;
833         case FRAME_READY:
834                 buf->bytesused = cam->buffers[buf->index].length;
835                 buf->timestamp = cam->buffers[buf->index].timestamp;
836                 buf->sequence = cam->buffers[buf->index].seq;
837                 buf->flags = V4L2_BUF_FLAG_DONE;
838                 break;
839         }
840
841         DBG("QUERYBUF index:%d offset:%d flags:%d seq:%d bytesused:%d\n",
842              buf->index, buf->m.offset, buf->flags, buf->sequence,
843              buf->bytesused);
844
845         return 0;
846 }
847
848 /******************************************************************************
849  *
850  *  ioctl_qbuf
851  *
852  *  V4L2 User is freeing buffer
853  *
854  *****************************************************************************/
855
856 static int cpia2_qbuf(struct file *file, void *fh, struct v4l2_buffer *buf)
857 {
858         struct camera_data *cam = video_drvdata(file);
859
860         if(buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
861            buf->memory != V4L2_MEMORY_MMAP ||
862            buf->index >= cam->num_frames)
863                 return -EINVAL;
864
865         DBG("QBUF #%d\n", buf->index);
866
867         if(cam->buffers[buf->index].status == FRAME_READY)
868                 cam->buffers[buf->index].status = FRAME_EMPTY;
869
870         return 0;
871 }
872
873 /******************************************************************************
874  *
875  *  find_earliest_filled_buffer
876  *
877  *  Helper for ioctl_dqbuf. Find the next ready buffer.
878  *
879  *****************************************************************************/
880
881 static int find_earliest_filled_buffer(struct camera_data *cam)
882 {
883         int i;
884         int found = -1;
885         for (i=0; i<cam->num_frames; i++) {
886                 if(cam->buffers[i].status == FRAME_READY) {
887                         if(found < 0) {
888                                 found = i;
889                         } else {
890                                 /* find which buffer is earlier */
891                                 struct timeval *tv1, *tv2;
892                                 tv1 = &cam->buffers[i].timestamp;
893                                 tv2 = &cam->buffers[found].timestamp;
894                                 if(tv1->tv_sec < tv2->tv_sec ||
895                                    (tv1->tv_sec == tv2->tv_sec &&
896                                     tv1->tv_usec < tv2->tv_usec))
897                                         found = i;
898                         }
899                 }
900         }
901         return found;
902 }
903
904 /******************************************************************************
905  *
906  *  ioctl_dqbuf
907  *
908  *  V4L2 User is asking for a filled buffer.
909  *
910  *****************************************************************************/
911
912 static int cpia2_dqbuf(struct file *file, void *fh, struct v4l2_buffer *buf)
913 {
914         struct camera_data *cam = video_drvdata(file);
915         int frame;
916
917         if(buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
918            buf->memory != V4L2_MEMORY_MMAP)
919                 return -EINVAL;
920
921         frame = find_earliest_filled_buffer(cam);
922
923         if(frame < 0 && file->f_flags&O_NONBLOCK)
924                 return -EAGAIN;
925
926         if(frame < 0) {
927                 /* Wait for a frame to become available */
928                 struct framebuf *cb=cam->curbuff;
929                 mutex_unlock(&cam->v4l2_lock);
930                 wait_event_interruptible(cam->wq_stream,
931                                          !video_is_registered(&cam->vdev) ||
932                                          (cb=cam->curbuff)->status == FRAME_READY);
933                 mutex_lock(&cam->v4l2_lock);
934                 if (signal_pending(current))
935                         return -ERESTARTSYS;
936                 if (!video_is_registered(&cam->vdev))
937                         return -ENOTTY;
938                 frame = cb->num;
939         }
940
941
942         buf->index = frame;
943         buf->bytesused = cam->buffers[buf->index].length;
944         buf->flags = V4L2_BUF_FLAG_MAPPED | V4L2_BUF_FLAG_DONE
945                 | V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
946         buf->field = V4L2_FIELD_NONE;
947         buf->timestamp = cam->buffers[buf->index].timestamp;
948         buf->sequence = cam->buffers[buf->index].seq;
949         buf->m.offset = cam->buffers[buf->index].data - cam->frame_buffer;
950         buf->length = cam->frame_size;
951         buf->reserved2 = 0;
952         buf->request_fd = 0;
953         memset(&buf->timecode, 0, sizeof(buf->timecode));
954
955         DBG("DQBUF #%d status:%d seq:%d length:%d\n", buf->index,
956             cam->buffers[buf->index].status, buf->sequence, buf->bytesused);
957
958         return 0;
959 }
960
961 static int cpia2_streamon(struct file *file, void *fh, enum v4l2_buf_type type)
962 {
963         struct camera_data *cam = video_drvdata(file);
964         int ret = -EINVAL;
965
966         DBG("VIDIOC_STREAMON, streaming=%d\n", cam->streaming);
967         if (!cam->mmapped || type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
968                 return -EINVAL;
969
970         if (!cam->streaming) {
971                 ret = cpia2_usb_stream_start(cam,
972                                 cam->params.camera_state.stream_mode);
973                 if (!ret)
974                         v4l2_ctrl_grab(cam->usb_alt, true);
975         }
976         return ret;
977 }
978
979 static int cpia2_streamoff(struct file *file, void *fh, enum v4l2_buf_type type)
980 {
981         struct camera_data *cam = video_drvdata(file);
982         int ret = -EINVAL;
983
984         DBG("VIDIOC_STREAMOFF, streaming=%d\n", cam->streaming);
985         if (!cam->mmapped || type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
986                 return -EINVAL;
987
988         if (cam->streaming) {
989                 ret = cpia2_usb_stream_stop(cam);
990                 if (!ret)
991                         v4l2_ctrl_grab(cam->usb_alt, false);
992         }
993         return ret;
994 }
995
996 /******************************************************************************
997  *
998  *  cpia2_mmap
999  *
1000  *****************************************************************************/
1001 static int cpia2_mmap(struct file *file, struct vm_area_struct *area)
1002 {
1003         struct camera_data *cam = video_drvdata(file);
1004         int retval;
1005
1006         if (mutex_lock_interruptible(&cam->v4l2_lock))
1007                 return -ERESTARTSYS;
1008         retval = cpia2_remap_buffer(cam, area);
1009
1010         if(!retval)
1011                 cam->stream_fh = file->private_data;
1012         mutex_unlock(&cam->v4l2_lock);
1013         return retval;
1014 }
1015
1016 /******************************************************************************
1017  *
1018  *  reset_camera_struct_v4l
1019  *
1020  *  Sets all values to the defaults
1021  *****************************************************************************/
1022 static void reset_camera_struct_v4l(struct camera_data *cam)
1023 {
1024         cam->width = cam->params.roi.width;
1025         cam->height = cam->params.roi.height;
1026
1027         cam->frame_size = buffer_size;
1028         cam->num_frames = num_buffers;
1029
1030         /* Flicker modes */
1031         cam->params.flicker_control.flicker_mode_req = flicker_mode;
1032
1033         /* stream modes */
1034         cam->params.camera_state.stream_mode = alternate;
1035
1036         cam->pixelformat = V4L2_PIX_FMT_JPEG;
1037 }
1038
1039 static const struct v4l2_ioctl_ops cpia2_ioctl_ops = {
1040         .vidioc_querycap                    = cpia2_querycap,
1041         .vidioc_enum_input                  = cpia2_enum_input,
1042         .vidioc_g_input                     = cpia2_g_input,
1043         .vidioc_s_input                     = cpia2_s_input,
1044         .vidioc_enum_fmt_vid_cap            = cpia2_enum_fmt_vid_cap,
1045         .vidioc_g_fmt_vid_cap               = cpia2_g_fmt_vid_cap,
1046         .vidioc_s_fmt_vid_cap               = cpia2_s_fmt_vid_cap,
1047         .vidioc_try_fmt_vid_cap             = cpia2_try_fmt_vid_cap,
1048         .vidioc_g_jpegcomp                  = cpia2_g_jpegcomp,
1049         .vidioc_s_jpegcomp                  = cpia2_s_jpegcomp,
1050         .vidioc_cropcap                     = cpia2_cropcap,
1051         .vidioc_reqbufs                     = cpia2_reqbufs,
1052         .vidioc_querybuf                    = cpia2_querybuf,
1053         .vidioc_qbuf                        = cpia2_qbuf,
1054         .vidioc_dqbuf                       = cpia2_dqbuf,
1055         .vidioc_streamon                    = cpia2_streamon,
1056         .vidioc_streamoff                   = cpia2_streamoff,
1057         .vidioc_s_parm                      = cpia2_s_parm,
1058         .vidioc_g_parm                      = cpia2_g_parm,
1059         .vidioc_enum_framesizes             = cpia2_enum_framesizes,
1060         .vidioc_enum_frameintervals         = cpia2_enum_frameintervals,
1061         .vidioc_subscribe_event             = v4l2_ctrl_subscribe_event,
1062         .vidioc_unsubscribe_event           = v4l2_event_unsubscribe,
1063 };
1064
1065 /***
1066  * The v4l video device structure initialized for this device
1067  ***/
1068 static const struct v4l2_file_operations cpia2_fops = {
1069         .owner          = THIS_MODULE,
1070         .open           = cpia2_open,
1071         .release        = cpia2_close,
1072         .read           = cpia2_v4l_read,
1073         .poll           = cpia2_v4l_poll,
1074         .unlocked_ioctl = video_ioctl2,
1075         .mmap           = cpia2_mmap,
1076 };
1077
1078 static const struct video_device cpia2_template = {
1079         /* I could not find any place for the old .initialize initializer?? */
1080         .name =         "CPiA2 Camera",
1081         .fops =         &cpia2_fops,
1082         .ioctl_ops =    &cpia2_ioctl_ops,
1083         .release =      video_device_release_empty,
1084 };
1085
1086 void cpia2_camera_release(struct v4l2_device *v4l2_dev)
1087 {
1088         struct camera_data *cam =
1089                 container_of(v4l2_dev, struct camera_data, v4l2_dev);
1090
1091         v4l2_ctrl_handler_free(&cam->hdl);
1092         v4l2_device_unregister(&cam->v4l2_dev);
1093         kfree(cam);
1094 }
1095
1096 static const struct v4l2_ctrl_ops cpia2_ctrl_ops = {
1097         .s_ctrl = cpia2_s_ctrl,
1098 };
1099
1100 /******************************************************************************
1101  *
1102  *  cpia2_register_camera
1103  *
1104  *****************************************************************************/
1105 int cpia2_register_camera(struct camera_data *cam)
1106 {
1107         struct v4l2_ctrl_handler *hdl = &cam->hdl;
1108         struct v4l2_ctrl_config cpia2_usb_alt = {
1109                 .ops = &cpia2_ctrl_ops,
1110                 .id = CPIA2_CID_USB_ALT,
1111                 .name = "USB Alternate",
1112                 .type = V4L2_CTRL_TYPE_INTEGER,
1113                 .min = USBIF_ISO_1,
1114                 .max = USBIF_ISO_6,
1115                 .step = 1,
1116         };
1117         int ret;
1118
1119         v4l2_ctrl_handler_init(hdl, 12);
1120         v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1121                         V4L2_CID_BRIGHTNESS,
1122                         cam->params.pnp_id.device_type == DEVICE_STV_672 ? 1 : 0,
1123                         255, 1, DEFAULT_BRIGHTNESS);
1124         v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1125                         V4L2_CID_CONTRAST, 0, 255, 1, DEFAULT_CONTRAST);
1126         v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1127                         V4L2_CID_SATURATION, 0, 255, 1, DEFAULT_SATURATION);
1128         v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1129                         V4L2_CID_HFLIP, 0, 1, 1, 0);
1130         v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1131                         V4L2_CID_JPEG_ACTIVE_MARKER, 0,
1132                         V4L2_JPEG_ACTIVE_MARKER_DHT, 0,
1133                         V4L2_JPEG_ACTIVE_MARKER_DHT);
1134         v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1135                         V4L2_CID_JPEG_COMPRESSION_QUALITY, 1,
1136                         100, 1, 100);
1137         cpia2_usb_alt.def = alternate;
1138         cam->usb_alt = v4l2_ctrl_new_custom(hdl, &cpia2_usb_alt, NULL);
1139         /* VP5 Only */
1140         if (cam->params.pnp_id.device_type != DEVICE_STV_672)
1141                 v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1142                         V4L2_CID_VFLIP, 0, 1, 1, 0);
1143         /* Flicker control only valid for 672 */
1144         if (cam->params.pnp_id.device_type == DEVICE_STV_672)
1145                 v4l2_ctrl_new_std_menu(hdl, &cpia2_ctrl_ops,
1146                         V4L2_CID_POWER_LINE_FREQUENCY,
1147                         V4L2_CID_POWER_LINE_FREQUENCY_60HZ, 0, 0);
1148         /* Light control only valid for the QX5 Microscope */
1149         if (cam->params.pnp_id.product == 0x151) {
1150                 cam->top_light = v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1151                                 V4L2_CID_ILLUMINATORS_1, 0, 1, 1, 0);
1152                 cam->bottom_light = v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1153                                 V4L2_CID_ILLUMINATORS_2, 0, 1, 1, 0);
1154                 v4l2_ctrl_cluster(2, &cam->top_light);
1155         }
1156
1157         if (hdl->error) {
1158                 ret = hdl->error;
1159                 v4l2_ctrl_handler_free(hdl);
1160                 return ret;
1161         }
1162
1163         cam->vdev = cpia2_template;
1164         video_set_drvdata(&cam->vdev, cam);
1165         cam->vdev.lock = &cam->v4l2_lock;
1166         cam->vdev.ctrl_handler = hdl;
1167         cam->vdev.v4l2_dev = &cam->v4l2_dev;
1168
1169         reset_camera_struct_v4l(cam);
1170
1171         /* register v4l device */
1172         if (video_register_device(&cam->vdev, VFL_TYPE_GRABBER, video_nr) < 0) {
1173                 ERR("video_register_device failed\n");
1174                 return -ENODEV;
1175         }
1176
1177         return 0;
1178 }
1179
1180 /******************************************************************************
1181  *
1182  *  cpia2_unregister_camera
1183  *
1184  *****************************************************************************/
1185 void cpia2_unregister_camera(struct camera_data *cam)
1186 {
1187         video_unregister_device(&cam->vdev);
1188 }
1189
1190 /******************************************************************************
1191  *
1192  *  check_parameters
1193  *
1194  *  Make sure that all user-supplied parameters are sensible
1195  *****************************************************************************/
1196 static void __init check_parameters(void)
1197 {
1198         if(buffer_size < PAGE_SIZE) {
1199                 buffer_size = PAGE_SIZE;
1200                 LOG("buffer_size too small, setting to %d\n", buffer_size);
1201         } else if(buffer_size > 1024*1024) {
1202                 /* arbitrary upper limiit */
1203                 buffer_size = 1024*1024;
1204                 LOG("buffer_size ridiculously large, setting to %d\n",
1205                     buffer_size);
1206         } else {
1207                 buffer_size += PAGE_SIZE-1;
1208                 buffer_size &= ~(PAGE_SIZE-1);
1209         }
1210
1211         if(num_buffers < 1) {
1212                 num_buffers = 1;
1213                 LOG("num_buffers too small, setting to %d\n", num_buffers);
1214         } else if(num_buffers > VIDEO_MAX_FRAME) {
1215                 num_buffers = VIDEO_MAX_FRAME;
1216                 LOG("num_buffers too large, setting to %d\n", num_buffers);
1217         }
1218
1219         if(alternate < USBIF_ISO_1 || alternate > USBIF_ISO_6) {
1220                 alternate = DEFAULT_ALT;
1221                 LOG("alternate specified is invalid, using %d\n", alternate);
1222         }
1223
1224         if (flicker_mode != 0 && flicker_mode != FLICKER_50 && flicker_mode != FLICKER_60) {
1225                 flicker_mode = 0;
1226                 LOG("Flicker mode specified is invalid, using %d\n",
1227                     flicker_mode);
1228         }
1229
1230         DBG("Using %d buffers, each %d bytes, alternate=%d\n",
1231             num_buffers, buffer_size, alternate);
1232 }
1233
1234 /************   Module Stuff ***************/
1235
1236
1237 /******************************************************************************
1238  *
1239  * cpia2_init/module_init
1240  *
1241  *****************************************************************************/
1242 static int __init cpia2_init(void)
1243 {
1244         LOG("%s v%s\n",
1245             ABOUT, CPIA_VERSION);
1246         check_parameters();
1247         cpia2_usb_init();
1248         return 0;
1249 }
1250
1251
1252 /******************************************************************************
1253  *
1254  * cpia2_exit/module_exit
1255  *
1256  *****************************************************************************/
1257 static void __exit cpia2_exit(void)
1258 {
1259         cpia2_usb_cleanup();
1260         schedule_timeout(2 * HZ);
1261 }
1262
1263 module_init(cpia2_init);
1264 module_exit(cpia2_exit);