media: cropcap/g_selection split
[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_g_selection(struct file *file, void *fh,
483                              struct v4l2_selection *s)
484 {
485         struct camera_data *cam = video_drvdata(file);
486
487         if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
488                 return -EINVAL;
489
490         switch (s->target) {
491         case V4L2_SEL_TGT_CROP_BOUNDS:
492         case V4L2_SEL_TGT_CROP_DEFAULT:
493                 s->r.left = 0;
494                 s->r.top = 0;
495                 s->r.width = cam->width;
496                 s->r.height = cam->height;
497                 break;
498         default:
499                 return -EINVAL;
500         }
501         return 0;
502 }
503
504 struct framerate_info {
505         int value;
506         struct v4l2_fract period;
507 };
508
509 static const struct framerate_info framerate_controls[] = {
510         { CPIA2_VP_FRAMERATE_6_25, { 4, 25 } },
511         { CPIA2_VP_FRAMERATE_7_5,  { 2, 15 } },
512         { CPIA2_VP_FRAMERATE_12_5, { 2, 25 } },
513         { CPIA2_VP_FRAMERATE_15,   { 1, 15 } },
514         { CPIA2_VP_FRAMERATE_25,   { 1, 25 } },
515         { CPIA2_VP_FRAMERATE_30,   { 1, 30 } },
516 };
517
518 static int cpia2_g_parm(struct file *file, void *fh, struct v4l2_streamparm *p)
519 {
520         struct camera_data *cam = video_drvdata(file);
521         struct v4l2_captureparm *cap = &p->parm.capture;
522         int i;
523
524         if (p->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
525                 return -EINVAL;
526
527         cap->capability = V4L2_CAP_TIMEPERFRAME;
528         cap->readbuffers = cam->num_frames;
529         for (i = 0; i < ARRAY_SIZE(framerate_controls); i++)
530                 if (cam->params.vp_params.frame_rate == framerate_controls[i].value) {
531                         cap->timeperframe = framerate_controls[i].period;
532                         break;
533                 }
534         return 0;
535 }
536
537 static int cpia2_s_parm(struct file *file, void *fh, struct v4l2_streamparm *p)
538 {
539         struct camera_data *cam = video_drvdata(file);
540         struct v4l2_captureparm *cap = &p->parm.capture;
541         struct v4l2_fract tpf = cap->timeperframe;
542         int max = ARRAY_SIZE(framerate_controls) - 1;
543         int ret;
544         int i;
545
546         ret = cpia2_g_parm(file, fh, p);
547         if (ret || !tpf.denominator || !tpf.numerator)
548                 return ret;
549
550         /* Maximum 15 fps for this model */
551         if (cam->params.pnp_id.device_type == DEVICE_STV_672 &&
552             cam->params.version.sensor_flags == CPIA2_VP_SENSOR_FLAGS_500)
553                 max -= 2;
554         for (i = 0; i <= max; i++) {
555                 struct v4l2_fract f1 = tpf;
556                 struct v4l2_fract f2 = framerate_controls[i].period;
557
558                 f1.numerator *= f2.denominator;
559                 f2.numerator *= f1.denominator;
560                 if (f1.numerator >= f2.numerator)
561                         break;
562         }
563         if (i > max)
564                 i = max;
565         cap->timeperframe = framerate_controls[i].period;
566         return cpia2_set_fps(cam, framerate_controls[i].value);
567 }
568
569 static const struct {
570         u32 width;
571         u32 height;
572 } cpia2_framesizes[] = {
573         { 640, 480 },
574         { 352, 288 },
575         { 320, 240 },
576         { 288, 216 },
577         { 256, 192 },
578         { 224, 168 },
579         { 192, 144 },
580         { 176, 144 },
581 };
582
583 static int cpia2_enum_framesizes(struct file *file, void *fh,
584                                          struct v4l2_frmsizeenum *fsize)
585 {
586
587         if (fsize->pixel_format != V4L2_PIX_FMT_MJPEG &&
588             fsize->pixel_format != V4L2_PIX_FMT_JPEG)
589                 return -EINVAL;
590         if (fsize->index >= ARRAY_SIZE(cpia2_framesizes))
591                 return -EINVAL;
592         fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
593         fsize->discrete.width = cpia2_framesizes[fsize->index].width;
594         fsize->discrete.height = cpia2_framesizes[fsize->index].height;
595
596         return 0;
597 }
598
599 static int cpia2_enum_frameintervals(struct file *file, void *fh,
600                                            struct v4l2_frmivalenum *fival)
601 {
602         struct camera_data *cam = video_drvdata(file);
603         int max = ARRAY_SIZE(framerate_controls) - 1;
604         int i;
605
606         if (fival->pixel_format != V4L2_PIX_FMT_MJPEG &&
607             fival->pixel_format != V4L2_PIX_FMT_JPEG)
608                 return -EINVAL;
609
610         /* Maximum 15 fps for this model */
611         if (cam->params.pnp_id.device_type == DEVICE_STV_672 &&
612             cam->params.version.sensor_flags == CPIA2_VP_SENSOR_FLAGS_500)
613                 max -= 2;
614         if (fival->index > max)
615                 return -EINVAL;
616         for (i = 0; i < ARRAY_SIZE(cpia2_framesizes); i++)
617                 if (fival->width == cpia2_framesizes[i].width &&
618                     fival->height == cpia2_framesizes[i].height)
619                         break;
620         if (i == ARRAY_SIZE(cpia2_framesizes))
621                 return -EINVAL;
622         fival->type = V4L2_FRMIVAL_TYPE_DISCRETE;
623         fival->discrete = framerate_controls[fival->index].period;
624         return 0;
625 }
626
627 /******************************************************************************
628  *
629  *  ioctl_s_ctrl
630  *
631  *  V4L2 set the value of a control variable
632  *
633  *****************************************************************************/
634
635 static int cpia2_s_ctrl(struct v4l2_ctrl *ctrl)
636 {
637         struct camera_data *cam =
638                 container_of(ctrl->handler, struct camera_data, hdl);
639         static const int flicker_table[] = {
640                 NEVER_FLICKER,
641                 FLICKER_50,
642                 FLICKER_60,
643         };
644
645         DBG("Set control id:%d, value:%d\n", ctrl->id, ctrl->val);
646
647         switch (ctrl->id) {
648         case V4L2_CID_BRIGHTNESS:
649                 cpia2_set_brightness(cam, ctrl->val);
650                 break;
651         case V4L2_CID_CONTRAST:
652                 cpia2_set_contrast(cam, ctrl->val);
653                 break;
654         case V4L2_CID_SATURATION:
655                 cpia2_set_saturation(cam, ctrl->val);
656                 break;
657         case V4L2_CID_HFLIP:
658                 cpia2_set_property_mirror(cam, ctrl->val);
659                 break;
660         case V4L2_CID_VFLIP:
661                 cpia2_set_property_flip(cam, ctrl->val);
662                 break;
663         case V4L2_CID_POWER_LINE_FREQUENCY:
664                 return cpia2_set_flicker_mode(cam, flicker_table[ctrl->val]);
665         case V4L2_CID_ILLUMINATORS_1:
666                 return cpia2_set_gpio(cam, (cam->top_light->val << 6) |
667                                            (cam->bottom_light->val << 7));
668         case V4L2_CID_JPEG_ACTIVE_MARKER:
669                 cam->params.compression.inhibit_htables =
670                         !(ctrl->val & V4L2_JPEG_ACTIVE_MARKER_DHT);
671                 break;
672         case V4L2_CID_JPEG_COMPRESSION_QUALITY:
673                 cam->params.vc_params.quality = ctrl->val;
674                 break;
675         case CPIA2_CID_USB_ALT:
676                 cam->params.camera_state.stream_mode = ctrl->val;
677                 break;
678         default:
679                 return -EINVAL;
680         }
681
682         return 0;
683 }
684
685 /******************************************************************************
686  *
687  *  ioctl_g_jpegcomp
688  *
689  *  V4L2 get the JPEG compression parameters
690  *
691  *****************************************************************************/
692
693 static int cpia2_g_jpegcomp(struct file *file, void *fh, struct v4l2_jpegcompression *parms)
694 {
695         struct camera_data *cam = video_drvdata(file);
696
697         memset(parms, 0, sizeof(*parms));
698
699         parms->quality = 80; // TODO: Can this be made meaningful?
700
701         parms->jpeg_markers = V4L2_JPEG_MARKER_DQT | V4L2_JPEG_MARKER_DRI;
702         if(!cam->params.compression.inhibit_htables) {
703                 parms->jpeg_markers |= V4L2_JPEG_MARKER_DHT;
704         }
705
706         parms->APPn = cam->APPn;
707         parms->APP_len = cam->APP_len;
708         if(cam->APP_len > 0) {
709                 memcpy(parms->APP_data, cam->APP_data, cam->APP_len);
710                 parms->jpeg_markers |= V4L2_JPEG_MARKER_APP;
711         }
712
713         parms->COM_len = cam->COM_len;
714         if(cam->COM_len > 0) {
715                 memcpy(parms->COM_data, cam->COM_data, cam->COM_len);
716                 parms->jpeg_markers |= JPEG_MARKER_COM;
717         }
718
719         DBG("G_JPEGCOMP APP_len:%d COM_len:%d\n",
720             parms->APP_len, parms->COM_len);
721
722         return 0;
723 }
724
725 /******************************************************************************
726  *
727  *  ioctl_s_jpegcomp
728  *
729  *  V4L2 set the JPEG compression parameters
730  *  NOTE: quality and some jpeg_markers are ignored.
731  *
732  *****************************************************************************/
733
734 static int cpia2_s_jpegcomp(struct file *file, void *fh,
735                 const struct v4l2_jpegcompression *parms)
736 {
737         struct camera_data *cam = video_drvdata(file);
738
739         DBG("S_JPEGCOMP APP_len:%d COM_len:%d\n",
740             parms->APP_len, parms->COM_len);
741
742         cam->params.compression.inhibit_htables =
743                 !(parms->jpeg_markers & V4L2_JPEG_MARKER_DHT);
744
745         if(parms->APP_len != 0) {
746                 if(parms->APP_len > 0 &&
747                    parms->APP_len <= sizeof(cam->APP_data) &&
748                    parms->APPn >= 0 && parms->APPn <= 15) {
749                         cam->APPn = parms->APPn;
750                         cam->APP_len = parms->APP_len;
751                         memcpy(cam->APP_data, parms->APP_data, parms->APP_len);
752                 } else {
753                         LOG("Bad APPn Params n=%d len=%d\n",
754                             parms->APPn, parms->APP_len);
755                         return -EINVAL;
756                 }
757         } else {
758                 cam->APP_len = 0;
759         }
760
761         if(parms->COM_len != 0) {
762                 if(parms->COM_len > 0 &&
763                    parms->COM_len <= sizeof(cam->COM_data)) {
764                         cam->COM_len = parms->COM_len;
765                         memcpy(cam->COM_data, parms->COM_data, parms->COM_len);
766                 } else {
767                         LOG("Bad COM_len=%d\n", parms->COM_len);
768                         return -EINVAL;
769                 }
770         }
771
772         return 0;
773 }
774
775 /******************************************************************************
776  *
777  *  ioctl_reqbufs
778  *
779  *  V4L2 Initiate memory mapping.
780  *  NOTE: The user's request is ignored. For now the buffers are fixed.
781  *
782  *****************************************************************************/
783
784 static int cpia2_reqbufs(struct file *file, void *fh, struct v4l2_requestbuffers *req)
785 {
786         struct camera_data *cam = video_drvdata(file);
787
788         if(req->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
789            req->memory != V4L2_MEMORY_MMAP)
790                 return -EINVAL;
791
792         DBG("REQBUFS requested:%d returning:%d\n", req->count, cam->num_frames);
793         req->count = cam->num_frames;
794         memset(&req->reserved, 0, sizeof(req->reserved));
795
796         return 0;
797 }
798
799 /******************************************************************************
800  *
801  *  ioctl_querybuf
802  *
803  *  V4L2 Query memory buffer status.
804  *
805  *****************************************************************************/
806
807 static int cpia2_querybuf(struct file *file, void *fh, struct v4l2_buffer *buf)
808 {
809         struct camera_data *cam = video_drvdata(file);
810
811         if(buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
812            buf->index >= cam->num_frames)
813                 return -EINVAL;
814
815         buf->m.offset = cam->buffers[buf->index].data - cam->frame_buffer;
816         buf->length = cam->frame_size;
817
818         buf->memory = V4L2_MEMORY_MMAP;
819
820         if(cam->mmapped)
821                 buf->flags = V4L2_BUF_FLAG_MAPPED;
822         else
823                 buf->flags = 0;
824
825         buf->flags |= V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
826
827         switch (cam->buffers[buf->index].status) {
828         case FRAME_EMPTY:
829         case FRAME_ERROR:
830         case FRAME_READING:
831                 buf->bytesused = 0;
832                 buf->flags = V4L2_BUF_FLAG_QUEUED;
833                 break;
834         case FRAME_READY:
835                 buf->bytesused = cam->buffers[buf->index].length;
836                 buf->timestamp = cam->buffers[buf->index].timestamp;
837                 buf->sequence = cam->buffers[buf->index].seq;
838                 buf->flags = V4L2_BUF_FLAG_DONE;
839                 break;
840         }
841
842         DBG("QUERYBUF index:%d offset:%d flags:%d seq:%d bytesused:%d\n",
843              buf->index, buf->m.offset, buf->flags, buf->sequence,
844              buf->bytesused);
845
846         return 0;
847 }
848
849 /******************************************************************************
850  *
851  *  ioctl_qbuf
852  *
853  *  V4L2 User is freeing buffer
854  *
855  *****************************************************************************/
856
857 static int cpia2_qbuf(struct file *file, void *fh, struct v4l2_buffer *buf)
858 {
859         struct camera_data *cam = video_drvdata(file);
860
861         if(buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
862            buf->memory != V4L2_MEMORY_MMAP ||
863            buf->index >= cam->num_frames)
864                 return -EINVAL;
865
866         DBG("QBUF #%d\n", buf->index);
867
868         if(cam->buffers[buf->index].status == FRAME_READY)
869                 cam->buffers[buf->index].status = FRAME_EMPTY;
870
871         return 0;
872 }
873
874 /******************************************************************************
875  *
876  *  find_earliest_filled_buffer
877  *
878  *  Helper for ioctl_dqbuf. Find the next ready buffer.
879  *
880  *****************************************************************************/
881
882 static int find_earliest_filled_buffer(struct camera_data *cam)
883 {
884         int i;
885         int found = -1;
886         for (i=0; i<cam->num_frames; i++) {
887                 if(cam->buffers[i].status == FRAME_READY) {
888                         if(found < 0) {
889                                 found = i;
890                         } else {
891                                 /* find which buffer is earlier */
892                                 struct timeval *tv1, *tv2;
893                                 tv1 = &cam->buffers[i].timestamp;
894                                 tv2 = &cam->buffers[found].timestamp;
895                                 if(tv1->tv_sec < tv2->tv_sec ||
896                                    (tv1->tv_sec == tv2->tv_sec &&
897                                     tv1->tv_usec < tv2->tv_usec))
898                                         found = i;
899                         }
900                 }
901         }
902         return found;
903 }
904
905 /******************************************************************************
906  *
907  *  ioctl_dqbuf
908  *
909  *  V4L2 User is asking for a filled buffer.
910  *
911  *****************************************************************************/
912
913 static int cpia2_dqbuf(struct file *file, void *fh, struct v4l2_buffer *buf)
914 {
915         struct camera_data *cam = video_drvdata(file);
916         int frame;
917
918         if(buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
919            buf->memory != V4L2_MEMORY_MMAP)
920                 return -EINVAL;
921
922         frame = find_earliest_filled_buffer(cam);
923
924         if(frame < 0 && file->f_flags&O_NONBLOCK)
925                 return -EAGAIN;
926
927         if(frame < 0) {
928                 /* Wait for a frame to become available */
929                 struct framebuf *cb=cam->curbuff;
930                 mutex_unlock(&cam->v4l2_lock);
931                 wait_event_interruptible(cam->wq_stream,
932                                          !video_is_registered(&cam->vdev) ||
933                                          (cb=cam->curbuff)->status == FRAME_READY);
934                 mutex_lock(&cam->v4l2_lock);
935                 if (signal_pending(current))
936                         return -ERESTARTSYS;
937                 if (!video_is_registered(&cam->vdev))
938                         return -ENOTTY;
939                 frame = cb->num;
940         }
941
942
943         buf->index = frame;
944         buf->bytesused = cam->buffers[buf->index].length;
945         buf->flags = V4L2_BUF_FLAG_MAPPED | V4L2_BUF_FLAG_DONE
946                 | V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
947         buf->field = V4L2_FIELD_NONE;
948         buf->timestamp = cam->buffers[buf->index].timestamp;
949         buf->sequence = cam->buffers[buf->index].seq;
950         buf->m.offset = cam->buffers[buf->index].data - cam->frame_buffer;
951         buf->length = cam->frame_size;
952         buf->reserved2 = 0;
953         buf->request_fd = 0;
954         memset(&buf->timecode, 0, sizeof(buf->timecode));
955
956         DBG("DQBUF #%d status:%d seq:%d length:%d\n", buf->index,
957             cam->buffers[buf->index].status, buf->sequence, buf->bytesused);
958
959         return 0;
960 }
961
962 static int cpia2_streamon(struct file *file, void *fh, enum v4l2_buf_type type)
963 {
964         struct camera_data *cam = video_drvdata(file);
965         int ret = -EINVAL;
966
967         DBG("VIDIOC_STREAMON, streaming=%d\n", cam->streaming);
968         if (!cam->mmapped || type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
969                 return -EINVAL;
970
971         if (!cam->streaming) {
972                 ret = cpia2_usb_stream_start(cam,
973                                 cam->params.camera_state.stream_mode);
974                 if (!ret)
975                         v4l2_ctrl_grab(cam->usb_alt, true);
976         }
977         return ret;
978 }
979
980 static int cpia2_streamoff(struct file *file, void *fh, enum v4l2_buf_type type)
981 {
982         struct camera_data *cam = video_drvdata(file);
983         int ret = -EINVAL;
984
985         DBG("VIDIOC_STREAMOFF, streaming=%d\n", cam->streaming);
986         if (!cam->mmapped || type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
987                 return -EINVAL;
988
989         if (cam->streaming) {
990                 ret = cpia2_usb_stream_stop(cam);
991                 if (!ret)
992                         v4l2_ctrl_grab(cam->usb_alt, false);
993         }
994         return ret;
995 }
996
997 /******************************************************************************
998  *
999  *  cpia2_mmap
1000  *
1001  *****************************************************************************/
1002 static int cpia2_mmap(struct file *file, struct vm_area_struct *area)
1003 {
1004         struct camera_data *cam = video_drvdata(file);
1005         int retval;
1006
1007         if (mutex_lock_interruptible(&cam->v4l2_lock))
1008                 return -ERESTARTSYS;
1009         retval = cpia2_remap_buffer(cam, area);
1010
1011         if(!retval)
1012                 cam->stream_fh = file->private_data;
1013         mutex_unlock(&cam->v4l2_lock);
1014         return retval;
1015 }
1016
1017 /******************************************************************************
1018  *
1019  *  reset_camera_struct_v4l
1020  *
1021  *  Sets all values to the defaults
1022  *****************************************************************************/
1023 static void reset_camera_struct_v4l(struct camera_data *cam)
1024 {
1025         cam->width = cam->params.roi.width;
1026         cam->height = cam->params.roi.height;
1027
1028         cam->frame_size = buffer_size;
1029         cam->num_frames = num_buffers;
1030
1031         /* Flicker modes */
1032         cam->params.flicker_control.flicker_mode_req = flicker_mode;
1033
1034         /* stream modes */
1035         cam->params.camera_state.stream_mode = alternate;
1036
1037         cam->pixelformat = V4L2_PIX_FMT_JPEG;
1038 }
1039
1040 static const struct v4l2_ioctl_ops cpia2_ioctl_ops = {
1041         .vidioc_querycap                    = cpia2_querycap,
1042         .vidioc_enum_input                  = cpia2_enum_input,
1043         .vidioc_g_input                     = cpia2_g_input,
1044         .vidioc_s_input                     = cpia2_s_input,
1045         .vidioc_enum_fmt_vid_cap            = cpia2_enum_fmt_vid_cap,
1046         .vidioc_g_fmt_vid_cap               = cpia2_g_fmt_vid_cap,
1047         .vidioc_s_fmt_vid_cap               = cpia2_s_fmt_vid_cap,
1048         .vidioc_try_fmt_vid_cap             = cpia2_try_fmt_vid_cap,
1049         .vidioc_g_jpegcomp                  = cpia2_g_jpegcomp,
1050         .vidioc_s_jpegcomp                  = cpia2_s_jpegcomp,
1051         .vidioc_g_selection                 = cpia2_g_selection,
1052         .vidioc_reqbufs                     = cpia2_reqbufs,
1053         .vidioc_querybuf                    = cpia2_querybuf,
1054         .vidioc_qbuf                        = cpia2_qbuf,
1055         .vidioc_dqbuf                       = cpia2_dqbuf,
1056         .vidioc_streamon                    = cpia2_streamon,
1057         .vidioc_streamoff                   = cpia2_streamoff,
1058         .vidioc_s_parm                      = cpia2_s_parm,
1059         .vidioc_g_parm                      = cpia2_g_parm,
1060         .vidioc_enum_framesizes             = cpia2_enum_framesizes,
1061         .vidioc_enum_frameintervals         = cpia2_enum_frameintervals,
1062         .vidioc_subscribe_event             = v4l2_ctrl_subscribe_event,
1063         .vidioc_unsubscribe_event           = v4l2_event_unsubscribe,
1064 };
1065
1066 /***
1067  * The v4l video device structure initialized for this device
1068  ***/
1069 static const struct v4l2_file_operations cpia2_fops = {
1070         .owner          = THIS_MODULE,
1071         .open           = cpia2_open,
1072         .release        = cpia2_close,
1073         .read           = cpia2_v4l_read,
1074         .poll           = cpia2_v4l_poll,
1075         .unlocked_ioctl = video_ioctl2,
1076         .mmap           = cpia2_mmap,
1077 };
1078
1079 static const struct video_device cpia2_template = {
1080         /* I could not find any place for the old .initialize initializer?? */
1081         .name =         "CPiA2 Camera",
1082         .fops =         &cpia2_fops,
1083         .ioctl_ops =    &cpia2_ioctl_ops,
1084         .release =      video_device_release_empty,
1085 };
1086
1087 void cpia2_camera_release(struct v4l2_device *v4l2_dev)
1088 {
1089         struct camera_data *cam =
1090                 container_of(v4l2_dev, struct camera_data, v4l2_dev);
1091
1092         v4l2_ctrl_handler_free(&cam->hdl);
1093         v4l2_device_unregister(&cam->v4l2_dev);
1094         kfree(cam);
1095 }
1096
1097 static const struct v4l2_ctrl_ops cpia2_ctrl_ops = {
1098         .s_ctrl = cpia2_s_ctrl,
1099 };
1100
1101 /******************************************************************************
1102  *
1103  *  cpia2_register_camera
1104  *
1105  *****************************************************************************/
1106 int cpia2_register_camera(struct camera_data *cam)
1107 {
1108         struct v4l2_ctrl_handler *hdl = &cam->hdl;
1109         struct v4l2_ctrl_config cpia2_usb_alt = {
1110                 .ops = &cpia2_ctrl_ops,
1111                 .id = CPIA2_CID_USB_ALT,
1112                 .name = "USB Alternate",
1113                 .type = V4L2_CTRL_TYPE_INTEGER,
1114                 .min = USBIF_ISO_1,
1115                 .max = USBIF_ISO_6,
1116                 .step = 1,
1117         };
1118         int ret;
1119
1120         v4l2_ctrl_handler_init(hdl, 12);
1121         v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1122                         V4L2_CID_BRIGHTNESS,
1123                         cam->params.pnp_id.device_type == DEVICE_STV_672 ? 1 : 0,
1124                         255, 1, DEFAULT_BRIGHTNESS);
1125         v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1126                         V4L2_CID_CONTRAST, 0, 255, 1, DEFAULT_CONTRAST);
1127         v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1128                         V4L2_CID_SATURATION, 0, 255, 1, DEFAULT_SATURATION);
1129         v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1130                         V4L2_CID_HFLIP, 0, 1, 1, 0);
1131         v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1132                         V4L2_CID_JPEG_ACTIVE_MARKER, 0,
1133                         V4L2_JPEG_ACTIVE_MARKER_DHT, 0,
1134                         V4L2_JPEG_ACTIVE_MARKER_DHT);
1135         v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1136                         V4L2_CID_JPEG_COMPRESSION_QUALITY, 1,
1137                         100, 1, 100);
1138         cpia2_usb_alt.def = alternate;
1139         cam->usb_alt = v4l2_ctrl_new_custom(hdl, &cpia2_usb_alt, NULL);
1140         /* VP5 Only */
1141         if (cam->params.pnp_id.device_type != DEVICE_STV_672)
1142                 v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1143                         V4L2_CID_VFLIP, 0, 1, 1, 0);
1144         /* Flicker control only valid for 672 */
1145         if (cam->params.pnp_id.device_type == DEVICE_STV_672)
1146                 v4l2_ctrl_new_std_menu(hdl, &cpia2_ctrl_ops,
1147                         V4L2_CID_POWER_LINE_FREQUENCY,
1148                         V4L2_CID_POWER_LINE_FREQUENCY_60HZ, 0, 0);
1149         /* Light control only valid for the QX5 Microscope */
1150         if (cam->params.pnp_id.product == 0x151) {
1151                 cam->top_light = v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1152                                 V4L2_CID_ILLUMINATORS_1, 0, 1, 1, 0);
1153                 cam->bottom_light = v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1154                                 V4L2_CID_ILLUMINATORS_2, 0, 1, 1, 0);
1155                 v4l2_ctrl_cluster(2, &cam->top_light);
1156         }
1157
1158         if (hdl->error) {
1159                 ret = hdl->error;
1160                 v4l2_ctrl_handler_free(hdl);
1161                 return ret;
1162         }
1163
1164         cam->vdev = cpia2_template;
1165         video_set_drvdata(&cam->vdev, cam);
1166         cam->vdev.lock = &cam->v4l2_lock;
1167         cam->vdev.ctrl_handler = hdl;
1168         cam->vdev.v4l2_dev = &cam->v4l2_dev;
1169
1170         reset_camera_struct_v4l(cam);
1171
1172         /* register v4l device */
1173         if (video_register_device(&cam->vdev, VFL_TYPE_GRABBER, video_nr) < 0) {
1174                 ERR("video_register_device failed\n");
1175                 return -ENODEV;
1176         }
1177
1178         return 0;
1179 }
1180
1181 /******************************************************************************
1182  *
1183  *  cpia2_unregister_camera
1184  *
1185  *****************************************************************************/
1186 void cpia2_unregister_camera(struct camera_data *cam)
1187 {
1188         video_unregister_device(&cam->vdev);
1189 }
1190
1191 /******************************************************************************
1192  *
1193  *  check_parameters
1194  *
1195  *  Make sure that all user-supplied parameters are sensible
1196  *****************************************************************************/
1197 static void __init check_parameters(void)
1198 {
1199         if(buffer_size < PAGE_SIZE) {
1200                 buffer_size = PAGE_SIZE;
1201                 LOG("buffer_size too small, setting to %d\n", buffer_size);
1202         } else if(buffer_size > 1024*1024) {
1203                 /* arbitrary upper limiit */
1204                 buffer_size = 1024*1024;
1205                 LOG("buffer_size ridiculously large, setting to %d\n",
1206                     buffer_size);
1207         } else {
1208                 buffer_size += PAGE_SIZE-1;
1209                 buffer_size &= ~(PAGE_SIZE-1);
1210         }
1211
1212         if(num_buffers < 1) {
1213                 num_buffers = 1;
1214                 LOG("num_buffers too small, setting to %d\n", num_buffers);
1215         } else if(num_buffers > VIDEO_MAX_FRAME) {
1216                 num_buffers = VIDEO_MAX_FRAME;
1217                 LOG("num_buffers too large, setting to %d\n", num_buffers);
1218         }
1219
1220         if(alternate < USBIF_ISO_1 || alternate > USBIF_ISO_6) {
1221                 alternate = DEFAULT_ALT;
1222                 LOG("alternate specified is invalid, using %d\n", alternate);
1223         }
1224
1225         if (flicker_mode != 0 && flicker_mode != FLICKER_50 && flicker_mode != FLICKER_60) {
1226                 flicker_mode = 0;
1227                 LOG("Flicker mode specified is invalid, using %d\n",
1228                     flicker_mode);
1229         }
1230
1231         DBG("Using %d buffers, each %d bytes, alternate=%d\n",
1232             num_buffers, buffer_size, alternate);
1233 }
1234
1235 /************   Module Stuff ***************/
1236
1237
1238 /******************************************************************************
1239  *
1240  * cpia2_init/module_init
1241  *
1242  *****************************************************************************/
1243 static int __init cpia2_init(void)
1244 {
1245         LOG("%s v%s\n",
1246             ABOUT, CPIA_VERSION);
1247         check_parameters();
1248         cpia2_usb_init();
1249         return 0;
1250 }
1251
1252
1253 /******************************************************************************
1254  *
1255  * cpia2_exit/module_exit
1256  *
1257  *****************************************************************************/
1258 static void __exit cpia2_exit(void)
1259 {
1260         cpia2_usb_cleanup();
1261         schedule_timeout(2 * HZ);
1262 }
1263
1264 module_init(cpia2_init);
1265 module_exit(cpia2_exit);