2 * Copyright (c) 2018 Sergey Lavrushkin
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 tensorflow backend implementation.
26 #include "dnn_backend_tf.h"
27 #include "dnn_backend_native.h"
28 #include "dnn_backend_native_layer_conv2d.h"
29 #include "dnn_backend_native_layer_depth2space.h"
30 #include "libavformat/avio.h"
31 #include "libavutil/avassert.h"
32 #include "../internal.h"
33 #include "dnn_backend_native_layer_pad.h"
34 #include "dnn_backend_native_layer_maximum.h"
35 #include "dnn_io_proc.h"
37 #include <tensorflow/c/c_api.h>
39 typedef struct TFOptions{
43 typedef struct TFContext {
48 typedef struct TFModel{
56 #define OFFSET(x) offsetof(TFContext, x)
57 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM
58 static const AVOption dnn_tensorflow_options[] = {
59 { "sess_config", "config for SessionOptions", OFFSET(options.sess_config), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, FLAGS },
63 AVFILTER_DEFINE_CLASS(dnn_tensorflow);
65 static DNNReturnType execute_model_tf(const DNNModel *model, const char *input_name, AVFrame *in_frame,
66 const char **output_names, uint32_t nb_output, AVFrame *out_frame,
69 static void free_buffer(void *data, size_t length)
74 static TF_Buffer *read_graph(const char *model_filename)
77 unsigned char *graph_data = NULL;
78 AVIOContext *model_file_context;
79 long size, bytes_read;
81 if (avio_open(&model_file_context, model_filename, AVIO_FLAG_READ) < 0){
85 size = avio_size(model_file_context);
87 graph_data = av_malloc(size);
89 avio_closep(&model_file_context);
92 bytes_read = avio_read(model_file_context, graph_data, size);
93 avio_closep(&model_file_context);
94 if (bytes_read != size){
95 av_freep(&graph_data);
99 graph_buf = TF_NewBuffer();
100 graph_buf->data = graph_data;
101 graph_buf->length = size;
102 graph_buf->data_deallocator = free_buffer;
107 static TF_Tensor *allocate_input_tensor(const DNNData *input)
111 int64_t input_dims[] = {1, input->height, input->width, input->channels};
115 size = sizeof(float);
122 av_assert0(!"should not reach here");
125 return TF_AllocateTensor(dt, input_dims, 4,
126 input_dims[1] * input_dims[2] * input_dims[3] * size);
129 static DNNReturnType get_input_tf(void *model, DNNData *input, const char *input_name)
131 TFModel *tf_model = model;
132 TFContext *ctx = &tf_model->ctx;
137 tf_output.oper = TF_GraphOperationByName(tf_model->graph, input_name);
138 if (!tf_output.oper) {
139 av_log(ctx, AV_LOG_ERROR, "Could not find \"%s\" in model\n", input_name);
144 input->dt = TF_OperationOutputType(tf_output);
146 status = TF_NewStatus();
147 TF_GraphGetTensorShape(tf_model->graph, tf_output, dims, 4, status);
148 if (TF_GetCode(status) != TF_OK){
149 TF_DeleteStatus(status);
150 av_log(ctx, AV_LOG_ERROR, "Failed to get input tensor shape: number of dimension incorrect\n");
153 TF_DeleteStatus(status);
155 // currently only NHWC is supported
156 av_assert0(dims[0] == 1);
157 input->height = dims[1];
158 input->width = dims[2];
159 input->channels = dims[3];
164 static DNNReturnType get_output_tf(void *model, const char *input_name, int input_width, int input_height,
165 const char *output_name, int *output_width, int *output_height)
168 TFModel *tf_model = model;
169 TFContext *ctx = &tf_model->ctx;
170 AVFrame *in_frame = av_frame_alloc();
171 AVFrame *out_frame = NULL;
174 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for input frame\n");
178 out_frame = av_frame_alloc();
180 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for output frame\n");
181 av_frame_free(&in_frame);
185 in_frame->width = input_width;
186 in_frame->height = input_height;
188 ret = execute_model_tf(tf_model->model, input_name, in_frame, &output_name, 1, out_frame, 0);
189 *output_width = out_frame->width;
190 *output_height = out_frame->height;
192 av_frame_free(&out_frame);
193 av_frame_free(&in_frame);
197 static DNNReturnType load_tf_model(TFModel *tf_model, const char *model_filename)
199 TFContext *ctx = &tf_model->ctx;
200 TF_Buffer *graph_def;
201 TF_ImportGraphDefOptions *graph_opts;
202 TF_SessionOptions *sess_opts;
203 const TF_Operation *init_op;
204 uint8_t *sess_config = NULL;
205 int sess_config_length = 0;
207 // prepare the sess config data
208 if (tf_model->ctx.options.sess_config != NULL) {
210 tf_model->ctx.options.sess_config is hex to present the serialized proto
211 required by TF_SetConfig below, so we need to first generate the serialized
212 proto in a python script, the following is a script example to generate
213 serialized proto which specifies one GPU, we can change the script to add
216 import tensorflow as tf
217 gpu_options = tf.GPUOptions(visible_device_list='0')
218 config = tf.ConfigProto(gpu_options=gpu_options)
219 s = config.SerializeToString()
220 b = ''.join("%02x" % int(ord(b)) for b in s[::-1])
223 the script output looks like: 0xab...cd, and then pass 0xab...cd to sess_config.
228 if (strncmp(tf_model->ctx.options.sess_config, "0x", 2) != 0) {
229 av_log(ctx, AV_LOG_ERROR, "sess_config should start with '0x'\n");
233 sess_config_length = strlen(tf_model->ctx.options.sess_config);
234 if (sess_config_length % 2 != 0) {
235 av_log(ctx, AV_LOG_ERROR, "the length of sess_config is not even (%s), "
236 "please re-generate the config.\n",
237 tf_model->ctx.options.sess_config);
241 sess_config_length -= 2; //ignore the first '0x'
242 sess_config_length /= 2; //get the data length in byte
244 sess_config = av_malloc(sess_config_length);
246 av_log(ctx, AV_LOG_ERROR, "failed to allocate memory\n");
250 for (int i = 0; i < sess_config_length; i++) {
251 int index = 2 + (sess_config_length - 1 - i) * 2;
252 tmp[0] = tf_model->ctx.options.sess_config[index];
253 tmp[1] = tf_model->ctx.options.sess_config[index + 1];
254 sess_config[i] = strtol(tmp, NULL, 16);
258 graph_def = read_graph(model_filename);
260 av_log(ctx, AV_LOG_ERROR, "Failed to read model \"%s\" graph\n", model_filename);
261 av_freep(&sess_config);
264 tf_model->graph = TF_NewGraph();
265 tf_model->status = TF_NewStatus();
266 graph_opts = TF_NewImportGraphDefOptions();
267 TF_GraphImportGraphDef(tf_model->graph, graph_def, graph_opts, tf_model->status);
268 TF_DeleteImportGraphDefOptions(graph_opts);
269 TF_DeleteBuffer(graph_def);
270 if (TF_GetCode(tf_model->status) != TF_OK){
271 TF_DeleteGraph(tf_model->graph);
272 TF_DeleteStatus(tf_model->status);
273 av_log(ctx, AV_LOG_ERROR, "Failed to import serialized graph to model graph\n");
274 av_freep(&sess_config);
278 init_op = TF_GraphOperationByName(tf_model->graph, "init");
279 sess_opts = TF_NewSessionOptions();
282 TF_SetConfig(sess_opts, sess_config, sess_config_length,tf_model->status);
283 av_freep(&sess_config);
284 if (TF_GetCode(tf_model->status) != TF_OK) {
285 av_log(ctx, AV_LOG_ERROR, "Failed to set config for sess options with %s\n",
286 tf_model->ctx.options.sess_config);
291 tf_model->session = TF_NewSession(tf_model->graph, sess_opts, tf_model->status);
292 TF_DeleteSessionOptions(sess_opts);
293 if (TF_GetCode(tf_model->status) != TF_OK)
295 av_log(ctx, AV_LOG_ERROR, "Failed to create new session with model graph\n");
299 // Run initialization operation with name "init" if it is present in graph
301 TF_SessionRun(tf_model->session, NULL,
304 &init_op, 1, NULL, tf_model->status);
305 if (TF_GetCode(tf_model->status) != TF_OK)
307 av_log(ctx, AV_LOG_ERROR, "Failed to run session when initializing\n");
315 #define NAME_BUFFER_SIZE 256
317 static DNNReturnType add_conv_layer(TFModel *tf_model, TF_Operation *transpose_op, TF_Operation **cur_op,
318 ConvolutionalParams* params, const int layer)
320 TFContext *ctx = &tf_model->ctx;
322 TF_OperationDescription *op_desc;
324 int64_t strides[] = {1, 1, 1, 1};
328 char name_buffer[NAME_BUFFER_SIZE];
331 size = params->input_num * params->output_num * params->kernel_size * params->kernel_size;
334 snprintf(name_buffer, NAME_BUFFER_SIZE, "conv_kernel%d", layer);
335 op_desc = TF_NewOperation(tf_model->graph, "Const", name_buffer);
336 TF_SetAttrType(op_desc, "dtype", TF_FLOAT);
337 dims[0] = params->output_num;
338 dims[1] = params->kernel_size;
339 dims[2] = params->kernel_size;
340 dims[3] = params->input_num;
342 tensor = TF_AllocateTensor(TF_FLOAT, dims, dims_len, size * sizeof(float));
343 memcpy(TF_TensorData(tensor), params->kernel, size * sizeof(float));
344 TF_SetAttrTensor(op_desc, "value", tensor, tf_model->status);
345 if (TF_GetCode(tf_model->status) != TF_OK){
346 av_log(ctx, AV_LOG_ERROR, "Failed to set value for kernel of conv layer %d\n", layer);
349 op = TF_FinishOperation(op_desc, tf_model->status);
350 if (TF_GetCode(tf_model->status) != TF_OK){
351 av_log(ctx, AV_LOG_ERROR, "Failed to add kernel to conv layer %d\n", layer);
355 snprintf(name_buffer, NAME_BUFFER_SIZE, "transpose%d", layer);
356 op_desc = TF_NewOperation(tf_model->graph, "Transpose", name_buffer);
358 TF_AddInput(op_desc, input);
359 input.oper = transpose_op;
360 TF_AddInput(op_desc, input);
361 TF_SetAttrType(op_desc, "T", TF_FLOAT);
362 TF_SetAttrType(op_desc, "Tperm", TF_INT32);
363 op = TF_FinishOperation(op_desc, tf_model->status);
364 if (TF_GetCode(tf_model->status) != TF_OK){
365 av_log(ctx, AV_LOG_ERROR, "Failed to add transpose to conv layer %d\n", layer);
369 snprintf(name_buffer, NAME_BUFFER_SIZE, "conv2d%d", layer);
370 op_desc = TF_NewOperation(tf_model->graph, "Conv2D", name_buffer);
371 input.oper = *cur_op;
372 TF_AddInput(op_desc, input);
374 TF_AddInput(op_desc, input);
375 TF_SetAttrType(op_desc, "T", TF_FLOAT);
376 TF_SetAttrIntList(op_desc, "strides", strides, 4);
377 TF_SetAttrString(op_desc, "padding", "VALID", 5);
378 *cur_op = TF_FinishOperation(op_desc, tf_model->status);
379 if (TF_GetCode(tf_model->status) != TF_OK){
380 av_log(ctx, AV_LOG_ERROR, "Failed to add conv2d to conv layer %d\n", layer);
384 snprintf(name_buffer, NAME_BUFFER_SIZE, "conv_biases%d", layer);
385 op_desc = TF_NewOperation(tf_model->graph, "Const", name_buffer);
386 TF_SetAttrType(op_desc, "dtype", TF_FLOAT);
387 dims[0] = params->output_num;
389 tensor = TF_AllocateTensor(TF_FLOAT, dims, dims_len, params->output_num * sizeof(float));
390 memcpy(TF_TensorData(tensor), params->biases, params->output_num * sizeof(float));
391 TF_SetAttrTensor(op_desc, "value", tensor, tf_model->status);
392 if (TF_GetCode(tf_model->status) != TF_OK){
393 av_log(ctx, AV_LOG_ERROR, "Failed to set value for conv_biases of conv layer %d\n", layer);
396 op = TF_FinishOperation(op_desc, tf_model->status);
397 if (TF_GetCode(tf_model->status) != TF_OK){
398 av_log(ctx, AV_LOG_ERROR, "Failed to add conv_biases to conv layer %d\n", layer);
402 snprintf(name_buffer, NAME_BUFFER_SIZE, "bias_add%d", layer);
403 op_desc = TF_NewOperation(tf_model->graph, "BiasAdd", name_buffer);
404 input.oper = *cur_op;
405 TF_AddInput(op_desc, input);
407 TF_AddInput(op_desc, input);
408 TF_SetAttrType(op_desc, "T", TF_FLOAT);
409 *cur_op = TF_FinishOperation(op_desc, tf_model->status);
410 if (TF_GetCode(tf_model->status) != TF_OK){
411 av_log(ctx, AV_LOG_ERROR, "Failed to add bias_add to conv layer %d\n", layer);
415 snprintf(name_buffer, NAME_BUFFER_SIZE, "activation%d", layer);
416 switch (params->activation){
418 op_desc = TF_NewOperation(tf_model->graph, "Relu", name_buffer);
421 op_desc = TF_NewOperation(tf_model->graph, "Tanh", name_buffer);
424 op_desc = TF_NewOperation(tf_model->graph, "Sigmoid", name_buffer);
427 avpriv_report_missing_feature(ctx, "convolutional activation function %d", params->activation);
430 input.oper = *cur_op;
431 TF_AddInput(op_desc, input);
432 TF_SetAttrType(op_desc, "T", TF_FLOAT);
433 *cur_op = TF_FinishOperation(op_desc, tf_model->status);
434 if (TF_GetCode(tf_model->status) != TF_OK){
435 av_log(ctx, AV_LOG_ERROR, "Failed to add activation function to conv layer %d\n", layer);
442 static DNNReturnType add_depth_to_space_layer(TFModel *tf_model, TF_Operation **cur_op,
443 DepthToSpaceParams *params, const int layer)
445 TFContext *ctx = &tf_model->ctx;
446 TF_OperationDescription *op_desc;
448 char name_buffer[NAME_BUFFER_SIZE];
450 snprintf(name_buffer, NAME_BUFFER_SIZE, "depth_to_space%d", layer);
451 op_desc = TF_NewOperation(tf_model->graph, "DepthToSpace", name_buffer);
452 input.oper = *cur_op;
454 TF_AddInput(op_desc, input);
455 TF_SetAttrType(op_desc, "T", TF_FLOAT);
456 TF_SetAttrInt(op_desc, "block_size", params->block_size);
457 *cur_op = TF_FinishOperation(op_desc, tf_model->status);
458 if (TF_GetCode(tf_model->status) != TF_OK){
459 av_log(ctx, AV_LOG_ERROR, "Failed to add depth_to_space to layer %d\n", layer);
466 static DNNReturnType add_pad_layer(TFModel *tf_model, TF_Operation **cur_op,
467 LayerPadParams *params, const int layer)
469 TFContext *ctx = &tf_model->ctx;
472 TF_OperationDescription *op_desc;
475 int64_t pads_shape[] = {4, 2};
477 char name_buffer[NAME_BUFFER_SIZE];
478 snprintf(name_buffer, NAME_BUFFER_SIZE, "pad%d", layer);
480 op_desc = TF_NewOperation(tf_model->graph, "Const", name_buffer);
481 TF_SetAttrType(op_desc, "dtype", TF_INT32);
482 tensor = TF_AllocateTensor(TF_INT32, pads_shape, 2, 4 * 2 * sizeof(int32_t));
483 pads = (int32_t *)TF_TensorData(tensor);
484 pads[0] = params->paddings[0][0];
485 pads[1] = params->paddings[0][1];
486 pads[2] = params->paddings[1][0];
487 pads[3] = params->paddings[1][1];
488 pads[4] = params->paddings[2][0];
489 pads[5] = params->paddings[2][1];
490 pads[6] = params->paddings[3][0];
491 pads[7] = params->paddings[3][1];
492 TF_SetAttrTensor(op_desc, "value", tensor, tf_model->status);
493 if (TF_GetCode(tf_model->status) != TF_OK){
494 av_log(ctx, AV_LOG_ERROR, "Failed to set value for pad of layer %d\n", layer);
497 op = TF_FinishOperation(op_desc, tf_model->status);
498 if (TF_GetCode(tf_model->status) != TF_OK){
499 av_log(ctx, AV_LOG_ERROR, "Failed to add pad to layer %d\n", layer);
503 op_desc = TF_NewOperation(tf_model->graph, "MirrorPad", "mirror_pad");
504 input.oper = *cur_op;
506 TF_AddInput(op_desc, input);
508 TF_AddInput(op_desc, input);
509 TF_SetAttrType(op_desc, "T", TF_FLOAT);
510 TF_SetAttrType(op_desc, "Tpaddings", TF_INT32);
511 TF_SetAttrString(op_desc, "mode", "SYMMETRIC", 9);
512 *cur_op = TF_FinishOperation(op_desc, tf_model->status);
513 if (TF_GetCode(tf_model->status) != TF_OK){
514 av_log(ctx, AV_LOG_ERROR, "Failed to add mirror_pad to layer %d\n", layer);
521 static DNNReturnType add_maximum_layer(TFModel *tf_model, TF_Operation **cur_op,
522 DnnLayerMaximumParams *params, const int layer)
524 TFContext *ctx = &tf_model->ctx;
527 TF_OperationDescription *op_desc;
531 char name_buffer[NAME_BUFFER_SIZE];
532 snprintf(name_buffer, NAME_BUFFER_SIZE, "maximum/y%d", layer);
534 op_desc = TF_NewOperation(tf_model->graph, "Const", name_buffer);
535 TF_SetAttrType(op_desc, "dtype", TF_FLOAT);
536 tensor = TF_AllocateTensor(TF_FLOAT, NULL, 0, TF_DataTypeSize(TF_FLOAT));
537 y = (float *)TF_TensorData(tensor);
539 TF_SetAttrTensor(op_desc, "value", tensor, tf_model->status);
540 if (TF_GetCode(tf_model->status) != TF_OK){
541 av_log(ctx, AV_LOG_ERROR, "Failed to set value for maximum/y of layer %d", layer);
544 op = TF_FinishOperation(op_desc, tf_model->status);
545 if (TF_GetCode(tf_model->status) != TF_OK){
546 av_log(ctx, AV_LOG_ERROR, "Failed to add maximum/y to layer %d\n", layer);
550 snprintf(name_buffer, NAME_BUFFER_SIZE, "maximum%d", layer);
551 op_desc = TF_NewOperation(tf_model->graph, "Maximum", name_buffer);
552 input.oper = *cur_op;
554 TF_AddInput(op_desc, input);
556 TF_AddInput(op_desc, input);
557 TF_SetAttrType(op_desc, "T", TF_FLOAT);
558 *cur_op = TF_FinishOperation(op_desc, tf_model->status);
559 if (TF_GetCode(tf_model->status) != TF_OK){
560 av_log(ctx, AV_LOG_ERROR, "Failed to add maximum to layer %d\n", layer);
567 static DNNReturnType load_native_model(TFModel *tf_model, const char *model_filename)
569 TFContext *ctx = &tf_model->ctx;
571 TF_OperationDescription *op_desc;
573 TF_Operation *transpose_op;
576 int32_t *transpose_perm;
577 int64_t transpose_perm_shape[] = {4};
578 int64_t input_shape[] = {1, -1, -1, -1};
579 DNNReturnType layer_add_res;
580 DNNModel *model = NULL;
581 NativeModel *native_model;
583 model = ff_dnn_load_model_native(model_filename, DFT_PROCESS_FRAME, NULL, NULL);
585 av_log(ctx, AV_LOG_ERROR, "Failed to load native model\n");
589 native_model = model->model;
590 tf_model->graph = TF_NewGraph();
591 tf_model->status = TF_NewStatus();
593 #define CLEANUP_ON_ERROR(tf_model) \
595 TF_DeleteGraph(tf_model->graph); \
596 TF_DeleteStatus(tf_model->status); \
597 av_log(ctx, AV_LOG_ERROR, "Failed to set value or add operator to layer\n"); \
601 op_desc = TF_NewOperation(tf_model->graph, "Placeholder", "x");
602 TF_SetAttrType(op_desc, "dtype", TF_FLOAT);
603 TF_SetAttrShape(op_desc, "shape", input_shape, 4);
604 op = TF_FinishOperation(op_desc, tf_model->status);
605 if (TF_GetCode(tf_model->status) != TF_OK){
606 CLEANUP_ON_ERROR(tf_model);
609 op_desc = TF_NewOperation(tf_model->graph, "Const", "transpose_perm");
610 TF_SetAttrType(op_desc, "dtype", TF_INT32);
611 tensor = TF_AllocateTensor(TF_INT32, transpose_perm_shape, 1, 4 * sizeof(int32_t));
612 transpose_perm = (int32_t *)TF_TensorData(tensor);
613 transpose_perm[0] = 1;
614 transpose_perm[1] = 2;
615 transpose_perm[2] = 3;
616 transpose_perm[3] = 0;
617 TF_SetAttrTensor(op_desc, "value", tensor, tf_model->status);
618 if (TF_GetCode(tf_model->status) != TF_OK){
619 CLEANUP_ON_ERROR(tf_model);
621 transpose_op = TF_FinishOperation(op_desc, tf_model->status);
623 for (layer = 0; layer < native_model->layers_num; ++layer){
624 switch (native_model->layers[layer].type){
626 layer_add_res = DNN_SUCCESS;
629 layer_add_res = add_conv_layer(tf_model, transpose_op, &op,
630 (ConvolutionalParams *)native_model->layers[layer].params, layer);
632 case DLT_DEPTH_TO_SPACE:
633 layer_add_res = add_depth_to_space_layer(tf_model, &op,
634 (DepthToSpaceParams *)native_model->layers[layer].params, layer);
637 layer_add_res = add_pad_layer(tf_model, &op,
638 (LayerPadParams *)native_model->layers[layer].params, layer);
641 layer_add_res = add_maximum_layer(tf_model, &op,
642 (DnnLayerMaximumParams *)native_model->layers[layer].params, layer);
645 CLEANUP_ON_ERROR(tf_model);
648 if (layer_add_res != DNN_SUCCESS){
649 CLEANUP_ON_ERROR(tf_model);
653 op_desc = TF_NewOperation(tf_model->graph, "Identity", "y");
656 TF_AddInput(op_desc, input);
657 TF_FinishOperation(op_desc, tf_model->status);
658 if (TF_GetCode(tf_model->status) != TF_OK){
659 CLEANUP_ON_ERROR(tf_model);
662 ff_dnn_free_model_native(&model);
667 DNNModel *ff_dnn_load_model_tf(const char *model_filename, DNNFunctionType func_type, const char *options, AVFilterContext *filter_ctx)
669 DNNModel *model = NULL;
670 TFModel *tf_model = NULL;
672 model = av_mallocz(sizeof(DNNModel));
677 tf_model = av_mallocz(sizeof(TFModel));
682 tf_model->ctx.class = &dnn_tensorflow_class;
683 tf_model->model = model;
686 av_opt_set_defaults(&tf_model->ctx);
687 if (av_opt_set_from_string(&tf_model->ctx, options, NULL, "=", "&") < 0) {
688 av_log(&tf_model->ctx, AV_LOG_ERROR, "Failed to parse options \"%s\"\n", options);
694 if (load_tf_model(tf_model, model_filename) != DNN_SUCCESS){
695 if (load_native_model(tf_model, model_filename) != DNN_SUCCESS){
703 model->model = tf_model;
704 model->get_input = &get_input_tf;
705 model->get_output = &get_output_tf;
706 model->options = options;
707 model->filter_ctx = filter_ctx;
708 model->func_type = func_type;
713 static DNNReturnType execute_model_tf(const DNNModel *model, const char *input_name, AVFrame *in_frame,
714 const char **output_names, uint32_t nb_output, AVFrame *out_frame,
717 TF_Output *tf_outputs;
718 TFModel *tf_model = model->model;
719 TFContext *ctx = &tf_model->ctx;
720 DNNData input, output;
721 TF_Tensor **output_tensors;
723 TF_Tensor *input_tensor;
725 if (get_input_tf(tf_model, &input, input_name) != DNN_SUCCESS)
727 input.height = in_frame->height;
728 input.width = in_frame->width;
730 tf_input.oper = TF_GraphOperationByName(tf_model->graph, input_name);
732 av_log(ctx, AV_LOG_ERROR, "Could not find \"%s\" in model\n", input_name);
736 input_tensor = allocate_input_tensor(&input);
738 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for input tensor\n");
741 input.data = (float *)TF_TensorData(input_tensor);
744 if (tf_model->model->pre_proc != NULL) {
745 tf_model->model->pre_proc(in_frame, &input, tf_model->model->filter_ctx);
747 ff_proc_from_frame_to_dnn(in_frame, &input, tf_model->model->func_type, ctx);
751 if (nb_output != 1) {
752 // currently, the filter does not need multiple outputs,
753 // so we just pending the support until we really need it.
754 avpriv_report_missing_feature(ctx, "multiple outputs");
758 tf_outputs = av_malloc_array(nb_output, sizeof(*tf_outputs));
759 if (tf_outputs == NULL) {
760 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for *tf_outputs\n"); \
764 output_tensors = av_mallocz_array(nb_output, sizeof(*output_tensors));
765 if (!output_tensors) {
766 av_freep(&tf_outputs);
767 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for output tensor\n"); \
771 for (int i = 0; i < nb_output; ++i) {
772 tf_outputs[i].oper = TF_GraphOperationByName(tf_model->graph, output_names[i]);
773 if (!tf_outputs[i].oper) {
774 av_freep(&tf_outputs);
775 av_freep(&output_tensors);
776 av_log(ctx, AV_LOG_ERROR, "Could not find output \"%s\" in model\n", output_names[i]); \
779 tf_outputs[i].index = 0;
782 TF_SessionRun(tf_model->session, NULL,
783 &tf_input, &input_tensor, 1,
784 tf_outputs, output_tensors, nb_output,
785 NULL, 0, NULL, tf_model->status);
786 if (TF_GetCode(tf_model->status) != TF_OK) {
787 av_freep(&tf_outputs);
788 av_freep(&output_tensors);
789 av_log(ctx, AV_LOG_ERROR, "Failed to run session when executing model\n");
793 for (uint32_t i = 0; i < nb_output; ++i) {
794 output.height = TF_Dim(output_tensors[i], 1);
795 output.width = TF_Dim(output_tensors[i], 2);
796 output.channels = TF_Dim(output_tensors[i], 3);
797 output.data = TF_TensorData(output_tensors[i]);
798 output.dt = TF_TensorType(output_tensors[i]);
801 if (tf_model->model->post_proc != NULL) {
802 tf_model->model->post_proc(out_frame, &output, tf_model->model->filter_ctx);
804 ff_proc_from_dnn_to_frame(out_frame, &output, ctx);
807 out_frame->width = output.width;
808 out_frame->height = output.height;
812 for (uint32_t i = 0; i < nb_output; ++i) {
813 if (output_tensors[i]) {
814 TF_DeleteTensor(output_tensors[i]);
817 TF_DeleteTensor(input_tensor);
818 av_freep(&output_tensors);
819 av_freep(&tf_outputs);
823 DNNReturnType ff_dnn_execute_model_tf(const DNNModel *model, const char *input_name, AVFrame *in_frame,
824 const char **output_names, uint32_t nb_output, AVFrame *out_frame)
826 TFModel *tf_model = model->model;
827 TFContext *ctx = &tf_model->ctx;
830 av_log(ctx, AV_LOG_ERROR, "in frame is NULL when execute model.\n");
835 av_log(ctx, AV_LOG_ERROR, "out frame is NULL when execute model.\n");
839 return execute_model_tf(model, input_name, in_frame, output_names, nb_output, out_frame, 1);
842 void ff_dnn_free_model_tf(DNNModel **model)
847 tf_model = (*model)->model;
848 if (tf_model->graph){
849 TF_DeleteGraph(tf_model->graph);
851 if (tf_model->session){
852 TF_CloseSession(tf_model->session, tf_model->status);
853 TF_DeleteSession(tf_model->session, tf_model->status);
855 if (tf_model->status){
856 TF_DeleteStatus(tf_model->status);