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