FFmpeg
Loading...
Searching...
No Matches
dnn_backend_tf.c
Go to the documentation of this file.
1/*
2 * Copyright (c) 2018 Sergey Lavrushkin
3 *
4 * This file is part of FFmpeg.
5 *
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.
10 *
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.
15 *
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
19 */
20
21/**
22 * @file
23 * DNN tensorflow backend implementation.
24 */
25
26#include "libavformat/avio.h"
27#include "libavutil/avassert.h"
28#include "libavutil/avstring.h"
29#include "libavutil/cpu.h"
30#include "libavutil/mem.h"
31#include "libavutil/opt.h"
32#include "libavcodec/defs.h"
33#include "dnn_io_proc.h"
34#include "dnn_backend_common.h"
35#include "safe_queue.h"
36#include <tensorflow/c/c_api.h>
37
49
50/**
51 * Stores execution parameters for single
52 * call to the TensorFlow C API
53 */
54typedef struct TFInferRequest {
55 TF_Output *tf_outputs;
56 TF_Tensor **output_tensors;
57 uint32_t nb_output;
58 TF_Output *tf_input;
59 TF_Tensor *input_tensor;
61
68
69#define OFFSET(x) offsetof(TFOptions, x)
70#define FLAGS AV_OPT_FLAG_FILTERING_PARAM
72 { "sess_config", "config for SessionOptions", OFFSET(sess_config), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, FLAGS },
73 { NULL }
74};
75
76
77static int execute_model_tf(TFRequestItem *request, Queue *lltask_queue);
78static void infer_completion_callback(void *args);
79static inline void destroy_request_item(TFRequestItem **arg);
80
81static void free_buffer(void *data, size_t length)
82{
83 av_freep(&data);
84}
85
86/**
87 * Free the contents of TensorFlow inference request.
88 * It does not free the TFInferRequest instance.
89 *
90 * @param request pointer to TFInferRequest instance.
91 * NULL pointer is allowed.
92 */
93static void tf_free_request(TFInferRequest *request)
94{
95 if (!request)
96 return;
97 if (request->input_tensor) {
98 TF_DeleteTensor(request->input_tensor);
99 request->input_tensor = NULL;
100 }
101 av_freep(&request->tf_input);
102 av_freep(&request->tf_outputs);
103 if (request->output_tensors) {
104 for (uint32_t i = 0; i < request->nb_output; ++i) {
105 if (request->output_tensors[i]) {
106 TF_DeleteTensor(request->output_tensors[i]);
107 request->output_tensors[i] = NULL;
108 }
109 }
110 av_freep(&request->output_tensors);
111 }
112}
113
114/**
115 * Create a TensorFlow inference request. All properties
116 * are initially unallocated and set as NULL.
117 *
118 * @return pointer to the allocated TFInferRequest instance.
119 */
121{
122 TFInferRequest *infer_request = av_malloc(sizeof(TFInferRequest));
123 if (!infer_request) {
124 return NULL;
125 }
126 infer_request->tf_outputs = NULL;
127 infer_request->tf_input = NULL;
128 infer_request->input_tensor = NULL;
129 infer_request->output_tensors = NULL;
130 return infer_request;
131}
132
133/**
134 * Start synchronous inference for the TensorFlow model.
135 *
136 * @param request pointer to the TFRequestItem for inference
137 * @retval 0 if execution is successful
138 * @retval AVERROR(EINVAL) if request is NULL
139 * @retval DNN_GENERIC_ERROR if execution fails
140 */
141static int tf_start_inference(void *args)
142{
143 TFRequestItem *request = args;
144 TFInferRequest *infer_request;
145 LastLevelTaskItem *lltask;
146 TaskItem *task;
147 TFModel *tf_model;
148
149 if (!request) {
150 av_log(NULL, AV_LOG_ERROR, "TFRequestItem is NULL\n");
151 return AVERROR(EINVAL);
152 }
153
154 infer_request = request->infer_request;
155 lltask = request->lltask;
156 task = lltask->task;
157 tf_model = task->model;
158
159 TF_SessionRun(tf_model->session, NULL,
160 infer_request->tf_input, &infer_request->input_tensor, 1,
161 infer_request->tf_outputs, infer_request->output_tensors,
162 task->nb_output, NULL, 0, NULL,
163 request->status);
164 if (TF_GetCode(request->status) != TF_OK) {
165 av_log(tf_model->ctx, AV_LOG_ERROR, "%s", TF_Message(request->status));
166 return DNN_GENERIC_ERROR;
167 }
168 return 0;
169}
170
171/**
172 * Free the TFRequestItem completely.
173 *
174 * @param arg Address of the TFInferRequest instance.
175 */
177 TFRequestItem *request;
178 if (!arg) {
179 return;
180 }
181 request = *arg;
183 av_freep(&request->infer_request);
184 av_freep(&request->lltask);
185 TF_DeleteStatus(request->status);
187 av_freep(arg);
188}
189
190static int extract_lltask_from_task(TaskItem *task, Queue *lltask_queue)
191{
192 TFModel *tf_model = task->model;
193 DnnContext *ctx = tf_model->ctx;
194 LastLevelTaskItem *lltask = av_malloc(sizeof(*lltask));
195 if (!lltask) {
196 av_log(ctx, AV_LOG_ERROR, "Unable to allocate space for LastLevelTaskItem\n");
197 return AVERROR(ENOMEM);
198 }
199 task->inference_todo = 1;
200 task->inference_done = 0;
201 lltask->task = task;
202 if (ff_queue_push_back(lltask_queue, lltask) < 0) {
203 av_log(ctx, AV_LOG_ERROR, "Failed to push back lltask_queue.\n");
204 av_freep(&lltask);
205 return AVERROR(ENOMEM);
206 }
207 return 0;
208}
209
210static TF_Buffer *read_graph(const char *model_filename)
211{
212 TF_Buffer *graph_buf;
213 unsigned char *graph_data = NULL;
214 AVIOContext *model_file_context;
215 long size, bytes_read;
216
217 if (avio_open(&model_file_context, model_filename, AVIO_FLAG_READ) < 0){
218 return NULL;
219 }
220
221 size = avio_size(model_file_context);
222
223 graph_data = av_malloc(size);
224 if (!graph_data){
225 avio_closep(&model_file_context);
226 return NULL;
227 }
228 bytes_read = avio_read(model_file_context, graph_data, size);
229 avio_closep(&model_file_context);
230 if (bytes_read != size){
231 av_freep(&graph_data);
232 return NULL;
233 }
234
235 graph_buf = TF_NewBuffer();
236 graph_buf->data = graph_data;
237 graph_buf->length = size;
238 graph_buf->data_deallocator = free_buffer;
239
240 return graph_buf;
241}
242
243static TF_Tensor *allocate_input_tensor(const DNNData *input)
244{
245 TF_DataType dt;
246 size_t size;
247 int64_t input_dims[4] = { 0 };
248
249 input_dims[0] = 1;
250 input_dims[1] = input->dims[dnn_get_height_idx_by_layout(input->layout)];
251 input_dims[2] = input->dims[dnn_get_width_idx_by_layout(input->layout)];
252 input_dims[3] = input->dims[dnn_get_channel_idx_by_layout(input->layout)];
253 switch (input->dt) {
254 case DNN_FLOAT:
255 dt = TF_FLOAT;
256 size = sizeof(float);
257 break;
258 case DNN_UINT8:
259 dt = TF_UINT8;
260 size = 1;
261 break;
262 default:
263 av_assert0(!"should not reach here");
264 }
265
266 return TF_AllocateTensor(dt, input_dims, 4,
267 input_dims[1] * input_dims[2] * input_dims[3] * size);
268}
269
270static int get_input_tf(DNNModel *model, DNNData *input, const char *input_name)
271{
272 TFModel *tf_model = (TFModel *)model;
273 DnnContext *ctx = tf_model->ctx;
274 TF_Status *status;
275 TF_DataType dt;
276 int64_t dims[4];
277
278 TF_Output tf_output;
279 tf_output.oper = TF_GraphOperationByName(tf_model->graph, input_name);
280 if (!tf_output.oper) {
281 av_log(ctx, AV_LOG_ERROR, "Could not find \"%s\" in model\n", input_name);
282 return AVERROR(EINVAL);
283 }
284
285 tf_output.index = 0;
286 dt = TF_OperationOutputType(tf_output);
287 switch (dt) {
288 case TF_FLOAT:
289 input->dt = DNN_FLOAT;
290 break;
291 case TF_UINT8:
292 input->dt = DNN_UINT8;
293 break;
294 default:
295 av_log(ctx, AV_LOG_ERROR, "Unsupported output type %d in model\n", dt);
296 return AVERROR(EINVAL);
297 }
298 input->order = DCO_RGB;
299
300 status = TF_NewStatus();
301 TF_GraphGetTensorShape(tf_model->graph, tf_output, dims, 4, status);
302 if (TF_GetCode(status) != TF_OK){
303 TF_DeleteStatus(status);
304 av_log(ctx, AV_LOG_ERROR, "Failed to get input tensor shape: number of dimension incorrect\n");
305 return DNN_GENERIC_ERROR;
306 }
307 TF_DeleteStatus(status);
308
309 // currently only NHWC is supported
310 av_assert0(dims[0] == 1 || dims[0] == -1);
311 for (int i = 0; i < 4; i++)
312 input->dims[i] = dims[i];
313 input->layout = DL_NHWC;
314
315 return 0;
316}
317
318static int get_output_tf(DNNModel *model, const char *input_name, int input_width, int input_height,
319 const char *output_name, int *output_width, int *output_height)
320{
321 int ret;
322 TFModel *tf_model = (TFModel *)model;
323 DnnContext *ctx = tf_model->ctx;
324 TaskItem task = { 0 };
325 TFRequestItem *request;
326 DNNExecBaseParams exec_params = {
327 .input_name = input_name,
328 .output_names = &output_name,
329 .nb_output = 1,
330 .in_frame = NULL,
331 .out_frame = NULL,
332 };
333
334 ret = ff_dnn_fill_gettingoutput_task(&task, &exec_params, tf_model, input_height, input_width, ctx);
335 if (ret != 0) {
336 goto err;
337 }
338
339 ret = extract_lltask_from_task(&task, tf_model->lltask_queue);
340 if (ret != 0) {
341 av_log(ctx, AV_LOG_ERROR, "unable to extract inference from task.\n");
342 goto err;
343 }
344
345 request = ff_safe_queue_pop_front(tf_model->request_queue);
346 if (!request) {
347 av_log(ctx, AV_LOG_ERROR, "unable to get infer request.\n");
348 ret = AVERROR(EINVAL);
349 goto err;
350 }
351
352 ret = execute_model_tf(request, tf_model->lltask_queue);
353 *output_width = task.out_frame->width;
354 *output_height = task.out_frame->height;
355
356err:
358 av_frame_free(&task.in_frame);
359 return ret;
360}
361
362#define SPACE_CHARS " \t\r\n"
363static int hex_to_data(uint8_t *data, const char *p)
364{
365 int c, len, v;
366
367 len = 0;
368 v = 1;
369 for (;;) {
370 p += strspn(p, SPACE_CHARS);
371 if (*p == '\0')
372 break;
373 c = av_toupper((unsigned char) *p++);
374 if (c >= '0' && c <= '9')
375 c = c - '0';
376 else if (c >= 'A' && c <= 'F')
377 c = c - 'A' + 10;
378 else
379 break;
380 v = (v << 4) | c;
381 if (v & 0x100) {
382 if (data) {
383 data[len] = v;
384 }
385 len++;
386 v = 1;
387 }
388 }
389 return len;
390}
391
392static int load_tf_model(TFModel *tf_model, const char *model_filename)
393{
394 DnnContext *ctx = tf_model->ctx;
395 TF_Buffer *graph_def;
396 TF_ImportGraphDefOptions *graph_opts;
397 TF_SessionOptions *sess_opts;
398 const TF_Operation *init_op;
399 uint8_t *sess_config = NULL;
400 int sess_config_length = 0;
401
402 // prepare the sess config data
403 if (ctx->tf_option.sess_config != NULL) {
404 const char *config;
405 /*
406 tf_model->ctx.options.sess_config is hex to present the serialized proto
407 required by TF_SetConfig below, so we need to first generate the serialized
408 proto in a python script, tools/python/tf_sess_config.py is a script example
409 to generate the configs of sess_config.
410 */
411 if (strncmp(ctx->tf_option.sess_config, "0x", 2) != 0) {
412 av_log(ctx, AV_LOG_ERROR, "sess_config should start with '0x'\n");
413 return AVERROR(EINVAL);
414 }
415 config = ctx->tf_option.sess_config + 2;
416 sess_config_length = hex_to_data(NULL, config);
417
418 sess_config = av_mallocz(sess_config_length + AV_INPUT_BUFFER_PADDING_SIZE);
419 if (!sess_config) {
420 av_log(ctx, AV_LOG_ERROR, "failed to allocate memory\n");
421 return AVERROR(ENOMEM);
422 }
423 if (hex_to_data(sess_config, config) < 0) {
424 av_log(ctx, AV_LOG_ERROR, "failed to convert hex to data\n");
425 return AVERROR(EINVAL);
426 }
427 }
428
429 graph_def = read_graph(model_filename);
430 if (!graph_def){
431 av_log(ctx, AV_LOG_ERROR, "Failed to read model \"%s\" graph\n", model_filename);
432 av_freep(&sess_config);
433 return AVERROR(EINVAL);
434 }
435 tf_model->graph = TF_NewGraph();
436 tf_model->status = TF_NewStatus();
437 graph_opts = TF_NewImportGraphDefOptions();
438 TF_GraphImportGraphDef(tf_model->graph, graph_def, graph_opts, tf_model->status);
439 TF_DeleteImportGraphDefOptions(graph_opts);
440 TF_DeleteBuffer(graph_def);
441 if (TF_GetCode(tf_model->status) != TF_OK){
442 av_log(ctx, AV_LOG_ERROR, "Failed to import serialized graph to model graph\n");
443 av_freep(&sess_config);
444 return DNN_GENERIC_ERROR;
445 }
446
447 init_op = TF_GraphOperationByName(tf_model->graph, "init");
448 sess_opts = TF_NewSessionOptions();
449
450 if (sess_config) {
451 TF_SetConfig(sess_opts, sess_config, sess_config_length,tf_model->status);
452 av_freep(&sess_config);
453 if (TF_GetCode(tf_model->status) != TF_OK) {
454 TF_DeleteSessionOptions(sess_opts);
455 av_log(ctx, AV_LOG_ERROR, "Failed to set config for sess options with %s\n",
456 ctx->tf_option.sess_config);
457 return DNN_GENERIC_ERROR;
458 }
459 }
460
461 tf_model->session = TF_NewSession(tf_model->graph, sess_opts, tf_model->status);
462 TF_DeleteSessionOptions(sess_opts);
463 if (TF_GetCode(tf_model->status) != TF_OK)
464 {
465 av_freep(&sess_config);
466 av_log(ctx, AV_LOG_ERROR, "Failed to create new session with model graph\n");
467 return DNN_GENERIC_ERROR;
468 }
469
470 // Run initialization operation with name "init" if it is present in graph
471 if (init_op){
472 TF_SessionRun(tf_model->session, NULL,
473 NULL, NULL, 0,
474 NULL, NULL, 0,
475 &init_op, 1, NULL, tf_model->status);
476 if (TF_GetCode(tf_model->status) != TF_OK)
477 {
478 av_freep(&sess_config);
479 av_log(ctx, AV_LOG_ERROR, "Failed to run session when initializing\n");
480 return DNN_GENERIC_ERROR;
481 }
482 }
483
484 return 0;
485}
486
487static void dnn_free_model_tf(DNNModel **model)
488{
489 TFModel *tf_model;
490
491 if (!model || !*model)
492 return;
493
494 tf_model = (TFModel *)(*model);
495 ff_dnn_wait_requests(tf_model->request_queue, tf_model->nb_requests);
496 while (ff_safe_queue_size(tf_model->request_queue) != 0) {
499 }
501
502 while (ff_queue_size(tf_model->lltask_queue) != 0) {
504 av_freep(&item);
505 }
507
508 while (ff_queue_size(tf_model->task_queue) != 0) {
509 TaskItem *item = ff_queue_pop_front(tf_model->task_queue);
510 av_frame_free(&item->in_frame);
511 av_frame_free(&item->out_frame);
512 av_freep(&item);
513 }
514 ff_queue_destroy(tf_model->task_queue);
515
516 if (tf_model->graph){
517 TF_DeleteGraph(tf_model->graph);
518 }
519 if (tf_model->session){
520 TF_CloseSession(tf_model->session, tf_model->status);
521 TF_DeleteSession(tf_model->session, tf_model->status);
522 }
523 if (tf_model->status){
524 TF_DeleteStatus(tf_model->status);
525 }
526 av_freep(&tf_model);
527 *model = NULL;
528}
529
531{
532 DNNModel *model = NULL;
533 TFModel *tf_model = NULL;
534
535 tf_model = av_mallocz(sizeof(TFModel));
536 if (!tf_model)
537 return NULL;
538 model = &tf_model->model;
539 tf_model->ctx = ctx;
540
541 if (load_tf_model(tf_model, ctx->model_filename) != 0){
542 av_log(ctx, AV_LOG_ERROR, "Failed to load TensorFlow model: \"%s\"\n", ctx->model_filename);
543 goto err;
544 }
545
546 if (ctx->nireq <= 0) {
547 ctx->nireq = av_cpu_count() / 2 + 1;
548 }
549
551 if (!tf_model->request_queue) {
552 goto err;
553 }
554
555 for (int i = 0; i < ctx->nireq; i++) {
556 TFRequestItem *item = av_mallocz(sizeof(*item));
557 if (!item) {
558 goto err;
559 }
560 item->lltask = NULL;
562 if (!item->infer_request) {
563 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for TensorFlow inference request\n");
564 av_freep(&item);
565 goto err;
566 }
567 item->status = TF_NewStatus();
570 item->exec_module.args = item;
571
572 if (ff_safe_queue_push_back(tf_model->request_queue, item) < 0) {
574 goto err;
575 }
576 tf_model->nb_requests++;
577 }
578
579 tf_model->lltask_queue = ff_queue_create();
580 if (!tf_model->lltask_queue) {
581 goto err;
582 }
583
584 tf_model->task_queue = ff_queue_create();
585 if (!tf_model->task_queue) {
586 goto err;
587 }
588
589 model->get_input = &get_input_tf;
590 model->get_output = &get_output_tf;
591 model->filter_ctx = filter_ctx;
592 model->func_type = func_type;
593
594 return model;
595err:
596 dnn_free_model_tf(&model);
597 return NULL;
598}
599
600static int fill_model_input_tf(TFModel *tf_model, TFRequestItem *request) {
601 DNNData input = { 0 };
602 LastLevelTaskItem *lltask;
603 TaskItem *task;
604 TFInferRequest *infer_request = NULL;
605 DnnContext *ctx = tf_model->ctx;
606 int ret = 0;
607
608 lltask = ff_queue_pop_front(tf_model->lltask_queue);
609 av_assert0(lltask);
610 task = lltask->task;
611 request->lltask = lltask;
612
613 ret = get_input_tf(&tf_model->model, &input, task->input_name);
614 if (ret != 0) {
615 goto err;
616 }
617
618 infer_request = request->infer_request;
619 input.dims[1] = task->in_frame->height;
620 input.dims[2] = task->in_frame->width;
621
622 infer_request->tf_input = av_malloc(sizeof(TF_Output));
623 if (!infer_request->tf_input) {
624 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for input tensor\n");
625 ret = AVERROR(ENOMEM);
626 goto err;
627 }
628
629 infer_request->tf_input->oper = TF_GraphOperationByName(tf_model->graph, task->input_name);
630 if (!infer_request->tf_input->oper){
631 av_log(ctx, AV_LOG_ERROR, "Could not find \"%s\" in model\n", task->input_name);
633 goto err;
634 }
635 infer_request->tf_input->index = 0;
636
637 infer_request->input_tensor = allocate_input_tensor(&input);
638 if (!infer_request->input_tensor){
639 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for input tensor\n");
640 ret = AVERROR(ENOMEM);
641 goto err;
642 }
643 input.data = (float *)TF_TensorData(infer_request->input_tensor);
644
645 switch (tf_model->model.func_type) {
647 if (task->do_ioproc) {
648 if (tf_model->model.frame_pre_proc != NULL) {
649 tf_model->model.frame_pre_proc(task->in_frame, &input, tf_model->model.filter_ctx);
650 } else {
651 ff_proc_from_frame_to_dnn(task->in_frame, &input, ctx);
652 }
653 }
654 break;
656 ff_frame_to_dnn_detect(task->in_frame, &input, ctx);
657 break;
658 default:
659 avpriv_report_missing_feature(ctx, "model function type %d", tf_model->model.func_type);
660 break;
661 }
662
663 infer_request->tf_outputs = av_malloc_array(task->nb_output, sizeof(TF_Output));
664 if (infer_request->tf_outputs == NULL) {
665 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for *tf_outputs\n");
666 ret = AVERROR(ENOMEM);
667 goto err;
668 }
669
670 infer_request->output_tensors = av_calloc(task->nb_output, sizeof(*infer_request->output_tensors));
671 if (!infer_request->output_tensors) {
672 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for output tensor\n");
673 ret = AVERROR(ENOMEM);
674 goto err;
675 }
676 infer_request->nb_output = task->nb_output;
677
678 for (int i = 0; i < task->nb_output; ++i) {
679 infer_request->output_tensors[i] = NULL;
680 infer_request->tf_outputs[i].oper = TF_GraphOperationByName(tf_model->graph, task->output_names[i]);
681 if (!infer_request->tf_outputs[i].oper) {
682 av_log(ctx, AV_LOG_ERROR, "Could not find output \"%s\" in model\n", task->output_names[i]);
684 goto err;
685 }
686 infer_request->tf_outputs[i].index = 0;
687 }
688
689 return 0;
690err:
691 tf_free_request(infer_request);
692 return ret;
693}
694
695static void infer_completion_callback(void *args) {
696 TFRequestItem *request = args;
697 LastLevelTaskItem *lltask = request->lltask;
698 TaskItem *task = lltask->task;
700 TFInferRequest *infer_request = request->infer_request;
701 TFModel *tf_model = task->model;
702 DnnContext *ctx = tf_model->ctx;
703
704 outputs = av_calloc(task->nb_output, sizeof(*outputs));
705 if (!outputs) {
706 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for *outputs\n");
707 goto err;
708 }
709
710 for (uint32_t i = 0; i < task->nb_output; ++i) {
711 outputs[i].layout = DL_NHWC;
713 TF_Dim(infer_request->output_tensors[i], 1);
715 TF_Dim(infer_request->output_tensors[i], 2);
717 TF_Dim(infer_request->output_tensors[i], 3);
718 outputs[i].data = TF_TensorData(infer_request->output_tensors[i]);
719 outputs[i].dt = (DNNDataType)TF_TensorType(infer_request->output_tensors[i]);
720 }
721 switch (tf_model->model.func_type) {
723 //it only support 1 output if it's frame in & frame out
724 if (task->do_ioproc) {
725 if (tf_model->model.frame_post_proc != NULL) {
726 tf_model->model.frame_post_proc(task->out_frame, outputs, tf_model->model.filter_ctx);
727 } else {
729 }
730 } else {
731 task->out_frame->width =
733 task->out_frame->height =
735 }
736 break;
738 if (!tf_model->model.detect_post_proc) {
739 av_log(ctx, AV_LOG_ERROR, "Detect filter needs provide post proc\n");
740 return;
741 }
742 tf_model->model.detect_post_proc(task->in_frame, outputs, task->nb_output, tf_model->model.filter_ctx);
743 break;
744 default:
745 av_log(ctx, AV_LOG_ERROR, "Tensorflow backend does not support this kind of dnn filter now\n");
746 goto err;
747 }
748 task->inference_done++;
749err:
750 tf_free_request(infer_request);
752 av_freep(&request->lltask);
753
754 if (ff_safe_queue_push_back(tf_model->request_queue, request) < 0) {
755 destroy_request_item(&request);
756 av_log(ctx, AV_LOG_ERROR, "Failed to push back request_queue.\n");
757 }
758}
759
760static int execute_model_tf(TFRequestItem *request, Queue *lltask_queue)
761{
762 TFModel *tf_model;
764 LastLevelTaskItem *lltask;
765 TaskItem *task;
766 int ret = 0;
767
768 if (ff_queue_size(lltask_queue) == 0) {
769 destroy_request_item(&request);
770 return 0;
771 }
772
773 lltask = ff_queue_peek_front(lltask_queue);
774 task = lltask->task;
775 tf_model = task->model;
776 ctx = tf_model->ctx;
777
778 ret = fill_model_input_tf(tf_model, request);
779 if (ret != 0) {
780 goto err;
781 }
782
783 if (task->async) {
784 if (ff_dnn_start_inference_async(ctx, &request->exec_module) != 0) {
785 goto err;
786 }
787 return 0;
788 }
789 else {
790 ret = tf_start_inference(request);
791 if (ret != 0) {
792 goto err;
793 }
795 return (task->inference_done == task->inference_todo) ? 0 : DNN_GENERIC_ERROR;
796 }
797err:
799 av_freep(&request->lltask);
800 if (ff_safe_queue_push_back(tf_model->request_queue, request) < 0) {
801 destroy_request_item(&request);
802 }
803
804 return ret;
805}
806
807static int dnn_execute_model_tf(const DNNModel *model, DNNExecBaseParams *exec_params)
808{
809 TFModel *tf_model = (TFModel *)model;
810 DnnContext *ctx = tf_model->ctx;
811 TaskItem *task;
812 TFRequestItem *request;
813 int ret = 0;
814
815 ret = ff_check_exec_params(ctx, DNN_TF, model->func_type, exec_params);
816 if (ret != 0) {
817 return ret;
818 }
819
820 task = av_malloc(sizeof(*task));
821 if (!task) {
822 av_log(ctx, AV_LOG_ERROR, "unable to alloc memory for task item.\n");
823 return AVERROR(ENOMEM);
824 }
825
826 ret = ff_dnn_fill_task(task, exec_params, tf_model, ctx->async, 1);
827 if (ret != 0) {
828 av_log(ctx, AV_LOG_ERROR, "Fill task with invalid parameter(s).\n");
829 av_freep(&task);
830 return ret;
831 }
832
833 if (ff_queue_push_back(tf_model->task_queue, task) < 0) {
834 av_freep(&task);
835 av_log(ctx, AV_LOG_ERROR, "unable to push back task_queue.\n");
836 return AVERROR(ENOMEM);
837 }
838
839 ret = extract_lltask_from_task(task, tf_model->lltask_queue);
840 if (ret != 0) {
841 av_log(ctx, AV_LOG_ERROR, "unable to extract last level task from task.\n");
842 return ret;
843 }
844
845 request = ff_safe_queue_pop_front(tf_model->request_queue);
846 if (!request) {
847 av_log(ctx, AV_LOG_ERROR, "unable to get infer request.\n");
848 return AVERROR(EINVAL);
849 }
850 return execute_model_tf(request, tf_model->lltask_queue);
851}
852
854{
855 TFModel *tf_model = (TFModel *)model;
856 return ff_dnn_get_result_common(tf_model->task_queue, in, out);
857}
858
859static int dnn_flush_tf(const DNNModel *model)
860{
861 TFModel *tf_model = (TFModel *)model;
862 DnnContext *ctx = tf_model->ctx;
863 TFRequestItem *request;
864 int ret;
865
866 if (ff_queue_size(tf_model->lltask_queue) == 0) {
867 // no pending task need to flush
868 return 0;
869 }
870
871 request = ff_safe_queue_pop_front(tf_model->request_queue);
872 if (!request) {
873 av_log(ctx, AV_LOG_ERROR, "unable to get infer request.\n");
874 return AVERROR(EINVAL);
875 }
876
877 ret = fill_model_input_tf(tf_model, request);
878 if (ret != 0) {
879 av_log(ctx, AV_LOG_ERROR, "Failed to fill model input.\n");
880 av_freep(&request->lltask);
881 if (ff_safe_queue_push_back(tf_model->request_queue, request) < 0) {
882 destroy_request_item(&request);
883 }
884 return ret;
885 }
886
888}
889
891 .clazz = DNN_DEFINE_CLASS(dnn_tensorflow),
892 .type = DNN_TF,
893 .load_model = dnn_load_model_tf,
894 .execute_model = dnn_execute_model_tf,
895 .get_result = dnn_get_result_tf,
896 .flush = dnn_flush_tf,
897 .free_model = dnn_free_model_tf,
898};
static const AVFilterPad outputs[]
Definition af_aap.c:310
static FILE * out
static AVFormatContext * ctx
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition avassert.h:42
int avio_open(AVIOContext **s, const char *filename, int flags)
Create and initialize a AVIOContext for accessing the resource indicated by url.
Definition avio.c:573
int avio_closep(AVIOContext **s)
Close the resource accessed by the AVIOContext *s, free it and set the pointer pointing to it to NULL...
Definition avio.c:725
Buffered I/O operations.
#define AVIO_FLAG_READ
read-only
Definition avio.h:630
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition aviobuf.c:326
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition aviobuf.c:620
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define FLAGS
Definition cmdutils.c:596
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
Misc types and constants that do not belong anywhere else.
int ff_check_exec_params(void *ctx, DNNBackendType backend, DNNFunctionType func_type, DNNExecBaseParams *exec_params)
void ff_dnn_wait_requests(SafeQueue *request_queue, int nireq)
Wait for all inference requests to complete before teardown.
DNNAsyncStatusType ff_dnn_get_result_common(Queue *task_queue, AVFrame **in, AVFrame **out)
Extract input and output frame from the Task Queue after asynchronous inference.
int ff_dnn_async_module_cleanup(DNNAsyncExecModule *async_module)
Join the Async Execution thread and set module pointers to NULL.
int ff_dnn_fill_task(TaskItem *task, DNNExecBaseParams *exec_params, void *backend_model, int async, int do_ioproc)
Fill the Task for Backend Execution.
int ff_dnn_start_inference_async(void *ctx, DNNAsyncExecModule *async_module)
Start asynchronous inference routine for the TensorFlow model on a detached thread.
int ff_dnn_fill_gettingoutput_task(TaskItem *task, DNNExecBaseParams *exec_params, void *backend_model, int input_height, int input_width, void *ctx)
Allocate input and output frames and fill the Task with execution parameters.
DNN common functions different backends.
#define DNN_DEFINE_CLASS(fname)
static void infer_completion_callback(void *args)
static int execute_model_tf(TFRequestItem *request, Queue *lltask_queue)
static int extract_lltask_from_task(TaskItem *task, Queue *lltask_queue)
static TFInferRequest * tf_create_inference_request(void)
Create a TensorFlow inference request.
static int get_output_tf(DNNModel *model, const char *input_name, int input_width, int input_height, const char *output_name, int *output_width, int *output_height)
static void tf_free_request(TFInferRequest *request)
Free the contents of TensorFlow inference request.
static int get_input_tf(DNNModel *model, DNNData *input, const char *input_name)
static int load_tf_model(TFModel *tf_model, const char *model_filename)
static int hex_to_data(uint8_t *data, const char *p)
static DNNAsyncStatusType dnn_get_result_tf(const DNNModel *model, AVFrame **in, AVFrame **out)
static DNNModel * dnn_load_model_tf(DnnContext *ctx, DNNFunctionType func_type, AVFilterContext *filter_ctx)
static int tf_start_inference(void *args)
Start synchronous inference for the TensorFlow model.
static int dnn_flush_tf(const DNNModel *model)
#define SPACE_CHARS
static TF_Buffer * read_graph(const char *model_filename)
static const AVOption dnn_tensorflow_options[]
static int dnn_execute_model_tf(const DNNModel *model, DNNExecBaseParams *exec_params)
static TF_Tensor * allocate_input_tensor(const DNNData *input)
const DNNModule ff_dnn_backend_tf
static void destroy_request_item(TFRequestItem **arg)
Free the TFRequestItem completely.
static int fill_model_input_tf(TFModel *tf_model, TFRequestItem *request)
#define OFFSET(x)
static void infer_completion_callback(void *args)
static void free_buffer(void *data, size_t length)
static void dnn_free_model_tf(DNNModel **model)
static int dnn_get_height_idx_by_layout(DNNLayout layout)
DNNAsyncStatusType
@ DL_NHWC
@ DNN_TF
DNNFunctionType
@ DFT_PROCESS_FRAME
@ DFT_ANALYTICS_DETECT
static int dnn_get_width_idx_by_layout(DNNLayout layout)
#define DNN_GENERIC_ERROR
DNNDataType
@ DNN_UINT8
@ DNN_FLOAT
@ DCO_RGB
static int dnn_get_channel_idx_by_layout(DNNLayout layout)
int ff_proc_from_frame_to_dnn(AVFrame *frame, DNNData *input, void *log_ctx)
int ff_frame_to_dnn_detect(AVFrame *frame, DNNData *input, void *log_ctx)
int ff_proc_from_dnn_to_frame(AVFrame *frame, DNNData *output, void *log_ctx)
Definition dnn_io_proc.c:42
DNN input&output process between AVFrame and DNNData.
int ret
Definition ffplay.c:391
@ AV_OPT_TYPE_STRING
Underlying C type is a uint8_t* that is either NULL or points to a C string allocated with the av_mal...
Definition opt.h:275
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding.
Definition defs.h:40
#define AVERROR(e)
Definition error.h:45
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition frame.c:65
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
static av_const int av_toupper(int c)
Locale-independent conversion of ASCII characters to uppercase.
Definition avstring.h:227
const char * arg
Definition jacosubdec.c:66
int av_cpu_count(void)
Definition cpu.c:229
void avpriv_report_missing_feature(void *avc, const char *msg,...) av_printf_format(2
Log a generic warning message about a missing feature.
uint64_t layout
void * av_calloc(size_t nmemb, size_t size)
Definition mem.c:370
Memory handling functions.
const char data[16]
Definition mxf.c:149
#define av_malloc(s)
Definition ops_static.c:52
AVOptions.
void ff_queue_destroy(Queue *q)
Destroy the Queue instance.
Definition queue.c:72
void * ff_queue_pop_front(Queue *q)
Remove and free first element from the Queue.
Definition queue.c:151
int ff_queue_push_back(Queue *q, void *v)
Add data to the tail of the queue.
Definition queue.c:130
void * ff_queue_peek_front(Queue *q)
Return a pointer to the data at the head of the queue.
Definition queue.c:93
size_t ff_queue_size(Queue *q)
Return the length of the Queue.
Definition queue.c:88
Queue * ff_queue_create(void)
Create a Queue instance.
Definition queue.c:47
int ff_safe_queue_push_back(SafeQueue *sq, void *v)
Add data to the tail of queue in the SafeQueue after locking mutex.
Definition safe_queue.c:87
void * ff_safe_queue_pop_front(SafeQueue *sq)
Remove and free first element from the queue in SafeQueue.
Definition safe_queue.c:97
size_t ff_safe_queue_size(SafeQueue *sq)
Return the length of the SafeQueue.
Definition safe_queue.c:61
SafeQueue * ff_safe_queue_create(void)
Create and initialize a SafeQueue instance.
Definition safe_queue.c:33
void ff_safe_queue_destroy(SafeQueue *sq)
Destroy the SafeQueue instance.
Definition safe_queue.c:50
An instance of a filter.
Definition avfilter.h:279
This structure describes decoded (raw) audio or video data.
Definition frame.h:479
int width
Definition frame.h:551
int height
Definition frame.h:551
Bytestream IO Context.
Definition avio.h:160
AVOption.
Definition opt.h:428
Common Async Execution Mechanism for the DNN Backends.
void * args
Argument for the execution functions.
int(* start_inference)(void *request)
Synchronous inference function for the backend with corresponding request item as the argument.
void(* callback)(void *args)
Completion Callback for the backend.
DNNDataType dt
int dims[4]
DNNColorOrder order
void * data
DNNLayout layout
int(* get_input)(struct DNNModel *model, DNNData *input, const char *input_name)
int(* get_output)(struct DNNModel *model, const char *input_name, int input_width, int input_height, const char *output_name, int *output_width, int *output_height)
FramePrePostProc frame_pre_proc
FramePrePostProc frame_post_proc
DetectPostProc detect_post_proc
AVFilterContext * filter_ctx
DNNFunctionType func_type
Linear double-ended data structure.
Definition executor.c:51
Double-ended queue with mutex locks ensuring data consistency while multithreading.
Definition safe_queue.c:27
Stores execution parameters for single call to the TensorFlow C API.
TF_Output * tf_outputs
TF_Tensor ** output_tensors
TF_Tensor * input_tensor
TF_Output * tf_input
SafeQueue * request_queue
int nb_requests
DNNModel model
TF_Graph * graph
Queue * task_queue
TF_Status * status
Queue * lltask_queue
TF_Session * session
DnnContext * ctx
LastLevelTaskItem * lltask
TFInferRequest * infer_request
DNNAsyncExecModule exec_module
TF_Status * status
uint32_t inference_done
AVFrame * in_frame
const char ** output_names
uint8_t do_ioproc
uint32_t inference_todo
const char * input_name
AVFrame * out_frame
uint32_t nb_output
#define av_malloc_array(a, b)
#define av_mallocz(s)
#define av_freep(p)
#define av_log(a,...)
static FilteringContext * filter_ctx
Definition transcode.c:52
int size
int len
static double c[64]