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     mInputCallCount = kInitialCallCount;
32     mInputCursor = 0;
33 }
34 
35 // Return true if there is a sample available.
isInputAvailable()36 bool SampleRateConverter::isInputAvailable() {
37     // If we have consumed all of the input data then go out and get some more.
38     if (mInputCursor >= mNumValidInputFrames) {
39         mInputCallCount++;
40         mNumValidInputFrames = input.pullData(mInputCallCount, input.getFramesPerBuffer());
41         mInputCursor = 0;
42     }
43     return (mInputCursor < mNumValidInputFrames);
44 }
45 
getNextInputFrame()46 const float *SampleRateConverter::getNextInputFrame() {
47     const float *inputBuffer = input.getBuffer();
48     return &inputBuffer[mInputCursor++ * input.getSamplesPerFrame()];
49 }
50 
onProcess(int32_t numFrames)51 int32_t SampleRateConverter::onProcess(int32_t numFrames) {
52     float *outputBuffer = output.getBuffer();
53     int32_t channelCount = output.getSamplesPerFrame();
54     int framesLeft = numFrames;
55     while (framesLeft > 0) {
56         // Gather input samples as needed.
57         if(mResampler.isWriteNeeded()) {
58             if (isInputAvailable()) {
59                 const float *frame = getNextInputFrame();
60                 mResampler.writeNextFrame(frame);
61             } else {
62                 break;
63             }
64         } else {
65             // Output frame is interpolated from input samples.
66             mResampler.readNextFrame(outputBuffer);
67             outputBuffer += channelCount;
68             framesLeft--;
69         }
70     }
71     return numFrames - framesLeft;
72 }
73