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