FFmpeg coverage


Directory: ../../../ffmpeg/
File: src/libavfilter/vf_dnn_detect.c
Date: 2022-12-05 03:11:11
Exec Total Coverage
Lines: 0 224 0.0%
Functions: 0 10 0.0%
Branches: 0 114 0.0%

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