1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Copyright (c) 2016 MediaTek Inc.
4 * Author: PC Chen <pc.chen@mediatek.com>
5 *         Tiffany Lin <tiffany.lin@mediatek.com>
6 */
7 
8 #include <media/v4l2-event.h>
9 #include <media/v4l2-mem2mem.h>
10 #include <media/videobuf2-dma-contig.h>
11 #include <soc/mediatek/smi.h>
12 #include <linux/pm_runtime.h>
13 
14 #include "mtk_vcodec_drv.h"
15 #include "mtk_vcodec_enc.h"
16 #include "mtk_vcodec_intr.h"
17 #include "mtk_vcodec_util.h"
18 #include "venc_drv_if.h"
19 
20 #define MTK_VENC_MIN_W	160U
21 #define MTK_VENC_MIN_H	128U
22 #define MTK_VENC_HD_MAX_W	1920U
23 #define MTK_VENC_HD_MAX_H	1088U
24 #define MTK_VENC_4K_MAX_W	3840U
25 #define MTK_VENC_4K_MAX_H	2176U
26 
27 #define DFT_CFG_WIDTH	MTK_VENC_MIN_W
28 #define DFT_CFG_HEIGHT	MTK_VENC_MIN_H
29 #define MTK_MAX_CTRLS_HINT	20
30 
31 #define MTK_DEFAULT_FRAMERATE_NUM 1001
32 #define MTK_DEFAULT_FRAMERATE_DENOM 30000
33 #define MTK_VENC_4K_CAPABILITY_ENABLE BIT(0)
34 
35 static void mtk_venc_worker(struct work_struct *work);
36 
37 static const struct v4l2_frmsize_stepwise mtk_venc_hd_framesizes = {
38 	MTK_VENC_MIN_W, MTK_VENC_HD_MAX_W, 16,
39 	MTK_VENC_MIN_H, MTK_VENC_HD_MAX_H, 16,
40 };
41 
42 static const struct v4l2_frmsize_stepwise mtk_venc_4k_framesizes = {
43 	MTK_VENC_MIN_W, MTK_VENC_4K_MAX_W, 16,
44 	MTK_VENC_MIN_H, MTK_VENC_4K_MAX_H, 16,
45 };
46 
vidioc_venc_s_ctrl(struct v4l2_ctrl * ctrl)47 static int vidioc_venc_s_ctrl(struct v4l2_ctrl *ctrl)
48 {
49 	struct mtk_vcodec_ctx *ctx = ctrl_to_ctx(ctrl);
50 	struct mtk_enc_params *p = &ctx->enc_params;
51 	int ret = 0;
52 
53 	switch (ctrl->id) {
54 	case V4L2_CID_MPEG_VIDEO_BITRATE:
55 		mtk_v4l2_debug(2, "V4L2_CID_MPEG_VIDEO_BITRATE val = %d",
56 			       ctrl->val);
57 		p->bitrate = ctrl->val;
58 		ctx->param_change |= MTK_ENCODE_PARAM_BITRATE;
59 		break;
60 	case V4L2_CID_MPEG_VIDEO_B_FRAMES:
61 		mtk_v4l2_debug(2, "V4L2_CID_MPEG_VIDEO_B_FRAMES val = %d",
62 			       ctrl->val);
63 		p->num_b_frame = ctrl->val;
64 		break;
65 	case V4L2_CID_MPEG_VIDEO_FRAME_RC_ENABLE:
66 		mtk_v4l2_debug(2, "V4L2_CID_MPEG_VIDEO_FRAME_RC_ENABLE val = %d",
67 			       ctrl->val);
68 		p->rc_frame = ctrl->val;
69 		break;
70 	case V4L2_CID_MPEG_VIDEO_H264_MAX_QP:
71 		mtk_v4l2_debug(2, "V4L2_CID_MPEG_VIDEO_H264_MAX_QP val = %d",
72 			       ctrl->val);
73 		p->h264_max_qp = ctrl->val;
74 		break;
75 	case V4L2_CID_MPEG_VIDEO_HEADER_MODE:
76 		mtk_v4l2_debug(2, "V4L2_CID_MPEG_VIDEO_HEADER_MODE val = %d",
77 			       ctrl->val);
78 		p->seq_hdr_mode = ctrl->val;
79 		break;
80 	case V4L2_CID_MPEG_VIDEO_MB_RC_ENABLE:
81 		mtk_v4l2_debug(2, "V4L2_CID_MPEG_VIDEO_MB_RC_ENABLE val = %d",
82 			       ctrl->val);
83 		p->rc_mb = ctrl->val;
84 		break;
85 	case V4L2_CID_MPEG_VIDEO_H264_PROFILE:
86 		mtk_v4l2_debug(2, "V4L2_CID_MPEG_VIDEO_H264_PROFILE val = %d",
87 			       ctrl->val);
88 		p->h264_profile = ctrl->val;
89 		break;
90 	case V4L2_CID_MPEG_VIDEO_H264_LEVEL:
91 		mtk_v4l2_debug(2, "V4L2_CID_MPEG_VIDEO_H264_LEVEL val = %d",
92 			       ctrl->val);
93 		p->h264_level = ctrl->val;
94 		break;
95 	case V4L2_CID_MPEG_VIDEO_H264_I_PERIOD:
96 		mtk_v4l2_debug(2, "V4L2_CID_MPEG_VIDEO_H264_I_PERIOD val = %d",
97 			       ctrl->val);
98 		p->intra_period = ctrl->val;
99 		ctx->param_change |= MTK_ENCODE_PARAM_INTRA_PERIOD;
100 		break;
101 	case V4L2_CID_MPEG_VIDEO_GOP_SIZE:
102 		mtk_v4l2_debug(2, "V4L2_CID_MPEG_VIDEO_GOP_SIZE val = %d",
103 			       ctrl->val);
104 		p->gop_size = ctrl->val;
105 		ctx->param_change |= MTK_ENCODE_PARAM_GOP_SIZE;
106 		break;
107 	case V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME:
108 		mtk_v4l2_debug(2, "V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME");
109 		p->force_intra = 1;
110 		ctx->param_change |= MTK_ENCODE_PARAM_FORCE_INTRA;
111 		break;
112 	default:
113 		ret = -EINVAL;
114 		break;
115 	}
116 
117 	return ret;
118 }
119 
120 static const struct v4l2_ctrl_ops mtk_vcodec_enc_ctrl_ops = {
121 	.s_ctrl = vidioc_venc_s_ctrl,
122 };
123 
vidioc_enum_fmt(struct v4l2_fmtdesc * f,const struct mtk_video_fmt * formats,size_t num_formats)124 static int vidioc_enum_fmt(struct v4l2_fmtdesc *f,
125 			   const struct mtk_video_fmt *formats,
126 			   size_t num_formats)
127 {
128 	if (f->index >= num_formats)
129 		return -EINVAL;
130 
131 	f->pixelformat = formats[f->index].fourcc;
132 
133 	return 0;
134 }
135 
136 static const struct mtk_video_fmt *
mtk_venc_find_format(u32 fourcc,const struct mtk_vcodec_enc_pdata * pdata)137 mtk_venc_find_format(u32 fourcc, const struct mtk_vcodec_enc_pdata *pdata)
138 {
139 	const struct mtk_video_fmt *fmt;
140 	unsigned int k;
141 
142 	for (k = 0; k < pdata->num_capture_formats; k++) {
143 		fmt = &pdata->capture_formats[k];
144 		if (fmt->fourcc == fourcc)
145 			return fmt;
146 	}
147 
148 	for (k = 0; k < pdata->num_output_formats; k++) {
149 		fmt = &pdata->output_formats[k];
150 		if (fmt->fourcc == fourcc)
151 			return fmt;
152 	}
153 
154 	return NULL;
155 }
156 
vidioc_enum_framesizes(struct file * file,void * fh,struct v4l2_frmsizeenum * fsize)157 static int vidioc_enum_framesizes(struct file *file, void *fh,
158 				  struct v4l2_frmsizeenum *fsize)
159 {
160 	const struct mtk_video_fmt *fmt;
161 	struct mtk_vcodec_ctx *ctx = fh_to_ctx(fh);
162 
163 	if (fsize->index != 0)
164 		return -EINVAL;
165 
166 	fmt = mtk_venc_find_format(fsize->pixel_format,
167 				   ctx->dev->venc_pdata);
168 	if (!fmt)
169 		return -EINVAL;
170 
171 	fsize->type = V4L2_FRMSIZE_TYPE_STEPWISE;
172 
173 	if (ctx->dev->enc_capability & MTK_VENC_4K_CAPABILITY_ENABLE)
174 		fsize->stepwise = mtk_venc_4k_framesizes;
175 	else
176 		fsize->stepwise = mtk_venc_hd_framesizes;
177 
178 	return 0;
179 }
180 
vidioc_enum_fmt_vid_cap(struct file * file,void * priv,struct v4l2_fmtdesc * f)181 static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv,
182 				   struct v4l2_fmtdesc *f)
183 {
184 	const struct mtk_vcodec_enc_pdata *pdata =
185 		fh_to_ctx(priv)->dev->venc_pdata;
186 
187 	return vidioc_enum_fmt(f, pdata->capture_formats,
188 			       pdata->num_capture_formats);
189 }
190 
vidioc_enum_fmt_vid_out(struct file * file,void * priv,struct v4l2_fmtdesc * f)191 static int vidioc_enum_fmt_vid_out(struct file *file, void *priv,
192 				   struct v4l2_fmtdesc *f)
193 {
194 	const struct mtk_vcodec_enc_pdata *pdata =
195 		fh_to_ctx(priv)->dev->venc_pdata;
196 
197 	return vidioc_enum_fmt(f, pdata->output_formats,
198 			       pdata->num_output_formats);
199 }
200 
vidioc_venc_querycap(struct file * file,void * priv,struct v4l2_capability * cap)201 static int vidioc_venc_querycap(struct file *file, void *priv,
202 				struct v4l2_capability *cap)
203 {
204 	strscpy(cap->driver, MTK_VCODEC_ENC_NAME, sizeof(cap->driver));
205 	strscpy(cap->bus_info, MTK_PLATFORM_STR, sizeof(cap->bus_info));
206 	strscpy(cap->card, MTK_PLATFORM_STR, sizeof(cap->card));
207 
208 	return 0;
209 }
210 
vidioc_venc_s_parm(struct file * file,void * priv,struct v4l2_streamparm * a)211 static int vidioc_venc_s_parm(struct file *file, void *priv,
212 			      struct v4l2_streamparm *a)
213 {
214 	struct mtk_vcodec_ctx *ctx = fh_to_ctx(priv);
215 	struct v4l2_fract *timeperframe = &a->parm.output.timeperframe;
216 
217 	if (a->type != V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
218 		return -EINVAL;
219 
220 	if (timeperframe->numerator == 0 || timeperframe->denominator == 0) {
221 		timeperframe->numerator = MTK_DEFAULT_FRAMERATE_NUM;
222 		timeperframe->denominator = MTK_DEFAULT_FRAMERATE_DENOM;
223 	}
224 
225 	ctx->enc_params.framerate_num = timeperframe->denominator;
226 	ctx->enc_params.framerate_denom = timeperframe->numerator;
227 	ctx->param_change |= MTK_ENCODE_PARAM_FRAMERATE;
228 
229 	a->parm.output.capability = V4L2_CAP_TIMEPERFRAME;
230 
231 	return 0;
232 }
233 
vidioc_venc_g_parm(struct file * file,void * priv,struct v4l2_streamparm * a)234 static int vidioc_venc_g_parm(struct file *file, void *priv,
235 			      struct v4l2_streamparm *a)
236 {
237 	struct mtk_vcodec_ctx *ctx = fh_to_ctx(priv);
238 
239 	if (a->type != V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
240 		return -EINVAL;
241 
242 	a->parm.output.capability = V4L2_CAP_TIMEPERFRAME;
243 	a->parm.output.timeperframe.denominator =
244 			ctx->enc_params.framerate_num;
245 	a->parm.output.timeperframe.numerator =
246 			ctx->enc_params.framerate_denom;
247 
248 	return 0;
249 }
250 
mtk_venc_get_q_data(struct mtk_vcodec_ctx * ctx,enum v4l2_buf_type type)251 static struct mtk_q_data *mtk_venc_get_q_data(struct mtk_vcodec_ctx *ctx,
252 					      enum v4l2_buf_type type)
253 {
254 	if (V4L2_TYPE_IS_OUTPUT(type))
255 		return &ctx->q_data[MTK_Q_DATA_SRC];
256 
257 	return &ctx->q_data[MTK_Q_DATA_DST];
258 }
259 
260 /* V4L2 specification suggests the driver corrects the format struct if any of
261  * the dimensions is unsupported
262  */
vidioc_try_fmt(struct mtk_vcodec_ctx * ctx,struct v4l2_format * f,const struct mtk_video_fmt * fmt)263 static int vidioc_try_fmt(struct mtk_vcodec_ctx *ctx, struct v4l2_format *f,
264 			  const struct mtk_video_fmt *fmt)
265 {
266 	struct v4l2_pix_format_mplane *pix_fmt_mp = &f->fmt.pix_mp;
267 
268 	pix_fmt_mp->field = V4L2_FIELD_NONE;
269 
270 	if (f->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
271 		pix_fmt_mp->num_planes = 1;
272 		pix_fmt_mp->plane_fmt[0].bytesperline = 0;
273 	} else if (f->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
274 		int tmp_w, tmp_h;
275 		unsigned int max_width, max_height;
276 
277 		if (ctx->dev->enc_capability & MTK_VENC_4K_CAPABILITY_ENABLE) {
278 			max_width = MTK_VENC_4K_MAX_W;
279 			max_height = MTK_VENC_4K_MAX_H;
280 		} else {
281 			max_width = MTK_VENC_HD_MAX_W;
282 			max_height = MTK_VENC_HD_MAX_H;
283 		}
284 
285 		pix_fmt_mp->height = clamp(pix_fmt_mp->height,
286 					MTK_VENC_MIN_H,
287 					max_height);
288 		pix_fmt_mp->width = clamp(pix_fmt_mp->width,
289 					MTK_VENC_MIN_W,
290 					max_width);
291 
292 		/* find next closer width align 16, heign align 32, size align
293 		 * 64 rectangle
294 		 */
295 		tmp_w = pix_fmt_mp->width;
296 		tmp_h = pix_fmt_mp->height;
297 		v4l_bound_align_image(&pix_fmt_mp->width,
298 					MTK_VENC_MIN_W,
299 					max_width, 4,
300 					&pix_fmt_mp->height,
301 					MTK_VENC_MIN_H,
302 					max_height, 5, 6);
303 
304 		if (pix_fmt_mp->width < tmp_w &&
305 			(pix_fmt_mp->width + 16) <= max_width)
306 			pix_fmt_mp->width += 16;
307 		if (pix_fmt_mp->height < tmp_h &&
308 			(pix_fmt_mp->height + 32) <= max_height)
309 			pix_fmt_mp->height += 32;
310 
311 		mtk_v4l2_debug(0,
312 			"before resize width=%d, height=%d, after resize width=%d, height=%d, sizeimage=%d %d",
313 			tmp_w, tmp_h, pix_fmt_mp->width,
314 			pix_fmt_mp->height,
315 			pix_fmt_mp->plane_fmt[0].sizeimage,
316 			pix_fmt_mp->plane_fmt[1].sizeimage);
317 
318 		pix_fmt_mp->num_planes = fmt->num_planes;
319 		pix_fmt_mp->plane_fmt[0].sizeimage =
320 				pix_fmt_mp->width * pix_fmt_mp->height +
321 				((ALIGN(pix_fmt_mp->width, 16) * 2) * 16);
322 		pix_fmt_mp->plane_fmt[0].bytesperline = pix_fmt_mp->width;
323 
324 		if (pix_fmt_mp->num_planes == 2) {
325 			pix_fmt_mp->plane_fmt[1].sizeimage =
326 				(pix_fmt_mp->width * pix_fmt_mp->height) / 2 +
327 				(ALIGN(pix_fmt_mp->width, 16) * 16);
328 			pix_fmt_mp->plane_fmt[2].sizeimage = 0;
329 			pix_fmt_mp->plane_fmt[1].bytesperline =
330 							pix_fmt_mp->width;
331 			pix_fmt_mp->plane_fmt[2].bytesperline = 0;
332 		} else if (pix_fmt_mp->num_planes == 3) {
333 			pix_fmt_mp->plane_fmt[1].sizeimage =
334 			pix_fmt_mp->plane_fmt[2].sizeimage =
335 				(pix_fmt_mp->width * pix_fmt_mp->height) / 4 +
336 				((ALIGN(pix_fmt_mp->width, 16) / 2) * 16);
337 			pix_fmt_mp->plane_fmt[1].bytesperline =
338 				pix_fmt_mp->plane_fmt[2].bytesperline =
339 				pix_fmt_mp->width / 2;
340 		}
341 	}
342 
343 	pix_fmt_mp->flags = 0;
344 
345 	return 0;
346 }
347 
mtk_venc_set_param(struct mtk_vcodec_ctx * ctx,struct venc_enc_param * param)348 static void mtk_venc_set_param(struct mtk_vcodec_ctx *ctx,
349 				struct venc_enc_param *param)
350 {
351 	struct mtk_q_data *q_data_src = &ctx->q_data[MTK_Q_DATA_SRC];
352 	struct mtk_enc_params *enc_params = &ctx->enc_params;
353 
354 	switch (q_data_src->fmt->fourcc) {
355 	case V4L2_PIX_FMT_YUV420M:
356 		param->input_yuv_fmt = VENC_YUV_FORMAT_I420;
357 		break;
358 	case V4L2_PIX_FMT_YVU420M:
359 		param->input_yuv_fmt = VENC_YUV_FORMAT_YV12;
360 		break;
361 	case V4L2_PIX_FMT_NV12M:
362 		param->input_yuv_fmt = VENC_YUV_FORMAT_NV12;
363 		break;
364 	case V4L2_PIX_FMT_NV21M:
365 		param->input_yuv_fmt = VENC_YUV_FORMAT_NV21;
366 		break;
367 	default:
368 		mtk_v4l2_err("Unsupported fourcc =%d", q_data_src->fmt->fourcc);
369 		break;
370 	}
371 	param->h264_profile = enc_params->h264_profile;
372 	param->h264_level = enc_params->h264_level;
373 
374 	/* Config visible resolution */
375 	param->width = q_data_src->visible_width;
376 	param->height = q_data_src->visible_height;
377 	/* Config coded resolution */
378 	param->buf_width = q_data_src->coded_width;
379 	param->buf_height = q_data_src->coded_height;
380 	param->frm_rate = enc_params->framerate_num /
381 			enc_params->framerate_denom;
382 	param->intra_period = enc_params->intra_period;
383 	param->gop_size = enc_params->gop_size;
384 	param->bitrate = enc_params->bitrate;
385 
386 	mtk_v4l2_debug(0,
387 		"fmt 0x%x, P/L %d/%d, w/h %d/%d, buf %d/%d, fps/bps %d/%d, gop %d, i_period %d",
388 		param->input_yuv_fmt, param->h264_profile,
389 		param->h264_level, param->width, param->height,
390 		param->buf_width, param->buf_height,
391 		param->frm_rate, param->bitrate,
392 		param->gop_size, param->intra_period);
393 }
394 
vidioc_venc_s_fmt_cap(struct file * file,void * priv,struct v4l2_format * f)395 static int vidioc_venc_s_fmt_cap(struct file *file, void *priv,
396 			     struct v4l2_format *f)
397 {
398 	struct mtk_vcodec_ctx *ctx = fh_to_ctx(priv);
399 	const struct mtk_vcodec_enc_pdata *pdata = ctx->dev->venc_pdata;
400 	struct vb2_queue *vq;
401 	struct mtk_q_data *q_data;
402 	int i, ret;
403 	const struct mtk_video_fmt *fmt;
404 
405 	vq = v4l2_m2m_get_vq(ctx->m2m_ctx, f->type);
406 	if (!vq) {
407 		mtk_v4l2_err("fail to get vq");
408 		return -EINVAL;
409 	}
410 
411 	if (vb2_is_busy(vq)) {
412 		mtk_v4l2_err("queue busy");
413 		return -EBUSY;
414 	}
415 
416 	q_data = mtk_venc_get_q_data(ctx, f->type);
417 	if (!q_data) {
418 		mtk_v4l2_err("fail to get q data");
419 		return -EINVAL;
420 	}
421 
422 	fmt = mtk_venc_find_format(f->fmt.pix.pixelformat, pdata);
423 	if (!fmt) {
424 		fmt = &ctx->dev->venc_pdata->capture_formats[0];
425 		f->fmt.pix.pixelformat = fmt->fourcc;
426 	}
427 
428 	q_data->fmt = fmt;
429 	ret = vidioc_try_fmt(ctx, f, q_data->fmt);
430 	if (ret)
431 		return ret;
432 
433 	q_data->coded_width = f->fmt.pix_mp.width;
434 	q_data->coded_height = f->fmt.pix_mp.height;
435 	q_data->field = f->fmt.pix_mp.field;
436 
437 	for (i = 0; i < f->fmt.pix_mp.num_planes; i++) {
438 		struct v4l2_plane_pix_format	*plane_fmt;
439 
440 		plane_fmt = &f->fmt.pix_mp.plane_fmt[i];
441 		q_data->bytesperline[i]	= plane_fmt->bytesperline;
442 		q_data->sizeimage[i] = plane_fmt->sizeimage;
443 	}
444 
445 	if (ctx->state == MTK_STATE_FREE) {
446 		ret = venc_if_init(ctx, q_data->fmt->fourcc);
447 		if (ret) {
448 			mtk_v4l2_err("venc_if_init failed=%d, codec type=%x",
449 					ret, q_data->fmt->fourcc);
450 			return -EBUSY;
451 		}
452 		ctx->state = MTK_STATE_INIT;
453 	}
454 
455 	return 0;
456 }
457 
vidioc_venc_s_fmt_out(struct file * file,void * priv,struct v4l2_format * f)458 static int vidioc_venc_s_fmt_out(struct file *file, void *priv,
459 			     struct v4l2_format *f)
460 {
461 	struct mtk_vcodec_ctx *ctx = fh_to_ctx(priv);
462 	const struct mtk_vcodec_enc_pdata *pdata = ctx->dev->venc_pdata;
463 	struct vb2_queue *vq;
464 	struct mtk_q_data *q_data;
465 	int ret, i;
466 	const struct mtk_video_fmt *fmt;
467 
468 	vq = v4l2_m2m_get_vq(ctx->m2m_ctx, f->type);
469 	if (!vq) {
470 		mtk_v4l2_err("fail to get vq");
471 		return -EINVAL;
472 	}
473 
474 	if (vb2_is_busy(vq)) {
475 		mtk_v4l2_err("queue busy");
476 		return -EBUSY;
477 	}
478 
479 	q_data = mtk_venc_get_q_data(ctx, f->type);
480 	if (!q_data) {
481 		mtk_v4l2_err("fail to get q data");
482 		return -EINVAL;
483 	}
484 
485 	fmt = mtk_venc_find_format(f->fmt.pix.pixelformat, pdata);
486 	if (!fmt) {
487 		fmt = &ctx->dev->venc_pdata->output_formats[0];
488 		f->fmt.pix.pixelformat = fmt->fourcc;
489 	}
490 
491 	ret = vidioc_try_fmt(ctx, f, fmt);
492 	if (ret)
493 		return ret;
494 
495 	q_data->fmt = fmt;
496 	q_data->visible_width = f->fmt.pix_mp.width;
497 	q_data->visible_height = f->fmt.pix_mp.height;
498 	q_data->coded_width = f->fmt.pix_mp.width;
499 	q_data->coded_height = f->fmt.pix_mp.height;
500 
501 	q_data->field = f->fmt.pix_mp.field;
502 	ctx->colorspace = f->fmt.pix_mp.colorspace;
503 	ctx->ycbcr_enc = f->fmt.pix_mp.ycbcr_enc;
504 	ctx->quantization = f->fmt.pix_mp.quantization;
505 	ctx->xfer_func = f->fmt.pix_mp.xfer_func;
506 
507 	for (i = 0; i < f->fmt.pix_mp.num_planes; i++) {
508 		struct v4l2_plane_pix_format *plane_fmt;
509 
510 		plane_fmt = &f->fmt.pix_mp.plane_fmt[i];
511 		q_data->bytesperline[i] = plane_fmt->bytesperline;
512 		q_data->sizeimage[i] = plane_fmt->sizeimage;
513 	}
514 
515 	return 0;
516 }
517 
vidioc_venc_g_fmt(struct file * file,void * priv,struct v4l2_format * f)518 static int vidioc_venc_g_fmt(struct file *file, void *priv,
519 			     struct v4l2_format *f)
520 {
521 	struct v4l2_pix_format_mplane *pix = &f->fmt.pix_mp;
522 	struct mtk_vcodec_ctx *ctx = fh_to_ctx(priv);
523 	struct vb2_queue *vq;
524 	struct mtk_q_data *q_data;
525 	int i;
526 
527 	vq = v4l2_m2m_get_vq(ctx->m2m_ctx, f->type);
528 	if (!vq)
529 		return -EINVAL;
530 
531 	q_data = mtk_venc_get_q_data(ctx, f->type);
532 
533 	pix->width = q_data->coded_width;
534 	pix->height = q_data->coded_height;
535 	pix->pixelformat = q_data->fmt->fourcc;
536 	pix->field = q_data->field;
537 	pix->num_planes = q_data->fmt->num_planes;
538 	for (i = 0; i < pix->num_planes; i++) {
539 		pix->plane_fmt[i].bytesperline = q_data->bytesperline[i];
540 		pix->plane_fmt[i].sizeimage = q_data->sizeimage[i];
541 	}
542 
543 	pix->flags = 0;
544 	pix->colorspace = ctx->colorspace;
545 	pix->ycbcr_enc = ctx->ycbcr_enc;
546 	pix->quantization = ctx->quantization;
547 	pix->xfer_func = ctx->xfer_func;
548 
549 	return 0;
550 }
551 
vidioc_try_fmt_vid_cap_mplane(struct file * file,void * priv,struct v4l2_format * f)552 static int vidioc_try_fmt_vid_cap_mplane(struct file *file, void *priv,
553 					 struct v4l2_format *f)
554 {
555 	const struct mtk_video_fmt *fmt;
556 	struct mtk_vcodec_ctx *ctx = fh_to_ctx(priv);
557 	const struct mtk_vcodec_enc_pdata *pdata = ctx->dev->venc_pdata;
558 
559 	fmt = mtk_venc_find_format(f->fmt.pix.pixelformat, pdata);
560 	if (!fmt) {
561 		fmt = &ctx->dev->venc_pdata->capture_formats[0];
562 		f->fmt.pix.pixelformat = fmt->fourcc;
563 	}
564 	f->fmt.pix_mp.colorspace = ctx->colorspace;
565 	f->fmt.pix_mp.ycbcr_enc = ctx->ycbcr_enc;
566 	f->fmt.pix_mp.quantization = ctx->quantization;
567 	f->fmt.pix_mp.xfer_func = ctx->xfer_func;
568 
569 	return vidioc_try_fmt(ctx, f, fmt);
570 }
571 
vidioc_try_fmt_vid_out_mplane(struct file * file,void * priv,struct v4l2_format * f)572 static int vidioc_try_fmt_vid_out_mplane(struct file *file, void *priv,
573 					 struct v4l2_format *f)
574 {
575 	const struct mtk_video_fmt *fmt;
576 	struct mtk_vcodec_ctx *ctx = fh_to_ctx(priv);
577 	const struct mtk_vcodec_enc_pdata *pdata = ctx->dev->venc_pdata;
578 
579 	fmt = mtk_venc_find_format(f->fmt.pix.pixelformat, pdata);
580 	if (!fmt) {
581 		fmt = &ctx->dev->venc_pdata->output_formats[0];
582 		f->fmt.pix.pixelformat = fmt->fourcc;
583 	}
584 	if (!f->fmt.pix_mp.colorspace) {
585 		f->fmt.pix_mp.colorspace = V4L2_COLORSPACE_REC709;
586 		f->fmt.pix_mp.ycbcr_enc = V4L2_YCBCR_ENC_DEFAULT;
587 		f->fmt.pix_mp.quantization = V4L2_QUANTIZATION_DEFAULT;
588 		f->fmt.pix_mp.xfer_func = V4L2_XFER_FUNC_DEFAULT;
589 	}
590 
591 	return vidioc_try_fmt(ctx, f, fmt);
592 }
593 
vidioc_venc_g_selection(struct file * file,void * priv,struct v4l2_selection * s)594 static int vidioc_venc_g_selection(struct file *file, void *priv,
595 				     struct v4l2_selection *s)
596 {
597 	struct mtk_vcodec_ctx *ctx = fh_to_ctx(priv);
598 	struct mtk_q_data *q_data;
599 
600 	if (s->type != V4L2_BUF_TYPE_VIDEO_OUTPUT)
601 		return -EINVAL;
602 
603 	q_data = mtk_venc_get_q_data(ctx, s->type);
604 	if (!q_data)
605 		return -EINVAL;
606 
607 	switch (s->target) {
608 	case V4L2_SEL_TGT_CROP_DEFAULT:
609 	case V4L2_SEL_TGT_CROP_BOUNDS:
610 		s->r.top = 0;
611 		s->r.left = 0;
612 		s->r.width = q_data->coded_width;
613 		s->r.height = q_data->coded_height;
614 		break;
615 	case V4L2_SEL_TGT_CROP:
616 		s->r.top = 0;
617 		s->r.left = 0;
618 		s->r.width = q_data->visible_width;
619 		s->r.height = q_data->visible_height;
620 		break;
621 	default:
622 		return -EINVAL;
623 	}
624 
625 	return 0;
626 }
627 
vidioc_venc_s_selection(struct file * file,void * priv,struct v4l2_selection * s)628 static int vidioc_venc_s_selection(struct file *file, void *priv,
629 				     struct v4l2_selection *s)
630 {
631 	struct mtk_vcodec_ctx *ctx = fh_to_ctx(priv);
632 	struct mtk_q_data *q_data;
633 
634 	if (s->type != V4L2_BUF_TYPE_VIDEO_OUTPUT)
635 		return -EINVAL;
636 
637 	q_data = mtk_venc_get_q_data(ctx, s->type);
638 	if (!q_data)
639 		return -EINVAL;
640 
641 	switch (s->target) {
642 	case V4L2_SEL_TGT_CROP:
643 		/* Only support crop from (0,0) */
644 		s->r.top = 0;
645 		s->r.left = 0;
646 		s->r.width = min(s->r.width, q_data->coded_width);
647 		s->r.height = min(s->r.height, q_data->coded_height);
648 		q_data->visible_width = s->r.width;
649 		q_data->visible_height = s->r.height;
650 		break;
651 	default:
652 		return -EINVAL;
653 	}
654 	return 0;
655 }
656 
vidioc_venc_qbuf(struct file * file,void * priv,struct v4l2_buffer * buf)657 static int vidioc_venc_qbuf(struct file *file, void *priv,
658 			    struct v4l2_buffer *buf)
659 {
660 	struct mtk_vcodec_ctx *ctx = fh_to_ctx(priv);
661 
662 	if (ctx->state == MTK_STATE_ABORT) {
663 		mtk_v4l2_err("[%d] Call on QBUF after unrecoverable error",
664 				ctx->id);
665 		return -EIO;
666 	}
667 
668 	return v4l2_m2m_qbuf(file, ctx->m2m_ctx, buf);
669 }
670 
vidioc_venc_dqbuf(struct file * file,void * priv,struct v4l2_buffer * buf)671 static int vidioc_venc_dqbuf(struct file *file, void *priv,
672 			     struct v4l2_buffer *buf)
673 {
674 	struct mtk_vcodec_ctx *ctx = fh_to_ctx(priv);
675 	int ret;
676 
677 	if (ctx->state == MTK_STATE_ABORT) {
678 		mtk_v4l2_err("[%d] Call on QBUF after unrecoverable error",
679 				ctx->id);
680 		return -EIO;
681 	}
682 
683 	ret = v4l2_m2m_dqbuf(file, ctx->m2m_ctx, buf);
684 	if (ret)
685 		return ret;
686 
687 	/*
688 	 * Complete flush if the user dequeued the 0-payload LAST buffer.
689 	 * We check the payload because a buffer with the LAST flag can also
690 	 * be seen during resolution changes. If we happen to be flushing at
691 	 * that time, the last buffer before the resolution changes could be
692 	 * misinterpreted for the buffer generated by the flush and terminate
693 	 * it earlier than we want.
694 	 */
695 	if (!V4L2_TYPE_IS_OUTPUT(buf->type) &&
696 	    buf->flags & V4L2_BUF_FLAG_LAST &&
697 	    buf->m.planes[0].bytesused == 0 &&
698 	    ctx->is_flushing) {
699 		/*
700 		 * Last CAPTURE buffer is dequeued, we can allow another flush
701 		 * to take place.
702 		 */
703 		ctx->is_flushing = false;
704 	}
705 
706 	return 0;
707 }
708 
vidioc_encoder_cmd(struct file * file,void * priv,struct v4l2_encoder_cmd * cmd)709 static int vidioc_encoder_cmd(struct file *file, void *priv,
710 			      struct v4l2_encoder_cmd *cmd)
711 {
712 	struct mtk_vcodec_ctx *ctx = fh_to_ctx(priv);
713 	struct vb2_queue *src_vq, *dst_vq;
714 	int ret;
715 
716 	if (ctx->state == MTK_STATE_ABORT) {
717 		mtk_v4l2_err("[%d] Call to CMD after unrecoverable error",
718 			     ctx->id);
719 		return -EIO;
720 	}
721 
722 	ret = v4l2_m2m_ioctl_try_encoder_cmd(file, priv, cmd);
723 	if (ret)
724 		return ret;
725 
726 	/* Calling START or STOP is invalid if a flush is in progress */
727 	if (ctx->is_flushing)
728 		return -EBUSY;
729 
730 	mtk_v4l2_debug(1, "encoder cmd=%u", cmd->cmd);
731 
732 	dst_vq = v4l2_m2m_get_vq(ctx->m2m_ctx,
733 				 V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE);
734 	switch (cmd->cmd) {
735 	case V4L2_ENC_CMD_STOP:
736 		src_vq = v4l2_m2m_get_vq(ctx->m2m_ctx,
737 					 V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE);
738 		if (!vb2_is_streaming(src_vq)) {
739 			mtk_v4l2_debug(1, "Output stream is off. No need to flush.");
740 			return 0;
741 		}
742 		if (!vb2_is_streaming(dst_vq)) {
743 			mtk_v4l2_debug(1, "Capture stream is off. No need to flush.");
744 			return 0;
745 		}
746 		ctx->is_flushing = true;
747 		v4l2_m2m_buf_queue(ctx->m2m_ctx, &ctx->empty_flush_buf.vb);
748 		v4l2_m2m_try_schedule(ctx->m2m_ctx);
749 		break;
750 
751 	case V4L2_ENC_CMD_START:
752 		vb2_clear_last_buffer_dequeued(dst_vq);
753 		break;
754 
755 	default:
756 		return -EINVAL;
757 	}
758 
759 	return 0;
760 }
761 
762 const struct v4l2_ioctl_ops mtk_venc_ioctl_ops = {
763 	.vidioc_streamon		= v4l2_m2m_ioctl_streamon,
764 	.vidioc_streamoff		= v4l2_m2m_ioctl_streamoff,
765 
766 	.vidioc_reqbufs			= v4l2_m2m_ioctl_reqbufs,
767 	.vidioc_querybuf		= v4l2_m2m_ioctl_querybuf,
768 	.vidioc_qbuf			= vidioc_venc_qbuf,
769 	.vidioc_dqbuf			= vidioc_venc_dqbuf,
770 
771 	.vidioc_querycap		= vidioc_venc_querycap,
772 	.vidioc_enum_fmt_vid_cap	= vidioc_enum_fmt_vid_cap,
773 	.vidioc_enum_fmt_vid_out	= vidioc_enum_fmt_vid_out,
774 	.vidioc_enum_framesizes		= vidioc_enum_framesizes,
775 
776 	.vidioc_try_fmt_vid_cap_mplane	= vidioc_try_fmt_vid_cap_mplane,
777 	.vidioc_try_fmt_vid_out_mplane	= vidioc_try_fmt_vid_out_mplane,
778 	.vidioc_expbuf			= v4l2_m2m_ioctl_expbuf,
779 	.vidioc_subscribe_event		= v4l2_ctrl_subscribe_event,
780 	.vidioc_unsubscribe_event	= v4l2_event_unsubscribe,
781 
782 	.vidioc_s_parm			= vidioc_venc_s_parm,
783 	.vidioc_g_parm			= vidioc_venc_g_parm,
784 	.vidioc_s_fmt_vid_cap_mplane	= vidioc_venc_s_fmt_cap,
785 	.vidioc_s_fmt_vid_out_mplane	= vidioc_venc_s_fmt_out,
786 
787 	.vidioc_g_fmt_vid_cap_mplane	= vidioc_venc_g_fmt,
788 	.vidioc_g_fmt_vid_out_mplane	= vidioc_venc_g_fmt,
789 
790 	.vidioc_create_bufs		= v4l2_m2m_ioctl_create_bufs,
791 	.vidioc_prepare_buf		= v4l2_m2m_ioctl_prepare_buf,
792 
793 	.vidioc_g_selection		= vidioc_venc_g_selection,
794 	.vidioc_s_selection		= vidioc_venc_s_selection,
795 
796 	.vidioc_encoder_cmd		= vidioc_encoder_cmd,
797 	.vidioc_try_encoder_cmd		= v4l2_m2m_ioctl_try_encoder_cmd,
798 };
799 
vb2ops_venc_queue_setup(struct vb2_queue * vq,unsigned int * nbuffers,unsigned int * nplanes,unsigned int sizes[],struct device * alloc_devs[])800 static int vb2ops_venc_queue_setup(struct vb2_queue *vq,
801 				   unsigned int *nbuffers,
802 				   unsigned int *nplanes,
803 				   unsigned int sizes[],
804 				   struct device *alloc_devs[])
805 {
806 	struct mtk_vcodec_ctx *ctx = vb2_get_drv_priv(vq);
807 	struct mtk_q_data *q_data;
808 	unsigned int i;
809 
810 	q_data = mtk_venc_get_q_data(ctx, vq->type);
811 
812 	if (q_data == NULL)
813 		return -EINVAL;
814 
815 	if (*nplanes) {
816 		for (i = 0; i < *nplanes; i++)
817 			if (sizes[i] < q_data->sizeimage[i])
818 				return -EINVAL;
819 	} else {
820 		*nplanes = q_data->fmt->num_planes;
821 		for (i = 0; i < *nplanes; i++)
822 			sizes[i] = q_data->sizeimage[i];
823 	}
824 
825 	return 0;
826 }
827 
vb2ops_venc_buf_prepare(struct vb2_buffer * vb)828 static int vb2ops_venc_buf_prepare(struct vb2_buffer *vb)
829 {
830 	struct mtk_vcodec_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
831 	struct mtk_q_data *q_data;
832 	int i;
833 
834 	q_data = mtk_venc_get_q_data(ctx, vb->vb2_queue->type);
835 
836 	for (i = 0; i < q_data->fmt->num_planes; i++) {
837 		if (vb2_plane_size(vb, i) < q_data->sizeimage[i]) {
838 			mtk_v4l2_err("data will not fit into plane %d (%lu < %d)",
839 				i, vb2_plane_size(vb, i),
840 				q_data->sizeimage[i]);
841 			return -EINVAL;
842 		}
843 	}
844 
845 	return 0;
846 }
847 
vb2ops_venc_buf_queue(struct vb2_buffer * vb)848 static void vb2ops_venc_buf_queue(struct vb2_buffer *vb)
849 {
850 	struct mtk_vcodec_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
851 	struct vb2_v4l2_buffer *vb2_v4l2 =
852 			container_of(vb, struct vb2_v4l2_buffer, vb2_buf);
853 
854 	struct mtk_video_enc_buf *mtk_buf =
855 			container_of(vb2_v4l2, struct mtk_video_enc_buf,
856 				     m2m_buf.vb);
857 
858 	if ((vb->vb2_queue->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) &&
859 	    (ctx->param_change != MTK_ENCODE_PARAM_NONE)) {
860 		mtk_v4l2_debug(1, "[%d] Before id=%d encode parameter change %x",
861 			       ctx->id,
862 			       vb2_v4l2->vb2_buf.index,
863 			       ctx->param_change);
864 		mtk_buf->param_change = ctx->param_change;
865 		mtk_buf->enc_params = ctx->enc_params;
866 		ctx->param_change = MTK_ENCODE_PARAM_NONE;
867 	}
868 
869 	v4l2_m2m_buf_queue(ctx->m2m_ctx, to_vb2_v4l2_buffer(vb));
870 }
871 
vb2ops_venc_start_streaming(struct vb2_queue * q,unsigned int count)872 static int vb2ops_venc_start_streaming(struct vb2_queue *q, unsigned int count)
873 {
874 	struct mtk_vcodec_ctx *ctx = vb2_get_drv_priv(q);
875 	struct venc_enc_param param;
876 	int ret, pm_ret;
877 	int i;
878 
879 	/* Once state turn into MTK_STATE_ABORT, we need stop_streaming
880 	  * to clear it
881 	  */
882 	if ((ctx->state == MTK_STATE_ABORT) || (ctx->state == MTK_STATE_FREE)) {
883 		ret = -EIO;
884 		goto err_start_stream;
885 	}
886 
887 	/* Do the initialization when both start_streaming have been called */
888 	if (V4L2_TYPE_IS_OUTPUT(q->type)) {
889 		if (!vb2_start_streaming_called(&ctx->m2m_ctx->cap_q_ctx.q))
890 			return 0;
891 	} else {
892 		if (!vb2_start_streaming_called(&ctx->m2m_ctx->out_q_ctx.q))
893 			return 0;
894 	}
895 
896 	ret = pm_runtime_resume_and_get(&ctx->dev->plat_dev->dev);
897 	if (ret < 0) {
898 		mtk_v4l2_err("pm_runtime_resume_and_get fail %d", ret);
899 		goto err_start_stream;
900 	}
901 
902 	mtk_venc_set_param(ctx, &param);
903 	ret = venc_if_set_param(ctx, VENC_SET_PARAM_ENC, &param);
904 	if (ret) {
905 		mtk_v4l2_err("venc_if_set_param failed=%d", ret);
906 		ctx->state = MTK_STATE_ABORT;
907 		goto err_set_param;
908 	}
909 	ctx->param_change = MTK_ENCODE_PARAM_NONE;
910 
911 	if ((ctx->q_data[MTK_Q_DATA_DST].fmt->fourcc == V4L2_PIX_FMT_H264) &&
912 	    (ctx->enc_params.seq_hdr_mode !=
913 				V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE)) {
914 		ret = venc_if_set_param(ctx,
915 					VENC_SET_PARAM_PREPEND_HEADER,
916 					NULL);
917 		if (ret) {
918 			mtk_v4l2_err("venc_if_set_param failed=%d", ret);
919 			ctx->state = MTK_STATE_ABORT;
920 			goto err_set_param;
921 		}
922 		ctx->state = MTK_STATE_HEADER;
923 	}
924 
925 	return 0;
926 
927 err_set_param:
928 	pm_ret = pm_runtime_put(&ctx->dev->plat_dev->dev);
929 	if (pm_ret < 0)
930 		mtk_v4l2_err("pm_runtime_put fail %d", pm_ret);
931 
932 err_start_stream:
933 	for (i = 0; i < q->num_buffers; ++i) {
934 		struct vb2_buffer *buf = vb2_get_buffer(q, i);
935 
936 		/*
937 		 * FIXME: This check is not needed as only active buffers
938 		 * can be marked as done.
939 		 */
940 		if (buf->state == VB2_BUF_STATE_ACTIVE) {
941 			mtk_v4l2_debug(0, "[%d] id=%d, type=%d, %d -> VB2_BUF_STATE_QUEUED",
942 					ctx->id, i, q->type,
943 					(int)buf->state);
944 			v4l2_m2m_buf_done(to_vb2_v4l2_buffer(buf),
945 					  VB2_BUF_STATE_QUEUED);
946 		}
947 	}
948 
949 	return ret;
950 }
951 
vb2ops_venc_stop_streaming(struct vb2_queue * q)952 static void vb2ops_venc_stop_streaming(struct vb2_queue *q)
953 {
954 	struct mtk_vcodec_ctx *ctx = vb2_get_drv_priv(q);
955 	struct vb2_v4l2_buffer *src_buf, *dst_buf;
956 	int ret;
957 
958 	mtk_v4l2_debug(2, "[%d]-> type=%d", ctx->id, q->type);
959 
960 	if (q->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
961 		while ((dst_buf = v4l2_m2m_dst_buf_remove(ctx->m2m_ctx))) {
962 			dst_buf->vb2_buf.planes[0].bytesused = 0;
963 			v4l2_m2m_buf_done(dst_buf, VB2_BUF_STATE_ERROR);
964 		}
965 		/* STREAMOFF on the CAPTURE queue completes any ongoing flush */
966 		if (ctx->is_flushing) {
967 			struct v4l2_m2m_buffer *b, *n;
968 
969 			mtk_v4l2_debug(1, "STREAMOFF called while flushing");
970 			/*
971 			 * STREAMOFF could be called before the flush buffer is
972 			 * dequeued. Check whether empty flush buf is still in
973 			 * queue before removing it.
974 			 */
975 			v4l2_m2m_for_each_src_buf_safe(ctx->m2m_ctx, b, n) {
976 				if (b == &ctx->empty_flush_buf) {
977 					v4l2_m2m_src_buf_remove_by_buf(ctx->m2m_ctx, &b->vb);
978 					break;
979 				}
980 			}
981 			ctx->is_flushing = false;
982 		}
983 	} else {
984 		while ((src_buf = v4l2_m2m_src_buf_remove(ctx->m2m_ctx))) {
985 			if (src_buf != &ctx->empty_flush_buf.vb)
986 				v4l2_m2m_buf_done(src_buf, VB2_BUF_STATE_ERROR);
987 		}
988 		if (ctx->is_flushing) {
989 			/*
990 			 * If we are in the middle of a flush, put the flush
991 			 * buffer back into the queue so the next CAPTURE
992 			 * buffer gets returned with the LAST flag set.
993 			 */
994 			v4l2_m2m_buf_queue(ctx->m2m_ctx,
995 					   &ctx->empty_flush_buf.vb);
996 		}
997 	}
998 
999 	if ((q->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE &&
1000 	     vb2_is_streaming(&ctx->m2m_ctx->out_q_ctx.q)) ||
1001 	    (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE &&
1002 	     vb2_is_streaming(&ctx->m2m_ctx->cap_q_ctx.q))) {
1003 		mtk_v4l2_debug(1, "[%d]-> q type %d out=%d cap=%d",
1004 			       ctx->id, q->type,
1005 			       vb2_is_streaming(&ctx->m2m_ctx->out_q_ctx.q),
1006 			       vb2_is_streaming(&ctx->m2m_ctx->cap_q_ctx.q));
1007 		return;
1008 	}
1009 
1010 	/* Release the encoder if both streams are stopped. */
1011 	ret = venc_if_deinit(ctx);
1012 	if (ret)
1013 		mtk_v4l2_err("venc_if_deinit failed=%d", ret);
1014 
1015 	ret = pm_runtime_put(&ctx->dev->plat_dev->dev);
1016 	if (ret < 0)
1017 		mtk_v4l2_err("pm_runtime_put fail %d", ret);
1018 
1019 	ctx->state = MTK_STATE_FREE;
1020 }
1021 
vb2ops_venc_buf_out_validate(struct vb2_buffer * vb)1022 static int vb2ops_venc_buf_out_validate(struct vb2_buffer *vb)
1023 {
1024 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1025 
1026 	vbuf->field = V4L2_FIELD_NONE;
1027 	return 0;
1028 }
1029 
1030 static const struct vb2_ops mtk_venc_vb2_ops = {
1031 	.queue_setup		= vb2ops_venc_queue_setup,
1032 	.buf_out_validate	= vb2ops_venc_buf_out_validate,
1033 	.buf_prepare		= vb2ops_venc_buf_prepare,
1034 	.buf_queue		= vb2ops_venc_buf_queue,
1035 	.wait_prepare		= vb2_ops_wait_prepare,
1036 	.wait_finish		= vb2_ops_wait_finish,
1037 	.start_streaming	= vb2ops_venc_start_streaming,
1038 	.stop_streaming		= vb2ops_venc_stop_streaming,
1039 };
1040 
mtk_venc_encode_header(void * priv)1041 static int mtk_venc_encode_header(void *priv)
1042 {
1043 	struct mtk_vcodec_ctx *ctx = priv;
1044 	int ret;
1045 	struct vb2_v4l2_buffer *src_buf, *dst_buf;
1046 	struct mtk_vcodec_mem bs_buf;
1047 	struct venc_done_result enc_result;
1048 
1049 	dst_buf = v4l2_m2m_dst_buf_remove(ctx->m2m_ctx);
1050 	if (!dst_buf) {
1051 		mtk_v4l2_debug(1, "No dst buffer");
1052 		return -EINVAL;
1053 	}
1054 
1055 	bs_buf.va = vb2_plane_vaddr(&dst_buf->vb2_buf, 0);
1056 	bs_buf.dma_addr = vb2_dma_contig_plane_dma_addr(&dst_buf->vb2_buf, 0);
1057 	bs_buf.size = (size_t)dst_buf->vb2_buf.planes[0].length;
1058 
1059 	mtk_v4l2_debug(1,
1060 			"[%d] buf id=%d va=0x%p dma_addr=0x%llx size=%zu",
1061 			ctx->id,
1062 			dst_buf->vb2_buf.index, bs_buf.va,
1063 			(u64)bs_buf.dma_addr,
1064 			bs_buf.size);
1065 
1066 	ret = venc_if_encode(ctx,
1067 			VENC_START_OPT_ENCODE_SEQUENCE_HEADER,
1068 			NULL, &bs_buf, &enc_result);
1069 
1070 	if (ret) {
1071 		dst_buf->vb2_buf.planes[0].bytesused = 0;
1072 		ctx->state = MTK_STATE_ABORT;
1073 		v4l2_m2m_buf_done(dst_buf, VB2_BUF_STATE_ERROR);
1074 		mtk_v4l2_err("venc_if_encode failed=%d", ret);
1075 		return -EINVAL;
1076 	}
1077 	src_buf = v4l2_m2m_next_src_buf(ctx->m2m_ctx);
1078 	if (src_buf) {
1079 		dst_buf->vb2_buf.timestamp = src_buf->vb2_buf.timestamp;
1080 		dst_buf->timecode = src_buf->timecode;
1081 	} else {
1082 		mtk_v4l2_err("No timestamp for the header buffer.");
1083 	}
1084 
1085 	ctx->state = MTK_STATE_HEADER;
1086 	dst_buf->vb2_buf.planes[0].bytesused = enc_result.bs_size;
1087 	v4l2_m2m_buf_done(dst_buf, VB2_BUF_STATE_DONE);
1088 
1089 	return 0;
1090 }
1091 
mtk_venc_param_change(struct mtk_vcodec_ctx * ctx)1092 static int mtk_venc_param_change(struct mtk_vcodec_ctx *ctx)
1093 {
1094 	struct venc_enc_param enc_prm;
1095 	struct vb2_v4l2_buffer *vb2_v4l2 = v4l2_m2m_next_src_buf(ctx->m2m_ctx);
1096 	struct mtk_video_enc_buf *mtk_buf;
1097 	int ret = 0;
1098 
1099 	/* Don't upcast the empty flush buffer */
1100 	if (vb2_v4l2 == &ctx->empty_flush_buf.vb)
1101 		return 0;
1102 
1103 	mtk_buf = container_of(vb2_v4l2, struct mtk_video_enc_buf, m2m_buf.vb);
1104 
1105 	memset(&enc_prm, 0, sizeof(enc_prm));
1106 	if (mtk_buf->param_change == MTK_ENCODE_PARAM_NONE)
1107 		return 0;
1108 
1109 	if (mtk_buf->param_change & MTK_ENCODE_PARAM_BITRATE) {
1110 		enc_prm.bitrate = mtk_buf->enc_params.bitrate;
1111 		mtk_v4l2_debug(1, "[%d] id=%d, change param br=%d",
1112 				ctx->id,
1113 				vb2_v4l2->vb2_buf.index,
1114 				enc_prm.bitrate);
1115 		ret |= venc_if_set_param(ctx,
1116 					 VENC_SET_PARAM_ADJUST_BITRATE,
1117 					 &enc_prm);
1118 	}
1119 	if (!ret && mtk_buf->param_change & MTK_ENCODE_PARAM_FRAMERATE) {
1120 		enc_prm.frm_rate = mtk_buf->enc_params.framerate_num /
1121 				   mtk_buf->enc_params.framerate_denom;
1122 		mtk_v4l2_debug(1, "[%d] id=%d, change param fr=%d",
1123 			       ctx->id,
1124 			       vb2_v4l2->vb2_buf.index,
1125 			       enc_prm.frm_rate);
1126 		ret |= venc_if_set_param(ctx,
1127 					 VENC_SET_PARAM_ADJUST_FRAMERATE,
1128 					 &enc_prm);
1129 	}
1130 	if (!ret && mtk_buf->param_change & MTK_ENCODE_PARAM_GOP_SIZE) {
1131 		enc_prm.gop_size = mtk_buf->enc_params.gop_size;
1132 		mtk_v4l2_debug(1, "change param intra period=%d",
1133 			       enc_prm.gop_size);
1134 		ret |= venc_if_set_param(ctx,
1135 					 VENC_SET_PARAM_GOP_SIZE,
1136 					 &enc_prm);
1137 	}
1138 	if (!ret && mtk_buf->param_change & MTK_ENCODE_PARAM_FORCE_INTRA) {
1139 		mtk_v4l2_debug(1, "[%d] id=%d, change param force I=%d",
1140 				ctx->id,
1141 				vb2_v4l2->vb2_buf.index,
1142 				mtk_buf->enc_params.force_intra);
1143 		if (mtk_buf->enc_params.force_intra)
1144 			ret |= venc_if_set_param(ctx,
1145 						 VENC_SET_PARAM_FORCE_INTRA,
1146 						 NULL);
1147 	}
1148 
1149 	mtk_buf->param_change = MTK_ENCODE_PARAM_NONE;
1150 
1151 	if (ret) {
1152 		ctx->state = MTK_STATE_ABORT;
1153 		mtk_v4l2_err("venc_if_set_param %d failed=%d",
1154 				mtk_buf->param_change, ret);
1155 		return -1;
1156 	}
1157 
1158 	return 0;
1159 }
1160 
1161 /*
1162  * v4l2_m2m_streamoff() holds dev_mutex and waits mtk_venc_worker()
1163  * to call v4l2_m2m_job_finish().
1164  * If mtk_venc_worker() tries to acquire dev_mutex, it will deadlock.
1165  * So this function must not try to acquire dev->dev_mutex.
1166  * This means v4l2 ioctls and mtk_venc_worker() can run at the same time.
1167  * mtk_venc_worker() should be carefully implemented to avoid bugs.
1168  */
mtk_venc_worker(struct work_struct * work)1169 static void mtk_venc_worker(struct work_struct *work)
1170 {
1171 	struct mtk_vcodec_ctx *ctx = container_of(work, struct mtk_vcodec_ctx,
1172 				    encode_work);
1173 	struct vb2_v4l2_buffer *src_buf, *dst_buf;
1174 	struct venc_frm_buf frm_buf;
1175 	struct mtk_vcodec_mem bs_buf;
1176 	struct venc_done_result enc_result;
1177 	int ret, i;
1178 
1179 	/* check dst_buf, dst_buf may be removed in device_run
1180 	 * to stored encdoe header so we need check dst_buf and
1181 	 * call job_finish here to prevent recursion
1182 	 */
1183 	dst_buf = v4l2_m2m_dst_buf_remove(ctx->m2m_ctx);
1184 	if (!dst_buf) {
1185 		v4l2_m2m_job_finish(ctx->dev->m2m_dev_enc, ctx->m2m_ctx);
1186 		return;
1187 	}
1188 
1189 	src_buf = v4l2_m2m_src_buf_remove(ctx->m2m_ctx);
1190 
1191 	/*
1192 	 * If we see the flush buffer, send an empty buffer with the LAST flag
1193 	 * to the client. is_flushing will be reset at the time the buffer
1194 	 * is dequeued.
1195 	 */
1196 	if (src_buf == &ctx->empty_flush_buf.vb) {
1197 		vb2_set_plane_payload(&dst_buf->vb2_buf, 0, 0);
1198 		dst_buf->flags |= V4L2_BUF_FLAG_LAST;
1199 		v4l2_m2m_buf_done(dst_buf, VB2_BUF_STATE_DONE);
1200 		v4l2_m2m_job_finish(ctx->dev->m2m_dev_enc, ctx->m2m_ctx);
1201 		return;
1202 	}
1203 
1204 	memset(&frm_buf, 0, sizeof(frm_buf));
1205 	for (i = 0; i < src_buf->vb2_buf.num_planes ; i++) {
1206 		frm_buf.fb_addr[i].dma_addr =
1207 				vb2_dma_contig_plane_dma_addr(&src_buf->vb2_buf, i);
1208 		frm_buf.fb_addr[i].size =
1209 				(size_t)src_buf->vb2_buf.planes[i].length;
1210 	}
1211 	bs_buf.va = vb2_plane_vaddr(&dst_buf->vb2_buf, 0);
1212 	bs_buf.dma_addr = vb2_dma_contig_plane_dma_addr(&dst_buf->vb2_buf, 0);
1213 	bs_buf.size = (size_t)dst_buf->vb2_buf.planes[0].length;
1214 
1215 	mtk_v4l2_debug(2,
1216 			"Framebuf PA=%llx Size=0x%zx;PA=0x%llx Size=0x%zx;PA=0x%llx Size=%zu",
1217 			(u64)frm_buf.fb_addr[0].dma_addr,
1218 			frm_buf.fb_addr[0].size,
1219 			(u64)frm_buf.fb_addr[1].dma_addr,
1220 			frm_buf.fb_addr[1].size,
1221 			(u64)frm_buf.fb_addr[2].dma_addr,
1222 			frm_buf.fb_addr[2].size);
1223 
1224 	ret = venc_if_encode(ctx, VENC_START_OPT_ENCODE_FRAME,
1225 			     &frm_buf, &bs_buf, &enc_result);
1226 
1227 	dst_buf->vb2_buf.timestamp = src_buf->vb2_buf.timestamp;
1228 	dst_buf->timecode = src_buf->timecode;
1229 
1230 	if (enc_result.is_key_frm)
1231 		dst_buf->flags |= V4L2_BUF_FLAG_KEYFRAME;
1232 
1233 	if (ret) {
1234 		v4l2_m2m_buf_done(src_buf, VB2_BUF_STATE_ERROR);
1235 		dst_buf->vb2_buf.planes[0].bytesused = 0;
1236 		v4l2_m2m_buf_done(dst_buf, VB2_BUF_STATE_ERROR);
1237 		mtk_v4l2_err("venc_if_encode failed=%d", ret);
1238 	} else {
1239 		v4l2_m2m_buf_done(src_buf, VB2_BUF_STATE_DONE);
1240 		dst_buf->vb2_buf.planes[0].bytesused = enc_result.bs_size;
1241 		v4l2_m2m_buf_done(dst_buf, VB2_BUF_STATE_DONE);
1242 		mtk_v4l2_debug(2, "venc_if_encode bs size=%d",
1243 				 enc_result.bs_size);
1244 	}
1245 
1246 	v4l2_m2m_job_finish(ctx->dev->m2m_dev_enc, ctx->m2m_ctx);
1247 
1248 	mtk_v4l2_debug(1, "<=== src_buf[%d] dst_buf[%d] venc_if_encode ret=%d Size=%u===>",
1249 			src_buf->vb2_buf.index, dst_buf->vb2_buf.index, ret,
1250 			enc_result.bs_size);
1251 }
1252 
m2mops_venc_device_run(void * priv)1253 static void m2mops_venc_device_run(void *priv)
1254 {
1255 	struct mtk_vcodec_ctx *ctx = priv;
1256 
1257 	if ((ctx->q_data[MTK_Q_DATA_DST].fmt->fourcc == V4L2_PIX_FMT_H264) &&
1258 	    (ctx->state != MTK_STATE_HEADER)) {
1259 		/* encode h264 sps/pps header */
1260 		mtk_venc_encode_header(ctx);
1261 		queue_work(ctx->dev->encode_workqueue, &ctx->encode_work);
1262 		return;
1263 	}
1264 
1265 	mtk_venc_param_change(ctx);
1266 	queue_work(ctx->dev->encode_workqueue, &ctx->encode_work);
1267 }
1268 
m2mops_venc_job_ready(void * m2m_priv)1269 static int m2mops_venc_job_ready(void *m2m_priv)
1270 {
1271 	struct mtk_vcodec_ctx *ctx = m2m_priv;
1272 
1273 	if (ctx->state == MTK_STATE_ABORT || ctx->state == MTK_STATE_FREE) {
1274 		mtk_v4l2_debug(3, "[%d]Not ready: state=0x%x.",
1275 			       ctx->id, ctx->state);
1276 		return 0;
1277 	}
1278 
1279 	return 1;
1280 }
1281 
m2mops_venc_job_abort(void * priv)1282 static void m2mops_venc_job_abort(void *priv)
1283 {
1284 	struct mtk_vcodec_ctx *ctx = priv;
1285 
1286 	ctx->state = MTK_STATE_ABORT;
1287 }
1288 
1289 const struct v4l2_m2m_ops mtk_venc_m2m_ops = {
1290 	.device_run	= m2mops_venc_device_run,
1291 	.job_ready	= m2mops_venc_job_ready,
1292 	.job_abort	= m2mops_venc_job_abort,
1293 };
1294 
mtk_vcodec_enc_set_default_params(struct mtk_vcodec_ctx * ctx)1295 void mtk_vcodec_enc_set_default_params(struct mtk_vcodec_ctx *ctx)
1296 {
1297 	struct mtk_q_data *q_data;
1298 
1299 	ctx->m2m_ctx->q_lock = &ctx->dev->dev_mutex;
1300 	ctx->fh.m2m_ctx = ctx->m2m_ctx;
1301 	ctx->fh.ctrl_handler = &ctx->ctrl_hdl;
1302 	INIT_WORK(&ctx->encode_work, mtk_venc_worker);
1303 
1304 	ctx->colorspace = V4L2_COLORSPACE_REC709;
1305 	ctx->ycbcr_enc = V4L2_YCBCR_ENC_DEFAULT;
1306 	ctx->quantization = V4L2_QUANTIZATION_DEFAULT;
1307 	ctx->xfer_func = V4L2_XFER_FUNC_DEFAULT;
1308 
1309 	q_data = &ctx->q_data[MTK_Q_DATA_SRC];
1310 	memset(q_data, 0, sizeof(struct mtk_q_data));
1311 	q_data->visible_width = DFT_CFG_WIDTH;
1312 	q_data->visible_height = DFT_CFG_HEIGHT;
1313 	q_data->coded_width = DFT_CFG_WIDTH;
1314 	q_data->coded_height = DFT_CFG_HEIGHT;
1315 	q_data->field = V4L2_FIELD_NONE;
1316 
1317 	q_data->fmt = &ctx->dev->venc_pdata->output_formats[0];
1318 
1319 	v4l_bound_align_image(&q_data->coded_width,
1320 				MTK_VENC_MIN_W,
1321 				MTK_VENC_HD_MAX_W, 4,
1322 				&q_data->coded_height,
1323 				MTK_VENC_MIN_H,
1324 				MTK_VENC_HD_MAX_H, 5, 6);
1325 
1326 	if (q_data->coded_width < DFT_CFG_WIDTH &&
1327 		(q_data->coded_width + 16) <= MTK_VENC_HD_MAX_W)
1328 		q_data->coded_width += 16;
1329 	if (q_data->coded_height < DFT_CFG_HEIGHT &&
1330 		(q_data->coded_height + 32) <= MTK_VENC_HD_MAX_H)
1331 		q_data->coded_height += 32;
1332 
1333 	q_data->sizeimage[0] =
1334 		q_data->coded_width * q_data->coded_height+
1335 		((ALIGN(q_data->coded_width, 16) * 2) * 16);
1336 	q_data->bytesperline[0] = q_data->coded_width;
1337 	q_data->sizeimage[1] =
1338 		(q_data->coded_width * q_data->coded_height) / 2 +
1339 		(ALIGN(q_data->coded_width, 16) * 16);
1340 	q_data->bytesperline[1] = q_data->coded_width;
1341 
1342 	q_data = &ctx->q_data[MTK_Q_DATA_DST];
1343 	memset(q_data, 0, sizeof(struct mtk_q_data));
1344 	q_data->coded_width = DFT_CFG_WIDTH;
1345 	q_data->coded_height = DFT_CFG_HEIGHT;
1346 	q_data->fmt = &ctx->dev->venc_pdata->capture_formats[0];
1347 	q_data->field = V4L2_FIELD_NONE;
1348 	ctx->q_data[MTK_Q_DATA_DST].sizeimage[0] =
1349 		DFT_CFG_WIDTH * DFT_CFG_HEIGHT;
1350 	ctx->q_data[MTK_Q_DATA_DST].bytesperline[0] = 0;
1351 
1352 	ctx->enc_params.framerate_num = MTK_DEFAULT_FRAMERATE_NUM;
1353 	ctx->enc_params.framerate_denom = MTK_DEFAULT_FRAMERATE_DENOM;
1354 }
1355 
mtk_vcodec_enc_ctrls_setup(struct mtk_vcodec_ctx * ctx)1356 int mtk_vcodec_enc_ctrls_setup(struct mtk_vcodec_ctx *ctx)
1357 {
1358 	const struct v4l2_ctrl_ops *ops = &mtk_vcodec_enc_ctrl_ops;
1359 	struct v4l2_ctrl_handler *handler = &ctx->ctrl_hdl;
1360 	u8 h264_max_level;
1361 
1362 	if (ctx->dev->enc_capability & MTK_VENC_4K_CAPABILITY_ENABLE)
1363 		h264_max_level = V4L2_MPEG_VIDEO_H264_LEVEL_5_1;
1364 	else
1365 		h264_max_level = V4L2_MPEG_VIDEO_H264_LEVEL_4_2;
1366 
1367 	v4l2_ctrl_handler_init(handler, MTK_MAX_CTRLS_HINT);
1368 
1369 	v4l2_ctrl_new_std(handler, ops, V4L2_CID_MIN_BUFFERS_FOR_OUTPUT,
1370 			  1, 1, 1, 1);
1371 	v4l2_ctrl_new_std(handler, ops, V4L2_CID_MPEG_VIDEO_BITRATE,
1372 			  ctx->dev->venc_pdata->min_bitrate,
1373 			  ctx->dev->venc_pdata->max_bitrate, 1, 4000000);
1374 	v4l2_ctrl_new_std(handler, ops, V4L2_CID_MPEG_VIDEO_B_FRAMES,
1375 			0, 2, 1, 0);
1376 	v4l2_ctrl_new_std(handler, ops, V4L2_CID_MPEG_VIDEO_FRAME_RC_ENABLE,
1377 			0, 1, 1, 1);
1378 	v4l2_ctrl_new_std(handler, ops, V4L2_CID_MPEG_VIDEO_H264_MAX_QP,
1379 			0, 51, 1, 51);
1380 	v4l2_ctrl_new_std(handler, ops, V4L2_CID_MPEG_VIDEO_H264_I_PERIOD,
1381 			0, 65535, 1, 0);
1382 	v4l2_ctrl_new_std(handler, ops, V4L2_CID_MPEG_VIDEO_GOP_SIZE,
1383 			0, 65535, 1, 0);
1384 	v4l2_ctrl_new_std(handler, ops, V4L2_CID_MPEG_VIDEO_MB_RC_ENABLE,
1385 			0, 1, 1, 0);
1386 	v4l2_ctrl_new_std(handler, ops, V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME,
1387 			0, 0, 0, 0);
1388 	v4l2_ctrl_new_std_menu(handler, ops,
1389 			V4L2_CID_MPEG_VIDEO_HEADER_MODE,
1390 			V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_1ST_FRAME,
1391 			0, V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE);
1392 	v4l2_ctrl_new_std_menu(handler, ops, V4L2_CID_MPEG_VIDEO_H264_PROFILE,
1393 			V4L2_MPEG_VIDEO_H264_PROFILE_HIGH,
1394 			0, V4L2_MPEG_VIDEO_H264_PROFILE_HIGH);
1395 	v4l2_ctrl_new_std_menu(handler, ops, V4L2_CID_MPEG_VIDEO_H264_LEVEL,
1396 			       h264_max_level,
1397 			       0, V4L2_MPEG_VIDEO_H264_LEVEL_4_0);
1398 
1399 	if (handler->error) {
1400 		mtk_v4l2_err("Init control handler fail %d",
1401 				handler->error);
1402 		return handler->error;
1403 	}
1404 
1405 	v4l2_ctrl_handler_setup(&ctx->ctrl_hdl);
1406 
1407 	return 0;
1408 }
1409 
mtk_vcodec_enc_queue_init(void * priv,struct vb2_queue * src_vq,struct vb2_queue * dst_vq)1410 int mtk_vcodec_enc_queue_init(void *priv, struct vb2_queue *src_vq,
1411 			      struct vb2_queue *dst_vq)
1412 {
1413 	struct mtk_vcodec_ctx *ctx = priv;
1414 	int ret;
1415 
1416 	/* Note: VB2_USERPTR works with dma-contig because mt8173
1417 	 * support iommu
1418 	 * https://patchwork.kernel.org/patch/8335461/
1419 	 * https://patchwork.kernel.org/patch/7596181/
1420 	 */
1421 	src_vq->type		= V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1422 	src_vq->io_modes	= VB2_DMABUF | VB2_MMAP | VB2_USERPTR;
1423 	src_vq->drv_priv	= ctx;
1424 	src_vq->buf_struct_size = sizeof(struct mtk_video_enc_buf);
1425 	src_vq->ops		= &mtk_venc_vb2_ops;
1426 	src_vq->mem_ops		= &vb2_dma_contig_memops;
1427 	src_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
1428 	src_vq->lock		= &ctx->dev->dev_mutex;
1429 	src_vq->dev		= &ctx->dev->plat_dev->dev;
1430 
1431 	ret = vb2_queue_init(src_vq);
1432 	if (ret)
1433 		return ret;
1434 
1435 	dst_vq->type		= V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1436 	dst_vq->io_modes	= VB2_DMABUF | VB2_MMAP | VB2_USERPTR;
1437 	dst_vq->drv_priv	= ctx;
1438 	dst_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
1439 	dst_vq->ops		= &mtk_venc_vb2_ops;
1440 	dst_vq->mem_ops		= &vb2_dma_contig_memops;
1441 	dst_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
1442 	dst_vq->lock		= &ctx->dev->dev_mutex;
1443 	dst_vq->dev		= &ctx->dev->plat_dev->dev;
1444 
1445 	return vb2_queue_init(dst_vq);
1446 }
1447 
mtk_venc_unlock(struct mtk_vcodec_ctx * ctx)1448 int mtk_venc_unlock(struct mtk_vcodec_ctx *ctx)
1449 {
1450 	struct mtk_vcodec_dev *dev = ctx->dev;
1451 
1452 	mutex_unlock(&dev->enc_mutex);
1453 	return 0;
1454 }
1455 
mtk_venc_lock(struct mtk_vcodec_ctx * ctx)1456 int mtk_venc_lock(struct mtk_vcodec_ctx *ctx)
1457 {
1458 	struct mtk_vcodec_dev *dev = ctx->dev;
1459 
1460 	mutex_lock(&dev->enc_mutex);
1461 	return 0;
1462 }
1463 
mtk_vcodec_enc_release(struct mtk_vcodec_ctx * ctx)1464 void mtk_vcodec_enc_release(struct mtk_vcodec_ctx *ctx)
1465 {
1466 	int ret = venc_if_deinit(ctx);
1467 
1468 	if (ret)
1469 		mtk_v4l2_err("venc_if_deinit failed=%d", ret);
1470 
1471 	ctx->state = MTK_STATE_FREE;
1472 }
1473