2 * This file is part of FFmpeg.
4 * FFmpeg is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * FFmpeg is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with FFmpeg; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 * implementing an object detecting filter using deep learning networks.
24 #include "libavformat/avio.h"
25 #include "libavutil/opt.h"
26 #include "libavutil/pixdesc.h"
27 #include "libavutil/avassert.h"
28 #include "libavutil/imgutils.h"
30 #include "dnn_filter_common.h"
33 #include "libavutil/time.h"
34 #include "libavutil/avstring.h"
35 #include "libavutil/detection_bbox.h"
37 typedef struct DnnDetectContext {
41 char *labels_filename;
46 #define OFFSET(x) offsetof(DnnDetectContext, dnnctx.x)
47 #define OFFSET2(x) offsetof(DnnDetectContext, x)
48 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM | AV_OPT_FLAG_VIDEO_PARAM
49 static const AVOption dnn_detect_options[] = {
50 { "dnn_backend", "DNN backend", OFFSET(backend_type), AV_OPT_TYPE_INT, { .i64 = 2 }, INT_MIN, INT_MAX, FLAGS, "backend" },
51 #if (CONFIG_LIBOPENVINO == 1)
52 { "openvino", "openvino backend flag", 0, AV_OPT_TYPE_CONST, { .i64 = 2 }, 0, 0, FLAGS, "backend" },
55 { "confidence", "threshold of confidence", OFFSET2(confidence), AV_OPT_TYPE_FLOAT, { .dbl = 0.5 }, 0, 1, FLAGS},
56 { "labels", "path to labels file", OFFSET2(labels_filename), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, FLAGS },
60 AVFILTER_DEFINE_CLASS(dnn_detect);
62 static int dnn_detect_post_proc(AVFrame *frame, DNNData *output, uint32_t nb, AVFilterContext *filter_ctx)
64 DnnDetectContext *ctx = filter_ctx->priv;
65 float conf_threshold = ctx->confidence;
66 int proposal_count = output->height;
67 int detect_size = output->width;
68 float *detections = output->data;
71 AVDetectionBBox *bbox;
72 AVDetectionBBoxHeader *header;
74 sd = av_frame_get_side_data(frame, AV_FRAME_DATA_DETECTION_BBOXES);
76 av_log(filter_ctx, AV_LOG_ERROR, "already have bounding boxes in side data.\n");
80 for (int i = 0; i < proposal_count; ++i) {
81 float conf = detections[i * detect_size + 2];
82 if (conf < conf_threshold) {
89 av_log(filter_ctx, AV_LOG_VERBOSE, "nothing detected in this frame.\n");
93 header = av_detection_bbox_create_side_data(frame, nb_bboxes);
95 av_log(filter_ctx, AV_LOG_ERROR, "failed to create side data with %d bounding boxes\n", nb_bboxes);
99 av_strlcpy(header->source, ctx->dnnctx.model_filename, sizeof(header->source));
101 for (int i = 0; i < proposal_count; ++i) {
102 int av_unused image_id = (int)detections[i * detect_size + 0];
103 int label_id = (int)detections[i * detect_size + 1];
104 float conf = detections[i * detect_size + 2];
105 float x0 = detections[i * detect_size + 3];
106 float y0 = detections[i * detect_size + 4];
107 float x1 = detections[i * detect_size + 5];
108 float y1 = detections[i * detect_size + 6];
110 bbox = av_get_detection_bbox(header, i);
112 if (conf < conf_threshold) {
116 bbox->x = (int)(x0 * frame->width);
117 bbox->w = (int)(x1 * frame->width) - bbox->x;
118 bbox->y = (int)(y0 * frame->height);
119 bbox->h = (int)(y1 * frame->height) - bbox->y;
121 bbox->detect_confidence = av_make_q((int)(conf * 10000), 10000);
122 bbox->classify_count = 0;
124 if (ctx->labels && label_id < ctx->label_count) {
125 av_strlcpy(bbox->detect_label, ctx->labels[label_id], sizeof(bbox->detect_label));
127 snprintf(bbox->detect_label, sizeof(bbox->detect_label), "%d", label_id);
131 if (nb_bboxes == 0) {
139 static void free_detect_labels(DnnDetectContext *ctx)
141 for (int i = 0; i < ctx->label_count; i++) {
142 av_freep(&ctx->labels[i]);
144 ctx->label_count = 0;
145 av_freep(&ctx->labels);
148 static int read_detect_label_file(AVFilterContext *context)
152 DnnDetectContext *ctx = context->priv;
154 file = av_fopen_utf8(ctx->labels_filename, "r");
156 av_log(context, AV_LOG_ERROR, "failed to open file %s\n", ctx->labels_filename);
157 return AVERROR(EINVAL);
160 while (!feof(file)) {
163 if (!fgets(buf, 256, file)) {
167 line_len = strlen(buf);
169 int i = line_len - 1;
170 if (buf[i] == '\n' || buf[i] == '\r' || buf[i] == ' ') {
178 if (line_len == 0) // empty line
181 if (line_len >= AV_DETECTION_BBOX_LABEL_NAME_MAX_SIZE) {
182 av_log(context, AV_LOG_ERROR, "label %s too long\n", buf);
184 return AVERROR(EINVAL);
187 label = av_strdup(buf);
189 av_log(context, AV_LOG_ERROR, "failed to allocate memory for label %s\n", buf);
191 return AVERROR(ENOMEM);
194 if (av_dynarray_add_nofree(&ctx->labels, &ctx->label_count, label) < 0) {
195 av_log(context, AV_LOG_ERROR, "failed to do av_dynarray_add\n");
198 return AVERROR(ENOMEM);
206 static av_cold int dnn_detect_init(AVFilterContext *context)
208 DnnDetectContext *ctx = context->priv;
209 int ret = ff_dnn_init(&ctx->dnnctx, DFT_ANALYTICS_DETECT, context);
212 ff_dnn_set_detect_post_proc(&ctx->dnnctx, dnn_detect_post_proc);
214 if (ctx->labels_filename) {
215 return read_detect_label_file(context);
220 static int dnn_detect_query_formats(AVFilterContext *context)
222 static const enum AVPixelFormat pix_fmts[] = {
223 AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
224 AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAYF32,
225 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
226 AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
230 AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
231 return ff_set_common_formats(context, fmts_list);
234 static int dnn_detect_filter_frame(AVFilterLink *inlink, AVFrame *in)
236 AVFilterContext *context = inlink->dst;
237 AVFilterLink *outlink = context->outputs[0];
238 DnnDetectContext *ctx = context->priv;
239 DNNReturnType dnn_result;
241 dnn_result = ff_dnn_execute_model(&ctx->dnnctx, in, in);
242 if (dnn_result != DNN_SUCCESS){
243 av_log(ctx, AV_LOG_ERROR, "failed to execute model\n");
248 return ff_filter_frame(outlink, in);
251 static int dnn_detect_activate_sync(AVFilterContext *filter_ctx)
253 AVFilterLink *inlink = filter_ctx->inputs[0];
254 AVFilterLink *outlink = filter_ctx->outputs[0];
260 FF_FILTER_FORWARD_STATUS_BACK(outlink, inlink);
263 // drain all input frames
264 ret = ff_inlink_consume_frame(inlink, &in);
268 ret = dnn_detect_filter_frame(inlink, in);
275 // if frame got, schedule to next filter
279 if (ff_inlink_acknowledge_status(inlink, &status, &pts)) {
280 if (status == AVERROR_EOF) {
281 ff_outlink_set_status(outlink, status, pts);
286 FF_FILTER_FORWARD_WANTED(outlink, inlink);
288 return FFERROR_NOT_READY;
291 static int dnn_detect_flush_frame(AVFilterLink *outlink, int64_t pts, int64_t *out_pts)
293 DnnDetectContext *ctx = outlink->src->priv;
295 DNNAsyncStatusType async_state;
297 ret = ff_dnn_flush(&ctx->dnnctx);
298 if (ret != DNN_SUCCESS) {
303 AVFrame *in_frame = NULL;
304 AVFrame *out_frame = NULL;
305 async_state = ff_dnn_get_async_result(&ctx->dnnctx, &in_frame, &out_frame);
307 av_assert0(in_frame == out_frame);
308 ret = ff_filter_frame(outlink, out_frame);
312 *out_pts = out_frame->pts + pts;
315 } while (async_state >= DAST_NOT_READY);
320 static int dnn_detect_activate_async(AVFilterContext *filter_ctx)
322 AVFilterLink *inlink = filter_ctx->inputs[0];
323 AVFilterLink *outlink = filter_ctx->outputs[0];
324 DnnDetectContext *ctx = filter_ctx->priv;
331 FF_FILTER_FORWARD_STATUS_BACK(outlink, inlink);
334 // drain all input frames
335 ret = ff_inlink_consume_frame(inlink, &in);
339 if (ff_dnn_execute_model_async(&ctx->dnnctx, in, in) != DNN_SUCCESS) {
345 // drain all processed frames
347 AVFrame *in_frame = NULL;
348 AVFrame *out_frame = NULL;
349 async_state = ff_dnn_get_async_result(&ctx->dnnctx, &in_frame, &out_frame);
351 av_assert0(in_frame == out_frame);
352 ret = ff_filter_frame(outlink, out_frame);
357 } while (async_state == DAST_SUCCESS);
359 // if frame got, schedule to next filter
363 if (ff_inlink_acknowledge_status(inlink, &status, &pts)) {
364 if (status == AVERROR_EOF) {
365 int64_t out_pts = pts;
366 ret = dnn_detect_flush_frame(outlink, pts, &out_pts);
367 ff_outlink_set_status(outlink, status, out_pts);
372 FF_FILTER_FORWARD_WANTED(outlink, inlink);
377 static int dnn_detect_activate(AVFilterContext *filter_ctx)
379 DnnDetectContext *ctx = filter_ctx->priv;
381 if (ctx->dnnctx.async)
382 return dnn_detect_activate_async(filter_ctx);
384 return dnn_detect_activate_sync(filter_ctx);
387 static av_cold void dnn_detect_uninit(AVFilterContext *context)
389 DnnDetectContext *ctx = context->priv;
390 ff_dnn_uninit(&ctx->dnnctx);
391 free_detect_labels(ctx);
394 static const AVFilterPad dnn_detect_inputs[] = {
397 .type = AVMEDIA_TYPE_VIDEO,
402 static const AVFilterPad dnn_detect_outputs[] = {
405 .type = AVMEDIA_TYPE_VIDEO,
410 const AVFilter ff_vf_dnn_detect = {
411 .name = "dnn_detect",
412 .description = NULL_IF_CONFIG_SMALL("Apply DNN detect filter to the input."),
413 .priv_size = sizeof(DnnDetectContext),
414 .init = dnn_detect_init,
415 .uninit = dnn_detect_uninit,
416 .query_formats = dnn_detect_query_formats,
417 .inputs = dnn_detect_inputs,
418 .outputs = dnn_detect_outputs,
419 .priv_class = &dnn_detect_class,
420 .activate = dnn_detect_activate,