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