FFmpeg
Loading...
Searching...
No Matches
dnn_backend_torch.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) 2024
3 *
4 * This file is part of FFmpeg.
5 *
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21/**
22 * @file
23 * DNN Torch backend implementation.
24 */
25
26#include <torch/torch.h>
27#include <torch/script.h>
28
29extern "C" {
30#include "config.h"
31#include "dnn_io_proc.h"
32#include "dnn_backend_common.h"
33#include "libavutil/opt.h"
34#include "libavutil/mem.h"
35#include "libavutil/cpu.h"
36#if CONFIG_CUDA
37#include "libavutil/hwcontext.h"
40#include "libavutil/pixfmt.h"
41#endif
42#include "queue.h"
43#include "safe_queue.h"
44}
45
55
56typedef struct THInferRequest {
57 torch::Tensor *output;
58 torch::Tensor *input_tensor;
60
67
68
69#define OFFSET(x) offsetof(THOptions, x)
70#define FLAGS AV_OPT_FLAG_FILTERING_PARAM
71static const AVOption dnn_th_options[] = {
72 { "optimize", "turn on graph executor optimization", OFFSET(optimize), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS},
73 { NULL }
74};
75
76static int extract_lltask_from_task(TaskItem *task, Queue *lltask_queue)
77{
78 THModel *th_model = (THModel *)task->model;
79 DnnContext *ctx = th_model->ctx;
80 LastLevelTaskItem *lltask = (LastLevelTaskItem *)av_malloc(sizeof(*lltask));
81 if (!lltask) {
82 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for LastLevelTaskItem\n");
83 return AVERROR(ENOMEM);
84 }
85 task->inference_todo = 1;
86 task->inference_done = 0;
87 lltask->task = task;
88 if (ff_queue_push_back(lltask_queue, lltask) < 0) {
89 av_log(ctx, AV_LOG_ERROR, "Failed to push back lltask_queue.\n");
90 av_freep(&lltask);
91 return AVERROR(ENOMEM);
92 }
93 return 0;
94}
95
96static void th_free_request(THInferRequest *request)
97{
98 if (!request)
99 return;
100 if (request->output) {
101 delete(request->output);
102 request->output = NULL;
103 }
104 if (request->input_tensor) {
105 delete(request->input_tensor);
106 request->input_tensor = NULL;
107 }
108 return;
109}
110
112{
113 THRequestItem *item;
114 if (!arg || !*arg) {
115 return;
116 }
117 item = *arg;
119 av_freep(&item->infer_request);
120 av_freep(&item->lltasks);
122 av_freep(arg);
123}
124
125static void dnn_free_model_th(DNNModel **model)
126{
127 THModel *th_model;
128 if (!model || !*model)
129 return;
130
131 th_model = (THModel *)(*model);
132
133 if (th_model->request_queue) {
134 ff_dnn_wait_requests(th_model->request_queue, th_model->nb_requests);
135 while (ff_safe_queue_size(th_model->request_queue) != 0) {
138 }
140 }
141
142 if (th_model->lltask_queue)
144 if (th_model->task_queue)
145 ff_queue_destroy(th_model->task_queue);
146
147 if (th_model->jit_model)
148 delete th_model->jit_model;
149
150 av_freep(&th_model);
151 *model = NULL;
152}
153
154static int get_input_th(DNNModel *model, DNNData *input, const char *input_name)
155{
156 input->dt = DNN_FLOAT;
157 input->order = DCO_RGB;
158 input->layout = DL_NCHW;
159 input->dims[0] = 1;
160 input->dims[1] = 3;
161 input->dims[2] = -1;
162 input->dims[3] = -1;
163 return 0;
164}
165
166static void deleter(void *arg)
167{
168 av_freep(&arg);
169}
170
171#if CONFIG_CUDA
172static void cuda_tensor_deleter(void *arg)
173{
174 /* No-op: GPU memory is owned by FFmpeg AVBuffer ref-counting.
175 * LibTorch must not free it. */
176 (void)arg;
177}
178
179/**
180 * Map a CUDA frame's GPU pointer directly into a LibTorch tensor,
181 * bypassing any host-device memory copy.
182 *
183 * The resulting tensor is a zero-copy view over the frame's VRAM
184 * buffer; the AVBuffer reference keeps the memory alive.
185 */
186static int fill_model_input_th_cuda(THModel *th_model, THRequestItem *request)
187{
188 THInferRequest *infer_request = request->infer_request;
189 LastLevelTaskItem *lltask = request->lltasks[0];
190 TaskItem *task = lltask->task;
191 AVFrame *frame = task->in_frame;
192
193
194 int height = frame->height;
195 int width = frame->width;
196 /* linesize[0] is in bytes; for packed RGB/BGR it equals width * channels
197 * plus alignment padding. Use it as the stride so PyTorch respects the
198 * actual memory layout. */
199 int stride_bytes = frame->linesize[0];
200 int channels = stride_bytes / width; /* 3 for RGB24, 4 for RGB0/BGR0 */
201
202 /* Wrap the GPU device pointer in a LibTorch tensor (no copy). */
203 torch::Tensor byte_tensor = torch::from_blob(
204 frame->data[0],
205 {1, height, width, channels},
206 {(long)(height * stride_bytes), (long)stride_bytes,
207 (long)channels, 1L},
208 cuda_tensor_deleter,
209 torch::TensorOptions().dtype(torch::kUInt8).device(torch::kCUDA));
210
211 /* Convert NHWC uint8 → NCHW float32 in [0, 1] and keep on GPU. */
212 *infer_request->input_tensor =
213 byte_tensor.to(torch::kFloat32).div(255.0f)
214 .permute({0, 3, 1, 2}) /* NHWC → NCHW */
215 .slice(1, 0, 3) /* drop alpha if present */
216 .contiguous();
217
218 return 0;
219}
220
221static void fill_model_output_th_cuda(THModel *th_model, TaskItem *task, torch::Tensor &out_slice)
222{
223 AVHWFramesContext *hw_frames_ctx =
225
226 /* Determine channel layout from sw_format. */
227 int hw_channels = 3;
228 int rgb_start = 0;
229 bool needs_flip = false;
230 switch (hw_frames_ctx->sw_format) {
231 case AV_PIX_FMT_RGB24:
232 hw_channels = 3; rgb_start = 0; needs_flip = false;
233 break;
234 case AV_PIX_FMT_BGR24:
235 hw_channels = 3; rgb_start = 0; needs_flip = true;
236 break;
237 case AV_PIX_FMT_RGB0:
238 hw_channels = 4; rgb_start = 0; needs_flip = false;
239 break;
240 case AV_PIX_FMT_BGR0:
241 hw_channels = 4; rgb_start = 0; needs_flip = true;
242 break;
243 case AV_PIX_FMT_0RGB:
244 hw_channels = 4; rgb_start = 1; needs_flip = false;
245 break;
246 case AV_PIX_FMT_0BGR:
247 hw_channels = 4; rgb_start = 1; needs_flip = true;
248 break;
249 default:
250 av_log(th_model->ctx, AV_LOG_ERROR,
251 "Unsupported sw_format for CUDA zero-copy output\n");
252 hw_channels = 3;
253 break;
254 }
255
256 /* Convert model output: NCHW float [0,1] → NHWC uint8 [0,255]. */
257 torch::Tensor out_u8 =
258 out_slice.mul(255.0f)
259 .permute({0, 2, 3, 1})
260 .to(torch::kUInt8)
261 .contiguous();
262 if (needs_flip)
263 out_u8 = out_u8.flip({3});
264
265 int out_h = (int)out_u8.size(1);
266 int out_w = (int)out_u8.size(2);
267
268 /* Map the output frame's VRAM into a tensor with correct
269 * stride (linesize includes alignment padding). */
270 torch::Tensor out_frame_tensor = torch::from_blob(
271 task->out_frame->data[0],
272 {1, out_h, out_w, hw_channels},
273 {(long)(out_h * task->out_frame->linesize[0]),
274 (long)task->out_frame->linesize[0],
275 (long)hw_channels, 1L},
276 cuda_tensor_deleter,
277 torch::TensorOptions()
278 .dtype(torch::kUInt8)
279 .device(torch::kCUDA));
280
281 /* Device-to-Device copy into the correct channel slice. */
282 out_frame_tensor.slice(3, rgb_start, rgb_start + 3)
283 .copy_(out_u8);
284
285 /* Flush the CUDA stream before the encoder reads the frame. */
286 torch::cuda::synchronize();
287}
288#endif /* CONFIG_CUDA */
289
290static int fill_model_input_th(THModel *th_model, THRequestItem *request)
291{
292 LastLevelTaskItem *lltask = NULL;
293 TaskItem *task = NULL;
294 THInferRequest *infer_request = NULL;
295 DNNData input = { 0 };
296 DnnContext *ctx = th_model->ctx;
297 int ret, width_idx, height_idx, channel_idx;
298 int batch_size = ctx->batch_size;
299 float *batch_data = NULL;
300 int frame_size = 0;
301
302 infer_request = request->infer_request;
303
304 ret = get_input_th(&th_model->model, &input, NULL);
305 if (ret != 0) {
306 goto err;
307 }
308 width_idx = dnn_get_width_idx_by_layout(input.layout);
309 height_idx = dnn_get_height_idx_by_layout(input.layout);
310 channel_idx = dnn_get_channel_idx_by_layout(input.layout);
311
313 if (!lltask) {
314 ret = AVERROR(EINVAL);
315 goto err;
316 }
317 task = lltask->task;
318 input.dims[height_idx] = task->in_frame->height;
319 input.dims[width_idx] = task->in_frame->width;
320
321 frame_size = input.dims[height_idx] * input.dims[width_idx] * input.dims[channel_idx];
322 batch_data = (float *)av_malloc(batch_size * frame_size * sizeof(float));
323 if (!batch_data) {
324 ret = AVERROR(ENOMEM);
325 goto err;
326 }
327
328 for (int i = 0; i < batch_size; i++) {
330 if (!lltask)
331 break;
332
333 request->lltasks[i] = lltask;
334 request->lltask_count = i + 1;
335 task = lltask->task;
336
337 input.data = batch_data + i * frame_size;
338
339 switch (th_model->model.func_type) {
341 input.scale = 255;
342 if (task->do_ioproc) {
343 if (th_model->model.frame_pre_proc != NULL) {
344 th_model->model.frame_pre_proc(task->in_frame, &input, th_model->model.filter_ctx);
345 } else {
346 ff_proc_from_frame_to_dnn(task->in_frame, &input, ctx);
347 }
348 }
349 break;
350 default:
351 avpriv_report_missing_feature(NULL, "model function type %d", th_model->model.func_type);
352 break;
353 }
354 }
355
356 infer_request->input_tensor = new torch::Tensor();
357 infer_request->output = new torch::Tensor();
358 *infer_request->input_tensor = torch::from_blob(batch_data,
359 {request->lltask_count, input.dims[channel_idx], input.dims[height_idx], input.dims[width_idx]},
360 deleter, torch::kFloat32);
361
362 return 0;
363
364err:
365 if (batch_data)
366 av_freep(&batch_data);
367 th_free_request(infer_request);
368 return ret;
369}
370
371static int th_start_inference(void *args)
372{
373 THRequestItem *request = (THRequestItem *)args;
374 THInferRequest *infer_request = NULL;
375 LastLevelTaskItem *lltask = NULL;
376 TaskItem *task = NULL;
377 THModel *th_model = NULL;
379 std::vector<torch::jit::IValue> inputs;
380 torch::NoGradGuard no_grad;
381
382 if (!request) {
383 av_log(NULL, AV_LOG_ERROR, "THRequestItem is NULL\n");
384 return AVERROR(EINVAL);
385 }
386 infer_request = request->infer_request;
387 lltask = request->lltasks[0];
388 task = lltask->task;
389 th_model = (THModel *)task->model;
390 ctx = th_model->ctx;
391
392 if (ctx->torch_option.optimize)
393 torch::jit::setGraphExecutorOptimize(true);
394 else
395 torch::jit::setGraphExecutorOptimize(false);
396
397 if (!infer_request->input_tensor || !infer_request->output) {
398 av_log(ctx, AV_LOG_ERROR, "input or output tensor is NULL\n");
399 return DNN_GENERIC_ERROR;
400 }
401 // Transfer tensor to the same device as model
402 const char *device_name = ctx->device ? ctx->device : "cpu";
403 c10::Device device(device_name);
404 if (infer_request->input_tensor->device() != device)
405 *infer_request->input_tensor = infer_request->input_tensor->to(device);
406 inputs.push_back(*infer_request->input_tensor);
407
408 *infer_request->output = th_model->jit_model->forward(inputs).toTensor();
409
410 return 0;
411}
412
413static void infer_completion_callback(void *args) {
414 THRequestItem *request = (THRequestItem*)args;
415 THInferRequest *infer_request = request->infer_request;
416 LastLevelTaskItem *lltask = request->lltasks[0];
417 THModel *th_model = (THModel *)lltask->task->model;
418 torch::Tensor *output = infer_request->output;
419 DNNData outputs = { 0 };
420
421 auto slices = torch::split(*output, /*split_size=*/1, /*dim=*/0);
422 for (uint32_t i = 0; i < request->lltask_count; i++) {
423 lltask = request->lltasks[i];
424 TaskItem *task = lltask->task;
425 torch::Tensor out_slice = slices[i];
426 c10::IntArrayRef sizes = out_slice.sizes();
427
428 outputs.order = DCO_RGB;
429 outputs.layout = DL_NCHW;
430 outputs.dt = DNN_FLOAT;
431
432 if (sizes.size() == 4) {
433 // 4 dimensions: [batch_size, channel, height, width]
434 // this format of data is normally used for video frame SR
435 outputs.dims[0] = sizes.at(0); // N
436 outputs.dims[1] = sizes.at(1); // C
437 outputs.dims[2] = sizes.at(2); // H
438 outputs.dims[3] = sizes.at(3); // W
439 } else {
440 avpriv_report_missing_feature(th_model->ctx, "Support of this kind of model");
441 goto err;
442 }
443
444 switch (th_model->model.func_type) {
446 if (task->do_ioproc) {
447#if CONFIG_CUDA
448 if (task->out_frame->format == AV_PIX_FMT_CUDA) {
449 fill_model_output_th_cuda(th_model, task, out_slice);
450 } else {
451#endif
452 if (out_slice.device() != torch::kCPU)
453 out_slice = out_slice.to(torch::kCPU);
454 outputs.scale = 255;
455 outputs.data = out_slice.data_ptr();
456 if (th_model->model.frame_post_proc != NULL) {
457 th_model->model.frame_post_proc(task->out_frame, &outputs,
458 th_model->model.filter_ctx);
459 } else {
461 th_model->ctx);
462 }
463#if CONFIG_CUDA
464 }
465#endif
466 } else {
469 }
470 break;
471 default:
472 avpriv_report_missing_feature(th_model->ctx, "model function type %d", th_model->model.func_type);
473 goto err;
474 }
475 task->inference_done++;
476 }
477
478err:
479 for (uint32_t i = 0; i < request->lltask_count; i++) {
480 av_freep(&request->lltasks[i]);
481 }
482 request->lltask_count = 0;
483
484 th_free_request(infer_request);
485
486 if (ff_safe_queue_push_back(th_model->request_queue, request) < 0) {
487 destroy_request_item(&request);
488 av_log(th_model->ctx, AV_LOG_ERROR, "Unable to push back request_queue when failed to start inference.\n");
489 }
490}
491
492static int execute_model_th(THRequestItem *request, Queue *lltask_queue)
493{
494 THModel *th_model = NULL;
495 LastLevelTaskItem *lltask;
496 TaskItem *task = NULL;
497 int ret = 0;
498
499 if (ff_queue_size(lltask_queue) == 0) {
500 destroy_request_item(&request);
501 return 0;
502 }
503
504 lltask = (LastLevelTaskItem *)ff_queue_peek_front(lltask_queue);
505 if (lltask == NULL) {
506 av_log(NULL, AV_LOG_ERROR, "Failed to get LastLevelTaskItem\n");
507 ret = AVERROR(EINVAL);
508 goto err;
509 }
510 task = lltask->task;
511 th_model = (THModel *)task->model;
512
513#if CONFIG_CUDA
514 if (task->in_frame->format == AV_PIX_FMT_CUDA) {
515 ret = fill_model_input_th_cuda(th_model, request);
516 } else {
517 ret = fill_model_input_th(th_model, request);
518 }
519#else
520 ret = fill_model_input_th(th_model, request);
521#endif
522 if (ret != 0) {
523 goto err;
524 }
525
526 if (task->async) {
527 ret = ff_dnn_start_inference_async(th_model->ctx, &request->exec_module);
528 if (ret != 0) {
529 goto err;
530 }
531 return 0;
532 } else {
533 // Synchronous execution path
534 ret = th_start_inference((void *)(request));
535 if (ret != 0) {
536 goto err;
537 }
539 return (task->inference_done == task->inference_todo) ? 0 : DNN_GENERIC_ERROR;
540 }
541
542err:
544 if (ff_safe_queue_push_back(th_model->request_queue, request) < 0) {
545 destroy_request_item(&request);
546 }
547 return ret;
548}
549
550static int get_output_th(DNNModel *model, const char *input_name, int input_width, int input_height,
551 const char *output_name, int *output_width, int *output_height)
552{
553 int ret = 0;
554 THModel *th_model = (THModel*) model;
555 DnnContext *ctx = th_model->ctx;
556 TaskItem task = { 0 };
557 THRequestItem *request = NULL;
558 DNNExecBaseParams exec_params = {
559 .input_name = input_name,
560 .output_names = &output_name,
561 .nb_output = 1,
562 .in_frame = NULL,
563 .out_frame = NULL,
564 };
565 ret = ff_dnn_fill_gettingoutput_task(&task, &exec_params, th_model, input_height, input_width, ctx);
566 if ( ret != 0) {
567 goto err;
568 }
569
570 ret = extract_lltask_from_task(&task, th_model->lltask_queue);
571 if ( ret != 0) {
572 av_log(ctx, AV_LOG_ERROR, "unable to extract last level task from task.\n");
573 goto err;
574 }
575
577 if (!request) {
578 av_log(ctx, AV_LOG_ERROR, "unable to get infer request.\n");
579 ret = AVERROR(EINVAL);
580 goto err;
581 }
582
583 ret = execute_model_th(request, th_model->lltask_queue);
584 *output_width = task.out_frame->width;
585 *output_height = task.out_frame->height;
586
587err:
589 av_frame_free(&task.in_frame);
590 return ret;
591}
592
594{
596 if (!request) {
597 return NULL;
598 }
599 request->input_tensor = NULL;
600 request->output = NULL;
601 return request;
602}
603
605{
606 DNNModel *model = NULL;
607 THModel *th_model = NULL;
608 THRequestItem *item = NULL;
609 const char *device_name = ctx->device ? ctx->device : "cpu";
610
611 th_model = (THModel *)av_mallocz(sizeof(THModel));
612 if (!th_model)
613 return NULL;
614 model = &th_model->model;
615 th_model->ctx = ctx;
616
617 c10::Device device = c10::Device(device_name);
618 if (device.is_xpu()) {
619 if (!at::hasXPU()) {
620 av_log(ctx, AV_LOG_ERROR, "No XPU device found\n");
621 goto fail;
622 }
623#if TORCH_VERSION_MAJOR > 2 || (TORCH_VERSION_MAJOR == 2 && TORCH_VERSION_MINOR >= 6)
624 at::detail::getXPUHooks().init();
625#else
626 at::detail::getXPUHooks().initXPU();
627#endif
628 } else if (device.is_cuda()) {
629 // CUDA device - works for both NVIDIA CUDA and AMD ROCm (which uses CUDA-compatible API)
630 if (!torch::cuda::is_available()) {
631 av_log(ctx, AV_LOG_ERROR, "CUDA/ROCm is not available\n");
632 goto fail;
633 }
634 av_log(ctx, AV_LOG_INFO, "Using CUDA/ROCm device: %s\n", device_name);
635 } else if (!device.is_cpu()) {
636 av_log(ctx, AV_LOG_ERROR, "Not supported device:\"%s\"\n", device_name);
637 goto fail;
638 }
639
640 try {
641 th_model->jit_model = new torch::jit::Module;
642 (*th_model->jit_model) = torch::jit::load(ctx->model_filename);
643 th_model->jit_model->to(device);
644 } catch (const c10::Error& e) {
645 av_log(ctx, AV_LOG_ERROR, "Failed to load torch model\n");
646 goto fail;
647 }
648
649 if (ctx->nireq <= 0) {
650 ctx->nireq = av_cpu_count() / 2 + 1;
651 }
652
654 if (!th_model->request_queue) {
655 goto fail;
656 }
657
658 for (int i = 0; i < ctx->nireq; i++) {
659 item = (THRequestItem *)av_mallocz(sizeof(THRequestItem));
660 if (!item) {
661 goto fail;
662 }
664 if (!item->infer_request) {
665 goto fail;
666 }
667 item->lltasks = (LastLevelTaskItem **)av_malloc_array(ctx->batch_size, sizeof(*item->lltasks));
668 if (!item->lltasks) {
669 goto fail;
670 }
671 item->lltask_count = 0;
672
675 item->exec_module.args = item;
676
677 if (ff_safe_queue_push_back(th_model->request_queue, item) < 0) {
678 goto fail;
679 }
680 th_model->nb_requests++;
681 item = NULL;
682 }
683
684 th_model->task_queue = ff_queue_create();
685 th_model->lltask_queue = ff_queue_create();
686
687 model->get_input = &get_input_th;
688 model->get_output = &get_output_th;
689 model->filter_ctx = filter_ctx;
690 model->func_type = func_type;
691 return model;
692
693fail:
694 if (item) {
696 }
697 dnn_free_model_th(&model);
698 return NULL;
699}
700
701static int dnn_execute_model_th(const DNNModel *model, DNNExecBaseParams *exec_params)
702{
703 THModel *th_model = (THModel *)model;
704 DnnContext *ctx = th_model->ctx;
705 TaskItem *task;
706 THRequestItem *request;
707 int ret = 0;
708
709 ret = ff_check_exec_params(ctx, DNN_TH, model->func_type, exec_params);
710 if (ret != 0) {
711 av_log(ctx, AV_LOG_ERROR, "exec parameter checking fail.\n");
712 return ret;
713 }
714
715 task = (TaskItem *)av_malloc(sizeof(TaskItem));
716 if (!task) {
717 av_log(ctx, AV_LOG_ERROR, "unable to alloc memory for task item.\n");
718 return AVERROR(ENOMEM);
719 }
720
721 ret = ff_dnn_fill_task(task, exec_params, th_model, ctx->async, 1);
722 if (ret != 0) {
723 av_freep(&task);
724 av_log(ctx, AV_LOG_ERROR, "unable to fill task.\n");
725 return ret;
726 }
727
728 ret = ff_queue_push_back(th_model->task_queue, task);
729 if (ret < 0) {
730 av_freep(&task);
731 av_log(ctx, AV_LOG_ERROR, "unable to push back task_queue.\n");
732 return ret;
733 }
734
735 ret = extract_lltask_from_task(task, th_model->lltask_queue);
736 if (ret != 0) {
737 av_log(ctx, AV_LOG_ERROR, "unable to extract last level task from task.\n");
738 return ret;
739 }
740
741 while (ff_queue_size(th_model->lltask_queue) >= ctx->batch_size) {
743 if (!request) {
744 av_log(ctx, AV_LOG_ERROR, "unable to get infer request.\n");
745 return AVERROR(EINVAL);
746 }
747
748 ret = execute_model_th(request, th_model->lltask_queue);
749 if (ret != 0) {
750 return ret;
751 }
752 }
753
754 return 0;
755}
756
758{
759 THModel *th_model = (THModel *)model;
760 return ff_dnn_get_result_common(th_model->task_queue, in, out);
761}
762
763static int dnn_flush_th(const DNNModel *model)
764{
765 THModel *th_model = (THModel *)model;
766 THRequestItem *request;
767
768 if (ff_queue_size(th_model->lltask_queue) == 0)
769 // no pending task need to flush
770 return 0;
771
773 if (!request) {
774 av_log(th_model->ctx, AV_LOG_ERROR, "unable to get infer request.\n");
775 return AVERROR(EINVAL);
776 }
777
778 return execute_model_th(request, th_model->lltask_queue);
779}
780
781extern const DNNModule ff_dnn_backend_torch = {
782 .clazz = DNN_DEFINE_CLASS(dnn_th),
783 .type = DNN_TH,
784 .load_model = dnn_load_model_th,
785 .execute_model = dnn_execute_model_th,
786 .get_result = dnn_get_result_th,
787 .flush = dnn_flush_th,
788 .free_model = dnn_free_model_th,
789};
static const AVFilterPad inputs[]
Definition af_aap.c:299
static const AVFilterPad outputs[]
Definition af_aap.c:310
static FILE * out
static AVFormatContext * ctx
channels
Definition aptx.h:31
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define FLAGS
Definition cmdutils.c:596
#define NULL
Definition coverity.c:32
static AVFrame * frame
int ff_check_exec_params(void *ctx, DNNBackendType backend, DNNFunctionType func_type, DNNExecBaseParams *exec_params)
void ff_dnn_wait_requests(SafeQueue *request_queue, int nireq)
Wait for all inference requests to complete before teardown.
DNNAsyncStatusType ff_dnn_get_result_common(Queue *task_queue, AVFrame **in, AVFrame **out)
Extract input and output frame from the Task Queue after asynchronous inference.
int ff_dnn_async_module_cleanup(DNNAsyncExecModule *async_module)
Join the Async Execution thread and set module pointers to NULL.
int ff_dnn_fill_task(TaskItem *task, DNNExecBaseParams *exec_params, void *backend_model, int async, int do_ioproc)
Fill the Task for Backend Execution.
int ff_dnn_start_inference_async(void *ctx, DNNAsyncExecModule *async_module)
Start asynchronous inference routine for the TensorFlow model on a detached thread.
int ff_dnn_fill_gettingoutput_task(TaskItem *task, DNNExecBaseParams *exec_params, void *backend_model, int input_height, int input_width, void *ctx)
Allocate input and output frames and fill the Task with execution parameters.
DNN common functions different backends.
#define DNN_DEFINE_CLASS(fname)
static void infer_completion_callback(void *args)
const DNNModule ff_dnn_backend_torch
static int get_input_th(DNNModel *model, DNNData *input, const char *input_name)
static int fill_model_input_th(THModel *th_model, THRequestItem *request)
static DNNAsyncStatusType dnn_get_result_th(const DNNModel *model, AVFrame **in, AVFrame **out)
static int extract_lltask_from_task(TaskItem *task, Queue *lltask_queue)
static int th_start_inference(void *args)
static int execute_model_th(THRequestItem *request, Queue *lltask_queue)
static const AVOption dnn_th_options[]
static void th_free_request(THInferRequest *request)
static THInferRequest * th_create_inference_request(void)
static int dnn_flush_th(const DNNModel *model)
static int dnn_execute_model_th(const DNNModel *model, DNNExecBaseParams *exec_params)
static DNNModel * dnn_load_model_th(DnnContext *ctx, DNNFunctionType func_type, AVFilterContext *filter_ctx)
#define OFFSET(x)
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)
static void deleter(void *arg)
static void destroy_request_item(THRequestItem **arg)
static void dnn_free_model_th(DNNModel **model)
static void infer_completion_callback(void *args)
static int dnn_get_height_idx_by_layout(DNNLayout layout)
DNNAsyncStatusType
@ DL_NCHW
@ DNN_TH
DNNFunctionType
@ DFT_PROCESS_FRAME
static int dnn_get_width_idx_by_layout(DNNLayout layout)
#define DNN_GENERIC_ERROR
@ DNN_FLOAT
@ DCO_RGB
static int dnn_get_channel_idx_by_layout(DNNLayout layout)
int ff_proc_from_frame_to_dnn(AVFrame *frame, DNNData *input, void *log_ctx)
int ff_proc_from_dnn_to_frame(AVFrame *frame, DNNData *output, void *log_ctx)
Definition dnn_io_proc.c:42
DNN input&output process between AVFrame and DNNData.
int ret
Definition ffplay.c:391
static const uint8_t frame_size[4]
Definition g723_1.h:222
#define fail
Definition test.h:479
@ AV_OPT_TYPE_INT
Underlying C type is int.
Definition opt.h:258
#define AVERROR(e)
Definition error.h:45
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition frame.c:65
#define AV_LOG_INFO
Standard information.
Definition log.h:221
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
An API-specific header for AV_HWDEVICE_TYPE_CUDA.
FFmpeg internal API for CUDA.
static const int sizes[][2]
Definition img2dec.c:63
const char * arg
Definition jacosubdec.c:66
const char * to
Definition webvttdec.c:37
int av_cpu_count(void)
Definition cpu.c:229
void avpriv_report_missing_feature(void *avc, const char *msg,...) av_printf_format(2
Log a generic warning message about a missing feature.
Memory handling functions.
#define av_malloc(s)
Definition ops_static.c:52
AVOptions.
pixel format definitions
@ AV_PIX_FMT_RGB24
packed RGB 8:8:8, 24bpp, RGBRGB...
Definition pixfmt.h:75
@ AV_PIX_FMT_BGR0
packed BGR 8:8:8, 32bpp, BGRXBGRX... X=unused/undefined
Definition pixfmt.h:265
@ AV_PIX_FMT_CUDA
HW acceleration through CUDA.
Definition pixfmt.h:260
@ AV_PIX_FMT_0BGR
packed BGR 8:8:8, 32bpp, XBGRXBGR... X=unused/undefined
Definition pixfmt.h:264
@ AV_PIX_FMT_RGB0
packed RGB 8:8:8, 32bpp, RGBXRGBX... X=unused/undefined
Definition pixfmt.h:263
@ AV_PIX_FMT_BGR24
packed RGB 8:8:8, 24bpp, BGRBGR...
Definition pixfmt.h:76
@ AV_PIX_FMT_0RGB
packed RGB 8:8:8, 32bpp, XRGBXRGB... X=unused/undefined
Definition pixfmt.h:262
void ff_queue_destroy(Queue *q)
Destroy the Queue instance.
Definition queue.c:72
void * ff_queue_pop_front(Queue *q)
Remove and free first element from the Queue.
Definition queue.c:151
int ff_queue_push_back(Queue *q, void *v)
Add data to the tail of the queue.
Definition queue.c:130
void * ff_queue_peek_front(Queue *q)
Return a pointer to the data at the head of the queue.
Definition queue.c:93
size_t ff_queue_size(Queue *q)
Return the length of the Queue.
Definition queue.c:88
Queue * ff_queue_create(void)
Create a Queue instance.
Definition queue.c:47
int ff_safe_queue_push_back(SafeQueue *sq, void *v)
Add data to the tail of queue in the SafeQueue after locking mutex.
Definition safe_queue.c:87
void * ff_safe_queue_pop_front(SafeQueue *sq)
Remove and free first element from the queue in SafeQueue.
Definition safe_queue.c:97
size_t ff_safe_queue_size(SafeQueue *sq)
Return the length of the SafeQueue.
Definition safe_queue.c:61
SafeQueue * ff_safe_queue_create(void)
Create and initialize a SafeQueue instance.
Definition safe_queue.c:33
void ff_safe_queue_destroy(SafeQueue *sq)
Destroy the SafeQueue instance.
Definition safe_queue.c:50
uint8_t * data
The data buffer.
Definition buffer.h:90
An instance of a filter.
Definition avfilter.h:279
This structure describes decoded (raw) audio or video data.
Definition frame.h:479
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition frame.h:500
int width
Definition frame.h:551
AVBufferRef * hw_frames_ctx
For hwaccel-format frames, this should be a reference to the AVHWFramesContext describing the frame.
Definition frame.h:779
int height
Definition frame.h:551
int format
format of the frame, -1 if unknown or unset Values correspond to enum AVPixelFormat for video frames,...
Definition frame.h:566
This struct describes a set or pool of "hardware" frames (i.e.
Definition hwcontext.h:118
AVOption.
Definition opt.h:428
Common Async Execution Mechanism for the DNN Backends.
void * args
Argument for the execution functions.
int(* start_inference)(void *request)
Synchronous inference function for the backend with corresponding request item as the argument.
void(* callback)(void *args)
Completion Callback for the backend.
float scale
DNNDataType dt
int dims[4]
DNNColorOrder order
void * data
DNNLayout layout
int(* get_input)(struct DNNModel *model, DNNData *input, const char *input_name)
int(* get_output)(struct DNNModel *model, const char *input_name, int input_width, int input_height, const char *output_name, int *output_width, int *output_height)
FramePrePostProc frame_pre_proc
FramePrePostProc frame_post_proc
AVFilterContext * filter_ctx
DNNFunctionType func_type
Linear double-ended data structure.
Definition executor.c:51
Double-ended queue with mutex locks ensuring data consistency while multithreading.
Definition safe_queue.c:27
torch::Tensor * input_tensor
torch::Tensor * output
torch::jit::Module * jit_model
Queue * lltask_queue
Queue * task_queue
DnnContext * ctx
SafeQueue * request_queue
LastLevelTaskItem ** lltasks
THInferRequest * infer_request
DNNAsyncExecModule exec_module
uint32_t inference_done
AVFrame * in_frame
uint8_t do_ioproc
uint32_t inference_todo
AVFrame * out_frame
#define av_malloc_array(a, b)
#define av_mallocz(s)
#define av_freep(p)
#define av_log(a,...)
#define height
Definition dsp.h:99
#define width
Definition dsp.h:99
static FilteringContext * filter_ctx
Definition transcode.c:52