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