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