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