Line data Source code
1 : /*
2 : * SPDX-License-Identifier: GPL-3.0-only
3 : * MuseScore-CLA-applies
4 : *
5 : * MuseScore Studio
6 : * Music Composition & Notation
7 : *
8 : * Copyright (C) 2021 MuseScore Limited and others
9 : *
10 : * This program is free software: you can redistribute it and/or modify
11 : * it under the terms of the GNU General Public License version 3 as
12 : * published by the Free Software Foundation.
13 : *
14 : * This program is distributed in the hope that it will be useful,
15 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 : * GNU General Public License for more details.
18 : *
19 : * You should have received a copy of the GNU General Public License
20 : * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 : */
22 :
23 : #ifndef MUSE_AUDIO_AUDIOMATHUTILS_H
24 : #define MUSE_AUDIO_AUDIOMATHUTILS_H
25 :
26 : #include <cstdlib>
27 : #include <limits>
28 :
29 : #include "audio/common/audiotypes.h"
30 :
31 : namespace muse::audio::dsp {
32 0 : inline float balanceGain(const balance_t balance, const int audioChannelNumber)
33 : {
34 0 : return (audioChannelNumber * 2 - 1) * balance + 1.f;
35 : }
36 :
37 : inline float samplesRootMeanSquare(const float squaredSum, const samples_t sampleCount)
38 : {
39 : return std::sqrt(squaredSum / sampleCount);
40 : }
41 :
42 0 : inline float sampleAttackTimeCoefficient(const unsigned int sampleRate, const float attackTimeInSecs)
43 : {
44 0 : return std::exp(-std::log(9) / (sampleRate * attackTimeInSecs));
45 : }
46 :
47 0 : inline float sampleReleaseTimeCoefficient(const unsigned int sampleRate, const float releaseTimeInSecs)
48 : {
49 0 : return std::exp(-std::log(9) / (sampleRate * releaseTimeInSecs));
50 : }
51 :
52 0 : inline void multiplySamples(float* buffer, const audioch_t& audioChannelsCount,
53 : const audioch_t& audioChannelNumber, const samples_t& samplesPerChannel,
54 : const float& multiplier)
55 : {
56 0 : for (samples_t i = 0; i < samplesPerChannel; ++i) {
57 0 : int idx = i * audioChannelsCount + audioChannelNumber;
58 :
59 0 : buffer[idx] *= multiplier;
60 : }
61 0 : }
62 :
63 : template<typename T>
64 0 : constexpr T convertFloatSamples(const float value, const int bits)
65 : {
66 0 : const int64_t max_val = (1LL << (bits - 1)) - 1LL;
67 0 : const float clampedValue = std::clamp(value, -1.0f, 1.0f);
68 0 : const float scaledValue = clampedValue * max_val;
69 0 : return static_cast<T>(std::round(scaledValue));
70 : }
71 : }
72 :
73 : #endif // MUSE_AUDIO_AUDIOMATHUTILS_H
|