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