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