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