FFmpeg  4.4.9
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 "dnn_backend_tf.h"
27 #include "dnn_backend_native.h"
30 #include "libavformat/avio.h"
31 #include "libavutil/avassert.h"
32 #include "../internal.h"
35 #include "dnn_io_proc.h"
36 
37 #include <tensorflow/c/c_api.h>
38 
39 typedef struct TFOptions{
40  char *sess_config;
41 } TFOptions;
42 
43 typedef struct TFContext {
44  const AVClass *class;
46 } TFContext;
47 
48 typedef struct TFModel{
51  TF_Graph *graph;
52  TF_Session *session;
53  TF_Status *status;
54 } TFModel;
55 
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 },
60  { NULL }
61 };
62 
63 AVFILTER_DEFINE_CLASS(dnn_tensorflow);
64 
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,
67  int do_ioproc);
68 
69 static void free_buffer(void *data, size_t length)
70 {
71  av_freep(&data);
72 }
73 
74 static TF_Buffer *read_graph(const char *model_filename)
75 {
76  TF_Buffer *graph_buf;
77  unsigned char *graph_data = NULL;
78  AVIOContext *model_file_context;
79  long size, bytes_read;
80 
81  if (avio_open(&model_file_context, model_filename, AVIO_FLAG_READ) < 0){
82  return NULL;
83  }
84 
85  size = avio_size(model_file_context);
86 
87  graph_data = av_malloc(size);
88  if (!graph_data){
89  avio_closep(&model_file_context);
90  return NULL;
91  }
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);
96  return NULL;
97  }
98 
99  graph_buf = TF_NewBuffer();
100  graph_buf->data = graph_data;
101  graph_buf->length = size;
102  graph_buf->data_deallocator = free_buffer;
103 
104  return graph_buf;
105 }
106 
107 static TF_Tensor *allocate_input_tensor(const DNNData *input)
108 {
109  TF_DataType dt;
110  size_t size;
111  int64_t input_dims[] = {1, input->height, input->width, input->channels};
112  switch (input->dt) {
113  case DNN_FLOAT:
114  dt = TF_FLOAT;
115  size = sizeof(float);
116  break;
117  case DNN_UINT8:
118  dt = TF_UINT8;
119  size = 1;
120  break;
121  default:
122  av_assert0(!"should not reach here");
123  }
124 
125  return TF_AllocateTensor(dt, input_dims, 4,
126  input_dims[1] * input_dims[2] * input_dims[3] * size);
127 }
128 
129 static DNNReturnType get_input_tf(void *model, DNNData *input, const char *input_name)
130 {
131  TFModel *tf_model = model;
132  TFContext *ctx = &tf_model->ctx;
133  TF_Status *status;
134  TF_DataType dt;
135  int64_t dims[4];
136 
137  TF_Output tf_output;
138  tf_output.oper = TF_GraphOperationByName(tf_model->graph, input_name);
139  if (!tf_output.oper) {
140  av_log(ctx, AV_LOG_ERROR, "Could not find \"%s\" in model\n", input_name);
141  return DNN_ERROR;
142  }
143 
144  tf_output.index = 0;
145  dt = TF_OperationOutputType(tf_output);
146  switch (dt) {
147  case TF_FLOAT:
148  input->dt = DNN_FLOAT;
149  break;
150  case TF_UINT8:
151  input->dt = DNN_UINT8;
152  break;
153  default:
154  av_log(ctx, AV_LOG_ERROR, "Unsupported output type %d in model\n", dt);
155  return DNN_ERROR;
156  }
157 
158  status = TF_NewStatus();
159  TF_GraphGetTensorShape(tf_model->graph, tf_output, dims, 4, status);
160  if (TF_GetCode(status) != TF_OK){
161  TF_DeleteStatus(status);
162  av_log(ctx, AV_LOG_ERROR, "Failed to get input tensor shape: number of dimension incorrect\n");
163  return DNN_ERROR;
164  }
165  TF_DeleteStatus(status);
166 
167  // currently only NHWC is supported
168  av_assert0(dims[0] == 1);
169  input->height = dims[1];
170  input->width = dims[2];
171  input->channels = dims[3];
172 
173  return DNN_SUCCESS;
174 }
175 
176 static DNNReturnType get_output_tf(void *model, const char *input_name, int input_width, int input_height,
177  const char *output_name, int *output_width, int *output_height)
178 {
179  DNNReturnType ret;
180  TFModel *tf_model = model;
181  TFContext *ctx = &tf_model->ctx;
182  AVFrame *in_frame = av_frame_alloc();
183  AVFrame *out_frame = NULL;
184 
185  if (!in_frame) {
186  av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for input frame\n");
187  return DNN_ERROR;
188  }
189 
190  out_frame = av_frame_alloc();
191  if (!out_frame) {
192  av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for output frame\n");
193  av_frame_free(&in_frame);
194  return DNN_ERROR;
195  }
196 
197  in_frame->width = input_width;
198  in_frame->height = input_height;
199 
200  ret = execute_model_tf(tf_model->model, input_name, in_frame, &output_name, 1, out_frame, 0);
201  *output_width = out_frame->width;
202  *output_height = out_frame->height;
203 
204  av_frame_free(&out_frame);
205  av_frame_free(&in_frame);
206  return ret;
207 }
208 
209 static DNNReturnType load_tf_model(TFModel *tf_model, const char *model_filename)
210 {
211  TFContext *ctx = &tf_model->ctx;
212  TF_Buffer *graph_def;
213  TF_ImportGraphDefOptions *graph_opts;
214  TF_SessionOptions *sess_opts;
215  const TF_Operation *init_op;
216  uint8_t *sess_config = NULL;
217  int sess_config_length = 0;
218 
219  // prepare the sess config data
220  if (tf_model->ctx.options.sess_config != NULL) {
221  /*
222  tf_model->ctx.options.sess_config is hex to present the serialized proto
223  required by TF_SetConfig below, so we need to first generate the serialized
224  proto in a python script, the following is a script example to generate
225  serialized proto which specifies one GPU, we can change the script to add
226  more options.
227 
228  import tensorflow as tf
229  gpu_options = tf.GPUOptions(visible_device_list='0')
230  config = tf.ConfigProto(gpu_options=gpu_options)
231  s = config.SerializeToString()
232  b = ''.join("%02x" % int(ord(b)) for b in s[::-1])
233  print('0x%s' % b)
234 
235  the script output looks like: 0xab...cd, and then pass 0xab...cd to sess_config.
236  */
237  char tmp[3];
238  tmp[2] = '\0';
239 
240  if (strncmp(tf_model->ctx.options.sess_config, "0x", 2) != 0) {
241  av_log(ctx, AV_LOG_ERROR, "sess_config should start with '0x'\n");
242  return DNN_ERROR;
243  }
244 
245  sess_config_length = strlen(tf_model->ctx.options.sess_config);
246  if (sess_config_length % 2 != 0) {
247  av_log(ctx, AV_LOG_ERROR, "the length of sess_config is not even (%s), "
248  "please re-generate the config.\n",
249  tf_model->ctx.options.sess_config);
250  return DNN_ERROR;
251  }
252 
253  sess_config_length -= 2; //ignore the first '0x'
254  sess_config_length /= 2; //get the data length in byte
255 
256  sess_config = av_malloc(sess_config_length);
257  if (!sess_config) {
258  av_log(ctx, AV_LOG_ERROR, "failed to allocate memory\n");
259  return DNN_ERROR;
260  }
261 
262  for (int i = 0; i < sess_config_length; i++) {
263  int index = 2 + (sess_config_length - 1 - i) * 2;
264  tmp[0] = tf_model->ctx.options.sess_config[index];
265  tmp[1] = tf_model->ctx.options.sess_config[index + 1];
266  sess_config[i] = strtol(tmp, NULL, 16);
267  }
268  }
269 
270  graph_def = read_graph(model_filename);
271  if (!graph_def){
272  av_log(ctx, AV_LOG_ERROR, "Failed to read model \"%s\" graph\n", model_filename);
273  av_freep(&sess_config);
274  return DNN_ERROR;
275  }
276  tf_model->graph = TF_NewGraph();
277  tf_model->status = TF_NewStatus();
278  graph_opts = TF_NewImportGraphDefOptions();
279  TF_GraphImportGraphDef(tf_model->graph, graph_def, graph_opts, tf_model->status);
280  TF_DeleteImportGraphDefOptions(graph_opts);
281  TF_DeleteBuffer(graph_def);
282  if (TF_GetCode(tf_model->status) != TF_OK){
283  TF_DeleteGraph(tf_model->graph);
284  TF_DeleteStatus(tf_model->status);
285  av_log(ctx, AV_LOG_ERROR, "Failed to import serialized graph to model graph\n");
286  av_freep(&sess_config);
287  return DNN_ERROR;
288  }
289 
290  init_op = TF_GraphOperationByName(tf_model->graph, "init");
291  sess_opts = TF_NewSessionOptions();
292 
293  if (sess_config) {
294  TF_SetConfig(sess_opts, sess_config, sess_config_length,tf_model->status);
295  av_freep(&sess_config);
296  if (TF_GetCode(tf_model->status) != TF_OK) {
297  TF_DeleteGraph(tf_model->graph);
298  TF_DeleteStatus(tf_model->status);
299  TF_DeleteSessionOptions(sess_opts);
300  av_log(ctx, AV_LOG_ERROR, "Failed to set config for sess options with %s\n",
301  tf_model->ctx.options.sess_config);
302  return DNN_ERROR;
303  }
304  }
305 
306  tf_model->session = TF_NewSession(tf_model->graph, sess_opts, tf_model->status);
307  TF_DeleteSessionOptions(sess_opts);
308  if (TF_GetCode(tf_model->status) != TF_OK)
309  {
310  TF_DeleteGraph(tf_model->graph);
311  TF_DeleteStatus(tf_model->status);
312  av_log(ctx, AV_LOG_ERROR, "Failed to create new session with model graph\n");
313  return DNN_ERROR;
314  }
315 
316  // Run initialization operation with name "init" if it is present in graph
317  if (init_op){
318  TF_SessionRun(tf_model->session, NULL,
319  NULL, NULL, 0,
320  NULL, NULL, 0,
321  &init_op, 1, NULL, tf_model->status);
322  if (TF_GetCode(tf_model->status) != TF_OK)
323  {
324  TF_DeleteSession(tf_model->session, tf_model->status);
325  TF_DeleteGraph(tf_model->graph);
326  TF_DeleteStatus(tf_model->status);
327  av_log(ctx, AV_LOG_ERROR, "Failed to run session when initializing\n");
328  return DNN_ERROR;
329  }
330  }
331 
332  return DNN_SUCCESS;
333 }
334 
335 #define NAME_BUFFER_SIZE 256
336 
337 static DNNReturnType add_conv_layer(TFModel *tf_model, TF_Operation *transpose_op, TF_Operation **cur_op,
338  ConvolutionalParams* params, const int layer)
339 {
340  TFContext *ctx = &tf_model->ctx;
341  TF_Operation *op;
342  TF_OperationDescription *op_desc;
343  TF_Output input;
344  int64_t strides[] = {1, 1, 1, 1};
345  TF_Tensor *kernel_tensor = NULL, *biases_tensor = NULL;
346  int64_t dims[4];
347  int dims_len;
348  char name_buffer[NAME_BUFFER_SIZE];
349  int32_t size;
350 
351  size = params->input_num * params->output_num * params->kernel_size * params->kernel_size;
352  input.index = 0;
353 
354  snprintf(name_buffer, NAME_BUFFER_SIZE, "conv_kernel%d", layer);
355  op_desc = TF_NewOperation(tf_model->graph, "Const", name_buffer);
356  TF_SetAttrType(op_desc, "dtype", TF_FLOAT);
357  dims[0] = params->output_num;
358  dims[1] = params->kernel_size;
359  dims[2] = params->kernel_size;
360  dims[3] = params->input_num;
361  dims_len = 4;
362  kernel_tensor = TF_AllocateTensor(TF_FLOAT, dims, dims_len, size * sizeof(float));
363  memcpy(TF_TensorData(kernel_tensor), params->kernel, size * sizeof(float));
364  TF_SetAttrTensor(op_desc, "value", kernel_tensor, tf_model->status);
365  if (TF_GetCode(tf_model->status) != TF_OK){
366  goto err;
367  }
368  op = TF_FinishOperation(op_desc, tf_model->status);
369  if (TF_GetCode(tf_model->status) != TF_OK){
370  goto err;
371  }
372 
373  snprintf(name_buffer, NAME_BUFFER_SIZE, "transpose%d", layer);
374  op_desc = TF_NewOperation(tf_model->graph, "Transpose", name_buffer);
375  input.oper = op;
376  TF_AddInput(op_desc, input);
377  input.oper = transpose_op;
378  TF_AddInput(op_desc, input);
379  TF_SetAttrType(op_desc, "T", TF_FLOAT);
380  TF_SetAttrType(op_desc, "Tperm", TF_INT32);
381  op = TF_FinishOperation(op_desc, tf_model->status);
382  if (TF_GetCode(tf_model->status) != TF_OK){
383  goto err;
384  }
385 
386  snprintf(name_buffer, NAME_BUFFER_SIZE, "conv2d%d", layer);
387  op_desc = TF_NewOperation(tf_model->graph, "Conv2D", name_buffer);
388  input.oper = *cur_op;
389  TF_AddInput(op_desc, input);
390  input.oper = op;
391  TF_AddInput(op_desc, input);
392  TF_SetAttrType(op_desc, "T", TF_FLOAT);
393  TF_SetAttrIntList(op_desc, "strides", strides, 4);
394  TF_SetAttrString(op_desc, "padding", "VALID", 5);
395  *cur_op = TF_FinishOperation(op_desc, tf_model->status);
396  if (TF_GetCode(tf_model->status) != TF_OK){
397  goto err;
398  }
399 
400  snprintf(name_buffer, NAME_BUFFER_SIZE, "conv_biases%d", layer);
401  op_desc = TF_NewOperation(tf_model->graph, "Const", name_buffer);
402  TF_SetAttrType(op_desc, "dtype", TF_FLOAT);
403  dims[0] = params->output_num;
404  dims_len = 1;
405  biases_tensor = TF_AllocateTensor(TF_FLOAT, dims, dims_len, params->output_num * sizeof(float));
406  memcpy(TF_TensorData(biases_tensor), params->biases, params->output_num * sizeof(float));
407  TF_SetAttrTensor(op_desc, "value", biases_tensor, tf_model->status);
408  if (TF_GetCode(tf_model->status) != TF_OK){
409  goto err;
410  }
411  op = TF_FinishOperation(op_desc, tf_model->status);
412  if (TF_GetCode(tf_model->status) != TF_OK){
413  goto err;
414  }
415 
416  snprintf(name_buffer, NAME_BUFFER_SIZE, "bias_add%d", layer);
417  op_desc = TF_NewOperation(tf_model->graph, "BiasAdd", name_buffer);
418  input.oper = *cur_op;
419  TF_AddInput(op_desc, input);
420  input.oper = op;
421  TF_AddInput(op_desc, input);
422  TF_SetAttrType(op_desc, "T", TF_FLOAT);
423  *cur_op = TF_FinishOperation(op_desc, tf_model->status);
424  if (TF_GetCode(tf_model->status) != TF_OK){
425  goto err;
426  }
427 
428  snprintf(name_buffer, NAME_BUFFER_SIZE, "activation%d", layer);
429  switch (params->activation){
430  case RELU:
431  op_desc = TF_NewOperation(tf_model->graph, "Relu", name_buffer);
432  break;
433  case TANH:
434  op_desc = TF_NewOperation(tf_model->graph, "Tanh", name_buffer);
435  break;
436  case SIGMOID:
437  op_desc = TF_NewOperation(tf_model->graph, "Sigmoid", name_buffer);
438  break;
439  default:
440  avpriv_report_missing_feature(ctx, "convolutional activation function %d", params->activation);
441  return DNN_ERROR;
442  }
443  input.oper = *cur_op;
444  TF_AddInput(op_desc, input);
445  TF_SetAttrType(op_desc, "T", TF_FLOAT);
446  *cur_op = TF_FinishOperation(op_desc, tf_model->status);
447  if (TF_GetCode(tf_model->status) != TF_OK){
448  goto err;
449  }
450 
451  return DNN_SUCCESS;
452 err:
453  TF_DeleteTensor(kernel_tensor);
454  TF_DeleteTensor(biases_tensor);
455  av_log(ctx, AV_LOG_ERROR, "Failed to add conv layer %d\n", layer);
456  return DNN_ERROR;
457 }
458 
459 static DNNReturnType add_depth_to_space_layer(TFModel *tf_model, TF_Operation **cur_op,
460  DepthToSpaceParams *params, const int layer)
461 {
462  TFContext *ctx = &tf_model->ctx;
463  TF_OperationDescription *op_desc;
464  TF_Output input;
465  char name_buffer[NAME_BUFFER_SIZE];
466 
467  snprintf(name_buffer, NAME_BUFFER_SIZE, "depth_to_space%d", layer);
468  op_desc = TF_NewOperation(tf_model->graph, "DepthToSpace", name_buffer);
469  input.oper = *cur_op;
470  input.index = 0;
471  TF_AddInput(op_desc, input);
472  TF_SetAttrType(op_desc, "T", TF_FLOAT);
473  TF_SetAttrInt(op_desc, "block_size", params->block_size);
474  *cur_op = TF_FinishOperation(op_desc, tf_model->status);
475  if (TF_GetCode(tf_model->status) != TF_OK){
476  av_log(ctx, AV_LOG_ERROR, "Failed to add depth_to_space to layer %d\n", layer);
477  return DNN_ERROR;
478  }
479 
480  return DNN_SUCCESS;
481 }
482 
483 static DNNReturnType add_pad_layer(TFModel *tf_model, TF_Operation **cur_op,
484  LayerPadParams *params, const int layer)
485 {
486  TFContext *ctx = &tf_model->ctx;
487  TF_Operation *op;
488  TF_Tensor *tensor;
489  TF_OperationDescription *op_desc;
490  TF_Output input;
491  int32_t *pads;
492  int64_t pads_shape[] = {4, 2};
493 
494  char name_buffer[NAME_BUFFER_SIZE];
495  snprintf(name_buffer, NAME_BUFFER_SIZE, "pad%d", layer);
496 
497  op_desc = TF_NewOperation(tf_model->graph, "Const", name_buffer);
498  TF_SetAttrType(op_desc, "dtype", TF_INT32);
499  tensor = TF_AllocateTensor(TF_INT32, pads_shape, 2, 4 * 2 * sizeof(int32_t));
500  pads = (int32_t *)TF_TensorData(tensor);
501  pads[0] = params->paddings[0][0];
502  pads[1] = params->paddings[0][1];
503  pads[2] = params->paddings[1][0];
504  pads[3] = params->paddings[1][1];
505  pads[4] = params->paddings[2][0];
506  pads[5] = params->paddings[2][1];
507  pads[6] = params->paddings[3][0];
508  pads[7] = params->paddings[3][1];
509  TF_SetAttrTensor(op_desc, "value", tensor, tf_model->status);
510  if (TF_GetCode(tf_model->status) != TF_OK){
511  TF_DeleteTensor(tensor);
512  av_log(ctx, AV_LOG_ERROR, "Failed to set value for pad of layer %d\n", layer);
513  return DNN_ERROR;
514  }
515  op = TF_FinishOperation(op_desc, tf_model->status);
516  if (TF_GetCode(tf_model->status) != TF_OK){
517  TF_DeleteTensor(tensor);
518  av_log(ctx, AV_LOG_ERROR, "Failed to add pad to layer %d\n", layer);
519  return DNN_ERROR;
520  }
521 
522  op_desc = TF_NewOperation(tf_model->graph, "MirrorPad", "mirror_pad");
523  input.oper = *cur_op;
524  input.index = 0;
525  TF_AddInput(op_desc, input);
526  input.oper = op;
527  TF_AddInput(op_desc, input);
528  TF_SetAttrType(op_desc, "T", TF_FLOAT);
529  TF_SetAttrType(op_desc, "Tpaddings", TF_INT32);
530  TF_SetAttrString(op_desc, "mode", "SYMMETRIC", 9);
531  *cur_op = TF_FinishOperation(op_desc, tf_model->status);
532  if (TF_GetCode(tf_model->status) != TF_OK){
533  TF_DeleteTensor(tensor);
534  av_log(ctx, AV_LOG_ERROR, "Failed to add mirror_pad to layer %d\n", layer);
535  return DNN_ERROR;
536  }
537 
538  return DNN_SUCCESS;
539 }
540 
541 static DNNReturnType add_maximum_layer(TFModel *tf_model, TF_Operation **cur_op,
542  DnnLayerMaximumParams *params, const int layer)
543 {
544  TFContext *ctx = &tf_model->ctx;
545  TF_Operation *op;
546  TF_Tensor *tensor;
547  TF_OperationDescription *op_desc;
548  TF_Output input;
549  float *y;
550 
551  char name_buffer[NAME_BUFFER_SIZE];
552  snprintf(name_buffer, NAME_BUFFER_SIZE, "maximum/y%d", layer);
553 
554  op_desc = TF_NewOperation(tf_model->graph, "Const", name_buffer);
555  TF_SetAttrType(op_desc, "dtype", TF_FLOAT);
556  tensor = TF_AllocateTensor(TF_FLOAT, NULL, 0, TF_DataTypeSize(TF_FLOAT));
557  y = (float *)TF_TensorData(tensor);
558  *y = params->val.y;
559  TF_SetAttrTensor(op_desc, "value", tensor, tf_model->status);
560  if (TF_GetCode(tf_model->status) != TF_OK){
561  TF_DeleteTensor(tensor);
562  av_log(ctx, AV_LOG_ERROR, "Failed to set value for maximum/y of layer %d", layer);
563  return DNN_ERROR;
564  }
565  op = TF_FinishOperation(op_desc, tf_model->status);
566  if (TF_GetCode(tf_model->status) != TF_OK){
567  TF_DeleteTensor(tensor);
568  av_log(ctx, AV_LOG_ERROR, "Failed to add maximum/y to layer %d\n", layer);
569  return DNN_ERROR;
570  }
571 
572  snprintf(name_buffer, NAME_BUFFER_SIZE, "maximum%d", layer);
573  op_desc = TF_NewOperation(tf_model->graph, "Maximum", name_buffer);
574  input.oper = *cur_op;
575  input.index = 0;
576  TF_AddInput(op_desc, input);
577  input.oper = op;
578  TF_AddInput(op_desc, input);
579  TF_SetAttrType(op_desc, "T", TF_FLOAT);
580  *cur_op = TF_FinishOperation(op_desc, tf_model->status);
581  if (TF_GetCode(tf_model->status) != TF_OK){
582  TF_DeleteTensor(tensor);
583  av_log(ctx, AV_LOG_ERROR, "Failed to add maximum to layer %d\n", layer);
584  return DNN_ERROR;
585  }
586 
587  return DNN_SUCCESS;
588 }
589 
590 static DNNReturnType load_native_model(TFModel *tf_model, const char *model_filename)
591 {
592  TFContext *ctx = &tf_model->ctx;
593  int32_t layer;
594  TF_OperationDescription *op_desc;
595  TF_Operation *op;
596  TF_Operation *transpose_op;
597  TF_Tensor *tensor = NULL;
598  TF_Output input;
600  int64_t transpose_perm_shape[] = {4};
601  int64_t input_shape[] = {1, -1, -1, -1};
602  DNNReturnType layer_add_res;
603  DNNModel *model = NULL;
604  NativeModel *native_model;
605 
606  model = ff_dnn_load_model_native(model_filename, DFT_PROCESS_FRAME, NULL, NULL);
607  if (!model){
608  av_log(ctx, AV_LOG_ERROR, "Failed to load native model\n");
609  return DNN_ERROR;
610  }
611 
612  native_model = model->model;
613  tf_model->graph = TF_NewGraph();
614  tf_model->status = TF_NewStatus();
615 
616 #define CLEANUP_ON_ERROR(tf_model) \
617  { \
618  TF_DeleteTensor(tensor); \
619  TF_DeleteGraph(tf_model->graph); \
620  TF_DeleteStatus(tf_model->status); \
621  av_log(ctx, AV_LOG_ERROR, "Failed to set value or add operator to layer\n"); \
622  return DNN_ERROR; \
623  }
624 
625  op_desc = TF_NewOperation(tf_model->graph, "Placeholder", "x");
626  TF_SetAttrType(op_desc, "dtype", TF_FLOAT);
627  TF_SetAttrShape(op_desc, "shape", input_shape, 4);
628  op = TF_FinishOperation(op_desc, tf_model->status);
629  if (TF_GetCode(tf_model->status) != TF_OK){
630  CLEANUP_ON_ERROR(tf_model);
631  }
632 
633  op_desc = TF_NewOperation(tf_model->graph, "Const", "transpose_perm");
634  TF_SetAttrType(op_desc, "dtype", TF_INT32);
635  tensor = TF_AllocateTensor(TF_INT32, transpose_perm_shape, 1, 4 * sizeof(int32_t));
636  transpose_perm = (int32_t *)TF_TensorData(tensor);
637  transpose_perm[0] = 1;
638  transpose_perm[1] = 2;
639  transpose_perm[2] = 3;
640  transpose_perm[3] = 0;
641  TF_SetAttrTensor(op_desc, "value", tensor, tf_model->status);
642  if (TF_GetCode(tf_model->status) != TF_OK){
643  CLEANUP_ON_ERROR(tf_model);
644  }
645  transpose_op = TF_FinishOperation(op_desc, tf_model->status);
646  if (TF_GetCode(tf_model->status) != TF_OK){
647  CLEANUP_ON_ERROR(tf_model);
648  }
649 
650  for (layer = 0; layer < native_model->layers_num; ++layer){
651  switch (native_model->layers[layer].type){
652  case DLT_INPUT:
653  layer_add_res = DNN_SUCCESS;
654  break;
655  case DLT_CONV2D:
656  layer_add_res = add_conv_layer(tf_model, transpose_op, &op,
657  (ConvolutionalParams *)native_model->layers[layer].params, layer);
658  break;
659  case DLT_DEPTH_TO_SPACE:
660  layer_add_res = add_depth_to_space_layer(tf_model, &op,
661  (DepthToSpaceParams *)native_model->layers[layer].params, layer);
662  break;
663  case DLT_MIRROR_PAD:
664  layer_add_res = add_pad_layer(tf_model, &op,
665  (LayerPadParams *)native_model->layers[layer].params, layer);
666  break;
667  case DLT_MAXIMUM:
668  layer_add_res = add_maximum_layer(tf_model, &op,
669  (DnnLayerMaximumParams *)native_model->layers[layer].params, layer);
670  break;
671  default:
672  CLEANUP_ON_ERROR(tf_model);
673  }
674 
675  if (layer_add_res != DNN_SUCCESS){
676  CLEANUP_ON_ERROR(tf_model);
677  }
678  }
679 
680  op_desc = TF_NewOperation(tf_model->graph, "Identity", "y");
681  input.oper = op;
682  input.index = 0;
683  TF_AddInput(op_desc, input);
684  TF_FinishOperation(op_desc, tf_model->status);
685  if (TF_GetCode(tf_model->status) != TF_OK){
686  CLEANUP_ON_ERROR(tf_model);
687  }
688 
689  ff_dnn_free_model_native(&model);
690 
691  return DNN_SUCCESS;
692 }
693 
694 DNNModel *ff_dnn_load_model_tf(const char *model_filename, DNNFunctionType func_type, const char *options, AVFilterContext *filter_ctx)
695 {
696  DNNModel *model = NULL;
697  TFModel *tf_model = NULL;
698 
699  model = av_mallocz(sizeof(DNNModel));
700  if (!model){
701  return NULL;
702  }
703 
704  tf_model = av_mallocz(sizeof(TFModel));
705  if (!tf_model){
706  av_freep(&model);
707  return NULL;
708  }
709  tf_model->ctx.class = &dnn_tensorflow_class;
710  tf_model->model = model;
711 
712  //parse options
713  av_opt_set_defaults(&tf_model->ctx);
714  if (av_opt_set_from_string(&tf_model->ctx, options, NULL, "=", "&") < 0) {
715  av_log(&tf_model->ctx, AV_LOG_ERROR, "Failed to parse options \"%s\"\n", options);
716  av_freep(&tf_model);
717  av_freep(&model);
718  return NULL;
719  }
720 
721  if (load_tf_model(tf_model, model_filename) != DNN_SUCCESS){
722  if (load_native_model(tf_model, model_filename) != DNN_SUCCESS){
723  av_freep(&tf_model);
724  av_freep(&model);
725 
726  return NULL;
727  }
728  }
729 
730  model->model = tf_model;
731  model->get_input = &get_input_tf;
732  model->get_output = &get_output_tf;
733  model->options = options;
734  model->filter_ctx = filter_ctx;
735  model->func_type = func_type;
736 
737  return model;
738 }
739 
740 static DNNReturnType execute_model_tf(const DNNModel *model, const char *input_name, AVFrame *in_frame,
741  const char **output_names, uint32_t nb_output, AVFrame *out_frame,
742  int do_ioproc)
743 {
744  TF_Output *tf_outputs;
745  TFModel *tf_model = model->model;
746  TFContext *ctx = &tf_model->ctx;
747  DNNData input, output;
748  TF_Tensor **output_tensors;
749  TF_Output tf_input;
750  TF_Tensor *input_tensor;
751 
752  if (get_input_tf(tf_model, &input, input_name) != DNN_SUCCESS)
753  return DNN_ERROR;
754  input.height = in_frame->height;
755  input.width = in_frame->width;
756 
757  tf_input.oper = TF_GraphOperationByName(tf_model->graph, input_name);
758  if (!tf_input.oper){
759  av_log(ctx, AV_LOG_ERROR, "Could not find \"%s\" in model\n", input_name);
760  return DNN_ERROR;
761  }
762  tf_input.index = 0;
763  input_tensor = allocate_input_tensor(&input);
764  if (!input_tensor){
765  av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for input tensor\n");
766  return DNN_ERROR;
767  }
768  input.data = (float *)TF_TensorData(input_tensor);
769 
770  if (do_ioproc) {
771  if (tf_model->model->pre_proc != NULL) {
772  tf_model->model->pre_proc(in_frame, &input, tf_model->model->filter_ctx);
773  } else {
774  ff_proc_from_frame_to_dnn(in_frame, &input, tf_model->model->func_type, ctx);
775  }
776  }
777 
778  if (nb_output != 1) {
779  // currently, the filter does not need multiple outputs,
780  // so we just pending the support until we really need it.
781  TF_DeleteTensor(input_tensor);
782  avpriv_report_missing_feature(ctx, "multiple outputs");
783  return DNN_ERROR;
784  }
785 
786  tf_outputs = av_malloc_array(nb_output, sizeof(*tf_outputs));
787  if (tf_outputs == NULL) {
788  TF_DeleteTensor(input_tensor);
789  av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for *tf_outputs\n"); \
790  return DNN_ERROR;
791  }
792 
793  output_tensors = av_mallocz_array(nb_output, sizeof(*output_tensors));
794  if (!output_tensors) {
795  TF_DeleteTensor(input_tensor);
796  av_freep(&tf_outputs);
797  av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for output tensor\n"); \
798  return DNN_ERROR;
799  }
800 
801  for (int i = 0; i < nb_output; ++i) {
802  tf_outputs[i].oper = TF_GraphOperationByName(tf_model->graph, output_names[i]);
803  if (!tf_outputs[i].oper) {
804  TF_DeleteTensor(input_tensor);
805  av_freep(&tf_outputs);
806  av_freep(&output_tensors);
807  av_log(ctx, AV_LOG_ERROR, "Could not find output \"%s\" in model\n", output_names[i]); \
808  return DNN_ERROR;
809  }
810  tf_outputs[i].index = 0;
811  }
812 
813  TF_SessionRun(tf_model->session, NULL,
814  &tf_input, &input_tensor, 1,
815  tf_outputs, output_tensors, nb_output,
816  NULL, 0, NULL, tf_model->status);
817  if (TF_GetCode(tf_model->status) != TF_OK) {
818  TF_DeleteTensor(input_tensor);
819  av_freep(&tf_outputs);
820  av_freep(&output_tensors);
821  av_log(ctx, AV_LOG_ERROR, "Failed to run session when executing model\n");
822  return DNN_ERROR;
823  }
824 
825  for (uint32_t i = 0; i < nb_output; ++i) {
826  output.height = TF_Dim(output_tensors[i], 1);
827  output.width = TF_Dim(output_tensors[i], 2);
828  output.channels = TF_Dim(output_tensors[i], 3);
829  output.data = TF_TensorData(output_tensors[i]);
830  output.dt = TF_TensorType(output_tensors[i]);
831 
832  if (do_ioproc) {
833  if (tf_model->model->post_proc != NULL) {
834  tf_model->model->post_proc(out_frame, &output, tf_model->model->filter_ctx);
835  } else {
836  ff_proc_from_dnn_to_frame(out_frame, &output, ctx);
837  }
838  } else {
839  out_frame->width = output.width;
840  out_frame->height = output.height;
841  }
842  }
843 
844  for (uint32_t i = 0; i < nb_output; ++i) {
845  if (output_tensors[i]) {
846  TF_DeleteTensor(output_tensors[i]);
847  }
848  }
849  TF_DeleteTensor(input_tensor);
850  av_freep(&output_tensors);
851  av_freep(&tf_outputs);
852  return DNN_SUCCESS;
853 }
854 
855 DNNReturnType ff_dnn_execute_model_tf(const DNNModel *model, const char *input_name, AVFrame *in_frame,
856  const char **output_names, uint32_t nb_output, AVFrame *out_frame)
857 {
858  TFModel *tf_model = model->model;
859  TFContext *ctx = &tf_model->ctx;
860 
861  if (!in_frame) {
862  av_log(ctx, AV_LOG_ERROR, "in frame is NULL when execute model.\n");
863  return DNN_ERROR;
864  }
865 
866  if (!out_frame) {
867  av_log(ctx, AV_LOG_ERROR, "out frame is NULL when execute model.\n");
868  return DNN_ERROR;
869  }
870 
871  return execute_model_tf(model, input_name, in_frame, output_names, nb_output, out_frame, 1);
872 }
873 
875 {
876  TFModel *tf_model;
877 
878  if (*model){
879  tf_model = (*model)->model;
880  if (tf_model->graph){
881  TF_DeleteGraph(tf_model->graph);
882  }
883  if (tf_model->session){
884  TF_CloseSession(tf_model->session, tf_model->status);
885  TF_DeleteSession(tf_model->session, tf_model->status);
886  }
887  if (tf_model->status){
888  TF_DeleteStatus(tf_model->status);
889  }
890  av_freep(&tf_model);
891  av_freep(model);
892  }
893 }
uint8_t
int32_t
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:37
Buffered I/O operations.
#define AVIO_FLAG_READ
read-only
Definition: avio.h:674
int avio_open(AVIOContext **s, const char *url, int flags)
Create and initialize a AVIOContext for accessing the resource indicated by url.
Definition: aviobuf.c:1154
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition: aviobuf.c:349
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:645
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: aviobuf.c:1209
#define NULL
Definition: coverity.c:32
long long int64_t
Definition: coverity.c:34
void ff_dnn_free_model_native(DNNModel **model)
DNNModel * ff_dnn_load_model_native(const char *model_filename, DNNFunctionType func_type, const char *options, AVFilterContext *filter_ctx)
DNN inference functions interface for native backend.
@ DLT_INPUT
@ DLT_CONV2D
@ DLT_MIRROR_PAD
@ DLT_MAXIMUM
@ DLT_DEPTH_TO_SPACE
@ SIGMOID
@ TANH
@ RELU
DNN inference functions interface for native backend.
DNN inference functions interface for native backend.
layer pad (equivalent to tf.pad) for native backend.
static DNNReturnType add_conv_layer(TFModel *tf_model, TF_Operation *transpose_op, TF_Operation **cur_op, ConvolutionalParams *params, const int layer)
static DNNReturnType get_input_tf(void *model, DNNData *input, const char *input_name)
static DNNReturnType add_depth_to_space_layer(TFModel *tf_model, TF_Operation **cur_op, DepthToSpaceParams *params, const int layer)
static DNNReturnType execute_model_tf(const DNNModel *model, const char *input_name, AVFrame *in_frame, const char **output_names, uint32_t nb_output, AVFrame *out_frame, int do_ioproc)
static DNNReturnType load_native_model(TFModel *tf_model, const char *model_filename)
DNNReturnType ff_dnn_execute_model_tf(const DNNModel *model, const char *input_name, AVFrame *in_frame, const char **output_names, uint32_t nb_output, AVFrame *out_frame)
static TF_Tensor * allocate_input_tensor(const DNNData *input)
DNNModel * ff_dnn_load_model_tf(const char *model_filename, DNNFunctionType func_type, const char *options, AVFilterContext *filter_ctx)
#define FLAGS
#define CLEANUP_ON_ERROR(tf_model)
static DNNReturnType load_tf_model(TFModel *tf_model, const char *model_filename)
AVFILTER_DEFINE_CLASS(dnn_tensorflow)
static DNNReturnType get_output_tf(void *model, const char *input_name, int input_width, int input_height, const char *output_name, int *output_width, int *output_height)
static const AVOption dnn_tensorflow_options[]
static DNNReturnType add_pad_layer(TFModel *tf_model, TF_Operation **cur_op, LayerPadParams *params, const int layer)
#define OFFSET(x)
static TF_Buffer * read_graph(const char *model_filename)
void ff_dnn_free_model_tf(DNNModel **model)
#define NAME_BUFFER_SIZE
static DNNReturnType add_maximum_layer(TFModel *tf_model, TF_Operation **cur_op, DnnLayerMaximumParams *params, const int layer)
static void free_buffer(void *data, size_t length)
DNN inference functions interface for TensorFlow backend.
DNNReturnType
Definition: dnn_interface.h:33
@ DNN_ERROR
Definition: dnn_interface.h:33
@ DNN_SUCCESS
Definition: dnn_interface.h:33
DNNFunctionType
Definition: dnn_interface.h:51
@ DFT_PROCESS_FRAME
Definition: dnn_interface.h:53
@ DNN_UINT8
Definition: dnn_interface.h:37
@ DNN_FLOAT
Definition: dnn_interface.h:37
DNNReturnType ff_proc_from_dnn_to_frame(AVFrame *frame, DNNData *output, void *log_ctx)
Definition: dnn_io_proc.c:26
DNNReturnType ff_proc_from_frame_to_dnn(AVFrame *frame, DNNData *input, DNNFunctionType func_type, void *log_ctx)
Definition: dnn_io_proc.c:222
DNN input&output process between AVFrame and DNNData.
const OptionDef options[]
int av_opt_set_from_string(void *ctx, const char *opts, const char *const *shorthand, const char *key_val_sep, const char *pairs_sep)
Parse the key-value pairs list in opts.
Definition: opt.c:1569
void av_opt_set_defaults(void *s)
Set the values of all AVOption fields to their default values.
Definition: opt.c:1368
@ AV_OPT_TYPE_STRING
Definition: opt.h:229
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:203
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition: frame.c:190
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:194
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:237
void * av_mallocz_array(size_t nmemb, size_t size)
Allocate a memory block for an array with av_mallocz().
Definition: mem.c:190
int index
Definition: gxfenc.c:89
int i
Definition: input.c:407
static int op(uint8_t **dst, const uint8_t *dst_end, GetByteContext *gb, int pixel, int count, int *x, int width, int linesize)
Perform decode operation.
Definition: anm.c:75
void avpriv_report_missing_feature(void *avc, const char *msg,...) av_printf_format(2
Log a generic warning message about a missing feature.
const char data[16]
Definition: mxf.c:142
#define snprintf
Definition: snprintf.h:34
Describe the class of an AVClass context structure.
Definition: log.h:67
An instance of a filter.
Definition: avfilter.h:341
This structure describes decoded (raw) audio or video data.
Definition: frame.h:318
int width
Definition: frame.h:376
int height
Definition: frame.h:376
Bytestream IO Context.
Definition: avio.h:161
AVOption.
Definition: opt.h:248
int channels
Definition: dnn_interface.h:60
DNNDataType dt
Definition: dnn_interface.h:62
int height
Definition: dnn_interface.h:60
void * data
Definition: dnn_interface.h:59
int(* pre_proc)(AVFrame *frame_in, DNNData *model_input, AVFilterContext *filter_ctx)
Definition: dnn_interface.h:83
int(* post_proc)(AVFrame *frame_out, DNNData *model_output, AVFilterContext *filter_ctx)
Definition: dnn_interface.h:86
void * model
Definition: dnn_interface.h:68
const char * options
Definition: dnn_interface.h:70
DNNReturnType(* get_output)(void *model, const char *input_name, int input_width, int input_height, const char *output_name, int *output_width, int *output_height)
Definition: dnn_interface.h:79
DNNReturnType(* get_input)(void *model, DNNData *input, const char *input_name)
Definition: dnn_interface.h:77
AVFilterContext * filter_ctx
Definition: dnn_interface.h:72
DNNFunctionType func_type
Definition: dnn_interface.h:74
union DnnLayerMaximumParams::@202 val
void * params
DNNLayerType type
TFOptions options
const AVClass * class
DNNModel * model
TF_Graph * graph
TF_Status * status
TF_Session * session
TFContext ctx
char * sess_config
#define av_malloc_array(a, b)
#define av_freep(p)
#define av_malloc(s)
#define av_log(a,...)
static uint8_t tmp[11]
Definition: aes_ctr.c:27
AVFormatContext * ctx
Definition: movenc.c:48
static FilteringContext * filter_ctx
Definition: transcoding.c:48
static void transpose_perm(int16_t *out, int16_t *in, int num_vect, const uint8_t line_len[2], int length_div)
Interpret the input data as in the following table:
Definition: twinvq.c:620
int size