上传完整项目文件
This commit is contained in:
1 parent
e63d58df8d
commit
aa0dd45839
8663 files changed
+2393125
No files matched your search
@@ -0,0 +1,11 @@
|
||||
OBJS-$(CONFIG_DNN) += dnn/dnn_interface.o
|
||||
OBJS-$(CONFIG_DNN) += dnn/dnn_io_proc.o
|
||||
OBJS-$(CONFIG_DNN) += dnn/queue.o
|
||||
OBJS-$(CONFIG_DNN) += dnn/safe_queue.o
|
||||
OBJS-$(CONFIG_DNN) += dnn/dnn_backend_common.o
|
||||
|
||||
DNN-OBJS-$(CONFIG_LIBTENSORFLOW) += dnn/dnn_backend_tf.o
|
||||
DNN-OBJS-$(CONFIG_LIBOPENVINO) += dnn/dnn_backend_openvino.o
|
||||
DNN-OBJS-$(CONFIG_LIBTORCH) += dnn/dnn_backend_torch.o
|
||||
|
||||
OBJS-$(CONFIG_DNN) += $(DNN-OBJS-yes)
|
||||
@@ -0,0 +1,180 @@
|
||||
/*
|
||||
* This file is part of FFmpeg.
|
||||
*
|
||||
* FFmpeg is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* FFmpeg is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with FFmpeg; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file
|
||||
* DNN common functions different backends.
|
||||
*/
|
||||
|
||||
#include "libavutil/mem.h"
|
||||
#include "dnn_backend_common.h"
|
||||
|
||||
#define DNN_ASYNC_SUCCESS (void *)0
|
||||
#define DNN_ASYNC_FAIL (void *)-1
|
||||
|
||||
int ff_check_exec_params(void *ctx, DNNBackendType backend, DNNFunctionType func_type, DNNExecBaseParams *exec_params)
|
||||
{
|
||||
if (!exec_params) {
|
||||
av_log(ctx, AV_LOG_ERROR, "exec_params is null when execute model.\n");
|
||||
return AVERROR(EINVAL);
|
||||
}
|
||||
|
||||
if (!exec_params->in_frame) {
|
||||
av_log(ctx, AV_LOG_ERROR, "in frame is NULL when execute model.\n");
|
||||
return AVERROR(EINVAL);
|
||||
}
|
||||
|
||||
if (!exec_params->out_frame && func_type == DFT_PROCESS_FRAME) {
|
||||
av_log(ctx, AV_LOG_ERROR, "out frame is NULL when execute model.\n");
|
||||
return AVERROR(EINVAL);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int ff_dnn_fill_task(TaskItem *task, DNNExecBaseParams *exec_params, void *backend_model, int async, int do_ioproc) {
|
||||
if (task == NULL || exec_params == NULL || backend_model == NULL)
|
||||
return AVERROR(EINVAL);
|
||||
if (do_ioproc != 0 && do_ioproc != 1)
|
||||
return AVERROR(EINVAL);
|
||||
if (async != 0 && async != 1)
|
||||
return AVERROR(EINVAL);
|
||||
|
||||
task->do_ioproc = do_ioproc;
|
||||
task->async = async;
|
||||
task->input_name = exec_params->input_name;
|
||||
task->in_frame = exec_params->in_frame;
|
||||
task->out_frame = exec_params->out_frame;
|
||||
task->model = backend_model;
|
||||
task->nb_output = exec_params->nb_output;
|
||||
task->output_names = exec_params->output_names;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Thread routine for async execution.
|
||||
* @param args pointer to DNNAsyncExecModule module
|
||||
*/
|
||||
static void *async_thread_routine(void *args)
|
||||
{
|
||||
DNNAsyncExecModule *async_module = args;
|
||||
void *request = async_module->args;
|
||||
|
||||
if (async_module->start_inference(request) != 0) {
|
||||
return DNN_ASYNC_FAIL;
|
||||
}
|
||||
async_module->callback(request);
|
||||
return DNN_ASYNC_SUCCESS;
|
||||
}
|
||||
|
||||
int ff_dnn_async_module_cleanup(DNNAsyncExecModule *async_module)
|
||||
{
|
||||
void *status = 0;
|
||||
if (!async_module) {
|
||||
return AVERROR(EINVAL);
|
||||
}
|
||||
#if HAVE_PTHREAD_CANCEL
|
||||
pthread_join(async_module->thread_id, &status);
|
||||
if (status == DNN_ASYNC_FAIL) {
|
||||
av_log(NULL, AV_LOG_ERROR, "Last Inference Failed.\n");
|
||||
return DNN_GENERIC_ERROR;
|
||||
}
|
||||
#endif
|
||||
async_module->start_inference = NULL;
|
||||
async_module->callback = NULL;
|
||||
async_module->args = NULL;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int ff_dnn_start_inference_async(void *ctx, DNNAsyncExecModule *async_module)
|
||||
{
|
||||
int ret;
|
||||
void *status = 0;
|
||||
|
||||
if (!async_module) {
|
||||
av_log(ctx, AV_LOG_ERROR, "async_module is null when starting async inference.\n");
|
||||
return AVERROR(EINVAL);
|
||||
}
|
||||
|
||||
#if HAVE_PTHREAD_CANCEL
|
||||
pthread_join(async_module->thread_id, &status);
|
||||
if (status == DNN_ASYNC_FAIL) {
|
||||
av_log(ctx, AV_LOG_ERROR, "Unable to start inference as previous inference failed.\n");
|
||||
return DNN_GENERIC_ERROR;
|
||||
}
|
||||
ret = pthread_create(&async_module->thread_id, NULL, async_thread_routine, async_module);
|
||||
if (ret != 0) {
|
||||
av_log(ctx, AV_LOG_ERROR, "Unable to start async inference.\n");
|
||||
return ret;
|
||||
}
|
||||
#else
|
||||
ret = async_module->start_inference(async_module->args);
|
||||
if (ret != 0) {
|
||||
return ret;
|
||||
}
|
||||
async_module->callback(async_module->args);
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
|
||||
DNNAsyncStatusType ff_dnn_get_result_common(Queue *task_queue, AVFrame **in, AVFrame **out)
|
||||
{
|
||||
TaskItem *task = ff_queue_peek_front(task_queue);
|
||||
|
||||
if (!task) {
|
||||
return DAST_EMPTY_QUEUE;
|
||||
}
|
||||
|
||||
if (task->inference_done != task->inference_todo) {
|
||||
return DAST_NOT_READY;
|
||||
}
|
||||
|
||||
*in = task->in_frame;
|
||||
*out = task->out_frame;
|
||||
ff_queue_pop_front(task_queue);
|
||||
av_freep(&task);
|
||||
|
||||
return DAST_SUCCESS;
|
||||
}
|
||||
|
||||
int ff_dnn_fill_gettingoutput_task(TaskItem *task, DNNExecBaseParams *exec_params, void *backend_model, int input_height, int input_width, void *ctx)
|
||||
{
|
||||
AVFrame *in_frame = NULL;
|
||||
AVFrame *out_frame = NULL;
|
||||
|
||||
in_frame = av_frame_alloc();
|
||||
if (!in_frame) {
|
||||
av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for input frame\n");
|
||||
return AVERROR(ENOMEM);
|
||||
}
|
||||
|
||||
out_frame = av_frame_alloc();
|
||||
if (!out_frame) {
|
||||
av_frame_free(&in_frame);
|
||||
av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for output frame\n");
|
||||
return AVERROR(ENOMEM);
|
||||
}
|
||||
|
||||
in_frame->width = input_width;
|
||||
in_frame->height = input_height;
|
||||
exec_params->in_frame = in_frame;
|
||||
exec_params->out_frame = out_frame;
|
||||
|
||||
return ff_dnn_fill_task(task, exec_params, backend_model, 0, 0);
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/*
|
||||
* This file is part of FFmpeg.
|
||||
*
|
||||
* FFmpeg is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* FFmpeg is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with FFmpeg; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file
|
||||
* DNN common functions different backends.
|
||||
*/
|
||||
|
||||
#ifndef AVFILTER_DNN_DNN_BACKEND_COMMON_H
|
||||
#define AVFILTER_DNN_DNN_BACKEND_COMMON_H
|
||||
|
||||
#include "queue.h"
|
||||
#include "../dnn_interface.h"
|
||||
#include "libavutil/thread.h"
|
||||
|
||||
#define DNN_DEFINE_CLASS_EXT(name, desc, options) \
|
||||
{ \
|
||||
.class_name = desc, \
|
||||
.item_name = av_default_item_name, \
|
||||
.option = options, \
|
||||
.version = LIBAVUTIL_VERSION_INT, \
|
||||
.category = AV_CLASS_CATEGORY_FILTER, \
|
||||
}
|
||||
#define DNN_DEFINE_CLASS(fname) \
|
||||
DNN_DEFINE_CLASS_EXT(fname, #fname, fname##_options)
|
||||
|
||||
// one task for one function call from dnn interface
|
||||
typedef struct TaskItem {
|
||||
void *model; // model for the backend
|
||||
AVFrame *in_frame;
|
||||
AVFrame *out_frame;
|
||||
const char *input_name;
|
||||
const char **output_names;
|
||||
uint8_t async;
|
||||
uint8_t do_ioproc;
|
||||
uint32_t nb_output;
|
||||
uint32_t inference_todo;
|
||||
uint32_t inference_done;
|
||||
} TaskItem;
|
||||
|
||||
// one task might have multiple inferences
|
||||
typedef struct LastLevelTaskItem {
|
||||
TaskItem *task;
|
||||
uint32_t bbox_index;
|
||||
} LastLevelTaskItem;
|
||||
|
||||
/**
|
||||
* Common Async Execution Mechanism for the DNN Backends.
|
||||
*/
|
||||
typedef struct DNNAsyncExecModule {
|
||||
/**
|
||||
* Synchronous inference function for the backend
|
||||
* with corresponding request item as the argument.
|
||||
*/
|
||||
int (*start_inference)(void *request);
|
||||
|
||||
/**
|
||||
* Completion Callback for the backend.
|
||||
* Expected argument type of callback must match that
|
||||
* of the inference function.
|
||||
*/
|
||||
void (*callback)(void *args);
|
||||
|
||||
/**
|
||||
* Argument for the execution functions.
|
||||
* i.e. Request item for the backend.
|
||||
*/
|
||||
void *args;
|
||||
#if HAVE_PTHREAD_CANCEL
|
||||
pthread_t thread_id;
|
||||
pthread_attr_t thread_attr;
|
||||
#endif
|
||||
} DNNAsyncExecModule;
|
||||
|
||||
int ff_check_exec_params(void *ctx, DNNBackendType backend, DNNFunctionType func_type, DNNExecBaseParams *exec_params);
|
||||
|
||||
/**
|
||||
* Fill the Task for Backend Execution. It should be called after
|
||||
* checking execution parameters using ff_check_exec_params.
|
||||
*
|
||||
* @param task pointer to the allocated task
|
||||
* @param exec_param pointer to execution parameters
|
||||
* @param backend_model void pointer to the backend model
|
||||
* @param async flag for async execution. Must be 0 or 1
|
||||
* @param do_ioproc flag for IO processing. Must be 0 or 1
|
||||
*
|
||||
* @returns 0 if successful or error code otherwise.
|
||||
*/
|
||||
int ff_dnn_fill_task(TaskItem *task, DNNExecBaseParams *exec_params, void *backend_model, int async, int do_ioproc);
|
||||
|
||||
/**
|
||||
* Join the Async Execution thread and set module pointers to NULL.
|
||||
*
|
||||
* @param async_module pointer to DNNAsyncExecModule module
|
||||
*
|
||||
* @returns 0 if successful or error code otherwise.
|
||||
*/
|
||||
int ff_dnn_async_module_cleanup(DNNAsyncExecModule *async_module);
|
||||
|
||||
/**
|
||||
* Start asynchronous inference routine for the TensorFlow
|
||||
* model on a detached thread. It calls the completion callback
|
||||
* after the inference completes. Completion callback and inference
|
||||
* function must be set before calling this function.
|
||||
*
|
||||
* If POSIX threads aren't supported, the execution rolls back
|
||||
* to synchronous mode, calling completion callback after inference.
|
||||
*
|
||||
* @param ctx pointer to the backend context
|
||||
* @param async_module pointer to DNNAsyncExecModule module
|
||||
*
|
||||
* @returns 0 on the start of async inference or error code otherwise.
|
||||
*/
|
||||
int ff_dnn_start_inference_async(void *ctx, DNNAsyncExecModule *async_module);
|
||||
|
||||
/**
|
||||
* Extract input and output frame from the Task Queue after
|
||||
* asynchronous inference.
|
||||
*
|
||||
* @param task_queue pointer to the task queue of the backend
|
||||
* @param in double pointer to the input frame
|
||||
* @param out double pointer to the output frame
|
||||
*
|
||||
* @retval DAST_EMPTY_QUEUE if task queue is empty
|
||||
* @retval DAST_NOT_READY if inference not completed yet.
|
||||
* @retval DAST_SUCCESS if result successfully extracted
|
||||
*/
|
||||
DNNAsyncStatusType ff_dnn_get_result_common(Queue *task_queue, AVFrame **in, AVFrame **out);
|
||||
|
||||
/**
|
||||
* Allocate input and output frames and fill the Task
|
||||
* with execution parameters.
|
||||
*
|
||||
* @param task pointer to the allocated task
|
||||
* @param exec_params pointer to execution parameters
|
||||
* @param backend_model void pointer to the backend model
|
||||
* @param input_height height of input frame
|
||||
* @param input_width width of input frame
|
||||
* @param ctx pointer to the backend context
|
||||
*
|
||||
* @returns 0 if successful or error code otherwise.
|
||||
*/
|
||||
int ff_dnn_fill_gettingoutput_task(TaskItem *task, DNNExecBaseParams *exec_params, void *backend_model, int input_height, int input_width, void *ctx);
|
||||
|
||||
#endif
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,892 @@
|
||||
/*
|
||||
* Copyright (c) 2018 Sergey Lavrushkin
|
||||
*
|
||||
* This file is part of FFmpeg.
|
||||
*
|
||||
* FFmpeg is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* FFmpeg is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with FFmpeg; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file
|
||||
* DNN tensorflow backend implementation.
|
||||
*/
|
||||
|
||||
#include "libavformat/avio.h"
|
||||
#include "libavutil/avassert.h"
|
||||
#include "libavutil/avstring.h"
|
||||
#include "libavutil/cpu.h"
|
||||
#include "libavutil/mem.h"
|
||||
#include "libavutil/opt.h"
|
||||
#include "libavcodec/defs.h"
|
||||
#include "dnn_io_proc.h"
|
||||
#include "dnn_backend_common.h"
|
||||
#include "safe_queue.h"
|
||||
#include <tensorflow/c/c_api.h>
|
||||
|
||||
typedef struct TFModel {
|
||||
DNNModel model;
|
||||
DnnContext *ctx;
|
||||
TF_Graph *graph;
|
||||
TF_Session *session;
|
||||
TF_Status *status;
|
||||
SafeQueue *request_queue;
|
||||
Queue *lltask_queue;
|
||||
Queue *task_queue;
|
||||
} TFModel;
|
||||
|
||||
/**
|
||||
* Stores execution parameters for single
|
||||
* call to the TensorFlow C API
|
||||
*/
|
||||
typedef struct TFInferRequest {
|
||||
TF_Output *tf_outputs;
|
||||
TF_Tensor **output_tensors;
|
||||
TF_Output *tf_input;
|
||||
TF_Tensor *input_tensor;
|
||||
} TFInferRequest;
|
||||
|
||||
typedef struct TFRequestItem {
|
||||
TFInferRequest *infer_request;
|
||||
LastLevelTaskItem *lltask;
|
||||
TF_Status *status;
|
||||
DNNAsyncExecModule exec_module;
|
||||
} TFRequestItem;
|
||||
|
||||
#define OFFSET(x) offsetof(TFOptions, x)
|
||||
#define FLAGS AV_OPT_FLAG_FILTERING_PARAM
|
||||
static const AVOption dnn_tensorflow_options[] = {
|
||||
{ "sess_config", "config for SessionOptions", OFFSET(sess_config), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, FLAGS },
|
||||
{ NULL }
|
||||
};
|
||||
|
||||
|
||||
static int execute_model_tf(TFRequestItem *request, Queue *lltask_queue);
|
||||
static void infer_completion_callback(void *args);
|
||||
static inline void destroy_request_item(TFRequestItem **arg);
|
||||
|
||||
static void free_buffer(void *data, size_t length)
|
||||
{
|
||||
av_freep(&data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Free the contents of TensorFlow inference request.
|
||||
* It does not free the TFInferRequest instance.
|
||||
*
|
||||
* @param request pointer to TFInferRequest instance.
|
||||
* NULL pointer is allowed.
|
||||
*/
|
||||
static void tf_free_request(TFInferRequest *request)
|
||||
{
|
||||
if (!request)
|
||||
return;
|
||||
if (request->input_tensor) {
|
||||
TF_DeleteTensor(request->input_tensor);
|
||||
request->input_tensor = NULL;
|
||||
}
|
||||
av_freep(&request->tf_input);
|
||||
av_freep(&request->tf_outputs);
|
||||
if (request->output_tensors) {
|
||||
int nb_output = sizeof(*request->output_tensors)/sizeof(request->output_tensors[0]);
|
||||
for (uint32_t i = 0; i < nb_output; ++i) {
|
||||
if (request->output_tensors[i]) {
|
||||
TF_DeleteTensor(request->output_tensors[i]);
|
||||
request->output_tensors[i] = NULL;
|
||||
}
|
||||
}
|
||||
av_freep(&request->output_tensors);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a TensorFlow inference request. All properties
|
||||
* are initially unallocated and set as NULL.
|
||||
*
|
||||
* @return pointer to the allocated TFInferRequest instance.
|
||||
*/
|
||||
static TFInferRequest *tf_create_inference_request(void)
|
||||
{
|
||||
TFInferRequest *infer_request = av_malloc(sizeof(TFInferRequest));
|
||||
if (!infer_request) {
|
||||
return NULL;
|
||||
}
|
||||
infer_request->tf_outputs = NULL;
|
||||
infer_request->tf_input = NULL;
|
||||
infer_request->input_tensor = NULL;
|
||||
infer_request->output_tensors = NULL;
|
||||
return infer_request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start synchronous inference for the TensorFlow model.
|
||||
*
|
||||
* @param request pointer to the TFRequestItem for inference
|
||||
* @retval 0 if execution is successful
|
||||
* @retval AVERROR(EINVAL) if request is NULL
|
||||
* @retval DNN_GENERIC_ERROR if execution fails
|
||||
*/
|
||||
static int tf_start_inference(void *args)
|
||||
{
|
||||
TFRequestItem *request = args;
|
||||
TFInferRequest *infer_request = request->infer_request;
|
||||
LastLevelTaskItem *lltask = request->lltask;
|
||||
TaskItem *task = lltask->task;
|
||||
TFModel *tf_model = task->model;
|
||||
|
||||
if (!request) {
|
||||
av_log(tf_model->ctx, AV_LOG_ERROR, "TFRequestItem is NULL\n");
|
||||
return AVERROR(EINVAL);
|
||||
}
|
||||
|
||||
TF_SessionRun(tf_model->session, NULL,
|
||||
infer_request->tf_input, &infer_request->input_tensor, 1,
|
||||
infer_request->tf_outputs, infer_request->output_tensors,
|
||||
task->nb_output, NULL, 0, NULL,
|
||||
request->status);
|
||||
if (TF_GetCode(request->status) != TF_OK) {
|
||||
av_log(tf_model->ctx, AV_LOG_ERROR, "%s", TF_Message(request->status));
|
||||
return DNN_GENERIC_ERROR;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Free the TFRequestItem completely.
|
||||
*
|
||||
* @param arg Address of the TFInferRequest instance.
|
||||
*/
|
||||
static inline void destroy_request_item(TFRequestItem **arg) {
|
||||
TFRequestItem *request;
|
||||
if (!arg) {
|
||||
return;
|
||||
}
|
||||
request = *arg;
|
||||
tf_free_request(request->infer_request);
|
||||
av_freep(&request->infer_request);
|
||||
av_freep(&request->lltask);
|
||||
TF_DeleteStatus(request->status);
|
||||
ff_dnn_async_module_cleanup(&request->exec_module);
|
||||
av_freep(arg);
|
||||
}
|
||||
|
||||
static int extract_lltask_from_task(TaskItem *task, Queue *lltask_queue)
|
||||
{
|
||||
TFModel *tf_model = task->model;
|
||||
DnnContext *ctx = tf_model->ctx;
|
||||
LastLevelTaskItem *lltask = av_malloc(sizeof(*lltask));
|
||||
if (!lltask) {
|
||||
av_log(ctx, AV_LOG_ERROR, "Unable to allocate space for LastLevelTaskItem\n");
|
||||
return AVERROR(ENOMEM);
|
||||
}
|
||||
task->inference_todo = 1;
|
||||
task->inference_done = 0;
|
||||
lltask->task = task;
|
||||
if (ff_queue_push_back(lltask_queue, lltask) < 0) {
|
||||
av_log(ctx, AV_LOG_ERROR, "Failed to push back lltask_queue.\n");
|
||||
av_freep(&lltask);
|
||||
return AVERROR(ENOMEM);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static TF_Buffer *read_graph(const char *model_filename)
|
||||
{
|
||||
TF_Buffer *graph_buf;
|
||||
unsigned char *graph_data = NULL;
|
||||
AVIOContext *model_file_context;
|
||||
long size, bytes_read;
|
||||
|
||||
if (avio_open(&model_file_context, model_filename, AVIO_FLAG_READ) < 0){
|
||||
return NULL;
|
||||
}
|
||||
|
||||
size = avio_size(model_file_context);
|
||||
|
||||
graph_data = av_malloc(size);
|
||||
if (!graph_data){
|
||||
avio_closep(&model_file_context);
|
||||
return NULL;
|
||||
}
|
||||
bytes_read = avio_read(model_file_context, graph_data, size);
|
||||
avio_closep(&model_file_context);
|
||||
if (bytes_read != size){
|
||||
av_freep(&graph_data);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
graph_buf = TF_NewBuffer();
|
||||
graph_buf->data = graph_data;
|
||||
graph_buf->length = size;
|
||||
graph_buf->data_deallocator = free_buffer;
|
||||
|
||||
return graph_buf;
|
||||
}
|
||||
|
||||
static TF_Tensor *allocate_input_tensor(const DNNData *input)
|
||||
{
|
||||
TF_DataType dt;
|
||||
size_t size;
|
||||
int64_t input_dims[4] = { 0 };
|
||||
|
||||
input_dims[0] = 1;
|
||||
input_dims[1] = input->dims[dnn_get_height_idx_by_layout(input->layout)];
|
||||
input_dims[2] = input->dims[dnn_get_width_idx_by_layout(input->layout)];
|
||||
input_dims[3] = input->dims[dnn_get_channel_idx_by_layout(input->layout)];
|
||||
switch (input->dt) {
|
||||
case DNN_FLOAT:
|
||||
dt = TF_FLOAT;
|
||||
size = sizeof(float);
|
||||
break;
|
||||
case DNN_UINT8:
|
||||
dt = TF_UINT8;
|
||||
size = 1;
|
||||
break;
|
||||
default:
|
||||
av_assert0(!"should not reach here");
|
||||
}
|
||||
|
||||
return TF_AllocateTensor(dt, input_dims, 4,
|
||||
input_dims[1] * input_dims[2] * input_dims[3] * size);
|
||||
}
|
||||
|
||||
static int get_input_tf(DNNModel *model, DNNData *input, const char *input_name)
|
||||
{
|
||||
TFModel *tf_model = (TFModel *)model;
|
||||
DnnContext *ctx = tf_model->ctx;
|
||||
TF_Status *status;
|
||||
TF_DataType dt;
|
||||
int64_t dims[4];
|
||||
|
||||
TF_Output tf_output;
|
||||
tf_output.oper = TF_GraphOperationByName(tf_model->graph, input_name);
|
||||
if (!tf_output.oper) {
|
||||
av_log(ctx, AV_LOG_ERROR, "Could not find \"%s\" in model\n", input_name);
|
||||
return AVERROR(EINVAL);
|
||||
}
|
||||
|
||||
tf_output.index = 0;
|
||||
dt = TF_OperationOutputType(tf_output);
|
||||
switch (dt) {
|
||||
case TF_FLOAT:
|
||||
input->dt = DNN_FLOAT;
|
||||
break;
|
||||
case TF_UINT8:
|
||||
input->dt = DNN_UINT8;
|
||||
break;
|
||||
default:
|
||||
av_log(ctx, AV_LOG_ERROR, "Unsupported output type %d in model\n", dt);
|
||||
return AVERROR(EINVAL);
|
||||
}
|
||||
input->order = DCO_RGB;
|
||||
|
||||
status = TF_NewStatus();
|
||||
TF_GraphGetTensorShape(tf_model->graph, tf_output, dims, 4, status);
|
||||
if (TF_GetCode(status) != TF_OK){
|
||||
TF_DeleteStatus(status);
|
||||
av_log(ctx, AV_LOG_ERROR, "Failed to get input tensor shape: number of dimension incorrect\n");
|
||||
return DNN_GENERIC_ERROR;
|
||||
}
|
||||
TF_DeleteStatus(status);
|
||||
|
||||
// currently only NHWC is supported
|
||||
av_assert0(dims[0] == 1 || dims[0] == -1);
|
||||
for (int i = 0; i < 4; i++)
|
||||
input->dims[i] = dims[i];
|
||||
input->layout = DL_NHWC;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
int ret;
|
||||
TFModel *tf_model = (TFModel *)model;
|
||||
DnnContext *ctx = tf_model->ctx;
|
||||
TaskItem task;
|
||||
TFRequestItem *request;
|
||||
DNNExecBaseParams exec_params = {
|
||||
.input_name = input_name,
|
||||
.output_names = &output_name,
|
||||
.nb_output = 1,
|
||||
.in_frame = NULL,
|
||||
.out_frame = NULL,
|
||||
};
|
||||
|
||||
ret = ff_dnn_fill_gettingoutput_task(&task, &exec_params, tf_model, input_height, input_width, ctx);
|
||||
if (ret != 0) {
|
||||
goto err;
|
||||
}
|
||||
|
||||
ret = extract_lltask_from_task(&task, tf_model->lltask_queue);
|
||||
if (ret != 0) {
|
||||
av_log(ctx, AV_LOG_ERROR, "unable to extract inference from task.\n");
|
||||
goto err;
|
||||
}
|
||||
|
||||
request = ff_safe_queue_pop_front(tf_model->request_queue);
|
||||
if (!request) {
|
||||
av_log(ctx, AV_LOG_ERROR, "unable to get infer request.\n");
|
||||
ret = AVERROR(EINVAL);
|
||||
goto err;
|
||||
}
|
||||
|
||||
ret = execute_model_tf(request, tf_model->lltask_queue);
|
||||
*output_width = task.out_frame->width;
|
||||
*output_height = task.out_frame->height;
|
||||
|
||||
err:
|
||||
av_frame_free(&task.out_frame);
|
||||
av_frame_free(&task.in_frame);
|
||||
return ret;
|
||||
}
|
||||
|
||||
#define SPACE_CHARS " \t\r\n"
|
||||
static int hex_to_data(uint8_t *data, const char *p)
|
||||
{
|
||||
int c, len, v;
|
||||
|
||||
len = 0;
|
||||
v = 1;
|
||||
for (;;) {
|
||||
p += strspn(p, SPACE_CHARS);
|
||||
if (*p == '\0')
|
||||
break;
|
||||
c = av_toupper((unsigned char) *p++);
|
||||
if (c >= '0' && c <= '9')
|
||||
c = c - '0';
|
||||
else if (c >= 'A' && c <= 'F')
|
||||
c = c - 'A' + 10;
|
||||
else
|
||||
break;
|
||||
v = (v << 4) | c;
|
||||
if (v & 0x100) {
|
||||
if (data) {
|
||||
data[len] = v;
|
||||
}
|
||||
len++;
|
||||
v = 1;
|
||||
}
|
||||
}
|
||||
return len;
|
||||
}
|
||||
|
||||
static int load_tf_model(TFModel *tf_model, const char *model_filename)
|
||||
{
|
||||
DnnContext *ctx = tf_model->ctx;
|
||||
TF_Buffer *graph_def;
|
||||
TF_ImportGraphDefOptions *graph_opts;
|
||||
TF_SessionOptions *sess_opts;
|
||||
const TF_Operation *init_op;
|
||||
uint8_t *sess_config = NULL;
|
||||
int sess_config_length = 0;
|
||||
|
||||
// prepare the sess config data
|
||||
if (ctx->tf_option.sess_config != NULL) {
|
||||
const char *config;
|
||||
/*
|
||||
tf_model->ctx.options.sess_config is hex to present the serialized proto
|
||||
required by TF_SetConfig below, so we need to first generate the serialized
|
||||
proto in a python script, tools/python/tf_sess_config.py is a script example
|
||||
to generate the configs of sess_config.
|
||||
*/
|
||||
if (strncmp(ctx->tf_option.sess_config, "0x", 2) != 0) {
|
||||
av_log(ctx, AV_LOG_ERROR, "sess_config should start with '0x'\n");
|
||||
return AVERROR(EINVAL);
|
||||
}
|
||||
config = ctx->tf_option.sess_config + 2;
|
||||
sess_config_length = hex_to_data(NULL, config);
|
||||
|
||||
sess_config = av_mallocz(sess_config_length + AV_INPUT_BUFFER_PADDING_SIZE);
|
||||
if (!sess_config) {
|
||||
av_log(ctx, AV_LOG_ERROR, "failed to allocate memory\n");
|
||||
return AVERROR(ENOMEM);
|
||||
}
|
||||
if (hex_to_data(sess_config, config) < 0) {
|
||||
av_log(ctx, AV_LOG_ERROR, "failed to convert hex to data\n");
|
||||
return AVERROR(EINVAL);
|
||||
}
|
||||
}
|
||||
|
||||
graph_def = read_graph(model_filename);
|
||||
if (!graph_def){
|
||||
av_log(ctx, AV_LOG_ERROR, "Failed to read model \"%s\" graph\n", model_filename);
|
||||
av_freep(&sess_config);
|
||||
return AVERROR(EINVAL);
|
||||
}
|
||||
tf_model->graph = TF_NewGraph();
|
||||
tf_model->status = TF_NewStatus();
|
||||
graph_opts = TF_NewImportGraphDefOptions();
|
||||
TF_GraphImportGraphDef(tf_model->graph, graph_def, graph_opts, tf_model->status);
|
||||
TF_DeleteImportGraphDefOptions(graph_opts);
|
||||
TF_DeleteBuffer(graph_def);
|
||||
if (TF_GetCode(tf_model->status) != TF_OK){
|
||||
av_log(ctx, AV_LOG_ERROR, "Failed to import serialized graph to model graph\n");
|
||||
av_freep(&sess_config);
|
||||
return DNN_GENERIC_ERROR;
|
||||
}
|
||||
|
||||
init_op = TF_GraphOperationByName(tf_model->graph, "init");
|
||||
sess_opts = TF_NewSessionOptions();
|
||||
|
||||
if (sess_config) {
|
||||
TF_SetConfig(sess_opts, sess_config, sess_config_length,tf_model->status);
|
||||
av_freep(&sess_config);
|
||||
if (TF_GetCode(tf_model->status) != TF_OK) {
|
||||
TF_DeleteSessionOptions(sess_opts);
|
||||
av_log(ctx, AV_LOG_ERROR, "Failed to set config for sess options with %s\n",
|
||||
ctx->tf_option.sess_config);
|
||||
return DNN_GENERIC_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
tf_model->session = TF_NewSession(tf_model->graph, sess_opts, tf_model->status);
|
||||
TF_DeleteSessionOptions(sess_opts);
|
||||
if (TF_GetCode(tf_model->status) != TF_OK)
|
||||
{
|
||||
av_freep(&sess_config);
|
||||
av_log(ctx, AV_LOG_ERROR, "Failed to create new session with model graph\n");
|
||||
return DNN_GENERIC_ERROR;
|
||||
}
|
||||
|
||||
// Run initialization operation with name "init" if it is present in graph
|
||||
if (init_op){
|
||||
TF_SessionRun(tf_model->session, NULL,
|
||||
NULL, NULL, 0,
|
||||
NULL, NULL, 0,
|
||||
&init_op, 1, NULL, tf_model->status);
|
||||
if (TF_GetCode(tf_model->status) != TF_OK)
|
||||
{
|
||||
av_freep(&sess_config);
|
||||
av_log(ctx, AV_LOG_ERROR, "Failed to run session when initializing\n");
|
||||
return DNN_GENERIC_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void dnn_free_model_tf(DNNModel **model)
|
||||
{
|
||||
TFModel *tf_model;
|
||||
|
||||
if (!model || !*model)
|
||||
return;
|
||||
|
||||
tf_model = (TFModel *)(*model);
|
||||
while (ff_safe_queue_size(tf_model->request_queue) != 0) {
|
||||
TFRequestItem *item = ff_safe_queue_pop_front(tf_model->request_queue);
|
||||
destroy_request_item(&item);
|
||||
}
|
||||
ff_safe_queue_destroy(tf_model->request_queue);
|
||||
|
||||
while (ff_queue_size(tf_model->lltask_queue) != 0) {
|
||||
LastLevelTaskItem *item = ff_queue_pop_front(tf_model->lltask_queue);
|
||||
av_freep(&item);
|
||||
}
|
||||
ff_queue_destroy(tf_model->lltask_queue);
|
||||
|
||||
while (ff_queue_size(tf_model->task_queue) != 0) {
|
||||
TaskItem *item = ff_queue_pop_front(tf_model->task_queue);
|
||||
av_frame_free(&item->in_frame);
|
||||
av_frame_free(&item->out_frame);
|
||||
av_freep(&item);
|
||||
}
|
||||
ff_queue_destroy(tf_model->task_queue);
|
||||
|
||||
if (tf_model->graph){
|
||||
TF_DeleteGraph(tf_model->graph);
|
||||
}
|
||||
if (tf_model->session){
|
||||
TF_CloseSession(tf_model->session, tf_model->status);
|
||||
TF_DeleteSession(tf_model->session, tf_model->status);
|
||||
}
|
||||
if (tf_model->status){
|
||||
TF_DeleteStatus(tf_model->status);
|
||||
}
|
||||
av_freep(&tf_model);
|
||||
*model = NULL;
|
||||
}
|
||||
|
||||
static DNNModel *dnn_load_model_tf(DnnContext *ctx, DNNFunctionType func_type, AVFilterContext *filter_ctx)
|
||||
{
|
||||
DNNModel *model = NULL;
|
||||
TFModel *tf_model = NULL;
|
||||
|
||||
tf_model = av_mallocz(sizeof(TFModel));
|
||||
if (!tf_model)
|
||||
return NULL;
|
||||
model = &tf_model->model;
|
||||
tf_model->ctx = ctx;
|
||||
|
||||
if (load_tf_model(tf_model, ctx->model_filename) != 0){
|
||||
av_log(ctx, AV_LOG_ERROR, "Failed to load TensorFlow model: \"%s\"\n", ctx->model_filename);
|
||||
goto err;
|
||||
}
|
||||
|
||||
if (ctx->nireq <= 0) {
|
||||
ctx->nireq = av_cpu_count() / 2 + 1;
|
||||
}
|
||||
|
||||
#if !HAVE_PTHREAD_CANCEL
|
||||
if (ctx->options.async) {
|
||||
ctx->options.async = 0;
|
||||
av_log(filter_ctx, AV_LOG_WARNING, "pthread is not supported, roll back to sync.\n");
|
||||
}
|
||||
#endif
|
||||
|
||||
tf_model->request_queue = ff_safe_queue_create();
|
||||
if (!tf_model->request_queue) {
|
||||
goto err;
|
||||
}
|
||||
|
||||
for (int i = 0; i < ctx->nireq; i++) {
|
||||
TFRequestItem *item = av_mallocz(sizeof(*item));
|
||||
if (!item) {
|
||||
goto err;
|
||||
}
|
||||
item->lltask = NULL;
|
||||
item->infer_request = tf_create_inference_request();
|
||||
if (!item->infer_request) {
|
||||
av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for TensorFlow inference request\n");
|
||||
av_freep(&item);
|
||||
goto err;
|
||||
}
|
||||
item->status = TF_NewStatus();
|
||||
item->exec_module.start_inference = &tf_start_inference;
|
||||
item->exec_module.callback = &infer_completion_callback;
|
||||
item->exec_module.args = item;
|
||||
|
||||
if (ff_safe_queue_push_back(tf_model->request_queue, item) < 0) {
|
||||
destroy_request_item(&item);
|
||||
goto err;
|
||||
}
|
||||
}
|
||||
|
||||
tf_model->lltask_queue = ff_queue_create();
|
||||
if (!tf_model->lltask_queue) {
|
||||
goto err;
|
||||
}
|
||||
|
||||
tf_model->task_queue = ff_queue_create();
|
||||
if (!tf_model->task_queue) {
|
||||
goto err;
|
||||
}
|
||||
|
||||
model->get_input = &get_input_tf;
|
||||
model->get_output = &get_output_tf;
|
||||
model->filter_ctx = filter_ctx;
|
||||
model->func_type = func_type;
|
||||
|
||||
return model;
|
||||
err:
|
||||
dnn_free_model_tf(&model);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static int fill_model_input_tf(TFModel *tf_model, TFRequestItem *request) {
|
||||
DNNData input = { 0 };
|
||||
LastLevelTaskItem *lltask;
|
||||
TaskItem *task;
|
||||
TFInferRequest *infer_request = NULL;
|
||||
DnnContext *ctx = tf_model->ctx;
|
||||
int ret = 0;
|
||||
|
||||
lltask = ff_queue_pop_front(tf_model->lltask_queue);
|
||||
av_assert0(lltask);
|
||||
task = lltask->task;
|
||||
request->lltask = lltask;
|
||||
|
||||
ret = get_input_tf(&tf_model->model, &input, task->input_name);
|
||||
if (ret != 0) {
|
||||
goto err;
|
||||
}
|
||||
|
||||
infer_request = request->infer_request;
|
||||
input.dims[1] = task->in_frame->height;
|
||||
input.dims[2] = task->in_frame->width;
|
||||
|
||||
infer_request->tf_input = av_malloc(sizeof(TF_Output));
|
||||
if (!infer_request->tf_input) {
|
||||
av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for input tensor\n");
|
||||
ret = AVERROR(ENOMEM);
|
||||
goto err;
|
||||
}
|
||||
|
||||
infer_request->tf_input->oper = TF_GraphOperationByName(tf_model->graph, task->input_name);
|
||||
if (!infer_request->tf_input->oper){
|
||||
av_log(ctx, AV_LOG_ERROR, "Could not find \"%s\" in model\n", task->input_name);
|
||||
ret = DNN_GENERIC_ERROR;
|
||||
goto err;
|
||||
}
|
||||
infer_request->tf_input->index = 0;
|
||||
|
||||
infer_request->input_tensor = allocate_input_tensor(&input);
|
||||
if (!infer_request->input_tensor){
|
||||
av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for input tensor\n");
|
||||
ret = AVERROR(ENOMEM);
|
||||
goto err;
|
||||
}
|
||||
input.data = (float *)TF_TensorData(infer_request->input_tensor);
|
||||
|
||||
switch (tf_model->model.func_type) {
|
||||
case DFT_PROCESS_FRAME:
|
||||
if (task->do_ioproc) {
|
||||
if (tf_model->model.frame_pre_proc != NULL) {
|
||||
tf_model->model.frame_pre_proc(task->in_frame, &input, tf_model->model.filter_ctx);
|
||||
} else {
|
||||
ff_proc_from_frame_to_dnn(task->in_frame, &input, ctx);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case DFT_ANALYTICS_DETECT:
|
||||
ff_frame_to_dnn_detect(task->in_frame, &input, ctx);
|
||||
break;
|
||||
default:
|
||||
avpriv_report_missing_feature(ctx, "model function type %d", tf_model->model.func_type);
|
||||
break;
|
||||
}
|
||||
|
||||
infer_request->tf_outputs = av_malloc_array(task->nb_output, sizeof(TF_Output));
|
||||
if (infer_request->tf_outputs == NULL) {
|
||||
av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for *tf_outputs\n");
|
||||
ret = AVERROR(ENOMEM);
|
||||
goto err;
|
||||
}
|
||||
|
||||
infer_request->output_tensors = av_calloc(task->nb_output, sizeof(*infer_request->output_tensors));
|
||||
if (!infer_request->output_tensors) {
|
||||
av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for output tensor\n");
|
||||
ret = AVERROR(ENOMEM);
|
||||
goto err;
|
||||
}
|
||||
|
||||
for (int i = 0; i < task->nb_output; ++i) {
|
||||
infer_request->output_tensors[i] = NULL;
|
||||
infer_request->tf_outputs[i].oper = TF_GraphOperationByName(tf_model->graph, task->output_names[i]);
|
||||
if (!infer_request->tf_outputs[i].oper) {
|
||||
av_log(ctx, AV_LOG_ERROR, "Could not find output \"%s\" in model\n", task->output_names[i]);
|
||||
ret = DNN_GENERIC_ERROR;
|
||||
goto err;
|
||||
}
|
||||
infer_request->tf_outputs[i].index = 0;
|
||||
}
|
||||
|
||||
return 0;
|
||||
err:
|
||||
tf_free_request(infer_request);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static void infer_completion_callback(void *args) {
|
||||
TFRequestItem *request = args;
|
||||
LastLevelTaskItem *lltask = request->lltask;
|
||||
TaskItem *task = lltask->task;
|
||||
DNNData *outputs;
|
||||
TFInferRequest *infer_request = request->infer_request;
|
||||
TFModel *tf_model = task->model;
|
||||
DnnContext *ctx = tf_model->ctx;
|
||||
|
||||
outputs = av_calloc(task->nb_output, sizeof(*outputs));
|
||||
if (!outputs) {
|
||||
av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for *outputs\n");
|
||||
goto err;
|
||||
}
|
||||
|
||||
for (uint32_t i = 0; i < task->nb_output; ++i) {
|
||||
outputs[i].dims[dnn_get_height_idx_by_layout(outputs[i].layout)] =
|
||||
TF_Dim(infer_request->output_tensors[i], 1);
|
||||
outputs[i].dims[dnn_get_width_idx_by_layout(outputs[i].layout)] =
|
||||
TF_Dim(infer_request->output_tensors[i], 2);
|
||||
outputs[i].dims[dnn_get_channel_idx_by_layout(outputs[i].layout)] =
|
||||
TF_Dim(infer_request->output_tensors[i], 3);
|
||||
outputs[i].data = TF_TensorData(infer_request->output_tensors[i]);
|
||||
outputs[i].dt = (DNNDataType)TF_TensorType(infer_request->output_tensors[i]);
|
||||
}
|
||||
switch (tf_model->model.func_type) {
|
||||
case DFT_PROCESS_FRAME:
|
||||
//it only support 1 output if it's frame in & frame out
|
||||
if (task->do_ioproc) {
|
||||
if (tf_model->model.frame_post_proc != NULL) {
|
||||
tf_model->model.frame_post_proc(task->out_frame, outputs, tf_model->model.filter_ctx);
|
||||
} else {
|
||||
ff_proc_from_dnn_to_frame(task->out_frame, outputs, ctx);
|
||||
}
|
||||
} else {
|
||||
task->out_frame->width =
|
||||
outputs[0].dims[dnn_get_width_idx_by_layout(outputs[0].layout)];
|
||||
task->out_frame->height =
|
||||
outputs[0].dims[dnn_get_height_idx_by_layout(outputs[0].layout)];
|
||||
}
|
||||
break;
|
||||
case DFT_ANALYTICS_DETECT:
|
||||
if (!tf_model->model.detect_post_proc) {
|
||||
av_log(ctx, AV_LOG_ERROR, "Detect filter needs provide post proc\n");
|
||||
return;
|
||||
}
|
||||
tf_model->model.detect_post_proc(task->in_frame, outputs, task->nb_output, tf_model->model.filter_ctx);
|
||||
break;
|
||||
default:
|
||||
av_log(ctx, AV_LOG_ERROR, "Tensorflow backend does not support this kind of dnn filter now\n");
|
||||
goto err;
|
||||
}
|
||||
task->inference_done++;
|
||||
err:
|
||||
tf_free_request(infer_request);
|
||||
av_freep(&outputs);
|
||||
|
||||
if (ff_safe_queue_push_back(tf_model->request_queue, request) < 0) {
|
||||
destroy_request_item(&request);
|
||||
av_log(ctx, AV_LOG_ERROR, "Failed to push back request_queue.\n");
|
||||
}
|
||||
}
|
||||
|
||||
static int execute_model_tf(TFRequestItem *request, Queue *lltask_queue)
|
||||
{
|
||||
TFModel *tf_model;
|
||||
DnnContext *ctx;
|
||||
LastLevelTaskItem *lltask;
|
||||
TaskItem *task;
|
||||
int ret = 0;
|
||||
|
||||
if (ff_queue_size(lltask_queue) == 0) {
|
||||
destroy_request_item(&request);
|
||||
return 0;
|
||||
}
|
||||
|
||||
lltask = ff_queue_peek_front(lltask_queue);
|
||||
task = lltask->task;
|
||||
tf_model = task->model;
|
||||
ctx = tf_model->ctx;
|
||||
|
||||
ret = fill_model_input_tf(tf_model, request);
|
||||
if (ret != 0) {
|
||||
goto err;
|
||||
}
|
||||
|
||||
if (task->async) {
|
||||
if (ff_dnn_start_inference_async(ctx, &request->exec_module) != 0) {
|
||||
goto err;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
else {
|
||||
ret = tf_start_inference(request);
|
||||
if (ret != 0) {
|
||||
goto err;
|
||||
}
|
||||
infer_completion_callback(request);
|
||||
return (task->inference_done == task->inference_todo) ? 0 : DNN_GENERIC_ERROR;
|
||||
}
|
||||
err:
|
||||
tf_free_request(request->infer_request);
|
||||
if (ff_safe_queue_push_back(tf_model->request_queue, request) < 0) {
|
||||
destroy_request_item(&request);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
static int dnn_execute_model_tf(const DNNModel *model, DNNExecBaseParams *exec_params)
|
||||
{
|
||||
TFModel *tf_model = (TFModel *)model;
|
||||
DnnContext *ctx = tf_model->ctx;
|
||||
TaskItem *task;
|
||||
TFRequestItem *request;
|
||||
int ret = 0;
|
||||
|
||||
ret = ff_check_exec_params(ctx, DNN_TF, model->func_type, exec_params);
|
||||
if (ret != 0) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
task = av_malloc(sizeof(*task));
|
||||
if (!task) {
|
||||
av_log(ctx, AV_LOG_ERROR, "unable to alloc memory for task item.\n");
|
||||
return AVERROR(ENOMEM);
|
||||
}
|
||||
|
||||
ret = ff_dnn_fill_task(task, exec_params, tf_model, ctx->async, 1);
|
||||
if (ret != 0) {
|
||||
av_log(ctx, AV_LOG_ERROR, "Fill task with invalid parameter(s).\n");
|
||||
av_freep(&task);
|
||||
return ret;
|
||||
}
|
||||
|
||||
if (ff_queue_push_back(tf_model->task_queue, task) < 0) {
|
||||
av_freep(&task);
|
||||
av_log(ctx, AV_LOG_ERROR, "unable to push back task_queue.\n");
|
||||
return AVERROR(ENOMEM);
|
||||
}
|
||||
|
||||
ret = extract_lltask_from_task(task, tf_model->lltask_queue);
|
||||
if (ret != 0) {
|
||||
av_log(ctx, AV_LOG_ERROR, "unable to extract last level task from task.\n");
|
||||
return ret;
|
||||
}
|
||||
|
||||
request = ff_safe_queue_pop_front(tf_model->request_queue);
|
||||
if (!request) {
|
||||
av_log(ctx, AV_LOG_ERROR, "unable to get infer request.\n");
|
||||
return AVERROR(EINVAL);
|
||||
}
|
||||
return execute_model_tf(request, tf_model->lltask_queue);
|
||||
}
|
||||
|
||||
static DNNAsyncStatusType dnn_get_result_tf(const DNNModel *model, AVFrame **in, AVFrame **out)
|
||||
{
|
||||
TFModel *tf_model = (TFModel *)model;
|
||||
return ff_dnn_get_result_common(tf_model->task_queue, in, out);
|
||||
}
|
||||
|
||||
static int dnn_flush_tf(const DNNModel *model)
|
||||
{
|
||||
TFModel *tf_model = (TFModel *)model;
|
||||
DnnContext *ctx = tf_model->ctx;
|
||||
TFRequestItem *request;
|
||||
int ret;
|
||||
|
||||
if (ff_queue_size(tf_model->lltask_queue) == 0) {
|
||||
// no pending task need to flush
|
||||
return 0;
|
||||
}
|
||||
|
||||
request = ff_safe_queue_pop_front(tf_model->request_queue);
|
||||
if (!request) {
|
||||
av_log(ctx, AV_LOG_ERROR, "unable to get infer request.\n");
|
||||
return AVERROR(EINVAL);
|
||||
}
|
||||
|
||||
ret = fill_model_input_tf(tf_model, request);
|
||||
if (ret != 0) {
|
||||
av_log(ctx, AV_LOG_ERROR, "Failed to fill model input.\n");
|
||||
if (ff_safe_queue_push_back(tf_model->request_queue, request) < 0) {
|
||||
destroy_request_item(&request);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
return ff_dnn_start_inference_async(ctx, &request->exec_module);
|
||||
}
|
||||
|
||||
const DNNModule ff_dnn_backend_tf = {
|
||||
.clazz = DNN_DEFINE_CLASS(dnn_tensorflow),
|
||||
.type = DNN_TF,
|
||||
.load_model = dnn_load_model_tf,
|
||||
.execute_model = dnn_execute_model_tf,
|
||||
.get_result = dnn_get_result_tf,
|
||||
.flush = dnn_flush_tf,
|
||||
.free_model = dnn_free_model_tf,
|
||||
};
|
||||
@@ -0,0 +1,583 @@
|
||||
/*
|
||||
* Copyright (c) 2024
|
||||
*
|
||||
* This file is part of FFmpeg.
|
||||
*
|
||||
* FFmpeg is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* FFmpeg is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with FFmpeg; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file
|
||||
* DNN Torch backend implementation.
|
||||
*/
|
||||
|
||||
#include <torch/torch.h>
|
||||
#include <torch/script.h>
|
||||
|
||||
extern "C" {
|
||||
#include "dnn_io_proc.h"
|
||||
#include "dnn_backend_common.h"
|
||||
#include "libavutil/opt.h"
|
||||
#include "libavutil/mem.h"
|
||||
#include "queue.h"
|
||||
#include "safe_queue.h"
|
||||
}
|
||||
|
||||
typedef struct THModel {
|
||||
DNNModel model;
|
||||
DnnContext *ctx;
|
||||
torch::jit::Module *jit_model;
|
||||
SafeQueue *request_queue;
|
||||
Queue *task_queue;
|
||||
Queue *lltask_queue;
|
||||
} THModel;
|
||||
|
||||
typedef struct THInferRequest {
|
||||
torch::Tensor *output;
|
||||
torch::Tensor *input_tensor;
|
||||
} THInferRequest;
|
||||
|
||||
typedef struct THRequestItem {
|
||||
THInferRequest *infer_request;
|
||||
LastLevelTaskItem *lltask;
|
||||
DNNAsyncExecModule exec_module;
|
||||
} THRequestItem;
|
||||
|
||||
|
||||
#define OFFSET(x) offsetof(THOptions, x)
|
||||
#define FLAGS AV_OPT_FLAG_FILTERING_PARAM
|
||||
static const AVOption dnn_th_options[] = {
|
||||
{ "optimize", "turn on graph executor optimization", OFFSET(optimize), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS},
|
||||
{ NULL }
|
||||
};
|
||||
|
||||
static int extract_lltask_from_task(TaskItem *task, Queue *lltask_queue)
|
||||
{
|
||||
THModel *th_model = (THModel *)task->model;
|
||||
DnnContext *ctx = th_model->ctx;
|
||||
LastLevelTaskItem *lltask = (LastLevelTaskItem *)av_malloc(sizeof(*lltask));
|
||||
if (!lltask) {
|
||||
av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for LastLevelTaskItem\n");
|
||||
return AVERROR(ENOMEM);
|
||||
}
|
||||
task->inference_todo = 1;
|
||||
task->inference_done = 0;
|
||||
lltask->task = task;
|
||||
if (ff_queue_push_back(lltask_queue, lltask) < 0) {
|
||||
av_log(ctx, AV_LOG_ERROR, "Failed to push back lltask_queue.\n");
|
||||
av_freep(&lltask);
|
||||
return AVERROR(ENOMEM);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void th_free_request(THInferRequest *request)
|
||||
{
|
||||
if (!request)
|
||||
return;
|
||||
if (request->output) {
|
||||
delete(request->output);
|
||||
request->output = NULL;
|
||||
}
|
||||
if (request->input_tensor) {
|
||||
delete(request->input_tensor);
|
||||
request->input_tensor = NULL;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
static inline void destroy_request_item(THRequestItem **arg)
|
||||
{
|
||||
THRequestItem *item;
|
||||
if (!arg || !*arg) {
|
||||
return;
|
||||
}
|
||||
item = *arg;
|
||||
th_free_request(item->infer_request);
|
||||
av_freep(&item->infer_request);
|
||||
av_freep(&item->lltask);
|
||||
ff_dnn_async_module_cleanup(&item->exec_module);
|
||||
av_freep(arg);
|
||||
}
|
||||
|
||||
static void dnn_free_model_th(DNNModel **model)
|
||||
{
|
||||
THModel *th_model;
|
||||
if (!model || !*model)
|
||||
return;
|
||||
|
||||
th_model = (THModel *) (*model);
|
||||
while (ff_safe_queue_size(th_model->request_queue) != 0) {
|
||||
THRequestItem *item = (THRequestItem *)ff_safe_queue_pop_front(th_model->request_queue);
|
||||
destroy_request_item(&item);
|
||||
}
|
||||
ff_safe_queue_destroy(th_model->request_queue);
|
||||
|
||||
while (ff_queue_size(th_model->lltask_queue) != 0) {
|
||||
LastLevelTaskItem *item = (LastLevelTaskItem *)ff_queue_pop_front(th_model->lltask_queue);
|
||||
av_freep(&item);
|
||||
}
|
||||
ff_queue_destroy(th_model->lltask_queue);
|
||||
|
||||
while (ff_queue_size(th_model->task_queue) != 0) {
|
||||
TaskItem *item = (TaskItem *)ff_queue_pop_front(th_model->task_queue);
|
||||
av_frame_free(&item->in_frame);
|
||||
av_frame_free(&item->out_frame);
|
||||
av_freep(&item);
|
||||
}
|
||||
ff_queue_destroy(th_model->task_queue);
|
||||
delete th_model->jit_model;
|
||||
av_freep(&th_model);
|
||||
*model = NULL;
|
||||
}
|
||||
|
||||
static int get_input_th(DNNModel *model, DNNData *input, const char *input_name)
|
||||
{
|
||||
input->dt = DNN_FLOAT;
|
||||
input->order = DCO_RGB;
|
||||
input->layout = DL_NCHW;
|
||||
input->dims[0] = 1;
|
||||
input->dims[1] = 3;
|
||||
input->dims[2] = -1;
|
||||
input->dims[3] = -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void deleter(void *arg)
|
||||
{
|
||||
av_freep(&arg);
|
||||
}
|
||||
|
||||
static int fill_model_input_th(THModel *th_model, THRequestItem *request)
|
||||
{
|
||||
LastLevelTaskItem *lltask = NULL;
|
||||
TaskItem *task = NULL;
|
||||
THInferRequest *infer_request = NULL;
|
||||
DNNData input = { 0 };
|
||||
DnnContext *ctx = th_model->ctx;
|
||||
int ret, width_idx, height_idx, channel_idx;
|
||||
|
||||
lltask = (LastLevelTaskItem *)ff_queue_pop_front(th_model->lltask_queue);
|
||||
if (!lltask) {
|
||||
ret = AVERROR(EINVAL);
|
||||
goto err;
|
||||
}
|
||||
request->lltask = lltask;
|
||||
task = lltask->task;
|
||||
infer_request = request->infer_request;
|
||||
|
||||
ret = get_input_th(&th_model->model, &input, NULL);
|
||||
if ( ret != 0) {
|
||||
goto err;
|
||||
}
|
||||
width_idx = dnn_get_width_idx_by_layout(input.layout);
|
||||
height_idx = dnn_get_height_idx_by_layout(input.layout);
|
||||
channel_idx = dnn_get_channel_idx_by_layout(input.layout);
|
||||
input.dims[height_idx] = task->in_frame->height;
|
||||
input.dims[width_idx] = task->in_frame->width;
|
||||
input.data = av_malloc(input.dims[height_idx] * input.dims[width_idx] *
|
||||
input.dims[channel_idx] * sizeof(float));
|
||||
if (!input.data)
|
||||
return AVERROR(ENOMEM);
|
||||
infer_request->input_tensor = new torch::Tensor();
|
||||
infer_request->output = new torch::Tensor();
|
||||
|
||||
switch (th_model->model.func_type) {
|
||||
case DFT_PROCESS_FRAME:
|
||||
input.scale = 255;
|
||||
if (task->do_ioproc) {
|
||||
if (th_model->model.frame_pre_proc != NULL) {
|
||||
th_model->model.frame_pre_proc(task->in_frame, &input, th_model->model.filter_ctx);
|
||||
} else {
|
||||
ff_proc_from_frame_to_dnn(task->in_frame, &input, ctx);
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
avpriv_report_missing_feature(NULL, "model function type %d", th_model->model.func_type);
|
||||
break;
|
||||
}
|
||||
*infer_request->input_tensor = torch::from_blob(input.data,
|
||||
{1, input.dims[channel_idx], input.dims[height_idx], input.dims[width_idx]},
|
||||
deleter, torch::kFloat32);
|
||||
return 0;
|
||||
|
||||
err:
|
||||
th_free_request(infer_request);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static int th_start_inference(void *args)
|
||||
{
|
||||
THRequestItem *request = (THRequestItem *)args;
|
||||
THInferRequest *infer_request = NULL;
|
||||
LastLevelTaskItem *lltask = NULL;
|
||||
TaskItem *task = NULL;
|
||||
THModel *th_model = NULL;
|
||||
DnnContext *ctx = NULL;
|
||||
std::vector<torch::jit::IValue> inputs;
|
||||
torch::NoGradGuard no_grad;
|
||||
|
||||
if (!request) {
|
||||
av_log(NULL, AV_LOG_ERROR, "THRequestItem is NULL\n");
|
||||
return AVERROR(EINVAL);
|
||||
}
|
||||
infer_request = request->infer_request;
|
||||
lltask = request->lltask;
|
||||
task = lltask->task;
|
||||
th_model = (THModel *)task->model;
|
||||
ctx = th_model->ctx;
|
||||
|
||||
if (ctx->torch_option.optimize)
|
||||
torch::jit::setGraphExecutorOptimize(true);
|
||||
else
|
||||
torch::jit::setGraphExecutorOptimize(false);
|
||||
|
||||
if (!infer_request->input_tensor || !infer_request->output) {
|
||||
av_log(ctx, AV_LOG_ERROR, "input or output tensor is NULL\n");
|
||||
return DNN_GENERIC_ERROR;
|
||||
}
|
||||
// Transfer tensor to the same device as model
|
||||
c10::Device device = (*th_model->jit_model->parameters().begin()).device();
|
||||
if (infer_request->input_tensor->device() != device)
|
||||
*infer_request->input_tensor = infer_request->input_tensor->to(device);
|
||||
inputs.push_back(*infer_request->input_tensor);
|
||||
|
||||
*infer_request->output = th_model->jit_model->forward(inputs).toTensor();
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void infer_completion_callback(void *args) {
|
||||
THRequestItem *request = (THRequestItem*)args;
|
||||
LastLevelTaskItem *lltask = request->lltask;
|
||||
TaskItem *task = lltask->task;
|
||||
DNNData outputs = { 0 };
|
||||
THInferRequest *infer_request = request->infer_request;
|
||||
THModel *th_model = (THModel *)task->model;
|
||||
torch::Tensor *output = infer_request->output;
|
||||
|
||||
c10::IntArrayRef sizes = output->sizes();
|
||||
outputs.order = DCO_RGB;
|
||||
outputs.layout = DL_NCHW;
|
||||
outputs.dt = DNN_FLOAT;
|
||||
if (sizes.size() == 4) {
|
||||
// 4 dimensions: [batch_size, channel, height, width]
|
||||
// this format of data is normally used for video frame SR
|
||||
outputs.dims[0] = sizes.at(0); // N
|
||||
outputs.dims[1] = sizes.at(1); // C
|
||||
outputs.dims[2] = sizes.at(2); // H
|
||||
outputs.dims[3] = sizes.at(3); // W
|
||||
} else {
|
||||
avpriv_report_missing_feature(th_model->ctx, "Support of this kind of model");
|
||||
goto err;
|
||||
}
|
||||
|
||||
switch (th_model->model.func_type) {
|
||||
case DFT_PROCESS_FRAME:
|
||||
if (task->do_ioproc) {
|
||||
// Post process can only deal with CPU memory.
|
||||
if (output->device() != torch::kCPU)
|
||||
*output = output->to(torch::kCPU);
|
||||
outputs.scale = 255;
|
||||
outputs.data = output->data_ptr();
|
||||
if (th_model->model.frame_post_proc != NULL) {
|
||||
th_model->model.frame_post_proc(task->out_frame, &outputs, th_model->model.filter_ctx);
|
||||
} else {
|
||||
ff_proc_from_dnn_to_frame(task->out_frame, &outputs, th_model->ctx);
|
||||
}
|
||||
} else {
|
||||
task->out_frame->width = outputs.dims[dnn_get_width_idx_by_layout(outputs.layout)];
|
||||
task->out_frame->height = outputs.dims[dnn_get_height_idx_by_layout(outputs.layout)];
|
||||
}
|
||||
break;
|
||||
default:
|
||||
avpriv_report_missing_feature(th_model->ctx, "model function type %d", th_model->model.func_type);
|
||||
goto err;
|
||||
}
|
||||
task->inference_done++;
|
||||
av_freep(&request->lltask);
|
||||
err:
|
||||
th_free_request(infer_request);
|
||||
|
||||
if (ff_safe_queue_push_back(th_model->request_queue, request) < 0) {
|
||||
destroy_request_item(&request);
|
||||
av_log(th_model->ctx, AV_LOG_ERROR, "Unable to push back request_queue when failed to start inference.\n");
|
||||
}
|
||||
}
|
||||
|
||||
static int execute_model_th(THRequestItem *request, Queue *lltask_queue)
|
||||
{
|
||||
THModel *th_model = NULL;
|
||||
LastLevelTaskItem *lltask;
|
||||
TaskItem *task = NULL;
|
||||
int ret = 0;
|
||||
|
||||
if (ff_queue_size(lltask_queue) == 0) {
|
||||
destroy_request_item(&request);
|
||||
return 0;
|
||||
}
|
||||
|
||||
lltask = (LastLevelTaskItem *)ff_queue_peek_front(lltask_queue);
|
||||
if (lltask == NULL) {
|
||||
av_log(NULL, AV_LOG_ERROR, "Failed to get LastLevelTaskItem\n");
|
||||
ret = AVERROR(EINVAL);
|
||||
goto err;
|
||||
}
|
||||
task = lltask->task;
|
||||
th_model = (THModel *)task->model;
|
||||
|
||||
ret = fill_model_input_th(th_model, request);
|
||||
if ( ret != 0) {
|
||||
goto err;
|
||||
}
|
||||
if (task->async) {
|
||||
avpriv_report_missing_feature(th_model->ctx, "LibTorch async");
|
||||
} else {
|
||||
ret = th_start_inference((void *)(request));
|
||||
if (ret != 0) {
|
||||
goto err;
|
||||
}
|
||||
infer_completion_callback(request);
|
||||
return (task->inference_done == task->inference_todo) ? 0 : DNN_GENERIC_ERROR;
|
||||
}
|
||||
|
||||
err:
|
||||
th_free_request(request->infer_request);
|
||||
if (ff_safe_queue_push_back(th_model->request_queue, request) < 0) {
|
||||
destroy_request_item(&request);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
static int get_output_th(DNNModel *model, const char *input_name, int input_width, int input_height,
|
||||
const char *output_name, int *output_width, int *output_height)
|
||||
{
|
||||
int ret = 0;
|
||||
THModel *th_model = (THModel*) model;
|
||||
DnnContext *ctx = th_model->ctx;
|
||||
TaskItem task = { 0 };
|
||||
THRequestItem *request = NULL;
|
||||
DNNExecBaseParams exec_params = {
|
||||
.input_name = input_name,
|
||||
.output_names = &output_name,
|
||||
.nb_output = 1,
|
||||
.in_frame = NULL,
|
||||
.out_frame = NULL,
|
||||
};
|
||||
ret = ff_dnn_fill_gettingoutput_task(&task, &exec_params, th_model, input_height, input_width, ctx);
|
||||
if ( ret != 0) {
|
||||
goto err;
|
||||
}
|
||||
|
||||
ret = extract_lltask_from_task(&task, th_model->lltask_queue);
|
||||
if ( ret != 0) {
|
||||
av_log(ctx, AV_LOG_ERROR, "unable to extract last level task from task.\n");
|
||||
goto err;
|
||||
}
|
||||
|
||||
request = (THRequestItem*) ff_safe_queue_pop_front(th_model->request_queue);
|
||||
if (!request) {
|
||||
av_log(ctx, AV_LOG_ERROR, "unable to get infer request.\n");
|
||||
ret = AVERROR(EINVAL);
|
||||
goto err;
|
||||
}
|
||||
|
||||
ret = execute_model_th(request, th_model->lltask_queue);
|
||||
*output_width = task.out_frame->width;
|
||||
*output_height = task.out_frame->height;
|
||||
|
||||
err:
|
||||
av_frame_free(&task.out_frame);
|
||||
av_frame_free(&task.in_frame);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static THInferRequest *th_create_inference_request(void)
|
||||
{
|
||||
THInferRequest *request = (THInferRequest *)av_malloc(sizeof(THInferRequest));
|
||||
if (!request) {
|
||||
return NULL;
|
||||
}
|
||||
request->input_tensor = NULL;
|
||||
request->output = NULL;
|
||||
return request;
|
||||
}
|
||||
|
||||
static DNNModel *dnn_load_model_th(DnnContext *ctx, DNNFunctionType func_type, AVFilterContext *filter_ctx)
|
||||
{
|
||||
DNNModel *model = NULL;
|
||||
THModel *th_model = NULL;
|
||||
THRequestItem *item = NULL;
|
||||
const char *device_name = ctx->device ? ctx->device : "cpu";
|
||||
|
||||
th_model = (THModel *)av_mallocz(sizeof(THModel));
|
||||
if (!th_model)
|
||||
return NULL;
|
||||
model = &th_model->model;
|
||||
th_model->ctx = ctx;
|
||||
|
||||
c10::Device device = c10::Device(device_name);
|
||||
if (device.is_xpu()) {
|
||||
if (!at::hasXPU()) {
|
||||
av_log(ctx, AV_LOG_ERROR, "No XPU device found\n");
|
||||
goto fail;
|
||||
}
|
||||
at::detail::getXPUHooks().initXPU();
|
||||
} else if (!device.is_cpu()) {
|
||||
av_log(ctx, AV_LOG_ERROR, "Not supported device:\"%s\"\n", device_name);
|
||||
goto fail;
|
||||
}
|
||||
|
||||
try {
|
||||
th_model->jit_model = new torch::jit::Module;
|
||||
(*th_model->jit_model) = torch::jit::load(ctx->model_filename);
|
||||
th_model->jit_model->to(device);
|
||||
} catch (const c10::Error& e) {
|
||||
av_log(ctx, AV_LOG_ERROR, "Failed to load torch model\n");
|
||||
goto fail;
|
||||
}
|
||||
|
||||
th_model->request_queue = ff_safe_queue_create();
|
||||
if (!th_model->request_queue) {
|
||||
goto fail;
|
||||
}
|
||||
|
||||
item = (THRequestItem *)av_mallocz(sizeof(THRequestItem));
|
||||
if (!item) {
|
||||
goto fail;
|
||||
}
|
||||
item->lltask = NULL;
|
||||
item->infer_request = th_create_inference_request();
|
||||
if (!item->infer_request) {
|
||||
av_log(NULL, AV_LOG_ERROR, "Failed to allocate memory for Torch inference request\n");
|
||||
goto fail;
|
||||
}
|
||||
item->exec_module.start_inference = &th_start_inference;
|
||||
item->exec_module.callback = &infer_completion_callback;
|
||||
item->exec_module.args = item;
|
||||
|
||||
if (ff_safe_queue_push_back(th_model->request_queue, item) < 0) {
|
||||
goto fail;
|
||||
}
|
||||
item = NULL;
|
||||
|
||||
th_model->task_queue = ff_queue_create();
|
||||
if (!th_model->task_queue) {
|
||||
goto fail;
|
||||
}
|
||||
|
||||
th_model->lltask_queue = ff_queue_create();
|
||||
if (!th_model->lltask_queue) {
|
||||
goto fail;
|
||||
}
|
||||
|
||||
model->get_input = &get_input_th;
|
||||
model->get_output = &get_output_th;
|
||||
model->filter_ctx = filter_ctx;
|
||||
model->func_type = func_type;
|
||||
return model;
|
||||
|
||||
fail:
|
||||
if (item) {
|
||||
destroy_request_item(&item);
|
||||
av_freep(&item);
|
||||
}
|
||||
dnn_free_model_th(&model);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static int dnn_execute_model_th(const DNNModel *model, DNNExecBaseParams *exec_params)
|
||||
{
|
||||
THModel *th_model = (THModel *)model;
|
||||
DnnContext *ctx = th_model->ctx;
|
||||
TaskItem *task;
|
||||
THRequestItem *request;
|
||||
int ret = 0;
|
||||
|
||||
ret = ff_check_exec_params(ctx, DNN_TH, model->func_type, exec_params);
|
||||
if (ret != 0) {
|
||||
av_log(ctx, AV_LOG_ERROR, "exec parameter checking fail.\n");
|
||||
return ret;
|
||||
}
|
||||
|
||||
task = (TaskItem *)av_malloc(sizeof(TaskItem));
|
||||
if (!task) {
|
||||
av_log(ctx, AV_LOG_ERROR, "unable to alloc memory for task item.\n");
|
||||
return AVERROR(ENOMEM);
|
||||
}
|
||||
|
||||
ret = ff_dnn_fill_task(task, exec_params, th_model, 0, 1);
|
||||
if (ret != 0) {
|
||||
av_freep(&task);
|
||||
av_log(ctx, AV_LOG_ERROR, "unable to fill task.\n");
|
||||
return ret;
|
||||
}
|
||||
|
||||
ret = ff_queue_push_back(th_model->task_queue, task);
|
||||
if (ret < 0) {
|
||||
av_freep(&task);
|
||||
av_log(ctx, AV_LOG_ERROR, "unable to push back task_queue.\n");
|
||||
return ret;
|
||||
}
|
||||
|
||||
ret = extract_lltask_from_task(task, th_model->lltask_queue);
|
||||
if (ret != 0) {
|
||||
av_log(ctx, AV_LOG_ERROR, "unable to extract last level task from task.\n");
|
||||
return ret;
|
||||
}
|
||||
|
||||
request = (THRequestItem *)ff_safe_queue_pop_front(th_model->request_queue);
|
||||
if (!request) {
|
||||
av_log(ctx, AV_LOG_ERROR, "unable to get infer request.\n");
|
||||
return AVERROR(EINVAL);
|
||||
}
|
||||
|
||||
return execute_model_th(request, th_model->lltask_queue);
|
||||
}
|
||||
|
||||
static DNNAsyncStatusType dnn_get_result_th(const DNNModel *model, AVFrame **in, AVFrame **out)
|
||||
{
|
||||
THModel *th_model = (THModel *)model;
|
||||
return ff_dnn_get_result_common(th_model->task_queue, in, out);
|
||||
}
|
||||
|
||||
static int dnn_flush_th(const DNNModel *model)
|
||||
{
|
||||
THModel *th_model = (THModel *)model;
|
||||
THRequestItem *request;
|
||||
|
||||
if (ff_queue_size(th_model->lltask_queue) == 0)
|
||||
// no pending task need to flush
|
||||
return 0;
|
||||
|
||||
request = (THRequestItem *)ff_safe_queue_pop_front(th_model->request_queue);
|
||||
if (!request) {
|
||||
av_log(th_model->ctx, AV_LOG_ERROR, "unable to get infer request.\n");
|
||||
return AVERROR(EINVAL);
|
||||
}
|
||||
|
||||
return execute_model_th(request, th_model->lltask_queue);
|
||||
}
|
||||
|
||||
extern const DNNModule ff_dnn_backend_torch = {
|
||||
.clazz = DNN_DEFINE_CLASS(dnn_th),
|
||||
.type = DNN_TH,
|
||||
.load_model = dnn_load_model_th,
|
||||
.execute_model = dnn_execute_model_th,
|
||||
.get_result = dnn_get_result_th,
|
||||
.flush = dnn_flush_th,
|
||||
.free_model = dnn_free_model_th,
|
||||
};
|
||||
@@ -0,0 +1,139 @@
|
||||
/*
|
||||
* Copyright (c) 2018 Sergey Lavrushkin
|
||||
*
|
||||
* This file is part of FFmpeg.
|
||||
*
|
||||
* FFmpeg is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* FFmpeg is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with FFmpeg; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Implements DNN module initialization with specified backend.
|
||||
*/
|
||||
|
||||
#include "../dnn_interface.h"
|
||||
#include "libavutil/avassert.h"
|
||||
#include "libavutil/mem.h"
|
||||
#include "libavutil/opt.h"
|
||||
|
||||
#include "libavfilter/filters.h"
|
||||
|
||||
extern const DNNModule ff_dnn_backend_openvino;
|
||||
extern const DNNModule ff_dnn_backend_tf;
|
||||
extern const DNNModule ff_dnn_backend_torch;
|
||||
|
||||
#define OFFSET(x) offsetof(DnnContext, x)
|
||||
#define FLAGS AV_OPT_FLAG_FILTERING_PARAM
|
||||
static const AVOption dnn_base_options[] = {
|
||||
{"model", "path to model file",
|
||||
OFFSET(model_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS},
|
||||
{"input", "input name of the model",
|
||||
OFFSET(model_inputname), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS},
|
||||
{"output", "output name of the model",
|
||||
OFFSET(model_outputnames_string), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS},
|
||||
{"backend_configs", "backend configs (deprecated)",
|
||||
OFFSET(backend_options), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS | AV_OPT_FLAG_DEPRECATED},
|
||||
{"options", "backend configs (deprecated)",
|
||||
OFFSET(backend_options), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS | AV_OPT_FLAG_DEPRECATED},
|
||||
{"nireq", "number of request",
|
||||
OFFSET(nireq), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, FLAGS},
|
||||
{"async", "use DNN async inference",
|
||||
OFFSET(async), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, FLAGS},
|
||||
{"device", "device to run model",
|
||||
OFFSET(device), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS},
|
||||
{NULL}
|
||||
};
|
||||
|
||||
AVFILTER_DEFINE_CLASS(dnn_base);
|
||||
|
||||
typedef struct DnnBackendInfo {
|
||||
const size_t offset;
|
||||
union {
|
||||
const AVClass *class;
|
||||
const DNNModule *module;
|
||||
};
|
||||
} DnnBackendInfo;
|
||||
|
||||
static const DnnBackendInfo dnn_backend_info_list[] = {
|
||||
{0, .class = &dnn_base_class},
|
||||
// Must keep the same order as in DNNOptions, so offset value in incremental order
|
||||
#if CONFIG_LIBTENSORFLOW
|
||||
{offsetof(DnnContext, tf_option), .module = &ff_dnn_backend_tf},
|
||||
#endif
|
||||
#if CONFIG_LIBOPENVINO
|
||||
{offsetof(DnnContext, ov_option), .module = &ff_dnn_backend_openvino},
|
||||
#endif
|
||||
#if CONFIG_LIBTORCH
|
||||
{offsetof(DnnContext, torch_option), .module = &ff_dnn_backend_torch},
|
||||
#endif
|
||||
};
|
||||
|
||||
const DNNModule *ff_get_dnn_module(DNNBackendType backend_type, void *log_ctx)
|
||||
{
|
||||
for (int i = 1; i < FF_ARRAY_ELEMS(dnn_backend_info_list); i++) {
|
||||
if (dnn_backend_info_list[i].module->type == backend_type)
|
||||
return dnn_backend_info_list[i].module;
|
||||
}
|
||||
|
||||
av_log(log_ctx, AV_LOG_ERROR,
|
||||
"Module backend_type %d is not supported or enabled.\n",
|
||||
backend_type);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void ff_dnn_init_child_class(DnnContext *ctx)
|
||||
{
|
||||
for (int i = 0; i < FF_ARRAY_ELEMS(dnn_backend_info_list); i++) {
|
||||
const AVClass **ptr = (const AVClass **) ((char *) ctx + dnn_backend_info_list[i].offset);
|
||||
*ptr = dnn_backend_info_list[i].class;
|
||||
}
|
||||
}
|
||||
|
||||
void *ff_dnn_child_next(DnnContext *obj, void *prev) {
|
||||
size_t pre_offset;
|
||||
|
||||
if (!prev) {
|
||||
av_assert0(obj->clazz);
|
||||
return obj;
|
||||
}
|
||||
|
||||
pre_offset = (char *)prev - (char *)obj;
|
||||
for (int i = 0; i < FF_ARRAY_ELEMS(dnn_backend_info_list) - 1; i++) {
|
||||
if (dnn_backend_info_list[i].offset == pre_offset) {
|
||||
const AVClass **ptr = (const AVClass **) ((char *) obj + dnn_backend_info_list[i + 1].offset);
|
||||
av_assert0(*ptr);
|
||||
return ptr;
|
||||
}
|
||||
}
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
const AVClass *ff_dnn_child_class_iterate_with_mask(void **iter, uint32_t backend_mask)
|
||||
{
|
||||
for (uintptr_t i = (uintptr_t)*iter; i < FF_ARRAY_ELEMS(dnn_backend_info_list); i++) {
|
||||
if (i > 0) {
|
||||
const DNNModule *module = dnn_backend_info_list[i].module;
|
||||
|
||||
if (!(module->type & backend_mask))
|
||||
continue;
|
||||
}
|
||||
|
||||
*iter = (void *)(i + 1);
|
||||
return dnn_backend_info_list[i].class;
|
||||
}
|
||||
|
||||
return NULL;
|
||||
}
|
||||
@@ -0,0 +1,471 @@
|
||||
/*
|
||||
* Copyright (c) 2020
|
||||
*
|
||||
* This file is part of FFmpeg.
|
||||
*
|
||||
* FFmpeg is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* FFmpeg is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with FFmpeg; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
#include "dnn_io_proc.h"
|
||||
#include "libavutil/imgutils.h"
|
||||
#include "libavutil/mem.h"
|
||||
#include "libswscale/swscale.h"
|
||||
#include "libavutil/avassert.h"
|
||||
#include "libavutil/detection_bbox.h"
|
||||
|
||||
static int get_datatype_size(DNNDataType dt)
|
||||
{
|
||||
switch (dt)
|
||||
{
|
||||
case DNN_FLOAT:
|
||||
return sizeof(float);
|
||||
case DNN_UINT8:
|
||||
return sizeof(uint8_t);
|
||||
default:
|
||||
av_assert0(!"not supported yet.");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
int ff_proc_from_dnn_to_frame(AVFrame *frame, DNNData *output, void *log_ctx)
|
||||
{
|
||||
struct SwsContext *sws_ctx;
|
||||
int ret = 0;
|
||||
int linesize[4] = { 0 };
|
||||
void **dst_data = NULL;
|
||||
void *middle_data = NULL;
|
||||
uint8_t *planar_data[4] = { 0 };
|
||||
int plane_size = frame->width * frame->height * sizeof(uint8_t);
|
||||
enum AVPixelFormat src_fmt = AV_PIX_FMT_NONE;
|
||||
int src_datatype_size = get_datatype_size(output->dt);
|
||||
|
||||
int bytewidth = av_image_get_linesize(frame->format, frame->width, 0);
|
||||
if (bytewidth < 0) {
|
||||
return AVERROR(EINVAL);
|
||||
}
|
||||
/* scale == 1 and mean == 0 and dt == UINT8: passthrough */
|
||||
if (fabsf(output->scale - 1) < 1e-6f && fabsf(output->mean) < 1e-6 && output->dt == DNN_UINT8)
|
||||
src_fmt = AV_PIX_FMT_GRAY8;
|
||||
/* (scale == 255 or scale == 0) and mean == 0 and dt == FLOAT: normalization */
|
||||
else if ((fabsf(output->scale - 255) < 1e-6f || fabsf(output->scale) < 1e-6f) &&
|
||||
fabsf(output->mean) < 1e-6 && output->dt == DNN_FLOAT)
|
||||
src_fmt = AV_PIX_FMT_GRAYF32;
|
||||
else {
|
||||
av_log(log_ctx, AV_LOG_ERROR, "dnn_process output data doesn't type: UINT8 "
|
||||
"scale: %f, mean: %f\n", output->scale, output->mean);
|
||||
return AVERROR(ENOSYS);
|
||||
}
|
||||
|
||||
dst_data = (void **)frame->data;
|
||||
linesize[0] = frame->linesize[0];
|
||||
if (output->layout == DL_NCHW) {
|
||||
middle_data = av_malloc(plane_size * output->dims[1]);
|
||||
if (!middle_data) {
|
||||
ret = AVERROR(ENOMEM);
|
||||
goto err;
|
||||
}
|
||||
dst_data = &middle_data;
|
||||
linesize[0] = frame->width * 3;
|
||||
}
|
||||
|
||||
switch (frame->format) {
|
||||
case AV_PIX_FMT_RGB24:
|
||||
case AV_PIX_FMT_BGR24:
|
||||
sws_ctx = sws_getContext(frame->width * 3,
|
||||
frame->height,
|
||||
src_fmt,
|
||||
frame->width * 3,
|
||||
frame->height,
|
||||
AV_PIX_FMT_GRAY8,
|
||||
0, NULL, NULL, NULL);
|
||||
if (!sws_ctx) {
|
||||
av_log(log_ctx, AV_LOG_ERROR, "Impossible to create scale context for the conversion "
|
||||
"fmt:%s s:%dx%d -> fmt:%s s:%dx%d\n",
|
||||
av_get_pix_fmt_name(src_fmt), frame->width * 3, frame->height,
|
||||
av_get_pix_fmt_name(AV_PIX_FMT_GRAY8), frame->width * 3, frame->height);
|
||||
ret = AVERROR(EINVAL);
|
||||
goto err;
|
||||
}
|
||||
sws_scale(sws_ctx, (const uint8_t *[4]){(const uint8_t *)output->data, 0, 0, 0},
|
||||
(const int[4]){frame->width * 3 * src_datatype_size, 0, 0, 0}, 0, frame->height,
|
||||
(uint8_t * const*)dst_data, linesize);
|
||||
sws_freeContext(sws_ctx);
|
||||
// convert data from planar to packed
|
||||
if (output->layout == DL_NCHW) {
|
||||
sws_ctx = sws_getContext(frame->width,
|
||||
frame->height,
|
||||
AV_PIX_FMT_GBRP,
|
||||
frame->width,
|
||||
frame->height,
|
||||
frame->format,
|
||||
0, NULL, NULL, NULL);
|
||||
if (!sws_ctx) {
|
||||
av_log(log_ctx, AV_LOG_ERROR, "Impossible to create scale context for the conversion "
|
||||
"fmt:%s s:%dx%d -> fmt:%s s:%dx%d\n",
|
||||
av_get_pix_fmt_name(AV_PIX_FMT_GBRP), frame->width, frame->height,
|
||||
av_get_pix_fmt_name(frame->format),frame->width, frame->height);
|
||||
ret = AVERROR(EINVAL);
|
||||
goto err;
|
||||
}
|
||||
if (frame->format == AV_PIX_FMT_RGB24) {
|
||||
planar_data[0] = (uint8_t *)middle_data + plane_size;
|
||||
planar_data[1] = (uint8_t *)middle_data + plane_size * 2;
|
||||
planar_data[2] = (uint8_t *)middle_data;
|
||||
} else if (frame->format == AV_PIX_FMT_BGR24) {
|
||||
planar_data[0] = (uint8_t *)middle_data + plane_size;
|
||||
planar_data[1] = (uint8_t *)middle_data;
|
||||
planar_data[2] = (uint8_t *)middle_data + plane_size * 2;
|
||||
}
|
||||
sws_scale(sws_ctx, (const uint8_t * const *)planar_data,
|
||||
(const int [4]){frame->width * sizeof(uint8_t),
|
||||
frame->width * sizeof(uint8_t),
|
||||
frame->width * sizeof(uint8_t), 0},
|
||||
0, frame->height, frame->data, frame->linesize);
|
||||
sws_freeContext(sws_ctx);
|
||||
}
|
||||
break;
|
||||
case AV_PIX_FMT_GRAYF32:
|
||||
av_image_copy_plane(frame->data[0], frame->linesize[0],
|
||||
output->data, bytewidth,
|
||||
bytewidth, frame->height);
|
||||
break;
|
||||
case AV_PIX_FMT_YUV420P:
|
||||
case AV_PIX_FMT_YUV422P:
|
||||
case AV_PIX_FMT_YUV444P:
|
||||
case AV_PIX_FMT_YUV410P:
|
||||
case AV_PIX_FMT_YUV411P:
|
||||
case AV_PIX_FMT_GRAY8:
|
||||
case AV_PIX_FMT_NV12:
|
||||
sws_ctx = sws_getContext(frame->width,
|
||||
frame->height,
|
||||
AV_PIX_FMT_GRAYF32,
|
||||
frame->width,
|
||||
frame->height,
|
||||
AV_PIX_FMT_GRAY8,
|
||||
0, NULL, NULL, NULL);
|
||||
if (!sws_ctx) {
|
||||
av_log(log_ctx, AV_LOG_ERROR, "Impossible to create scale context for the conversion "
|
||||
"fmt:%s s:%dx%d -> fmt:%s s:%dx%d\n",
|
||||
av_get_pix_fmt_name(src_fmt), frame->width, frame->height,
|
||||
av_get_pix_fmt_name(AV_PIX_FMT_GRAY8), frame->width, frame->height);
|
||||
ret = AVERROR(EINVAL);
|
||||
goto err;
|
||||
}
|
||||
sws_scale(sws_ctx, (const uint8_t *[4]){(const uint8_t *)output->data, 0, 0, 0},
|
||||
(const int[4]){frame->width * src_datatype_size, 0, 0, 0}, 0, frame->height,
|
||||
(uint8_t * const*)frame->data, frame->linesize);
|
||||
sws_freeContext(sws_ctx);
|
||||
break;
|
||||
default:
|
||||
avpriv_report_missing_feature(log_ctx, "%s", av_get_pix_fmt_name(frame->format));
|
||||
ret = AVERROR(ENOSYS);
|
||||
goto err;
|
||||
}
|
||||
|
||||
err:
|
||||
av_free(middle_data);
|
||||
return ret;
|
||||
}
|
||||
|
||||
int ff_proc_from_frame_to_dnn(AVFrame *frame, DNNData *input, void *log_ctx)
|
||||
{
|
||||
struct SwsContext *sws_ctx;
|
||||
int ret = 0;
|
||||
int linesize[4] = { 0 };
|
||||
void **src_data = NULL;
|
||||
void *middle_data = NULL;
|
||||
uint8_t *planar_data[4] = { 0 };
|
||||
int plane_size = frame->width * frame->height * sizeof(uint8_t);
|
||||
enum AVPixelFormat dst_fmt = AV_PIX_FMT_NONE;
|
||||
int dst_datatype_size = get_datatype_size(input->dt);
|
||||
int bytewidth = av_image_get_linesize(frame->format, frame->width, 0);
|
||||
if (bytewidth < 0) {
|
||||
return AVERROR(EINVAL);
|
||||
}
|
||||
/* scale == 1 and mean == 0 and dt == UINT8: passthrough */
|
||||
if (fabsf(input->scale - 1) < 1e-6f && fabsf(input->mean) < 1e-6 && input->dt == DNN_UINT8)
|
||||
dst_fmt = AV_PIX_FMT_GRAY8;
|
||||
/* (scale == 255 or scale == 0) and mean == 0 and dt == FLOAT: normalization */
|
||||
else if ((fabsf(input->scale - 255) < 1e-6f || fabsf(input->scale) < 1e-6f) &&
|
||||
fabsf(input->mean) < 1e-6 && input->dt == DNN_FLOAT)
|
||||
dst_fmt = AV_PIX_FMT_GRAYF32;
|
||||
else {
|
||||
av_log(log_ctx, AV_LOG_ERROR, "dnn_process input data doesn't support type: UINT8 "
|
||||
"scale: %f, mean: %f\n", input->scale, input->mean);
|
||||
return AVERROR(ENOSYS);
|
||||
}
|
||||
|
||||
src_data = (void **)frame->data;
|
||||
linesize[0] = frame->linesize[0];
|
||||
if (input->layout == DL_NCHW) {
|
||||
middle_data = av_malloc(plane_size * input->dims[1]);
|
||||
if (!middle_data) {
|
||||
ret = AVERROR(ENOMEM);
|
||||
goto err;
|
||||
}
|
||||
src_data = &middle_data;
|
||||
linesize[0] = frame->width * 3;
|
||||
}
|
||||
|
||||
switch (frame->format) {
|
||||
case AV_PIX_FMT_RGB24:
|
||||
case AV_PIX_FMT_BGR24:
|
||||
// convert data from planar to packed
|
||||
if (input->layout == DL_NCHW) {
|
||||
sws_ctx = sws_getContext(frame->width,
|
||||
frame->height,
|
||||
frame->format,
|
||||
frame->width,
|
||||
frame->height,
|
||||
AV_PIX_FMT_GBRP,
|
||||
0, NULL, NULL, NULL);
|
||||
if (!sws_ctx) {
|
||||
av_log(log_ctx, AV_LOG_ERROR, "Impossible to create scale context for the conversion "
|
||||
"fmt:%s s:%dx%d -> fmt:%s s:%dx%d\n",
|
||||
av_get_pix_fmt_name(frame->format), frame->width, frame->height,
|
||||
av_get_pix_fmt_name(AV_PIX_FMT_GBRP),frame->width, frame->height);
|
||||
ret = AVERROR(EINVAL);
|
||||
goto err;
|
||||
}
|
||||
if (frame->format == AV_PIX_FMT_RGB24) {
|
||||
planar_data[0] = (uint8_t *)middle_data + plane_size;
|
||||
planar_data[1] = (uint8_t *)middle_data + plane_size * 2;
|
||||
planar_data[2] = (uint8_t *)middle_data;
|
||||
} else if (frame->format == AV_PIX_FMT_BGR24) {
|
||||
planar_data[0] = (uint8_t *)middle_data + plane_size;
|
||||
planar_data[1] = (uint8_t *)middle_data;
|
||||
planar_data[2] = (uint8_t *)middle_data + plane_size * 2;
|
||||
}
|
||||
sws_scale(sws_ctx, (const uint8_t * const *)frame->data,
|
||||
frame->linesize, 0, frame->height, planar_data,
|
||||
(const int [4]){frame->width * sizeof(uint8_t),
|
||||
frame->width * sizeof(uint8_t),
|
||||
frame->width * sizeof(uint8_t), 0});
|
||||
sws_freeContext(sws_ctx);
|
||||
}
|
||||
sws_ctx = sws_getContext(frame->width * 3,
|
||||
frame->height,
|
||||
AV_PIX_FMT_GRAY8,
|
||||
frame->width * 3,
|
||||
frame->height,
|
||||
dst_fmt,
|
||||
0, NULL, NULL, NULL);
|
||||
if (!sws_ctx) {
|
||||
av_log(log_ctx, AV_LOG_ERROR, "Impossible to create scale context for the conversion "
|
||||
"fmt:%s s:%dx%d -> fmt:%s s:%dx%d\n",
|
||||
av_get_pix_fmt_name(AV_PIX_FMT_GRAY8), frame->width * 3, frame->height,
|
||||
av_get_pix_fmt_name(dst_fmt),frame->width * 3, frame->height);
|
||||
ret = AVERROR(EINVAL);
|
||||
goto err;
|
||||
}
|
||||
sws_scale(sws_ctx, (const uint8_t **)src_data,
|
||||
linesize, 0, frame->height,
|
||||
(uint8_t * const [4]){input->data, 0, 0, 0},
|
||||
(const int [4]){frame->width * 3 * dst_datatype_size, 0, 0, 0});
|
||||
sws_freeContext(sws_ctx);
|
||||
break;
|
||||
case AV_PIX_FMT_GRAYF32:
|
||||
av_image_copy_plane(input->data, bytewidth,
|
||||
frame->data[0], frame->linesize[0],
|
||||
bytewidth, frame->height);
|
||||
break;
|
||||
case AV_PIX_FMT_YUV420P:
|
||||
case AV_PIX_FMT_YUV422P:
|
||||
case AV_PIX_FMT_YUV444P:
|
||||
case AV_PIX_FMT_YUV410P:
|
||||
case AV_PIX_FMT_YUV411P:
|
||||
case AV_PIX_FMT_GRAY8:
|
||||
case AV_PIX_FMT_NV12:
|
||||
sws_ctx = sws_getContext(frame->width,
|
||||
frame->height,
|
||||
AV_PIX_FMT_GRAY8,
|
||||
frame->width,
|
||||
frame->height,
|
||||
dst_fmt,
|
||||
0, NULL, NULL, NULL);
|
||||
if (!sws_ctx) {
|
||||
av_log(log_ctx, AV_LOG_ERROR, "Impossible to create scale context for the conversion "
|
||||
"fmt:%s s:%dx%d -> fmt:%s s:%dx%d\n",
|
||||
av_get_pix_fmt_name(AV_PIX_FMT_GRAY8), frame->width, frame->height,
|
||||
av_get_pix_fmt_name(dst_fmt),frame->width, frame->height);
|
||||
ret = AVERROR(EINVAL);
|
||||
goto err;
|
||||
}
|
||||
sws_scale(sws_ctx, (const uint8_t **)frame->data,
|
||||
frame->linesize, 0, frame->height,
|
||||
(uint8_t * const [4]){input->data, 0, 0, 0},
|
||||
(const int [4]){frame->width * dst_datatype_size, 0, 0, 0});
|
||||
sws_freeContext(sws_ctx);
|
||||
break;
|
||||
default:
|
||||
avpriv_report_missing_feature(log_ctx, "%s", av_get_pix_fmt_name(frame->format));
|
||||
ret = AVERROR(ENOSYS);
|
||||
goto err;
|
||||
}
|
||||
err:
|
||||
av_free(middle_data);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static enum AVPixelFormat get_pixel_format(DNNData *data)
|
||||
{
|
||||
if (data->dt == DNN_UINT8) {
|
||||
switch (data->order) {
|
||||
case DCO_BGR:
|
||||
return AV_PIX_FMT_BGR24;
|
||||
case DCO_RGB:
|
||||
return AV_PIX_FMT_RGB24;
|
||||
default:
|
||||
av_assert0(!"unsupported data pixel format.\n");
|
||||
return AV_PIX_FMT_BGR24;
|
||||
}
|
||||
}
|
||||
|
||||
av_assert0(!"unsupported data type.\n");
|
||||
return AV_PIX_FMT_BGR24;
|
||||
}
|
||||
|
||||
int ff_frame_to_dnn_classify(AVFrame *frame, DNNData *input, uint32_t bbox_index, void *log_ctx)
|
||||
{
|
||||
const AVPixFmtDescriptor *desc;
|
||||
int offsetx[4], offsety[4];
|
||||
uint8_t *bbox_data[4];
|
||||
struct SwsContext *sws_ctx;
|
||||
int linesizes[4];
|
||||
int ret = 0;
|
||||
enum AVPixelFormat fmt;
|
||||
int left, top, width, height;
|
||||
int width_idx, height_idx;
|
||||
const AVDetectionBBoxHeader *header;
|
||||
const AVDetectionBBox *bbox;
|
||||
AVFrameSideData *sd = av_frame_get_side_data(frame, AV_FRAME_DATA_DETECTION_BBOXES);
|
||||
int max_step[4] = { 0 };
|
||||
av_assert0(sd);
|
||||
|
||||
/* (scale != 1 and scale != 0) or mean != 0 */
|
||||
if ((fabsf(input->scale - 1) > 1e-6f && fabsf(input->scale) > 1e-6f) ||
|
||||
fabsf(input->mean) > 1e-6f) {
|
||||
av_log(log_ctx, AV_LOG_ERROR, "dnn_classify input data doesn't support "
|
||||
"scale: %f, mean: %f\n", input->scale, input->mean);
|
||||
return AVERROR(ENOSYS);
|
||||
}
|
||||
|
||||
if (input->layout == DL_NCHW) {
|
||||
av_log(log_ctx, AV_LOG_ERROR, "dnn_classify input data doesn't support layout: NCHW\n");
|
||||
return AVERROR(ENOSYS);
|
||||
}
|
||||
|
||||
width_idx = dnn_get_width_idx_by_layout(input->layout);
|
||||
height_idx = dnn_get_height_idx_by_layout(input->layout);
|
||||
|
||||
header = (const AVDetectionBBoxHeader *)sd->data;
|
||||
bbox = av_get_detection_bbox(header, bbox_index);
|
||||
|
||||
left = bbox->x;
|
||||
width = bbox->w;
|
||||
top = bbox->y;
|
||||
height = bbox->h;
|
||||
|
||||
fmt = get_pixel_format(input);
|
||||
sws_ctx = sws_getContext(width, height, frame->format,
|
||||
input->dims[width_idx],
|
||||
input->dims[height_idx], fmt,
|
||||
SWS_FAST_BILINEAR, NULL, NULL, NULL);
|
||||
if (!sws_ctx) {
|
||||
av_log(log_ctx, AV_LOG_ERROR, "Failed to create scale context for the conversion "
|
||||
"fmt:%s s:%dx%d -> fmt:%s s:%dx%d\n",
|
||||
av_get_pix_fmt_name(frame->format), width, height,
|
||||
av_get_pix_fmt_name(fmt),
|
||||
input->dims[width_idx],
|
||||
input->dims[height_idx]);
|
||||
return AVERROR(EINVAL);
|
||||
}
|
||||
|
||||
ret = av_image_fill_linesizes(linesizes, fmt, input->dims[width_idx]);
|
||||
if (ret < 0) {
|
||||
av_log(log_ctx, AV_LOG_ERROR, "unable to get linesizes with av_image_fill_linesizes");
|
||||
sws_freeContext(sws_ctx);
|
||||
return ret;
|
||||
}
|
||||
|
||||
desc = av_pix_fmt_desc_get(frame->format);
|
||||
offsetx[1] = offsetx[2] = AV_CEIL_RSHIFT(left, desc->log2_chroma_w);
|
||||
offsetx[0] = offsetx[3] = left;
|
||||
|
||||
offsety[1] = offsety[2] = AV_CEIL_RSHIFT(top, desc->log2_chroma_h);
|
||||
offsety[0] = offsety[3] = top;
|
||||
|
||||
av_image_fill_max_pixsteps(max_step, NULL, desc);
|
||||
for (int k = 0; frame->data[k]; k++)
|
||||
bbox_data[k] = frame->data[k] + offsety[k] * frame->linesize[k] + offsetx[k] * max_step[k];
|
||||
|
||||
sws_scale(sws_ctx, (const uint8_t *const *)&bbox_data, frame->linesize,
|
||||
0, height,
|
||||
(uint8_t *const [4]){input->data, 0, 0, 0}, linesizes);
|
||||
|
||||
sws_freeContext(sws_ctx);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
int ff_frame_to_dnn_detect(AVFrame *frame, DNNData *input, void *log_ctx)
|
||||
{
|
||||
struct SwsContext *sws_ctx;
|
||||
int linesizes[4];
|
||||
int ret = 0, width_idx, height_idx;
|
||||
enum AVPixelFormat fmt = get_pixel_format(input);
|
||||
|
||||
/* (scale != 1 and scale != 0) or mean != 0 */
|
||||
if ((fabsf(input->scale - 1) > 1e-6f && fabsf(input->scale) > 1e-6f) ||
|
||||
fabsf(input->mean) > 1e-6f) {
|
||||
av_log(log_ctx, AV_LOG_ERROR, "dnn_detect input data doesn't support "
|
||||
"scale: %f, mean: %f\n", input->scale, input->mean);
|
||||
return AVERROR(ENOSYS);
|
||||
}
|
||||
|
||||
if (input->layout == DL_NCHW) {
|
||||
av_log(log_ctx, AV_LOG_ERROR, "dnn_detect input data doesn't support layout: NCHW\n");
|
||||
return AVERROR(ENOSYS);
|
||||
}
|
||||
|
||||
width_idx = dnn_get_width_idx_by_layout(input->layout);
|
||||
height_idx = dnn_get_height_idx_by_layout(input->layout);
|
||||
|
||||
sws_ctx = sws_getContext(frame->width, frame->height, frame->format,
|
||||
input->dims[width_idx],
|
||||
input->dims[height_idx], fmt,
|
||||
SWS_FAST_BILINEAR, NULL, NULL, NULL);
|
||||
if (!sws_ctx) {
|
||||
av_log(log_ctx, AV_LOG_ERROR, "Impossible to create scale context for the conversion "
|
||||
"fmt:%s s:%dx%d -> fmt:%s s:%dx%d\n",
|
||||
av_get_pix_fmt_name(frame->format), frame->width, frame->height,
|
||||
av_get_pix_fmt_name(fmt), input->dims[width_idx],
|
||||
input->dims[height_idx]);
|
||||
return AVERROR(EINVAL);
|
||||
}
|
||||
|
||||
ret = av_image_fill_linesizes(linesizes, fmt, input->dims[width_idx]);
|
||||
if (ret < 0) {
|
||||
av_log(log_ctx, AV_LOG_ERROR, "unable to get linesizes with av_image_fill_linesizes");
|
||||
sws_freeContext(sws_ctx);
|
||||
return ret;
|
||||
}
|
||||
|
||||
sws_scale(sws_ctx, (const uint8_t *const *)frame->data, frame->linesize, 0, frame->height,
|
||||
(uint8_t *const [4]){input->data, 0, 0, 0}, linesizes);
|
||||
|
||||
sws_freeContext(sws_ctx);
|
||||
return ret;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright (c) 2020
|
||||
*
|
||||
* This file is part of FFmpeg.
|
||||
*
|
||||
* FFmpeg is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* FFmpeg is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with FFmpeg; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file
|
||||
* DNN input&output process between AVFrame and DNNData.
|
||||
*/
|
||||
|
||||
|
||||
#ifndef AVFILTER_DNN_DNN_IO_PROC_H
|
||||
#define AVFILTER_DNN_DNN_IO_PROC_H
|
||||
|
||||
#include "../dnn_interface.h"
|
||||
#include "libavutil/frame.h"
|
||||
|
||||
int ff_proc_from_frame_to_dnn(AVFrame *frame, DNNData *input, void *log_ctx);
|
||||
int ff_proc_from_dnn_to_frame(AVFrame *frame, DNNData *output, void *log_ctx);
|
||||
int ff_frame_to_dnn_detect(AVFrame *frame, DNNData *input, void *log_ctx);
|
||||
int ff_frame_to_dnn_classify(AVFrame *frame, DNNData *input, uint32_t bbox_index, void *log_ctx);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,191 @@
|
||||
/*
|
||||
* Copyright (c) 2020
|
||||
*
|
||||
* This file is part of FFmpeg.
|
||||
*
|
||||
* FFmpeg is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* FFmpeg is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with FFmpeg; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include "queue.h"
|
||||
#include "libavutil/mem.h"
|
||||
|
||||
typedef struct QueueEntry QueueEntry;
|
||||
|
||||
struct QueueEntry {
|
||||
void *value;
|
||||
QueueEntry *prev;
|
||||
QueueEntry *next;
|
||||
};
|
||||
|
||||
struct Queue {
|
||||
QueueEntry *head;
|
||||
QueueEntry *tail;
|
||||
size_t length;
|
||||
};
|
||||
|
||||
static inline QueueEntry *create_entry(void *val)
|
||||
{
|
||||
QueueEntry *entry = av_malloc(sizeof(*entry));
|
||||
if (entry)
|
||||
entry->value = val;
|
||||
return entry;
|
||||
}
|
||||
|
||||
Queue* ff_queue_create(void)
|
||||
{
|
||||
Queue *q = av_malloc(sizeof(*q));
|
||||
if (!q)
|
||||
return NULL;
|
||||
|
||||
q->head = create_entry(q);
|
||||
q->tail = create_entry(q);
|
||||
|
||||
if (!q->head || !q->tail) {
|
||||
av_freep(&q->head);
|
||||
av_freep(&q->tail);
|
||||
av_freep(&q);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
q->head->next = q->tail;
|
||||
q->tail->prev = q->head;
|
||||
q->head->prev = NULL;
|
||||
q->tail->next = NULL;
|
||||
q->length = 0;
|
||||
|
||||
return q;
|
||||
}
|
||||
|
||||
void ff_queue_destroy(Queue *q)
|
||||
{
|
||||
QueueEntry *entry;
|
||||
if (!q)
|
||||
return;
|
||||
|
||||
entry = q->head;
|
||||
while (entry != NULL) {
|
||||
QueueEntry *temp = entry;
|
||||
entry = entry->next;
|
||||
av_freep(&temp);
|
||||
}
|
||||
|
||||
av_freep(&q);
|
||||
}
|
||||
|
||||
size_t ff_queue_size(Queue *q)
|
||||
{
|
||||
return q ? q->length : 0;
|
||||
}
|
||||
|
||||
void *ff_queue_peek_front(Queue *q)
|
||||
{
|
||||
if (!q || q->length == 0)
|
||||
return NULL;
|
||||
|
||||
return q->head->next->value;
|
||||
}
|
||||
|
||||
void *ff_queue_peek_back(Queue *q)
|
||||
{
|
||||
if (!q || q->length == 0)
|
||||
return NULL;
|
||||
|
||||
return q->tail->prev->value;
|
||||
}
|
||||
|
||||
int ff_queue_push_front(Queue *q, void *v)
|
||||
{
|
||||
QueueEntry *new_entry;
|
||||
QueueEntry *original_next;
|
||||
if (!q)
|
||||
return 0;
|
||||
|
||||
new_entry = create_entry(v);
|
||||
if (!new_entry)
|
||||
return -1;
|
||||
original_next = q->head->next;
|
||||
|
||||
q->head->next = new_entry;
|
||||
original_next->prev = new_entry;
|
||||
new_entry->prev = q->head;
|
||||
new_entry->next = original_next;
|
||||
q->length++;
|
||||
|
||||
return q->length;
|
||||
}
|
||||
|
||||
int ff_queue_push_back(Queue *q, void *v)
|
||||
{
|
||||
QueueEntry *new_entry;
|
||||
QueueEntry *original_prev;
|
||||
if (!q)
|
||||
return 0;
|
||||
|
||||
new_entry = create_entry(v);
|
||||
if (!new_entry)
|
||||
return -1;
|
||||
original_prev = q->tail->prev;
|
||||
|
||||
q->tail->prev = new_entry;
|
||||
original_prev->next = new_entry;
|
||||
new_entry->next = q->tail;
|
||||
new_entry->prev = original_prev;
|
||||
q->length++;
|
||||
|
||||
return q->length;
|
||||
}
|
||||
|
||||
void *ff_queue_pop_front(Queue *q)
|
||||
{
|
||||
QueueEntry *front;
|
||||
QueueEntry *new_head_next;
|
||||
void *ret;
|
||||
|
||||
if (!q || q->length == 0)
|
||||
return NULL;
|
||||
|
||||
front = q->head->next;
|
||||
new_head_next = front->next;
|
||||
ret = front->value;
|
||||
|
||||
q->head->next = new_head_next;
|
||||
new_head_next->prev = q->head;
|
||||
|
||||
av_freep(&front);
|
||||
q->length--;
|
||||
return ret;
|
||||
}
|
||||
|
||||
void *ff_queue_pop_back(Queue *q)
|
||||
{
|
||||
QueueEntry *back;
|
||||
QueueEntry *new_tail_prev;
|
||||
void *ret;
|
||||
|
||||
if (!q || q->length == 0)
|
||||
return NULL;
|
||||
|
||||
back = q->tail->prev;
|
||||
new_tail_prev = back->prev;
|
||||
ret = back->value;
|
||||
|
||||
q->tail->prev = new_tail_prev;
|
||||
new_tail_prev->next = q->tail;
|
||||
|
||||
av_freep(&back);
|
||||
q->length--;
|
||||
return ret;
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
* Copyright (c) 2020
|
||||
*
|
||||
* This file is part of FFmpeg.
|
||||
*
|
||||
* FFmpeg is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* FFmpeg is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with FFmpeg; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
#ifndef AVFILTER_DNN_QUEUE_H
|
||||
#define AVFILTER_DNN_QUEUE_H
|
||||
|
||||
/**
|
||||
* Linear double-ended data structure
|
||||
*/
|
||||
typedef struct Queue Queue;
|
||||
|
||||
/**
|
||||
* @brief Create a Queue instance.
|
||||
* It initializes the length of the Queue as 0.
|
||||
*
|
||||
* @return Pointer to the Queue
|
||||
* @retval NULL if allocation fails
|
||||
*/
|
||||
Queue *ff_queue_create(void);
|
||||
|
||||
/**
|
||||
* @brief Destroy the Queue instance.
|
||||
* It also frees all elements of the Queue.
|
||||
*/
|
||||
void ff_queue_destroy(Queue *q);
|
||||
|
||||
/**
|
||||
* @brief Return the length of the Queue
|
||||
*/
|
||||
size_t ff_queue_size(Queue *q);
|
||||
|
||||
/**
|
||||
* @brief Return a pointer to the data
|
||||
* at the head of the queue.
|
||||
*
|
||||
* @retval NULL if null pointer was passed
|
||||
* or queue is empty
|
||||
*/
|
||||
void *ff_queue_peek_front(Queue *q);
|
||||
|
||||
/**
|
||||
* @brief Return a pointer to the data at
|
||||
* the tail of the queue.
|
||||
*
|
||||
* @retval NULL if null pointer was passed
|
||||
* or queue is empty
|
||||
*/
|
||||
void *ff_queue_peek_back(Queue *q);
|
||||
|
||||
/**
|
||||
* @brief Add data to the head of the queue.
|
||||
* It increases the length of Queue by one.
|
||||
*
|
||||
* @param q pointer to the Queue.
|
||||
* @param v data to be added
|
||||
* @return The length of the Queue
|
||||
* @retval 0 if the pointer to queue is NULL
|
||||
* @retval -1 if new entry cannot be created
|
||||
*/
|
||||
int ff_queue_push_front(Queue *q, void *v);
|
||||
|
||||
/**
|
||||
* @brief Add data to the tail of the queue.
|
||||
* It increases the length of Queue by one.
|
||||
*
|
||||
* @param q pointer to the Queue
|
||||
* @param v data to be added
|
||||
* @return The length of the Queue
|
||||
* @retval 0 if the pointer to queue is NULL
|
||||
* @retval -1 if new entry cannot be created
|
||||
*/
|
||||
int ff_queue_push_back(Queue *q, void *v);
|
||||
|
||||
/**
|
||||
* @brief Remove and free first element from
|
||||
* the Queue. It shrinks the length of Queue
|
||||
* by one.
|
||||
*
|
||||
* @param q pointer to the Queue.
|
||||
* @return The value of first element as void.
|
||||
* If a null pointer or empty queue is passed,
|
||||
* it returns NULL
|
||||
*/
|
||||
void *ff_queue_pop_front(Queue *q);
|
||||
|
||||
/**
|
||||
* @brief Remove and free last element from
|
||||
* the Queue. It shrinks the length of Queue
|
||||
* by one.
|
||||
*
|
||||
* @param q pointer to the Queue.
|
||||
* @return The value of last element as void.
|
||||
* If a null pointer or empty queue is passed,
|
||||
* it returns NULL
|
||||
*/
|
||||
void *ff_queue_pop_back(Queue *q);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* Copyright (c) 2020
|
||||
*
|
||||
* This file is part of FFmpeg.
|
||||
*
|
||||
* FFmpeg is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* FFmpeg is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with FFmpeg; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include "queue.h"
|
||||
#include "safe_queue.h"
|
||||
#include "libavutil/mem.h"
|
||||
#include "libavutil/avassert.h"
|
||||
#include "libavutil/thread.h"
|
||||
|
||||
#if HAVE_PTHREAD_CANCEL
|
||||
#define DNNCond pthread_cond_t
|
||||
#define dnn_cond_init pthread_cond_init
|
||||
#define dnn_cond_destroy pthread_cond_destroy
|
||||
#define dnn_cond_signal pthread_cond_signal
|
||||
#define dnn_cond_wait pthread_cond_wait
|
||||
#else
|
||||
#define DNNCond char
|
||||
static inline int dnn_cond_init(DNNCond *cond, const void *attr) { return 0; }
|
||||
static inline int dnn_cond_destroy(DNNCond *cond) { return 0; }
|
||||
static inline int dnn_cond_signal(DNNCond *cond) { return 0; }
|
||||
static inline int dnn_cond_wait(DNNCond *cond, AVMutex *mutex)
|
||||
{
|
||||
av_assert0(!"should not reach here");
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
struct SafeQueue {
|
||||
Queue *q;
|
||||
AVMutex mutex;
|
||||
DNNCond cond;
|
||||
};
|
||||
|
||||
SafeQueue *ff_safe_queue_create(void)
|
||||
{
|
||||
SafeQueue *sq = av_malloc(sizeof(*sq));
|
||||
if (!sq)
|
||||
return NULL;
|
||||
|
||||
sq->q = ff_queue_create();
|
||||
if (!sq->q) {
|
||||
av_freep(&sq);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
ff_mutex_init(&sq->mutex, NULL);
|
||||
dnn_cond_init(&sq->cond, NULL);
|
||||
return sq;
|
||||
}
|
||||
|
||||
void ff_safe_queue_destroy(SafeQueue *sq)
|
||||
{
|
||||
if (!sq)
|
||||
return;
|
||||
|
||||
ff_queue_destroy(sq->q);
|
||||
ff_mutex_destroy(&sq->mutex);
|
||||
dnn_cond_destroy(&sq->cond);
|
||||
av_freep(&sq);
|
||||
}
|
||||
|
||||
size_t ff_safe_queue_size(SafeQueue *sq)
|
||||
{
|
||||
return sq ? ff_queue_size(sq->q) : 0;
|
||||
}
|
||||
|
||||
int ff_safe_queue_push_front(SafeQueue *sq, void *v)
|
||||
{
|
||||
int ret;
|
||||
ff_mutex_lock(&sq->mutex);
|
||||
ret = ff_queue_push_front(sq->q, v);
|
||||
dnn_cond_signal(&sq->cond);
|
||||
ff_mutex_unlock(&sq->mutex);
|
||||
return ret;
|
||||
}
|
||||
|
||||
int ff_safe_queue_push_back(SafeQueue *sq, void *v)
|
||||
{
|
||||
int ret;
|
||||
ff_mutex_lock(&sq->mutex);
|
||||
ret = ff_queue_push_back(sq->q, v);
|
||||
dnn_cond_signal(&sq->cond);
|
||||
ff_mutex_unlock(&sq->mutex);
|
||||
return ret;
|
||||
}
|
||||
|
||||
void *ff_safe_queue_pop_front(SafeQueue *sq)
|
||||
{
|
||||
void *value;
|
||||
ff_mutex_lock(&sq->mutex);
|
||||
while (ff_queue_size(sq->q) == 0) {
|
||||
dnn_cond_wait(&sq->cond, &sq->mutex);
|
||||
}
|
||||
value = ff_queue_pop_front(sq->q);
|
||||
dnn_cond_signal(&sq->cond);
|
||||
ff_mutex_unlock(&sq->mutex);
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* Copyright (c) 2020
|
||||
*
|
||||
* This file is part of FFmpeg.
|
||||
*
|
||||
* FFmpeg is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* FFmpeg is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with FFmpeg; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
#ifndef AVFILTER_DNN_SAFE_QUEUE_H
|
||||
#define AVFILTER_DNN_SAFE_QUEUE_H
|
||||
|
||||
/**
|
||||
* Double-ended queue with mutex locks ensuring
|
||||
* data consistency while multithreading.
|
||||
*/
|
||||
typedef struct SafeQueue SafeQueue;
|
||||
|
||||
/**
|
||||
* @brief Create and initialize a SafeQueue instance.
|
||||
*
|
||||
* @return Pointer to the SafeQueue
|
||||
* @retval NULL if initialization fails
|
||||
*/
|
||||
SafeQueue *ff_safe_queue_create(void);
|
||||
|
||||
/**
|
||||
* @brief Destroy the SafeQueue instance.
|
||||
* It also frees all elements of the queue,
|
||||
* destroys the mutex and condition variable.
|
||||
*/
|
||||
void ff_safe_queue_destroy(SafeQueue *sq);
|
||||
|
||||
/**
|
||||
* @brief Return the length of the SafeQueue
|
||||
*/
|
||||
size_t ff_safe_queue_size(SafeQueue *sq);
|
||||
|
||||
/**
|
||||
* @brief Add data to the head of queue in the
|
||||
* SafeQueue after locking mutex. After adding
|
||||
* the data, it signals the condition variable
|
||||
* and unlocks the mutex. It increases the length
|
||||
* of queue in the SafeQueue by one.
|
||||
*
|
||||
* @param sq pointer to the SafeQueue
|
||||
* @param v data to be added
|
||||
* @return The length of the queue
|
||||
* @retval 0 if the queue is not initialized
|
||||
* @retval -1 if new entry cannot be created
|
||||
*/
|
||||
int ff_safe_queue_push_front(SafeQueue *sq, void *v);
|
||||
|
||||
/**
|
||||
* @brief Add data to the tail of queue in the
|
||||
* SafeQueue after locking mutex. After adding
|
||||
* the data, it signals the condition variable
|
||||
* and unlocks the mutex. It increases the length
|
||||
* of queue in the SafeQueue by one.
|
||||
*
|
||||
* @param sq pointer to the SafeQueue
|
||||
* @param v data to be added
|
||||
* @return The length of the queue
|
||||
* @retval 0 if the queue is not initialized
|
||||
* @retval -1 if new entry cannot be created
|
||||
*/
|
||||
int ff_safe_queue_push_back(SafeQueue *sq, void *v);
|
||||
|
||||
/**
|
||||
* @brief Remove and free first element from
|
||||
* the queue in SafeQueue. Before removing, it
|
||||
* waits for the condition variable to signal and
|
||||
* acquires the mutex. Finally, it signals the
|
||||
* condition and unlocks the mutex.
|
||||
* It shrinks the length of queue in the SafeQueue
|
||||
* by one.
|
||||
*
|
||||
* @param sq pointer to the SafeQueue.
|
||||
* @return The value of first element as void.
|
||||
* If a null pointer or empty queue is passed,
|
||||
* it returns NULL
|
||||
*/
|
||||
void *ff_safe_queue_pop_front(SafeQueue *sq);
|
||||
|
||||
#endif
|
||||
Reference in new issue
Block a user