4 * This file is part of FFmpeg.
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.
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.
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
23 * DNN OpenVINO backend implementation.
26 #include "dnn_backend_openvino.h"
27 #include "dnn_io_proc.h"
28 #include "libavformat/avio.h"
29 #include "libavutil/avassert.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/avstring.h"
32 #include "../internal.h"
34 #include "safe_queue.h"
35 #include <c_api/ie_c_api.h>
37 typedef struct OVOptions{
44 typedef struct OVContext {
49 typedef struct OVModel{
53 ie_network_t *network;
54 ie_executable_network_t *exe_network;
55 ie_infer_request_t *infer_request;
57 /* for async execution */
58 SafeQueue *request_queue; // holds RequestItem
59 Queue *task_queue; // holds TaskItem
62 typedef struct TaskItem {
64 const char *input_name;
66 const char *output_name;
73 typedef struct RequestItem {
74 ie_infer_request_t *infer_request;
77 ie_complete_call_back_t callback;
80 #define APPEND_STRING(generated_string, iterate_string) \
81 generated_string = generated_string ? av_asprintf("%s %s", generated_string, iterate_string) : \
82 av_asprintf("%s", iterate_string);
84 #define OFFSET(x) offsetof(OVContext, x)
85 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM
86 static const AVOption dnn_openvino_options[] = {
87 { "device", "device to run model", OFFSET(options.device_type), AV_OPT_TYPE_STRING, { .str = "CPU" }, 0, 0, FLAGS },
88 { "nireq", "number of request", OFFSET(options.nireq), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, FLAGS },
89 { "batch_size", "batch size per request", OFFSET(options.batch_size), AV_OPT_TYPE_INT, { .i64 = 1 }, 1, 1000, FLAGS},
90 { "input_resizable", "can input be resizable or not", OFFSET(options.input_resizable), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
94 AVFILTER_DEFINE_CLASS(dnn_openvino);
96 static DNNDataType precision_to_datatype(precision_e precision)
105 av_assert0(!"not supported yet.");
110 static int get_datatype_size(DNNDataType dt)
115 return sizeof(float);
117 return sizeof(uint8_t);
119 av_assert0(!"not supported yet.");
124 static DNNReturnType fill_model_input_ov(OVModel *ov_model, RequestItem *request)
127 precision_e precision;
128 ie_blob_buffer_t blob_buffer;
129 OVContext *ctx = &ov_model->ctx;
132 ie_blob_t *input_blob = NULL;
133 TaskItem *task = request->tasks[0];
135 status = ie_infer_request_get_blob(request->infer_request, task->input_name, &input_blob);
137 av_log(ctx, AV_LOG_ERROR, "Failed to get input blob with name %s\n", task->input_name);
141 status |= ie_blob_get_dims(input_blob, &dims);
142 status |= ie_blob_get_precision(input_blob, &precision);
144 ie_blob_free(&input_blob);
145 av_log(ctx, AV_LOG_ERROR, "Failed to get input blob dims/precision\n");
149 status = ie_blob_get_buffer(input_blob, &blob_buffer);
151 ie_blob_free(&input_blob);
152 av_log(ctx, AV_LOG_ERROR, "Failed to get input blob buffer\n");
156 input.height = dims.dims[2];
157 input.width = dims.dims[3];
158 input.channels = dims.dims[1];
159 input.data = blob_buffer.buffer;
160 input.dt = precision_to_datatype(precision);
161 // all models in openvino open model zoo use BGR as input,
162 // change to be an option when necessary.
163 input.order = DCO_BGR;
165 av_assert0(request->task_count <= dims.dims[0]);
166 for (int i = 0; i < request->task_count; ++i) {
167 task = request->tasks[i];
168 if (task->do_ioproc) {
169 if (ov_model->model->frame_pre_proc != NULL) {
170 ov_model->model->frame_pre_proc(task->in_frame, &input, ov_model->model->filter_ctx);
172 ff_proc_from_frame_to_dnn(task->in_frame, &input, ov_model->model->func_type, ctx);
175 input.data = (uint8_t *)input.data
176 + input.width * input.height * input.channels * get_datatype_size(input.dt);
178 ie_blob_free(&input_blob);
183 static void infer_completion_callback(void *args)
186 precision_e precision;
188 RequestItem *request = args;
189 TaskItem *task = request->tasks[0];
190 SafeQueue *requestq = task->ov_model->request_queue;
191 ie_blob_t *output_blob = NULL;
192 ie_blob_buffer_t blob_buffer;
194 OVContext *ctx = &task->ov_model->ctx;
196 status = ie_infer_request_get_blob(request->infer_request, task->output_name, &output_blob);
198 //incorrect output name
199 char *model_output_name = NULL;
200 char *all_output_names = NULL;
201 size_t model_output_count = 0;
202 av_log(ctx, AV_LOG_ERROR, "Failed to get model output data\n");
203 status = ie_network_get_outputs_number(task->ov_model->network, &model_output_count);
204 for (size_t i = 0; i < model_output_count; i++) {
205 status = ie_network_get_output_name(task->ov_model->network, i, &model_output_name);
206 APPEND_STRING(all_output_names, model_output_name)
208 av_log(ctx, AV_LOG_ERROR,
209 "output \"%s\" may not correct, all output(s) are: \"%s\"\n",
210 task->output_name, all_output_names);
214 status = ie_blob_get_buffer(output_blob, &blob_buffer);
216 ie_blob_free(&output_blob);
217 av_log(ctx, AV_LOG_ERROR, "Failed to access output memory\n");
221 status |= ie_blob_get_dims(output_blob, &dims);
222 status |= ie_blob_get_precision(output_blob, &precision);
224 ie_blob_free(&output_blob);
225 av_log(ctx, AV_LOG_ERROR, "Failed to get dims or precision of output\n");
229 output.channels = dims.dims[1];
230 output.height = dims.dims[2];
231 output.width = dims.dims[3];
232 output.dt = precision_to_datatype(precision);
233 output.data = blob_buffer.buffer;
235 av_assert0(request->task_count <= dims.dims[0]);
236 av_assert0(request->task_count >= 1);
237 for (int i = 0; i < request->task_count; ++i) {
238 task = request->tasks[i];
240 switch (task->ov_model->model->func_type) {
241 case DFT_PROCESS_FRAME:
242 if (task->do_ioproc) {
243 if (task->ov_model->model->frame_post_proc != NULL) {
244 task->ov_model->model->frame_post_proc(task->out_frame, &output, task->ov_model->model->filter_ctx);
246 ff_proc_from_dnn_to_frame(task->out_frame, &output, ctx);
249 task->out_frame->width = output.width;
250 task->out_frame->height = output.height;
253 case DFT_ANALYTICS_DETECT:
254 if (!task->ov_model->model->detect_post_proc) {
255 av_log(ctx, AV_LOG_ERROR, "detect filter needs to provide post proc\n");
258 task->ov_model->model->detect_post_proc(task->out_frame, &output, 1, task->ov_model->model->filter_ctx);
261 av_assert0(!"should not reach here");
266 output.data = (uint8_t *)output.data
267 + output.width * output.height * output.channels * get_datatype_size(output.dt);
269 ie_blob_free(&output_blob);
271 request->task_count = 0;
274 if (ff_safe_queue_push_back(requestq, request) < 0) {
275 av_log(ctx, AV_LOG_ERROR, "Failed to push back request_queue.\n");
281 static DNNReturnType init_model_ov(OVModel *ov_model, const char *input_name, const char *output_name)
283 OVContext *ctx = &ov_model->ctx;
285 ie_available_devices_t a_dev;
286 ie_config_t config = {NULL, NULL, NULL};
287 char *all_dev_names = NULL;
290 if (ctx->options.batch_size <= 0) {
291 ctx->options.batch_size = 1;
294 if (ctx->options.batch_size > 1) {
295 input_shapes_t input_shapes;
296 status = ie_network_get_input_shapes(ov_model->network, &input_shapes);
299 for (int i = 0; i < input_shapes.shape_num; i++)
300 input_shapes.shapes[i].shape.dims[0] = ctx->options.batch_size;
301 status = ie_network_reshape(ov_model->network, input_shapes);
302 ie_network_input_shapes_free(&input_shapes);
307 // The order of dims in the openvino is fixed and it is always NCHW for 4-D data.
308 // while we pass NHWC data from FFmpeg to openvino
309 status = ie_network_set_input_layout(ov_model->network, input_name, NHWC);
311 av_log(ctx, AV_LOG_ERROR, "Failed to set layout as NHWC for input %s\n", input_name);
314 status = ie_network_set_output_layout(ov_model->network, output_name, NHWC);
316 av_log(ctx, AV_LOG_ERROR, "Failed to set layout as NHWC for output %s\n", output_name);
320 // all models in openvino open model zoo use BGR with range [0.0f, 255.0f] as input,
321 // we don't have a AVPixelFormat to descibe it, so we'll use AV_PIX_FMT_BGR24 and
322 // ask openvino to do the conversion internally.
323 // the current supported SR model (frame processing) is generated from tensorflow model,
324 // and its input is Y channel as float with range [0.0f, 1.0f], so do not set for this case.
325 // TODO: we need to get a final clear&general solution with all backends/formats considered.
326 if (ov_model->model->func_type != DFT_PROCESS_FRAME) {
327 status = ie_network_set_input_precision(ov_model->network, input_name, U8);
329 av_log(ctx, AV_LOG_ERROR, "Failed to set input precision as U8 for %s\n", input_name);
334 status = ie_core_load_network(ov_model->core, ov_model->network, ctx->options.device_type, &config, &ov_model->exe_network);
336 av_log(ctx, AV_LOG_ERROR, "Failed to load OpenVINO model network\n");
337 status = ie_core_get_available_devices(ov_model->core, &a_dev);
339 av_log(ctx, AV_LOG_ERROR, "Failed to get available devices\n");
342 for (int i = 0; i < a_dev.num_devices; i++) {
343 APPEND_STRING(all_dev_names, a_dev.devices[i])
345 av_log(ctx, AV_LOG_ERROR,"device %s may not be supported, all available devices are: \"%s\"\n",
346 ctx->options.device_type, all_dev_names);
350 // create infer_request for sync execution
351 status = ie_exec_network_create_infer_request(ov_model->exe_network, &ov_model->infer_request);
355 // create infer_requests for async execution
356 if (ctx->options.nireq <= 0) {
357 // the default value is a rough estimation
358 ctx->options.nireq = av_cpu_count() / 2 + 1;
361 ov_model->request_queue = ff_safe_queue_create();
362 if (!ov_model->request_queue) {
366 for (int i = 0; i < ctx->options.nireq; i++) {
367 RequestItem *item = av_mallocz(sizeof(*item));
372 item->callback.completeCallBackFunc = infer_completion_callback;
373 item->callback.args = item;
374 if (ff_safe_queue_push_back(ov_model->request_queue, item) < 0) {
379 status = ie_exec_network_create_infer_request(ov_model->exe_network, &item->infer_request);
384 item->tasks = av_malloc_array(ctx->options.batch_size, sizeof(*item->tasks));
388 item->task_count = 0;
391 ov_model->task_queue = ff_queue_create();
392 if (!ov_model->task_queue) {
399 ff_dnn_free_model_ov(&ov_model->model);
403 static DNNReturnType execute_model_ov(RequestItem *request)
407 TaskItem *task = request->tasks[0];
408 OVContext *ctx = &task->ov_model->ctx;
411 if (request->task_count < ctx->options.batch_size) {
412 if (ff_safe_queue_push_front(task->ov_model->request_queue, request) < 0) {
413 av_log(ctx, AV_LOG_ERROR, "Failed to push back request_queue.\n");
418 ret = fill_model_input_ov(task->ov_model, request);
419 if (ret != DNN_SUCCESS) {
422 status = ie_infer_set_completion_callback(request->infer_request, &request->callback);
424 av_log(ctx, AV_LOG_ERROR, "Failed to set completion callback for inference\n");
427 status = ie_infer_request_infer_async(request->infer_request);
429 av_log(ctx, AV_LOG_ERROR, "Failed to start async inference\n");
434 ret = fill_model_input_ov(task->ov_model, request);
435 if (ret != DNN_SUCCESS) {
438 status = ie_infer_request_infer(request->infer_request);
440 av_log(ctx, AV_LOG_ERROR, "Failed to start synchronous model inference\n");
443 infer_completion_callback(request);
444 return task->done ? DNN_SUCCESS : DNN_ERROR;
448 static DNNReturnType get_input_ov(void *model, DNNData *input, const char *input_name)
450 OVModel *ov_model = model;
451 OVContext *ctx = &ov_model->ctx;
452 char *model_input_name = NULL;
453 char *all_input_names = NULL;
455 size_t model_input_count = 0;
457 precision_e precision;
458 int input_resizable = ctx->options.input_resizable;
460 status = ie_network_get_inputs_number(ov_model->network, &model_input_count);
462 av_log(ctx, AV_LOG_ERROR, "Failed to get input count\n");
466 for (size_t i = 0; i < model_input_count; i++) {
467 status = ie_network_get_input_name(ov_model->network, i, &model_input_name);
469 av_log(ctx, AV_LOG_ERROR, "Failed to get No.%d input's name\n", (int)i);
472 if (strcmp(model_input_name, input_name) == 0) {
473 ie_network_name_free(&model_input_name);
474 status |= ie_network_get_input_dims(ov_model->network, input_name, &dims);
475 status |= ie_network_get_input_precision(ov_model->network, input_name, &precision);
477 av_log(ctx, AV_LOG_ERROR, "Failed to get No.%d input's dims or precision\n", (int)i);
481 input->channels = dims.dims[1];
482 input->height = input_resizable ? -1 : dims.dims[2];
483 input->width = input_resizable ? -1 : dims.dims[3];
484 input->dt = precision_to_datatype(precision);
487 //incorrect input name
488 APPEND_STRING(all_input_names, model_input_name)
491 ie_network_name_free(&model_input_name);
494 av_log(ctx, AV_LOG_ERROR, "Could not find \"%s\" in model, all input(s) are: \"%s\"\n", input_name, all_input_names);
498 static DNNReturnType get_output_ov(void *model, const char *input_name, int input_width, int input_height,
499 const char *output_name, int *output_width, int *output_height)
502 OVModel *ov_model = model;
503 OVContext *ctx = &ov_model->ctx;
506 AVFrame *in_frame = NULL;
507 AVFrame *out_frame = NULL;
508 TaskItem *ptask = &task;
510 input_shapes_t input_shapes;
512 if (ov_model->model->func_type != DFT_PROCESS_FRAME) {
513 av_log(ctx, AV_LOG_ERROR, "Get output dim only when processing frame.\n");
517 if (ctx->options.input_resizable) {
518 status = ie_network_get_input_shapes(ov_model->network, &input_shapes);
519 input_shapes.shapes->shape.dims[2] = input_height;
520 input_shapes.shapes->shape.dims[3] = input_width;
521 status |= ie_network_reshape(ov_model->network, input_shapes);
522 ie_network_input_shapes_free(&input_shapes);
524 av_log(ctx, AV_LOG_ERROR, "Failed to reshape input size for %s\n", input_name);
529 if (!ov_model->exe_network) {
530 if (init_model_ov(ov_model, input_name, output_name) != DNN_SUCCESS) {
531 av_log(ctx, AV_LOG_ERROR, "Failed init OpenVINO exectuable network or inference request\n");
536 in_frame = av_frame_alloc();
538 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for input frame\n");
541 in_frame->width = input_width;
542 in_frame->height = input_height;
544 out_frame = av_frame_alloc();
546 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for output frame\n");
547 av_frame_free(&in_frame);
554 task.input_name = input_name;
555 task.in_frame = in_frame;
556 task.output_name = output_name;
557 task.out_frame = out_frame;
558 task.ov_model = ov_model;
560 request.infer_request = ov_model->infer_request;
561 request.task_count = 1;
562 request.tasks = &ptask;
564 ret = execute_model_ov(&request);
565 *output_width = out_frame->width;
566 *output_height = out_frame->height;
568 av_frame_free(&out_frame);
569 av_frame_free(&in_frame);
573 DNNModel *ff_dnn_load_model_ov(const char *model_filename, DNNFunctionType func_type, const char *options, AVFilterContext *filter_ctx)
575 DNNModel *model = NULL;
576 OVModel *ov_model = NULL;
577 OVContext *ctx = NULL;
580 model = av_mallocz(sizeof(DNNModel));
585 ov_model = av_mallocz(sizeof(OVModel));
590 model->model = ov_model;
591 ov_model->model = model;
592 ov_model->ctx.class = &dnn_openvino_class;
593 ctx = &ov_model->ctx;
596 av_opt_set_defaults(ctx);
597 if (av_opt_set_from_string(ctx, options, NULL, "=", "&") < 0) {
598 av_log(ctx, AV_LOG_ERROR, "Failed to parse options \"%s\"\n", options);
602 status = ie_core_create("", &ov_model->core);
606 status = ie_core_read_network(ov_model->core, model_filename, NULL, &ov_model->network);
609 ver = ie_c_api_version();
610 av_log(ctx, AV_LOG_ERROR, "Failed to read the network from model file %s,\n"
611 "Please check if the model version matches the runtime OpenVINO %s\n",
612 model_filename, ver.api_version);
613 ie_version_free(&ver);
617 model->get_input = &get_input_ov;
618 model->get_output = &get_output_ov;
619 model->options = options;
620 model->filter_ctx = filter_ctx;
621 model->func_type = func_type;
626 ff_dnn_free_model_ov(&model);
630 DNNReturnType ff_dnn_execute_model_ov(const DNNModel *model, const char *input_name, AVFrame *in_frame,
631 const char **output_names, uint32_t nb_output, AVFrame *out_frame)
633 OVModel *ov_model = model->model;
634 OVContext *ctx = &ov_model->ctx;
637 TaskItem *ptask = &task;
640 av_log(ctx, AV_LOG_ERROR, "in frame is NULL when execute model.\n");
644 if (!out_frame && model->func_type == DFT_PROCESS_FRAME) {
645 av_log(ctx, AV_LOG_ERROR, "out frame is NULL when execute model.\n");
649 if (nb_output != 1) {
650 // currently, the filter does not need multiple outputs,
651 // so we just pending the support until we really need it.
652 avpriv_report_missing_feature(ctx, "multiple outputs");
656 if (ctx->options.batch_size > 1) {
657 avpriv_report_missing_feature(ctx, "batch mode for sync execution");
661 if (!ov_model->exe_network) {
662 if (init_model_ov(ov_model, input_name, output_names[0]) != DNN_SUCCESS) {
663 av_log(ctx, AV_LOG_ERROR, "Failed init OpenVINO exectuable network or inference request\n");
671 task.input_name = input_name;
672 task.in_frame = in_frame;
673 task.output_name = output_names[0];
674 task.out_frame = out_frame;
675 task.ov_model = ov_model;
677 request.infer_request = ov_model->infer_request;
678 request.task_count = 1;
679 request.tasks = &ptask;
681 return execute_model_ov(&request);
684 DNNReturnType ff_dnn_execute_model_async_ov(const DNNModel *model, const char *input_name, AVFrame *in_frame,
685 const char **output_names, uint32_t nb_output, AVFrame *out_frame)
687 OVModel *ov_model = model->model;
688 OVContext *ctx = &ov_model->ctx;
689 RequestItem *request;
693 av_log(ctx, AV_LOG_ERROR, "in frame is NULL when async execute model.\n");
697 if (!out_frame && model->func_type == DFT_PROCESS_FRAME) {
698 av_log(ctx, AV_LOG_ERROR, "out frame is NULL when async execute model.\n");
702 if (!ov_model->exe_network) {
703 if (init_model_ov(ov_model, input_name, output_names[0]) != DNN_SUCCESS) {
704 av_log(ctx, AV_LOG_ERROR, "Failed init OpenVINO exectuable network or inference request\n");
709 task = av_malloc(sizeof(*task));
711 av_log(ctx, AV_LOG_ERROR, "unable to alloc memory for task item.\n");
718 task->input_name = input_name;
719 task->in_frame = in_frame;
720 task->output_name = output_names[0];
721 task->out_frame = out_frame;
722 task->ov_model = ov_model;
723 if (ff_queue_push_back(ov_model->task_queue, task) < 0) {
725 av_log(ctx, AV_LOG_ERROR, "unable to push back task_queue.\n");
729 request = ff_safe_queue_pop_front(ov_model->request_queue);
731 av_log(ctx, AV_LOG_ERROR, "unable to get infer request.\n");
735 request->tasks[request->task_count++] = task;
736 return execute_model_ov(request);
739 DNNAsyncStatusType ff_dnn_get_async_result_ov(const DNNModel *model, AVFrame **in, AVFrame **out)
741 OVModel *ov_model = model->model;
742 TaskItem *task = ff_queue_peek_front(ov_model->task_queue);
745 return DAST_EMPTY_QUEUE;
749 return DAST_NOT_READY;
752 *in = task->in_frame;
753 *out = task->out_frame;
754 ff_queue_pop_front(ov_model->task_queue);
760 DNNReturnType ff_dnn_flush_ov(const DNNModel *model)
762 OVModel *ov_model = model->model;
763 OVContext *ctx = &ov_model->ctx;
764 RequestItem *request;
768 request = ff_safe_queue_pop_front(ov_model->request_queue);
770 av_log(ctx, AV_LOG_ERROR, "unable to get infer request.\n");
774 if (request->task_count == 0) {
775 // no pending task need to flush
776 if (ff_safe_queue_push_back(ov_model->request_queue, request) < 0) {
777 av_log(ctx, AV_LOG_ERROR, "Failed to push back request_queue.\n");
783 ret = fill_model_input_ov(ov_model, request);
784 if (ret != DNN_SUCCESS) {
785 av_log(ctx, AV_LOG_ERROR, "Failed to fill model input.\n");
788 status = ie_infer_set_completion_callback(request->infer_request, &request->callback);
790 av_log(ctx, AV_LOG_ERROR, "Failed to set completion callback for inference\n");
793 status = ie_infer_request_infer_async(request->infer_request);
795 av_log(ctx, AV_LOG_ERROR, "Failed to start async inference\n");
802 void ff_dnn_free_model_ov(DNNModel **model)
805 OVModel *ov_model = (*model)->model;
806 while (ff_safe_queue_size(ov_model->request_queue) != 0) {
807 RequestItem *item = ff_safe_queue_pop_front(ov_model->request_queue);
808 if (item && item->infer_request) {
809 ie_infer_request_free(&item->infer_request);
811 av_freep(&item->tasks);
814 ff_safe_queue_destroy(ov_model->request_queue);
816 while (ff_queue_size(ov_model->task_queue) != 0) {
817 TaskItem *item = ff_queue_pop_front(ov_model->task_queue);
818 av_frame_free(&item->in_frame);
819 av_frame_free(&item->out_frame);
822 ff_queue_destroy(ov_model->task_queue);
824 if (ov_model->infer_request)
825 ie_infer_request_free(&ov_model->infer_request);
826 if (ov_model->exe_network)
827 ie_exec_network_free(&ov_model->exe_network);
828 if (ov_model->network)
829 ie_network_free(&ov_model->network);
831 ie_core_free(&ov_model->core);