The open source OpenXR runtime
1// Copyright 2022, Collabora, Ltd.
2// SPDX-License-Identifier: BSL-1.0
3/*!
4 * @file
5 * @brief Wrap integer filters for C
6 * @author Rylie Pavlik <rylie.pavlik@collabora.com>
7 * @ingroup aux_math
8 */
9
10#include "m_lowpass_integer.h"
11#include "m_lowpass_integer.hpp"
12
13#include "util/u_logging.h"
14
15#include <memory>
16
17using xrt::auxiliary::math::IntegerLowPassIIRFilter;
18// using xrt::auxiliary::math::Rational;
19using Rational64 = xrt::auxiliary::math::Rational<int64_t>;
20
21struct m_lowpass_integer
22{
23 m_lowpass_integer(Rational64 alpha) : filter(alpha) {}
24
25 IntegerLowPassIIRFilter<int64_t> filter;
26};
27
28#define DEFAULT_CATCH(...) \
29 catch (std::exception const &e) \
30 { \
31 U_LOG_E("Caught exception: %s", e.what()); \
32 return __VA_ARGS__; \
33 } \
34 catch (...) \
35 { \
36 U_LOG_E("Caught exception"); \
37 return __VA_ARGS__; \
38 }
39
40struct m_lowpass_integer *
41m_lowpass_integer_create(int64_t alpha_numerator, int64_t alpha_denominator)
42{
43 try {
44 if (alpha_denominator <= 0) {
45 return nullptr;
46 }
47 if (alpha_numerator <= 0 || alpha_numerator >= alpha_denominator) {
48 return nullptr;
49 }
50 auto ret = std::make_unique<m_lowpass_integer>(Rational64{alpha_numerator, alpha_denominator});
51 return ret.release();
52 }
53 DEFAULT_CATCH(nullptr)
54}
55
56void
57m_lowpass_integer_add_sample(struct m_lowpass_integer *mli, int64_t sample)
58{
59 try {
60 mli->filter.addSample(sample);
61 }
62 DEFAULT_CATCH()
63}
64
65int64_t
66m_lowpass_integer_get_state(const struct m_lowpass_integer *mli)
67{
68
69 try {
70 return mli->filter.getState();
71 }
72 DEFAULT_CATCH(0)
73}
74
75bool
76m_lowpass_integer_is_initialized(const struct m_lowpass_integer *mli)
77{
78
79 try {
80 return mli->filter.isInitialized();
81 }
82 DEFAULT_CATCH(false)
83}
84
85void
86m_lowpass_integer_destroy(struct m_lowpass_integer **ptr_to_mli)
87{
88 try {
89 if (ptr_to_mli == nullptr) {
90 return;
91 }
92 struct m_lowpass_integer *mli = *ptr_to_mli;
93 if (mli == nullptr) {
94 return;
95 }
96 delete mli;
97 *ptr_to_mli = nullptr;
98 }
99 DEFAULT_CATCH()
100}