FFmpeg
Loading...
Searching...
No Matches
vf_dnn_processing.c
Go to the documentation of this file.
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 "config.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 "formats.h"
33#include "dnn_filter_common.h"
34#include "video.h"
35#include "libswscale/swscale.h"
36#include "libavutil/time.h"
37
44
45#define OFFSET(x) offsetof(DnnProcessingContext, dnnctx.x)
46#define FLAGS AV_OPT_FLAG_FILTERING_PARAM | AV_OPT_FLAG_VIDEO_PARAM
48 { "dnn_backend", "DNN backend", OFFSET(backend_type), AV_OPT_TYPE_INT, { .i64 = DNN_TF }, INT_MIN, INT_MAX, FLAGS, .unit = "backend" },
49#if (CONFIG_LIBTENSORFLOW == 1)
50 { "tensorflow", "tensorflow backend flag", 0, AV_OPT_TYPE_CONST, { .i64 = DNN_TF }, 0, 0, FLAGS, .unit = "backend" },
51#endif
52#if (CONFIG_LIBOPENVINO == 1)
53 { "openvino", "openvino backend flag", 0, AV_OPT_TYPE_CONST, { .i64 = DNN_OV }, 0, 0, FLAGS, .unit = "backend" },
54#endif
55#if (CONFIG_LIBTORCH == 1)
56 { "torch", "torch backend flag", 0, AV_OPT_TYPE_CONST, { .i64 = DNN_TH }, 0, 0, FLAGS, "backend" },
57#endif
58#if (CONFIG_LIBONNXRUNTIME == 1)
59 { "onnx", "onnx backend flag", 0, AV_OPT_TYPE_CONST, { .i64 = DNN_ONNX }, 0, 0, FLAGS, "backend" },
60#endif
61 { NULL }
62};
63
65
66static av_cold int init(AVFilterContext *context)
67{
68 DnnProcessingContext *ctx = context->priv;
69 return ff_dnn_init(&ctx->dnnctx, DFT_PROCESS_FRAME, context);
70}
71
83
84#define LOG_FORMAT_CHANNEL_MISMATCH() \
85 av_log(ctx, AV_LOG_ERROR, \
86 "the frame's format %s does not match " \
87 "the model input channel %d\n", \
88 av_get_pix_fmt_name(fmt), \
89 model_input->dims[dnn_get_channel_idx_by_layout(model_input->layout)]);
90
91static int check_modelinput_inlink(const DNNData *model_input, const AVFilterLink *inlink)
92{
93 AVFilterContext *ctx = inlink->dst;
94 enum AVPixelFormat fmt = inlink->format;
95 int width_idx, height_idx;
96
97 width_idx = dnn_get_width_idx_by_layout(model_input->layout);
98 height_idx = dnn_get_height_idx_by_layout(model_input->layout);
99 // the design is to add explicit scale filter before this filter
100 if (model_input->dims[height_idx] != -1 &&
101 model_input->dims[height_idx] != inlink->h) {
102 av_log(ctx, AV_LOG_ERROR, "the model requires frame height %d but got %d\n",
103 model_input->dims[height_idx],
104 inlink->h);
105 return AVERROR(EIO);
106 }
107 if (model_input->dims[width_idx] != -1 &&
108 model_input->dims[width_idx] != inlink->w) {
109 av_log(ctx, AV_LOG_ERROR, "the model requires frame width %d but got %d\n",
110 model_input->dims[width_idx],
111 inlink->w);
112 return AVERROR(EIO);
113 }
114 if (model_input->dt != DNN_FLOAT) {
115 avpriv_report_missing_feature(ctx, "data type rather than DNN_FLOAT");
116 return AVERROR(EIO);
117 }
118
119 switch (fmt) {
120 case AV_PIX_FMT_RGB24:
121 case AV_PIX_FMT_BGR24:
122 if (model_input->dims[dnn_get_channel_idx_by_layout(model_input->layout)] != 3) {
124 return AVERROR(EIO);
125 }
126 return 0;
127 case AV_PIX_FMT_GRAY8:
134 case AV_PIX_FMT_NV12:
135 if (model_input->dims[dnn_get_channel_idx_by_layout(model_input->layout)] != 1) {
137 return AVERROR(EIO);
138 }
139 return 0;
140#if CONFIG_CUDA
141 case AV_PIX_FMT_CUDA:
142 {
143 DnnProcessingContext *dnn_ctx = ctx->priv;
144 return ff_dnn_zero_copy_supported_cuda(&dnn_ctx->dnnctx, inlink);
145 }
146#endif
147 default:
149 return AVERROR(EIO);
150 }
151
152 return 0;
153}
154
155static int config_input(AVFilterLink *inlink)
156{
157 AVFilterContext *context = inlink->dst;
158 DnnProcessingContext *ctx = context->priv;
159 int result;
160 DNNData model_input = { 0 };
161 int check;
162
163 result = ff_dnn_get_input(&ctx->dnnctx, &model_input);
164 if (result != 0) {
165 av_log(ctx, AV_LOG_ERROR, "could not get input from the model\n");
166 return result;
167 }
168
169 check = check_modelinput_inlink(&model_input, inlink);
170 if (check != 0) {
171 return check;
172 }
173
174 return 0;
175}
176
178{
181 return !(desc->flags & AV_PIX_FMT_FLAG_RGB) && desc->nb_components == 3;
182}
183
184static int prepare_uv_scale(AVFilterLink *outlink)
185{
186 AVFilterContext *context = outlink->src;
187 DnnProcessingContext *ctx = context->priv;
188 AVFilterLink *inlink = context->inputs[0];
189 enum AVPixelFormat fmt = inlink->format;
190
191 if (isPlanarYUV(fmt)) {
192 if (inlink->w != outlink->w || inlink->h != outlink->h) {
193 if (fmt == AV_PIX_FMT_NV12) {
194 ctx->sws_uv_scale = sws_getContext(inlink->w >> 1, inlink->h >> 1, AV_PIX_FMT_YA8,
195 outlink->w >> 1, outlink->h >> 1, AV_PIX_FMT_YA8,
197 ctx->sws_uv_height = inlink->h >> 1;
198 } else {
200 int sws_src_h = AV_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
201 int sws_src_w = AV_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
202 int sws_dst_h = AV_CEIL_RSHIFT(outlink->h, desc->log2_chroma_h);
203 int sws_dst_w = AV_CEIL_RSHIFT(outlink->w, desc->log2_chroma_w);
204 ctx->sws_uv_scale = sws_getContext(sws_src_w, sws_src_h, AV_PIX_FMT_GRAY8,
205 sws_dst_w, sws_dst_h, AV_PIX_FMT_GRAY8,
207 ctx->sws_uv_height = sws_src_h;
208 }
209 }
210 }
211
212 return 0;
213}
214
215static int config_output(AVFilterLink *outlink)
216{
217 AVFilterContext *context = outlink->src;
218 DnnProcessingContext *ctx = context->priv;
219 int result;
220 AVFilterLink *inlink = context->inputs[0];
221
222 // have a try run in case that the dnn model resize the frame
223 result = ff_dnn_get_output(&ctx->dnnctx, inlink->w, inlink->h, &outlink->w, &outlink->h);
224 if (result != 0) {
225 av_log(ctx, AV_LOG_ERROR, "could not get output from the model\n");
226 return result;
227 }
228
229 prepare_uv_scale(outlink);
230
231 return 0;
232}
233
235{
237 int uv_height;
238
239 if (!ctx->sws_uv_scale) {
240 av_assert0(in->height == out->height && in->width == out->width);
242 uv_height = AV_CEIL_RSHIFT(in->height, desc->log2_chroma_h);
243 for (int i = 1; i < 3; ++i) {
244 int bytewidth = av_image_get_linesize(in->format, in->width, i);
245 if (bytewidth < 0) {
246 return AVERROR(EINVAL);
247 }
248 av_image_copy_plane(out->data[i], out->linesize[i],
249 in->data[i], in->linesize[i],
250 bytewidth, uv_height);
251 }
252 } else if (in->format == AV_PIX_FMT_NV12) {
253 sws_scale(ctx->sws_uv_scale, (const uint8_t **)(in->data + 1), in->linesize + 1,
254 0, ctx->sws_uv_height, out->data + 1, out->linesize + 1);
255 } else {
256 sws_scale(ctx->sws_uv_scale, (const uint8_t **)(in->data + 1), in->linesize + 1,
257 0, ctx->sws_uv_height, out->data + 1, out->linesize + 1);
258 sws_scale(ctx->sws_uv_scale, (const uint8_t **)(in->data + 2), in->linesize + 2,
259 0, ctx->sws_uv_height, out->data + 2, out->linesize + 2);
260 }
261
262 return 0;
263}
264
265static int flush_frame(AVFilterLink *outlink, int64_t pts, int64_t *out_pts)
266{
267 DnnProcessingContext *ctx = outlink->src->priv;
268 int ret;
269 DNNAsyncStatusType async_state;
270
271 ret = ff_dnn_flush(&ctx->dnnctx);
272 if (ret != 0) {
273 return -1;
274 }
275
276 do {
277 AVFrame *in_frame = NULL;
278 AVFrame *out_frame = NULL;
279 async_state = ff_dnn_get_result(&ctx->dnnctx, &in_frame, &out_frame);
280 if (out_frame) {
281 if (isPlanarYUV(in_frame->format))
282 copy_uv_planes(ctx, out_frame, in_frame);
283 av_frame_free(&in_frame);
284 ret = ff_filter_frame(outlink, out_frame);
285 if (ret < 0)
286 return ret;
287 if (out_pts)
288 *out_pts = out_frame->pts + pts;
289 }
290 av_usleep(5000);
291 } while (async_state >= DAST_NOT_READY);
292
293 return 0;
294}
295
297{
298 AVFilterLink *inlink = filter_ctx->inputs[0];
299 AVFilterLink *outlink = filter_ctx->outputs[0];
301 AVFrame *in = NULL, *out = NULL;
302 int64_t pts;
303 int ret, status;
304 int got_frame = 0;
305 int async_state;
306
307 FF_FILTER_FORWARD_STATUS_BACK(outlink, inlink);
308
309 do {
310 // drain all input frames
311 ret = ff_inlink_consume_frame(inlink, &in);
312 if (ret < 0)
313 return ret;
314 if (ret > 0) {
315 out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
316 if (!out) {
317 av_frame_free(&in);
318 return AVERROR(ENOMEM);
319 }
321 if (ff_dnn_execute_model(&ctx->dnnctx, in, out) != 0) {
322 return AVERROR(EIO);
323 }
324 }
325 } while (ret > 0);
326
327 // drain all processed frames
328 do {
329 AVFrame *in_frame = NULL;
330 AVFrame *out_frame = NULL;
331 async_state = ff_dnn_get_result(&ctx->dnnctx, &in_frame, &out_frame);
332 if (out_frame) {
333 if (isPlanarYUV(in_frame->format))
334 copy_uv_planes(ctx, out_frame, in_frame);
335 av_frame_free(&in_frame);
336 ret = ff_filter_frame(outlink, out_frame);
337 if (ret < 0)
338 return ret;
339 got_frame = 1;
340 }
341 } while (async_state == DAST_SUCCESS);
342
343 // if frame got, schedule to next filter
344 if (got_frame)
345 return 0;
346
347 if (ff_inlink_acknowledge_status(inlink, &status, &pts)) {
348 if (status == AVERROR_EOF) {
349 int64_t out_pts = pts;
350 ret = flush_frame(outlink, pts, &out_pts);
351 ff_outlink_set_status(outlink, status, out_pts);
352 return ret;
353 }
354 }
355
356 FF_FILTER_FORWARD_WANTED(outlink, inlink);
357
358 return 0;
359}
360
362{
363 DnnProcessingContext *context = ctx->priv;
364
366 ff_dnn_uninit(&context->dnnctx);
367}
368
370 {
371 .name = "default",
372 .type = AVMEDIA_TYPE_VIDEO,
373 .config_props = config_input,
374 },
375};
376
378 {
379 .name = "default",
380 .type = AVMEDIA_TYPE_VIDEO,
381 .config_props = config_output,
382 },
383};
384
386 .p.name = "dnn_processing",
387 .p.description = NULL_IF_CONFIG_SMALL("Apply DNN processing filter to the input."),
388 .p.priv_class = &dnn_processing_class,
389 .priv_size = sizeof(DnnProcessingContext),
391 .init = init,
392 .uninit = uninit,
396 .activate = activate,
397};
static int config_input(AVFilterLink *inlink)
const FFFilter ff_vf_dnn_processing
static FILE * out
static AVFormatContext * ctx
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition avassert.h:42
int ff_inlink_acknowledge_status(AVFilterLink *link, int *rstatus, int64_t *rpts)
Test and acknowledge the change of status on the link.
Definition avfilter.c:1467
int ff_filter_frame(AVFilterLink *link, AVFrame *frame)
Send a frame of data to the next filter.
Definition avfilter.c:1068
int ff_inlink_consume_frame(AVFilterLink *link, AVFrame **rframe)
Take a frame from the link's FIFO and update the link's stats.
Definition avfilter.c:1520
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define FLAGS
Definition cmdutils.c:598
#define AV_CEIL_RSHIFT(a, b)
Definition common.h:60
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
static enum AVPixelFormat pix_fmt
void ff_dnn_uninit(DnnContext *ctx)
DNNAsyncStatusType ff_dnn_get_result(DnnContext *ctx, AVFrame **in_frame, AVFrame **out_frame)
int ff_dnn_execute_model(DnnContext *ctx, AVFrame *in_frame, AVFrame *out_frame)
int ff_dnn_init(DnnContext *ctx, DNNFunctionType func_type, AVFilterContext *filter_ctx)
int ff_dnn_get_input(DnnContext *ctx, DNNData *input)
int ff_dnn_get_output(DnnContext *ctx, int input_width, int input_height, int *output_width, int *output_height)
int ff_dnn_flush(DnnContext *ctx)
int ff_dnn_filter_init_child_class(AVFilterContext *filter)
common functions for the dnn based filters
#define AVFILTER_DNN_DEFINE_CLASS(fname, backend_mask)
static int dnn_get_height_idx_by_layout(DNNLayout layout)
DNNAsyncStatusType
@ DAST_NOT_READY
@ DAST_SUCCESS
@ DNN_OV
@ DNN_ONNX
@ DNN_TH
@ DNN_TF
@ DFT_PROCESS_FRAME
static int dnn_get_width_idx_by_layout(DNNLayout layout)
@ DNN_FLOAT
static int dnn_get_channel_idx_by_layout(DNNLayout layout)
int(* init)(AVBSFContext *ctx)
Definition dts2pts.c:608
@ AV_OPT_TYPE_CONST
Special option type for declaring named constants.
Definition opt.h:298
@ AV_OPT_TYPE_INT
Underlying C type is int.
Definition opt.h:258
#define AVERROR_EOF
End of file.
Definition error.h:57
#define AVERROR(e)
Definition error.h:45
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition frame.c:64
int av_frame_copy_props(AVFrame *dst, const AVFrame *src)
Copy only "metadata" fields from src to dst.
Definition frame.c:599
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
@ AVMEDIA_TYPE_VIDEO
Definition avutil.h:200
void av_image_copy_plane(uint8_t *dst, int dst_linesize, const uint8_t *src, int src_linesize, int bytewidth, int height)
Copy image plane from src to dst.
Definition imgutils.c:374
int av_image_get_linesize(enum AVPixelFormat pix_fmt, int width, int plane)
Compute the size of an image line with format pix_fmt and width width for the plane plane.
Definition imgutils.c:76
int attribute_align_arg sws_scale(SwsContext *sws, const uint8_t *const srcSlice[], const int srcStride[], int srcSliceY, int srcSliceH, uint8_t *const dst[], const int dstStride[])
swscale wrapper, so we don't need to export the SwsContext.
Definition swscale.c:1626
SwsContext * sws_getContext(int srcW, int srcH, enum AVPixelFormat srcFormat, int dstW, int dstH, enum AVPixelFormat dstFormat, int flags, SwsFilter *srcFilter, SwsFilter *dstFilter, const double *param)
Allocate and return an SwsContext.
Definition utils.c:1919
void sws_freeContext(SwsContext *swsContext)
Free the swscaler context swsContext.
Definition utils.c:2250
@ SWS_BICUBIC
2-tap cubic B-spline
Definition swscale.h:199
misc image utilities
static av_cold void uninit(AVBitStreamFilterContext *ctx)
static int activate(AVBitStreamFilterContext *ctx)
static int config_output(AVBitStreamFilterLink *outlink)
#define FILTER_INPUTS(array)
Definition filters.h:264
#define FILTER_OUTPUTS(array)
Definition filters.h:265
#define FF_FILTER_FORWARD_WANTED(outlink, inlink)
Forward the frame_wanted_out flag from an output link to an input link.
Definition filters.h:694
#define FILTER_PIXFMTS_ARRAY(array)
Definition filters.h:244
static void ff_outlink_set_status(AVFilterLink *link, int status, int64_t pts)
Set the status field of a link from the source filter.
Definition filters.h:629
#define FF_FILTER_FORWARD_STATUS_BACK(outlink, inlink)
Forward the status on an output link to an input link.
Definition filters.h:639
#define av_always_inline
Definition attributes.h:72
#define av_cold
Definition attributes.h:117
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition internal.h:88
void avpriv_report_missing_feature(void *avc, const char *msg,...) av_printf_format(2
Log a generic warning message about a missing feature.
static enum AVPixelFormat pix_fmts[]
Definition libkvazaar.c:296
const char * desc
Definition libsvtav1.c:83
#define check(x, y, S, v)
AVOptions.
const char * av_get_pix_fmt_name(enum AVPixelFormat pix_fmt)
Return the short name for a pixel format, NULL in case pix_fmt is unknown.
Definition pixdesc.c:3380
const AVPixFmtDescriptor * av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt)
Definition pixdesc.c:3460
#define AV_PIX_FMT_FLAG_RGB
The pixel format contains RGB-like data (as opposed to YUV/grayscale).
Definition pixdesc.h:136
#define AV_PIX_FMT_GRAYF32
Definition pixfmt.h:588
AVPixelFormat
Pixel format.
Definition pixfmt.h:71
@ AV_PIX_FMT_NV12
planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (firs...
Definition pixfmt.h:96
@ AV_PIX_FMT_NONE
Definition pixfmt.h:72
@ AV_PIX_FMT_RGB24
packed RGB 8:8:8, 24bpp, RGBRGB...
Definition pixfmt.h:75
@ AV_PIX_FMT_YUV420P
planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
Definition pixfmt.h:73
@ AV_PIX_FMT_YUV422P
planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples)
Definition pixfmt.h:77
@ AV_PIX_FMT_GRAY8
Y , 8bpp.
Definition pixfmt.h:81
@ AV_PIX_FMT_CUDA
HW acceleration through CUDA.
Definition pixfmt.h:260
@ AV_PIX_FMT_YUV410P
planar YUV 4:1:0, 9bpp, (1 Cr & Cb sample per 4x4 Y samples)
Definition pixfmt.h:79
@ AV_PIX_FMT_YUV411P
planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples)
Definition pixfmt.h:80
@ AV_PIX_FMT_YUV444P
planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples)
Definition pixfmt.h:78
@ AV_PIX_FMT_BGR24
packed RGB 8:8:8, 24bpp, BGRBGR...
Definition pixfmt.h:76
@ AV_PIX_FMT_YA8
8 bits gray, 8 bits alpha
Definition pixfmt.h:140
static av_cold int preinit(AVBitStreamFilterContext *ctx)
Definition source.c:137
Describe the class of an AVClass context structure.
Definition log.h:76
An instance of a filter.
Definition avfilter.h:273
AVFilterLink ** inputs
array of pointers to input links
Definition avfilter.h:281
void * priv
private data for use by the filter
Definition avfilter.h:288
A filter pad used for either input or output.
Definition filters.h:40
This structure describes decoded (raw) audio or video data.
Definition frame.h:472
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
Definition frame.h:574
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition frame.h:493
int width
Definition frame.h:544
int height
Definition frame.h:544
int linesize[AV_NUM_DATA_POINTERS]
For video, a positive or negative value, which is typically indicating the size in bytes of each pict...
Definition frame.h:517
int format
format of the frame, -1 if unknown or unset Values correspond to enum AVPixelFormat for video frames,...
Definition frame.h:559
AVOption.
Definition opt.h:428
Descriptor that unambiguously describes how the bits of a pixel are stored in the up to 4 data planes...
Definition pixdesc.h:69
DNNDataType dt
int dims[4]
DNNLayout layout
struct SwsContext * sws_uv_scale
Main external API structure.
Definition swscale.h:227
external API header
#define av_log(a,...)
int av_usleep(unsigned usec)
Sleep for a period of time.
Definition time.c:93
static FilteringContext * filter_ctx
Definition transcode.c:52
static int64_t pts
static int flush_frame(AVFilterLink *outlink, int64_t pts, int64_t *out_pts)
static int copy_uv_planes(DnnProcessingContext *ctx, AVFrame *out, const AVFrame *in)
static av_always_inline int isPlanarYUV(enum AVPixelFormat pix_fmt)
static int check_modelinput_inlink(const DNNData *model_input, const AVFilterLink *inlink)
static int config_input(AVFilterLink *inlink)
static const AVFilterPad dnn_processing_outputs[]
static int prepare_uv_scale(AVFilterLink *outlink)
static int activate(AVFilterContext *filter_ctx)
static const AVOption dnn_processing_options[]
static av_cold void uninit(AVFilterContext *ctx)
#define LOG_FORMAT_CHANNEL_MISMATCH()
static const AVFilterPad dnn_processing_inputs[]
#define OFFSET(x)
static int config_output(AVFilterLink *outlink)
AVFrame * ff_get_video_buffer(AVFilterLink *link, int w, int h)
Request a picture buffer with a specific set of permissions.
Definition video.c:89