xref: /aosp_15_r20/external/oboe/samples/shared/Mixer.h (revision 05767d913155b055644481607e6fa1e35e2fe72c)
1 /*
2  * Copyright 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef SHARED_MIXER_H
18 #define SHARED_MIXER_H
19 
20 #include <array>
21 #include "IRenderableAudio.h"
22 
23 /**
24  * A Mixer object which sums the output from multiple tracks into a single output. The number of
25  * input channels on each track must match the number of output channels (default 1=mono). This can
26  * be changed by calling `setChannelCount`.
27  * The inputs to the mixer are not owned by the mixer, they should not be deleted while rendering.
28  */
29 class Mixer : public IRenderableAudio {
30 
31 public:
renderAudio(float * audioData,int32_t numFrames)32     void renderAudio(float *audioData, int32_t numFrames) {
33 
34         int numSamples = numFrames * mChannelCount;
35         if (numSamples > mBufferSize) {
36             mMixingBuffer = std::make_unique<float[]>(numSamples);
37             mBufferSize = numSamples;
38         }
39 
40         // Zero out the incoming container array
41         memset(audioData, 0, sizeof(float) * numSamples);
42 
43         for (int i = 0; i < mTracks.size(); ++i) {
44             mTracks[i]->renderAudio(mMixingBuffer.get(), numFrames);
45 
46             for (int j = 0; j < numSamples; ++j) {
47                 audioData[j] += mMixingBuffer[j];
48             }
49         }
50     }
51 
addTrack(IRenderableAudio * renderer)52     void addTrack(IRenderableAudio *renderer){
53         mTracks.push_back(renderer);
54     }
55 
setChannelCount(int32_t channelCount)56     void setChannelCount(int32_t channelCount){ mChannelCount = channelCount; }
57 
removeAllTracks()58     void removeAllTracks(){
59         mTracks.clear();
60     }
61 
62 private:
63     int32_t mBufferSize = 0;
64     std::unique_ptr<float[]> mMixingBuffer;
65     std::vector<IRenderableAudio*> mTracks;
66     int32_t mChannelCount = 1; // Default to mono
67 };
68 
69 
70 #endif //SHARED_MIXER_H
71