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