]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_dnn_processing.c
dnn: add NV12 pixel format support
[ffmpeg] / libavfilter / vf_dnn_processing.c
1 /*
2  * Copyright (c) 2019 Guo Yejun
3  *
4  * This file is part of FFmpeg.
5  *
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.
10  *
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.
15  *
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
19  */
20
21 /**
22  * @file
23  * implementing a generic image processing filter using deep learning networks.
24  */
25
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"
31 #include "avfilter.h"
32 #include "dnn_interface.h"
33 #include "formats.h"
34 #include "internal.h"
35 #include "libswscale/swscale.h"
36
37 typedef struct DnnProcessingContext {
38     const AVClass *class;
39
40     char *model_filename;
41     DNNBackendType backend_type;
42     char *model_inputname;
43     char *model_outputname;
44     char *backend_options;
45
46     DNNModule *dnn_module;
47     DNNModel *model;
48
49     struct SwsContext *sws_uv_scale;
50     int sws_uv_height;
51 } DnnProcessingContext;
52
53 #define OFFSET(x) offsetof(DnnProcessingContext, x)
54 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM | AV_OPT_FLAG_VIDEO_PARAM
55 static const AVOption dnn_processing_options[] = {
56     { "dnn_backend", "DNN backend",                OFFSET(backend_type),     AV_OPT_TYPE_INT,       { .i64 = 0 },    INT_MIN, INT_MAX, FLAGS, "backend" },
57     { "native",      "native backend flag",        0,                        AV_OPT_TYPE_CONST,     { .i64 = 0 },    0, 0, FLAGS, "backend" },
58 #if (CONFIG_LIBTENSORFLOW == 1)
59     { "tensorflow",  "tensorflow backend flag",    0,                        AV_OPT_TYPE_CONST,     { .i64 = 1 },    0, 0, FLAGS, "backend" },
60 #endif
61 #if (CONFIG_LIBOPENVINO == 1)
62     { "openvino",    "openvino backend flag",      0,                        AV_OPT_TYPE_CONST,     { .i64 = 2 },    0, 0, FLAGS, "backend" },
63 #endif
64     { "model",       "path to model file",         OFFSET(model_filename),   AV_OPT_TYPE_STRING,    { .str = NULL }, 0, 0, FLAGS },
65     { "input",       "input name of the model",    OFFSET(model_inputname),  AV_OPT_TYPE_STRING,    { .str = NULL }, 0, 0, FLAGS },
66     { "output",      "output name of the model",   OFFSET(model_outputname), AV_OPT_TYPE_STRING,    { .str = NULL }, 0, 0, FLAGS },
67     { "options",     "backend options",            OFFSET(backend_options),  AV_OPT_TYPE_STRING,    { .str = NULL }, 0, 0, FLAGS },
68     { NULL }
69 };
70
71 AVFILTER_DEFINE_CLASS(dnn_processing);
72
73 static av_cold int init(AVFilterContext *context)
74 {
75     DnnProcessingContext *ctx = context->priv;
76
77     if (!ctx->model_filename) {
78         av_log(ctx, AV_LOG_ERROR, "model file for network is not specified\n");
79         return AVERROR(EINVAL);
80     }
81     if (!ctx->model_inputname) {
82         av_log(ctx, AV_LOG_ERROR, "input name of the model network is not specified\n");
83         return AVERROR(EINVAL);
84     }
85     if (!ctx->model_outputname) {
86         av_log(ctx, AV_LOG_ERROR, "output name of the model network is not specified\n");
87         return AVERROR(EINVAL);
88     }
89
90     ctx->dnn_module = ff_get_dnn_module(ctx->backend_type);
91     if (!ctx->dnn_module) {
92         av_log(ctx, AV_LOG_ERROR, "could not create DNN module for requested backend\n");
93         return AVERROR(ENOMEM);
94     }
95     if (!ctx->dnn_module->load_model) {
96         av_log(ctx, AV_LOG_ERROR, "load_model for network is not specified\n");
97         return AVERROR(EINVAL);
98     }
99
100     ctx->model = (ctx->dnn_module->load_model)(ctx->model_filename, ctx->backend_options, ctx);
101     if (!ctx->model) {
102         av_log(ctx, AV_LOG_ERROR, "could not load DNN model\n");
103         return AVERROR(EINVAL);
104     }
105
106     return 0;
107 }
108
109 static int query_formats(AVFilterContext *context)
110 {
111     static const enum AVPixelFormat pix_fmts[] = {
112         AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
113         AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAYF32,
114         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
115         AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
116         AV_PIX_FMT_NV12,
117         AV_PIX_FMT_NONE
118     };
119     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
120     return ff_set_common_formats(context, fmts_list);
121 }
122
123 #define LOG_FORMAT_CHANNEL_MISMATCH()                       \
124     av_log(ctx, AV_LOG_ERROR,                               \
125            "the frame's format %s does not match "          \
126            "the model input channel %d\n",                  \
127            av_get_pix_fmt_name(fmt),                        \
128            model_input->channels);
129
130 static int check_modelinput_inlink(const DNNData *model_input, const AVFilterLink *inlink)
131 {
132     AVFilterContext *ctx   = inlink->dst;
133     enum AVPixelFormat fmt = inlink->format;
134
135     // the design is to add explicit scale filter before this filter
136     if (model_input->height != -1 && model_input->height != inlink->h) {
137         av_log(ctx, AV_LOG_ERROR, "the model requires frame height %d but got %d\n",
138                                    model_input->height, inlink->h);
139         return AVERROR(EIO);
140     }
141     if (model_input->width != -1 && model_input->width != inlink->w) {
142         av_log(ctx, AV_LOG_ERROR, "the model requires frame width %d but got %d\n",
143                                    model_input->width, inlink->w);
144         return AVERROR(EIO);
145     }
146     if (model_input->dt != DNN_FLOAT) {
147         av_log(ctx, AV_LOG_ERROR, "only support dnn models with input data type as float32.\n");
148         return AVERROR(EIO);
149     }
150
151     switch (fmt) {
152     case AV_PIX_FMT_RGB24:
153     case AV_PIX_FMT_BGR24:
154         if (model_input->channels != 3) {
155             LOG_FORMAT_CHANNEL_MISMATCH();
156             return AVERROR(EIO);
157         }
158         return 0;
159     case AV_PIX_FMT_GRAYF32:
160     case AV_PIX_FMT_YUV420P:
161     case AV_PIX_FMT_YUV422P:
162     case AV_PIX_FMT_YUV444P:
163     case AV_PIX_FMT_YUV410P:
164     case AV_PIX_FMT_YUV411P:
165     case AV_PIX_FMT_NV12:
166         if (model_input->channels != 1) {
167             LOG_FORMAT_CHANNEL_MISMATCH();
168             return AVERROR(EIO);
169         }
170         return 0;
171     default:
172         av_log(ctx, AV_LOG_ERROR, "%s not supported.\n", av_get_pix_fmt_name(fmt));
173         return AVERROR(EIO);
174     }
175
176     return 0;
177 }
178
179 static int config_input(AVFilterLink *inlink)
180 {
181     AVFilterContext *context     = inlink->dst;
182     DnnProcessingContext *ctx = context->priv;
183     DNNReturnType result;
184     DNNData model_input;
185     int check;
186
187     result = ctx->model->get_input(ctx->model->model, &model_input, ctx->model_inputname);
188     if (result != DNN_SUCCESS) {
189         av_log(ctx, AV_LOG_ERROR, "could not get input from the model\n");
190         return AVERROR(EIO);
191     }
192
193     check = check_modelinput_inlink(&model_input, inlink);
194     if (check != 0) {
195         return check;
196     }
197
198     return 0;
199 }
200
201 static av_always_inline int isPlanarYUV(enum AVPixelFormat pix_fmt)
202 {
203     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
204     av_assert0(desc);
205     return !(desc->flags & AV_PIX_FMT_FLAG_RGB) && desc->nb_components == 3;
206 }
207
208 static int prepare_uv_scale(AVFilterLink *outlink)
209 {
210     AVFilterContext *context = outlink->src;
211     DnnProcessingContext *ctx = context->priv;
212     AVFilterLink *inlink = context->inputs[0];
213     enum AVPixelFormat fmt = inlink->format;
214
215     if (isPlanarYUV(fmt)) {
216         if (inlink->w != outlink->w || inlink->h != outlink->h) {
217             if (fmt == AV_PIX_FMT_NV12) {
218                 ctx->sws_uv_scale = sws_getContext(inlink->w >> 1, inlink->h >> 1, AV_PIX_FMT_YA8,
219                                                    outlink->w >> 1, outlink->h >> 1, AV_PIX_FMT_YA8,
220                                                    SWS_BICUBIC, NULL, NULL, NULL);
221                 ctx->sws_uv_height = inlink->h >> 1;
222             } else {
223                 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(fmt);
224                 int sws_src_h = AV_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
225                 int sws_src_w = AV_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
226                 int sws_dst_h = AV_CEIL_RSHIFT(outlink->h, desc->log2_chroma_h);
227                 int sws_dst_w = AV_CEIL_RSHIFT(outlink->w, desc->log2_chroma_w);
228                 ctx->sws_uv_scale = sws_getContext(sws_src_w, sws_src_h, AV_PIX_FMT_GRAY8,
229                                                    sws_dst_w, sws_dst_h, AV_PIX_FMT_GRAY8,
230                                                    SWS_BICUBIC, NULL, NULL, NULL);
231                 ctx->sws_uv_height = sws_src_h;
232             }
233         }
234     }
235
236     return 0;
237 }
238
239 static int config_output(AVFilterLink *outlink)
240 {
241     AVFilterContext *context = outlink->src;
242     DnnProcessingContext *ctx = context->priv;
243     DNNReturnType result;
244     AVFilterLink *inlink = context->inputs[0];
245
246     // have a try run in case that the dnn model resize the frame
247     result = ctx->model->get_output(ctx->model->model, ctx->model_inputname, inlink->w, inlink->h,
248                                     ctx->model_outputname, &outlink->w, &outlink->h);
249     if (result != DNN_SUCCESS) {
250         av_log(ctx, AV_LOG_ERROR, "could not get output from the model\n");
251         return AVERROR(EIO);
252     }
253
254     prepare_uv_scale(outlink);
255
256     return 0;
257 }
258
259 static int copy_uv_planes(DnnProcessingContext *ctx, AVFrame *out, const AVFrame *in)
260 {
261     const AVPixFmtDescriptor *desc;
262     int uv_height;
263
264     if (!ctx->sws_uv_scale) {
265         av_assert0(in->height == out->height && in->width == out->width);
266         desc = av_pix_fmt_desc_get(in->format);
267         uv_height = AV_CEIL_RSHIFT(in->height, desc->log2_chroma_h);
268         for (int i = 1; i < 3; ++i) {
269             int bytewidth = av_image_get_linesize(in->format, in->width, i);
270             av_image_copy_plane(out->data[i], out->linesize[i],
271                                 in->data[i], in->linesize[i],
272                                 bytewidth, uv_height);
273         }
274     } else if (in->format == AV_PIX_FMT_NV12) {
275         sws_scale(ctx->sws_uv_scale, (const uint8_t **)(in->data + 1), in->linesize + 1,
276                   0, ctx->sws_uv_height, out->data + 1, out->linesize + 1);
277     } else {
278         sws_scale(ctx->sws_uv_scale, (const uint8_t **)(in->data + 1), in->linesize + 1,
279                   0, ctx->sws_uv_height, out->data + 1, out->linesize + 1);
280         sws_scale(ctx->sws_uv_scale, (const uint8_t **)(in->data + 2), in->linesize + 2,
281                   0, ctx->sws_uv_height, out->data + 2, out->linesize + 2);
282     }
283
284     return 0;
285 }
286
287 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
288 {
289     AVFilterContext *context  = inlink->dst;
290     AVFilterLink *outlink = context->outputs[0];
291     DnnProcessingContext *ctx = context->priv;
292     DNNReturnType dnn_result;
293     AVFrame *out;
294
295     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
296     if (!out) {
297         av_frame_free(&in);
298         return AVERROR(ENOMEM);
299     }
300     av_frame_copy_props(out, in);
301
302     dnn_result = (ctx->dnn_module->execute_model)(ctx->model, ctx->model_inputname, in,
303                                                   (const char **)&ctx->model_outputname, 1, out);
304     if (dnn_result != DNN_SUCCESS){
305         av_log(ctx, AV_LOG_ERROR, "failed to execute model\n");
306         av_frame_free(&in);
307         av_frame_free(&out);
308         return AVERROR(EIO);
309     }
310
311     if (isPlanarYUV(in->format))
312         copy_uv_planes(ctx, out, in);
313
314     av_frame_free(&in);
315     return ff_filter_frame(outlink, out);
316 }
317
318 static av_cold void uninit(AVFilterContext *ctx)
319 {
320     DnnProcessingContext *context = ctx->priv;
321
322     sws_freeContext(context->sws_uv_scale);
323
324     if (context->dnn_module)
325         (context->dnn_module->free_model)(&context->model);
326
327     av_freep(&context->dnn_module);
328 }
329
330 static const AVFilterPad dnn_processing_inputs[] = {
331     {
332         .name         = "default",
333         .type         = AVMEDIA_TYPE_VIDEO,
334         .config_props = config_input,
335         .filter_frame = filter_frame,
336     },
337     { NULL }
338 };
339
340 static const AVFilterPad dnn_processing_outputs[] = {
341     {
342         .name = "default",
343         .type = AVMEDIA_TYPE_VIDEO,
344         .config_props  = config_output,
345     },
346     { NULL }
347 };
348
349 AVFilter ff_vf_dnn_processing = {
350     .name          = "dnn_processing",
351     .description   = NULL_IF_CONFIG_SMALL("Apply DNN processing filter to the input."),
352     .priv_size     = sizeof(DnnProcessingContext),
353     .init          = init,
354     .uninit        = uninit,
355     .query_formats = query_formats,
356     .inputs        = dnn_processing_inputs,
357     .outputs       = dnn_processing_outputs,
358     .priv_class    = &dnn_processing_class,
359 };