2 * Copyright (c) 2019 Guo Yejun
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 * implementing a generic image processing filter using deep learning networks.
26 #include "libavformat/avio.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/pixdesc.h"
29 #include "libavutil/avassert.h"
30 #include "libavutil/imgutils.h"
32 #include "dnn_interface.h"
35 #include "libswscale/swscale.h"
37 typedef struct DnnProcessingContext {
41 DNNBackendType backend_type;
42 char *model_inputname;
43 char *model_outputname;
44 char *backend_options;
47 DNNModule *dnn_module;
50 struct SwsContext *sws_uv_scale;
52 } DnnProcessingContext;
54 #define OFFSET(x) offsetof(DnnProcessingContext, x)
55 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM | AV_OPT_FLAG_VIDEO_PARAM
56 static const AVOption dnn_processing_options[] = {
57 { "dnn_backend", "DNN backend", OFFSET(backend_type), AV_OPT_TYPE_INT, { .i64 = 0 }, INT_MIN, INT_MAX, FLAGS, "backend" },
58 { "native", "native backend flag", 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, 0, 0, FLAGS, "backend" },
59 #if (CONFIG_LIBTENSORFLOW == 1)
60 { "tensorflow", "tensorflow backend flag", 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, 0, 0, FLAGS, "backend" },
62 #if (CONFIG_LIBOPENVINO == 1)
63 { "openvino", "openvino backend flag", 0, AV_OPT_TYPE_CONST, { .i64 = 2 }, 0, 0, FLAGS, "backend" },
65 { "model", "path to model file", OFFSET(model_filename), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, FLAGS },
66 { "input", "input name of the model", OFFSET(model_inputname), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, FLAGS },
67 { "output", "output name of the model", OFFSET(model_outputname), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, FLAGS },
68 { "options", "backend options", OFFSET(backend_options), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, FLAGS },
69 { "async", "use DNN async inference", OFFSET(async), AV_OPT_TYPE_BOOL, { .i64 = 1}, 0, 1, FLAGS},
73 AVFILTER_DEFINE_CLASS(dnn_processing);
75 static av_cold int init(AVFilterContext *context)
77 DnnProcessingContext *ctx = context->priv;
79 if (!ctx->model_filename) {
80 av_log(ctx, AV_LOG_ERROR, "model file for network is not specified\n");
81 return AVERROR(EINVAL);
83 if (!ctx->model_inputname) {
84 av_log(ctx, AV_LOG_ERROR, "input name of the model network is not specified\n");
85 return AVERROR(EINVAL);
87 if (!ctx->model_outputname) {
88 av_log(ctx, AV_LOG_ERROR, "output name of the model network is not specified\n");
89 return AVERROR(EINVAL);
92 ctx->dnn_module = ff_get_dnn_module(ctx->backend_type);
93 if (!ctx->dnn_module) {
94 av_log(ctx, AV_LOG_ERROR, "could not create DNN module for requested backend\n");
95 return AVERROR(ENOMEM);
97 if (!ctx->dnn_module->load_model) {
98 av_log(ctx, AV_LOG_ERROR, "load_model for network is not specified\n");
99 return AVERROR(EINVAL);
102 ctx->model = (ctx->dnn_module->load_model)(ctx->model_filename, ctx->backend_options, context);
104 av_log(ctx, AV_LOG_ERROR, "could not load DNN model\n");
105 return AVERROR(EINVAL);
108 if (!ctx->dnn_module->execute_model_async && ctx->async) {
110 av_log(ctx, AV_LOG_WARNING, "this backend does not support async execution, roll back to sync.\n");
113 #if !HAVE_PTHREAD_CANCEL
116 av_log(ctx, AV_LOG_WARNING, "pthread is not supported, roll back to sync.\n");
123 static int query_formats(AVFilterContext *context)
125 static const enum AVPixelFormat pix_fmts[] = {
126 AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
127 AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAYF32,
128 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
129 AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
133 AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
134 return ff_set_common_formats(context, fmts_list);
137 #define LOG_FORMAT_CHANNEL_MISMATCH() \
138 av_log(ctx, AV_LOG_ERROR, \
139 "the frame's format %s does not match " \
140 "the model input channel %d\n", \
141 av_get_pix_fmt_name(fmt), \
142 model_input->channels);
144 static int check_modelinput_inlink(const DNNData *model_input, const AVFilterLink *inlink)
146 AVFilterContext *ctx = inlink->dst;
147 enum AVPixelFormat fmt = inlink->format;
149 // the design is to add explicit scale filter before this filter
150 if (model_input->height != -1 && model_input->height != inlink->h) {
151 av_log(ctx, AV_LOG_ERROR, "the model requires frame height %d but got %d\n",
152 model_input->height, inlink->h);
155 if (model_input->width != -1 && model_input->width != inlink->w) {
156 av_log(ctx, AV_LOG_ERROR, "the model requires frame width %d but got %d\n",
157 model_input->width, inlink->w);
160 if (model_input->dt != DNN_FLOAT) {
161 av_log(ctx, AV_LOG_ERROR, "only support dnn models with input data type as float32.\n");
166 case AV_PIX_FMT_RGB24:
167 case AV_PIX_FMT_BGR24:
168 if (model_input->channels != 3) {
169 LOG_FORMAT_CHANNEL_MISMATCH();
173 case AV_PIX_FMT_GRAYF32:
174 case AV_PIX_FMT_YUV420P:
175 case AV_PIX_FMT_YUV422P:
176 case AV_PIX_FMT_YUV444P:
177 case AV_PIX_FMT_YUV410P:
178 case AV_PIX_FMT_YUV411P:
179 case AV_PIX_FMT_NV12:
180 if (model_input->channels != 1) {
181 LOG_FORMAT_CHANNEL_MISMATCH();
186 av_log(ctx, AV_LOG_ERROR, "%s not supported.\n", av_get_pix_fmt_name(fmt));
193 static int config_input(AVFilterLink *inlink)
195 AVFilterContext *context = inlink->dst;
196 DnnProcessingContext *ctx = context->priv;
197 DNNReturnType result;
201 result = ctx->model->get_input(ctx->model->model, &model_input, ctx->model_inputname);
202 if (result != DNN_SUCCESS) {
203 av_log(ctx, AV_LOG_ERROR, "could not get input from the model\n");
207 check = check_modelinput_inlink(&model_input, inlink);
215 static av_always_inline int isPlanarYUV(enum AVPixelFormat pix_fmt)
217 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
219 return !(desc->flags & AV_PIX_FMT_FLAG_RGB) && desc->nb_components == 3;
222 static int prepare_uv_scale(AVFilterLink *outlink)
224 AVFilterContext *context = outlink->src;
225 DnnProcessingContext *ctx = context->priv;
226 AVFilterLink *inlink = context->inputs[0];
227 enum AVPixelFormat fmt = inlink->format;
229 if (isPlanarYUV(fmt)) {
230 if (inlink->w != outlink->w || inlink->h != outlink->h) {
231 if (fmt == AV_PIX_FMT_NV12) {
232 ctx->sws_uv_scale = sws_getContext(inlink->w >> 1, inlink->h >> 1, AV_PIX_FMT_YA8,
233 outlink->w >> 1, outlink->h >> 1, AV_PIX_FMT_YA8,
234 SWS_BICUBIC, NULL, NULL, NULL);
235 ctx->sws_uv_height = inlink->h >> 1;
237 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(fmt);
238 int sws_src_h = AV_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
239 int sws_src_w = AV_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
240 int sws_dst_h = AV_CEIL_RSHIFT(outlink->h, desc->log2_chroma_h);
241 int sws_dst_w = AV_CEIL_RSHIFT(outlink->w, desc->log2_chroma_w);
242 ctx->sws_uv_scale = sws_getContext(sws_src_w, sws_src_h, AV_PIX_FMT_GRAY8,
243 sws_dst_w, sws_dst_h, AV_PIX_FMT_GRAY8,
244 SWS_BICUBIC, NULL, NULL, NULL);
245 ctx->sws_uv_height = sws_src_h;
253 static int config_output(AVFilterLink *outlink)
255 AVFilterContext *context = outlink->src;
256 DnnProcessingContext *ctx = context->priv;
257 DNNReturnType result;
258 AVFilterLink *inlink = context->inputs[0];
260 // have a try run in case that the dnn model resize the frame
261 result = ctx->model->get_output(ctx->model->model, ctx->model_inputname, inlink->w, inlink->h,
262 ctx->model_outputname, &outlink->w, &outlink->h);
263 if (result != DNN_SUCCESS) {
264 av_log(ctx, AV_LOG_ERROR, "could not get output from the model\n");
268 prepare_uv_scale(outlink);
273 static int copy_uv_planes(DnnProcessingContext *ctx, AVFrame *out, const AVFrame *in)
275 const AVPixFmtDescriptor *desc;
278 if (!ctx->sws_uv_scale) {
279 av_assert0(in->height == out->height && in->width == out->width);
280 desc = av_pix_fmt_desc_get(in->format);
281 uv_height = AV_CEIL_RSHIFT(in->height, desc->log2_chroma_h);
282 for (int i = 1; i < 3; ++i) {
283 int bytewidth = av_image_get_linesize(in->format, in->width, i);
284 av_image_copy_plane(out->data[i], out->linesize[i],
285 in->data[i], in->linesize[i],
286 bytewidth, uv_height);
288 } else if (in->format == AV_PIX_FMT_NV12) {
289 sws_scale(ctx->sws_uv_scale, (const uint8_t **)(in->data + 1), in->linesize + 1,
290 0, ctx->sws_uv_height, out->data + 1, out->linesize + 1);
292 sws_scale(ctx->sws_uv_scale, (const uint8_t **)(in->data + 1), in->linesize + 1,
293 0, ctx->sws_uv_height, out->data + 1, out->linesize + 1);
294 sws_scale(ctx->sws_uv_scale, (const uint8_t **)(in->data + 2), in->linesize + 2,
295 0, ctx->sws_uv_height, out->data + 2, out->linesize + 2);
301 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
303 AVFilterContext *context = inlink->dst;
304 AVFilterLink *outlink = context->outputs[0];
305 DnnProcessingContext *ctx = context->priv;
306 DNNReturnType dnn_result;
309 out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
312 return AVERROR(ENOMEM);
314 av_frame_copy_props(out, in);
316 dnn_result = (ctx->dnn_module->execute_model)(ctx->model, ctx->model_inputname, in,
317 (const char **)&ctx->model_outputname, 1, out);
318 if (dnn_result != DNN_SUCCESS){
319 av_log(ctx, AV_LOG_ERROR, "failed to execute model\n");
325 if (isPlanarYUV(in->format))
326 copy_uv_planes(ctx, out, in);
329 return ff_filter_frame(outlink, out);
332 static int activate_sync(AVFilterContext *filter_ctx)
334 AVFilterLink *inlink = filter_ctx->inputs[0];
335 AVFilterLink *outlink = filter_ctx->outputs[0];
341 FF_FILTER_FORWARD_STATUS_BACK(outlink, inlink);
344 // drain all input frames
345 ret = ff_inlink_consume_frame(inlink, &in);
349 ret = filter_frame(inlink, in);
356 // if frame got, schedule to next filter
360 if (ff_inlink_acknowledge_status(inlink, &status, &pts)) {
361 if (status == AVERROR_EOF) {
362 ff_outlink_set_status(outlink, status, pts);
367 FF_FILTER_FORWARD_WANTED(outlink, inlink);
369 return FFERROR_NOT_READY;
372 static int activate_async(AVFilterContext *filter_ctx)
374 AVFilterLink *inlink = filter_ctx->inputs[0];
375 AVFilterLink *outlink = filter_ctx->outputs[0];
376 DnnProcessingContext *ctx = (DnnProcessingContext *)filter_ctx->priv;
377 AVFrame *in = NULL, *out = NULL;
383 FF_FILTER_FORWARD_STATUS_BACK(outlink, inlink);
386 // drain all input frames
387 ret = ff_inlink_consume_frame(inlink, &in);
391 out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
394 return AVERROR(ENOMEM);
396 av_frame_copy_props(out, in);
397 if ((ctx->dnn_module->execute_model_async)(ctx->model, ctx->model_inputname, in,
398 (const char **)&ctx->model_outputname, 1, out) != DNN_SUCCESS) {
399 return FFERROR_NOT_READY;
404 // drain all processed frames
406 AVFrame *in_frame = NULL;
407 AVFrame *out_frame = NULL;
408 async_state = (ctx->dnn_module->get_async_result)(ctx->model, &in_frame, &out_frame);
410 if (isPlanarYUV(in_frame->format))
411 copy_uv_planes(ctx, out_frame, in_frame);
412 av_frame_free(&in_frame);
413 ret = ff_filter_frame(outlink, out_frame);
418 } while (async_state == DAST_SUCCESS);
420 // if frame got, schedule to next filter
424 if (ff_inlink_acknowledge_status(inlink, &status, &pts)) {
425 if (status == AVERROR_EOF) {
426 ff_outlink_set_status(outlink, status, pts);
431 FF_FILTER_FORWARD_WANTED(outlink, inlink);
433 return FFERROR_NOT_READY;
436 static int activate(AVFilterContext *filter_ctx)
438 DnnProcessingContext *ctx = filter_ctx->priv;
441 return activate_async(filter_ctx);
443 return activate_sync(filter_ctx);
446 static av_cold void uninit(AVFilterContext *ctx)
448 DnnProcessingContext *context = ctx->priv;
450 sws_freeContext(context->sws_uv_scale);
452 if (context->dnn_module)
453 (context->dnn_module->free_model)(&context->model);
455 av_freep(&context->dnn_module);
458 static const AVFilterPad dnn_processing_inputs[] = {
461 .type = AVMEDIA_TYPE_VIDEO,
462 .config_props = config_input,
467 static const AVFilterPad dnn_processing_outputs[] = {
470 .type = AVMEDIA_TYPE_VIDEO,
471 .config_props = config_output,
476 AVFilter ff_vf_dnn_processing = {
477 .name = "dnn_processing",
478 .description = NULL_IF_CONFIG_SMALL("Apply DNN processing filter to the input."),
479 .priv_size = sizeof(DnnProcessingContext),
482 .query_formats = query_formats,
483 .inputs = dnn_processing_inputs,
484 .outputs = dnn_processing_outputs,
485 .priv_class = &dnn_processing_class,
486 .activate = activate,