1 /*
2 * This file is part of FFmpeg.
3 *
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.
8 *
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.
13 *
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
17 */
18
19 /**
20 * @file
21 * implementing an object detecting filter using deep learning networks.
22 */
23
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"
29 #include "filters.h"
30 #include "dnn_filter_common.h"
31 #include "formats.h"
32 #include "internal.h"
33 #include "libavutil/time.h"
34 #include "libavutil/avstring.h"
35 #include "libavutil/detection_bbox.h"
36
37 typedef struct DnnDetectContext {
38 const AVClass *class;
39 DnnContext dnnctx;
40 float confidence;
41 char *labels_filename;
42 char **labels;
43 int label_count;
44 } DnnDetectContext;
45
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_LIBTENSORFLOW == 1)
52 { "tensorflow", "tensorflow backend flag", 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, 0, 0, FLAGS, "backend" },
53 #endif
54 #if (CONFIG_LIBOPENVINO == 1)
55 { "openvino", "openvino backend flag", 0, AV_OPT_TYPE_CONST, { .i64 = 2 }, 0, 0, FLAGS, "backend" },
56 #endif
57 DNN_COMMON_OPTIONS
58 { "confidence", "threshold of confidence", OFFSET2(confidence), AV_OPT_TYPE_FLOAT, { .dbl = 0.5 }, 0, 1, FLAGS},
59 { "labels", "path to labels file", OFFSET2(labels_filename), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, FLAGS },
60 { NULL }
61 };
62
63 AVFILTER_DEFINE_CLASS(dnn_detect);
64
dnn_detect_post_proc_ov(AVFrame * frame,DNNData * output,AVFilterContext * filter_ctx)65 static int dnn_detect_post_proc_ov(AVFrame *frame, DNNData *output, AVFilterContext *filter_ctx)
66 {
67 DnnDetectContext *ctx = filter_ctx->priv;
68 float conf_threshold = ctx->confidence;
69 int proposal_count = output->height;
70 int detect_size = output->width;
71 float *detections = output->data;
72 int nb_bboxes = 0;
73 AVFrameSideData *sd;
74 AVDetectionBBox *bbox;
75 AVDetectionBBoxHeader *header;
76
77 sd = av_frame_get_side_data(frame, AV_FRAME_DATA_DETECTION_BBOXES);
78 if (sd) {
79 av_log(filter_ctx, AV_LOG_ERROR, "already have bounding boxes in side data.\n");
80 return -1;
81 }
82
83 for (int i = 0; i < proposal_count; ++i) {
84 float conf = detections[i * detect_size + 2];
85 if (conf < conf_threshold) {
86 continue;
87 }
88 nb_bboxes++;
89 }
90
91 if (nb_bboxes == 0) {
92 av_log(filter_ctx, AV_LOG_VERBOSE, "nothing detected in this frame.\n");
93 return 0;
94 }
95
96 header = av_detection_bbox_create_side_data(frame, nb_bboxes);
97 if (!header) {
98 av_log(filter_ctx, AV_LOG_ERROR, "failed to create side data with %d bounding boxes\n", nb_bboxes);
99 return -1;
100 }
101
102 av_strlcpy(header->source, ctx->dnnctx.model_filename, sizeof(header->source));
103
104 for (int i = 0; i < proposal_count; ++i) {
105 int av_unused image_id = (int)detections[i * detect_size + 0];
106 int label_id = (int)detections[i * detect_size + 1];
107 float conf = detections[i * detect_size + 2];
108 float x0 = detections[i * detect_size + 3];
109 float y0 = detections[i * detect_size + 4];
110 float x1 = detections[i * detect_size + 5];
111 float y1 = detections[i * detect_size + 6];
112
113 bbox = av_get_detection_bbox(header, i);
114
115 if (conf < conf_threshold) {
116 continue;
117 }
118
119 bbox->x = (int)(x0 * frame->width);
120 bbox->w = (int)(x1 * frame->width) - bbox->x;
121 bbox->y = (int)(y0 * frame->height);
122 bbox->h = (int)(y1 * frame->height) - bbox->y;
123
124 bbox->detect_confidence = av_make_q((int)(conf * 10000), 10000);
125 bbox->classify_count = 0;
126
127 if (ctx->labels && label_id < ctx->label_count) {
128 av_strlcpy(bbox->detect_label, ctx->labels[label_id], sizeof(bbox->detect_label));
129 } else {
130 snprintf(bbox->detect_label, sizeof(bbox->detect_label), "%d", label_id);
131 }
132
133 nb_bboxes--;
134 if (nb_bboxes == 0) {
135 break;
136 }
137 }
138
139 return 0;
140 }
141
dnn_detect_post_proc_tf(AVFrame * frame,DNNData * output,AVFilterContext * filter_ctx)142 static int dnn_detect_post_proc_tf(AVFrame *frame, DNNData *output, AVFilterContext *filter_ctx)
143 {
144 DnnDetectContext *ctx = filter_ctx->priv;
145 int proposal_count;
146 float conf_threshold = ctx->confidence;
147 float *conf, *position, *label_id, x0, y0, x1, y1;
148 int nb_bboxes = 0;
149 AVFrameSideData *sd;
150 AVDetectionBBox *bbox;
151 AVDetectionBBoxHeader *header;
152
153 proposal_count = *(float *)(output[0].data);
154 conf = output[1].data;
155 position = output[3].data;
156 label_id = output[2].data;
157
158 sd = av_frame_get_side_data(frame, AV_FRAME_DATA_DETECTION_BBOXES);
159 if (sd) {
160 av_log(filter_ctx, AV_LOG_ERROR, "already have dnn bounding boxes in side data.\n");
161 return -1;
162 }
163
164 for (int i = 0; i < proposal_count; ++i) {
165 if (conf[i] < conf_threshold)
166 continue;
167 nb_bboxes++;
168 }
169
170 if (nb_bboxes == 0) {
171 av_log(filter_ctx, AV_LOG_VERBOSE, "nothing detected in this frame.\n");
172 return 0;
173 }
174
175 header = av_detection_bbox_create_side_data(frame, nb_bboxes);
176 if (!header) {
177 av_log(filter_ctx, AV_LOG_ERROR, "failed to create side data with %d bounding boxes\n", nb_bboxes);
178 return -1;
179 }
180
181 av_strlcpy(header->source, ctx->dnnctx.model_filename, sizeof(header->source));
182
183 for (int i = 0; i < proposal_count; ++i) {
184 y0 = position[i * 4];
185 x0 = position[i * 4 + 1];
186 y1 = position[i * 4 + 2];
187 x1 = position[i * 4 + 3];
188
189 bbox = av_get_detection_bbox(header, i);
190
191 if (conf[i] < conf_threshold) {
192 continue;
193 }
194
195 bbox->x = (int)(x0 * frame->width);
196 bbox->w = (int)(x1 * frame->width) - bbox->x;
197 bbox->y = (int)(y0 * frame->height);
198 bbox->h = (int)(y1 * frame->height) - bbox->y;
199
200 bbox->detect_confidence = av_make_q((int)(conf[i] * 10000), 10000);
201 bbox->classify_count = 0;
202
203 if (ctx->labels && label_id[i] < ctx->label_count) {
204 av_strlcpy(bbox->detect_label, ctx->labels[(int)label_id[i]], sizeof(bbox->detect_label));
205 } else {
206 snprintf(bbox->detect_label, sizeof(bbox->detect_label), "%d", (int)label_id[i]);
207 }
208
209 nb_bboxes--;
210 if (nb_bboxes == 0) {
211 break;
212 }
213 }
214 return 0;
215 }
216
dnn_detect_post_proc(AVFrame * frame,DNNData * output,uint32_t nb,AVFilterContext * filter_ctx)217 static int dnn_detect_post_proc(AVFrame *frame, DNNData *output, uint32_t nb, AVFilterContext *filter_ctx)
218 {
219 DnnDetectContext *ctx = filter_ctx->priv;
220 DnnContext *dnn_ctx = &ctx->dnnctx;
221 switch (dnn_ctx->backend_type) {
222 case DNN_OV:
223 return dnn_detect_post_proc_ov(frame, output, filter_ctx);
224 case DNN_TF:
225 return dnn_detect_post_proc_tf(frame, output, filter_ctx);
226 default:
227 avpriv_report_missing_feature(filter_ctx, "Current dnn backend does not support detect filter\n");
228 return AVERROR(EINVAL);
229 }
230 }
231
free_detect_labels(DnnDetectContext * ctx)232 static void free_detect_labels(DnnDetectContext *ctx)
233 {
234 for (int i = 0; i < ctx->label_count; i++) {
235 av_freep(&ctx->labels[i]);
236 }
237 ctx->label_count = 0;
238 av_freep(&ctx->labels);
239 }
240
read_detect_label_file(AVFilterContext * context)241 static int read_detect_label_file(AVFilterContext *context)
242 {
243 int line_len;
244 FILE *file;
245 DnnDetectContext *ctx = context->priv;
246
247 file = avpriv_fopen_utf8(ctx->labels_filename, "r");
248 if (!file){
249 av_log(context, AV_LOG_ERROR, "failed to open file %s\n", ctx->labels_filename);
250 return AVERROR(EINVAL);
251 }
252
253 while (!feof(file)) {
254 char *label;
255 char buf[256];
256 if (!fgets(buf, 256, file)) {
257 break;
258 }
259
260 line_len = strlen(buf);
261 while (line_len) {
262 int i = line_len - 1;
263 if (buf[i] == '\n' || buf[i] == '\r' || buf[i] == ' ') {
264 buf[i] = '\0';
265 line_len--;
266 } else {
267 break;
268 }
269 }
270
271 if (line_len == 0) // empty line
272 continue;
273
274 if (line_len >= AV_DETECTION_BBOX_LABEL_NAME_MAX_SIZE) {
275 av_log(context, AV_LOG_ERROR, "label %s too long\n", buf);
276 fclose(file);
277 return AVERROR(EINVAL);
278 }
279
280 label = av_strdup(buf);
281 if (!label) {
282 av_log(context, AV_LOG_ERROR, "failed to allocate memory for label %s\n", buf);
283 fclose(file);
284 return AVERROR(ENOMEM);
285 }
286
287 if (av_dynarray_add_nofree(&ctx->labels, &ctx->label_count, label) < 0) {
288 av_log(context, AV_LOG_ERROR, "failed to do av_dynarray_add\n");
289 fclose(file);
290 av_freep(&label);
291 return AVERROR(ENOMEM);
292 }
293 }
294
295 fclose(file);
296 return 0;
297 }
298
check_output_nb(DnnDetectContext * ctx,DNNBackendType backend_type,int output_nb)299 static int check_output_nb(DnnDetectContext *ctx, DNNBackendType backend_type, int output_nb)
300 {
301 switch(backend_type) {
302 case DNN_TF:
303 if (output_nb != 4) {
304 av_log(ctx, AV_LOG_ERROR, "Only support tensorflow detect model with 4 outputs, \
305 but get %d instead\n", output_nb);
306 return AVERROR(EINVAL);
307 }
308 return 0;
309 case DNN_OV:
310 if (output_nb != 1) {
311 av_log(ctx, AV_LOG_ERROR, "Dnn detect filter with openvino backend needs 1 output only, \
312 but get %d instead\n", output_nb);
313 return AVERROR(EINVAL);
314 }
315 return 0;
316 default:
317 avpriv_report_missing_feature(ctx, "Dnn detect filter does not support current backend\n");
318 return AVERROR(EINVAL);
319 }
320 return 0;
321 }
322
dnn_detect_init(AVFilterContext * context)323 static av_cold int dnn_detect_init(AVFilterContext *context)
324 {
325 DnnDetectContext *ctx = context->priv;
326 DnnContext *dnn_ctx = &ctx->dnnctx;
327 int ret;
328
329 ret = ff_dnn_init(&ctx->dnnctx, DFT_ANALYTICS_DETECT, context);
330 if (ret < 0)
331 return ret;
332 ret = check_output_nb(ctx, dnn_ctx->backend_type, dnn_ctx->nb_outputs);
333 if (ret < 0)
334 return ret;
335 ff_dnn_set_detect_post_proc(&ctx->dnnctx, dnn_detect_post_proc);
336
337 if (ctx->labels_filename) {
338 return read_detect_label_file(context);
339 }
340 return 0;
341 }
342
343 static const enum AVPixelFormat pix_fmts[] = {
344 AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
345 AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAYF32,
346 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
347 AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
348 AV_PIX_FMT_NV12,
349 AV_PIX_FMT_NONE
350 };
351
dnn_detect_flush_frame(AVFilterLink * outlink,int64_t pts,int64_t * out_pts)352 static int dnn_detect_flush_frame(AVFilterLink *outlink, int64_t pts, int64_t *out_pts)
353 {
354 DnnDetectContext *ctx = outlink->src->priv;
355 int ret;
356 DNNAsyncStatusType async_state;
357
358 ret = ff_dnn_flush(&ctx->dnnctx);
359 if (ret != 0) {
360 return -1;
361 }
362
363 do {
364 AVFrame *in_frame = NULL;
365 AVFrame *out_frame = NULL;
366 async_state = ff_dnn_get_result(&ctx->dnnctx, &in_frame, &out_frame);
367 if (async_state == DAST_SUCCESS) {
368 ret = ff_filter_frame(outlink, in_frame);
369 if (ret < 0)
370 return ret;
371 if (out_pts)
372 *out_pts = in_frame->pts + pts;
373 }
374 av_usleep(5000);
375 } while (async_state >= DAST_NOT_READY);
376
377 return 0;
378 }
379
dnn_detect_activate(AVFilterContext * filter_ctx)380 static int dnn_detect_activate(AVFilterContext *filter_ctx)
381 {
382 AVFilterLink *inlink = filter_ctx->inputs[0];
383 AVFilterLink *outlink = filter_ctx->outputs[0];
384 DnnDetectContext *ctx = filter_ctx->priv;
385 AVFrame *in = NULL;
386 int64_t pts;
387 int ret, status;
388 int got_frame = 0;
389 int async_state;
390
391 FF_FILTER_FORWARD_STATUS_BACK(outlink, inlink);
392
393 do {
394 // drain all input frames
395 ret = ff_inlink_consume_frame(inlink, &in);
396 if (ret < 0)
397 return ret;
398 if (ret > 0) {
399 if (ff_dnn_execute_model(&ctx->dnnctx, in, NULL) != 0) {
400 return AVERROR(EIO);
401 }
402 }
403 } while (ret > 0);
404
405 // drain all processed frames
406 do {
407 AVFrame *in_frame = NULL;
408 AVFrame *out_frame = NULL;
409 async_state = ff_dnn_get_result(&ctx->dnnctx, &in_frame, &out_frame);
410 if (async_state == DAST_SUCCESS) {
411 ret = ff_filter_frame(outlink, in_frame);
412 if (ret < 0)
413 return ret;
414 got_frame = 1;
415 }
416 } while (async_state == DAST_SUCCESS);
417
418 // if frame got, schedule to next filter
419 if (got_frame)
420 return 0;
421
422 if (ff_inlink_acknowledge_status(inlink, &status, &pts)) {
423 if (status == AVERROR_EOF) {
424 int64_t out_pts = pts;
425 ret = dnn_detect_flush_frame(outlink, pts, &out_pts);
426 ff_outlink_set_status(outlink, status, out_pts);
427 return ret;
428 }
429 }
430
431 FF_FILTER_FORWARD_WANTED(outlink, inlink);
432
433 return 0;
434 }
435
dnn_detect_uninit(AVFilterContext * context)436 static av_cold void dnn_detect_uninit(AVFilterContext *context)
437 {
438 DnnDetectContext *ctx = context->priv;
439 ff_dnn_uninit(&ctx->dnnctx);
440 free_detect_labels(ctx);
441 }
442
443 static const AVFilterPad dnn_detect_inputs[] = {
444 {
445 .name = "default",
446 .type = AVMEDIA_TYPE_VIDEO,
447 },
448 };
449
450 static const AVFilterPad dnn_detect_outputs[] = {
451 {
452 .name = "default",
453 .type = AVMEDIA_TYPE_VIDEO,
454 },
455 };
456
457 const AVFilter ff_vf_dnn_detect = {
458 .name = "dnn_detect",
459 .description = NULL_IF_CONFIG_SMALL("Apply DNN detect filter to the input."),
460 .priv_size = sizeof(DnnDetectContext),
461 .init = dnn_detect_init,
462 .uninit = dnn_detect_uninit,
463 FILTER_INPUTS(dnn_detect_inputs),
464 FILTER_OUTPUTS(dnn_detect_outputs),
465 FILTER_PIXFMTS_ARRAY(pix_fmts),
466 .priv_class = &dnn_detect_class,
467 .activate = dnn_detect_activate,
468 };
469