Merge git://git.kernel.org/pub/scm/linux/kernel/git/davem/sparc
[sfrench/cifs-2.6.git] / drivers / media / platform / vivid / vivid-vid-cap.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * vivid-vid-cap.c - video capture support functions.
4  *
5  * Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
6  */
7
8 #include <linux/errno.h>
9 #include <linux/kernel.h>
10 #include <linux/sched.h>
11 #include <linux/vmalloc.h>
12 #include <linux/videodev2.h>
13 #include <linux/v4l2-dv-timings.h>
14 #include <media/v4l2-common.h>
15 #include <media/v4l2-event.h>
16 #include <media/v4l2-dv-timings.h>
17 #include <media/v4l2-rect.h>
18
19 #include "vivid-core.h"
20 #include "vivid-vid-common.h"
21 #include "vivid-kthread-cap.h"
22 #include "vivid-vid-cap.h"
23
24 /* timeperframe: min/max and default */
25 static const struct v4l2_fract
26         tpf_min     = {.numerator = 1,          .denominator = FPS_MAX},
27         tpf_max     = {.numerator = FPS_MAX,    .denominator = 1};
28
29 static const struct vivid_fmt formats_ovl[] = {
30         {
31                 .fourcc   = V4L2_PIX_FMT_RGB565, /* gggbbbbb rrrrrggg */
32                 .vdownsampling = { 1 },
33                 .bit_depth = { 16 },
34                 .planes   = 1,
35                 .buffers = 1,
36         },
37         {
38                 .fourcc   = V4L2_PIX_FMT_XRGB555, /* gggbbbbb arrrrrgg */
39                 .vdownsampling = { 1 },
40                 .bit_depth = { 16 },
41                 .planes   = 1,
42                 .buffers = 1,
43         },
44         {
45                 .fourcc   = V4L2_PIX_FMT_ARGB555, /* gggbbbbb arrrrrgg */
46                 .vdownsampling = { 1 },
47                 .bit_depth = { 16 },
48                 .planes   = 1,
49                 .buffers = 1,
50         },
51 };
52
53 /* The number of discrete webcam framesizes */
54 #define VIVID_WEBCAM_SIZES 6
55 /* The number of discrete webcam frameintervals */
56 #define VIVID_WEBCAM_IVALS (VIVID_WEBCAM_SIZES * 2)
57
58 /* Sizes must be in increasing order */
59 static const struct v4l2_frmsize_discrete webcam_sizes[VIVID_WEBCAM_SIZES] = {
60         {  320, 180 },
61         {  640, 360 },
62         {  640, 480 },
63         { 1280, 720 },
64         { 1920, 1080 },
65         { 3840, 2160 },
66 };
67
68 /*
69  * Intervals must be in increasing order and there must be twice as many
70  * elements in this array as there are in webcam_sizes.
71  */
72 static const struct v4l2_fract webcam_intervals[VIVID_WEBCAM_IVALS] = {
73         {  1, 1 },
74         {  1, 2 },
75         {  1, 4 },
76         {  1, 5 },
77         {  1, 10 },
78         {  2, 25 },
79         {  1, 15 },
80         {  1, 25 },
81         {  1, 30 },
82         {  1, 40 },
83         {  1, 50 },
84         {  1, 60 },
85 };
86
87 static int vid_cap_queue_setup(struct vb2_queue *vq,
88                        unsigned *nbuffers, unsigned *nplanes,
89                        unsigned sizes[], struct device *alloc_devs[])
90 {
91         struct vivid_dev *dev = vb2_get_drv_priv(vq);
92         unsigned buffers = tpg_g_buffers(&dev->tpg);
93         unsigned h = dev->fmt_cap_rect.height;
94         unsigned p;
95
96         if (dev->field_cap == V4L2_FIELD_ALTERNATE) {
97                 /*
98                  * You cannot use read() with FIELD_ALTERNATE since the field
99                  * information (TOP/BOTTOM) cannot be passed back to the user.
100                  */
101                 if (vb2_fileio_is_active(vq))
102                         return -EINVAL;
103         }
104
105         if (dev->queue_setup_error) {
106                 /*
107                  * Error injection: test what happens if queue_setup() returns
108                  * an error.
109                  */
110                 dev->queue_setup_error = false;
111                 return -EINVAL;
112         }
113         if (*nplanes) {
114                 /*
115                  * Check if the number of requested planes match
116                  * the number of buffers in the current format. You can't mix that.
117                  */
118                 if (*nplanes != buffers)
119                         return -EINVAL;
120                 for (p = 0; p < buffers; p++) {
121                         if (sizes[p] < tpg_g_line_width(&dev->tpg, p) * h +
122                                                 dev->fmt_cap->data_offset[p])
123                                 return -EINVAL;
124                 }
125         } else {
126                 for (p = 0; p < buffers; p++)
127                         sizes[p] = tpg_g_line_width(&dev->tpg, p) * h +
128                                         dev->fmt_cap->data_offset[p];
129         }
130
131         if (vq->num_buffers + *nbuffers < 2)
132                 *nbuffers = 2 - vq->num_buffers;
133
134         *nplanes = buffers;
135
136         dprintk(dev, 1, "%s: count=%d\n", __func__, *nbuffers);
137         for (p = 0; p < buffers; p++)
138                 dprintk(dev, 1, "%s: size[%u]=%u\n", __func__, p, sizes[p]);
139
140         return 0;
141 }
142
143 static int vid_cap_buf_prepare(struct vb2_buffer *vb)
144 {
145         struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
146         unsigned long size;
147         unsigned buffers = tpg_g_buffers(&dev->tpg);
148         unsigned p;
149
150         dprintk(dev, 1, "%s\n", __func__);
151
152         if (WARN_ON(NULL == dev->fmt_cap))
153                 return -EINVAL;
154
155         if (dev->buf_prepare_error) {
156                 /*
157                  * Error injection: test what happens if buf_prepare() returns
158                  * an error.
159                  */
160                 dev->buf_prepare_error = false;
161                 return -EINVAL;
162         }
163         for (p = 0; p < buffers; p++) {
164                 size = tpg_g_line_width(&dev->tpg, p) * dev->fmt_cap_rect.height +
165                         dev->fmt_cap->data_offset[p];
166
167                 if (vb2_plane_size(vb, p) < size) {
168                         dprintk(dev, 1, "%s data will not fit into plane %u (%lu < %lu)\n",
169                                         __func__, p, vb2_plane_size(vb, p), size);
170                         return -EINVAL;
171                 }
172
173                 vb2_set_plane_payload(vb, p, size);
174                 vb->planes[p].data_offset = dev->fmt_cap->data_offset[p];
175         }
176
177         return 0;
178 }
179
180 static void vid_cap_buf_finish(struct vb2_buffer *vb)
181 {
182         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
183         struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
184         struct v4l2_timecode *tc = &vbuf->timecode;
185         unsigned fps = 25;
186         unsigned seq = vbuf->sequence;
187
188         if (!vivid_is_sdtv_cap(dev))
189                 return;
190
191         /*
192          * Set the timecode. Rarely used, so it is interesting to
193          * test this.
194          */
195         vbuf->flags |= V4L2_BUF_FLAG_TIMECODE;
196         if (dev->std_cap & V4L2_STD_525_60)
197                 fps = 30;
198         tc->type = (fps == 30) ? V4L2_TC_TYPE_30FPS : V4L2_TC_TYPE_25FPS;
199         tc->flags = 0;
200         tc->frames = seq % fps;
201         tc->seconds = (seq / fps) % 60;
202         tc->minutes = (seq / (60 * fps)) % 60;
203         tc->hours = (seq / (60 * 60 * fps)) % 24;
204 }
205
206 static void vid_cap_buf_queue(struct vb2_buffer *vb)
207 {
208         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
209         struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
210         struct vivid_buffer *buf = container_of(vbuf, struct vivid_buffer, vb);
211
212         dprintk(dev, 1, "%s\n", __func__);
213
214         spin_lock(&dev->slock);
215         list_add_tail(&buf->list, &dev->vid_cap_active);
216         spin_unlock(&dev->slock);
217 }
218
219 static int vid_cap_start_streaming(struct vb2_queue *vq, unsigned count)
220 {
221         struct vivid_dev *dev = vb2_get_drv_priv(vq);
222         unsigned i;
223         int err;
224
225         if (vb2_is_streaming(&dev->vb_vid_out_q))
226                 dev->can_loop_video = vivid_vid_can_loop(dev);
227
228         if (dev->kthread_vid_cap)
229                 return 0;
230
231         dev->vid_cap_seq_count = 0;
232         dprintk(dev, 1, "%s\n", __func__);
233         for (i = 0; i < VIDEO_MAX_FRAME; i++)
234                 dev->must_blank[i] = tpg_g_perc_fill(&dev->tpg) < 100;
235         if (dev->start_streaming_error) {
236                 dev->start_streaming_error = false;
237                 err = -EINVAL;
238         } else {
239                 err = vivid_start_generating_vid_cap(dev, &dev->vid_cap_streaming);
240         }
241         if (err) {
242                 struct vivid_buffer *buf, *tmp;
243
244                 list_for_each_entry_safe(buf, tmp, &dev->vid_cap_active, list) {
245                         list_del(&buf->list);
246                         v4l2_ctrl_request_complete(buf->vb.vb2_buf.req_obj.req,
247                                                    &dev->ctrl_hdl_vid_cap);
248                         vb2_buffer_done(&buf->vb.vb2_buf,
249                                         VB2_BUF_STATE_QUEUED);
250                 }
251         }
252         return err;
253 }
254
255 /* abort streaming and wait for last buffer */
256 static void vid_cap_stop_streaming(struct vb2_queue *vq)
257 {
258         struct vivid_dev *dev = vb2_get_drv_priv(vq);
259
260         dprintk(dev, 1, "%s\n", __func__);
261         vivid_stop_generating_vid_cap(dev, &dev->vid_cap_streaming);
262         dev->can_loop_video = false;
263 }
264
265 static void vid_cap_buf_request_complete(struct vb2_buffer *vb)
266 {
267         struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
268
269         v4l2_ctrl_request_complete(vb->req_obj.req, &dev->ctrl_hdl_vid_cap);
270 }
271
272 const struct vb2_ops vivid_vid_cap_qops = {
273         .queue_setup            = vid_cap_queue_setup,
274         .buf_prepare            = vid_cap_buf_prepare,
275         .buf_finish             = vid_cap_buf_finish,
276         .buf_queue              = vid_cap_buf_queue,
277         .start_streaming        = vid_cap_start_streaming,
278         .stop_streaming         = vid_cap_stop_streaming,
279         .buf_request_complete   = vid_cap_buf_request_complete,
280         .wait_prepare           = vb2_ops_wait_prepare,
281         .wait_finish            = vb2_ops_wait_finish,
282 };
283
284 /*
285  * Determine the 'picture' quality based on the current TV frequency: either
286  * COLOR for a good 'signal', GRAY (grayscale picture) for a slightly off
287  * signal or NOISE for no signal.
288  */
289 void vivid_update_quality(struct vivid_dev *dev)
290 {
291         unsigned freq_modulus;
292
293         if (dev->loop_video && (vivid_is_svid_cap(dev) || vivid_is_hdmi_cap(dev))) {
294                 /*
295                  * The 'noise' will only be replaced by the actual video
296                  * if the output video matches the input video settings.
297                  */
298                 tpg_s_quality(&dev->tpg, TPG_QUAL_NOISE, 0);
299                 return;
300         }
301         if (vivid_is_hdmi_cap(dev) && VIVID_INVALID_SIGNAL(dev->dv_timings_signal_mode)) {
302                 tpg_s_quality(&dev->tpg, TPG_QUAL_NOISE, 0);
303                 return;
304         }
305         if (vivid_is_sdtv_cap(dev) && VIVID_INVALID_SIGNAL(dev->std_signal_mode)) {
306                 tpg_s_quality(&dev->tpg, TPG_QUAL_NOISE, 0);
307                 return;
308         }
309         if (!vivid_is_tv_cap(dev)) {
310                 tpg_s_quality(&dev->tpg, TPG_QUAL_COLOR, 0);
311                 return;
312         }
313
314         /*
315          * There is a fake channel every 6 MHz at 49.25, 55.25, etc.
316          * From +/- 0.25 MHz around the channel there is color, and from
317          * +/- 1 MHz there is grayscale (chroma is lost).
318          * Everywhere else it is just noise.
319          */
320         freq_modulus = (dev->tv_freq - 676 /* (43.25-1) * 16 */) % (6 * 16);
321         if (freq_modulus > 2 * 16) {
322                 tpg_s_quality(&dev->tpg, TPG_QUAL_NOISE,
323                         next_pseudo_random32(dev->tv_freq ^ 0x55) & 0x3f);
324                 return;
325         }
326         if (freq_modulus < 12 /*0.75 * 16*/ || freq_modulus > 20 /*1.25 * 16*/)
327                 tpg_s_quality(&dev->tpg, TPG_QUAL_GRAY, 0);
328         else
329                 tpg_s_quality(&dev->tpg, TPG_QUAL_COLOR, 0);
330 }
331
332 /*
333  * Get the current picture quality and the associated afc value.
334  */
335 static enum tpg_quality vivid_get_quality(struct vivid_dev *dev, s32 *afc)
336 {
337         unsigned freq_modulus;
338
339         if (afc)
340                 *afc = 0;
341         if (tpg_g_quality(&dev->tpg) == TPG_QUAL_COLOR ||
342             tpg_g_quality(&dev->tpg) == TPG_QUAL_NOISE)
343                 return tpg_g_quality(&dev->tpg);
344
345         /*
346          * There is a fake channel every 6 MHz at 49.25, 55.25, etc.
347          * From +/- 0.25 MHz around the channel there is color, and from
348          * +/- 1 MHz there is grayscale (chroma is lost).
349          * Everywhere else it is just gray.
350          */
351         freq_modulus = (dev->tv_freq - 676 /* (43.25-1) * 16 */) % (6 * 16);
352         if (afc)
353                 *afc = freq_modulus - 1 * 16;
354         return TPG_QUAL_GRAY;
355 }
356
357 enum tpg_video_aspect vivid_get_video_aspect(const struct vivid_dev *dev)
358 {
359         if (vivid_is_sdtv_cap(dev))
360                 return dev->std_aspect_ratio;
361
362         if (vivid_is_hdmi_cap(dev))
363                 return dev->dv_timings_aspect_ratio;
364
365         return TPG_VIDEO_ASPECT_IMAGE;
366 }
367
368 static enum tpg_pixel_aspect vivid_get_pixel_aspect(const struct vivid_dev *dev)
369 {
370         if (vivid_is_sdtv_cap(dev))
371                 return (dev->std_cap & V4L2_STD_525_60) ?
372                         TPG_PIXEL_ASPECT_NTSC : TPG_PIXEL_ASPECT_PAL;
373
374         if (vivid_is_hdmi_cap(dev) &&
375             dev->src_rect.width == 720 && dev->src_rect.height <= 576)
376                 return dev->src_rect.height == 480 ?
377                         TPG_PIXEL_ASPECT_NTSC : TPG_PIXEL_ASPECT_PAL;
378
379         return TPG_PIXEL_ASPECT_SQUARE;
380 }
381
382 /*
383  * Called whenever the format has to be reset which can occur when
384  * changing inputs, standard, timings, etc.
385  */
386 void vivid_update_format_cap(struct vivid_dev *dev, bool keep_controls)
387 {
388         struct v4l2_bt_timings *bt = &dev->dv_timings_cap.bt;
389         unsigned size;
390         u64 pixelclock;
391
392         switch (dev->input_type[dev->input]) {
393         case WEBCAM:
394         default:
395                 dev->src_rect.width = webcam_sizes[dev->webcam_size_idx].width;
396                 dev->src_rect.height = webcam_sizes[dev->webcam_size_idx].height;
397                 dev->timeperframe_vid_cap = webcam_intervals[dev->webcam_ival_idx];
398                 dev->field_cap = V4L2_FIELD_NONE;
399                 tpg_s_rgb_range(&dev->tpg, V4L2_DV_RGB_RANGE_AUTO);
400                 break;
401         case TV:
402         case SVID:
403                 dev->field_cap = dev->tv_field_cap;
404                 dev->src_rect.width = 720;
405                 if (dev->std_cap & V4L2_STD_525_60) {
406                         dev->src_rect.height = 480;
407                         dev->timeperframe_vid_cap = (struct v4l2_fract) { 1001, 30000 };
408                         dev->service_set_cap = V4L2_SLICED_CAPTION_525;
409                 } else {
410                         dev->src_rect.height = 576;
411                         dev->timeperframe_vid_cap = (struct v4l2_fract) { 1000, 25000 };
412                         dev->service_set_cap = V4L2_SLICED_WSS_625 | V4L2_SLICED_TELETEXT_B;
413                 }
414                 tpg_s_rgb_range(&dev->tpg, V4L2_DV_RGB_RANGE_AUTO);
415                 break;
416         case HDMI:
417                 dev->src_rect.width = bt->width;
418                 dev->src_rect.height = bt->height;
419                 size = V4L2_DV_BT_FRAME_WIDTH(bt) * V4L2_DV_BT_FRAME_HEIGHT(bt);
420                 if (dev->reduced_fps && can_reduce_fps(bt)) {
421                         pixelclock = div_u64(bt->pixelclock * 1000, 1001);
422                         bt->flags |= V4L2_DV_FL_REDUCED_FPS;
423                 } else {
424                         pixelclock = bt->pixelclock;
425                         bt->flags &= ~V4L2_DV_FL_REDUCED_FPS;
426                 }
427                 dev->timeperframe_vid_cap = (struct v4l2_fract) {
428                         size / 100, (u32)pixelclock / 100
429                 };
430                 if (bt->interlaced)
431                         dev->field_cap = V4L2_FIELD_ALTERNATE;
432                 else
433                         dev->field_cap = V4L2_FIELD_NONE;
434
435                 /*
436                  * We can be called from within s_ctrl, in that case we can't
437                  * set/get controls. Luckily we don't need to in that case.
438                  */
439                 if (keep_controls || !dev->colorspace)
440                         break;
441                 if (bt->flags & V4L2_DV_FL_IS_CE_VIDEO) {
442                         if (bt->width == 720 && bt->height <= 576)
443                                 v4l2_ctrl_s_ctrl(dev->colorspace, VIVID_CS_170M);
444                         else
445                                 v4l2_ctrl_s_ctrl(dev->colorspace, VIVID_CS_709);
446                         v4l2_ctrl_s_ctrl(dev->real_rgb_range_cap, 1);
447                 } else {
448                         v4l2_ctrl_s_ctrl(dev->colorspace, VIVID_CS_SRGB);
449                         v4l2_ctrl_s_ctrl(dev->real_rgb_range_cap, 0);
450                 }
451                 tpg_s_rgb_range(&dev->tpg, v4l2_ctrl_g_ctrl(dev->rgb_range_cap));
452                 break;
453         }
454         vivid_update_quality(dev);
455         tpg_reset_source(&dev->tpg, dev->src_rect.width, dev->src_rect.height, dev->field_cap);
456         dev->crop_cap = dev->src_rect;
457         dev->crop_bounds_cap = dev->src_rect;
458         dev->compose_cap = dev->crop_cap;
459         if (V4L2_FIELD_HAS_T_OR_B(dev->field_cap))
460                 dev->compose_cap.height /= 2;
461         dev->fmt_cap_rect = dev->compose_cap;
462         tpg_s_video_aspect(&dev->tpg, vivid_get_video_aspect(dev));
463         tpg_s_pixel_aspect(&dev->tpg, vivid_get_pixel_aspect(dev));
464         tpg_update_mv_step(&dev->tpg);
465 }
466
467 /* Map the field to something that is valid for the current input */
468 static enum v4l2_field vivid_field_cap(struct vivid_dev *dev, enum v4l2_field field)
469 {
470         if (vivid_is_sdtv_cap(dev)) {
471                 switch (field) {
472                 case V4L2_FIELD_INTERLACED_TB:
473                 case V4L2_FIELD_INTERLACED_BT:
474                 case V4L2_FIELD_SEQ_TB:
475                 case V4L2_FIELD_SEQ_BT:
476                 case V4L2_FIELD_TOP:
477                 case V4L2_FIELD_BOTTOM:
478                 case V4L2_FIELD_ALTERNATE:
479                         return field;
480                 case V4L2_FIELD_INTERLACED:
481                 default:
482                         return V4L2_FIELD_INTERLACED;
483                 }
484         }
485         if (vivid_is_hdmi_cap(dev))
486                 return dev->dv_timings_cap.bt.interlaced ? V4L2_FIELD_ALTERNATE :
487                                                        V4L2_FIELD_NONE;
488         return V4L2_FIELD_NONE;
489 }
490
491 static unsigned vivid_colorspace_cap(struct vivid_dev *dev)
492 {
493         if (!dev->loop_video || vivid_is_webcam(dev) || vivid_is_tv_cap(dev))
494                 return tpg_g_colorspace(&dev->tpg);
495         return dev->colorspace_out;
496 }
497
498 static unsigned vivid_xfer_func_cap(struct vivid_dev *dev)
499 {
500         if (!dev->loop_video || vivid_is_webcam(dev) || vivid_is_tv_cap(dev))
501                 return tpg_g_xfer_func(&dev->tpg);
502         return dev->xfer_func_out;
503 }
504
505 static unsigned vivid_ycbcr_enc_cap(struct vivid_dev *dev)
506 {
507         if (!dev->loop_video || vivid_is_webcam(dev) || vivid_is_tv_cap(dev))
508                 return tpg_g_ycbcr_enc(&dev->tpg);
509         return dev->ycbcr_enc_out;
510 }
511
512 static unsigned int vivid_hsv_enc_cap(struct vivid_dev *dev)
513 {
514         if (!dev->loop_video || vivid_is_webcam(dev) || vivid_is_tv_cap(dev))
515                 return tpg_g_hsv_enc(&dev->tpg);
516         return dev->hsv_enc_out;
517 }
518
519 static unsigned vivid_quantization_cap(struct vivid_dev *dev)
520 {
521         if (!dev->loop_video || vivid_is_webcam(dev) || vivid_is_tv_cap(dev))
522                 return tpg_g_quantization(&dev->tpg);
523         return dev->quantization_out;
524 }
525
526 int vivid_g_fmt_vid_cap(struct file *file, void *priv,
527                                         struct v4l2_format *f)
528 {
529         struct vivid_dev *dev = video_drvdata(file);
530         struct v4l2_pix_format_mplane *mp = &f->fmt.pix_mp;
531         unsigned p;
532
533         mp->width        = dev->fmt_cap_rect.width;
534         mp->height       = dev->fmt_cap_rect.height;
535         mp->field        = dev->field_cap;
536         mp->pixelformat  = dev->fmt_cap->fourcc;
537         mp->colorspace   = vivid_colorspace_cap(dev);
538         mp->xfer_func    = vivid_xfer_func_cap(dev);
539         if (dev->fmt_cap->color_enc == TGP_COLOR_ENC_HSV)
540                 mp->hsv_enc    = vivid_hsv_enc_cap(dev);
541         else
542                 mp->ycbcr_enc    = vivid_ycbcr_enc_cap(dev);
543         mp->quantization = vivid_quantization_cap(dev);
544         mp->num_planes = dev->fmt_cap->buffers;
545         for (p = 0; p < mp->num_planes; p++) {
546                 mp->plane_fmt[p].bytesperline = tpg_g_bytesperline(&dev->tpg, p);
547                 mp->plane_fmt[p].sizeimage =
548                         tpg_g_line_width(&dev->tpg, p) * mp->height +
549                         dev->fmt_cap->data_offset[p];
550         }
551         return 0;
552 }
553
554 int vivid_try_fmt_vid_cap(struct file *file, void *priv,
555                         struct v4l2_format *f)
556 {
557         struct v4l2_pix_format_mplane *mp = &f->fmt.pix_mp;
558         struct v4l2_plane_pix_format *pfmt = mp->plane_fmt;
559         struct vivid_dev *dev = video_drvdata(file);
560         const struct vivid_fmt *fmt;
561         unsigned bytesperline, max_bpl;
562         unsigned factor = 1;
563         unsigned w, h;
564         unsigned p;
565
566         fmt = vivid_get_format(dev, mp->pixelformat);
567         if (!fmt) {
568                 dprintk(dev, 1, "Fourcc format (0x%08x) unknown.\n",
569                         mp->pixelformat);
570                 mp->pixelformat = V4L2_PIX_FMT_YUYV;
571                 fmt = vivid_get_format(dev, mp->pixelformat);
572         }
573
574         mp->field = vivid_field_cap(dev, mp->field);
575         if (vivid_is_webcam(dev)) {
576                 const struct v4l2_frmsize_discrete *sz =
577                         v4l2_find_nearest_size(webcam_sizes,
578                                                VIVID_WEBCAM_SIZES, width,
579                                                height, mp->width, mp->height);
580
581                 w = sz->width;
582                 h = sz->height;
583         } else if (vivid_is_sdtv_cap(dev)) {
584                 w = 720;
585                 h = (dev->std_cap & V4L2_STD_525_60) ? 480 : 576;
586         } else {
587                 w = dev->src_rect.width;
588                 h = dev->src_rect.height;
589         }
590         if (V4L2_FIELD_HAS_T_OR_B(mp->field))
591                 factor = 2;
592         if (vivid_is_webcam(dev) ||
593             (!dev->has_scaler_cap && !dev->has_crop_cap && !dev->has_compose_cap)) {
594                 mp->width = w;
595                 mp->height = h / factor;
596         } else {
597                 struct v4l2_rect r = { 0, 0, mp->width, mp->height * factor };
598
599                 v4l2_rect_set_min_size(&r, &vivid_min_rect);
600                 v4l2_rect_set_max_size(&r, &vivid_max_rect);
601                 if (dev->has_scaler_cap && !dev->has_compose_cap) {
602                         struct v4l2_rect max_r = { 0, 0, MAX_ZOOM * w, MAX_ZOOM * h };
603
604                         v4l2_rect_set_max_size(&r, &max_r);
605                 } else if (!dev->has_scaler_cap && dev->has_crop_cap && !dev->has_compose_cap) {
606                         v4l2_rect_set_max_size(&r, &dev->src_rect);
607                 } else if (!dev->has_scaler_cap && !dev->has_crop_cap) {
608                         v4l2_rect_set_min_size(&r, &dev->src_rect);
609                 }
610                 mp->width = r.width;
611                 mp->height = r.height / factor;
612         }
613
614         /* This driver supports custom bytesperline values */
615
616         mp->num_planes = fmt->buffers;
617         for (p = 0; p < fmt->buffers; p++) {
618                 /* Calculate the minimum supported bytesperline value */
619                 bytesperline = (mp->width * fmt->bit_depth[p]) >> 3;
620                 /* Calculate the maximum supported bytesperline value */
621                 max_bpl = (MAX_ZOOM * MAX_WIDTH * fmt->bit_depth[p]) >> 3;
622
623                 if (pfmt[p].bytesperline > max_bpl)
624                         pfmt[p].bytesperline = max_bpl;
625                 if (pfmt[p].bytesperline < bytesperline)
626                         pfmt[p].bytesperline = bytesperline;
627
628                 pfmt[p].sizeimage = (pfmt[p].bytesperline * mp->height) /
629                                 fmt->vdownsampling[p] + fmt->data_offset[p];
630
631                 memset(pfmt[p].reserved, 0, sizeof(pfmt[p].reserved));
632         }
633         for (p = fmt->buffers; p < fmt->planes; p++)
634                 pfmt[0].sizeimage += (pfmt[0].bytesperline * mp->height *
635                         (fmt->bit_depth[p] / fmt->vdownsampling[p])) /
636                         (fmt->bit_depth[0] / fmt->vdownsampling[0]);
637
638         mp->colorspace = vivid_colorspace_cap(dev);
639         if (fmt->color_enc == TGP_COLOR_ENC_HSV)
640                 mp->hsv_enc = vivid_hsv_enc_cap(dev);
641         else
642                 mp->ycbcr_enc = vivid_ycbcr_enc_cap(dev);
643         mp->xfer_func = vivid_xfer_func_cap(dev);
644         mp->quantization = vivid_quantization_cap(dev);
645         memset(mp->reserved, 0, sizeof(mp->reserved));
646         return 0;
647 }
648
649 int vivid_s_fmt_vid_cap(struct file *file, void *priv,
650                                         struct v4l2_format *f)
651 {
652         struct v4l2_pix_format_mplane *mp = &f->fmt.pix_mp;
653         struct vivid_dev *dev = video_drvdata(file);
654         struct v4l2_rect *crop = &dev->crop_cap;
655         struct v4l2_rect *compose = &dev->compose_cap;
656         struct vb2_queue *q = &dev->vb_vid_cap_q;
657         int ret = vivid_try_fmt_vid_cap(file, priv, f);
658         unsigned factor = 1;
659         unsigned p;
660         unsigned i;
661
662         if (ret < 0)
663                 return ret;
664
665         if (vb2_is_busy(q)) {
666                 dprintk(dev, 1, "%s device busy\n", __func__);
667                 return -EBUSY;
668         }
669
670         if (dev->overlay_cap_owner && dev->fb_cap.fmt.pixelformat != mp->pixelformat) {
671                 dprintk(dev, 1, "overlay is active, can't change pixelformat\n");
672                 return -EBUSY;
673         }
674
675         dev->fmt_cap = vivid_get_format(dev, mp->pixelformat);
676         if (V4L2_FIELD_HAS_T_OR_B(mp->field))
677                 factor = 2;
678
679         /* Note: the webcam input doesn't support scaling, cropping or composing */
680
681         if (!vivid_is_webcam(dev) &&
682             (dev->has_scaler_cap || dev->has_crop_cap || dev->has_compose_cap)) {
683                 struct v4l2_rect r = { 0, 0, mp->width, mp->height };
684
685                 if (dev->has_scaler_cap) {
686                         if (dev->has_compose_cap)
687                                 v4l2_rect_map_inside(compose, &r);
688                         else
689                                 *compose = r;
690                         if (dev->has_crop_cap && !dev->has_compose_cap) {
691                                 struct v4l2_rect min_r = {
692                                         0, 0,
693                                         r.width / MAX_ZOOM,
694                                         factor * r.height / MAX_ZOOM
695                                 };
696                                 struct v4l2_rect max_r = {
697                                         0, 0,
698                                         r.width * MAX_ZOOM,
699                                         factor * r.height * MAX_ZOOM
700                                 };
701
702                                 v4l2_rect_set_min_size(crop, &min_r);
703                                 v4l2_rect_set_max_size(crop, &max_r);
704                                 v4l2_rect_map_inside(crop, &dev->crop_bounds_cap);
705                         } else if (dev->has_crop_cap) {
706                                 struct v4l2_rect min_r = {
707                                         0, 0,
708                                         compose->width / MAX_ZOOM,
709                                         factor * compose->height / MAX_ZOOM
710                                 };
711                                 struct v4l2_rect max_r = {
712                                         0, 0,
713                                         compose->width * MAX_ZOOM,
714                                         factor * compose->height * MAX_ZOOM
715                                 };
716
717                                 v4l2_rect_set_min_size(crop, &min_r);
718                                 v4l2_rect_set_max_size(crop, &max_r);
719                                 v4l2_rect_map_inside(crop, &dev->crop_bounds_cap);
720                         }
721                 } else if (dev->has_crop_cap && !dev->has_compose_cap) {
722                         r.height *= factor;
723                         v4l2_rect_set_size_to(crop, &r);
724                         v4l2_rect_map_inside(crop, &dev->crop_bounds_cap);
725                         r = *crop;
726                         r.height /= factor;
727                         v4l2_rect_set_size_to(compose, &r);
728                 } else if (!dev->has_crop_cap) {
729                         v4l2_rect_map_inside(compose, &r);
730                 } else {
731                         r.height *= factor;
732                         v4l2_rect_set_max_size(crop, &r);
733                         v4l2_rect_map_inside(crop, &dev->crop_bounds_cap);
734                         compose->top *= factor;
735                         compose->height *= factor;
736                         v4l2_rect_set_size_to(compose, crop);
737                         v4l2_rect_map_inside(compose, &r);
738                         compose->top /= factor;
739                         compose->height /= factor;
740                 }
741         } else if (vivid_is_webcam(dev)) {
742                 /* Guaranteed to be a match */
743                 for (i = 0; i < ARRAY_SIZE(webcam_sizes); i++)
744                         if (webcam_sizes[i].width == mp->width &&
745                                         webcam_sizes[i].height == mp->height)
746                                 break;
747                 dev->webcam_size_idx = i;
748                 if (dev->webcam_ival_idx >= 2 * (VIVID_WEBCAM_SIZES - i))
749                         dev->webcam_ival_idx = 2 * (VIVID_WEBCAM_SIZES - i) - 1;
750                 vivid_update_format_cap(dev, false);
751         } else {
752                 struct v4l2_rect r = { 0, 0, mp->width, mp->height };
753
754                 v4l2_rect_set_size_to(compose, &r);
755                 r.height *= factor;
756                 v4l2_rect_set_size_to(crop, &r);
757         }
758
759         dev->fmt_cap_rect.width = mp->width;
760         dev->fmt_cap_rect.height = mp->height;
761         tpg_s_buf_height(&dev->tpg, mp->height);
762         tpg_s_fourcc(&dev->tpg, dev->fmt_cap->fourcc);
763         for (p = 0; p < tpg_g_buffers(&dev->tpg); p++)
764                 tpg_s_bytesperline(&dev->tpg, p, mp->plane_fmt[p].bytesperline);
765         dev->field_cap = mp->field;
766         if (dev->field_cap == V4L2_FIELD_ALTERNATE)
767                 tpg_s_field(&dev->tpg, V4L2_FIELD_TOP, true);
768         else
769                 tpg_s_field(&dev->tpg, dev->field_cap, false);
770         tpg_s_crop_compose(&dev->tpg, &dev->crop_cap, &dev->compose_cap);
771         if (vivid_is_sdtv_cap(dev))
772                 dev->tv_field_cap = mp->field;
773         tpg_update_mv_step(&dev->tpg);
774         return 0;
775 }
776
777 int vidioc_g_fmt_vid_cap_mplane(struct file *file, void *priv,
778                                         struct v4l2_format *f)
779 {
780         struct vivid_dev *dev = video_drvdata(file);
781
782         if (!dev->multiplanar)
783                 return -ENOTTY;
784         return vivid_g_fmt_vid_cap(file, priv, f);
785 }
786
787 int vidioc_try_fmt_vid_cap_mplane(struct file *file, void *priv,
788                         struct v4l2_format *f)
789 {
790         struct vivid_dev *dev = video_drvdata(file);
791
792         if (!dev->multiplanar)
793                 return -ENOTTY;
794         return vivid_try_fmt_vid_cap(file, priv, f);
795 }
796
797 int vidioc_s_fmt_vid_cap_mplane(struct file *file, void *priv,
798                         struct v4l2_format *f)
799 {
800         struct vivid_dev *dev = video_drvdata(file);
801
802         if (!dev->multiplanar)
803                 return -ENOTTY;
804         return vivid_s_fmt_vid_cap(file, priv, f);
805 }
806
807 int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
808                                         struct v4l2_format *f)
809 {
810         struct vivid_dev *dev = video_drvdata(file);
811
812         if (dev->multiplanar)
813                 return -ENOTTY;
814         return fmt_sp2mp_func(file, priv, f, vivid_g_fmt_vid_cap);
815 }
816
817 int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
818                         struct v4l2_format *f)
819 {
820         struct vivid_dev *dev = video_drvdata(file);
821
822         if (dev->multiplanar)
823                 return -ENOTTY;
824         return fmt_sp2mp_func(file, priv, f, vivid_try_fmt_vid_cap);
825 }
826
827 int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
828                         struct v4l2_format *f)
829 {
830         struct vivid_dev *dev = video_drvdata(file);
831
832         if (dev->multiplanar)
833                 return -ENOTTY;
834         return fmt_sp2mp_func(file, priv, f, vivid_s_fmt_vid_cap);
835 }
836
837 int vivid_vid_cap_g_selection(struct file *file, void *priv,
838                               struct v4l2_selection *sel)
839 {
840         struct vivid_dev *dev = video_drvdata(file);
841
842         if (!dev->has_crop_cap && !dev->has_compose_cap)
843                 return -ENOTTY;
844         if (sel->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
845                 return -EINVAL;
846         if (vivid_is_webcam(dev))
847                 return -ENODATA;
848
849         sel->r.left = sel->r.top = 0;
850         switch (sel->target) {
851         case V4L2_SEL_TGT_CROP:
852                 if (!dev->has_crop_cap)
853                         return -EINVAL;
854                 sel->r = dev->crop_cap;
855                 break;
856         case V4L2_SEL_TGT_CROP_DEFAULT:
857         case V4L2_SEL_TGT_CROP_BOUNDS:
858                 if (!dev->has_crop_cap)
859                         return -EINVAL;
860                 sel->r = dev->src_rect;
861                 break;
862         case V4L2_SEL_TGT_COMPOSE_BOUNDS:
863                 if (!dev->has_compose_cap)
864                         return -EINVAL;
865                 sel->r = vivid_max_rect;
866                 break;
867         case V4L2_SEL_TGT_COMPOSE:
868                 if (!dev->has_compose_cap)
869                         return -EINVAL;
870                 sel->r = dev->compose_cap;
871                 break;
872         case V4L2_SEL_TGT_COMPOSE_DEFAULT:
873                 if (!dev->has_compose_cap)
874                         return -EINVAL;
875                 sel->r = dev->fmt_cap_rect;
876                 break;
877         default:
878                 return -EINVAL;
879         }
880         return 0;
881 }
882
883 int vivid_vid_cap_s_selection(struct file *file, void *fh, struct v4l2_selection *s)
884 {
885         struct vivid_dev *dev = video_drvdata(file);
886         struct v4l2_rect *crop = &dev->crop_cap;
887         struct v4l2_rect *compose = &dev->compose_cap;
888         unsigned factor = V4L2_FIELD_HAS_T_OR_B(dev->field_cap) ? 2 : 1;
889         int ret;
890
891         if (!dev->has_crop_cap && !dev->has_compose_cap)
892                 return -ENOTTY;
893         if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
894                 return -EINVAL;
895         if (vivid_is_webcam(dev))
896                 return -ENODATA;
897
898         switch (s->target) {
899         case V4L2_SEL_TGT_CROP:
900                 if (!dev->has_crop_cap)
901                         return -EINVAL;
902                 ret = vivid_vid_adjust_sel(s->flags, &s->r);
903                 if (ret)
904                         return ret;
905                 v4l2_rect_set_min_size(&s->r, &vivid_min_rect);
906                 v4l2_rect_set_max_size(&s->r, &dev->src_rect);
907                 v4l2_rect_map_inside(&s->r, &dev->crop_bounds_cap);
908                 s->r.top /= factor;
909                 s->r.height /= factor;
910                 if (dev->has_scaler_cap) {
911                         struct v4l2_rect fmt = dev->fmt_cap_rect;
912                         struct v4l2_rect max_rect = {
913                                 0, 0,
914                                 s->r.width * MAX_ZOOM,
915                                 s->r.height * MAX_ZOOM
916                         };
917                         struct v4l2_rect min_rect = {
918                                 0, 0,
919                                 s->r.width / MAX_ZOOM,
920                                 s->r.height / MAX_ZOOM
921                         };
922
923                         v4l2_rect_set_min_size(&fmt, &min_rect);
924                         if (!dev->has_compose_cap)
925                                 v4l2_rect_set_max_size(&fmt, &max_rect);
926                         if (!v4l2_rect_same_size(&dev->fmt_cap_rect, &fmt) &&
927                             vb2_is_busy(&dev->vb_vid_cap_q))
928                                 return -EBUSY;
929                         if (dev->has_compose_cap) {
930                                 v4l2_rect_set_min_size(compose, &min_rect);
931                                 v4l2_rect_set_max_size(compose, &max_rect);
932                         }
933                         dev->fmt_cap_rect = fmt;
934                         tpg_s_buf_height(&dev->tpg, fmt.height);
935                 } else if (dev->has_compose_cap) {
936                         struct v4l2_rect fmt = dev->fmt_cap_rect;
937
938                         v4l2_rect_set_min_size(&fmt, &s->r);
939                         if (!v4l2_rect_same_size(&dev->fmt_cap_rect, &fmt) &&
940                             vb2_is_busy(&dev->vb_vid_cap_q))
941                                 return -EBUSY;
942                         dev->fmt_cap_rect = fmt;
943                         tpg_s_buf_height(&dev->tpg, fmt.height);
944                         v4l2_rect_set_size_to(compose, &s->r);
945                         v4l2_rect_map_inside(compose, &dev->fmt_cap_rect);
946                 } else {
947                         if (!v4l2_rect_same_size(&s->r, &dev->fmt_cap_rect) &&
948                             vb2_is_busy(&dev->vb_vid_cap_q))
949                                 return -EBUSY;
950                         v4l2_rect_set_size_to(&dev->fmt_cap_rect, &s->r);
951                         v4l2_rect_set_size_to(compose, &s->r);
952                         v4l2_rect_map_inside(compose, &dev->fmt_cap_rect);
953                         tpg_s_buf_height(&dev->tpg, dev->fmt_cap_rect.height);
954                 }
955                 s->r.top *= factor;
956                 s->r.height *= factor;
957                 *crop = s->r;
958                 break;
959         case V4L2_SEL_TGT_COMPOSE:
960                 if (!dev->has_compose_cap)
961                         return -EINVAL;
962                 ret = vivid_vid_adjust_sel(s->flags, &s->r);
963                 if (ret)
964                         return ret;
965                 v4l2_rect_set_min_size(&s->r, &vivid_min_rect);
966                 v4l2_rect_set_max_size(&s->r, &dev->fmt_cap_rect);
967                 if (dev->has_scaler_cap) {
968                         struct v4l2_rect max_rect = {
969                                 0, 0,
970                                 dev->src_rect.width * MAX_ZOOM,
971                                 (dev->src_rect.height / factor) * MAX_ZOOM
972                         };
973
974                         v4l2_rect_set_max_size(&s->r, &max_rect);
975                         if (dev->has_crop_cap) {
976                                 struct v4l2_rect min_rect = {
977                                         0, 0,
978                                         s->r.width / MAX_ZOOM,
979                                         (s->r.height * factor) / MAX_ZOOM
980                                 };
981                                 struct v4l2_rect max_rect = {
982                                         0, 0,
983                                         s->r.width * MAX_ZOOM,
984                                         (s->r.height * factor) * MAX_ZOOM
985                                 };
986
987                                 v4l2_rect_set_min_size(crop, &min_rect);
988                                 v4l2_rect_set_max_size(crop, &max_rect);
989                                 v4l2_rect_map_inside(crop, &dev->crop_bounds_cap);
990                         }
991                 } else if (dev->has_crop_cap) {
992                         s->r.top *= factor;
993                         s->r.height *= factor;
994                         v4l2_rect_set_max_size(&s->r, &dev->src_rect);
995                         v4l2_rect_set_size_to(crop, &s->r);
996                         v4l2_rect_map_inside(crop, &dev->crop_bounds_cap);
997                         s->r.top /= factor;
998                         s->r.height /= factor;
999                 } else {
1000                         v4l2_rect_set_size_to(&s->r, &dev->src_rect);
1001                         s->r.height /= factor;
1002                 }
1003                 v4l2_rect_map_inside(&s->r, &dev->fmt_cap_rect);
1004                 if (dev->bitmap_cap && (compose->width != s->r.width ||
1005                                         compose->height != s->r.height)) {
1006                         kfree(dev->bitmap_cap);
1007                         dev->bitmap_cap = NULL;
1008                 }
1009                 *compose = s->r;
1010                 break;
1011         default:
1012                 return -EINVAL;
1013         }
1014
1015         tpg_s_crop_compose(&dev->tpg, crop, compose);
1016         return 0;
1017 }
1018
1019 int vivid_vid_cap_cropcap(struct file *file, void *priv,
1020                               struct v4l2_cropcap *cap)
1021 {
1022         struct vivid_dev *dev = video_drvdata(file);
1023
1024         if (cap->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1025                 return -EINVAL;
1026
1027         switch (vivid_get_pixel_aspect(dev)) {
1028         case TPG_PIXEL_ASPECT_NTSC:
1029                 cap->pixelaspect.numerator = 11;
1030                 cap->pixelaspect.denominator = 10;
1031                 break;
1032         case TPG_PIXEL_ASPECT_PAL:
1033                 cap->pixelaspect.numerator = 54;
1034                 cap->pixelaspect.denominator = 59;
1035                 break;
1036         case TPG_PIXEL_ASPECT_SQUARE:
1037                 cap->pixelaspect.numerator = 1;
1038                 cap->pixelaspect.denominator = 1;
1039                 break;
1040         }
1041         return 0;
1042 }
1043
1044 int vidioc_enum_fmt_vid_overlay(struct file *file, void  *priv,
1045                                         struct v4l2_fmtdesc *f)
1046 {
1047         struct vivid_dev *dev = video_drvdata(file);
1048         const struct vivid_fmt *fmt;
1049
1050         if (dev->multiplanar)
1051                 return -ENOTTY;
1052
1053         if (f->index >= ARRAY_SIZE(formats_ovl))
1054                 return -EINVAL;
1055
1056         fmt = &formats_ovl[f->index];
1057
1058         f->pixelformat = fmt->fourcc;
1059         return 0;
1060 }
1061
1062 int vidioc_g_fmt_vid_overlay(struct file *file, void *priv,
1063                                         struct v4l2_format *f)
1064 {
1065         struct vivid_dev *dev = video_drvdata(file);
1066         const struct v4l2_rect *compose = &dev->compose_cap;
1067         struct v4l2_window *win = &f->fmt.win;
1068         unsigned clipcount = win->clipcount;
1069
1070         if (dev->multiplanar)
1071                 return -ENOTTY;
1072
1073         win->w.top = dev->overlay_cap_top;
1074         win->w.left = dev->overlay_cap_left;
1075         win->w.width = compose->width;
1076         win->w.height = compose->height;
1077         win->field = dev->overlay_cap_field;
1078         win->clipcount = dev->clipcount_cap;
1079         if (clipcount > dev->clipcount_cap)
1080                 clipcount = dev->clipcount_cap;
1081         if (dev->bitmap_cap == NULL)
1082                 win->bitmap = NULL;
1083         else if (win->bitmap) {
1084                 if (copy_to_user(win->bitmap, dev->bitmap_cap,
1085                     ((compose->width + 7) / 8) * compose->height))
1086                         return -EFAULT;
1087         }
1088         if (clipcount && win->clips) {
1089                 if (copy_to_user(win->clips, dev->clips_cap,
1090                                  clipcount * sizeof(dev->clips_cap[0])))
1091                         return -EFAULT;
1092         }
1093         return 0;
1094 }
1095
1096 int vidioc_try_fmt_vid_overlay(struct file *file, void *priv,
1097                                         struct v4l2_format *f)
1098 {
1099         struct vivid_dev *dev = video_drvdata(file);
1100         const struct v4l2_rect *compose = &dev->compose_cap;
1101         struct v4l2_window *win = &f->fmt.win;
1102         int i, j;
1103
1104         if (dev->multiplanar)
1105                 return -ENOTTY;
1106
1107         win->w.left = clamp_t(int, win->w.left,
1108                               -dev->fb_cap.fmt.width, dev->fb_cap.fmt.width);
1109         win->w.top = clamp_t(int, win->w.top,
1110                              -dev->fb_cap.fmt.height, dev->fb_cap.fmt.height);
1111         win->w.width = compose->width;
1112         win->w.height = compose->height;
1113         if (win->field != V4L2_FIELD_BOTTOM && win->field != V4L2_FIELD_TOP)
1114                 win->field = V4L2_FIELD_ANY;
1115         win->chromakey = 0;
1116         win->global_alpha = 0;
1117         if (win->clipcount && !win->clips)
1118                 win->clipcount = 0;
1119         if (win->clipcount > MAX_CLIPS)
1120                 win->clipcount = MAX_CLIPS;
1121         if (win->clipcount) {
1122                 if (copy_from_user(dev->try_clips_cap, win->clips,
1123                                    win->clipcount * sizeof(dev->clips_cap[0])))
1124                         return -EFAULT;
1125                 for (i = 0; i < win->clipcount; i++) {
1126                         struct v4l2_rect *r = &dev->try_clips_cap[i].c;
1127
1128                         r->top = clamp_t(s32, r->top, 0, dev->fb_cap.fmt.height - 1);
1129                         r->height = clamp_t(s32, r->height, 1, dev->fb_cap.fmt.height - r->top);
1130                         r->left = clamp_t(u32, r->left, 0, dev->fb_cap.fmt.width - 1);
1131                         r->width = clamp_t(u32, r->width, 1, dev->fb_cap.fmt.width - r->left);
1132                 }
1133                 /*
1134                  * Yeah, so sue me, it's an O(n^2) algorithm. But n is a small
1135                  * number and it's typically a one-time deal.
1136                  */
1137                 for (i = 0; i < win->clipcount - 1; i++) {
1138                         struct v4l2_rect *r1 = &dev->try_clips_cap[i].c;
1139
1140                         for (j = i + 1; j < win->clipcount; j++) {
1141                                 struct v4l2_rect *r2 = &dev->try_clips_cap[j].c;
1142
1143                                 if (v4l2_rect_overlap(r1, r2))
1144                                         return -EINVAL;
1145                         }
1146                 }
1147                 if (copy_to_user(win->clips, dev->try_clips_cap,
1148                                  win->clipcount * sizeof(dev->clips_cap[0])))
1149                         return -EFAULT;
1150         }
1151         return 0;
1152 }
1153
1154 int vidioc_s_fmt_vid_overlay(struct file *file, void *priv,
1155                                         struct v4l2_format *f)
1156 {
1157         struct vivid_dev *dev = video_drvdata(file);
1158         const struct v4l2_rect *compose = &dev->compose_cap;
1159         struct v4l2_window *win = &f->fmt.win;
1160         int ret = vidioc_try_fmt_vid_overlay(file, priv, f);
1161         unsigned bitmap_size = ((compose->width + 7) / 8) * compose->height;
1162         unsigned clips_size = win->clipcount * sizeof(dev->clips_cap[0]);
1163         void *new_bitmap = NULL;
1164
1165         if (ret)
1166                 return ret;
1167
1168         if (win->bitmap) {
1169                 new_bitmap = vzalloc(bitmap_size);
1170
1171                 if (new_bitmap == NULL)
1172                         return -ENOMEM;
1173                 if (copy_from_user(new_bitmap, win->bitmap, bitmap_size)) {
1174                         vfree(new_bitmap);
1175                         return -EFAULT;
1176                 }
1177         }
1178
1179         dev->overlay_cap_top = win->w.top;
1180         dev->overlay_cap_left = win->w.left;
1181         dev->overlay_cap_field = win->field;
1182         vfree(dev->bitmap_cap);
1183         dev->bitmap_cap = new_bitmap;
1184         dev->clipcount_cap = win->clipcount;
1185         if (dev->clipcount_cap)
1186                 memcpy(dev->clips_cap, dev->try_clips_cap, clips_size);
1187         return 0;
1188 }
1189
1190 int vivid_vid_cap_overlay(struct file *file, void *fh, unsigned i)
1191 {
1192         struct vivid_dev *dev = video_drvdata(file);
1193
1194         if (dev->multiplanar)
1195                 return -ENOTTY;
1196
1197         if (i && dev->fb_vbase_cap == NULL)
1198                 return -EINVAL;
1199
1200         if (i && dev->fb_cap.fmt.pixelformat != dev->fmt_cap->fourcc) {
1201                 dprintk(dev, 1, "mismatch between overlay and video capture pixelformats\n");
1202                 return -EINVAL;
1203         }
1204
1205         if (dev->overlay_cap_owner && dev->overlay_cap_owner != fh)
1206                 return -EBUSY;
1207         dev->overlay_cap_owner = i ? fh : NULL;
1208         return 0;
1209 }
1210
1211 int vivid_vid_cap_g_fbuf(struct file *file, void *fh,
1212                                 struct v4l2_framebuffer *a)
1213 {
1214         struct vivid_dev *dev = video_drvdata(file);
1215
1216         if (dev->multiplanar)
1217                 return -ENOTTY;
1218
1219         *a = dev->fb_cap;
1220         a->capability = V4L2_FBUF_CAP_BITMAP_CLIPPING |
1221                         V4L2_FBUF_CAP_LIST_CLIPPING;
1222         a->flags = V4L2_FBUF_FLAG_PRIMARY;
1223         a->fmt.field = V4L2_FIELD_NONE;
1224         a->fmt.colorspace = V4L2_COLORSPACE_SRGB;
1225         a->fmt.priv = 0;
1226         return 0;
1227 }
1228
1229 int vivid_vid_cap_s_fbuf(struct file *file, void *fh,
1230                                 const struct v4l2_framebuffer *a)
1231 {
1232         struct vivid_dev *dev = video_drvdata(file);
1233         const struct vivid_fmt *fmt;
1234
1235         if (dev->multiplanar)
1236                 return -ENOTTY;
1237
1238         if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RAWIO))
1239                 return -EPERM;
1240
1241         if (dev->overlay_cap_owner)
1242                 return -EBUSY;
1243
1244         if (a->base == NULL) {
1245                 dev->fb_cap.base = NULL;
1246                 dev->fb_vbase_cap = NULL;
1247                 return 0;
1248         }
1249
1250         if (a->fmt.width < 48 || a->fmt.height < 32)
1251                 return -EINVAL;
1252         fmt = vivid_get_format(dev, a->fmt.pixelformat);
1253         if (!fmt || !fmt->can_do_overlay)
1254                 return -EINVAL;
1255         if (a->fmt.bytesperline < (a->fmt.width * fmt->bit_depth[0]) / 8)
1256                 return -EINVAL;
1257         if (a->fmt.height * a->fmt.bytesperline < a->fmt.sizeimage)
1258                 return -EINVAL;
1259
1260         dev->fb_vbase_cap = phys_to_virt((unsigned long)a->base);
1261         dev->fb_cap = *a;
1262         dev->overlay_cap_left = clamp_t(int, dev->overlay_cap_left,
1263                                     -dev->fb_cap.fmt.width, dev->fb_cap.fmt.width);
1264         dev->overlay_cap_top = clamp_t(int, dev->overlay_cap_top,
1265                                    -dev->fb_cap.fmt.height, dev->fb_cap.fmt.height);
1266         return 0;
1267 }
1268
1269 static const struct v4l2_audio vivid_audio_inputs[] = {
1270         { 0, "TV", V4L2_AUDCAP_STEREO },
1271         { 1, "Line-In", V4L2_AUDCAP_STEREO },
1272 };
1273
1274 int vidioc_enum_input(struct file *file, void *priv,
1275                                 struct v4l2_input *inp)
1276 {
1277         struct vivid_dev *dev = video_drvdata(file);
1278
1279         if (inp->index >= dev->num_inputs)
1280                 return -EINVAL;
1281
1282         inp->type = V4L2_INPUT_TYPE_CAMERA;
1283         switch (dev->input_type[inp->index]) {
1284         case WEBCAM:
1285                 snprintf(inp->name, sizeof(inp->name), "Webcam %u",
1286                                 dev->input_name_counter[inp->index]);
1287                 inp->capabilities = 0;
1288                 break;
1289         case TV:
1290                 snprintf(inp->name, sizeof(inp->name), "TV %u",
1291                                 dev->input_name_counter[inp->index]);
1292                 inp->type = V4L2_INPUT_TYPE_TUNER;
1293                 inp->std = V4L2_STD_ALL;
1294                 if (dev->has_audio_inputs)
1295                         inp->audioset = (1 << ARRAY_SIZE(vivid_audio_inputs)) - 1;
1296                 inp->capabilities = V4L2_IN_CAP_STD;
1297                 break;
1298         case SVID:
1299                 snprintf(inp->name, sizeof(inp->name), "S-Video %u",
1300                                 dev->input_name_counter[inp->index]);
1301                 inp->std = V4L2_STD_ALL;
1302                 if (dev->has_audio_inputs)
1303                         inp->audioset = (1 << ARRAY_SIZE(vivid_audio_inputs)) - 1;
1304                 inp->capabilities = V4L2_IN_CAP_STD;
1305                 break;
1306         case HDMI:
1307                 snprintf(inp->name, sizeof(inp->name), "HDMI %u",
1308                                 dev->input_name_counter[inp->index]);
1309                 inp->capabilities = V4L2_IN_CAP_DV_TIMINGS;
1310                 if (dev->edid_blocks == 0 ||
1311                     dev->dv_timings_signal_mode == NO_SIGNAL)
1312                         inp->status |= V4L2_IN_ST_NO_SIGNAL;
1313                 else if (dev->dv_timings_signal_mode == NO_LOCK ||
1314                          dev->dv_timings_signal_mode == OUT_OF_RANGE)
1315                         inp->status |= V4L2_IN_ST_NO_H_LOCK;
1316                 break;
1317         }
1318         if (dev->sensor_hflip)
1319                 inp->status |= V4L2_IN_ST_HFLIP;
1320         if (dev->sensor_vflip)
1321                 inp->status |= V4L2_IN_ST_VFLIP;
1322         if (dev->input == inp->index && vivid_is_sdtv_cap(dev)) {
1323                 if (dev->std_signal_mode == NO_SIGNAL) {
1324                         inp->status |= V4L2_IN_ST_NO_SIGNAL;
1325                 } else if (dev->std_signal_mode == NO_LOCK) {
1326                         inp->status |= V4L2_IN_ST_NO_H_LOCK;
1327                 } else if (vivid_is_tv_cap(dev)) {
1328                         switch (tpg_g_quality(&dev->tpg)) {
1329                         case TPG_QUAL_GRAY:
1330                                 inp->status |= V4L2_IN_ST_COLOR_KILL;
1331                                 break;
1332                         case TPG_QUAL_NOISE:
1333                                 inp->status |= V4L2_IN_ST_NO_H_LOCK;
1334                                 break;
1335                         default:
1336                                 break;
1337                         }
1338                 }
1339         }
1340         return 0;
1341 }
1342
1343 int vidioc_g_input(struct file *file, void *priv, unsigned *i)
1344 {
1345         struct vivid_dev *dev = video_drvdata(file);
1346
1347         *i = dev->input;
1348         return 0;
1349 }
1350
1351 int vidioc_s_input(struct file *file, void *priv, unsigned i)
1352 {
1353         struct vivid_dev *dev = video_drvdata(file);
1354         struct v4l2_bt_timings *bt = &dev->dv_timings_cap.bt;
1355         unsigned brightness;
1356
1357         if (i >= dev->num_inputs)
1358                 return -EINVAL;
1359
1360         if (i == dev->input)
1361                 return 0;
1362
1363         if (vb2_is_busy(&dev->vb_vid_cap_q) || vb2_is_busy(&dev->vb_vbi_cap_q))
1364                 return -EBUSY;
1365
1366         dev->input = i;
1367         dev->vid_cap_dev.tvnorms = 0;
1368         if (dev->input_type[i] == TV || dev->input_type[i] == SVID) {
1369                 dev->tv_audio_input = (dev->input_type[i] == TV) ? 0 : 1;
1370                 dev->vid_cap_dev.tvnorms = V4L2_STD_ALL;
1371         }
1372         dev->vbi_cap_dev.tvnorms = dev->vid_cap_dev.tvnorms;
1373         vivid_update_format_cap(dev, false);
1374
1375         if (dev->colorspace) {
1376                 switch (dev->input_type[i]) {
1377                 case WEBCAM:
1378                         v4l2_ctrl_s_ctrl(dev->colorspace, VIVID_CS_SRGB);
1379                         break;
1380                 case TV:
1381                 case SVID:
1382                         v4l2_ctrl_s_ctrl(dev->colorspace, VIVID_CS_170M);
1383                         break;
1384                 case HDMI:
1385                         if (bt->flags & V4L2_DV_FL_IS_CE_VIDEO) {
1386                                 if (dev->src_rect.width == 720 && dev->src_rect.height <= 576)
1387                                         v4l2_ctrl_s_ctrl(dev->colorspace, VIVID_CS_170M);
1388                                 else
1389                                         v4l2_ctrl_s_ctrl(dev->colorspace, VIVID_CS_709);
1390                         } else {
1391                                 v4l2_ctrl_s_ctrl(dev->colorspace, VIVID_CS_SRGB);
1392                         }
1393                         break;
1394                 }
1395         }
1396
1397         /*
1398          * Modify the brightness range depending on the input.
1399          * This makes it easy to use vivid to test if applications can
1400          * handle control range modifications and is also how this is
1401          * typically used in practice as different inputs may be hooked
1402          * up to different receivers with different control ranges.
1403          */
1404         brightness = 128 * i + dev->input_brightness[i];
1405         v4l2_ctrl_modify_range(dev->brightness,
1406                         128 * i, 255 + 128 * i, 1, 128 + 128 * i);
1407         v4l2_ctrl_s_ctrl(dev->brightness, brightness);
1408         return 0;
1409 }
1410
1411 int vidioc_enumaudio(struct file *file, void *fh, struct v4l2_audio *vin)
1412 {
1413         if (vin->index >= ARRAY_SIZE(vivid_audio_inputs))
1414                 return -EINVAL;
1415         *vin = vivid_audio_inputs[vin->index];
1416         return 0;
1417 }
1418
1419 int vidioc_g_audio(struct file *file, void *fh, struct v4l2_audio *vin)
1420 {
1421         struct vivid_dev *dev = video_drvdata(file);
1422
1423         if (!vivid_is_sdtv_cap(dev))
1424                 return -EINVAL;
1425         *vin = vivid_audio_inputs[dev->tv_audio_input];
1426         return 0;
1427 }
1428
1429 int vidioc_s_audio(struct file *file, void *fh, const struct v4l2_audio *vin)
1430 {
1431         struct vivid_dev *dev = video_drvdata(file);
1432
1433         if (!vivid_is_sdtv_cap(dev))
1434                 return -EINVAL;
1435         if (vin->index >= ARRAY_SIZE(vivid_audio_inputs))
1436                 return -EINVAL;
1437         dev->tv_audio_input = vin->index;
1438         return 0;
1439 }
1440
1441 int vivid_video_g_frequency(struct file *file, void *fh, struct v4l2_frequency *vf)
1442 {
1443         struct vivid_dev *dev = video_drvdata(file);
1444
1445         if (vf->tuner != 0)
1446                 return -EINVAL;
1447         vf->frequency = dev->tv_freq;
1448         return 0;
1449 }
1450
1451 int vivid_video_s_frequency(struct file *file, void *fh, const struct v4l2_frequency *vf)
1452 {
1453         struct vivid_dev *dev = video_drvdata(file);
1454
1455         if (vf->tuner != 0)
1456                 return -EINVAL;
1457         dev->tv_freq = clamp_t(unsigned, vf->frequency, MIN_TV_FREQ, MAX_TV_FREQ);
1458         if (vivid_is_tv_cap(dev))
1459                 vivid_update_quality(dev);
1460         return 0;
1461 }
1462
1463 int vivid_video_s_tuner(struct file *file, void *fh, const struct v4l2_tuner *vt)
1464 {
1465         struct vivid_dev *dev = video_drvdata(file);
1466
1467         if (vt->index != 0)
1468                 return -EINVAL;
1469         if (vt->audmode > V4L2_TUNER_MODE_LANG1_LANG2)
1470                 return -EINVAL;
1471         dev->tv_audmode = vt->audmode;
1472         return 0;
1473 }
1474
1475 int vivid_video_g_tuner(struct file *file, void *fh, struct v4l2_tuner *vt)
1476 {
1477         struct vivid_dev *dev = video_drvdata(file);
1478         enum tpg_quality qual;
1479
1480         if (vt->index != 0)
1481                 return -EINVAL;
1482
1483         vt->capability = V4L2_TUNER_CAP_NORM | V4L2_TUNER_CAP_STEREO |
1484                          V4L2_TUNER_CAP_LANG1 | V4L2_TUNER_CAP_LANG2;
1485         vt->audmode = dev->tv_audmode;
1486         vt->rangelow = MIN_TV_FREQ;
1487         vt->rangehigh = MAX_TV_FREQ;
1488         qual = vivid_get_quality(dev, &vt->afc);
1489         if (qual == TPG_QUAL_COLOR)
1490                 vt->signal = 0xffff;
1491         else if (qual == TPG_QUAL_GRAY)
1492                 vt->signal = 0x8000;
1493         else
1494                 vt->signal = 0;
1495         if (qual == TPG_QUAL_NOISE) {
1496                 vt->rxsubchans = 0;
1497         } else if (qual == TPG_QUAL_GRAY) {
1498                 vt->rxsubchans = V4L2_TUNER_SUB_MONO;
1499         } else {
1500                 unsigned channel_nr = dev->tv_freq / (6 * 16);
1501                 unsigned options = (dev->std_cap & V4L2_STD_NTSC_M) ? 4 : 3;
1502
1503                 switch (channel_nr % options) {
1504                 case 0:
1505                         vt->rxsubchans = V4L2_TUNER_SUB_MONO;
1506                         break;
1507                 case 1:
1508                         vt->rxsubchans = V4L2_TUNER_SUB_STEREO;
1509                         break;
1510                 case 2:
1511                         if (dev->std_cap & V4L2_STD_NTSC_M)
1512                                 vt->rxsubchans = V4L2_TUNER_SUB_MONO | V4L2_TUNER_SUB_SAP;
1513                         else
1514                                 vt->rxsubchans = V4L2_TUNER_SUB_LANG1 | V4L2_TUNER_SUB_LANG2;
1515                         break;
1516                 case 3:
1517                         vt->rxsubchans = V4L2_TUNER_SUB_STEREO | V4L2_TUNER_SUB_SAP;
1518                         break;
1519                 }
1520         }
1521         strscpy(vt->name, "TV Tuner", sizeof(vt->name));
1522         return 0;
1523 }
1524
1525 /* Must remain in sync with the vivid_ctrl_standard_strings array */
1526 const v4l2_std_id vivid_standard[] = {
1527         V4L2_STD_NTSC_M,
1528         V4L2_STD_NTSC_M_JP,
1529         V4L2_STD_NTSC_M_KR,
1530         V4L2_STD_NTSC_443,
1531         V4L2_STD_PAL_BG | V4L2_STD_PAL_H,
1532         V4L2_STD_PAL_I,
1533         V4L2_STD_PAL_DK,
1534         V4L2_STD_PAL_M,
1535         V4L2_STD_PAL_N,
1536         V4L2_STD_PAL_Nc,
1537         V4L2_STD_PAL_60,
1538         V4L2_STD_SECAM_B | V4L2_STD_SECAM_G | V4L2_STD_SECAM_H,
1539         V4L2_STD_SECAM_DK,
1540         V4L2_STD_SECAM_L,
1541         V4L2_STD_SECAM_LC,
1542         V4L2_STD_UNKNOWN
1543 };
1544
1545 /* Must remain in sync with the vivid_standard array */
1546 const char * const vivid_ctrl_standard_strings[] = {
1547         "NTSC-M",
1548         "NTSC-M-JP",
1549         "NTSC-M-KR",
1550         "NTSC-443",
1551         "PAL-BGH",
1552         "PAL-I",
1553         "PAL-DK",
1554         "PAL-M",
1555         "PAL-N",
1556         "PAL-Nc",
1557         "PAL-60",
1558         "SECAM-BGH",
1559         "SECAM-DK",
1560         "SECAM-L",
1561         "SECAM-Lc",
1562         NULL,
1563 };
1564
1565 int vidioc_querystd(struct file *file, void *priv, v4l2_std_id *id)
1566 {
1567         struct vivid_dev *dev = video_drvdata(file);
1568
1569         if (!vivid_is_sdtv_cap(dev))
1570                 return -ENODATA;
1571         if (dev->std_signal_mode == NO_SIGNAL ||
1572             dev->std_signal_mode == NO_LOCK) {
1573                 *id = V4L2_STD_UNKNOWN;
1574                 return 0;
1575         }
1576         if (vivid_is_tv_cap(dev) && tpg_g_quality(&dev->tpg) == TPG_QUAL_NOISE) {
1577                 *id = V4L2_STD_UNKNOWN;
1578         } else if (dev->std_signal_mode == CURRENT_STD) {
1579                 *id = dev->std_cap;
1580         } else if (dev->std_signal_mode == SELECTED_STD) {
1581                 *id = dev->query_std;
1582         } else {
1583                 *id = vivid_standard[dev->query_std_last];
1584                 dev->query_std_last = (dev->query_std_last + 1) % ARRAY_SIZE(vivid_standard);
1585         }
1586
1587         return 0;
1588 }
1589
1590 int vivid_vid_cap_s_std(struct file *file, void *priv, v4l2_std_id id)
1591 {
1592         struct vivid_dev *dev = video_drvdata(file);
1593
1594         if (!vivid_is_sdtv_cap(dev))
1595                 return -ENODATA;
1596         if (dev->std_cap == id)
1597                 return 0;
1598         if (vb2_is_busy(&dev->vb_vid_cap_q) || vb2_is_busy(&dev->vb_vbi_cap_q))
1599                 return -EBUSY;
1600         dev->std_cap = id;
1601         vivid_update_format_cap(dev, false);
1602         return 0;
1603 }
1604
1605 static void find_aspect_ratio(u32 width, u32 height,
1606                                u32 *num, u32 *denom)
1607 {
1608         if (!(height % 3) && ((height * 4 / 3) == width)) {
1609                 *num = 4;
1610                 *denom = 3;
1611         } else if (!(height % 9) && ((height * 16 / 9) == width)) {
1612                 *num = 16;
1613                 *denom = 9;
1614         } else if (!(height % 10) && ((height * 16 / 10) == width)) {
1615                 *num = 16;
1616                 *denom = 10;
1617         } else if (!(height % 4) && ((height * 5 / 4) == width)) {
1618                 *num = 5;
1619                 *denom = 4;
1620         } else if (!(height % 9) && ((height * 15 / 9) == width)) {
1621                 *num = 15;
1622                 *denom = 9;
1623         } else { /* default to 16:9 */
1624                 *num = 16;
1625                 *denom = 9;
1626         }
1627 }
1628
1629 static bool valid_cvt_gtf_timings(struct v4l2_dv_timings *timings)
1630 {
1631         struct v4l2_bt_timings *bt = &timings->bt;
1632         u32 total_h_pixel;
1633         u32 total_v_lines;
1634         u32 h_freq;
1635
1636         if (!v4l2_valid_dv_timings(timings, &vivid_dv_timings_cap,
1637                                 NULL, NULL))
1638                 return false;
1639
1640         total_h_pixel = V4L2_DV_BT_FRAME_WIDTH(bt);
1641         total_v_lines = V4L2_DV_BT_FRAME_HEIGHT(bt);
1642
1643         h_freq = (u32)bt->pixelclock / total_h_pixel;
1644
1645         if (bt->standards == 0 || (bt->standards & V4L2_DV_BT_STD_CVT)) {
1646                 if (v4l2_detect_cvt(total_v_lines, h_freq, bt->vsync, bt->width,
1647                                     bt->polarities, bt->interlaced, timings))
1648                         return true;
1649         }
1650
1651         if (bt->standards == 0 || (bt->standards & V4L2_DV_BT_STD_GTF)) {
1652                 struct v4l2_fract aspect_ratio;
1653
1654                 find_aspect_ratio(bt->width, bt->height,
1655                                   &aspect_ratio.numerator,
1656                                   &aspect_ratio.denominator);
1657                 if (v4l2_detect_gtf(total_v_lines, h_freq, bt->vsync,
1658                                     bt->polarities, bt->interlaced,
1659                                     aspect_ratio, timings))
1660                         return true;
1661         }
1662         return false;
1663 }
1664
1665 int vivid_vid_cap_s_dv_timings(struct file *file, void *_fh,
1666                                     struct v4l2_dv_timings *timings)
1667 {
1668         struct vivid_dev *dev = video_drvdata(file);
1669
1670         if (!vivid_is_hdmi_cap(dev))
1671                 return -ENODATA;
1672         if (!v4l2_find_dv_timings_cap(timings, &vivid_dv_timings_cap,
1673                                       0, NULL, NULL) &&
1674             !valid_cvt_gtf_timings(timings))
1675                 return -EINVAL;
1676
1677         if (v4l2_match_dv_timings(timings, &dev->dv_timings_cap, 0, false))
1678                 return 0;
1679         if (vb2_is_busy(&dev->vb_vid_cap_q))
1680                 return -EBUSY;
1681
1682         dev->dv_timings_cap = *timings;
1683         vivid_update_format_cap(dev, false);
1684         return 0;
1685 }
1686
1687 int vidioc_query_dv_timings(struct file *file, void *_fh,
1688                                     struct v4l2_dv_timings *timings)
1689 {
1690         struct vivid_dev *dev = video_drvdata(file);
1691
1692         if (!vivid_is_hdmi_cap(dev))
1693                 return -ENODATA;
1694         if (dev->dv_timings_signal_mode == NO_SIGNAL ||
1695             dev->edid_blocks == 0)
1696                 return -ENOLINK;
1697         if (dev->dv_timings_signal_mode == NO_LOCK)
1698                 return -ENOLCK;
1699         if (dev->dv_timings_signal_mode == OUT_OF_RANGE) {
1700                 timings->bt.pixelclock = vivid_dv_timings_cap.bt.max_pixelclock * 2;
1701                 return -ERANGE;
1702         }
1703         if (dev->dv_timings_signal_mode == CURRENT_DV_TIMINGS) {
1704                 *timings = dev->dv_timings_cap;
1705         } else if (dev->dv_timings_signal_mode == SELECTED_DV_TIMINGS) {
1706                 *timings = v4l2_dv_timings_presets[dev->query_dv_timings];
1707         } else {
1708                 *timings = v4l2_dv_timings_presets[dev->query_dv_timings_last];
1709                 dev->query_dv_timings_last = (dev->query_dv_timings_last + 1) %
1710                                                 dev->query_dv_timings_size;
1711         }
1712         return 0;
1713 }
1714
1715 int vidioc_s_edid(struct file *file, void *_fh,
1716                          struct v4l2_edid *edid)
1717 {
1718         struct vivid_dev *dev = video_drvdata(file);
1719         u16 phys_addr;
1720         unsigned int i;
1721         int ret;
1722
1723         memset(edid->reserved, 0, sizeof(edid->reserved));
1724         if (edid->pad >= dev->num_inputs)
1725                 return -EINVAL;
1726         if (dev->input_type[edid->pad] != HDMI || edid->start_block)
1727                 return -EINVAL;
1728         if (edid->blocks == 0) {
1729                 dev->edid_blocks = 0;
1730                 phys_addr = CEC_PHYS_ADDR_INVALID;
1731                 goto set_phys_addr;
1732         }
1733         if (edid->blocks > dev->edid_max_blocks) {
1734                 edid->blocks = dev->edid_max_blocks;
1735                 return -E2BIG;
1736         }
1737         phys_addr = cec_get_edid_phys_addr(edid->edid, edid->blocks * 128, NULL);
1738         ret = v4l2_phys_addr_validate(phys_addr, &phys_addr, NULL);
1739         if (ret)
1740                 return ret;
1741
1742         if (vb2_is_busy(&dev->vb_vid_cap_q))
1743                 return -EBUSY;
1744
1745         dev->edid_blocks = edid->blocks;
1746         memcpy(dev->edid, edid->edid, edid->blocks * 128);
1747
1748 set_phys_addr:
1749         /* TODO: a proper hotplug detect cycle should be emulated here */
1750         cec_s_phys_addr(dev->cec_rx_adap, phys_addr, false);
1751
1752         for (i = 0; i < MAX_OUTPUTS && dev->cec_tx_adap[i]; i++)
1753                 cec_s_phys_addr(dev->cec_tx_adap[i],
1754                                 v4l2_phys_addr_for_input(phys_addr, i + 1),
1755                                 false);
1756         return 0;
1757 }
1758
1759 int vidioc_enum_framesizes(struct file *file, void *fh,
1760                                          struct v4l2_frmsizeenum *fsize)
1761 {
1762         struct vivid_dev *dev = video_drvdata(file);
1763
1764         if (!vivid_is_webcam(dev) && !dev->has_scaler_cap)
1765                 return -EINVAL;
1766         if (vivid_get_format(dev, fsize->pixel_format) == NULL)
1767                 return -EINVAL;
1768         if (vivid_is_webcam(dev)) {
1769                 if (fsize->index >= ARRAY_SIZE(webcam_sizes))
1770                         return -EINVAL;
1771                 fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
1772                 fsize->discrete = webcam_sizes[fsize->index];
1773                 return 0;
1774         }
1775         if (fsize->index)
1776                 return -EINVAL;
1777         fsize->type = V4L2_FRMSIZE_TYPE_STEPWISE;
1778         fsize->stepwise.min_width = MIN_WIDTH;
1779         fsize->stepwise.max_width = MAX_WIDTH * MAX_ZOOM;
1780         fsize->stepwise.step_width = 2;
1781         fsize->stepwise.min_height = MIN_HEIGHT;
1782         fsize->stepwise.max_height = MAX_HEIGHT * MAX_ZOOM;
1783         fsize->stepwise.step_height = 2;
1784         return 0;
1785 }
1786
1787 /* timeperframe is arbitrary and continuous */
1788 int vidioc_enum_frameintervals(struct file *file, void *priv,
1789                                              struct v4l2_frmivalenum *fival)
1790 {
1791         struct vivid_dev *dev = video_drvdata(file);
1792         const struct vivid_fmt *fmt;
1793         int i;
1794
1795         fmt = vivid_get_format(dev, fival->pixel_format);
1796         if (!fmt)
1797                 return -EINVAL;
1798
1799         if (!vivid_is_webcam(dev)) {
1800                 if (fival->index)
1801                         return -EINVAL;
1802                 if (fival->width < MIN_WIDTH || fival->width > MAX_WIDTH * MAX_ZOOM)
1803                         return -EINVAL;
1804                 if (fival->height < MIN_HEIGHT || fival->height > MAX_HEIGHT * MAX_ZOOM)
1805                         return -EINVAL;
1806                 fival->type = V4L2_FRMIVAL_TYPE_DISCRETE;
1807                 fival->discrete = dev->timeperframe_vid_cap;
1808                 return 0;
1809         }
1810
1811         for (i = 0; i < ARRAY_SIZE(webcam_sizes); i++)
1812                 if (fival->width == webcam_sizes[i].width &&
1813                     fival->height == webcam_sizes[i].height)
1814                         break;
1815         if (i == ARRAY_SIZE(webcam_sizes))
1816                 return -EINVAL;
1817         if (fival->index >= 2 * (VIVID_WEBCAM_SIZES - i))
1818                 return -EINVAL;
1819         fival->type = V4L2_FRMIVAL_TYPE_DISCRETE;
1820         fival->discrete = webcam_intervals[fival->index];
1821         return 0;
1822 }
1823
1824 int vivid_vid_cap_g_parm(struct file *file, void *priv,
1825                           struct v4l2_streamparm *parm)
1826 {
1827         struct vivid_dev *dev = video_drvdata(file);
1828
1829         if (parm->type != (dev->multiplanar ?
1830                            V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE :
1831                            V4L2_BUF_TYPE_VIDEO_CAPTURE))
1832                 return -EINVAL;
1833
1834         parm->parm.capture.capability   = V4L2_CAP_TIMEPERFRAME;
1835         parm->parm.capture.timeperframe = dev->timeperframe_vid_cap;
1836         parm->parm.capture.readbuffers  = 1;
1837         return 0;
1838 }
1839
1840 #define FRACT_CMP(a, OP, b)     \
1841         ((u64)(a).numerator * (b).denominator  OP  (u64)(b).numerator * (a).denominator)
1842
1843 int vivid_vid_cap_s_parm(struct file *file, void *priv,
1844                           struct v4l2_streamparm *parm)
1845 {
1846         struct vivid_dev *dev = video_drvdata(file);
1847         unsigned ival_sz = 2 * (VIVID_WEBCAM_SIZES - dev->webcam_size_idx);
1848         struct v4l2_fract tpf;
1849         unsigned i;
1850
1851         if (parm->type != (dev->multiplanar ?
1852                            V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE :
1853                            V4L2_BUF_TYPE_VIDEO_CAPTURE))
1854                 return -EINVAL;
1855         if (!vivid_is_webcam(dev))
1856                 return vivid_vid_cap_g_parm(file, priv, parm);
1857
1858         tpf = parm->parm.capture.timeperframe;
1859
1860         if (tpf.denominator == 0)
1861                 tpf = webcam_intervals[ival_sz - 1];
1862         for (i = 0; i < ival_sz; i++)
1863                 if (FRACT_CMP(tpf, >=, webcam_intervals[i]))
1864                         break;
1865         if (i == ival_sz)
1866                 i = ival_sz - 1;
1867         dev->webcam_ival_idx = i;
1868         tpf = webcam_intervals[dev->webcam_ival_idx];
1869         tpf = FRACT_CMP(tpf, <, tpf_min) ? tpf_min : tpf;
1870         tpf = FRACT_CMP(tpf, >, tpf_max) ? tpf_max : tpf;
1871
1872         /* resync the thread's timings */
1873         dev->cap_seq_resync = true;
1874         dev->timeperframe_vid_cap = tpf;
1875         parm->parm.capture.capability   = V4L2_CAP_TIMEPERFRAME;
1876         parm->parm.capture.timeperframe = tpf;
1877         parm->parm.capture.readbuffers  = 1;
1878         return 0;
1879 }