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 <cassert>
18 #include "PolyphaseResamplerMono.h"
19 
20 using namespace resampler;
21 
22 #define MONO  1
23 
PolyphaseResamplerMono(const MultiChannelResampler::Builder & builder)24 PolyphaseResamplerMono::PolyphaseResamplerMono(const MultiChannelResampler::Builder &builder)
25         : PolyphaseResampler(builder) {
26     assert(builder.getChannelCount() == MONO);
27 }
28 
writeFrame(const float * frame)29 void PolyphaseResamplerMono::writeFrame(const float *frame) {
30     // Move cursor before write so that cursor points to last written frame in read.
31     if (--mCursor < 0) {
32         mCursor = getNumTaps() - 1;
33     }
34     float *dest = &mX[mCursor * MONO];
35     const int offset = mNumTaps * MONO;
36     // Write each channel twice so we avoid having to wrap when running the FIR.
37     const float sample =  frame[0];
38     // Put ordered writes together.
39     dest[0] = sample;
40     dest[offset] = sample;
41 }
42 
readFrame(float * frame)43 void PolyphaseResamplerMono::readFrame(float *frame) {
44     // Clear accumulator.
45     float sum = 0.0;
46 
47     // Multiply input times precomputed windowed sinc function.
48     const float *coefficients = &mCoefficients[mCoefficientCursor];
49     float *xFrame = &mX[mCursor * MONO];
50     const int numLoops = mNumTaps >> 2; // n/4
51     for (int i = 0; i < numLoops; i++) {
52         // Manual loop unrolling, might get converted to SIMD.
53         sum += *xFrame++ * *coefficients++;
54         sum += *xFrame++ * *coefficients++;
55         sum += *xFrame++ * *coefficients++;
56         sum += *xFrame++ * *coefficients++;
57     }
58 
59     mCoefficientCursor = (mCoefficientCursor + mNumTaps) % mCoefficients.size();
60 
61     // Copy accumulator to output.
62     frame[0] = sum;
63 }
64