xref: /aosp_15_r20/external/oboe/src/flowgraph/SampleRateConverter.cpp (revision 05767d913155b055644481607e6fa1e35e2fe72c)
1 /*
2  * Copyright 2019 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 #include "SampleRateConverter.h"
18 
19 using namespace FLOWGRAPH_OUTER_NAMESPACE::flowgraph;
20 using namespace RESAMPLER_OUTER_NAMESPACE::resampler;
21 
SampleRateConverter(int32_t channelCount,MultiChannelResampler & resampler)22 SampleRateConverter::SampleRateConverter(int32_t channelCount,
23                                          MultiChannelResampler &resampler)
24         : FlowGraphFilter(channelCount)
25         , mResampler(resampler) {
26     setDataPulledAutomatically(false);
27 }
28 
reset()29 void SampleRateConverter::reset() {
30     FlowGraphNode::reset();
31     mInputCursor = kInitialCallCount;
32 }
33 
34 // Return true if there is a sample available.
isInputAvailable()35 bool SampleRateConverter::isInputAvailable() {
36     // If we have consumed all of the input data then go out and get some more.
37     if (mInputCursor >= mNumValidInputFrames) {
38         mInputCallCount++;
39         mNumValidInputFrames = input.pullData(mInputCallCount, input.getFramesPerBuffer());
40         mInputCursor = 0;
41     }
42     return (mInputCursor < mNumValidInputFrames);
43 }
44 
getNextInputFrame()45 const float *SampleRateConverter::getNextInputFrame() {
46     const float *inputBuffer = input.getBuffer();
47     return &inputBuffer[mInputCursor++ * input.getSamplesPerFrame()];
48 }
49 
onProcess(int32_t numFrames)50 int32_t SampleRateConverter::onProcess(int32_t numFrames) {
51     float *outputBuffer = output.getBuffer();
52     int32_t channelCount = output.getSamplesPerFrame();
53     int framesLeft = numFrames;
54     while (framesLeft > 0) {
55         // Gather input samples as needed.
56         if(mResampler.isWriteNeeded()) {
57             if (isInputAvailable()) {
58                 const float *frame = getNextInputFrame();
59                 mResampler.writeNextFrame(frame);
60             } else {
61                 break;
62             }
63         } else {
64             // Output frame is interpolated from input samples.
65             mResampler.readNextFrame(outputBuffer);
66             outputBuffer += channelCount;
67             framesLeft--;
68         }
69     }
70     return numFrames - framesLeft;
71 }
72