FFmpeg
Loading...
Searching...
No Matches
dnn_backend_onnx.c
Go to the documentation of this file.
1/*
2 * Copyright (c) 2026 Advanced Micro Devices, Inc.
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 ONNX Runtime backend implementation.
24 */
25
26#include "libavutil/opt.h"
27#include "libavutil/avassert.h"
29#include "libavutil/imgutils.h"
30#include "libavutil/mem.h"
31#include "libavutil/avstring.h"
32#include "libavutil/thread.h"
34#include "../filters.h"
35#include "dnn_io_proc.h"
36#include "dnn_backend_common.h"
37#include "queue.h"
38#include "safe_queue.h"
39#include <onnxruntime_c_api.h>
40#include <inttypes.h>
41#include <stdio.h>
42#include <string.h>
43
44#if CONFIG_DNN_ONNX_D3D12
45#include "libavutil/hwcontext.h"
47#include "dnn_onnx_d3d12.h"
48#endif
49
50typedef struct ONNXModel {
53 OrtEnv *env;
54 OrtSession *session;
55 OrtSessionOptions *session_options;
56 OrtAllocator *allocator;
63#if CONFIG_DNN_ONNX_D3D12
64 DnnOnnxD3D12Ctx *hw_ctx;
65#endif
66} ONNXModel;
67
68typedef struct ONNXInferRequest {
69 OrtValue *input_tensor;
70 OrtValue **output_tensors;
71 uint32_t nb_outputs;
73#if CONFIG_DNN_ONNX_D3D12
74 void *hw_in_tensor;
75 void *hw_out_tensor;
76#endif
78
84
85#define OFFSET(x) offsetof(ONNXOptions, x)
86#define FLAGS AV_OPT_FLAG_FILTERING_PARAM
87static const AVOption dnn_onnx_options[] = {
88 { "threads_per_operation", "number of CPU threads per ORT operator (device=cpu only)",
89 OFFSET(num_threads), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, FLAGS },
90 { NULL }
91};
92
94
95static const OrtApi *g_ort = NULL;
97
98static void init_ort_api(void)
99{
100 g_ort = OrtGetApiBase()->GetApi(ORT_API_VERSION);
101}
102
103#define ORT_ABORT_ON_ERROR(expr) \
104 do { \
105 OrtStatus *status = (expr); \
106 if (status != NULL) { \
107 const char *msg = g_ort->GetErrorMessage(status); \
108 av_log(ctx, AV_LOG_ERROR, "ONNX Runtime error: %s\n", msg); \
109 g_ort->ReleaseStatus(status); \
110 goto err; \
111 } \
112 } while (0)
113
115{
116 AVFrameSideData *sd;
118 const AVDetectionBBox *bbox;
119
121 if (!sd)
122 return 0;
123
124 if (!sd->size)
125 return 0;
126
127 header = (const AVDetectionBBoxHeader *)sd->data;
128 if (!header->nb_bboxes)
129 return 0;
130
131 for (uint32_t i = 0; i < header->nb_bboxes; i++) {
133 if (bbox->x < 0 || bbox->w < 0 || bbox->x + bbox->w > frame->width)
134 return 0;
135 if (bbox->y < 0 || bbox->h < 0 || bbox->y + bbox->h > frame->height)
136 return 0;
138 return 0;
139 }
140
141 return 1;
142}
143
145 Queue *lltask_queue, DNNExecBaseParams *exec_params)
146{
147 ONNXModel *onnx_model = (ONNXModel *)task->model;
148 DnnContext *ctx = onnx_model->ctx;
149
150 switch (func_type) {
153 {
154 LastLevelTaskItem *lltask = av_malloc(sizeof(*lltask));
155 if (!lltask) {
156 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for LastLevelTaskItem\n");
157 return AVERROR(ENOMEM);
158 }
159 task->inference_todo = 1;
160 task->inference_done = 0;
161 lltask->task = task;
162 if (ff_queue_push_back(lltask_queue, lltask) < 0) {
163 av_log(ctx, AV_LOG_ERROR, "Failed to push back lltask_queue.\n");
164 av_freep(&lltask);
165 return AVERROR(ENOMEM);
166 }
167 return 0;
168 }
170 {
172 AVFrame *frame = task->in_frame;
173 AVFrameSideData *sd;
175
176 task->inference_todo = 0;
177 task->inference_done = 0;
178
180 return 0;
181
183 header = (const AVDetectionBBoxHeader *)sd->data;
184
185 for (uint32_t i = 0; i < header->nb_bboxes; i++) {
186 LastLevelTaskItem *lltask;
188
189 if (params->target) {
190 if (av_strncasecmp(bbox->detect_label, params->target, sizeof(bbox->detect_label)) != 0)
191 continue;
192 }
193
194 lltask = av_malloc(sizeof(*lltask));
195 if (!lltask) {
196 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for LastLevelTaskItem\n");
197 return AVERROR(ENOMEM);
198 }
199 task->inference_todo++;
200 lltask->task = task;
201 lltask->bbox_index = i;
202 if (ff_queue_push_back(lltask_queue, lltask) < 0) {
203 av_log(ctx, AV_LOG_ERROR, "Failed to push back lltask_queue.\n");
204 av_freep(&lltask);
205 return AVERROR(ENOMEM);
206 }
207 }
208 return 0;
209 }
210 default:
211 avpriv_report_missing_feature(ctx, "model function type %d", func_type);
212 return AVERROR(ENOSYS);
213 }
214}
215
217{
218 if (!request)
219 return;
220 if (request->input_tensor) {
221 g_ort->ReleaseValue(request->input_tensor);
222 request->input_tensor = NULL;
223 }
224 av_freep(&request->input_data);
225 if (request->output_tensors) {
226 for (uint32_t i = 0; i < request->nb_outputs; i++) {
227 if (request->output_tensors[i]) {
228 g_ort->ReleaseValue(request->output_tensors[i]);
229 request->output_tensors[i] = NULL;
230 }
231 }
232 av_freep(&request->output_tensors);
233 }
234 request->nb_outputs = 0;
235#if CONFIG_DNN_ONNX_D3D12
236 /* Borrowed references owned by ONNXModel.hw_ctx; never release here. */
237 request->hw_in_tensor = NULL;
238 request->hw_out_tensor = NULL;
239#endif
240}
241
243{
244 ONNXRequestItem *item;
245 if (!arg || !*arg)
246 return;
247 item = *arg;
249 av_freep(&item->infer_request);
250 av_freep(&item->lltask);
252 av_freep(arg);
253}
254
255static void dnn_free_model_onnx(DNNModel **model)
256{
257 ONNXModel *onnx_model;
258 if (!model || !*model)
259 return;
260
261 onnx_model = (ONNXModel *)(*model);
262
263 ff_dnn_wait_requests(onnx_model->request_queue, onnx_model->ctx->nireq);
264 while (ff_safe_queue_size(onnx_model->request_queue) != 0) {
267 }
269
270 while (ff_queue_size(onnx_model->lltask_queue) != 0) {
272 av_freep(&item);
273 }
274 ff_queue_destroy(onnx_model->lltask_queue);
275
276#if CONFIG_DNN_ONNX_D3D12
277 ff_dnn_onnx_d3d12_sync(onnx_model->hw_ctx);
278#endif
279
280 while (ff_queue_size(onnx_model->task_queue) != 0) {
281 TaskItem *item = (TaskItem *)ff_queue_pop_front(onnx_model->task_queue);
282 av_frame_free(&item->in_frame);
283 av_frame_free(&item->out_frame);
284 av_freep(&item);
285 }
286 ff_queue_destroy(onnx_model->task_queue);
287
288 if (onnx_model->session)
289 g_ort->ReleaseSession(onnx_model->session);
290 if (onnx_model->session_options)
291 g_ort->ReleaseSessionOptions(onnx_model->session_options);
292 if (onnx_model->env)
293 g_ort->ReleaseEnv(onnx_model->env);
294
295#if CONFIG_DNN_ONNX_D3D12
296 /* Must be released after the session and session_options above have
297 * let go of the DirectML device and shared command queue it wraps. */
298 ff_dnn_onnx_d3d12_free(&onnx_model->hw_ctx);
299#endif
300
301 av_freep(&onnx_model);
302 *model = NULL;
303}
304
305#if CONFIG_DNN_ONNX_D3D12
306static void append_d3d12_dml_ep(ONNXModel *onnx_model)
307{
308 DnnContext *ctx = onnx_model->ctx;
309 AVHWFramesContext *frames_ctx;
310 AVHWDeviceContext *dev_ctx;
311 AVD3D12VADeviceContext *d3d12_hwctx;
312 int is_uma = 0;
313
314 if (!ctx->hw_frames_ctx)
315 return;
316
317 frames_ctx = (AVHWFramesContext *)ctx->hw_frames_ctx->data;
318 dev_ctx = frames_ctx->device_ctx;
319 if (dev_ctx->type != AV_HWDEVICE_TYPE_D3D12VA) {
321 "dnn_onnx_d3d12: hw_frames_ctx is not backed by a D3D12VA "
322 "device; falling back to host I/O\n");
323 return;
324 }
325 d3d12_hwctx = (AVD3D12VADeviceContext *)dev_ctx->hwctx;
326
327 if (ff_dnn_onnx_d3d12_probe(d3d12_hwctx->device, DNN_ONNX_D3D12_TENSOR_GPU, &is_uma, ctx) < 0)
328 return;
329
330 onnx_model->hw_ctx = ff_dnn_onnx_d3d12_create(d3d12_hwctx->device, DNN_ONNX_D3D12_TENSOR_GPU, ctx);
331 if (!onnx_model->hw_ctx)
332 return;
333
334 if (ff_dnn_onnx_d3d12_append_ep(onnx_model->hw_ctx, onnx_model->session_options) < 0) {
336 "Failed to register the DirectML EP on the frames' D3D12 "
337 "device; D3D12 hardware-frame input will fail to configure, "
338 "only software-frame input can use the default-device DirectML EP\n");
339 ff_dnn_onnx_d3d12_free(&onnx_model->hw_ctx);
340 return;
341 }
342
343 ctx->zero_copy_negotiated = 1;
345 "Using DirectML execution provider on the frames' own D3D12 device%s\n",
346 is_uma ? " (UMA)" : "");
347}
348#endif
349
350static int get_input_onnx(DNNModel *model, DNNData *input, const char *input_name)
351{
352 ONNXModel *onnx_model = (ONNXModel *)model;
353 DnnContext *ctx = onnx_model->ctx;
354 OrtTypeInfo *type_info = NULL;
355 const OrtTensorTypeAndShapeInfo *tensor_info = NULL;
356 size_t num_dims;
357 size_t input_count = 0;
358 size_t input_index = 0;
359 int found_input = 0;
360 int64_t *dims;
361 ONNXTensorElementDataType tensor_type;
362 OrtStatus *status;
363
364 if (!input_name || !*input_name) {
365 av_log(ctx, AV_LOG_ERROR, "ONNX input name is not specified\n");
366 return AVERROR(EINVAL);
367 }
368
369 if (onnx_model->input_resolved) {
370 *input = onnx_model->input_info;
371 return 0;
372 }
373
374 status = g_ort->SessionGetInputCount(onnx_model->session, &input_count);
375 if (status != NULL) {
376 const char *msg = g_ort->GetErrorMessage(status);
377 av_log(ctx, AV_LOG_ERROR, "Failed to get input count: %s\n", msg);
378 g_ort->ReleaseStatus(status);
379 return AVERROR(EINVAL);
380 }
381
382 for (size_t i = 0; i < input_count; i++) {
383 char *name = NULL;
384 status = g_ort->SessionGetInputName(onnx_model->session, i,
385 onnx_model->allocator, &name);
386 if (status != NULL) {
387 g_ort->ReleaseStatus(status);
388 continue;
389 }
390 if (!strcmp(name, input_name)) {
391 input_index = i;
392 found_input = 1;
393 }
394 onnx_model->allocator->Free(onnx_model->allocator, name);
395 if (found_input)
396 break;
397 }
398
399 if (!found_input) {
400 av_log(ctx, AV_LOG_ERROR, "Input name '%s' not found in ONNX model\n",
401 input_name);
402 return AVERROR(EINVAL);
403 }
404
405 status = g_ort->SessionGetInputTypeInfo(onnx_model->session, input_index,
406 &type_info);
407 if (status != NULL) {
408 const char *msg = g_ort->GetErrorMessage(status);
409 av_log(ctx, AV_LOG_ERROR, "Failed to get input type info: %s\n", msg);
410 g_ort->ReleaseStatus(status);
411 return AVERROR(EINVAL);
412 }
413
414 status = g_ort->CastTypeInfoToTensorInfo(type_info, &tensor_info);
415 if (status != NULL) {
416 g_ort->ReleaseTypeInfo(type_info);
417 g_ort->ReleaseStatus(status);
418 return AVERROR(EINVAL);
419 }
420
421 status = g_ort->GetDimensionsCount(tensor_info, &num_dims);
422 if (status != NULL) {
423 g_ort->ReleaseTypeInfo(type_info);
424 g_ort->ReleaseStatus(status);
425 return AVERROR(EINVAL);
426 }
427
428 if (num_dims != 4) {
429 avpriv_report_missing_feature(ctx, "Support for %zu dimensional input", num_dims);
430 g_ort->ReleaseTypeInfo(type_info);
431 return AVERROR(ENOSYS);
432 }
433
434 dims = av_malloc(num_dims * sizeof(int64_t));
435 if (!dims) {
436 g_ort->ReleaseTypeInfo(type_info);
437 return AVERROR(ENOMEM);
438 }
439
440 g_ort->GetDimensions(tensor_info, dims, num_dims);
441 g_ort->GetTensorElementType(tensor_info, &tensor_type);
442
443 if (dims[0] > 1) {
445 "ONNX model has fixed batch size %"PRId64", but the backend "
446 "only supports a batch size of 1\n", dims[0]);
447 av_free(dims);
448 g_ort->ReleaseTypeInfo(type_info);
449 return AVERROR(ENOSYS);
450 }
451
452 for (size_t i = 1; i < num_dims; i++) {
453 if (dims[i] > INT_MAX) {
455 "ONNX model input dimension %zu (%"PRId64") is too large to be represented\n",
456 i, dims[i]);
457 av_free(dims);
458 g_ort->ReleaseTypeInfo(type_info);
459 return AVERROR(ENOSYS);
460 }
461 }
462
463 /*
464 * The ONNX backend assumes a 4-D NCHW input tensor (the rank check
465 * above already rejects anything else).
466 */
467 input->layout = DL_NCHW;
468 input->dims[0] = dims[0] > 0 ? dims[0] : 1;
469 input->dims[1] = dims[1] > 0 ? dims[1] : 3;
470 input->dims[2] = dims[2] > 0 ? dims[2] : -1;
471 input->dims[3] = dims[3] > 0 ? dims[3] : -1;
472
473 if (tensor_type == ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT) {
474 input->dt = DNN_FLOAT;
475 } else {
476 av_log(ctx, AV_LOG_ERROR, "Unsupported input tensor data type, only float is supported\n");
477 av_free(dims);
478 g_ort->ReleaseTypeInfo(type_info);
479 return AVERROR(ENOSYS);
480 }
481
482 /*
483 * The DCO_RGB setting below is only consulted by the dnn_detect and dnn_classify;
484 * the dnn_processing path lets the source AVFrame pixel format determine the
485 * tensor channel order, so both RGB24 and BGR24 inputs work transparently
486 * for that flow.
487 */
488 input->order = DCO_RGB;
489 av_free(dims);
490 g_ort->ReleaseTypeInfo(type_info);
491
492 onnx_model->input_info = *input;
493 onnx_model->input_resolved = 1;
494 return 0;
495}
496
497static int fill_model_input_onnx(ONNXModel *onnx_model, ONNXRequestItem *request)
498{
499 LastLevelTaskItem *lltask = NULL;
500 TaskItem *task = NULL;
501 ONNXInferRequest *infer_request = NULL;
502 DNNData input = { 0 };
503 DnnContext *ctx = onnx_model->ctx;
504 int ret, width_idx, height_idx, channel_idx;
505 int64_t input_shape[4];
506 size_t input_tensor_size;
507 OrtMemoryInfo *memory_info;
508 OrtStatus *status;
509
510 lltask = (LastLevelTaskItem *)ff_queue_pop_front(onnx_model->lltask_queue);
511 if (!lltask) {
512 ret = AVERROR(EINVAL);
513 goto err;
514 }
515 request->lltask = lltask;
516 task = lltask->task;
517 infer_request = request->infer_request;
518
519 ret = get_input_onnx(&onnx_model->model, &input, task->input_name);
520 if (ret != 0) {
521 goto err;
522 }
523
524 width_idx = dnn_get_width_idx_by_layout(input.layout);
525 height_idx = dnn_get_height_idx_by_layout(input.layout);
526 channel_idx = dnn_get_channel_idx_by_layout(input.layout);
527
528 if (input.dims[height_idx] < 0)
529 input.dims[height_idx] = task->in_frame->height;
530 if (input.dims[width_idx] < 0)
531 input.dims[width_idx] = task->in_frame->width;
532
533 if (input.dims[0] <= 0 || input.dims[channel_idx] <= 0 ||
534 input.dims[height_idx] <= 0 || input.dims[width_idx] <= 0) {
535 av_log(ctx, AV_LOG_ERROR, "ONNX input tensor has a non-positive dimension\n");
536 ret = AVERROR(EINVAL);
537 goto err;
538 }
539
540 ret = av_image_check_size((unsigned)input.dims[width_idx],
541 (unsigned)input.dims[height_idx], 0, ctx);
542 if (ret < 0) {
543 av_log(ctx, AV_LOG_ERROR, "ONNX input image dimensions %dx%d are not supported\n",
544 input.dims[width_idx], input.dims[height_idx]);
545 goto err;
546 }
547
548 input_shape[0] = input.dims[0];
549 input_shape[1] = input.dims[channel_idx];
550 input_shape[2] = input.dims[height_idx];
551 input_shape[3] = input.dims[width_idx];
552
553#if CONFIG_DNN_ONNX_D3D12
554 /*
555 * task->in_frame may lack hw_frames_ctx (e.g. get_output_onnx()'s
556 * shape probe); such frames fall through to the host-memory tensor
557 * path, which still works via the DML EP from
558 * ff_dnn_onnx_d3d12_append_ep(), just without zero-copy.
559 */
560 if (ctx->zero_copy_negotiated && task->in_frame->hw_frames_ctx) {
561 ret = ff_dnn_onnx_d3d12_config(onnx_model->hw_ctx,
562 task->in_frame->width, task->in_frame->height,
563 task->out_frame->width, task->out_frame->height,
564 input.dt, input.layout, input.dims[channel_idx]);
565 if (ret < 0)
566 goto err;
567
568 ret = ff_dnn_onnx_d3d12_fill_input(onnx_model->hw_ctx, task->in_frame,
569 &infer_request->hw_in_tensor,
570 &infer_request->hw_out_tensor);
571 if (ret < 0)
572 goto err;
573
574 return 0;
575 }
576#endif
577
578 /*
579 * Build the byte count with checked size_t multiplications instead of
580 * multiplying four int64_t shape values in one expression.
581 */
582 input_tensor_size = sizeof(float);
583 if (av_size_mult(input_tensor_size, (size_t)input_shape[0], &input_tensor_size) < 0 ||
584 av_size_mult(input_tensor_size, (size_t)input_shape[1], &input_tensor_size) < 0 ||
585 av_size_mult(input_tensor_size, (size_t)input_shape[2], &input_tensor_size) < 0 ||
586 av_size_mult(input_tensor_size, (size_t)input_shape[3], &input_tensor_size) < 0) {
587 av_log(ctx, AV_LOG_ERROR, "ONNX input tensor size overflows\n");
588 ret = AVERROR(EINVAL);
589 goto err;
590 }
591
592 input.data = av_malloc(input_tensor_size);
593 if (!input.data) {
594 ret = AVERROR(ENOMEM);
595 goto err;
596 }
597 infer_request->input_data = input.data;
598
599 switch (onnx_model->model.func_type) {
601 input.scale = 255;
602 if (task->do_ioproc) {
603 if (onnx_model->model.frame_pre_proc != NULL) {
604 ret = onnx_model->model.frame_pre_proc(task->in_frame, &input,
605 onnx_model->model.filter_ctx);
606 } else {
607 ret = ff_proc_from_frame_to_dnn(task->in_frame, &input, ctx);
608 }
609 if (ret < 0)
610 goto err;
611 }
612 break;
614 ret = ff_frame_to_dnn_detect(task->in_frame, &input, ctx);
615 if (ret < 0)
616 goto err;
617 break;
619 ret = ff_frame_to_dnn_classify(task->in_frame, &input, lltask->bbox_index, ctx);
620 if (ret < 0)
621 goto err;
622 break;
623 default:
624 avpriv_report_missing_feature(ctx, "model function type %d", onnx_model->model.func_type);
625 ret = AVERROR(ENOSYS);
626 goto err;
627 }
628
629 status = g_ort->CreateCpuMemoryInfo(OrtArenaAllocator, OrtMemTypeDefault, &memory_info);
630 if (status != NULL) {
631 ret = AVERROR(ENOMEM);
632 goto err;
633 }
634
635 status = g_ort->CreateTensorWithDataAsOrtValue(
636 memory_info, input.data, input_tensor_size,
637 input_shape, 4, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT,
638 &infer_request->input_tensor);
639
640 g_ort->ReleaseMemoryInfo(memory_info);
641
642 if (status != NULL) {
643 const char *msg = g_ort->GetErrorMessage(status);
644 av_log(ctx, AV_LOG_ERROR, "Failed to create input tensor: %s\n", msg);
645 g_ort->ReleaseStatus(status);
646 ret = AVERROR(ENOMEM);
647 goto err;
648 }
649
650 return 0;
651
652err:
653 onnx_free_request(infer_request);
654 return ret;
655}
656
657static int onnx_start_inference(void *args)
658{
659 ONNXRequestItem *request = (ONNXRequestItem *)args;
660 ONNXInferRequest *infer_request = NULL;
661 LastLevelTaskItem *lltask = NULL;
662 TaskItem *task = NULL;
663 ONNXModel *onnx_model = NULL;
665 OrtStatus *status;
666 const char *input_names[1];
668
669 if (!request) {
670 av_log(NULL, AV_LOG_ERROR, "ONNXRequestItem is NULL\n");
671 return AVERROR(EINVAL);
672 }
673
674 infer_request = request->infer_request;
675 lltask = request->lltask;
676 task = lltask->task;
677 onnx_model = (ONNXModel *)task->model;
678 ctx = onnx_model->ctx;
679
680 if (!task->input_name || !task->output_names || !task->output_names[0]) {
682 "ONNX backend: input/output tensor name was not resolved at load time\n");
683 return AVERROR(EINVAL);
684 }
685
686#if CONFIG_DNN_ONNX_D3D12
687 if (infer_request->hw_in_tensor) {
688 if (!infer_request->hw_out_tensor) {
689 av_log(ctx, AV_LOG_ERROR, "D3D12 output tensor is NULL\n");
690 return DNN_GENERIC_ERROR;
691 }
692 } else
693#endif
694 if (!infer_request->input_tensor) {
695 av_log(ctx, AV_LOG_ERROR, "Input tensor is NULL\n");
696 return DNN_GENERIC_ERROR;
697 }
698
699 if (!onnx_model->output_resolved) {
700 size_t output_count = 0;
701 int found_output = 0;
702
703 status = g_ort->SessionGetOutputCount(onnx_model->session, &output_count);
704 if (status != NULL) {
705 const char *msg = g_ort->GetErrorMessage(status);
706 av_log(ctx, AV_LOG_ERROR, "Failed to get output count: %s\n", msg);
707 g_ort->ReleaseStatus(status);
708 return AVERROR(EINVAL);
709 }
710
711 for (uint32_t req = 0; req < task->nb_output; req++) {
712 found_output = 0;
713 for (size_t i = 0; i < output_count; i++) {
714 char *name = NULL;
715 status = g_ort->SessionGetOutputName(onnx_model->session, i,
716 onnx_model->allocator, &name);
717 if (status != NULL) {
718 g_ort->ReleaseStatus(status);
719 continue;
720 }
721 if (!strcmp(name, task->output_names[req]))
722 found_output = 1;
723 onnx_model->allocator->Free(onnx_model->allocator, name);
724 if (found_output)
725 break;
726 }
727 if (!found_output) {
729 "Output name '%s' not found in ONNX model\n",
730 task->output_names[req]);
731 return AVERROR(EINVAL);
732 }
733 }
734
735 onnx_model->output_resolved = 1;
736 }
737
738 input_names[0] = task->input_name;
739
740#if CONFIG_DNN_ONNX_D3D12
741 if (infer_request->hw_in_tensor) {
742 return ff_dnn_onnx_d3d12_run(onnx_model->hw_ctx, onnx_model->session,
743 input_names[0], task->output_names[0],
744 infer_request->hw_in_tensor,
745 infer_request->hw_out_tensor);
746 }
747#endif
748
749 /* ORT writes task->nb_output result handles into this array; it must be
750 * allocated (and NULL-initialised) before Run() so ORT owns each slot. */
751 av_freep(&infer_request->output_tensors);
752 infer_request->output_tensors = av_calloc(task->nb_output,
753 sizeof(*infer_request->output_tensors));
754 if (!infer_request->output_tensors) {
755 infer_request->nb_outputs = 0;
756 return AVERROR(ENOMEM);
757 }
758 infer_request->nb_outputs = task->nb_output;
759
760 status = g_ort->Run(onnx_model->session, NULL,
761 input_names, (const OrtValue *const *)&infer_request->input_tensor, 1,
762 task->output_names, task->nb_output, infer_request->output_tensors);
763
764 if (status != NULL) {
765 const char *msg = g_ort->GetErrorMessage(status);
766 av_log(ctx, AV_LOG_ERROR, "ONNX inference failed: %s\n", msg);
767 g_ort->ReleaseStatus(status);
768 goto err;
769 }
770
771 return 0;
772
773err:
774 av_freep(&infer_request->output_tensors);
775 infer_request->nb_outputs = 0;
776 return ret;
777}
778
779static void infer_completion_callback(void *args)
780{
781 ONNXRequestItem *request = (ONNXRequestItem *)args;
782 LastLevelTaskItem *lltask = request->lltask;
783 TaskItem *task = lltask->task;
785 ONNXInferRequest *infer_request = request->infer_request;
786 ONNXModel *onnx_model = (ONNXModel *)task->model;
787 DnnContext *ctx = onnx_model->ctx;
788 OrtTensorTypeAndShapeInfo *tensor_info;
789 ONNXTensorElementDataType tensor_type;
790 size_t num_dims;
791 int64_t *dims;
792 OrtStatus *status;
793 int ret;
794
795#if CONFIG_DNN_ONNX_D3D12
796 if (infer_request->hw_in_tensor) {
797 ret = ff_dnn_onnx_d3d12_writeback(onnx_model->hw_ctx, task->out_frame);
798 if (ret < 0)
799 av_log(ctx, AV_LOG_ERROR, "D3D12 writeback failed (%d)\n", ret);
800 else
801 task->inference_done++;
802 goto err;
803 }
804#endif
805
806 outputs = av_calloc(infer_request->nb_outputs, sizeof(*outputs));
807 if (!outputs) {
808 av_log(ctx, AV_LOG_ERROR, "Failed to allocate output DNNData array\n");
809 goto err;
810 }
811
812 for (uint32_t i = 0; i < infer_request->nb_outputs; i++) {
813 status = g_ort->GetTensorTypeAndShape(infer_request->output_tensors[i],
814 &tensor_info);
815 if (status != NULL) {
816 av_log(ctx, AV_LOG_ERROR, "Failed to get output tensor[%u] type/shape\n", i);
817 g_ort->ReleaseStatus(status);
818 goto err;
819 }
820
821 status = g_ort->GetDimensionsCount(tensor_info, &num_dims);
822 if (status != NULL) {
823 av_log(ctx, AV_LOG_ERROR, "Failed to get output tensor[%u] dimension count\n", i);
824 g_ort->ReleaseStatus(status);
825 g_ort->ReleaseTensorTypeAndShapeInfo(tensor_info);
826 goto err;
827 }
828
829 dims = av_malloc(num_dims * sizeof(int64_t));
830 if (!dims) {
831 av_log(ctx, AV_LOG_ERROR, "Failed to allocate dims array\n");
832 g_ort->ReleaseTensorTypeAndShapeInfo(tensor_info);
833 goto err;
834 }
835
836 status = g_ort->GetDimensions(tensor_info, dims, num_dims);
837 if (status != NULL) {
838 av_log(ctx, AV_LOG_ERROR, "Failed to get output tensor[%u] dimensions\n", i);
839 g_ort->ReleaseStatus(status);
840 av_free(dims);
841 g_ort->ReleaseTensorTypeAndShapeInfo(tensor_info);
842 goto err;
843 }
844
845 for (size_t d = 0; d < num_dims; d++) {
846 if (dims[d] < 0 || dims[d] > INT_MAX) {
848 "Output tensor[%u] dimension %zu (%"PRId64") is out of representable range\n",
849 i, d, dims[d]);
850 av_free(dims);
851 g_ort->ReleaseTensorTypeAndShapeInfo(tensor_info);
852 goto err;
853 }
854 }
855
856 status = g_ort->GetTensorElementType(tensor_info, &tensor_type);
857 if (status != NULL) {
858 av_log(ctx, AV_LOG_ERROR, "Failed to get output tensor[%u] element type\n", i);
859 g_ort->ReleaseStatus(status);
860 av_free(dims);
861 g_ort->ReleaseTensorTypeAndShapeInfo(tensor_info);
862 goto err;
863 }
864 if (tensor_type == ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT) {
865 outputs[i].dt = DNN_FLOAT;
866 } else {
868 "Unsupported output tensor[%u] data type, only float supported\n", i);
869 av_free(dims);
870 g_ort->ReleaseTensorTypeAndShapeInfo(tensor_info);
871 goto err;
872 }
873
874 if (i == 0 && ctx->zero_copy_negotiated && onnx_model->model.func_type == DFT_PROCESS_FRAME &&
875 (num_dims != 4 || dims[1] != 1)) {
877 "D3D12 zero-copy requires a [1,1,H,W] output tensor, got rank %zu with dims[1]=%"PRId64"\n",
878 num_dims, num_dims > 1 ? dims[1] : 0);
879 av_free(dims);
880 g_ort->ReleaseTensorTypeAndShapeInfo(tensor_info);
881 goto err;
882 }
883
884 /* Output is interpreted as NCHW, matching the input assumption. */
885 outputs[i].layout = DL_NCHW;
886 outputs[i].order = DCO_RGB;
887
888 if (num_dims == 4) {
889 outputs[i].dims[0] = dims[0];
890 outputs[i].dims[1] = dims[1];
891 outputs[i].dims[2] = dims[2];
892 outputs[i].dims[3] = dims[3];
893 } else if (num_dims == 3) {
894 /* Some detection models output [1, N, D]; promote it to [1, 1, N, D]. */
895 outputs[i].dims[0] = dims[0];
896 outputs[i].dims[1] = 1;
897 outputs[i].dims[2] = dims[1];
898 outputs[i].dims[3] = dims[2];
899 } else if (num_dims == 2) {
900 /* [N, C] -> [N, C, 1, 1] */
901 outputs[i].dims[0] = dims[0];
902 outputs[i].dims[1] = dims[1];
903 outputs[i].dims[2] = 1;
904 outputs[i].dims[3] = 1;
905 } else if (num_dims == 1) {
906 /* [C] -> [1, C, 1, 1] */
907 outputs[i].dims[0] = 1;
908 outputs[i].dims[1] = dims[0];
909 outputs[i].dims[2] = 1;
910 outputs[i].dims[3] = 1;
911 } else {
913 "Support for %zu-dimensional output (tensor[%u])", num_dims, i);
914 av_free(dims);
915 g_ort->ReleaseTensorTypeAndShapeInfo(tensor_info);
916 goto err;
917 }
918
919 if (outputs[i].dims[0] != 1) {
921 "Output tensor[%u] batch size %d unsupported, must be 1\n",
922 i, outputs[i].dims[0]);
923 av_free(dims);
924 g_ort->ReleaseTensorTypeAndShapeInfo(tensor_info);
925 goto err;
926 }
927
928 status = g_ort->GetTensorMutableData(infer_request->output_tensors[i], &outputs[i].data);
929 if (status != NULL) {
930 av_log(ctx, AV_LOG_ERROR, "Failed to get tensor[%u] data pointer\n", i);
931 g_ort->ReleaseStatus(status);
932 av_free(dims);
933 g_ort->ReleaseTensorTypeAndShapeInfo(tensor_info);
934 goto err;
935 }
936
937 av_free(dims);
938 g_ort->ReleaseTensorTypeAndShapeInfo(tensor_info);
939 }
940
941 switch (onnx_model->model.func_type) {
943 if (task->do_ioproc) {
944 outputs[0].scale = 255;
945 if (onnx_model->model.frame_post_proc != NULL) {
946 onnx_model->model.frame_post_proc(task->out_frame, outputs, onnx_model->model.filter_ctx);
947 } else {
949 }
950 } else {
953 }
954 break;
956 ret = onnx_model->model.detect_post_proc(task->in_frame, outputs,
957 infer_request->nb_outputs,
958 onnx_model->model.filter_ctx);
959 if (ret < 0)
960 goto err;
961 break;
963 if (!onnx_model->model.classify_post_proc) {
964 av_log(ctx, AV_LOG_ERROR, "classify filter needs to provide classify_post_proc\n");
965 goto err;
966 }
967 onnx_model->model.classify_post_proc(task->in_frame, outputs,
968 request->lltask->bbox_index,
969 onnx_model->model.filter_ctx);
970 break;
971 default:
972 avpriv_report_missing_feature(ctx, "model function type %d", onnx_model->model.func_type);
973 goto err;
974 }
975
976 task->inference_done++;
977
978err:
980 av_freep(&request->lltask);
981 onnx_free_request(infer_request);
982 if (ff_safe_queue_push_back(onnx_model->request_queue, request) < 0) {
983 destroy_request_item(&request);
984 av_log(ctx, AV_LOG_ERROR, "Unable to push back request_queue.\n");
985 }
986}
987
988static int execute_model_onnx(ONNXModel *onnx_model, ONNXRequestItem *request, Queue *lltask_queue)
989{
990 LastLevelTaskItem *lltask;
991 TaskItem *task = NULL;
992 int ret = 0;
993
994 if (ff_queue_size(lltask_queue) == 0) {
995 if (ff_safe_queue_push_back(onnx_model->request_queue, request) < 0) {
996 destroy_request_item(&request);
997 }
998 return 0;
999 }
1000
1001 /* Drain all lltasks for the current frame. */
1002 for (;;) {
1003 lltask = (LastLevelTaskItem *)ff_queue_peek_front(lltask_queue);
1004 if (lltask == NULL) {
1005 av_log(NULL, AV_LOG_ERROR, "Failed to get LastLevelTaskItem\n");
1006 ret = AVERROR(EINVAL);
1007 goto err;
1008 }
1009 task = lltask->task;
1010
1011 ret = fill_model_input_onnx(onnx_model, request);
1012 if (ret != 0) {
1013 goto err;
1014 }
1015
1016 if (task->async) {
1017 avpriv_report_missing_feature(onnx_model->ctx, "ONNX async inference");
1018 ret = AVERROR(ENOSYS);
1019 goto err;
1020 }
1021
1022 ret = onnx_start_inference((void *)request);
1023 if (ret != 0) {
1024 goto err;
1025 }
1027
1028 if (ff_queue_size(lltask_queue) == 0) {
1029 break;
1030 }
1031 request = (ONNXRequestItem *)ff_safe_queue_pop_front(onnx_model->request_queue);
1032 }
1033
1034 return (task->inference_done == task->inference_todo) ? 0 : DNN_GENERIC_ERROR;
1035
1036err:
1037 av_freep(&request->lltask);
1039 if (ff_safe_queue_push_back(onnx_model->request_queue, request) < 0) {
1040 destroy_request_item(&request);
1041 }
1042 return ret;
1043}
1044
1045static int get_output_onnx(DNNModel *model, const char *input_name, int input_width, int input_height,
1046 const char *output_name, int *output_width, int *output_height)
1047{
1048 int ret = 0;
1049 ONNXModel *onnx_model = (ONNXModel *)model;
1050 DnnContext *ctx = onnx_model->ctx;
1051 TaskItem task = { 0 };
1052 ONNXRequestItem *request = NULL;
1053 DNNExecBaseParams exec_params = {
1054 .input_name = input_name,
1055 .output_names = &output_name,
1056 .nb_output = 1,
1057 .in_frame = NULL,
1058 .out_frame = NULL,
1059 };
1060
1061 ret = ff_dnn_fill_gettingoutput_task(&task, &exec_params, onnx_model, input_height, input_width, ctx);
1062 if (ret != 0) {
1063 goto err;
1064 }
1065
1067 if (ret != 0) {
1068 av_log(ctx, AV_LOG_ERROR, "Unable to extract last level task from task.\n");
1069 goto err;
1070 }
1071
1072 request = (ONNXRequestItem *)ff_safe_queue_pop_front(onnx_model->request_queue);
1073 if (!request) {
1074 av_log(ctx, AV_LOG_ERROR, "Unable to get infer request.\n");
1075 ret = AVERROR(EINVAL);
1076 goto err;
1077 }
1078
1079 ret = execute_model_onnx(onnx_model, request, onnx_model->lltask_queue);
1080 *output_width = task.out_frame->width;
1081 *output_height = task.out_frame->height;
1082
1083err:
1084 av_frame_free(&task.out_frame);
1085 av_frame_free(&task.in_frame);
1086 return ret;
1087}
1088
1090{
1091 ONNXInferRequest *request = av_mallocz(sizeof(ONNXInferRequest));
1092 if (!request)
1093 return NULL;
1094 return request;
1095}
1096
1098{
1099 DNNModel *model = NULL;
1100 ONNXModel *onnx_model = NULL;
1101 ONNXRequestItem *item = NULL;
1102 ONNXOptions *options = &ctx->onnx_option;
1103 OrtStatus *status;
1104
1106 if (!g_ort) {
1107 av_log(ctx, AV_LOG_ERROR, "Failed to get ONNX Runtime API\n");
1108 return NULL;
1109 }
1110
1111 onnx_model = av_mallocz(sizeof(ONNXModel));
1112 if (!onnx_model)
1113 return NULL;
1114
1115 model = &onnx_model->model;
1116 onnx_model->ctx = ctx;
1117
1118 if (ctx->nireq > 1) {
1120 "nireq=%d is not supported by the ONNX Runtime backend, "
1121 "which only allocates a single, synchronous inference "
1122 "request. Rolling back to nireq=1.\n", ctx->nireq);
1123 }
1124 ctx->nireq = 1;
1125
1126 status = g_ort->CreateEnv(ORT_LOGGING_LEVEL_WARNING, "FFmpeg", &onnx_model->env);
1127 if (status != NULL) {
1128 av_log(ctx, AV_LOG_ERROR, "Failed to create ONNX Runtime environment\n");
1129 goto fail;
1130 }
1131
1132 status = g_ort->CreateSessionOptions(&onnx_model->session_options);
1133 if (status != NULL) {
1134 av_log(ctx, AV_LOG_ERROR, "Failed to create session options\n");
1135 goto fail;
1136 }
1137
1138 if (options->num_threads > 0 &&
1139 (!ctx->device || av_strcasecmp(ctx->device, "cpu") == 0)) {
1140 g_ort->SetIntraOpNumThreads(onnx_model->session_options, options->num_threads);
1141 }
1142 g_ort->SetSessionGraphOptimizationLevel(onnx_model->session_options, ORT_ENABLE_ALL);
1143
1144 /*
1145 * device=dml is registered below exactly like cuda/vitisai, but with
1146 * one extra detail: if ctx->hw_frames_ctx is already set,
1147 * append_d3d12_dml_ep() binds the DirectML EP directly to that D3D12
1148 * device, instead of letting ONNX Runtime pick its own default one.
1149 */
1150 if (ctx->device && av_strcasecmp(ctx->device, "cpu") != 0) {
1151 if (av_strcasecmp(ctx->device, "cuda") == 0) {
1152 if (g_ort->SessionOptionsAppendExecutionProvider_CUDA) {
1153 OrtCUDAProviderOptions cuda_options;
1154 memset(&cuda_options, 0, sizeof(cuda_options));
1155 cuda_options.device_id = ctx->device_id;
1156
1157 status = g_ort->SessionOptionsAppendExecutionProvider_CUDA(
1158 onnx_model->session_options, &cuda_options);
1159 if (status != NULL) {
1160 const char *msg = g_ort->GetErrorMessage(status);
1161 av_log(ctx, AV_LOG_WARNING, "Failed to enable CUDA (device %d): %s. Falling back to CPU\n",
1162 ctx->device_id, msg);
1163 g_ort->ReleaseStatus(status);
1164 } else {
1165 av_log(ctx, AV_LOG_INFO, "Using CUDA execution provider on device %d\n", ctx->device_id);
1166 }
1167 } else {
1168 av_log(ctx, AV_LOG_WARNING, "CUDA provider function not available in this ONNX Runtime API version. Falling back to CPU\n");
1169 }
1170 } else if (av_strcasecmp(ctx->device, "dml") == 0) {
1171#ifdef _WIN32
1172 const char* dml_options_keys[] = {"device_id"};
1173 const char* dml_options_values[] = {NULL};
1174 char device_id_str[32];
1175 snprintf(device_id_str, sizeof(device_id_str), "%d", ctx->device_id);
1176 dml_options_values[0] = device_id_str;
1177
1178 /* DirectML cannot use ORT's memory-pattern optimizer and only
1179 * supports sequential execution. */
1180 status = g_ort->SetSessionExecutionMode(onnx_model->session_options, ORT_SEQUENTIAL);
1181 if (status)
1182 g_ort->ReleaseStatus(status);
1183 status = g_ort->DisableMemPattern(onnx_model->session_options);
1184 if (status)
1185 g_ort->ReleaseStatus(status);
1186
1187#if CONFIG_DNN_ONNX_D3D12
1188 /* No-op unless the filter already set ctx->hw_frames_ctx via
1189 * ff_dnn_set_hw_frames_ctx(); if set, binds the DirectML EP to
1190 * that device so tensor I/O can stay in VRAM. */
1191 append_d3d12_dml_ep(onnx_model);
1192#endif
1193
1194 if (ctx->zero_copy_negotiated) {
1195 /* Device-bound DirectML EP already appended above. */
1196 } else if (g_ort->SessionOptionsAppendExecutionProvider) {
1197 status = g_ort->SessionOptionsAppendExecutionProvider(
1198 onnx_model->session_options, "DML",
1199 dml_options_keys, dml_options_values, 1);
1200 if (status != NULL) {
1201 const char *msg = g_ort->GetErrorMessage(status);
1202 av_log(ctx, AV_LOG_WARNING, "Failed to enable DirectML (device %d): %s. Falling back to CPU\n",
1203 ctx->device_id, msg);
1204 g_ort->ReleaseStatus(status);
1205 } else {
1206 av_log(ctx, AV_LOG_INFO, "Using DirectML execution provider on device %d\n", ctx->device_id);
1207 }
1208 } else {
1209 av_log(ctx, AV_LOG_WARNING, "DirectML provider function not available in this ONNX Runtime API version. Falling back to CPU\n");
1210 }
1211#else
1212 av_log(ctx, AV_LOG_WARNING, "DirectML is only available on Windows. Falling back to CPU\n");
1213#endif
1214 } else if (av_strcasecmp(ctx->device, "vitisai") == 0) {
1215 if (g_ort->SessionOptionsAppendExecutionProvider) {
1216 status = g_ort->SessionOptionsAppendExecutionProvider(
1217 onnx_model->session_options, "VitisAI",
1218 NULL, NULL, 0);
1219 if (status != NULL) {
1220 const char *msg = g_ort->GetErrorMessage(status);
1222 "Failed to enable VitisAI EP: %s. Falling back to CPU\n", msg);
1223 g_ort->ReleaseStatus(status);
1224 } else {
1225 av_log(ctx, AV_LOG_INFO, "Using VitisAI execution provider (AMD Ryzen AI NPU)\n");
1226 }
1227 } else {
1229 "VitisAI provider function not available in this ONNX Runtime API version. Falling back to CPU.\n");
1230 }
1231 } else {
1232#ifdef _WIN32
1234 "Unknown device '%s'. Supported: cpu, cuda, dml, vitisai. Using CPU\n",
1235 ctx->device);
1236#else
1238 "Unknown device '%s'. Supported: cpu, cuda, vitisai. Using CPU\n",
1239 ctx->device);
1240#endif
1241 }
1242 } else {
1243 av_log(ctx, AV_LOG_INFO, "Using CPU execution provider\n");
1244 }
1245
1246#ifdef _WIN32
1247 {
1248 wchar_t *wfilename = NULL;
1249 if (utf8towchar(ctx->model_filename, &wfilename)) {
1250 av_log(ctx, AV_LOG_ERROR, "Failed to convert model filename to UTF-16\n");
1251 goto fail;
1252 }
1253 if (!wfilename) {
1254 av_log(ctx, AV_LOG_ERROR, "Failed to convert model filename to UTF-16\n");
1255 goto fail;
1256 }
1257
1258 status = g_ort->CreateSession(onnx_model->env, wfilename,
1259 onnx_model->session_options, &onnx_model->session);
1260 av_free(wfilename);
1261 }
1262#else
1263 status = g_ort->CreateSession(onnx_model->env, ctx->model_filename,
1264 onnx_model->session_options, &onnx_model->session);
1265#endif
1266 if (status != NULL) {
1267 const char *msg = g_ort->GetErrorMessage(status);
1268 av_log(ctx, AV_LOG_ERROR, "Failed to create ONNX session: %s\n", msg);
1269 g_ort->ReleaseStatus(status);
1270 goto fail;
1271 }
1272
1273 status = g_ort->GetAllocatorWithDefaultOptions(&onnx_model->allocator);
1274 if (status != NULL) {
1275 av_log(ctx, AV_LOG_ERROR, "Failed to get allocator\n");
1276 goto fail;
1277 }
1278
1279 /*
1280 * The ONNX backend binds exactly one input tensor to Run(), so only
1281 * single-input models are supported.
1282 */
1283 {
1284 size_t input_count = 0;
1285 status = g_ort->SessionGetInputCount(onnx_model->session, &input_count);
1286 if (status != NULL) {
1287 const char *msg = g_ort->GetErrorMessage(status);
1288 av_log(ctx, AV_LOG_ERROR, "Failed to get model input count: %s\n", msg);
1289 g_ort->ReleaseStatus(status);
1290 goto fail;
1291 }
1292 if (input_count == 0) {
1293 av_log(ctx, AV_LOG_ERROR, "ONNX model exposes no input tensors\n");
1294 goto fail;
1295 }
1296 if (input_count > 1) {
1298 "ONNX model exposes %zu input tensors; the ONNX backend "
1299 "supports single-input models only.\n",
1300 input_count);
1301 goto fail;
1302 }
1303 }
1304
1305 /* Auto-detect the input tensor name when the user did not pass input=NAME. */
1306 if (!ctx->model_inputname || !*ctx->model_inputname) {
1307 char *name = NULL;
1308 status = g_ort->SessionGetInputName(onnx_model->session, 0,
1309 onnx_model->allocator, &name);
1310 if (status != NULL) {
1311 const char *msg = g_ort->GetErrorMessage(status);
1312 av_log(ctx, AV_LOG_ERROR, "Failed to get model input name: %s\n", msg);
1313 g_ort->ReleaseStatus(status);
1314 goto fail;
1315 }
1316 av_freep(&ctx->model_inputname);
1317 ctx->model_inputname = av_strdup(name);
1318 onnx_model->allocator->Free(onnx_model->allocator, name);
1319 if (!ctx->model_inputname)
1320 goto fail;
1321 av_log(ctx, AV_LOG_INFO, "Auto-detected ONNX input tensor '%s'\n",
1322 ctx->model_inputname);
1323 }
1324
1325 /* Auto-detect the output tensor name when the user did not pass output=NAME. */
1326 if (!ctx->model_outputnames) {
1327 size_t output_count = 0;
1328 char *name = NULL;
1329 status = g_ort->SessionGetOutputCount(onnx_model->session, &output_count);
1330 if (status != NULL) {
1331 const char *msg = g_ort->GetErrorMessage(status);
1332 av_log(ctx, AV_LOG_ERROR, "Failed to get model output count: %s\n", msg);
1333 g_ort->ReleaseStatus(status);
1334 goto fail;
1335 }
1336 if (output_count == 0) {
1337 av_log(ctx, AV_LOG_ERROR, "ONNX model exposes no output tensors\n");
1338 goto fail;
1339 }
1340 status = g_ort->SessionGetOutputName(onnx_model->session, 0,
1341 onnx_model->allocator, &name);
1342 if (status != NULL) {
1343 const char *msg = g_ort->GetErrorMessage(status);
1344 av_log(ctx, AV_LOG_ERROR, "Failed to get model output name: %s\n", msg);
1345 g_ort->ReleaseStatus(status);
1346 goto fail;
1347 }
1348 ctx->model_outputnames = av_calloc(1, sizeof(*ctx->model_outputnames));
1349 if (!ctx->model_outputnames) {
1350 onnx_model->allocator->Free(onnx_model->allocator, name);
1351 goto fail;
1352 }
1353 ctx->model_outputnames[0] = av_strdup(name);
1354 onnx_model->allocator->Free(onnx_model->allocator, name);
1355 if (!ctx->model_outputnames[0]) {
1356 av_freep(&ctx->model_outputnames);
1357 goto fail;
1358 }
1359 ctx->nb_outputs = 1;
1360 if (output_count == 1) {
1361 av_log(ctx, AV_LOG_INFO, "Auto-detected ONNX output tensor '%s'\n",
1362 ctx->model_outputnames[0]);
1363 } else {
1365 "ONNX model exposes %zu output tensors; auto-using index 0 ('%s'). "
1366 "Specify output=NAME to choose a different one.\n",
1367 output_count, ctx->model_outputnames[0]);
1368 }
1369 }
1370
1371 onnx_model->request_queue = ff_safe_queue_create();
1372 if (!onnx_model->request_queue) {
1373 goto fail;
1374 }
1375
1376 item = av_mallocz(sizeof(ONNXRequestItem));
1377 if (!item) {
1378 goto fail;
1379 }
1380 item->lltask = NULL;
1382 if (!item->infer_request) {
1383 av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory for ONNX inference request\n");
1384 goto fail;
1385 }
1388 item->exec_module.args = item;
1389
1390 if (ff_safe_queue_push_back(onnx_model->request_queue, item) < 0) {
1391 goto fail;
1392 }
1393 item = NULL;
1394
1395 onnx_model->task_queue = ff_queue_create();
1396 if (!onnx_model->task_queue) {
1397 goto fail;
1398 }
1399
1400 onnx_model->lltask_queue = ff_queue_create();
1401 if (!onnx_model->lltask_queue) {
1402 goto fail;
1403 }
1404
1405 model->get_input = &get_input_onnx;
1406 model->get_output = &get_output_onnx;
1407 model->filter_ctx = filter_ctx;
1408 model->func_type = func_type;
1409
1410 return model;
1411
1412fail:
1413 if (item) {
1414 destroy_request_item(&item);
1415 }
1416 dnn_free_model_onnx(&model);
1417 return NULL;
1418}
1419
1420static int dnn_execute_model_onnx(const DNNModel *model, DNNExecBaseParams *exec_params)
1421{
1422 ONNXModel *onnx_model = (ONNXModel *)model;
1423 DnnContext *ctx = onnx_model->ctx;
1424 TaskItem *task;
1425 ONNXRequestItem *request;
1426 int ret = 0;
1427
1428 ret = ff_check_exec_params(ctx, DNN_ONNX, model->func_type, exec_params);
1429 if (ret != 0) {
1430 av_log(ctx, AV_LOG_ERROR, "Exec parameter checking failed.\n");
1431 return ret;
1432 }
1433
1434 task = av_malloc(sizeof(TaskItem));
1435 if (!task) {
1436 av_log(ctx, AV_LOG_ERROR, "Unable to alloc memory for task item.\n");
1437 return AVERROR(ENOMEM);
1438 }
1439
1440 ret = ff_dnn_fill_task(task, exec_params, onnx_model, 0, 1);
1441 if (ret != 0) {
1442 av_freep(&task);
1443 av_log(ctx, AV_LOG_ERROR, "Unable to fill task.\n");
1444 return ret;
1445 }
1446
1447 ret = ff_queue_push_back(onnx_model->task_queue, task);
1448 if (ret < 0) {
1449 av_freep(&task);
1450 av_log(ctx, AV_LOG_ERROR, "Unable to push back task_queue.\n");
1451 return ret;
1452 }
1453
1454 ret = extract_lltask_from_task(model->func_type, task, onnx_model->lltask_queue, exec_params);
1455 if (ret != 0) {
1456 av_log(ctx, AV_LOG_ERROR, "Unable to extract last level task from task.\n");
1457 return ret;
1458 }
1459
1460 /* No lltasks queued, nothing to infer. */
1461 if (ff_queue_size(onnx_model->lltask_queue) == 0) {
1462 return 0;
1463 }
1464
1465 request = (ONNXRequestItem *)ff_safe_queue_pop_front(onnx_model->request_queue);
1466 if (!request) {
1467 av_log(ctx, AV_LOG_ERROR, "Unable to get infer request.\n");
1468 return AVERROR(EINVAL);
1469 }
1470
1471 return execute_model_onnx(onnx_model, request, onnx_model->lltask_queue);
1472}
1473
1475{
1476 ONNXModel *onnx_model = (ONNXModel *)model;
1477 return ff_dnn_get_result_common(onnx_model->task_queue, in, out);
1478}
1479
1480static int dnn_flush_onnx(const DNNModel *model)
1481{
1482 ONNXModel *onnx_model = (ONNXModel *)model;
1483 ONNXRequestItem *request;
1484
1485 if (ff_queue_size(onnx_model->lltask_queue) == 0)
1486 return 0;
1487
1488 request = (ONNXRequestItem *)ff_safe_queue_pop_front(onnx_model->request_queue);
1489 if (!request) {
1490 av_log(onnx_model->ctx, AV_LOG_ERROR, "Unable to get infer request.\n");
1491 return AVERROR(EINVAL);
1492 }
1493
1494 return execute_model_onnx(onnx_model, request, onnx_model->lltask_queue);
1495}
1496
1498 .clazz = DNN_DEFINE_CLASS(dnn_onnx),
1499 .type = DNN_ONNX,
1500 .load_model = dnn_load_model_onnx,
1501 .execute_model = dnn_execute_model_onnx,
1502 .get_result = dnn_get_result_onnx,
1503 .flush = dnn_flush_onnx,
1504 .free_model = dnn_free_model_onnx,
1505};
SwsAArch64OpImplParams params
Definition ops.c:51
static const AVFilterPad outputs[]
Definition af_aap.c:310
static FILE * out
static AVFormatContext * ctx
simple assert() macros that are a bit more flexible than ISO C assert().
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define FLAGS
Definition cmdutils.c:596
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
static AVFrame * frame
#define AV_NUM_DETECTION_BBOX_CLASSIFY
At most 4 classifications based on the detected bounding box.
static av_always_inline AVDetectionBBox * av_get_detection_bbox(const AVDetectionBBoxHeader *header, unsigned int idx)
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_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 int dnn_execute_model_onnx(const DNNModel *model, DNNExecBaseParams *exec_params)
const DNNModule ff_dnn_backend_onnx
static const AVOption dnn_onnx_options[]
static int dnn_flush_onnx(const DNNModel *model)
static DNNModel * dnn_load_model_onnx(DnnContext *ctx, DNNFunctionType func_type, AVFilterContext *filter_ctx)
static int get_output_onnx(DNNModel *model, const char *input_name, int input_width, int input_height, const char *output_name, int *output_width, int *output_height)
static int fill_model_input_onnx(ONNXModel *onnx_model, ONNXRequestItem *request)
static ONNXInferRequest * onnx_create_inference_request(void)
static void init_ort_api(void)
static void onnx_free_request(ONNXInferRequest *request)
static const OrtApi * g_ort
static void dnn_free_model_onnx(DNNModel **model)
static DNNAsyncStatusType dnn_get_result_onnx(const DNNModel *model, AVFrame **in, AVFrame **out)
static AVOnce g_ort_init_once
static int onnx_start_inference(void *args)
static int extract_lltask_from_task(DNNFunctionType func_type, TaskItem *task, Queue *lltask_queue, DNNExecBaseParams *exec_params)
#define OFFSET(x)
static int contain_valid_detection_bbox(AVFrame *frame)
static void destroy_request_item(ONNXRequestItem **arg)
static int execute_model_onnx(ONNXModel *onnx_model, ONNXRequestItem *request, Queue *lltask_queue)
static void infer_completion_callback(void *args)
static int get_input_onnx(DNNModel *model, DNNData *input, const char *input_name)
static int dnn_get_height_idx_by_layout(DNNLayout layout)
DNNAsyncStatusType
@ DL_NCHW
@ DNN_ONNX
DNNFunctionType
@ DFT_ANALYTICS_CLASSIFY
@ DFT_PROCESS_FRAME
@ DFT_ANALYTICS_DETECT
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_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)
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 ff_dnn_onnx_d3d12_probe(void *d3d12_device_void, DnnOnnxD3D12TensorMem mem, int *is_uma, void *log_ctx)
Check whether the D3D12/DirectML path is usable on d3d12_device, without creating any lasting state.
int ff_dnn_onnx_d3d12_writeback(DnnOnnxD3D12Ctx *ctx, AVFrame *out)
Step 3/3 of the per-frame pipeline: write ctx's compact GPU output tensor back into the luma plane of...
int ff_dnn_onnx_d3d12_sync(DnnOnnxD3D12Ctx *ctx)
Block until all work submitted to ctx's shared command queue, by the helper and by the DirectML execu...
void ff_dnn_onnx_d3d12_free(DnnOnnxD3D12Ctx **ctx)
Release a context created by ff_dnn_onnx_d3d12_create(), including any buffers configured via ff_dnn_...
int ff_dnn_onnx_d3d12_run(DnnOnnxD3D12Ctx *ctx, void *session_void, const char *in_name, const char *out_name, void *in_tensor_void, void *out_tensor_void)
Step 2/3 of the per-frame pipeline: run the model against the tensors produced by ff_dnn_onnx_d3d12_f...
DnnOnnxD3D12Ctx * ff_dnn_onnx_d3d12_create(void *d3d12_device_void, DnnOnnxD3D12TensorMem mem, void *log_ctx)
Create a helper context bound to d3d12_device: a DirectML device and a single dedicated DIRECT comman...
int ff_dnn_onnx_d3d12_append_ep(DnnOnnxD3D12Ctx *ctx, void *session_options_void)
Append the DirectML execution provider to session_options, built on top of ctx's DirectML device and ...
int ff_dnn_onnx_d3d12_config(DnnOnnxD3D12Ctx *ctx, int in_w, int in_h, int out_w, int out_h, DNNDataType dt, DNNLayout layout, int channels)
Configure ctx's buffers for the given model input/output tensor.
int ff_dnn_onnx_d3d12_fill_input(DnnOnnxD3D12Ctx *ctx, const AVFrame *in, void **in_tensor, void **out_tensor)
Step 1/3 of the per-frame pipeline: extract the luma plane of the D3D12 NV12 input frame into ctx's c...
Pure C interface to the D3D12/DirectML GPU pipeline helper used by the ONNX Runtime backend and the d...
@ DNN_ONNX_D3D12_TENSOR_GPU
int ret
Definition ffplay.c:391
#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
AVFrameSideData * av_frame_get_side_data(const AVFrame *frame, enum AVFrameSideDataType type)
Definition frame.c:662
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition frame.c:65
@ AV_FRAME_DATA_DETECTION_BBOXES
Bounding boxes for object detection and classification, as described by AVDetectionBBoxHeader.
Definition frame.h:194
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#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
int av_size_mult(size_t a, size_t b, size_t *r)
Multiply two size_t values checking for overflow.
Definition mem.c:671
int av_image_check_size(unsigned int w, unsigned int h, int log_offset, void *log_ctx)
Check if the given dimension of an image is valid, meaning that all bytes of the image can be address...
Definition imgutils.c:318
int av_strcasecmp(const char *a, const char *b)
Locale-independent case-insensitive compare.
Definition avstring.c:208
int av_strncasecmp(const char *a, const char *b, size_t n)
Locale-independent case-insensitive compare.
Definition avstring.c:218
@ AV_HWDEVICE_TYPE_D3D12VA
Definition hwcontext.h:40
An API-specific header for AV_HWDEVICE_TYPE_D3D12VA.
misc image utilities
const char * arg
Definition jacosubdec.c:66
#define AVFILTER_DEFINE_CLASS(fname)
Definition filters.h:493
void avpriv_report_missing_feature(void *avc, const char *msg,...) av_printf_format(2
Log a generic warning message about a missing feature.
#define AVOnce
Definition thread.h:202
static int ff_thread_once(char *control, void(*routine)(void))
Definition thread.h:205
#define AV_ONCE_INIT
Definition thread.h:203
uint64_t layout
void * av_calloc(size_t nmemb, size_t size)
Definition mem.c:370
Memory handling functions.
#define av_strdup(s)
Definition ops_static.c:55
#define av_malloc(s)
Definition ops_static.c:52
AVOptions.
const char * name
Definition qsvenc.c:142
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
static const uint8_t header[24]
Definition sdr2.c:68
This struct is allocated as AVHWDeviceContext.hwctx.
ID3D12Device * device
Device used for objects creation and access.
char detect_label[AV_DETECTION_BBOX_LABEL_NAME_MAX_SIZE]
Detect result with confidence.
int x
Distance in pixels from the left/top edge of the frame, together with width and height,...
uint32_t classify_count
An instance of a filter.
Definition avfilter.h:279
Structure to hold side data for an AVFrame.
Definition frame.h:334
size_t size
Definition frame.h:337
uint8_t * data
Definition frame.h:336
This structure describes decoded (raw) audio or video data.
Definition frame.h:479
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:776
int height
Definition frame.h:551
This struct aggregates all the (hardware/vendor-specific) "high-level" state, i.e.
Definition hwcontext.h:63
void * hwctx
The format-specific data, allocated and freed by libavutil along with this context.
Definition hwcontext.h:88
enum AVHWDeviceType type
This field identifies the underlying API used for hardware access.
Definition hwcontext.h:75
This struct describes a set or pool of "hardware" frames (i.e.
Definition hwcontext.h:118
AVHWDeviceContext * device_ctx
The parent AVHWDeviceContext.
Definition hwcontext.h:137
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
ClassifyPostProc classify_post_proc
FramePrePostProc frame_post_proc
DetectPostProc detect_post_proc
AVFilterContext * filter_ctx
DNNFunctionType func_type
OrtValue * input_tensor
OrtValue ** output_tensors
Queue * task_queue
DnnContext * ctx
DNNData input_info
OrtSessionOptions * session_options
SafeQueue * request_queue
OrtSession * session
DNNModel model
OrtAllocator * allocator
Queue * lltask_queue
DNNAsyncExecModule exec_module
ONNXInferRequest * infer_request
LastLevelTaskItem * lltask
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
uint32_t inference_done
AVFrame * in_frame
const char ** output_names
uint8_t do_ioproc
uint32_t inference_todo
const char * input_name
AVFrame * out_frame
uint32_t nb_output
#define av_free(p)
#define av_mallocz(s)
#define av_freep(p)
#define av_log(a,...)
static FilteringContext * filter_ctx
Definition transcode.c:52