[media] vivid: add the kthread code that controls the video rate
[firefly-linux-kernel-4.4.55.git] / drivers / media / platform / vivid / vivid-kthread-cap.c
1 /*
2  * vivid-kthread-cap.h - video/vbi capture thread 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/module.h>
21 #include <linux/errno.h>
22 #include <linux/kernel.h>
23 #include <linux/init.h>
24 #include <linux/sched.h>
25 #include <linux/slab.h>
26 #include <linux/font.h>
27 #include <linux/mutex.h>
28 #include <linux/videodev2.h>
29 #include <linux/kthread.h>
30 #include <linux/freezer.h>
31 #include <linux/random.h>
32 #include <linux/v4l2-dv-timings.h>
33 #include <asm/div64.h>
34 #include <media/videobuf2-vmalloc.h>
35 #include <media/v4l2-dv-timings.h>
36 #include <media/v4l2-ioctl.h>
37 #include <media/v4l2-fh.h>
38 #include <media/v4l2-event.h>
39
40 #include "vivid-core.h"
41 #include "vivid-vid-common.h"
42 #include "vivid-vid-cap.h"
43 #include "vivid-vid-out.h"
44 #include "vivid-radio-common.h"
45 #include "vivid-radio-rx.h"
46 #include "vivid-radio-tx.h"
47 #include "vivid-sdr-cap.h"
48 #include "vivid-vbi-cap.h"
49 #include "vivid-vbi-out.h"
50 #include "vivid-osd.h"
51 #include "vivid-ctrls.h"
52
53 static inline v4l2_std_id vivid_get_std_cap(const struct vivid_dev *dev)
54 {
55         if (vivid_is_sdtv_cap(dev))
56                 return dev->std_cap;
57         return 0;
58 }
59
60 static void copy_pix(struct vivid_dev *dev, int win_y, int win_x,
61                         u16 *cap, const u16 *osd)
62 {
63         u16 out;
64         int left = dev->overlay_out_left;
65         int top = dev->overlay_out_top;
66         int fb_x = win_x + left;
67         int fb_y = win_y + top;
68         int i;
69
70         out = *cap;
71         *cap = *osd;
72         if (dev->bitmap_out) {
73                 const u8 *p = dev->bitmap_out;
74                 unsigned stride = (dev->compose_out.width + 7) / 8;
75
76                 win_x -= dev->compose_out.left;
77                 win_y -= dev->compose_out.top;
78                 if (!(p[stride * win_y + win_x / 8] & (1 << (win_x & 7))))
79                         return;
80         }
81
82         for (i = 0; i < dev->clipcount_out; i++) {
83                 struct v4l2_rect *r = &dev->clips_out[i].c;
84
85                 if (fb_y >= r->top && fb_y < r->top + r->height &&
86                     fb_x >= r->left && fb_x < r->left + r->width)
87                         return;
88         }
89         if ((dev->fbuf_out_flags & V4L2_FBUF_FLAG_CHROMAKEY) &&
90             *osd != dev->chromakey_out)
91                 return;
92         if ((dev->fbuf_out_flags & V4L2_FBUF_FLAG_SRC_CHROMAKEY) &&
93             out == dev->chromakey_out)
94                 return;
95         if (dev->fmt_cap->alpha_mask) {
96                 if ((dev->fbuf_out_flags & V4L2_FBUF_FLAG_GLOBAL_ALPHA) &&
97                     dev->global_alpha_out)
98                         return;
99                 if ((dev->fbuf_out_flags & V4L2_FBUF_FLAG_LOCAL_ALPHA) &&
100                     *cap & dev->fmt_cap->alpha_mask)
101                         return;
102                 if ((dev->fbuf_out_flags & V4L2_FBUF_FLAG_LOCAL_INV_ALPHA) &&
103                     !(*cap & dev->fmt_cap->alpha_mask))
104                         return;
105         }
106         *cap = out;
107 }
108
109 static void blend_line(struct vivid_dev *dev, unsigned y_offset, unsigned x_offset,
110                 u8 *vcapbuf, const u8 *vosdbuf,
111                 unsigned width, unsigned pixsize)
112 {
113         unsigned x;
114
115         for (x = 0; x < width; x++, vcapbuf += pixsize, vosdbuf += pixsize) {
116                 copy_pix(dev, y_offset, x_offset + x,
117                          (u16 *)vcapbuf, (const u16 *)vosdbuf);
118         }
119 }
120
121 static void scale_line(const u8 *src, u8 *dst, unsigned srcw, unsigned dstw, unsigned twopixsize)
122 {
123         /* Coarse scaling with Bresenham */
124         unsigned int_part;
125         unsigned fract_part;
126         unsigned src_x = 0;
127         unsigned error = 0;
128         unsigned x;
129
130         /*
131          * We always combine two pixels to prevent color bleed in the packed
132          * yuv case.
133          */
134         srcw /= 2;
135         dstw /= 2;
136         int_part = srcw / dstw;
137         fract_part = srcw % dstw;
138         for (x = 0; x < dstw; x++, dst += twopixsize) {
139                 memcpy(dst, src + src_x * twopixsize, twopixsize);
140                 src_x += int_part;
141                 error += fract_part;
142                 if (error >= dstw) {
143                         error -= dstw;
144                         src_x++;
145                 }
146         }
147 }
148
149 /*
150  * Precalculate the rectangles needed to perform video looping:
151  *
152  * The nominal pipeline is that the video output buffer is cropped by
153  * crop_out, scaled to compose_out, overlaid with the output overlay,
154  * cropped on the capture side by crop_cap and scaled again to the video
155  * capture buffer using compose_cap.
156  *
157  * To keep things efficient we calculate the intersection of compose_out
158  * and crop_cap (since that's the only part of the video that will
159  * actually end up in the capture buffer), determine which part of the
160  * video output buffer that is and which part of the video capture buffer
161  * so we can scale the video straight from the output buffer to the capture
162  * buffer without any intermediate steps.
163  *
164  * If we need to deal with an output overlay, then there is no choice and
165  * that intermediate step still has to be taken. For the output overlay
166  * support we calculate the intersection of the framebuffer and the overlay
167  * window (which may be partially or wholly outside of the framebuffer
168  * itself) and the intersection of that with loop_vid_copy (i.e. the part of
169  * the actual looped video that will be overlaid). The result is calculated
170  * both in framebuffer coordinates (loop_fb_copy) and compose_out coordinates
171  * (loop_vid_overlay). Finally calculate the part of the capture buffer that
172  * will receive that overlaid video.
173  */
174 static void vivid_precalc_copy_rects(struct vivid_dev *dev)
175 {
176         /* Framebuffer rectangle */
177         struct v4l2_rect r_fb = {
178                 0, 0, dev->display_width, dev->display_height
179         };
180         /* Overlay window rectangle in framebuffer coordinates */
181         struct v4l2_rect r_overlay = {
182                 dev->overlay_out_left, dev->overlay_out_top,
183                 dev->compose_out.width, dev->compose_out.height
184         };
185
186         dev->loop_vid_copy = rect_intersect(&dev->crop_cap, &dev->compose_out);
187
188         dev->loop_vid_out = dev->loop_vid_copy;
189         rect_scale(&dev->loop_vid_out, &dev->compose_out, &dev->crop_out);
190         dev->loop_vid_out.left += dev->crop_out.left;
191         dev->loop_vid_out.top += dev->crop_out.top;
192
193         dev->loop_vid_cap = dev->loop_vid_copy;
194         rect_scale(&dev->loop_vid_cap, &dev->crop_cap, &dev->compose_cap);
195
196         dprintk(dev, 1,
197                 "loop_vid_copy: %dx%d@%dx%d loop_vid_out: %dx%d@%dx%d loop_vid_cap: %dx%d@%dx%d\n",
198                 dev->loop_vid_copy.width, dev->loop_vid_copy.height,
199                 dev->loop_vid_copy.left, dev->loop_vid_copy.top,
200                 dev->loop_vid_out.width, dev->loop_vid_out.height,
201                 dev->loop_vid_out.left, dev->loop_vid_out.top,
202                 dev->loop_vid_cap.width, dev->loop_vid_cap.height,
203                 dev->loop_vid_cap.left, dev->loop_vid_cap.top);
204
205         r_overlay = rect_intersect(&r_fb, &r_overlay);
206
207         /* shift r_overlay to the same origin as compose_out */
208         r_overlay.left += dev->compose_out.left - dev->overlay_out_left;
209         r_overlay.top += dev->compose_out.top - dev->overlay_out_top;
210
211         dev->loop_vid_overlay = rect_intersect(&r_overlay, &dev->loop_vid_copy);
212         dev->loop_fb_copy = dev->loop_vid_overlay;
213
214         /* shift dev->loop_fb_copy back again to the fb origin */
215         dev->loop_fb_copy.left -= dev->compose_out.left - dev->overlay_out_left;
216         dev->loop_fb_copy.top -= dev->compose_out.top - dev->overlay_out_top;
217
218         dev->loop_vid_overlay_cap = dev->loop_vid_overlay;
219         rect_scale(&dev->loop_vid_overlay_cap, &dev->crop_cap, &dev->compose_cap);
220
221         dprintk(dev, 1,
222                 "loop_fb_copy: %dx%d@%dx%d loop_vid_overlay: %dx%d@%dx%d loop_vid_overlay_cap: %dx%d@%dx%d\n",
223                 dev->loop_fb_copy.width, dev->loop_fb_copy.height,
224                 dev->loop_fb_copy.left, dev->loop_fb_copy.top,
225                 dev->loop_vid_overlay.width, dev->loop_vid_overlay.height,
226                 dev->loop_vid_overlay.left, dev->loop_vid_overlay.top,
227                 dev->loop_vid_overlay_cap.width, dev->loop_vid_overlay_cap.height,
228                 dev->loop_vid_overlay_cap.left, dev->loop_vid_overlay_cap.top);
229 }
230
231 static int vivid_copy_buffer(struct vivid_dev *dev, unsigned p, u8 *vcapbuf,
232                 struct vivid_buffer *vid_cap_buf)
233 {
234         bool blank = dev->must_blank[vid_cap_buf->vb.v4l2_buf.index];
235         struct tpg_data *tpg = &dev->tpg;
236         struct vivid_buffer *vid_out_buf = NULL;
237         unsigned pixsize = tpg_g_twopixelsize(tpg, p) / 2;
238         unsigned img_width = dev->compose_cap.width;
239         unsigned img_height = dev->compose_cap.height;
240         unsigned stride_cap = tpg->bytesperline[p];
241         unsigned stride_out = dev->bytesperline_out[p];
242         unsigned stride_osd = dev->display_byte_stride;
243         unsigned hmax = (img_height * tpg->perc_fill) / 100;
244         u8 *voutbuf;
245         u8 *vosdbuf = NULL;
246         unsigned y;
247         bool blend = dev->bitmap_out || dev->clipcount_out || dev->fbuf_out_flags;
248         /* Coarse scaling with Bresenham */
249         unsigned vid_out_int_part;
250         unsigned vid_out_fract_part;
251         unsigned vid_out_y = 0;
252         unsigned vid_out_error = 0;
253         unsigned vid_overlay_int_part = 0;
254         unsigned vid_overlay_fract_part = 0;
255         unsigned vid_overlay_y = 0;
256         unsigned vid_overlay_error = 0;
257         unsigned vid_cap_right;
258         bool quick;
259
260         vid_out_int_part = dev->loop_vid_out.height / dev->loop_vid_cap.height;
261         vid_out_fract_part = dev->loop_vid_out.height % dev->loop_vid_cap.height;
262
263         if (!list_empty(&dev->vid_out_active))
264                 vid_out_buf = list_entry(dev->vid_out_active.next,
265                                          struct vivid_buffer, list);
266         if (vid_out_buf == NULL)
267                 return -ENODATA;
268
269         vid_cap_buf->vb.v4l2_buf.field = vid_out_buf->vb.v4l2_buf.field;
270
271         voutbuf = vb2_plane_vaddr(&vid_out_buf->vb, p) +
272                                   vid_out_buf->vb.v4l2_planes[p].data_offset;
273         voutbuf += dev->loop_vid_out.left * pixsize + dev->loop_vid_out.top * stride_out;
274         vcapbuf += dev->compose_cap.left * pixsize + dev->compose_cap.top * stride_cap;
275
276         if (dev->loop_vid_copy.width == 0 || dev->loop_vid_copy.height == 0) {
277                 /*
278                  * If there is nothing to copy, then just fill the capture window
279                  * with black.
280                  */
281                 for (y = 0; y < hmax; y++, vcapbuf += stride_cap)
282                         memcpy(vcapbuf, tpg->black_line[p], img_width * pixsize);
283                 return 0;
284         }
285
286         if (dev->overlay_out_enabled &&
287             dev->loop_vid_overlay.width && dev->loop_vid_overlay.height) {
288                 vosdbuf = dev->video_vbase;
289                 vosdbuf += dev->loop_fb_copy.left * pixsize +
290                            dev->loop_fb_copy.top * stride_osd;
291                 vid_overlay_int_part = dev->loop_vid_overlay.height /
292                                        dev->loop_vid_overlay_cap.height;
293                 vid_overlay_fract_part = dev->loop_vid_overlay.height %
294                                          dev->loop_vid_overlay_cap.height;
295         }
296
297         vid_cap_right = dev->loop_vid_cap.left + dev->loop_vid_cap.width;
298         /* quick is true if no video scaling is needed */
299         quick = dev->loop_vid_out.width == dev->loop_vid_cap.width;
300
301         dev->cur_scaled_line = dev->loop_vid_out.height;
302         for (y = 0; y < hmax; y++, vcapbuf += stride_cap) {
303                 /* osdline is true if this line requires overlay blending */
304                 bool osdline = vosdbuf && y >= dev->loop_vid_overlay_cap.top &&
305                           y < dev->loop_vid_overlay_cap.top + dev->loop_vid_overlay_cap.height;
306
307                 /*
308                  * If this line of the capture buffer doesn't get any video, then
309                  * just fill with black.
310                  */
311                 if (y < dev->loop_vid_cap.top ||
312                     y >= dev->loop_vid_cap.top + dev->loop_vid_cap.height) {
313                         memcpy(vcapbuf, tpg->black_line[p], img_width * pixsize);
314                         continue;
315                 }
316
317                 /* fill the left border with black */
318                 if (dev->loop_vid_cap.left)
319                         memcpy(vcapbuf, tpg->black_line[p], dev->loop_vid_cap.left * pixsize);
320
321                 /* fill the right border with black */
322                 if (vid_cap_right < img_width)
323                         memcpy(vcapbuf + vid_cap_right * pixsize,
324                                 tpg->black_line[p], (img_width - vid_cap_right) * pixsize);
325
326                 if (quick && !osdline) {
327                         memcpy(vcapbuf + dev->loop_vid_cap.left * pixsize,
328                                voutbuf + vid_out_y * stride_out,
329                                dev->loop_vid_cap.width * pixsize);
330                         goto update_vid_out_y;
331                 }
332                 if (dev->cur_scaled_line == vid_out_y) {
333                         memcpy(vcapbuf + dev->loop_vid_cap.left * pixsize,
334                                dev->scaled_line,
335                                dev->loop_vid_cap.width * pixsize);
336                         goto update_vid_out_y;
337                 }
338                 if (!osdline) {
339                         scale_line(voutbuf + vid_out_y * stride_out, dev->scaled_line,
340                                 dev->loop_vid_out.width, dev->loop_vid_cap.width,
341                                 tpg_g_twopixelsize(tpg, p));
342                 } else {
343                         /*
344                          * Offset in bytes within loop_vid_copy to the start of the
345                          * loop_vid_overlay rectangle.
346                          */
347                         unsigned offset =
348                                 (dev->loop_vid_overlay.left - dev->loop_vid_copy.left) * pixsize;
349                         u8 *osd = vosdbuf + vid_overlay_y * stride_osd;
350
351                         scale_line(voutbuf + vid_out_y * stride_out, dev->blended_line,
352                                 dev->loop_vid_out.width, dev->loop_vid_copy.width,
353                                 tpg_g_twopixelsize(tpg, p));
354                         if (blend)
355                                 blend_line(dev, vid_overlay_y + dev->loop_vid_overlay.top,
356                                            dev->loop_vid_overlay.left,
357                                            dev->blended_line + offset, osd,
358                                            dev->loop_vid_overlay.width, pixsize);
359                         else
360                                 memcpy(dev->blended_line + offset,
361                                        osd, dev->loop_vid_overlay.width * pixsize);
362                         scale_line(dev->blended_line, dev->scaled_line,
363                                         dev->loop_vid_copy.width, dev->loop_vid_cap.width,
364                                         tpg_g_twopixelsize(tpg, p));
365                 }
366                 dev->cur_scaled_line = vid_out_y;
367                 memcpy(vcapbuf + dev->loop_vid_cap.left * pixsize,
368                        dev->scaled_line,
369                        dev->loop_vid_cap.width * pixsize);
370
371 update_vid_out_y:
372                 if (osdline) {
373                         vid_overlay_y += vid_overlay_int_part;
374                         vid_overlay_error += vid_overlay_fract_part;
375                         if (vid_overlay_error >= dev->loop_vid_overlay_cap.height) {
376                                 vid_overlay_error -= dev->loop_vid_overlay_cap.height;
377                                 vid_overlay_y++;
378                         }
379                 }
380                 vid_out_y += vid_out_int_part;
381                 vid_out_error += vid_out_fract_part;
382                 if (vid_out_error >= dev->loop_vid_cap.height) {
383                         vid_out_error -= dev->loop_vid_cap.height;
384                         vid_out_y++;
385                 }
386         }
387
388         if (!blank)
389                 return 0;
390         for (; y < img_height; y++, vcapbuf += stride_cap)
391                 memcpy(vcapbuf, tpg->contrast_line[p], img_width * pixsize);
392         return 0;
393 }
394
395 static void vivid_fillbuff(struct vivid_dev *dev, struct vivid_buffer *buf)
396 {
397         unsigned factor = V4L2_FIELD_HAS_T_OR_B(dev->field_cap) ? 2 : 1;
398         unsigned line_height = 16 / factor;
399         bool is_tv = vivid_is_sdtv_cap(dev);
400         bool is_60hz = is_tv && (dev->std_cap & V4L2_STD_525_60);
401         unsigned p;
402         int line = 1;
403         u8 *basep[TPG_MAX_PLANES][2];
404         unsigned ms;
405         char str[100];
406         s32 gain;
407         bool is_loop = false;
408
409         if (dev->loop_video && dev->can_loop_video &&
410             ((vivid_is_svid_cap(dev) && !VIVID_INVALID_SIGNAL(dev->std_signal_mode)) ||
411              (vivid_is_hdmi_cap(dev) && !VIVID_INVALID_SIGNAL(dev->dv_timings_signal_mode))))
412                 is_loop = true;
413
414         buf->vb.v4l2_buf.sequence = dev->vid_cap_seq_count;
415         /*
416          * Take the timestamp now if the timestamp source is set to
417          * "Start of Exposure".
418          */
419         if (dev->tstamp_src_is_soe)
420                 v4l2_get_timestamp(&buf->vb.v4l2_buf.timestamp);
421         if (dev->field_cap == V4L2_FIELD_ALTERNATE) {
422                 /*
423                  * 60 Hz standards start with the bottom field, 50 Hz standards
424                  * with the top field. So if the 0-based seq_count is even,
425                  * then the field is TOP for 50 Hz and BOTTOM for 60 Hz
426                  * standards.
427                  */
428                 buf->vb.v4l2_buf.field = ((dev->vid_cap_seq_count & 1) ^ is_60hz) ?
429                         V4L2_FIELD_TOP : V4L2_FIELD_BOTTOM;
430                 /*
431                  * The sequence counter counts frames, not fields. So divide
432                  * by two.
433                  */
434                 buf->vb.v4l2_buf.sequence /= 2;
435         } else {
436                 buf->vb.v4l2_buf.field = dev->field_cap;
437         }
438         tpg_s_field(&dev->tpg, buf->vb.v4l2_buf.field);
439         tpg_s_perc_fill_blank(&dev->tpg, dev->must_blank[buf->vb.v4l2_buf.index]);
440
441         vivid_precalc_copy_rects(dev);
442
443         for (p = 0; p < tpg_g_planes(&dev->tpg); p++) {
444                 void *vbuf = vb2_plane_vaddr(&buf->vb, p);
445
446                 /*
447                  * The first plane of a multiplanar format has a non-zero
448                  * data_offset. This helps testing whether the application
449                  * correctly supports non-zero data offsets.
450                  */
451                 if (dev->fmt_cap->data_offset[p]) {
452                         memset(vbuf, dev->fmt_cap->data_offset[p] & 0xff,
453                                dev->fmt_cap->data_offset[p]);
454                         vbuf += dev->fmt_cap->data_offset[p];
455                 }
456                 tpg_calc_text_basep(&dev->tpg, basep, p, vbuf);
457                 if (!is_loop || vivid_copy_buffer(dev, p, vbuf, buf))
458                         tpg_fillbuffer(&dev->tpg, vivid_get_std_cap(dev), p, vbuf);
459         }
460         dev->must_blank[buf->vb.v4l2_buf.index] = false;
461
462         /* Updates stream time, only update at the start of a new frame. */
463         if (dev->field_cap != V4L2_FIELD_ALTERNATE || (buf->vb.v4l2_buf.sequence & 1) == 0)
464                 dev->ms_vid_cap = jiffies_to_msecs(jiffies - dev->jiffies_vid_cap);
465
466         ms = dev->ms_vid_cap;
467         if (dev->osd_mode <= 1) {
468                 snprintf(str, sizeof(str), " %02d:%02d:%02d:%03d %u%s",
469                                 (ms / (60 * 60 * 1000)) % 24,
470                                 (ms / (60 * 1000)) % 60,
471                                 (ms / 1000) % 60,
472                                 ms % 1000,
473                                 buf->vb.v4l2_buf.sequence,
474                                 (dev->field_cap == V4L2_FIELD_ALTERNATE) ?
475                                         (buf->vb.v4l2_buf.field == V4L2_FIELD_TOP ?
476                                          " top" : " bottom") : "");
477                 tpg_gen_text(&dev->tpg, basep, line++ * line_height, 16, str);
478         }
479         if (dev->osd_mode == 0) {
480                 snprintf(str, sizeof(str), " %dx%d, input %d ",
481                                 dev->src_rect.width, dev->src_rect.height, dev->input);
482                 tpg_gen_text(&dev->tpg, basep, line++ * line_height, 16, str);
483
484                 gain = v4l2_ctrl_g_ctrl(dev->gain);
485                 mutex_lock(dev->ctrl_hdl_user_vid.lock);
486                 snprintf(str, sizeof(str),
487                         " brightness %3d, contrast %3d, saturation %3d, hue %d ",
488                         dev->brightness->cur.val,
489                         dev->contrast->cur.val,
490                         dev->saturation->cur.val,
491                         dev->hue->cur.val);
492                 tpg_gen_text(&dev->tpg, basep, line++ * line_height, 16, str);
493                 snprintf(str, sizeof(str),
494                         " autogain %d, gain %3d, alpha 0x%02x ",
495                         dev->autogain->cur.val, gain, dev->alpha->cur.val);
496                 mutex_unlock(dev->ctrl_hdl_user_vid.lock);
497                 tpg_gen_text(&dev->tpg, basep, line++ * line_height, 16, str);
498                 mutex_lock(dev->ctrl_hdl_user_aud.lock);
499                 snprintf(str, sizeof(str),
500                         " volume %3d, mute %d ",
501                         dev->volume->cur.val, dev->mute->cur.val);
502                 mutex_unlock(dev->ctrl_hdl_user_aud.lock);
503                 tpg_gen_text(&dev->tpg, basep, line++ * line_height, 16, str);
504                 mutex_lock(dev->ctrl_hdl_user_gen.lock);
505                 snprintf(str, sizeof(str), " int32 %d, int64 %lld, bitmask %08x ",
506                         dev->int32->cur.val,
507                         *dev->int64->p_cur.p_s64,
508                         dev->bitmask->cur.val);
509                 tpg_gen_text(&dev->tpg, basep, line++ * line_height, 16, str);
510                 snprintf(str, sizeof(str), " boolean %d, menu %s, string \"%s\" ",
511                         dev->boolean->cur.val,
512                         dev->menu->qmenu[dev->menu->cur.val],
513                         dev->string->p_cur.p_char);
514                 tpg_gen_text(&dev->tpg, basep, line++ * line_height, 16, str);
515                 snprintf(str, sizeof(str), " integer_menu %lld, value %d ",
516                         dev->int_menu->qmenu_int[dev->int_menu->cur.val],
517                         dev->int_menu->cur.val);
518                 mutex_unlock(dev->ctrl_hdl_user_gen.lock);
519                 tpg_gen_text(&dev->tpg, basep, line++ * line_height, 16, str);
520                 if (dev->button_pressed) {
521                         dev->button_pressed--;
522                         snprintf(str, sizeof(str), " button pressed!");
523                         tpg_gen_text(&dev->tpg, basep, line++ * line_height, 16, str);
524                 }
525         }
526
527         /*
528          * If "End of Frame" is specified at the timestamp source, then take
529          * the timestamp now.
530          */
531         if (!dev->tstamp_src_is_soe)
532                 v4l2_get_timestamp(&buf->vb.v4l2_buf.timestamp);
533         buf->vb.v4l2_buf.timestamp.tv_sec += dev->time_wrap_offset;
534 }
535
536 /*
537  * Return true if this pixel coordinate is a valid video pixel.
538  */
539 static bool valid_pix(struct vivid_dev *dev, int win_y, int win_x, int fb_y, int fb_x)
540 {
541         int i;
542
543         if (dev->bitmap_cap) {
544                 /*
545                  * Only if the corresponding bit in the bitmap is set can
546                  * the video pixel be shown. Coordinates are relative to
547                  * the overlay window set by VIDIOC_S_FMT.
548                  */
549                 const u8 *p = dev->bitmap_cap;
550                 unsigned stride = (dev->compose_cap.width + 7) / 8;
551
552                 if (!(p[stride * win_y + win_x / 8] & (1 << (win_x & 7))))
553                         return false;
554         }
555
556         for (i = 0; i < dev->clipcount_cap; i++) {
557                 /*
558                  * Only if the framebuffer coordinate is not in any of the
559                  * clip rectangles will be video pixel be shown.
560                  */
561                 struct v4l2_rect *r = &dev->clips_cap[i].c;
562
563                 if (fb_y >= r->top && fb_y < r->top + r->height &&
564                     fb_x >= r->left && fb_x < r->left + r->width)
565                         return false;
566         }
567         return true;
568 }
569
570 /*
571  * Draw the image into the overlay buffer.
572  * Note that the combination of overlay and multiplanar is not supported.
573  */
574 static void vivid_overlay(struct vivid_dev *dev, struct vivid_buffer *buf)
575 {
576         struct tpg_data *tpg = &dev->tpg;
577         unsigned pixsize = tpg_g_twopixelsize(tpg, 0) / 2;
578         void *vbase = dev->fb_vbase_cap;
579         void *vbuf = vb2_plane_vaddr(&buf->vb, 0);
580         unsigned img_width = dev->compose_cap.width;
581         unsigned img_height = dev->compose_cap.height;
582         unsigned stride = tpg->bytesperline[0];
583         /* if quick is true, then valid_pix() doesn't have to be called */
584         bool quick = dev->bitmap_cap == NULL && dev->clipcount_cap == 0;
585         int x, y, w, out_x = 0;
586
587         if ((dev->overlay_cap_field == V4L2_FIELD_TOP ||
588              dev->overlay_cap_field == V4L2_FIELD_BOTTOM) &&
589             dev->overlay_cap_field != buf->vb.v4l2_buf.field)
590                 return;
591
592         vbuf += dev->compose_cap.left * pixsize + dev->compose_cap.top * stride;
593         x = dev->overlay_cap_left;
594         w = img_width;
595         if (x < 0) {
596                 out_x = -x;
597                 w = w - out_x;
598                 x = 0;
599         } else {
600                 w = dev->fb_cap.fmt.width - x;
601                 if (w > img_width)
602                         w = img_width;
603         }
604         if (w <= 0)
605                 return;
606         if (dev->overlay_cap_top >= 0)
607                 vbase += dev->overlay_cap_top * dev->fb_cap.fmt.bytesperline;
608         for (y = dev->overlay_cap_top;
609              y < dev->overlay_cap_top + (int)img_height;
610              y++, vbuf += stride) {
611                 int px;
612
613                 if (y < 0 || y > dev->fb_cap.fmt.height)
614                         continue;
615                 if (quick) {
616                         memcpy(vbase + x * pixsize,
617                                vbuf + out_x * pixsize, w * pixsize);
618                         vbase += dev->fb_cap.fmt.bytesperline;
619                         continue;
620                 }
621                 for (px = 0; px < w; px++) {
622                         if (!valid_pix(dev, y - dev->overlay_cap_top,
623                                        px + out_x, y, px + x))
624                                 continue;
625                         memcpy(vbase + (px + x) * pixsize,
626                                vbuf + (px + out_x) * pixsize,
627                                pixsize);
628                 }
629                 vbase += dev->fb_cap.fmt.bytesperline;
630         }
631 }
632
633 static void vivid_thread_vid_cap_tick(struct vivid_dev *dev, int dropped_bufs)
634 {
635         struct vivid_buffer *vid_cap_buf = NULL;
636         struct vivid_buffer *vbi_cap_buf = NULL;
637
638         dprintk(dev, 1, "Video Capture Thread Tick\n");
639
640         while (dropped_bufs-- > 1)
641                 tpg_update_mv_count(&dev->tpg,
642                                 dev->field_cap == V4L2_FIELD_NONE ||
643                                 dev->field_cap == V4L2_FIELD_ALTERNATE);
644
645         /* Drop a certain percentage of buffers. */
646         if (dev->perc_dropped_buffers &&
647             prandom_u32_max(100) < dev->perc_dropped_buffers)
648                 goto update_mv;
649
650         spin_lock(&dev->slock);
651         if (!list_empty(&dev->vid_cap_active)) {
652                 vid_cap_buf = list_entry(dev->vid_cap_active.next, struct vivid_buffer, list);
653                 list_del(&vid_cap_buf->list);
654         }
655         if (!list_empty(&dev->vbi_cap_active)) {
656                 if (dev->field_cap != V4L2_FIELD_ALTERNATE ||
657                     (dev->vbi_cap_seq_count & 1)) {
658                         vbi_cap_buf = list_entry(dev->vbi_cap_active.next,
659                                                  struct vivid_buffer, list);
660                         list_del(&vbi_cap_buf->list);
661                 }
662         }
663         spin_unlock(&dev->slock);
664
665         if (!vid_cap_buf && !vbi_cap_buf)
666                 goto update_mv;
667
668         if (vid_cap_buf) {
669                 /* Fill buffer */
670                 vivid_fillbuff(dev, vid_cap_buf);
671                 dprintk(dev, 1, "filled buffer %d\n",
672                         vid_cap_buf->vb.v4l2_buf.index);
673
674                 /* Handle overlay */
675                 if (dev->overlay_cap_owner && dev->fb_cap.base &&
676                                 dev->fb_cap.fmt.pixelformat == dev->fmt_cap->fourcc)
677                         vivid_overlay(dev, vid_cap_buf);
678
679                 vb2_buffer_done(&vid_cap_buf->vb, dev->dqbuf_error ?
680                                 VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE);
681                 dprintk(dev, 2, "vid_cap buffer %d done\n",
682                                 vid_cap_buf->vb.v4l2_buf.index);
683         }
684
685         if (vbi_cap_buf) {
686                 if (dev->stream_sliced_vbi_cap)
687                         vivid_sliced_vbi_cap_process(dev, vbi_cap_buf);
688                 else
689                         vivid_raw_vbi_cap_process(dev, vbi_cap_buf);
690                 vb2_buffer_done(&vbi_cap_buf->vb, dev->dqbuf_error ?
691                                 VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE);
692                 dprintk(dev, 2, "vbi_cap %d done\n",
693                                 vbi_cap_buf->vb.v4l2_buf.index);
694         }
695         dev->dqbuf_error = false;
696
697 update_mv:
698         /* Update the test pattern movement counters */
699         tpg_update_mv_count(&dev->tpg, dev->field_cap == V4L2_FIELD_NONE ||
700                                        dev->field_cap == V4L2_FIELD_ALTERNATE);
701 }
702
703 static int vivid_thread_vid_cap(void *data)
704 {
705         struct vivid_dev *dev = data;
706         u64 numerators_since_start;
707         u64 buffers_since_start;
708         u64 next_jiffies_since_start;
709         unsigned long jiffies_since_start;
710         unsigned long cur_jiffies;
711         unsigned wait_jiffies;
712         unsigned numerator;
713         unsigned denominator;
714         int dropped_bufs;
715
716         dprintk(dev, 1, "Video Capture Thread Start\n");
717
718         set_freezable();
719
720         /* Resets frame counters */
721         dev->cap_seq_offset = 0;
722         dev->cap_seq_count = 0;
723         dev->cap_seq_resync = false;
724         dev->jiffies_vid_cap = jiffies;
725
726         for (;;) {
727                 try_to_freeze();
728                 if (kthread_should_stop())
729                         break;
730
731                 mutex_lock(&dev->mutex);
732                 cur_jiffies = jiffies;
733                 if (dev->cap_seq_resync) {
734                         dev->jiffies_vid_cap = cur_jiffies;
735                         dev->cap_seq_offset = dev->cap_seq_count + 1;
736                         dev->cap_seq_count = 0;
737                         dev->cap_seq_resync = false;
738                 }
739                 numerator = dev->timeperframe_vid_cap.numerator;
740                 denominator = dev->timeperframe_vid_cap.denominator;
741
742                 if (dev->field_cap == V4L2_FIELD_ALTERNATE)
743                         denominator *= 2;
744
745                 /* Calculate the number of jiffies since we started streaming */
746                 jiffies_since_start = cur_jiffies - dev->jiffies_vid_cap;
747                 /* Get the number of buffers streamed since the start */
748                 buffers_since_start = (u64)jiffies_since_start * denominator +
749                                       (HZ * numerator) / 2;
750                 do_div(buffers_since_start, HZ * numerator);
751
752                 /*
753                  * After more than 0xf0000000 (rounded down to a multiple of
754                  * 'jiffies-per-day' to ease jiffies_to_msecs calculation)
755                  * jiffies have passed since we started streaming reset the
756                  * counters and keep track of the sequence offset.
757                  */
758                 if (jiffies_since_start > JIFFIES_RESYNC) {
759                         dev->jiffies_vid_cap = cur_jiffies;
760                         dev->cap_seq_offset = buffers_since_start;
761                         buffers_since_start = 0;
762                 }
763                 dropped_bufs = buffers_since_start + dev->cap_seq_offset - dev->cap_seq_count;
764                 dev->cap_seq_count = buffers_since_start + dev->cap_seq_offset;
765                 dev->vid_cap_seq_count = dev->cap_seq_count - dev->vid_cap_seq_start;
766                 dev->vbi_cap_seq_count = dev->cap_seq_count - dev->vbi_cap_seq_start;
767
768                 vivid_thread_vid_cap_tick(dev, dropped_bufs);
769
770                 /*
771                  * Calculate the number of 'numerators' streamed since we started,
772                  * including the current buffer.
773                  */
774                 numerators_since_start = ++buffers_since_start * numerator;
775
776                 /* And the number of jiffies since we started */
777                 jiffies_since_start = jiffies - dev->jiffies_vid_cap;
778
779                 mutex_unlock(&dev->mutex);
780
781                 /*
782                  * Calculate when that next buffer is supposed to start
783                  * in jiffies since we started streaming.
784                  */
785                 next_jiffies_since_start = numerators_since_start * HZ +
786                                            denominator / 2;
787                 do_div(next_jiffies_since_start, denominator);
788                 /* If it is in the past, then just schedule asap */
789                 if (next_jiffies_since_start < jiffies_since_start)
790                         next_jiffies_since_start = jiffies_since_start;
791
792                 wait_jiffies = next_jiffies_since_start - jiffies_since_start;
793                 schedule_timeout_interruptible(wait_jiffies ? wait_jiffies : 1);
794         }
795         dprintk(dev, 1, "Video Capture Thread End\n");
796         return 0;
797 }
798
799 static void vivid_grab_controls(struct vivid_dev *dev, bool grab)
800 {
801         v4l2_ctrl_grab(dev->ctrl_has_crop_cap, grab);
802         v4l2_ctrl_grab(dev->ctrl_has_compose_cap, grab);
803         v4l2_ctrl_grab(dev->ctrl_has_scaler_cap, grab);
804 }
805
806 int vivid_start_generating_vid_cap(struct vivid_dev *dev, bool *pstreaming)
807 {
808         dprintk(dev, 1, "%s\n", __func__);
809
810         if (dev->kthread_vid_cap) {
811                 u32 seq_count = dev->cap_seq_count + dev->seq_wrap * 128;
812
813                 if (pstreaming == &dev->vid_cap_streaming)
814                         dev->vid_cap_seq_start = seq_count;
815                 else
816                         dev->vbi_cap_seq_start = seq_count;
817                 *pstreaming = true;
818                 return 0;
819         }
820
821         /* Resets frame counters */
822         tpg_init_mv_count(&dev->tpg);
823
824         dev->vid_cap_seq_start = dev->seq_wrap * 128;
825         dev->vbi_cap_seq_start = dev->seq_wrap * 128;
826
827         dev->kthread_vid_cap = kthread_run(vivid_thread_vid_cap, dev,
828                         "%s-vid-cap", dev->v4l2_dev.name);
829
830         if (IS_ERR(dev->kthread_vid_cap)) {
831                 v4l2_err(&dev->v4l2_dev, "kernel_thread() failed\n");
832                 return PTR_ERR(dev->kthread_vid_cap);
833         }
834         *pstreaming = true;
835         vivid_grab_controls(dev, true);
836
837         dprintk(dev, 1, "returning from %s\n", __func__);
838         return 0;
839 }
840
841 void vivid_stop_generating_vid_cap(struct vivid_dev *dev, bool *pstreaming)
842 {
843         dprintk(dev, 1, "%s\n", __func__);
844
845         if (dev->kthread_vid_cap == NULL)
846                 return;
847
848         *pstreaming = false;
849         if (pstreaming == &dev->vid_cap_streaming) {
850                 /* Release all active buffers */
851                 while (!list_empty(&dev->vid_cap_active)) {
852                         struct vivid_buffer *buf;
853
854                         buf = list_entry(dev->vid_cap_active.next,
855                                          struct vivid_buffer, list);
856                         list_del(&buf->list);
857                         vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
858                         dprintk(dev, 2, "vid_cap buffer %d done\n",
859                                 buf->vb.v4l2_buf.index);
860                 }
861         }
862
863         if (pstreaming == &dev->vbi_cap_streaming) {
864                 while (!list_empty(&dev->vbi_cap_active)) {
865                         struct vivid_buffer *buf;
866
867                         buf = list_entry(dev->vbi_cap_active.next,
868                                          struct vivid_buffer, list);
869                         list_del(&buf->list);
870                         vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
871                         dprintk(dev, 2, "vbi_cap buffer %d done\n",
872                                 buf->vb.v4l2_buf.index);
873                 }
874         }
875
876         if (dev->vid_cap_streaming || dev->vbi_cap_streaming)
877                 return;
878
879         /* shutdown control thread */
880         vivid_grab_controls(dev, false);
881         mutex_unlock(&dev->mutex);
882         kthread_stop(dev->kthread_vid_cap);
883         dev->kthread_vid_cap = NULL;
884         mutex_lock(&dev->mutex);
885 }