]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_dnn_processing.c
avutil/opt: check return value of av_bprint_finalize()
[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
45     DNNModule *dnn_module;
46     DNNModel *model;
47
48     // input & output of the model at execution time
49     DNNData input;
50     DNNData output;
51
52     struct SwsContext *sws_gray8_to_grayf32;
53     struct SwsContext *sws_grayf32_to_gray8;
54     struct SwsContext *sws_uv_scale;
55     int sws_uv_height;
56 } DnnProcessingContext;
57
58 #define OFFSET(x) offsetof(DnnProcessingContext, x)
59 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM | AV_OPT_FLAG_VIDEO_PARAM
60 static const AVOption dnn_processing_options[] = {
61     { "dnn_backend", "DNN backend",                OFFSET(backend_type),     AV_OPT_TYPE_INT,       { .i64 = 0 },    INT_MIN, INT_MAX, FLAGS, "backend" },
62     { "native",      "native backend flag",        0,                        AV_OPT_TYPE_CONST,     { .i64 = 0 },    0, 0, FLAGS, "backend" },
63 #if (CONFIG_LIBTENSORFLOW == 1)
64     { "tensorflow",  "tensorflow backend flag",    0,                        AV_OPT_TYPE_CONST,     { .i64 = 1 },    0, 0, FLAGS, "backend" },
65 #endif
66 #if (CONFIG_LIBOPENVINO == 1)
67     { "openvino",    "openvino backend flag",      0,                        AV_OPT_TYPE_CONST,     { .i64 = 2 },    0, 0, FLAGS, "backend" },
68 #endif
69     { "model",       "path to model file",         OFFSET(model_filename),   AV_OPT_TYPE_STRING,    { .str = NULL }, 0, 0, FLAGS },
70     { "input",       "input name of the model",    OFFSET(model_inputname),  AV_OPT_TYPE_STRING,    { .str = NULL }, 0, 0, FLAGS },
71     { "output",      "output name of the model",   OFFSET(model_outputname), AV_OPT_TYPE_STRING,    { .str = NULL }, 0, 0, FLAGS },
72     { NULL }
73 };
74
75 AVFILTER_DEFINE_CLASS(dnn_processing);
76
77 static av_cold int init(AVFilterContext *context)
78 {
79     DnnProcessingContext *ctx = context->priv;
80
81     if (!ctx->model_filename) {
82         av_log(ctx, AV_LOG_ERROR, "model file for network is not specified\n");
83         return AVERROR(EINVAL);
84     }
85     if (!ctx->model_inputname) {
86         av_log(ctx, AV_LOG_ERROR, "input name of the model network is not specified\n");
87         return AVERROR(EINVAL);
88     }
89     if (!ctx->model_outputname) {
90         av_log(ctx, AV_LOG_ERROR, "output name of the model network is not specified\n");
91         return AVERROR(EINVAL);
92     }
93
94     ctx->dnn_module = ff_get_dnn_module(ctx->backend_type);
95     if (!ctx->dnn_module) {
96         av_log(ctx, AV_LOG_ERROR, "could not create DNN module for requested backend\n");
97         return AVERROR(ENOMEM);
98     }
99     if (!ctx->dnn_module->load_model) {
100         av_log(ctx, AV_LOG_ERROR, "load_model for network is not specified\n");
101         return AVERROR(EINVAL);
102     }
103
104     ctx->model = (ctx->dnn_module->load_model)(ctx->model_filename);
105     if (!ctx->model) {
106         av_log(ctx, AV_LOG_ERROR, "could not load DNN model\n");
107         return AVERROR(EINVAL);
108     }
109
110     return 0;
111 }
112
113 static int query_formats(AVFilterContext *context)
114 {
115     static const enum AVPixelFormat pix_fmts[] = {
116         AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
117         AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAYF32,
118         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
119         AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
120         AV_PIX_FMT_NONE
121     };
122     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
123     return ff_set_common_formats(context, fmts_list);
124 }
125
126 #define LOG_FORMAT_CHANNEL_MISMATCH()                       \
127     av_log(ctx, AV_LOG_ERROR,                               \
128            "the frame's format %s does not match "          \
129            "the model input channel %d\n",                  \
130            av_get_pix_fmt_name(fmt),                        \
131            model_input->channels);
132
133 static int check_modelinput_inlink(const DNNData *model_input, const AVFilterLink *inlink)
134 {
135     AVFilterContext *ctx   = inlink->dst;
136     enum AVPixelFormat fmt = inlink->format;
137
138     // the design is to add explicit scale filter before this filter
139     if (model_input->height != -1 && model_input->height != inlink->h) {
140         av_log(ctx, AV_LOG_ERROR, "the model requires frame height %d but got %d\n",
141                                    model_input->height, inlink->h);
142         return AVERROR(EIO);
143     }
144     if (model_input->width != -1 && model_input->width != inlink->w) {
145         av_log(ctx, AV_LOG_ERROR, "the model requires frame width %d but got %d\n",
146                                    model_input->width, inlink->w);
147         return AVERROR(EIO);
148     }
149
150     switch (fmt) {
151     case AV_PIX_FMT_RGB24:
152     case AV_PIX_FMT_BGR24:
153         if (model_input->channels != 3) {
154             LOG_FORMAT_CHANNEL_MISMATCH();
155             return AVERROR(EIO);
156         }
157         if (model_input->dt != DNN_FLOAT && model_input->dt != DNN_UINT8) {
158             av_log(ctx, AV_LOG_ERROR, "only support dnn models with input data type as float32 and uint8.\n");
159             return AVERROR(EIO);
160         }
161         return 0;
162     case AV_PIX_FMT_GRAY8:
163         if (model_input->channels != 1) {
164             LOG_FORMAT_CHANNEL_MISMATCH();
165             return AVERROR(EIO);
166         }
167         if (model_input->dt != DNN_UINT8) {
168             av_log(ctx, AV_LOG_ERROR, "only support dnn models with input data type uint8.\n");
169             return AVERROR(EIO);
170         }
171         return 0;
172     case AV_PIX_FMT_GRAYF32:
173     case AV_PIX_FMT_YUV420P:
174     case AV_PIX_FMT_YUV422P:
175     case AV_PIX_FMT_YUV444P:
176     case AV_PIX_FMT_YUV410P:
177     case AV_PIX_FMT_YUV411P:
178         if (model_input->channels != 1) {
179             LOG_FORMAT_CHANNEL_MISMATCH();
180             return AVERROR(EIO);
181         }
182         if (model_input->dt != DNN_FLOAT) {
183             av_log(ctx, AV_LOG_ERROR, "only support dnn models with input data type float32.\n");
184             return AVERROR(EIO);
185         }
186         return 0;
187     default:
188         av_log(ctx, AV_LOG_ERROR, "%s not supported.\n", av_get_pix_fmt_name(fmt));
189         return AVERROR(EIO);
190     }
191
192     return 0;
193 }
194
195 static int config_input(AVFilterLink *inlink)
196 {
197     AVFilterContext *context     = inlink->dst;
198     DnnProcessingContext *ctx = context->priv;
199     DNNReturnType result;
200     DNNData model_input;
201     int check;
202
203     result = ctx->model->get_input(ctx->model->model, &model_input, ctx->model_inputname);
204     if (result != DNN_SUCCESS) {
205         av_log(ctx, AV_LOG_ERROR, "could not get input from the model\n");
206         return AVERROR(EIO);
207     }
208
209     check = check_modelinput_inlink(&model_input, inlink);
210     if (check != 0) {
211         return check;
212     }
213
214     ctx->input.width    = inlink->w;
215     ctx->input.height   = inlink->h;
216     ctx->input.channels = model_input.channels;
217     ctx->input.dt = model_input.dt;
218
219     result = (ctx->model->set_input_output)(ctx->model->model,
220                                         &ctx->input, ctx->model_inputname,
221                                         (const char **)&ctx->model_outputname, 1);
222     if (result != DNN_SUCCESS) {
223         av_log(ctx, AV_LOG_ERROR, "could not set input and output for the model\n");
224         return AVERROR(EIO);
225     }
226
227     return 0;
228 }
229
230 static int prepare_sws_context(AVFilterLink *outlink)
231 {
232     AVFilterContext *context = outlink->src;
233     DnnProcessingContext *ctx = context->priv;
234     AVFilterLink *inlink = context->inputs[0];
235     enum AVPixelFormat fmt = inlink->format;
236     DNNDataType input_dt  = ctx->input.dt;
237     DNNDataType output_dt = ctx->output.dt;
238
239     switch (fmt) {
240     case AV_PIX_FMT_RGB24:
241     case AV_PIX_FMT_BGR24:
242         if (input_dt == DNN_FLOAT) {
243             ctx->sws_gray8_to_grayf32 = sws_getContext(inlink->w * 3,
244                                                        inlink->h,
245                                                        AV_PIX_FMT_GRAY8,
246                                                        inlink->w * 3,
247                                                        inlink->h,
248                                                        AV_PIX_FMT_GRAYF32,
249                                                        0, NULL, NULL, NULL);
250         }
251         if (output_dt == DNN_FLOAT) {
252             ctx->sws_grayf32_to_gray8 = sws_getContext(outlink->w * 3,
253                                                        outlink->h,
254                                                        AV_PIX_FMT_GRAYF32,
255                                                        outlink->w * 3,
256                                                        outlink->h,
257                                                        AV_PIX_FMT_GRAY8,
258                                                        0, NULL, NULL, NULL);
259         }
260         return 0;
261     case AV_PIX_FMT_YUV420P:
262     case AV_PIX_FMT_YUV422P:
263     case AV_PIX_FMT_YUV444P:
264     case AV_PIX_FMT_YUV410P:
265     case AV_PIX_FMT_YUV411P:
266         av_assert0(input_dt == DNN_FLOAT);
267         av_assert0(output_dt == DNN_FLOAT);
268         ctx->sws_gray8_to_grayf32 = sws_getContext(inlink->w,
269                                                    inlink->h,
270                                                    AV_PIX_FMT_GRAY8,
271                                                    inlink->w,
272                                                    inlink->h,
273                                                    AV_PIX_FMT_GRAYF32,
274                                                    0, NULL, NULL, NULL);
275         ctx->sws_grayf32_to_gray8 = sws_getContext(outlink->w,
276                                                    outlink->h,
277                                                    AV_PIX_FMT_GRAYF32,
278                                                    outlink->w,
279                                                    outlink->h,
280                                                    AV_PIX_FMT_GRAY8,
281                                                    0, NULL, NULL, NULL);
282
283         if (inlink->w != outlink->w || inlink->h != outlink->h) {
284             const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(fmt);
285             int sws_src_h = AV_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
286             int sws_src_w = AV_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
287             int sws_dst_h = AV_CEIL_RSHIFT(outlink->h, desc->log2_chroma_h);
288             int sws_dst_w = AV_CEIL_RSHIFT(outlink->w, desc->log2_chroma_w);
289             ctx->sws_uv_scale = sws_getContext(sws_src_w, sws_src_h, AV_PIX_FMT_GRAY8,
290                                                sws_dst_w, sws_dst_h, AV_PIX_FMT_GRAY8,
291                                                SWS_BICUBIC, NULL, NULL, NULL);
292             ctx->sws_uv_height = sws_src_h;
293         }
294         return 0;
295     default:
296         //do nothing
297         break;
298     }
299
300     return 0;
301 }
302
303 static int config_output(AVFilterLink *outlink)
304 {
305     AVFilterContext *context = outlink->src;
306     DnnProcessingContext *ctx = context->priv;
307     DNNReturnType result;
308
309     // have a try run in case that the dnn model resize the frame
310     result = (ctx->dnn_module->execute_model)(ctx->model, &ctx->output, 1);
311     if (result != DNN_SUCCESS){
312         av_log(ctx, AV_LOG_ERROR, "failed to execute model\n");
313         return AVERROR(EIO);
314     }
315
316     outlink->w = ctx->output.width;
317     outlink->h = ctx->output.height;
318
319     prepare_sws_context(outlink);
320
321     return 0;
322 }
323
324 static int copy_from_frame_to_dnn(DnnProcessingContext *ctx, const AVFrame *frame)
325 {
326     int bytewidth = av_image_get_linesize(frame->format, frame->width, 0);
327     DNNData *dnn_input = &ctx->input;
328
329     switch (frame->format) {
330     case AV_PIX_FMT_RGB24:
331     case AV_PIX_FMT_BGR24:
332         if (dnn_input->dt == DNN_FLOAT) {
333             sws_scale(ctx->sws_gray8_to_grayf32, (const uint8_t **)frame->data, frame->linesize,
334                       0, frame->height, (uint8_t * const*)(&dnn_input->data),
335                       (const int [4]){frame->width * 3 * sizeof(float), 0, 0, 0});
336         } else {
337             av_assert0(dnn_input->dt == DNN_UINT8);
338             av_image_copy_plane(dnn_input->data, bytewidth,
339                                 frame->data[0], frame->linesize[0],
340                                 bytewidth, frame->height);
341         }
342         return 0;
343     case AV_PIX_FMT_GRAY8:
344     case AV_PIX_FMT_GRAYF32:
345         av_image_copy_plane(dnn_input->data, bytewidth,
346                             frame->data[0], frame->linesize[0],
347                             bytewidth, frame->height);
348         return 0;
349     case AV_PIX_FMT_YUV420P:
350     case AV_PIX_FMT_YUV422P:
351     case AV_PIX_FMT_YUV444P:
352     case AV_PIX_FMT_YUV410P:
353     case AV_PIX_FMT_YUV411P:
354         sws_scale(ctx->sws_gray8_to_grayf32, (const uint8_t **)frame->data, frame->linesize,
355                   0, frame->height, (uint8_t * const*)(&dnn_input->data),
356                   (const int [4]){frame->width * sizeof(float), 0, 0, 0});
357         return 0;
358     default:
359         return AVERROR(EIO);
360     }
361
362     return 0;
363 }
364
365 static int copy_from_dnn_to_frame(DnnProcessingContext *ctx, AVFrame *frame)
366 {
367     int bytewidth = av_image_get_linesize(frame->format, frame->width, 0);
368     DNNData *dnn_output = &ctx->output;
369
370     switch (frame->format) {
371     case AV_PIX_FMT_RGB24:
372     case AV_PIX_FMT_BGR24:
373         if (dnn_output->dt == DNN_FLOAT) {
374             sws_scale(ctx->sws_grayf32_to_gray8, (const uint8_t *[4]){(const uint8_t *)dnn_output->data, 0, 0, 0},
375                       (const int[4]){frame->width * 3 * sizeof(float), 0, 0, 0},
376                       0, frame->height, (uint8_t * const*)frame->data, frame->linesize);
377
378         } else {
379             av_assert0(dnn_output->dt == DNN_UINT8);
380             av_image_copy_plane(frame->data[0], frame->linesize[0],
381                                 dnn_output->data, bytewidth,
382                                 bytewidth, frame->height);
383         }
384         return 0;
385     case AV_PIX_FMT_GRAY8:
386         // it is possible that data type of dnn output is float32,
387         // need to add support for such case when needed.
388         av_assert0(dnn_output->dt == DNN_UINT8);
389         av_image_copy_plane(frame->data[0], frame->linesize[0],
390                             dnn_output->data, bytewidth,
391                             bytewidth, frame->height);
392         return 0;
393     case AV_PIX_FMT_GRAYF32:
394         av_assert0(dnn_output->dt == DNN_FLOAT);
395         av_image_copy_plane(frame->data[0], frame->linesize[0],
396                             dnn_output->data, bytewidth,
397                             bytewidth, frame->height);
398         return 0;
399     case AV_PIX_FMT_YUV420P:
400     case AV_PIX_FMT_YUV422P:
401     case AV_PIX_FMT_YUV444P:
402     case AV_PIX_FMT_YUV410P:
403     case AV_PIX_FMT_YUV411P:
404         sws_scale(ctx->sws_grayf32_to_gray8, (const uint8_t *[4]){(const uint8_t *)dnn_output->data, 0, 0, 0},
405                   (const int[4]){frame->width * sizeof(float), 0, 0, 0},
406                   0, frame->height, (uint8_t * const*)frame->data, frame->linesize);
407         return 0;
408     default:
409         return AVERROR(EIO);
410     }
411
412     return 0;
413 }
414
415 static av_always_inline int isPlanarYUV(enum AVPixelFormat pix_fmt)
416 {
417     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
418     av_assert0(desc);
419     return !(desc->flags & AV_PIX_FMT_FLAG_RGB) && desc->nb_components == 3;
420 }
421
422 static int copy_uv_planes(DnnProcessingContext *ctx, AVFrame *out, const AVFrame *in)
423 {
424     const AVPixFmtDescriptor *desc;
425     int uv_height;
426
427     if (!ctx->sws_uv_scale) {
428         av_assert0(in->height == out->height && in->width == out->width);
429         desc = av_pix_fmt_desc_get(in->format);
430         uv_height = AV_CEIL_RSHIFT(in->height, desc->log2_chroma_h);
431         for (int i = 1; i < 3; ++i) {
432             int bytewidth = av_image_get_linesize(in->format, in->width, i);
433             av_image_copy_plane(out->data[i], out->linesize[i],
434                                 in->data[i], in->linesize[i],
435                                 bytewidth, uv_height);
436         }
437     } else {
438         sws_scale(ctx->sws_uv_scale, (const uint8_t **)(in->data + 1), in->linesize + 1,
439                   0, ctx->sws_uv_height, out->data + 1, out->linesize + 1);
440         sws_scale(ctx->sws_uv_scale, (const uint8_t **)(in->data + 2), in->linesize + 2,
441                   0, ctx->sws_uv_height, out->data + 2, out->linesize + 2);
442     }
443
444     return 0;
445 }
446
447 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
448 {
449     AVFilterContext *context  = inlink->dst;
450     AVFilterLink *outlink = context->outputs[0];
451     DnnProcessingContext *ctx = context->priv;
452     DNNReturnType dnn_result;
453     AVFrame *out;
454
455     copy_from_frame_to_dnn(ctx, in);
456
457     dnn_result = (ctx->dnn_module->execute_model)(ctx->model, &ctx->output, 1);
458     if (dnn_result != DNN_SUCCESS){
459         av_log(ctx, AV_LOG_ERROR, "failed to execute model\n");
460         av_frame_free(&in);
461         return AVERROR(EIO);
462     }
463
464     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
465     if (!out) {
466         av_frame_free(&in);
467         return AVERROR(ENOMEM);
468     }
469
470     av_frame_copy_props(out, in);
471     copy_from_dnn_to_frame(ctx, out);
472
473     if (isPlanarYUV(in->format))
474         copy_uv_planes(ctx, out, in);
475
476     av_frame_free(&in);
477     return ff_filter_frame(outlink, out);
478 }
479
480 static av_cold void uninit(AVFilterContext *ctx)
481 {
482     DnnProcessingContext *context = ctx->priv;
483
484     sws_freeContext(context->sws_gray8_to_grayf32);
485     sws_freeContext(context->sws_grayf32_to_gray8);
486     sws_freeContext(context->sws_uv_scale);
487
488     if (context->dnn_module)
489         (context->dnn_module->free_model)(&context->model);
490
491     av_freep(&context->dnn_module);
492 }
493
494 static const AVFilterPad dnn_processing_inputs[] = {
495     {
496         .name         = "default",
497         .type         = AVMEDIA_TYPE_VIDEO,
498         .config_props = config_input,
499         .filter_frame = filter_frame,
500     },
501     { NULL }
502 };
503
504 static const AVFilterPad dnn_processing_outputs[] = {
505     {
506         .name = "default",
507         .type = AVMEDIA_TYPE_VIDEO,
508         .config_props  = config_output,
509     },
510     { NULL }
511 };
512
513 AVFilter ff_vf_dnn_processing = {
514     .name          = "dnn_processing",
515     .description   = NULL_IF_CONFIG_SMALL("Apply DNN processing filter to the input."),
516     .priv_size     = sizeof(DnnProcessingContext),
517     .init          = init,
518     .uninit        = uninit,
519     .query_formats = query_formats,
520     .inputs        = dnn_processing_inputs,
521     .outputs       = dnn_processing_outputs,
522     .priv_class    = &dnn_processing_class,
523 };