FFmpeg coverage


Directory: ../../../ffmpeg/
File: src/libavfilter/vf_dnn_classify.c
Date: 2022-11-26 13:19:19
Exec Total Coverage
Lines: 0 130 0.0%
Branches: 0 78 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 classification 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 DnnClassifyContext {
34 const AVClass *class;
35 DnnContext dnnctx;
36 float confidence;
37 char *labels_filename;
38 char *target;
39 char **labels;
40 int label_count;
41 } DnnClassifyContext;
42
43 #define OFFSET(x) offsetof(DnnClassifyContext, dnnctx.x)
44 #define OFFSET2(x) offsetof(DnnClassifyContext, x)
45 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM | AV_OPT_FLAG_VIDEO_PARAM
46 static const AVOption dnn_classify_options[] = {
47 { "dnn_backend", "DNN backend", OFFSET(backend_type), AV_OPT_TYPE_INT, { .i64 = 2 }, INT_MIN, INT_MAX, FLAGS, "backend" },
48 #if (CONFIG_LIBOPENVINO == 1)
49 { "openvino", "openvino backend flag", 0, AV_OPT_TYPE_CONST, { .i64 = 2 }, 0, 0, FLAGS, "backend" },
50 #endif
51 DNN_COMMON_OPTIONS
52 { "confidence", "threshold of confidence", OFFSET2(confidence), AV_OPT_TYPE_FLOAT, { .dbl = 0.5 }, 0, 1, FLAGS},
53 { "labels", "path to labels file", OFFSET2(labels_filename), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, FLAGS },
54 { "target", "which one to be classified", OFFSET2(target), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, FLAGS },
55 { NULL }
56 };
57
58 AVFILTER_DEFINE_CLASS(dnn_classify);
59
60 static int dnn_classify_post_proc(AVFrame *frame, DNNData *output, uint32_t bbox_index, AVFilterContext *filter_ctx)
61 {
62 DnnClassifyContext *ctx = filter_ctx->priv;
63 float conf_threshold = ctx->confidence;
64 AVDetectionBBoxHeader *header;
65 AVDetectionBBox *bbox;
66 float *classifications;
67 uint32_t label_id;
68 float confidence;
69 AVFrameSideData *sd;
70
71 if (output->channels <= 0) {
72 return -1;
73 }
74
75 sd = av_frame_get_side_data(frame, AV_FRAME_DATA_DETECTION_BBOXES);
76 if (!sd) {
77 av_log(filter_ctx, AV_LOG_ERROR, "Cannot get side data in dnn_classify_post_proc\n");
78 return -1;
79 }
80 header = (AVDetectionBBoxHeader *)sd->data;
81
82 if (bbox_index == 0) {
83 av_strlcat(header->source, ", ", sizeof(header->source));
84 av_strlcat(header->source, ctx->dnnctx.model_filename, sizeof(header->source));
85 }
86
87 classifications = output->data;
88 label_id = 0;
89 confidence= classifications[0];
90 for (int i = 1; i < output->channels; i++) {
91 if (classifications[i] > confidence) {
92 label_id = i;
93 confidence= classifications[i];
94 }
95 }
96
97 if (confidence < conf_threshold) {
98 return 0;
99 }
100
101 bbox = av_get_detection_bbox(header, bbox_index);
102 bbox->classify_confidences[bbox->classify_count] = av_make_q((int)(confidence * 10000), 10000);
103
104 if (ctx->labels && label_id < ctx->label_count) {
105 av_strlcpy(bbox->classify_labels[bbox->classify_count], ctx->labels[label_id], sizeof(bbox->classify_labels[bbox->classify_count]));
106 } else {
107 snprintf(bbox->classify_labels[bbox->classify_count], sizeof(bbox->classify_labels[bbox->classify_count]), "%d", label_id);
108 }
109
110 bbox->classify_count++;
111
112 return 0;
113 }
114
115 static void free_classify_labels(DnnClassifyContext *ctx)
116 {
117 for (int i = 0; i < ctx->label_count; i++) {
118 av_freep(&ctx->labels[i]);
119 }
120 ctx->label_count = 0;
121 av_freep(&ctx->labels);
122 }
123
124 static int read_classify_label_file(AVFilterContext *context)
125 {
126 int line_len;
127 FILE *file;
128 DnnClassifyContext *ctx = context->priv;
129
130 file = avpriv_fopen_utf8(ctx->labels_filename, "r");
131 if (!file){
132 av_log(context, AV_LOG_ERROR, "failed to open file %s\n", ctx->labels_filename);
133 return AVERROR(EINVAL);
134 }
135
136 while (!feof(file)) {
137 char *label;
138 char buf[256];
139 if (!fgets(buf, 256, file)) {
140 break;
141 }
142
143 line_len = strlen(buf);
144 while (line_len) {
145 int i = line_len - 1;
146 if (buf[i] == '\n' || buf[i] == '\r' || buf[i] == ' ') {
147 buf[i] = '\0';
148 line_len--;
149 } else {
150 break;
151 }
152 }
153
154 if (line_len == 0) // empty line
155 continue;
156
157 if (line_len >= AV_DETECTION_BBOX_LABEL_NAME_MAX_SIZE) {
158 av_log(context, AV_LOG_ERROR, "label %s too long\n", buf);
159 fclose(file);
160 return AVERROR(EINVAL);
161 }
162
163 label = av_strdup(buf);
164 if (!label) {
165 av_log(context, AV_LOG_ERROR, "failed to allocate memory for label %s\n", buf);
166 fclose(file);
167 return AVERROR(ENOMEM);
168 }
169
170 if (av_dynarray_add_nofree(&ctx->labels, &ctx->label_count, label) < 0) {
171 av_log(context, AV_LOG_ERROR, "failed to do av_dynarray_add\n");
172 fclose(file);
173 av_freep(&label);
174 return AVERROR(ENOMEM);
175 }
176 }
177
178 fclose(file);
179 return 0;
180 }
181
182 static av_cold int dnn_classify_init(AVFilterContext *context)
183 {
184 DnnClassifyContext *ctx = context->priv;
185 int ret = ff_dnn_init(&ctx->dnnctx, DFT_ANALYTICS_CLASSIFY, context);
186 if (ret < 0)
187 return ret;
188 ff_dnn_set_classify_post_proc(&ctx->dnnctx, dnn_classify_post_proc);
189
190 if (ctx->labels_filename) {
191 return read_classify_label_file(context);
192 }
193 return 0;
194 }
195
196 static const enum AVPixelFormat pix_fmts[] = {
197 AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
198 AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAYF32,
199 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
200 AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
201 AV_PIX_FMT_NV12,
202 AV_PIX_FMT_NONE
203 };
204
205 static int dnn_classify_flush_frame(AVFilterLink *outlink, int64_t pts, int64_t *out_pts)
206 {
207 DnnClassifyContext *ctx = outlink->src->priv;
208 int ret;
209 DNNAsyncStatusType async_state;
210
211 ret = ff_dnn_flush(&ctx->dnnctx);
212 if (ret != 0) {
213 return -1;
214 }
215
216 do {
217 AVFrame *in_frame = NULL;
218 AVFrame *out_frame = NULL;
219 async_state = ff_dnn_get_result(&ctx->dnnctx, &in_frame, &out_frame);
220 if (async_state == DAST_SUCCESS) {
221 ret = ff_filter_frame(outlink, in_frame);
222 if (ret < 0)
223 return ret;
224 if (out_pts)
225 *out_pts = in_frame->pts + pts;
226 }
227 av_usleep(5000);
228 } while (async_state >= DAST_NOT_READY);
229
230 return 0;
231 }
232
233 static int dnn_classify_activate(AVFilterContext *filter_ctx)
234 {
235 AVFilterLink *inlink = filter_ctx->inputs[0];
236 AVFilterLink *outlink = filter_ctx->outputs[0];
237 DnnClassifyContext *ctx = filter_ctx->priv;
238 AVFrame *in = NULL;
239 int64_t pts;
240 int ret, status;
241 int got_frame = 0;
242 int async_state;
243
244 FF_FILTER_FORWARD_STATUS_BACK(outlink, inlink);
245
246 do {
247 // drain all input frames
248 ret = ff_inlink_consume_frame(inlink, &in);
249 if (ret < 0)
250 return ret;
251 if (ret > 0) {
252 if (ff_dnn_execute_model_classification(&ctx->dnnctx, in, NULL, ctx->target) != 0) {
253 return AVERROR(EIO);
254 }
255 }
256 } while (ret > 0);
257
258 // drain all processed frames
259 do {
260 AVFrame *in_frame = NULL;
261 AVFrame *out_frame = NULL;
262 async_state = ff_dnn_get_result(&ctx->dnnctx, &in_frame, &out_frame);
263 if (async_state == DAST_SUCCESS) {
264 ret = ff_filter_frame(outlink, in_frame);
265 if (ret < 0)
266 return ret;
267 got_frame = 1;
268 }
269 } while (async_state == DAST_SUCCESS);
270
271 // if frame got, schedule to next filter
272 if (got_frame)
273 return 0;
274
275 if (ff_inlink_acknowledge_status(inlink, &status, &pts)) {
276 if (status == AVERROR_EOF) {
277 int64_t out_pts = pts;
278 ret = dnn_classify_flush_frame(outlink, pts, &out_pts);
279 ff_outlink_set_status(outlink, status, out_pts);
280 return ret;
281 }
282 }
283
284 FF_FILTER_FORWARD_WANTED(outlink, inlink);
285
286 return 0;
287 }
288
289 static av_cold void dnn_classify_uninit(AVFilterContext *context)
290 {
291 DnnClassifyContext *ctx = context->priv;
292 ff_dnn_uninit(&ctx->dnnctx);
293 free_classify_labels(ctx);
294 }
295
296 static const AVFilterPad dnn_classify_inputs[] = {
297 {
298 .name = "default",
299 .type = AVMEDIA_TYPE_VIDEO,
300 },
301 };
302
303 static const AVFilterPad dnn_classify_outputs[] = {
304 {
305 .name = "default",
306 .type = AVMEDIA_TYPE_VIDEO,
307 },
308 };
309
310 const AVFilter ff_vf_dnn_classify = {
311 .name = "dnn_classify",
312 .description = NULL_IF_CONFIG_SMALL("Apply DNN classify filter to the input."),
313 .priv_size = sizeof(DnnClassifyContext),
314 .init = dnn_classify_init,
315 .uninit = dnn_classify_uninit,
316 FILTER_INPUTS(dnn_classify_inputs),
317 FILTER_OUTPUTS(dnn_classify_outputs),
318 FILTER_PIXFMTS_ARRAY(pix_fmts),
319 .priv_class = &dnn_classify_class,
320 .activate = dnn_classify_activate,
321 };
322