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) 2023 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_SAMPLEDELAY_H
24 : #define MUSE_AUDIO_SAMPLEDELAY_H
25 :
26 : #include <cassert>
27 :
28 : #include "circularsamplebuffer.h"
29 :
30 : namespace muse::audio::fx {
31 : template<typename SampleT, int maxNumChannels>
32 : class SampleDelay
33 : {
34 : public:
35 0 : SampleDelay()
36 0 : {
37 0 : }
38 :
39 0 : ~SampleDelay()
40 : {
41 0 : }
42 :
43 0 : void allocateForMaxDelaySamples(int maxDelaySamples)
44 : {
45 0 : for (auto ch = 0; ch < maxNumChannels; ++ch) {
46 0 : m_buffer[ch].setSize(maxDelaySamples);
47 : }
48 0 : }
49 :
50 0 : void setDelaySamples(int samples)
51 : {
52 0 : if (m_delaySamples == samples) {
53 0 : return;
54 : }
55 :
56 0 : m_delaySamples = samples;
57 0 : allocateForMaxDelaySamples(samples);
58 0 : reset();
59 : }
60 :
61 : int getDelaySamples() const
62 : {
63 : return m_delaySamples;
64 : }
65 :
66 0 : void reset()
67 : {
68 0 : for (auto ch = 0; ch < maxNumChannels; ++ch) {
69 0 : m_buffer[ch].reset();
70 : }
71 0 : }
72 :
73 : SampleT processSample(const SampleT& sample, int ch)
74 : {
75 : if (m_delaySamples == 0) {
76 : return sample;
77 : }
78 :
79 : auto s = m_buffer[ch].read(-m_delaySamples);
80 : m_buffer[ch].writeOffset0(sample);
81 : m_buffer[ch].advance(1);
82 : return s;
83 : }
84 :
85 0 : void processBlock(SampleT** smp, int numCh, int numSamples)
86 : {
87 0 : assert(numCh <= maxNumChannels);
88 0 : if (m_delaySamples == 0) {
89 0 : return;
90 : }
91 :
92 0 : for (auto ch = 0; ch < numCh; ++ch) {
93 0 : for (auto i = 0; i < numSamples; ++i) {
94 0 : auto s = m_buffer[ch].read(-m_delaySamples);
95 0 : m_buffer[ch].writeOffset0(smp[ch][i]);
96 0 : smp[ch][i] = s;
97 0 : m_buffer[ch].advance(1);
98 : }
99 : }
100 : }
101 :
102 : private:
103 : CircularSampleBuffer<SampleT> m_buffer[maxNumChannels];
104 : int m_delaySamples = 0;
105 : };
106 : } // namespace muse::audio::fx
107 :
108 : #endif // MUSE_AUDIO_SAMPLEDELAY_H
|