]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_dnn_processing.c
lavfi/dnn_processing: refine code to use function av_image_copy_plane for data copy
[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
36 typedef struct DnnProcessingContext {
37     const AVClass *class;
38
39     char *model_filename;
40     DNNBackendType backend_type;
41     char *model_inputname;
42     char *model_outputname;
43
44     DNNModule *dnn_module;
45     DNNModel *model;
46
47     // input & output of the model at execution time
48     DNNData input;
49     DNNData output;
50 } DnnProcessingContext;
51
52 #define OFFSET(x) offsetof(DnnProcessingContext, x)
53 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM | AV_OPT_FLAG_VIDEO_PARAM
54 static const AVOption dnn_processing_options[] = {
55     { "dnn_backend", "DNN backend",                OFFSET(backend_type),     AV_OPT_TYPE_INT,       { .i64 = 0 },    0, 1, FLAGS, "backend" },
56     { "native",      "native backend flag",        0,                        AV_OPT_TYPE_CONST,     { .i64 = 0 },    0, 0, FLAGS, "backend" },
57 #if (CONFIG_LIBTENSORFLOW == 1)
58     { "tensorflow",  "tensorflow backend flag",    0,                        AV_OPT_TYPE_CONST,     { .i64 = 1 },    0, 0, FLAGS, "backend" },
59 #endif
60     { "model",       "path to model file",         OFFSET(model_filename),   AV_OPT_TYPE_STRING,    { .str = NULL }, 0, 0, FLAGS },
61     { "input",       "input name of the model",    OFFSET(model_inputname),  AV_OPT_TYPE_STRING,    { .str = NULL }, 0, 0, FLAGS },
62     { "output",      "output name of the model",   OFFSET(model_outputname), AV_OPT_TYPE_STRING,    { .str = NULL }, 0, 0, FLAGS },
63     { NULL }
64 };
65
66 AVFILTER_DEFINE_CLASS(dnn_processing);
67
68 static av_cold int init(AVFilterContext *context)
69 {
70     DnnProcessingContext *ctx = context->priv;
71
72     if (!ctx->model_filename) {
73         av_log(ctx, AV_LOG_ERROR, "model file for network is not specified\n");
74         return AVERROR(EINVAL);
75     }
76     if (!ctx->model_inputname) {
77         av_log(ctx, AV_LOG_ERROR, "input name of the model network is not specified\n");
78         return AVERROR(EINVAL);
79     }
80     if (!ctx->model_outputname) {
81         av_log(ctx, AV_LOG_ERROR, "output name of the model network is not specified\n");
82         return AVERROR(EINVAL);
83     }
84
85     ctx->dnn_module = ff_get_dnn_module(ctx->backend_type);
86     if (!ctx->dnn_module) {
87         av_log(ctx, AV_LOG_ERROR, "could not create DNN module for requested backend\n");
88         return AVERROR(ENOMEM);
89     }
90     if (!ctx->dnn_module->load_model) {
91         av_log(ctx, AV_LOG_ERROR, "load_model for network is not specified\n");
92         return AVERROR(EINVAL);
93     }
94
95     ctx->model = (ctx->dnn_module->load_model)(ctx->model_filename);
96     if (!ctx->model) {
97         av_log(ctx, AV_LOG_ERROR, "could not load DNN model\n");
98         return AVERROR(EINVAL);
99     }
100
101     return 0;
102 }
103
104 static int query_formats(AVFilterContext *context)
105 {
106     static const enum AVPixelFormat pix_fmts[] = {
107         AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
108         AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAYF32,
109         AV_PIX_FMT_NONE
110     };
111     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
112     return ff_set_common_formats(context, fmts_list);
113 }
114
115 #define LOG_FORMAT_CHANNEL_MISMATCH()                       \
116     av_log(ctx, AV_LOG_ERROR,                               \
117            "the frame's format %s does not match "          \
118            "the model input channel %d\n",                  \
119            av_get_pix_fmt_name(fmt),                        \
120            model_input->channels);
121
122 static int check_modelinput_inlink(const DNNData *model_input, const AVFilterLink *inlink)
123 {
124     AVFilterContext *ctx   = inlink->dst;
125     enum AVPixelFormat fmt = inlink->format;
126
127     // the design is to add explicit scale filter before this filter
128     if (model_input->height != -1 && model_input->height != inlink->h) {
129         av_log(ctx, AV_LOG_ERROR, "the model requires frame height %d but got %d\n",
130                                    model_input->height, inlink->h);
131         return AVERROR(EIO);
132     }
133     if (model_input->width != -1 && model_input->width != inlink->w) {
134         av_log(ctx, AV_LOG_ERROR, "the model requires frame width %d but got %d\n",
135                                    model_input->width, inlink->w);
136         return AVERROR(EIO);
137     }
138
139     switch (fmt) {
140     case AV_PIX_FMT_RGB24:
141     case AV_PIX_FMT_BGR24:
142         if (model_input->channels != 3) {
143             LOG_FORMAT_CHANNEL_MISMATCH();
144             return AVERROR(EIO);
145         }
146         if (model_input->dt != DNN_FLOAT && model_input->dt != DNN_UINT8) {
147             av_log(ctx, AV_LOG_ERROR, "only support dnn models with input data type as float32 and uint8.\n");
148             return AVERROR(EIO);
149         }
150         return 0;
151     case AV_PIX_FMT_GRAY8:
152         if (model_input->channels != 1) {
153             LOG_FORMAT_CHANNEL_MISMATCH();
154             return AVERROR(EIO);
155         }
156         if (model_input->dt != DNN_UINT8) {
157             av_log(ctx, AV_LOG_ERROR, "only support dnn models with input data type uint8.\n");
158             return AVERROR(EIO);
159         }
160         return 0;
161     case AV_PIX_FMT_GRAYF32:
162         if (model_input->channels != 1) {
163             LOG_FORMAT_CHANNEL_MISMATCH();
164             return AVERROR(EIO);
165         }
166         if (model_input->dt != DNN_FLOAT) {
167             av_log(ctx, AV_LOG_ERROR, "only support dnn models with input data type float32.\n");
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     ctx->input.width    = inlink->w;
199     ctx->input.height   = inlink->h;
200     ctx->input.channels = model_input.channels;
201     ctx->input.dt = model_input.dt;
202
203     result = (ctx->model->set_input_output)(ctx->model->model,
204                                         &ctx->input, ctx->model_inputname,
205                                         (const char **)&ctx->model_outputname, 1);
206     if (result != DNN_SUCCESS) {
207         av_log(ctx, AV_LOG_ERROR, "could not set input and output for the model\n");
208         return AVERROR(EIO);
209     }
210
211     return 0;
212 }
213
214 static int config_output(AVFilterLink *outlink)
215 {
216     AVFilterContext *context = outlink->src;
217     DnnProcessingContext *ctx = context->priv;
218     DNNReturnType result;
219
220     // have a try run in case that the dnn model resize the frame
221     result = (ctx->dnn_module->execute_model)(ctx->model, &ctx->output, 1);
222     if (result != DNN_SUCCESS){
223         av_log(ctx, AV_LOG_ERROR, "failed to execute model\n");
224         return AVERROR(EIO);
225     }
226
227     outlink->w = ctx->output.width;
228     outlink->h = ctx->output.height;
229
230     return 0;
231 }
232
233 static int copy_from_frame_to_dnn(DNNData *dnn_input, const AVFrame *frame)
234 {
235     int bytewidth = av_image_get_linesize(frame->format, frame->width, 0);
236
237     switch (frame->format) {
238     case AV_PIX_FMT_RGB24:
239     case AV_PIX_FMT_BGR24:
240         if (dnn_input->dt == DNN_FLOAT) {
241             float *dnn_input_data = dnn_input->data;
242             for (int i = 0; i < frame->height; i++) {
243                 for(int j = 0; j < frame->width * 3; j++) {
244                     int k = i * frame->linesize[0] + j;
245                     int t = i * frame->width * 3 + j;
246                     dnn_input_data[t] = frame->data[0][k] / 255.0f;
247                 }
248             }
249         } else {
250             av_assert0(dnn_input->dt == DNN_UINT8);
251             av_image_copy_plane(dnn_input->data, bytewidth,
252                                 frame->data[0], frame->linesize[0],
253                                 bytewidth, frame->height);
254         }
255         return 0;
256     case AV_PIX_FMT_GRAY8:
257     case AV_PIX_FMT_GRAYF32:
258         av_image_copy_plane(dnn_input->data, bytewidth,
259                             frame->data[0], frame->linesize[0],
260                             bytewidth, frame->height);
261         return 0;
262     default:
263         return AVERROR(EIO);
264     }
265
266     return 0;
267 }
268
269 static int copy_from_dnn_to_frame(AVFrame *frame, const DNNData *dnn_output)
270 {
271     int bytewidth = av_image_get_linesize(frame->format, frame->width, 0);
272
273     switch (frame->format) {
274     case AV_PIX_FMT_RGB24:
275     case AV_PIX_FMT_BGR24:
276         if (dnn_output->dt == DNN_FLOAT) {
277             float *dnn_output_data = dnn_output->data;
278             for (int i = 0; i < frame->height; i++) {
279                 for(int j = 0; j < frame->width * 3; j++) {
280                     int k = i * frame->linesize[0] + j;
281                     int t = i * frame->width * 3 + j;
282                     frame->data[0][k] = av_clip_uintp2((int)(dnn_output_data[t] * 255.0f), 8);
283                 }
284             }
285         } else {
286             av_assert0(dnn_output->dt == DNN_UINT8);
287             av_image_copy_plane(frame->data[0], frame->linesize[0],
288                                 dnn_output->data, bytewidth,
289                                 bytewidth, frame->height);
290         }
291         return 0;
292     case AV_PIX_FMT_GRAY8:
293         // it is possible that data type of dnn output is float32,
294         // need to add support for such case when needed.
295         av_assert0(dnn_output->dt == DNN_UINT8);
296         av_image_copy_plane(frame->data[0], frame->linesize[0],
297                             dnn_output->data, bytewidth,
298                             bytewidth, frame->height);
299         return 0;
300     case AV_PIX_FMT_GRAYF32:
301         av_assert0(dnn_output->dt == DNN_FLOAT);
302         av_image_copy_plane(frame->data[0], frame->linesize[0],
303                             dnn_output->data, bytewidth,
304                             bytewidth, frame->height);
305         return 0;
306     default:
307         return AVERROR(EIO);
308     }
309
310     return 0;
311 }
312
313 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
314 {
315     AVFilterContext *context  = inlink->dst;
316     AVFilterLink *outlink = context->outputs[0];
317     DnnProcessingContext *ctx = context->priv;
318     DNNReturnType dnn_result;
319     AVFrame *out;
320
321     copy_from_frame_to_dnn(&ctx->input, in);
322
323     dnn_result = (ctx->dnn_module->execute_model)(ctx->model, &ctx->output, 1);
324     if (dnn_result != DNN_SUCCESS){
325         av_log(ctx, AV_LOG_ERROR, "failed to execute model\n");
326         av_frame_free(&in);
327         return AVERROR(EIO);
328     }
329
330     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
331     if (!out) {
332         av_frame_free(&in);
333         return AVERROR(ENOMEM);
334     }
335
336     av_frame_copy_props(out, in);
337     copy_from_dnn_to_frame(out, &ctx->output);
338     av_frame_free(&in);
339     return ff_filter_frame(outlink, out);
340 }
341
342 static av_cold void uninit(AVFilterContext *ctx)
343 {
344     DnnProcessingContext *context = ctx->priv;
345
346     if (context->dnn_module)
347         (context->dnn_module->free_model)(&context->model);
348
349     av_freep(&context->dnn_module);
350 }
351
352 static const AVFilterPad dnn_processing_inputs[] = {
353     {
354         .name         = "default",
355         .type         = AVMEDIA_TYPE_VIDEO,
356         .config_props = config_input,
357         .filter_frame = filter_frame,
358     },
359     { NULL }
360 };
361
362 static const AVFilterPad dnn_processing_outputs[] = {
363     {
364         .name = "default",
365         .type = AVMEDIA_TYPE_VIDEO,
366         .config_props  = config_output,
367     },
368     { NULL }
369 };
370
371 AVFilter ff_vf_dnn_processing = {
372     .name          = "dnn_processing",
373     .description   = NULL_IF_CONFIG_SMALL("Apply DNN processing filter to the input."),
374     .priv_size     = sizeof(DnnProcessingContext),
375     .init          = init,
376     .uninit        = uninit,
377     .query_formats = query_formats,
378     .inputs        = dnn_processing_inputs,
379     .outputs       = dnn_processing_outputs,
380     .priv_class    = &dnn_processing_class,
381 };