Monado OpenXR Runtime
Loading...
Searching...
No Matches
onnx_wrapper.hpp
Go to the documentation of this file.
1// Copyright 2022, Collabora, Ltd.
2// Copyright 2026, Beyley Cardellio
3// SPDX-License-Identifier: BSL-1.0
4/*!
5 * @file
6 * @brief onnxruntime wrapper objects and functions.
7 * @author Beyley Cardellio <ep1cm1n10n123@gmail.com>
8 * @author Moshi Turner <moshiturner@protonmail.com>
9 * @author Jakob Bornecrantz <jakob@collabora.com>
10 * @ingroup aux_onnxruntime
11 */
12
13#pragma once
14
15#include "xrt/xrt_config_build.h"
16
17#include "util/u_logging.h"
18
19#include <concepts>
20#include <onnxruntime_c_api.h>
21#include <source_location>
22#include <string>
23#include <utility>
24#include <stdexcept>
25
26
27#define ONNX_TRACE(onnx, ...) U_LOG_IFL_T(onnx->log_level, __VA_ARGS__)
28#define ONNX_DEBUG(onnx, ...) U_LOG_IFL_D(onnx->log_level, __VA_ARGS__)
29#define ONNX_INFO(onnx, ...) U_LOG_IFL_I(onnx->log_level, __VA_ARGS__)
30#define ONNX_WARN(onnx, ...) U_LOG_IFL_W(onnx->log_level, __VA_ARGS__)
31#define ONNX_ERROR(onnx, ...) U_LOG_IFL_E(onnx->log_level, __VA_ARGS__)
32
33namespace xrt::auxiliary::onnx {
34
35class Error : public std::runtime_error
36{
37public:
38 explicit Error(const std::string &message) : std::runtime_error(message) {}
39};
40
42{
43public:
44 enum u_logging_level log_level = U_LOGGING_INFO;
45
46 const OrtApi *api = nullptr;
47 OrtEnv *env = nullptr;
48
49 OrtMemoryInfo *meminfo = nullptr;
50 OrtSession *session = nullptr;
51
52 OnnxWrapper() {}
53
54 OnnxWrapper(enum u_logging_level log_level, std::string path, std::string env_name = "monado_onnx");
55
56 template <typename Fn>
57 inline void
58 ort_safe(Fn &&fn, std::source_location loc = std::source_location::current())
59 {
60 assert(this->api != nullptr);
61
62 OrtStatus *status = std::forward<Fn>(fn)(this->api);
63 if (status != nullptr) {
64 std::string msg = this->api->GetErrorMessage(status);
65 ONNX_ERROR(this, "[%s:%u]: %s", loc.file_name(), loc.line(), msg.c_str());
66 this->api->ReleaseStatus(status);
67 throw onnx::Error(msg); // throw it as an exception.
68 }
69 }
70
72};
73
74#define ORT_SAFE(wrap, fn) (wrap).ort_safe([&](const OrtApi *api) { return api->fn; })
75
76}; // namespace xrt::auxiliary::onnx
Definition onnx_wrapper.hpp:36
Definition onnx_wrapper.hpp:42
u_logging_level
Logging level enum.
Definition u_logging.h:45
@ U_LOGGING_INFO
Info messages: not very verbose, not indicating a problem.
Definition u_logging.h:48
Basic logging functionality.