Merge branch 'for-2.6.30' into for-2.6.31
[linux-2.6] / drivers / media / video / 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 #include <linux/version.h>
33
34
35 #include <linux/module.h>
36 #include <linux/time.h>
37 #include <linux/sched.h>
38 #include <linux/slab.h>
39 #include <linux/init.h>
40 #include <linux/videodev.h>
41 #include <media/v4l2-ioctl.h>
42
43 #include "cpia2.h"
44 #include "cpia2dev.h"
45
46
47 //#define _CPIA2_DEBUG_
48
49 #define MAKE_STRING_1(x)        #x
50 #define MAKE_STRING(x)  MAKE_STRING_1(x)
51
52 static int video_nr = -1;
53 module_param(video_nr, int, 0);
54 MODULE_PARM_DESC(video_nr,"video device to register (0=/dev/video0, etc)");
55
56 static int buffer_size = 68*1024;
57 module_param(buffer_size, int, 0);
58 MODULE_PARM_DESC(buffer_size, "Size for each frame buffer in bytes (default 68k)");
59
60 static int num_buffers = 3;
61 module_param(num_buffers, int, 0);
62 MODULE_PARM_DESC(num_buffers, "Number of frame buffers (1-"
63                  MAKE_STRING(VIDEO_MAX_FRAME) ", default 3)");
64
65 static int alternate = DEFAULT_ALT;
66 module_param(alternate, int, 0);
67 MODULE_PARM_DESC(alternate, "USB Alternate (" MAKE_STRING(USBIF_ISO_1) "-"
68                  MAKE_STRING(USBIF_ISO_6) ", default "
69                  MAKE_STRING(DEFAULT_ALT) ")");
70
71 static int flicker_freq = 60;
72 module_param(flicker_freq, int, 0);
73 MODULE_PARM_DESC(flicker_freq, "Flicker frequency (" MAKE_STRING(50) "or"
74                  MAKE_STRING(60) ", default "
75                  MAKE_STRING(60) ")");
76
77 static int flicker_mode = NEVER_FLICKER;
78 module_param(flicker_mode, int, 0);
79 MODULE_PARM_DESC(flicker_mode,
80                  "Flicker supression (" MAKE_STRING(NEVER_FLICKER) "or"
81                  MAKE_STRING(ANTI_FLICKER_ON) ", default "
82                  MAKE_STRING(NEVER_FLICKER) ")");
83
84 MODULE_AUTHOR("Steve Miller (STMicroelectronics) <steve.miller@st.com>");
85 MODULE_DESCRIPTION("V4L-driver for STMicroelectronics CPiA2 based cameras");
86 MODULE_SUPPORTED_DEVICE("video");
87 MODULE_LICENSE("GPL");
88
89 #define ABOUT "V4L-Driver for Vision CPiA2 based cameras"
90
91 struct control_menu_info {
92         int value;
93         char name[32];
94 };
95
96 static struct control_menu_info framerate_controls[] =
97 {
98         { CPIA2_VP_FRAMERATE_6_25, "6.25 fps" },
99         { CPIA2_VP_FRAMERATE_7_5,  "7.5 fps"  },
100         { CPIA2_VP_FRAMERATE_12_5, "12.5 fps" },
101         { CPIA2_VP_FRAMERATE_15,   "15 fps"   },
102         { CPIA2_VP_FRAMERATE_25,   "25 fps"   },
103         { CPIA2_VP_FRAMERATE_30,   "30 fps"   },
104 };
105 #define NUM_FRAMERATE_CONTROLS (ARRAY_SIZE(framerate_controls))
106
107 static struct control_menu_info flicker_controls[] =
108 {
109         { NEVER_FLICKER, "Off" },
110         { FLICKER_50,    "50 Hz" },
111         { FLICKER_60,    "60 Hz"  },
112 };
113 #define NUM_FLICKER_CONTROLS (ARRAY_SIZE(flicker_controls))
114
115 static struct control_menu_info lights_controls[] =
116 {
117         { 0,   "Off" },
118         { 64,  "Top" },
119         { 128, "Bottom"  },
120         { 192, "Both"  },
121 };
122 #define NUM_LIGHTS_CONTROLS (ARRAY_SIZE(lights_controls))
123 #define GPIO_LIGHTS_MASK 192
124
125 static struct v4l2_queryctrl controls[] = {
126         {
127                 .id            = V4L2_CID_BRIGHTNESS,
128                 .type          = V4L2_CTRL_TYPE_INTEGER,
129                 .name          = "Brightness",
130                 .minimum       = 0,
131                 .maximum       = 255,
132                 .step          = 1,
133                 .default_value = DEFAULT_BRIGHTNESS,
134         },
135         {
136                 .id            = V4L2_CID_CONTRAST,
137                 .type          = V4L2_CTRL_TYPE_INTEGER,
138                 .name          = "Contrast",
139                 .minimum       = 0,
140                 .maximum       = 255,
141                 .step          = 1,
142                 .default_value = DEFAULT_CONTRAST,
143         },
144         {
145                 .id            = V4L2_CID_SATURATION,
146                 .type          = V4L2_CTRL_TYPE_INTEGER,
147                 .name          = "Saturation",
148                 .minimum       = 0,
149                 .maximum       = 255,
150                 .step          = 1,
151                 .default_value = DEFAULT_SATURATION,
152         },
153         {
154                 .id            = V4L2_CID_HFLIP,
155                 .type          = V4L2_CTRL_TYPE_BOOLEAN,
156                 .name          = "Mirror Horizontally",
157                 .minimum       = 0,
158                 .maximum       = 1,
159                 .step          = 1,
160                 .default_value = 0,
161         },
162         {
163                 .id            = V4L2_CID_VFLIP,
164                 .type          = V4L2_CTRL_TYPE_BOOLEAN,
165                 .name          = "Flip Vertically",
166                 .minimum       = 0,
167                 .maximum       = 1,
168                 .step          = 1,
169                 .default_value = 0,
170         },
171         {
172                 .id            = CPIA2_CID_TARGET_KB,
173                 .type          = V4L2_CTRL_TYPE_INTEGER,
174                 .name          = "Target KB",
175                 .minimum       = 0,
176                 .maximum       = 255,
177                 .step          = 1,
178                 .default_value = DEFAULT_TARGET_KB,
179         },
180         {
181                 .id            = CPIA2_CID_GPIO,
182                 .type          = V4L2_CTRL_TYPE_INTEGER,
183                 .name          = "GPIO",
184                 .minimum       = 0,
185                 .maximum       = 255,
186                 .step          = 1,
187                 .default_value = 0,
188         },
189         {
190                 .id            = CPIA2_CID_FLICKER_MODE,
191                 .type          = V4L2_CTRL_TYPE_MENU,
192                 .name          = "Flicker Reduction",
193                 .minimum       = 0,
194                 .maximum       = NUM_FLICKER_CONTROLS-1,
195                 .step          = 1,
196                 .default_value = 0,
197         },
198         {
199                 .id            = CPIA2_CID_FRAMERATE,
200                 .type          = V4L2_CTRL_TYPE_MENU,
201                 .name          = "Framerate",
202                 .minimum       = 0,
203                 .maximum       = NUM_FRAMERATE_CONTROLS-1,
204                 .step          = 1,
205                 .default_value = NUM_FRAMERATE_CONTROLS-1,
206         },
207         {
208                 .id            = CPIA2_CID_USB_ALT,
209                 .type          = V4L2_CTRL_TYPE_INTEGER,
210                 .name          = "USB Alternate",
211                 .minimum       = USBIF_ISO_1,
212                 .maximum       = USBIF_ISO_6,
213                 .step          = 1,
214                 .default_value = DEFAULT_ALT,
215         },
216         {
217                 .id            = CPIA2_CID_LIGHTS,
218                 .type          = V4L2_CTRL_TYPE_MENU,
219                 .name          = "Lights",
220                 .minimum       = 0,
221                 .maximum       = NUM_LIGHTS_CONTROLS-1,
222                 .step          = 1,
223                 .default_value = 0,
224         },
225         {
226                 .id            = CPIA2_CID_RESET_CAMERA,
227                 .type          = V4L2_CTRL_TYPE_BUTTON,
228                 .name          = "Reset Camera",
229                 .minimum       = 0,
230                 .maximum       = 0,
231                 .step          = 0,
232                 .default_value = 0,
233         },
234 };
235 #define NUM_CONTROLS (ARRAY_SIZE(controls))
236
237
238 /******************************************************************************
239  *
240  *  cpia2_open
241  *
242  *****************************************************************************/
243 static int cpia2_open(struct file *file)
244 {
245         struct camera_data *cam = video_drvdata(file);
246         int retval = 0;
247
248         if (!cam) {
249                 ERR("Internal error, camera_data not found!\n");
250                 return -ENODEV;
251         }
252
253         if(mutex_lock_interruptible(&cam->busy_lock))
254                 return -ERESTARTSYS;
255
256         if(!cam->present) {
257                 retval = -ENODEV;
258                 goto err_return;
259         }
260
261         if (cam->open_count > 0) {
262                 goto skip_init;
263         }
264
265         if (cpia2_allocate_buffers(cam)) {
266                 retval = -ENOMEM;
267                 goto err_return;
268         }
269
270         /* reset the camera */
271         if (cpia2_reset_camera(cam) < 0) {
272                 retval = -EIO;
273                 goto err_return;
274         }
275
276         cam->APP_len = 0;
277         cam->COM_len = 0;
278
279 skip_init:
280         {
281                 struct cpia2_fh *fh = kmalloc(sizeof(*fh),GFP_KERNEL);
282                 if(!fh) {
283                         retval = -ENOMEM;
284                         goto err_return;
285                 }
286                 file->private_data = fh;
287                 fh->prio = V4L2_PRIORITY_UNSET;
288                 v4l2_prio_open(&cam->prio, &fh->prio);
289                 fh->mmapped = 0;
290         }
291
292         ++cam->open_count;
293
294         cpia2_dbg_dump_registers(cam);
295
296 err_return:
297         mutex_unlock(&cam->busy_lock);
298         return retval;
299 }
300
301 /******************************************************************************
302  *
303  *  cpia2_close
304  *
305  *****************************************************************************/
306 static int cpia2_close(struct file *file)
307 {
308         struct video_device *dev = video_devdata(file);
309         struct camera_data *cam = video_get_drvdata(dev);
310         struct cpia2_fh *fh = file->private_data;
311
312         mutex_lock(&cam->busy_lock);
313
314         if (cam->present &&
315             (cam->open_count == 1
316              || fh->prio == V4L2_PRIORITY_RECORD
317             )) {
318                 cpia2_usb_stream_stop(cam);
319
320                 if(cam->open_count == 1) {
321                         /* save camera state for later open */
322                         cpia2_save_camera_state(cam);
323
324                         cpia2_set_low_power(cam);
325                         cpia2_free_buffers(cam);
326                 }
327         }
328
329         {
330                 if(fh->mmapped)
331                         cam->mmapped = 0;
332                 v4l2_prio_close(&cam->prio,&fh->prio);
333                 file->private_data = NULL;
334                 kfree(fh);
335         }
336
337         if (--cam->open_count == 0) {
338                 cpia2_free_buffers(cam);
339                 if (!cam->present) {
340                         video_unregister_device(dev);
341                         mutex_unlock(&cam->busy_lock);
342                         kfree(cam);
343                         return 0;
344                 }
345         }
346
347         mutex_unlock(&cam->busy_lock);
348
349         return 0;
350 }
351
352 /******************************************************************************
353  *
354  *  cpia2_v4l_read
355  *
356  *****************************************************************************/
357 static ssize_t cpia2_v4l_read(struct file *file, char __user *buf, size_t count,
358                               loff_t *off)
359 {
360         struct camera_data *cam = video_drvdata(file);
361         int noblock = file->f_flags&O_NONBLOCK;
362
363         struct cpia2_fh *fh = file->private_data;
364
365         if(!cam)
366                 return -EINVAL;
367
368         /* Priority check */
369         if(fh->prio != V4L2_PRIORITY_RECORD) {
370                 return -EBUSY;
371         }
372
373         return cpia2_read(cam, buf, count, noblock);
374 }
375
376
377 /******************************************************************************
378  *
379  *  cpia2_v4l_poll
380  *
381  *****************************************************************************/
382 static unsigned int cpia2_v4l_poll(struct file *filp, struct poll_table_struct *wait)
383 {
384         struct camera_data *cam = video_drvdata(filp);
385         struct cpia2_fh *fh = filp->private_data;
386
387         if(!cam)
388                 return POLLERR;
389
390         /* Priority check */
391         if(fh->prio != V4L2_PRIORITY_RECORD) {
392                 return POLLERR;
393         }
394
395         return cpia2_poll(cam, filp, wait);
396 }
397
398
399 /******************************************************************************
400  *
401  *  ioctl_cap_query
402  *
403  *****************************************************************************/
404 static int ioctl_cap_query(void *arg, struct camera_data *cam)
405 {
406         struct video_capability *vc;
407         int retval = 0;
408         vc = arg;
409
410         if (cam->params.pnp_id.product == 0x151)
411                 strcpy(vc->name, "QX5 Microscope");
412         else
413                 strcpy(vc->name, "CPiA2 Camera");
414
415         vc->type = VID_TYPE_CAPTURE | VID_TYPE_MJPEG_ENCODER;
416         vc->channels = 1;
417         vc->audios = 0;
418         vc->minwidth = 176;     /* VIDEOSIZE_QCIF */
419         vc->minheight = 144;
420         switch (cam->params.version.sensor_flags) {
421         case CPIA2_VP_SENSOR_FLAGS_500:
422                 vc->maxwidth = STV_IMAGE_VGA_COLS;
423                 vc->maxheight = STV_IMAGE_VGA_ROWS;
424                 break;
425         case CPIA2_VP_SENSOR_FLAGS_410:
426                 vc->maxwidth = STV_IMAGE_CIF_COLS;
427                 vc->maxheight = STV_IMAGE_CIF_ROWS;
428                 break;
429         default:
430                 return -EINVAL;
431         }
432
433         return retval;
434 }
435
436 /******************************************************************************
437  *
438  *  ioctl_get_channel
439  *
440  *****************************************************************************/
441 static int ioctl_get_channel(void *arg)
442 {
443         int retval = 0;
444         struct video_channel *v;
445         v = arg;
446
447         if (v->channel != 0)
448                 return -EINVAL;
449
450         v->channel = 0;
451         strcpy(v->name, "Camera");
452         v->tuners = 0;
453         v->flags = 0;
454         v->type = VIDEO_TYPE_CAMERA;
455         v->norm = 0;
456
457         return retval;
458 }
459
460 /******************************************************************************
461  *
462  *  ioctl_set_channel
463  *
464  *****************************************************************************/
465 static int ioctl_set_channel(void *arg)
466 {
467         struct video_channel *v;
468         int retval = 0;
469         v = arg;
470
471         if (retval == 0 && v->channel != 0)
472                 retval = -EINVAL;
473
474         return retval;
475 }
476
477 /******************************************************************************
478  *
479  *  ioctl_set_image_prop
480  *
481  *****************************************************************************/
482 static int ioctl_set_image_prop(void *arg, struct camera_data *cam)
483 {
484         struct video_picture *vp;
485         int retval = 0;
486         vp = arg;
487
488         /* brightness, color, contrast need no check 0-65535 */
489         memcpy(&cam->vp, vp, sizeof(*vp));
490
491         /* update cam->params.colorParams */
492         cam->params.color_params.brightness = vp->brightness / 256;
493         cam->params.color_params.saturation = vp->colour / 256;
494         cam->params.color_params.contrast = vp->contrast / 256;
495
496         DBG("Requested params: bright 0x%X, sat 0x%X, contrast 0x%X\n",
497             cam->params.color_params.brightness,
498             cam->params.color_params.saturation,
499             cam->params.color_params.contrast);
500
501         cpia2_set_color_params(cam);
502
503         return retval;
504 }
505
506 static int sync(struct camera_data *cam, int frame_nr)
507 {
508         struct framebuf *frame = &cam->buffers[frame_nr];
509
510         while (1) {
511                 if (frame->status == FRAME_READY)
512                         return 0;
513
514                 if (!cam->streaming) {
515                         frame->status = FRAME_READY;
516                         frame->length = 0;
517                         return 0;
518                 }
519
520                 mutex_unlock(&cam->busy_lock);
521                 wait_event_interruptible(cam->wq_stream,
522                                          !cam->streaming ||
523                                          frame->status == FRAME_READY);
524                 mutex_lock(&cam->busy_lock);
525                 if (signal_pending(current))
526                         return -ERESTARTSYS;
527                 if(!cam->present)
528                         return -ENOTTY;
529         }
530 }
531
532 /******************************************************************************
533  *
534  *  ioctl_set_window_size
535  *
536  *****************************************************************************/
537 static int ioctl_set_window_size(void *arg, struct camera_data *cam,
538                                  struct cpia2_fh *fh)
539 {
540         /* copy_from_user, check validity, copy to internal structure */
541         struct video_window *vw;
542         int frame, err;
543         vw = arg;
544
545         if (vw->clipcount != 0) /* clipping not supported */
546                 return -EINVAL;
547
548         if (vw->clips != NULL)  /* clipping not supported */
549                 return -EINVAL;
550
551         /* Ensure that only this process can change the format. */
552         err = v4l2_prio_change(&cam->prio, &fh->prio, V4L2_PRIORITY_RECORD);
553         if(err != 0)
554                 return err;
555
556         cam->pixelformat = V4L2_PIX_FMT_JPEG;
557
558         /* Be sure to supply the Huffman tables, this isn't MJPEG */
559         cam->params.compression.inhibit_htables = 0;
560
561         /* we set the video window to something smaller or equal to what
562          * is requested by the user???
563          */
564         DBG("Requested width = %d, height = %d\n", vw->width, vw->height);
565         if (vw->width != cam->vw.width || vw->height != cam->vw.height) {
566                 cam->vw.width = vw->width;
567                 cam->vw.height = vw->height;
568                 cam->params.roi.width = vw->width;
569                 cam->params.roi.height = vw->height;
570                 cpia2_set_format(cam);
571         }
572
573         for (frame = 0; frame < cam->num_frames; ++frame) {
574                 if (cam->buffers[frame].status == FRAME_READING)
575                         if ((err = sync(cam, frame)) < 0)
576                                 return err;
577
578                 cam->buffers[frame].status = FRAME_EMPTY;
579         }
580
581         return 0;
582 }
583
584 /******************************************************************************
585  *
586  *  ioctl_get_mbuf
587  *
588  *****************************************************************************/
589 static int ioctl_get_mbuf(void *arg, struct camera_data *cam)
590 {
591         struct video_mbuf *vm;
592         int i;
593         vm = arg;
594
595         memset(vm, 0, sizeof(*vm));
596         vm->size = cam->frame_size*cam->num_frames;
597         vm->frames = cam->num_frames;
598         for (i = 0; i < cam->num_frames; i++)
599                 vm->offsets[i] = cam->frame_size * i;
600
601         return 0;
602 }
603
604 /******************************************************************************
605  *
606  *  ioctl_mcapture
607  *
608  *****************************************************************************/
609 static int ioctl_mcapture(void *arg, struct camera_data *cam,
610                           struct cpia2_fh *fh)
611 {
612         struct video_mmap *vm;
613         int video_size, err;
614         vm = arg;
615
616         if (vm->frame < 0 || vm->frame >= cam->num_frames)
617                 return -EINVAL;
618
619         /* set video size */
620         video_size = cpia2_match_video_size(vm->width, vm->height);
621         if (cam->video_size < 0) {
622                 return -EINVAL;
623         }
624
625         /* Ensure that only this process can change the format. */
626         err = v4l2_prio_change(&cam->prio, &fh->prio, V4L2_PRIORITY_RECORD);
627         if(err != 0)
628                 return err;
629
630         if (video_size != cam->video_size) {
631                 cam->video_size = video_size;
632                 cam->params.roi.width = vm->width;
633                 cam->params.roi.height = vm->height;
634                 cpia2_set_format(cam);
635         }
636
637         if (cam->buffers[vm->frame].status == FRAME_READING)
638                 if ((err=sync(cam, vm->frame)) < 0)
639                         return err;
640
641         cam->buffers[vm->frame].status = FRAME_EMPTY;
642
643         return cpia2_usb_stream_start(cam,cam->params.camera_state.stream_mode);
644 }
645
646 /******************************************************************************
647  *
648  *  ioctl_sync
649  *
650  *****************************************************************************/
651 static int ioctl_sync(void *arg, struct camera_data *cam)
652 {
653         int frame;
654
655         frame = *(int*)arg;
656
657         if (frame < 0 || frame >= cam->num_frames)
658                 return -EINVAL;
659
660         return sync(cam, frame);
661 }
662
663
664 /******************************************************************************
665  *
666  *  ioctl_set_gpio
667  *
668  *****************************************************************************/
669
670 static int ioctl_set_gpio(void *arg, struct camera_data *cam)
671 {
672         __u32 gpio_val;
673
674         gpio_val = *(__u32*) arg;
675
676         if (gpio_val &~ 0xFFU)
677                 return -EINVAL;
678
679         return cpia2_set_gpio(cam, (unsigned char)gpio_val);
680 }
681
682 /******************************************************************************
683  *
684  *  ioctl_querycap
685  *
686  *  V4L2 device capabilities
687  *
688  *****************************************************************************/
689
690 static int ioctl_querycap(void *arg, struct camera_data *cam)
691 {
692         struct v4l2_capability *vc = arg;
693
694         memset(vc, 0, sizeof(*vc));
695         strcpy(vc->driver, "cpia2");
696
697         if (cam->params.pnp_id.product == 0x151)
698                 strcpy(vc->card, "QX5 Microscope");
699         else
700                 strcpy(vc->card, "CPiA2 Camera");
701         switch (cam->params.pnp_id.device_type) {
702         case DEVICE_STV_672:
703                 strcat(vc->card, " (672/");
704                 break;
705         case DEVICE_STV_676:
706                 strcat(vc->card, " (676/");
707                 break;
708         default:
709                 strcat(vc->card, " (???/");
710                 break;
711         }
712         switch (cam->params.version.sensor_flags) {
713         case CPIA2_VP_SENSOR_FLAGS_404:
714                 strcat(vc->card, "404)");
715                 break;
716         case CPIA2_VP_SENSOR_FLAGS_407:
717                 strcat(vc->card, "407)");
718                 break;
719         case CPIA2_VP_SENSOR_FLAGS_409:
720                 strcat(vc->card, "409)");
721                 break;
722         case CPIA2_VP_SENSOR_FLAGS_410:
723                 strcat(vc->card, "410)");
724                 break;
725         case CPIA2_VP_SENSOR_FLAGS_500:
726                 strcat(vc->card, "500)");
727                 break;
728         default:
729                 strcat(vc->card, "???)");
730                 break;
731         }
732
733         if (usb_make_path(cam->dev, vc->bus_info, sizeof(vc->bus_info)) <0)
734                 memset(vc->bus_info,0, sizeof(vc->bus_info));
735
736         vc->version = KERNEL_VERSION(CPIA2_MAJ_VER, CPIA2_MIN_VER,
737                                      CPIA2_PATCH_VER);
738
739         vc->capabilities = V4L2_CAP_VIDEO_CAPTURE |
740                            V4L2_CAP_READWRITE |
741                            V4L2_CAP_STREAMING;
742
743         return 0;
744 }
745
746 /******************************************************************************
747  *
748  *  ioctl_input
749  *
750  *  V4L2 input get/set/enumerate
751  *
752  *****************************************************************************/
753
754 static int ioctl_input(unsigned int ioclt_nr,void *arg,struct camera_data *cam)
755 {
756         struct v4l2_input *i = arg;
757
758         if(ioclt_nr  != VIDIOC_G_INPUT) {
759                 if (i->index != 0)
760                        return -EINVAL;
761         }
762
763         memset(i, 0, sizeof(*i));
764         strcpy(i->name, "Camera");
765         i->type = V4L2_INPUT_TYPE_CAMERA;
766
767         return 0;
768 }
769
770 /******************************************************************************
771  *
772  *  ioctl_enum_fmt
773  *
774  *  V4L2 format enumerate
775  *
776  *****************************************************************************/
777
778 static int ioctl_enum_fmt(void *arg,struct camera_data *cam)
779 {
780         struct v4l2_fmtdesc *f = arg;
781         int index = f->index;
782
783         if (index < 0 || index > 1)
784                return -EINVAL;
785
786         memset(f, 0, sizeof(*f));
787         f->index = index;
788         f->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
789         f->flags = V4L2_FMT_FLAG_COMPRESSED;
790         switch(index) {
791         case 0:
792                 strcpy(f->description, "MJPEG");
793                 f->pixelformat = V4L2_PIX_FMT_MJPEG;
794                 break;
795         case 1:
796                 strcpy(f->description, "JPEG");
797                 f->pixelformat = V4L2_PIX_FMT_JPEG;
798                 break;
799         default:
800                 return -EINVAL;
801         }
802
803         return 0;
804 }
805
806 /******************************************************************************
807  *
808  *  ioctl_try_fmt
809  *
810  *  V4L2 format try
811  *
812  *****************************************************************************/
813
814 static int ioctl_try_fmt(void *arg,struct camera_data *cam)
815 {
816         struct v4l2_format *f = arg;
817
818         if (f->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
819                return -EINVAL;
820
821         if (f->fmt.pix.pixelformat != V4L2_PIX_FMT_MJPEG &&
822             f->fmt.pix.pixelformat != V4L2_PIX_FMT_JPEG)
823                return -EINVAL;
824
825         f->fmt.pix.field = V4L2_FIELD_NONE;
826         f->fmt.pix.bytesperline = 0;
827         f->fmt.pix.sizeimage = cam->frame_size;
828         f->fmt.pix.colorspace = V4L2_COLORSPACE_JPEG;
829         f->fmt.pix.priv = 0;
830
831         switch (cpia2_match_video_size(f->fmt.pix.width, f->fmt.pix.height)) {
832         case VIDEOSIZE_VGA:
833                 f->fmt.pix.width = 640;
834                 f->fmt.pix.height = 480;
835                 break;
836         case VIDEOSIZE_CIF:
837                 f->fmt.pix.width = 352;
838                 f->fmt.pix.height = 288;
839                 break;
840         case VIDEOSIZE_QVGA:
841                 f->fmt.pix.width = 320;
842                 f->fmt.pix.height = 240;
843                 break;
844         case VIDEOSIZE_288_216:
845                 f->fmt.pix.width = 288;
846                 f->fmt.pix.height = 216;
847                 break;
848         case VIDEOSIZE_256_192:
849                 f->fmt.pix.width = 256;
850                 f->fmt.pix.height = 192;
851                 break;
852         case VIDEOSIZE_224_168:
853                 f->fmt.pix.width = 224;
854                 f->fmt.pix.height = 168;
855                 break;
856         case VIDEOSIZE_192_144:
857                 f->fmt.pix.width = 192;
858                 f->fmt.pix.height = 144;
859                 break;
860         case VIDEOSIZE_QCIF:
861         default:
862                 f->fmt.pix.width = 176;
863                 f->fmt.pix.height = 144;
864                 break;
865         }
866
867         return 0;
868 }
869
870 /******************************************************************************
871  *
872  *  ioctl_set_fmt
873  *
874  *  V4L2 format set
875  *
876  *****************************************************************************/
877
878 static int ioctl_set_fmt(void *arg,struct camera_data *cam, struct cpia2_fh *fh)
879 {
880         struct v4l2_format *f = arg;
881         int err, frame;
882
883         err = ioctl_try_fmt(arg, cam);
884         if(err != 0)
885                 return err;
886
887         /* Ensure that only this process can change the format. */
888         err = v4l2_prio_change(&cam->prio, &fh->prio, V4L2_PRIORITY_RECORD);
889         if(err != 0) {
890                 return err;
891         }
892
893         cam->pixelformat = f->fmt.pix.pixelformat;
894
895         /* NOTE: This should be set to 1 for MJPEG, but some apps don't handle
896          * the missing Huffman table properly. */
897         cam->params.compression.inhibit_htables = 0;
898                 /*f->fmt.pix.pixelformat == V4L2_PIX_FMT_MJPEG;*/
899
900         /* we set the video window to something smaller or equal to what
901          * is requested by the user???
902          */
903         DBG("Requested width = %d, height = %d\n",
904             f->fmt.pix.width, f->fmt.pix.height);
905         if (f->fmt.pix.width != cam->vw.width ||
906             f->fmt.pix.height != cam->vw.height) {
907                 cam->vw.width = f->fmt.pix.width;
908                 cam->vw.height = f->fmt.pix.height;
909                 cam->params.roi.width = f->fmt.pix.width;
910                 cam->params.roi.height = f->fmt.pix.height;
911                 cpia2_set_format(cam);
912         }
913
914         for (frame = 0; frame < cam->num_frames; ++frame) {
915                 if (cam->buffers[frame].status == FRAME_READING)
916                         if ((err = sync(cam, frame)) < 0)
917                                 return err;
918
919                 cam->buffers[frame].status = FRAME_EMPTY;
920         }
921
922         return 0;
923 }
924
925 /******************************************************************************
926  *
927  *  ioctl_get_fmt
928  *
929  *  V4L2 format get
930  *
931  *****************************************************************************/
932
933 static int ioctl_get_fmt(void *arg,struct camera_data *cam)
934 {
935         struct v4l2_format *f = arg;
936
937         if (f->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
938                return -EINVAL;
939
940         f->fmt.pix.width = cam->vw.width;
941         f->fmt.pix.height = cam->vw.height;
942         f->fmt.pix.pixelformat = cam->pixelformat;
943         f->fmt.pix.field = V4L2_FIELD_NONE;
944         f->fmt.pix.bytesperline = 0;
945         f->fmt.pix.sizeimage = cam->frame_size;
946         f->fmt.pix.colorspace = V4L2_COLORSPACE_JPEG;
947         f->fmt.pix.priv = 0;
948
949         return 0;
950 }
951
952 /******************************************************************************
953  *
954  *  ioctl_cropcap
955  *
956  *  V4L2 query cropping capabilities
957  *  NOTE: cropping is currently disabled
958  *
959  *****************************************************************************/
960
961 static int ioctl_cropcap(void *arg,struct camera_data *cam)
962 {
963         struct v4l2_cropcap *c = arg;
964
965         if (c->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
966                return -EINVAL;
967
968         c->bounds.left = 0;
969         c->bounds.top = 0;
970         c->bounds.width = cam->vw.width;
971         c->bounds.height = cam->vw.height;
972         c->defrect.left = 0;
973         c->defrect.top = 0;
974         c->defrect.width = cam->vw.width;
975         c->defrect.height = cam->vw.height;
976         c->pixelaspect.numerator = 1;
977         c->pixelaspect.denominator = 1;
978
979         return 0;
980 }
981
982 /******************************************************************************
983  *
984  *  ioctl_queryctrl
985  *
986  *  V4L2 query possible control variables
987  *
988  *****************************************************************************/
989
990 static int ioctl_queryctrl(void *arg,struct camera_data *cam)
991 {
992         struct v4l2_queryctrl *c = arg;
993         int i;
994
995         for(i=0; i<NUM_CONTROLS; ++i) {
996                 if(c->id == controls[i].id) {
997                         memcpy(c, controls+i, sizeof(*c));
998                         break;
999                 }
1000         }
1001
1002         if(i == NUM_CONTROLS)
1003                 return -EINVAL;
1004
1005         /* Some devices have additional limitations */
1006         switch(c->id) {
1007         case V4L2_CID_BRIGHTNESS:
1008                 /***
1009                  * Don't let the register be set to zero - bug in VP4
1010                  * flash of full brightness
1011                  ***/
1012                 if (cam->params.pnp_id.device_type == DEVICE_STV_672)
1013                         c->minimum = 1;
1014                 break;
1015         case V4L2_CID_VFLIP:
1016                 // VP5 Only
1017                 if(cam->params.pnp_id.device_type == DEVICE_STV_672)
1018                         c->flags |= V4L2_CTRL_FLAG_DISABLED;
1019                 break;
1020         case CPIA2_CID_FRAMERATE:
1021                 if(cam->params.pnp_id.device_type == DEVICE_STV_672 &&
1022                    cam->params.version.sensor_flags==CPIA2_VP_SENSOR_FLAGS_500){
1023                         // Maximum 15fps
1024                         for(i=0; i<c->maximum; ++i) {
1025                                 if(framerate_controls[i].value ==
1026                                    CPIA2_VP_FRAMERATE_15) {
1027                                         c->maximum = i;
1028                                         c->default_value = i;
1029                                 }
1030                         }
1031                 }
1032                 break;
1033         case CPIA2_CID_FLICKER_MODE:
1034                 // Flicker control only valid for 672.
1035                 if(cam->params.pnp_id.device_type != DEVICE_STV_672)
1036                         c->flags |= V4L2_CTRL_FLAG_DISABLED;
1037                 break;
1038         case CPIA2_CID_LIGHTS:
1039                 // Light control only valid for the QX5 Microscope.
1040                 if(cam->params.pnp_id.product != 0x151)
1041                         c->flags |= V4L2_CTRL_FLAG_DISABLED;
1042                 break;
1043         default:
1044                 break;
1045         }
1046
1047         return 0;
1048 }
1049
1050 /******************************************************************************
1051  *
1052  *  ioctl_querymenu
1053  *
1054  *  V4L2 query possible control variables
1055  *
1056  *****************************************************************************/
1057
1058 static int ioctl_querymenu(void *arg,struct camera_data *cam)
1059 {
1060         struct v4l2_querymenu *m = arg;
1061
1062         memset(m->name, 0, sizeof(m->name));
1063         m->reserved = 0;
1064
1065         switch(m->id) {
1066         case CPIA2_CID_FLICKER_MODE:
1067                 if(m->index < 0 || m->index >= NUM_FLICKER_CONTROLS)
1068                         return -EINVAL;
1069
1070                 strcpy(m->name, flicker_controls[m->index].name);
1071                 break;
1072         case CPIA2_CID_FRAMERATE:
1073             {
1074                 int maximum = NUM_FRAMERATE_CONTROLS - 1;
1075                 if(cam->params.pnp_id.device_type == DEVICE_STV_672 &&
1076                    cam->params.version.sensor_flags==CPIA2_VP_SENSOR_FLAGS_500){
1077                         // Maximum 15fps
1078                         int i;
1079                         for(i=0; i<maximum; ++i) {
1080                                 if(framerate_controls[i].value ==
1081                                    CPIA2_VP_FRAMERATE_15)
1082                                         maximum = i;
1083                         }
1084                 }
1085                 if(m->index < 0 || m->index > maximum)
1086                         return -EINVAL;
1087
1088                 strcpy(m->name, framerate_controls[m->index].name);
1089                 break;
1090             }
1091         case CPIA2_CID_LIGHTS:
1092                 if(m->index < 0 || m->index >= NUM_LIGHTS_CONTROLS)
1093                         return -EINVAL;
1094
1095                 strcpy(m->name, lights_controls[m->index].name);
1096                 break;
1097         default:
1098                 return -EINVAL;
1099         }
1100
1101         return 0;
1102 }
1103
1104 /******************************************************************************
1105  *
1106  *  ioctl_g_ctrl
1107  *
1108  *  V4L2 get the value of a control variable
1109  *
1110  *****************************************************************************/
1111
1112 static int ioctl_g_ctrl(void *arg,struct camera_data *cam)
1113 {
1114         struct v4l2_control *c = arg;
1115
1116         switch(c->id) {
1117         case V4L2_CID_BRIGHTNESS:
1118                 cpia2_do_command(cam, CPIA2_CMD_GET_VP_BRIGHTNESS,
1119                                  TRANSFER_READ, 0);
1120                 c->value = cam->params.color_params.brightness;
1121                 break;
1122         case V4L2_CID_CONTRAST:
1123                 cpia2_do_command(cam, CPIA2_CMD_GET_CONTRAST,
1124                                  TRANSFER_READ, 0);
1125                 c->value = cam->params.color_params.contrast;
1126                 break;
1127         case V4L2_CID_SATURATION:
1128                 cpia2_do_command(cam, CPIA2_CMD_GET_VP_SATURATION,
1129                                  TRANSFER_READ, 0);
1130                 c->value = cam->params.color_params.saturation;
1131                 break;
1132         case V4L2_CID_HFLIP:
1133                 cpia2_do_command(cam, CPIA2_CMD_GET_USER_EFFECTS,
1134                                  TRANSFER_READ, 0);
1135                 c->value = (cam->params.vp_params.user_effects &
1136                             CPIA2_VP_USER_EFFECTS_MIRROR) != 0;
1137                 break;
1138         case V4L2_CID_VFLIP:
1139                 cpia2_do_command(cam, CPIA2_CMD_GET_USER_EFFECTS,
1140                                  TRANSFER_READ, 0);
1141                 c->value = (cam->params.vp_params.user_effects &
1142                             CPIA2_VP_USER_EFFECTS_FLIP) != 0;
1143                 break;
1144         case CPIA2_CID_TARGET_KB:
1145                 c->value = cam->params.vc_params.target_kb;
1146                 break;
1147         case CPIA2_CID_GPIO:
1148                 cpia2_do_command(cam, CPIA2_CMD_GET_VP_GPIO_DATA,
1149                                  TRANSFER_READ, 0);
1150                 c->value = cam->params.vp_params.gpio_data;
1151                 break;
1152         case CPIA2_CID_FLICKER_MODE:
1153         {
1154                 int i, mode;
1155                 cpia2_do_command(cam, CPIA2_CMD_GET_FLICKER_MODES,
1156                                  TRANSFER_READ, 0);
1157                 if(cam->params.flicker_control.cam_register &
1158                    CPIA2_VP_FLICKER_MODES_NEVER_FLICKER) {
1159                         mode = NEVER_FLICKER;
1160                 } else {
1161                     if(cam->params.flicker_control.cam_register &
1162                        CPIA2_VP_FLICKER_MODES_50HZ) {
1163                         mode = FLICKER_50;
1164                     } else {
1165                         mode = FLICKER_60;
1166                     }
1167                 }
1168                 for(i=0; i<NUM_FLICKER_CONTROLS; i++) {
1169                         if(flicker_controls[i].value == mode) {
1170                                 c->value = i;
1171                                 break;
1172                         }
1173                 }
1174                 if(i == NUM_FLICKER_CONTROLS)
1175                         return -EINVAL;
1176                 break;
1177         }
1178         case CPIA2_CID_FRAMERATE:
1179         {
1180                 int maximum = NUM_FRAMERATE_CONTROLS - 1;
1181                 int i;
1182                 for(i=0; i<= maximum; i++) {
1183                         if(cam->params.vp_params.frame_rate ==
1184                            framerate_controls[i].value)
1185                                 break;
1186                 }
1187                 if(i > maximum)
1188                         return -EINVAL;
1189                 c->value = i;
1190                 break;
1191         }
1192         case CPIA2_CID_USB_ALT:
1193                 c->value = cam->params.camera_state.stream_mode;
1194                 break;
1195         case CPIA2_CID_LIGHTS:
1196         {
1197                 int i;
1198                 cpia2_do_command(cam, CPIA2_CMD_GET_VP_GPIO_DATA,
1199                                  TRANSFER_READ, 0);
1200                 for(i=0; i<NUM_LIGHTS_CONTROLS; i++) {
1201                         if((cam->params.vp_params.gpio_data&GPIO_LIGHTS_MASK) ==
1202                            lights_controls[i].value) {
1203                                 break;
1204                         }
1205                 }
1206                 if(i == NUM_LIGHTS_CONTROLS)
1207                         return -EINVAL;
1208                 c->value = i;
1209                 break;
1210         }
1211         case CPIA2_CID_RESET_CAMERA:
1212                 return -EINVAL;
1213         default:
1214                 return -EINVAL;
1215         }
1216
1217         DBG("Get control id:%d, value:%d\n", c->id, c->value);
1218
1219         return 0;
1220 }
1221
1222 /******************************************************************************
1223  *
1224  *  ioctl_s_ctrl
1225  *
1226  *  V4L2 set the value of a control variable
1227  *
1228  *****************************************************************************/
1229
1230 static int ioctl_s_ctrl(void *arg,struct camera_data *cam)
1231 {
1232         struct v4l2_control *c = arg;
1233         int i;
1234         int retval = 0;
1235
1236         DBG("Set control id:%d, value:%d\n", c->id, c->value);
1237
1238         /* Check that the value is in range */
1239         for(i=0; i<NUM_CONTROLS; i++) {
1240                 if(c->id == controls[i].id) {
1241                         if(c->value < controls[i].minimum ||
1242                            c->value > controls[i].maximum) {
1243                                 return -EINVAL;
1244                         }
1245                         break;
1246                 }
1247         }
1248         if(i == NUM_CONTROLS)
1249                 return -EINVAL;
1250
1251         switch(c->id) {
1252         case V4L2_CID_BRIGHTNESS:
1253                 cpia2_set_brightness(cam, c->value);
1254                 break;
1255         case V4L2_CID_CONTRAST:
1256                 cpia2_set_contrast(cam, c->value);
1257                 break;
1258         case V4L2_CID_SATURATION:
1259                 cpia2_set_saturation(cam, c->value);
1260                 break;
1261         case V4L2_CID_HFLIP:
1262                 cpia2_set_property_mirror(cam, c->value);
1263                 break;
1264         case V4L2_CID_VFLIP:
1265                 cpia2_set_property_flip(cam, c->value);
1266                 break;
1267         case CPIA2_CID_TARGET_KB:
1268                 retval = cpia2_set_target_kb(cam, c->value);
1269                 break;
1270         case CPIA2_CID_GPIO:
1271                 retval = cpia2_set_gpio(cam, c->value);
1272                 break;
1273         case CPIA2_CID_FLICKER_MODE:
1274                 retval = cpia2_set_flicker_mode(cam,
1275                                               flicker_controls[c->value].value);
1276                 break;
1277         case CPIA2_CID_FRAMERATE:
1278                 retval = cpia2_set_fps(cam, framerate_controls[c->value].value);
1279                 break;
1280         case CPIA2_CID_USB_ALT:
1281                 retval = cpia2_usb_change_streaming_alternate(cam, c->value);
1282                 break;
1283         case CPIA2_CID_LIGHTS:
1284                 retval = cpia2_set_gpio(cam, lights_controls[c->value].value);
1285                 break;
1286         case CPIA2_CID_RESET_CAMERA:
1287                 cpia2_usb_stream_pause(cam);
1288                 cpia2_reset_camera(cam);
1289                 cpia2_usb_stream_resume(cam);
1290                 break;
1291         default:
1292                 retval = -EINVAL;
1293         }
1294
1295         return retval;
1296 }
1297
1298 /******************************************************************************
1299  *
1300  *  ioctl_g_jpegcomp
1301  *
1302  *  V4L2 get the JPEG compression parameters
1303  *
1304  *****************************************************************************/
1305
1306 static int ioctl_g_jpegcomp(void *arg,struct camera_data *cam)
1307 {
1308         struct v4l2_jpegcompression *parms = arg;
1309
1310         memset(parms, 0, sizeof(*parms));
1311
1312         parms->quality = 80; // TODO: Can this be made meaningful?
1313
1314         parms->jpeg_markers = V4L2_JPEG_MARKER_DQT | V4L2_JPEG_MARKER_DRI;
1315         if(!cam->params.compression.inhibit_htables) {
1316                 parms->jpeg_markers |= V4L2_JPEG_MARKER_DHT;
1317         }
1318
1319         parms->APPn = cam->APPn;
1320         parms->APP_len = cam->APP_len;
1321         if(cam->APP_len > 0) {
1322                 memcpy(parms->APP_data, cam->APP_data, cam->APP_len);
1323                 parms->jpeg_markers |= V4L2_JPEG_MARKER_APP;
1324         }
1325
1326         parms->COM_len = cam->COM_len;
1327         if(cam->COM_len > 0) {
1328                 memcpy(parms->COM_data, cam->COM_data, cam->COM_len);
1329                 parms->jpeg_markers |= JPEG_MARKER_COM;
1330         }
1331
1332         DBG("G_JPEGCOMP APP_len:%d COM_len:%d\n",
1333             parms->APP_len, parms->COM_len);
1334
1335         return 0;
1336 }
1337
1338 /******************************************************************************
1339  *
1340  *  ioctl_s_jpegcomp
1341  *
1342  *  V4L2 set the JPEG compression parameters
1343  *  NOTE: quality and some jpeg_markers are ignored.
1344  *
1345  *****************************************************************************/
1346
1347 static int ioctl_s_jpegcomp(void *arg,struct camera_data *cam)
1348 {
1349         struct v4l2_jpegcompression *parms = arg;
1350
1351         DBG("S_JPEGCOMP APP_len:%d COM_len:%d\n",
1352             parms->APP_len, parms->COM_len);
1353
1354         cam->params.compression.inhibit_htables =
1355                 !(parms->jpeg_markers & V4L2_JPEG_MARKER_DHT);
1356
1357         if(parms->APP_len != 0) {
1358                 if(parms->APP_len > 0 &&
1359                    parms->APP_len <= sizeof(cam->APP_data) &&
1360                    parms->APPn >= 0 && parms->APPn <= 15) {
1361                         cam->APPn = parms->APPn;
1362                         cam->APP_len = parms->APP_len;
1363                         memcpy(cam->APP_data, parms->APP_data, parms->APP_len);
1364                 } else {
1365                         LOG("Bad APPn Params n=%d len=%d\n",
1366                             parms->APPn, parms->APP_len);
1367                         return -EINVAL;
1368                 }
1369         } else {
1370                 cam->APP_len = 0;
1371         }
1372
1373         if(parms->COM_len != 0) {
1374                 if(parms->COM_len > 0 &&
1375                    parms->COM_len <= sizeof(cam->COM_data)) {
1376                         cam->COM_len = parms->COM_len;
1377                         memcpy(cam->COM_data, parms->COM_data, parms->COM_len);
1378                 } else {
1379                         LOG("Bad COM_len=%d\n", parms->COM_len);
1380                         return -EINVAL;
1381                 }
1382         }
1383
1384         return 0;
1385 }
1386
1387 /******************************************************************************
1388  *
1389  *  ioctl_reqbufs
1390  *
1391  *  V4L2 Initiate memory mapping.
1392  *  NOTE: The user's request is ignored. For now the buffers are fixed.
1393  *
1394  *****************************************************************************/
1395
1396 static int ioctl_reqbufs(void *arg,struct camera_data *cam)
1397 {
1398         struct v4l2_requestbuffers *req = arg;
1399
1400         if(req->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1401            req->memory != V4L2_MEMORY_MMAP)
1402                 return -EINVAL;
1403
1404         DBG("REQBUFS requested:%d returning:%d\n", req->count, cam->num_frames);
1405         req->count = cam->num_frames;
1406         memset(&req->reserved, 0, sizeof(req->reserved));
1407
1408         return 0;
1409 }
1410
1411 /******************************************************************************
1412  *
1413  *  ioctl_querybuf
1414  *
1415  *  V4L2 Query memory buffer status.
1416  *
1417  *****************************************************************************/
1418
1419 static int ioctl_querybuf(void *arg,struct camera_data *cam)
1420 {
1421         struct v4l2_buffer *buf = arg;
1422
1423         if(buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1424            buf->index > cam->num_frames)
1425                 return -EINVAL;
1426
1427         buf->m.offset = cam->buffers[buf->index].data - cam->frame_buffer;
1428         buf->length = cam->frame_size;
1429
1430         buf->memory = V4L2_MEMORY_MMAP;
1431
1432         if(cam->mmapped)
1433                 buf->flags = V4L2_BUF_FLAG_MAPPED;
1434         else
1435                 buf->flags = 0;
1436
1437         switch (cam->buffers[buf->index].status) {
1438         case FRAME_EMPTY:
1439         case FRAME_ERROR:
1440         case FRAME_READING:
1441                 buf->bytesused = 0;
1442                 buf->flags = V4L2_BUF_FLAG_QUEUED;
1443                 break;
1444         case FRAME_READY:
1445                 buf->bytesused = cam->buffers[buf->index].length;
1446                 buf->timestamp = cam->buffers[buf->index].timestamp;
1447                 buf->sequence = cam->buffers[buf->index].seq;
1448                 buf->flags = V4L2_BUF_FLAG_DONE;
1449                 break;
1450         }
1451
1452         DBG("QUERYBUF index:%d offset:%d flags:%d seq:%d bytesused:%d\n",
1453              buf->index, buf->m.offset, buf->flags, buf->sequence,
1454              buf->bytesused);
1455
1456         return 0;
1457 }
1458
1459 /******************************************************************************
1460  *
1461  *  ioctl_qbuf
1462  *
1463  *  V4L2 User is freeing buffer
1464  *
1465  *****************************************************************************/
1466
1467 static int ioctl_qbuf(void *arg,struct camera_data *cam)
1468 {
1469         struct v4l2_buffer *buf = arg;
1470
1471         if(buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1472            buf->memory != V4L2_MEMORY_MMAP ||
1473            buf->index > cam->num_frames)
1474                 return -EINVAL;
1475
1476         DBG("QBUF #%d\n", buf->index);
1477
1478         if(cam->buffers[buf->index].status == FRAME_READY)
1479                 cam->buffers[buf->index].status = FRAME_EMPTY;
1480
1481         return 0;
1482 }
1483
1484 /******************************************************************************
1485  *
1486  *  find_earliest_filled_buffer
1487  *
1488  *  Helper for ioctl_dqbuf. Find the next ready buffer.
1489  *
1490  *****************************************************************************/
1491
1492 static int find_earliest_filled_buffer(struct camera_data *cam)
1493 {
1494         int i;
1495         int found = -1;
1496         for (i=0; i<cam->num_frames; i++) {
1497                 if(cam->buffers[i].status == FRAME_READY) {
1498                         if(found < 0) {
1499                                 found = i;
1500                         } else {
1501                                 /* find which buffer is earlier */
1502                                 struct timeval *tv1, *tv2;
1503                                 tv1 = &cam->buffers[i].timestamp;
1504                                 tv2 = &cam->buffers[found].timestamp;
1505                                 if(tv1->tv_sec < tv2->tv_sec ||
1506                                    (tv1->tv_sec == tv2->tv_sec &&
1507                                     tv1->tv_usec < tv2->tv_usec))
1508                                         found = i;
1509                         }
1510                 }
1511         }
1512         return found;
1513 }
1514
1515 /******************************************************************************
1516  *
1517  *  ioctl_dqbuf
1518  *
1519  *  V4L2 User is asking for a filled buffer.
1520  *
1521  *****************************************************************************/
1522
1523 static int ioctl_dqbuf(void *arg,struct camera_data *cam, struct file *file)
1524 {
1525         struct v4l2_buffer *buf = arg;
1526         int frame;
1527
1528         if(buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1529            buf->memory != V4L2_MEMORY_MMAP)
1530                 return -EINVAL;
1531
1532         frame = find_earliest_filled_buffer(cam);
1533
1534         if(frame < 0 && file->f_flags&O_NONBLOCK)
1535                 return -EAGAIN;
1536
1537         if(frame < 0) {
1538                 /* Wait for a frame to become available */
1539                 struct framebuf *cb=cam->curbuff;
1540                 mutex_unlock(&cam->busy_lock);
1541                 wait_event_interruptible(cam->wq_stream,
1542                                          !cam->present ||
1543                                          (cb=cam->curbuff)->status == FRAME_READY);
1544                 mutex_lock(&cam->busy_lock);
1545                 if (signal_pending(current))
1546                         return -ERESTARTSYS;
1547                 if(!cam->present)
1548                         return -ENOTTY;
1549                 frame = cb->num;
1550         }
1551
1552
1553         buf->index = frame;
1554         buf->bytesused = cam->buffers[buf->index].length;
1555         buf->flags = V4L2_BUF_FLAG_MAPPED | V4L2_BUF_FLAG_DONE;
1556         buf->field = V4L2_FIELD_NONE;
1557         buf->timestamp = cam->buffers[buf->index].timestamp;
1558         buf->sequence = cam->buffers[buf->index].seq;
1559         buf->m.offset = cam->buffers[buf->index].data - cam->frame_buffer;
1560         buf->length = cam->frame_size;
1561         buf->input = 0;
1562         buf->reserved = 0;
1563         memset(&buf->timecode, 0, sizeof(buf->timecode));
1564
1565         DBG("DQBUF #%d status:%d seq:%d length:%d\n", buf->index,
1566             cam->buffers[buf->index].status, buf->sequence, buf->bytesused);
1567
1568         return 0;
1569 }
1570
1571 /******************************************************************************
1572  *
1573  *  cpia2_ioctl
1574  *
1575  *****************************************************************************/
1576 static long cpia2_do_ioctl(struct file *file, unsigned int cmd, void *arg)
1577 {
1578         struct camera_data *cam = video_drvdata(file);
1579         long retval = 0;
1580
1581         if (!cam)
1582                 return -ENOTTY;
1583
1584         /* make this _really_ smp-safe */
1585         if (mutex_lock_interruptible(&cam->busy_lock))
1586                 return -ERESTARTSYS;
1587
1588         if (!cam->present) {
1589                 mutex_unlock(&cam->busy_lock);
1590                 return -ENODEV;
1591         }
1592
1593         /* Priority check */
1594         switch (cmd) {
1595         case VIDIOCSWIN:
1596         case VIDIOCMCAPTURE:
1597         case VIDIOC_S_FMT:
1598         {
1599                 struct cpia2_fh *fh = file->private_data;
1600                 retval = v4l2_prio_check(&cam->prio, &fh->prio);
1601                 if(retval) {
1602                         mutex_unlock(&cam->busy_lock);
1603                         return retval;
1604                 }
1605                 break;
1606         }
1607         case VIDIOCGMBUF:
1608         case VIDIOCSYNC:
1609         {
1610                 struct cpia2_fh *fh = file->private_data;
1611                 if(fh->prio != V4L2_PRIORITY_RECORD) {
1612                         mutex_unlock(&cam->busy_lock);
1613                         return -EBUSY;
1614                 }
1615                 break;
1616         }
1617         default:
1618                 break;
1619         }
1620
1621         switch (cmd) {
1622         case VIDIOCGCAP:        /* query capabilities */
1623                 retval = ioctl_cap_query(arg, cam);
1624                 break;
1625
1626         case VIDIOCGCHAN:       /* get video source - we are a camera, nothing else */
1627                 retval = ioctl_get_channel(arg);
1628                 break;
1629         case VIDIOCSCHAN:       /* set video source - we are a camera, nothing else */
1630                 retval = ioctl_set_channel(arg);
1631                 break;
1632         case VIDIOCGPICT:       /* image properties */
1633                 memcpy(arg, &cam->vp, sizeof(struct video_picture));
1634                 break;
1635         case VIDIOCSPICT:
1636                 retval = ioctl_set_image_prop(arg, cam);
1637                 break;
1638         case VIDIOCGWIN:        /* get/set capture window */
1639                 memcpy(arg, &cam->vw, sizeof(struct video_window));
1640                 break;
1641         case VIDIOCSWIN:
1642                 retval = ioctl_set_window_size(arg, cam, file->private_data);
1643                 break;
1644         case VIDIOCGMBUF:       /* mmap interface */
1645                 retval = ioctl_get_mbuf(arg, cam);
1646                 break;
1647         case VIDIOCMCAPTURE:
1648                 retval = ioctl_mcapture(arg, cam, file->private_data);
1649                 break;
1650         case VIDIOCSYNC:
1651                 retval = ioctl_sync(arg, cam);
1652                 break;
1653                 /* pointless to implement overlay with this camera */
1654         case VIDIOCCAPTURE:
1655         case VIDIOCGFBUF:
1656         case VIDIOCSFBUF:
1657         case VIDIOCKEY:
1658                 retval = -EINVAL;
1659                 break;
1660
1661                 /* tuner interface - we have none */
1662         case VIDIOCGTUNER:
1663         case VIDIOCSTUNER:
1664         case VIDIOCGFREQ:
1665         case VIDIOCSFREQ:
1666                 retval = -EINVAL;
1667                 break;
1668
1669                 /* audio interface - we have none */
1670         case VIDIOCGAUDIO:
1671         case VIDIOCSAUDIO:
1672                 retval = -EINVAL;
1673                 break;
1674
1675         /* CPIA2 extension to Video4Linux API */
1676         case CPIA2_IOC_SET_GPIO:
1677                 retval = ioctl_set_gpio(arg, cam);
1678                 break;
1679         case VIDIOC_QUERYCAP:
1680                 retval = ioctl_querycap(arg,cam);
1681                 break;
1682
1683         case VIDIOC_ENUMINPUT:
1684         case VIDIOC_G_INPUT:
1685         case VIDIOC_S_INPUT:
1686                 retval = ioctl_input(cmd, arg, cam);
1687                 break;
1688
1689         case VIDIOC_ENUM_FMT:
1690                 retval = ioctl_enum_fmt(arg,cam);
1691                 break;
1692         case VIDIOC_TRY_FMT:
1693                 retval = ioctl_try_fmt(arg,cam);
1694                 break;
1695         case VIDIOC_G_FMT:
1696                 retval = ioctl_get_fmt(arg,cam);
1697                 break;
1698         case VIDIOC_S_FMT:
1699                 retval = ioctl_set_fmt(arg,cam,file->private_data);
1700                 break;
1701
1702         case VIDIOC_CROPCAP:
1703                 retval = ioctl_cropcap(arg,cam);
1704                 break;
1705         case VIDIOC_G_CROP:
1706         case VIDIOC_S_CROP:
1707                 // TODO: I think cropping can be implemented - SJB
1708                 retval = -EINVAL;
1709                 break;
1710
1711         case VIDIOC_QUERYCTRL:
1712                 retval = ioctl_queryctrl(arg,cam);
1713                 break;
1714         case VIDIOC_QUERYMENU:
1715                 retval = ioctl_querymenu(arg,cam);
1716                 break;
1717         case VIDIOC_G_CTRL:
1718                 retval = ioctl_g_ctrl(arg,cam);
1719                 break;
1720         case VIDIOC_S_CTRL:
1721                 retval = ioctl_s_ctrl(arg,cam);
1722                 break;
1723
1724         case VIDIOC_G_JPEGCOMP:
1725                 retval = ioctl_g_jpegcomp(arg,cam);
1726                 break;
1727         case VIDIOC_S_JPEGCOMP:
1728                 retval = ioctl_s_jpegcomp(arg,cam);
1729                 break;
1730
1731         case VIDIOC_G_PRIORITY:
1732         {
1733                 struct cpia2_fh *fh = file->private_data;
1734                 *(enum v4l2_priority*)arg = fh->prio;
1735                 break;
1736         }
1737         case VIDIOC_S_PRIORITY:
1738         {
1739                 struct cpia2_fh *fh = file->private_data;
1740                 enum v4l2_priority prio;
1741                 prio = *(enum v4l2_priority*)arg;
1742                 if(cam->streaming &&
1743                    prio != fh->prio &&
1744                    fh->prio == V4L2_PRIORITY_RECORD) {
1745                         /* Can't drop record priority while streaming */
1746                         retval = -EBUSY;
1747                 } else if(prio == V4L2_PRIORITY_RECORD &&
1748                    prio != fh->prio &&
1749                    v4l2_prio_max(&cam->prio) == V4L2_PRIORITY_RECORD) {
1750                         /* Only one program can record at a time */
1751                         retval = -EBUSY;
1752                 } else {
1753                         retval = v4l2_prio_change(&cam->prio, &fh->prio, prio);
1754                 }
1755                 break;
1756         }
1757
1758         case VIDIOC_REQBUFS:
1759                 retval = ioctl_reqbufs(arg,cam);
1760                 break;
1761         case VIDIOC_QUERYBUF:
1762                 retval = ioctl_querybuf(arg,cam);
1763                 break;
1764         case VIDIOC_QBUF:
1765                 retval = ioctl_qbuf(arg,cam);
1766                 break;
1767         case VIDIOC_DQBUF:
1768                 retval = ioctl_dqbuf(arg,cam,file);
1769                 break;
1770         case VIDIOC_STREAMON:
1771         {
1772                 int type;
1773                 DBG("VIDIOC_STREAMON, streaming=%d\n", cam->streaming);
1774                 type = *(int*)arg;
1775                 if(!cam->mmapped || type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1776                         retval = -EINVAL;
1777
1778                 if(!cam->streaming) {
1779                         retval = cpia2_usb_stream_start(cam,
1780                                           cam->params.camera_state.stream_mode);
1781                 } else {
1782                         retval = -EINVAL;
1783                 }
1784
1785                 break;
1786         }
1787         case VIDIOC_STREAMOFF:
1788         {
1789                 int type;
1790                 DBG("VIDIOC_STREAMOFF, streaming=%d\n", cam->streaming);
1791                 type = *(int*)arg;
1792                 if(!cam->mmapped || type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1793                         retval = -EINVAL;
1794
1795                 if(cam->streaming) {
1796                         retval = cpia2_usb_stream_stop(cam);
1797                 } else {
1798                         retval = -EINVAL;
1799                 }
1800
1801                 break;
1802         }
1803
1804         case VIDIOC_ENUMOUTPUT:
1805         case VIDIOC_G_OUTPUT:
1806         case VIDIOC_S_OUTPUT:
1807         case VIDIOC_G_MODULATOR:
1808         case VIDIOC_S_MODULATOR:
1809
1810         case VIDIOC_ENUMAUDIO:
1811         case VIDIOC_G_AUDIO:
1812         case VIDIOC_S_AUDIO:
1813
1814         case VIDIOC_ENUMAUDOUT:
1815         case VIDIOC_G_AUDOUT:
1816         case VIDIOC_S_AUDOUT:
1817
1818         case VIDIOC_ENUMSTD:
1819         case VIDIOC_QUERYSTD:
1820         case VIDIOC_G_STD:
1821         case VIDIOC_S_STD:
1822
1823         case VIDIOC_G_TUNER:
1824         case VIDIOC_S_TUNER:
1825         case VIDIOC_G_FREQUENCY:
1826         case VIDIOC_S_FREQUENCY:
1827
1828         case VIDIOC_OVERLAY:
1829         case VIDIOC_G_FBUF:
1830         case VIDIOC_S_FBUF:
1831
1832         case VIDIOC_G_PARM:
1833         case VIDIOC_S_PARM:
1834                 retval = -EINVAL;
1835                 break;
1836         default:
1837                 retval = -ENOIOCTLCMD;
1838                 break;
1839         }
1840
1841         mutex_unlock(&cam->busy_lock);
1842         return retval;
1843 }
1844
1845 static long cpia2_ioctl(struct file *file,
1846                        unsigned int cmd, unsigned long arg)
1847 {
1848         return video_usercopy(file, cmd, arg, cpia2_do_ioctl);
1849 }
1850
1851 /******************************************************************************
1852  *
1853  *  cpia2_mmap
1854  *
1855  *****************************************************************************/
1856 static int cpia2_mmap(struct file *file, struct vm_area_struct *area)
1857 {
1858         struct camera_data *cam = video_drvdata(file);
1859         int retval;
1860
1861         /* Priority check */
1862         struct cpia2_fh *fh = file->private_data;
1863         if(fh->prio != V4L2_PRIORITY_RECORD) {
1864                 return -EBUSY;
1865         }
1866
1867         retval = cpia2_remap_buffer(cam, area);
1868
1869         if(!retval)
1870                 fh->mmapped = 1;
1871         return retval;
1872 }
1873
1874 /******************************************************************************
1875  *
1876  *  reset_camera_struct_v4l
1877  *
1878  *  Sets all values to the defaults
1879  *****************************************************************************/
1880 static void reset_camera_struct_v4l(struct camera_data *cam)
1881 {
1882         /***
1883          * Fill in the v4l structures.  video_cap is filled in inside the VIDIOCCAP
1884          * Ioctl.  Here, just do the window and picture stucts.
1885          ***/
1886         cam->vp.palette = (u16) VIDEO_PALETTE_RGB24;    /* Is this right? */
1887         cam->vp.brightness = (u16) cam->params.color_params.brightness * 256;
1888         cam->vp.colour = (u16) cam->params.color_params.saturation * 256;
1889         cam->vp.contrast = (u16) cam->params.color_params.contrast * 256;
1890
1891         cam->vw.x = 0;
1892         cam->vw.y = 0;
1893         cam->vw.width = cam->params.roi.width;
1894         cam->vw.height = cam->params.roi.height;
1895         cam->vw.flags = 0;
1896         cam->vw.clipcount = 0;
1897
1898         cam->frame_size = buffer_size;
1899         cam->num_frames = num_buffers;
1900
1901         /* FlickerModes */
1902         cam->params.flicker_control.flicker_mode_req = flicker_mode;
1903         cam->params.flicker_control.mains_frequency = flicker_freq;
1904
1905         /* streamMode */
1906         cam->params.camera_state.stream_mode = alternate;
1907
1908         cam->pixelformat = V4L2_PIX_FMT_JPEG;
1909         v4l2_prio_init(&cam->prio);
1910         return;
1911 }
1912
1913 /***
1914  * The v4l video device structure initialized for this device
1915  ***/
1916 static const struct v4l2_file_operations fops_template = {
1917         .owner          = THIS_MODULE,
1918         .open           = cpia2_open,
1919         .release        = cpia2_close,
1920         .read           = cpia2_v4l_read,
1921         .poll           = cpia2_v4l_poll,
1922         .ioctl          = cpia2_ioctl,
1923         .mmap           = cpia2_mmap,
1924 };
1925
1926 static struct video_device cpia2_template = {
1927         /* I could not find any place for the old .initialize initializer?? */
1928         .name=          "CPiA2 Camera",
1929         .minor=         -1,
1930         .fops=          &fops_template,
1931         .release=       video_device_release,
1932 };
1933
1934 /******************************************************************************
1935  *
1936  *  cpia2_register_camera
1937  *
1938  *****************************************************************************/
1939 int cpia2_register_camera(struct camera_data *cam)
1940 {
1941         cam->vdev = video_device_alloc();
1942         if(!cam->vdev)
1943                 return -ENOMEM;
1944
1945         memcpy(cam->vdev, &cpia2_template, sizeof(cpia2_template));
1946         video_set_drvdata(cam->vdev, cam);
1947
1948         reset_camera_struct_v4l(cam);
1949
1950         /* register v4l device */
1951         if (video_register_device(cam->vdev, VFL_TYPE_GRABBER, video_nr) < 0) {
1952                 ERR("video_register_device failed\n");
1953                 video_device_release(cam->vdev);
1954                 return -ENODEV;
1955         }
1956
1957         return 0;
1958 }
1959
1960 /******************************************************************************
1961  *
1962  *  cpia2_unregister_camera
1963  *
1964  *****************************************************************************/
1965 void cpia2_unregister_camera(struct camera_data *cam)
1966 {
1967         if (!cam->open_count) {
1968                 video_unregister_device(cam->vdev);
1969         } else {
1970                 LOG("/dev/video%d removed while open, "
1971                     "deferring video_unregister_device\n",
1972                     cam->vdev->num);
1973         }
1974 }
1975
1976 /******************************************************************************
1977  *
1978  *  check_parameters
1979  *
1980  *  Make sure that all user-supplied parameters are sensible
1981  *****************************************************************************/
1982 static void __init check_parameters(void)
1983 {
1984         if(buffer_size < PAGE_SIZE) {
1985                 buffer_size = PAGE_SIZE;
1986                 LOG("buffer_size too small, setting to %d\n", buffer_size);
1987         } else if(buffer_size > 1024*1024) {
1988                 /* arbitrary upper limiit */
1989                 buffer_size = 1024*1024;
1990                 LOG("buffer_size ridiculously large, setting to %d\n",
1991                     buffer_size);
1992         } else {
1993                 buffer_size += PAGE_SIZE-1;
1994                 buffer_size &= ~(PAGE_SIZE-1);
1995         }
1996
1997         if(num_buffers < 1) {
1998                 num_buffers = 1;
1999                 LOG("num_buffers too small, setting to %d\n", num_buffers);
2000         } else if(num_buffers > VIDEO_MAX_FRAME) {
2001                 num_buffers = VIDEO_MAX_FRAME;
2002                 LOG("num_buffers too large, setting to %d\n", num_buffers);
2003         }
2004
2005         if(alternate < USBIF_ISO_1 || alternate > USBIF_ISO_6) {
2006                 alternate = DEFAULT_ALT;
2007                 LOG("alternate specified is invalid, using %d\n", alternate);
2008         }
2009
2010         if (flicker_mode != NEVER_FLICKER && flicker_mode != ANTI_FLICKER_ON) {
2011                 flicker_mode = NEVER_FLICKER;
2012                 LOG("Flicker mode specified is invalid, using %d\n",
2013                     flicker_mode);
2014         }
2015
2016         if (flicker_freq != FLICKER_50 && flicker_freq != FLICKER_60) {
2017                 flicker_freq = FLICKER_60;
2018                 LOG("Flicker mode specified is invalid, using %d\n",
2019                     flicker_freq);
2020         }
2021
2022         if(video_nr < -1 || video_nr > 64) {
2023                 video_nr = -1;
2024                 LOG("invalid video_nr specified, must be -1 to 64\n");
2025         }
2026
2027         DBG("Using %d buffers, each %d bytes, alternate=%d\n",
2028             num_buffers, buffer_size, alternate);
2029 }
2030
2031 /************   Module Stuff ***************/
2032
2033
2034 /******************************************************************************
2035  *
2036  * cpia2_init/module_init
2037  *
2038  *****************************************************************************/
2039 static int __init cpia2_init(void)
2040 {
2041         LOG("%s v%d.%d.%d\n",
2042             ABOUT, CPIA2_MAJ_VER, CPIA2_MIN_VER, CPIA2_PATCH_VER);
2043         check_parameters();
2044         cpia2_usb_init();
2045         return 0;
2046 }
2047
2048
2049 /******************************************************************************
2050  *
2051  * cpia2_exit/module_exit
2052  *
2053  *****************************************************************************/
2054 static void __exit cpia2_exit(void)
2055 {
2056         cpia2_usb_cleanup();
2057         schedule_timeout(2 * HZ);
2058 }
2059
2060 module_init(cpia2_init);
2061 module_exit(cpia2_exit);
2062