blob: 0a389bb398f146c93347426d18ab8212c53e6ab3 [file] [log] [blame]
Andy Hung86eae0e2013-12-09 12:12:46 -08001/*
2 * Copyright (C) 2013 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#define LOG_TAG "AudioResamplerDyn"
18//#define LOG_NDEBUG 0
19
20#include <malloc.h>
21#include <string.h>
22#include <stdlib.h>
23#include <dlfcn.h>
24#include <math.h>
25
26#include <cutils/compiler.h>
27#include <cutils/properties.h>
Andy Hungd5491392014-04-08 18:28:09 -070028#include <utils/Debug.h>
Andy Hung86eae0e2013-12-09 12:12:46 -080029#include <utils/Log.h>
Andy Hung5e58b0a2014-06-23 19:07:29 -070030#include <audio_utils/primitives.h>
Andy Hung86eae0e2013-12-09 12:12:46 -080031
Henrik Smiding841920d2016-02-15 16:20:45 +010032#include "AudioResamplerFirOps.h" // USE_NEON, USE_SSE and USE_INLINE_ASSEMBLY defined here
Andy Hung86eae0e2013-12-09 12:12:46 -080033#include "AudioResamplerFirProcess.h"
34#include "AudioResamplerFirProcessNeon.h"
Henrik Smiding841920d2016-02-15 16:20:45 +010035#include "AudioResamplerFirProcessSSE.h"
Andy Hung86eae0e2013-12-09 12:12:46 -080036#include "AudioResamplerFirGen.h" // requires math.h
37#include "AudioResamplerDyn.h"
38
39//#define DEBUG_RESAMPLER
40
Andy Hung6bd378f2017-10-24 19:23:52 -070041// use this for our buffer alignment. Should be at least 32 bytes.
42constexpr size_t CACHE_LINE_SIZE = 64;
43
Andy Hung86eae0e2013-12-09 12:12:46 -080044namespace android {
45
Andy Hung86eae0e2013-12-09 12:12:46 -080046/*
47 * InBuffer is a type agnostic input buffer.
48 *
49 * Layout of the state buffer for halfNumCoefs=8.
50 *
51 * [rrrrrrppppppppnnnnnnnnrrrrrrrrrrrrrrrrrrr.... rrrrrrr]
52 * S I R
53 *
54 * S = mState
55 * I = mImpulse
56 * R = mRingFull
57 * p = past samples, convoluted with the (p)ositive side of sinc()
58 * n = future samples, convoluted with the (n)egative side of sinc()
59 * r = extra space for implementing the ring buffer
60 */
61
Andy Hung771386e2014-04-08 18:44:38 -070062template<typename TC, typename TI, typename TO>
63AudioResamplerDyn<TC, TI, TO>::InBuffer::InBuffer()
64 : mState(NULL), mImpulse(NULL), mRingFull(NULL), mStateCount(0)
65{
Andy Hung86eae0e2013-12-09 12:12:46 -080066}
67
Andy Hung771386e2014-04-08 18:44:38 -070068template<typename TC, typename TI, typename TO>
69AudioResamplerDyn<TC, TI, TO>::InBuffer::~InBuffer()
70{
Andy Hung86eae0e2013-12-09 12:12:46 -080071 init();
72}
73
Andy Hung771386e2014-04-08 18:44:38 -070074template<typename TC, typename TI, typename TO>
75void AudioResamplerDyn<TC, TI, TO>::InBuffer::init()
76{
Andy Hung86eae0e2013-12-09 12:12:46 -080077 free(mState);
78 mState = NULL;
79 mImpulse = NULL;
80 mRingFull = NULL;
Andy Hung771386e2014-04-08 18:44:38 -070081 mStateCount = 0;
Andy Hung86eae0e2013-12-09 12:12:46 -080082}
83
84// resizes the state buffer to accommodate the appropriate filter length
Andy Hung771386e2014-04-08 18:44:38 -070085template<typename TC, typename TI, typename TO>
86void AudioResamplerDyn<TC, TI, TO>::InBuffer::resize(int CHANNELS, int halfNumCoefs)
87{
Andy Hung86eae0e2013-12-09 12:12:46 -080088 // calculate desired state size
Glenn Kastena4daf0b2014-07-28 16:34:45 -070089 size_t stateCount = halfNumCoefs * CHANNELS * 2 * kStateSizeMultipleOfFilterLength;
Andy Hung86eae0e2013-12-09 12:12:46 -080090
91 // check if buffer needs resizing
92 if (mState
Andy Hung771386e2014-04-08 18:44:38 -070093 && stateCount == mStateCount
Glenn Kastena4daf0b2014-07-28 16:34:45 -070094 && mRingFull-mState == (ssize_t) (mStateCount-halfNumCoefs*CHANNELS)) {
Andy Hung86eae0e2013-12-09 12:12:46 -080095 return;
96 }
97
98 // create new buffer
Glenn Kastena4daf0b2014-07-28 16:34:45 -070099 TI* state = NULL;
Andy Hung6bd378f2017-10-24 19:23:52 -0700100 (void)posix_memalign(
101 reinterpret_cast<void **>(&state),
102 CACHE_LINE_SIZE /* alignment */,
103 stateCount * sizeof(*state));
Andy Hung771386e2014-04-08 18:44:38 -0700104 memset(state, 0, stateCount*sizeof(*state));
Andy Hung86eae0e2013-12-09 12:12:46 -0800105
106 // attempt to preserve state
107 if (mState) {
108 TI* srcLo = mImpulse - halfNumCoefs*CHANNELS;
109 TI* srcHi = mImpulse + halfNumCoefs*CHANNELS;
110 TI* dst = state;
111
112 if (srcLo < mState) {
113 dst += mState-srcLo;
114 srcLo = mState;
115 }
Andy Hung771386e2014-04-08 18:44:38 -0700116 if (srcHi > mState + mStateCount) {
117 srcHi = mState + mStateCount;
Andy Hung86eae0e2013-12-09 12:12:46 -0800118 }
119 memcpy(dst, srcLo, (srcHi - srcLo) * sizeof(*srcLo));
120 free(mState);
121 }
122
123 // set class member vars
124 mState = state;
Andy Hung771386e2014-04-08 18:44:38 -0700125 mStateCount = stateCount;
126 mImpulse = state + halfNumCoefs*CHANNELS; // actually one sample greater than needed
127 mRingFull = state + mStateCount - halfNumCoefs*CHANNELS;
Andy Hung86eae0e2013-12-09 12:12:46 -0800128}
129
130// copy in the input data into the head (impulse+halfNumCoefs) of the buffer.
Andy Hung771386e2014-04-08 18:44:38 -0700131template<typename TC, typename TI, typename TO>
Andy Hung86eae0e2013-12-09 12:12:46 -0800132template<int CHANNELS>
Andy Hung771386e2014-04-08 18:44:38 -0700133void AudioResamplerDyn<TC, TI, TO>::InBuffer::readAgain(TI*& impulse, const int halfNumCoefs,
134 const TI* const in, const size_t inputIndex)
135{
136 TI* head = impulse + halfNumCoefs*CHANNELS;
Andy Hung86eae0e2013-12-09 12:12:46 -0800137 for (size_t i=0 ; i<CHANNELS ; i++) {
138 head[i] = in[inputIndex*CHANNELS + i];
139 }
140}
141
142// advance the impulse pointer, and load in data into the head (impulse+halfNumCoefs)
Andy Hung771386e2014-04-08 18:44:38 -0700143template<typename TC, typename TI, typename TO>
Andy Hung86eae0e2013-12-09 12:12:46 -0800144template<int CHANNELS>
Andy Hung771386e2014-04-08 18:44:38 -0700145void AudioResamplerDyn<TC, TI, TO>::InBuffer::readAdvance(TI*& impulse, const int halfNumCoefs,
146 const TI* const in, const size_t inputIndex)
147{
Andy Hung86eae0e2013-12-09 12:12:46 -0800148 impulse += CHANNELS;
149
150 if (CC_UNLIKELY(impulse >= mRingFull)) {
151 const size_t shiftDown = mRingFull - mState - halfNumCoefs*CHANNELS;
152 memcpy(mState, mState+shiftDown, halfNumCoefs*CHANNELS*2*sizeof(TI));
153 impulse -= shiftDown;
154 }
155 readAgain<CHANNELS>(impulse, halfNumCoefs, in, inputIndex);
156}
157
Andy Hung771386e2014-04-08 18:44:38 -0700158template<typename TC, typename TI, typename TO>
Hochi Huangbd179d12016-03-28 13:30:46 -0700159void AudioResamplerDyn<TC, TI, TO>::InBuffer::reset()
160{
161 // clear resampler state
162 if (mState != nullptr) {
163 memset(mState, 0, mStateCount * sizeof(TI));
164 }
165}
166
167template<typename TC, typename TI, typename TO>
Andy Hung771386e2014-04-08 18:44:38 -0700168void AudioResamplerDyn<TC, TI, TO>::Constants::set(
Andy Hung86eae0e2013-12-09 12:12:46 -0800169 int L, int halfNumCoefs, int inSampleRate, int outSampleRate)
170{
171 int bits = 0;
172 int lscale = inSampleRate/outSampleRate < 2 ? L - 1 :
173 static_cast<int>(static_cast<uint64_t>(L)*inSampleRate/outSampleRate);
174 for (int i=lscale; i; ++bits, i>>=1)
175 ;
176 mL = L;
177 mShift = kNumPhaseBits - bits;
178 mHalfNumCoefs = halfNumCoefs;
179}
180
Andy Hung771386e2014-04-08 18:44:38 -0700181template<typename TC, typename TI, typename TO>
Andy Hung3348e362014-07-07 10:21:44 -0700182AudioResamplerDyn<TC, TI, TO>::AudioResamplerDyn(
Andy Hung86eae0e2013-12-09 12:12:46 -0800183 int inChannelCount, int32_t sampleRate, src_quality quality)
Andy Hung3348e362014-07-07 10:21:44 -0700184 : AudioResampler(inChannelCount, sampleRate, quality),
Andy Hung771386e2014-04-08 18:44:38 -0700185 mResampleFunc(0), mFilterSampleRate(0), mFilterQuality(DEFAULT_QUALITY),
Andy Hung6582f2b2014-01-03 12:30:41 -0800186 mCoefBuffer(NULL)
Andy Hung86eae0e2013-12-09 12:12:46 -0800187{
188 mVolumeSimd[0] = mVolumeSimd[1] = 0;
Andy Hung1af34082014-02-19 17:42:25 -0800189 // The AudioResampler base class assumes we are always ready for 1:1 resampling.
190 // We reset mInSampleRate to 0, so setSampleRate() will calculate filters for
191 // setSampleRate() for 1:1. (May be removed if precalculated filters are used.)
192 mInSampleRate = 0;
Andy Hung86eae0e2013-12-09 12:12:46 -0800193 mConstants.set(128, 8, mSampleRate, mSampleRate); // TODO: set better
Andy Hung6bd378f2017-10-24 19:23:52 -0700194
195 // fetch property based resampling parameters
196 mPropertyEnableAtSampleRate = property_get_int32(
197 "ro.audio.resampler.psd.enable_at_samplerate", mPropertyEnableAtSampleRate);
198 mPropertyHalfFilterLength = property_get_int32(
199 "ro.audio.resampler.psd.halflength", mPropertyHalfFilterLength);
200 mPropertyStopbandAttenuation = property_get_int32(
201 "ro.audio.resampler.psd.stopband", mPropertyStopbandAttenuation);
202 mPropertyCutoffPercent = property_get_int32(
203 "ro.audio.resampler.psd.cutoff_percent", mPropertyCutoffPercent);
Andy Hung86eae0e2013-12-09 12:12:46 -0800204}
205
Andy Hung771386e2014-04-08 18:44:38 -0700206template<typename TC, typename TI, typename TO>
207AudioResamplerDyn<TC, TI, TO>::~AudioResamplerDyn()
208{
Andy Hung86eae0e2013-12-09 12:12:46 -0800209 free(mCoefBuffer);
210}
211
Andy Hung771386e2014-04-08 18:44:38 -0700212template<typename TC, typename TI, typename TO>
213void AudioResamplerDyn<TC, TI, TO>::init()
214{
Andy Hung86eae0e2013-12-09 12:12:46 -0800215 mFilterSampleRate = 0; // always trigger new filter generation
216 mInBuffer.init();
217}
218
Andy Hung771386e2014-04-08 18:44:38 -0700219template<typename TC, typename TI, typename TO>
Andy Hung5e58b0a2014-06-23 19:07:29 -0700220void AudioResamplerDyn<TC, TI, TO>::setVolume(float left, float right)
Andy Hung771386e2014-04-08 18:44:38 -0700221{
Andy Hung86eae0e2013-12-09 12:12:46 -0800222 AudioResampler::setVolume(left, right);
Andy Hung771386e2014-04-08 18:44:38 -0700223 if (is_same<TO, float>::value || is_same<TO, double>::value) {
Andy Hung5e58b0a2014-06-23 19:07:29 -0700224 mVolumeSimd[0] = static_cast<TO>(left);
225 mVolumeSimd[1] = static_cast<TO>(right);
226 } else { // integer requires scaling to U4_28 (rounding down)
227 // integer volumes are clamped to 0 to UNITY_GAIN so there
228 // are no issues with signed overflow.
229 mVolumeSimd[0] = u4_28_from_float(clampFloatVol(left));
230 mVolumeSimd[1] = u4_28_from_float(clampFloatVol(right));
Andy Hung771386e2014-04-08 18:44:38 -0700231 }
Andy Hung86eae0e2013-12-09 12:12:46 -0800232}
233
Andy Hung6bd378f2017-10-24 19:23:52 -0700234// TODO: update to C++11
235
Andy Hung771386e2014-04-08 18:44:38 -0700236template<typename T> T max(T a, T b) {return a > b ? a : b;}
Andy Hung86eae0e2013-12-09 12:12:46 -0800237
Andy Hung771386e2014-04-08 18:44:38 -0700238template<typename T> T absdiff(T a, T b) {return a > b ? a - b : b - a;}
Andy Hung86eae0e2013-12-09 12:12:46 -0800239
Andy Hung771386e2014-04-08 18:44:38 -0700240template<typename TC, typename TI, typename TO>
241void AudioResamplerDyn<TC, TI, TO>::createKaiserFir(Constants &c,
242 double stopBandAtten, int inSampleRate, int outSampleRate, double tbwCheat)
243{
Andy Hung6bd378f2017-10-24 19:23:52 -0700244 // compute the normalized transition bandwidth
245 const double tbw = firKaiserTbw(c.mHalfNumCoefs, stopBandAtten);
Andy Hung3f692412019-04-02 15:48:22 -0700246 const double halfbw = tbw * 0.5;
Andy Hung86eae0e2013-12-09 12:12:46 -0800247
Andy Hung6bd378f2017-10-24 19:23:52 -0700248 double fcr; // compute fcr, the 3 dB amplitude cut-off.
Andy Hung86eae0e2013-12-09 12:12:46 -0800249 if (inSampleRate < outSampleRate) { // upsample
Andy Hung6bd378f2017-10-24 19:23:52 -0700250 fcr = max(0.5 * tbwCheat - halfbw, halfbw);
Andy Hung86eae0e2013-12-09 12:12:46 -0800251 } else { // downsample
Andy Hung6bd378f2017-10-24 19:23:52 -0700252 fcr = max(0.5 * tbwCheat * outSampleRate / inSampleRate - halfbw, halfbw);
Andy Hung86eae0e2013-12-09 12:12:46 -0800253 }
Andy Hung6bd378f2017-10-24 19:23:52 -0700254 createKaiserFir(c, stopBandAtten, fcr);
255}
256
257template<typename TC, typename TI, typename TO>
258void AudioResamplerDyn<TC, TI, TO>::createKaiserFir(Constants &c,
259 double stopBandAtten, double fcr) {
260 // compute the normalized transition bandwidth
261 const double tbw = firKaiserTbw(c.mHalfNumCoefs, stopBandAtten);
262 const int phases = c.mL;
263 const int halfLength = c.mHalfNumCoefs;
264
265 // create buffer
266 TC *coefs = nullptr;
267 int ret = posix_memalign(
268 reinterpret_cast<void **>(&coefs),
269 CACHE_LINE_SIZE /* alignment */,
270 (phases + 1) * halfLength * sizeof(TC));
271 LOG_ALWAYS_FATAL_IF(ret != 0, "Cannot allocate buffer memory, ret %d", ret);
272 c.mFirCoefs = coefs;
273 free(mCoefBuffer);
274 mCoefBuffer = coefs;
275
276 // square the computed minimum passband value (extra safety).
277 double attenuation =
278 computeWindowedSincMinimumPassbandValue(stopBandAtten);
279 attenuation *= attenuation;
280
281 // design filter
282 firKaiserGen(coefs, phases, halfLength, stopBandAtten, fcr, attenuation);
283
284 // update the design criteria
285 mNormalizedCutoffFrequency = fcr;
286 mNormalizedTransitionBandwidth = tbw;
287 mFilterAttenuation = attenuation;
288 mStopbandAttenuationDb = stopBandAtten;
289 mPassbandRippleDb = computeWindowedSincPassbandRippleDb(stopBandAtten);
290
291#if 0
292 // Keep this debug code in case an app causes resampler design issues.
Andy Hung3f692412019-04-02 15:48:22 -0700293 const double halfbw = tbw * 0.5;
Andy Hung86eae0e2013-12-09 12:12:46 -0800294 // print basic filter stats
Andy Hung6bd378f2017-10-24 19:23:52 -0700295 ALOGD("L:%d hnc:%d stopBandAtten:%lf fcr:%lf atten:%lf tbw:%lf\n",
296 c.mL, c.mHalfNumCoefs, stopBandAtten, fcr, attenuation, tbw);
297
298 // test the filter and report results.
299 // Since this is a polyphase filter, normalized fp and fs must be scaled.
300 const double fp = (fcr - halfbw) / phases;
301 const double fs = (fcr + halfbw) / phases;
302
Andy Hung6582f2b2014-01-03 12:30:41 -0800303 double passMin, passMax, passRipple;
304 double stopMax, stopRipple;
Andy Hung6bd378f2017-10-24 19:23:52 -0700305
306 const int32_t passSteps = 1000;
307
Andy Hung3f692412019-04-02 15:48:22 -0700308 testFir(coefs, c.mL, c.mHalfNumCoefs, fp, fs, passSteps, passSteps * c.mL /*stopSteps*/,
Andy Hung6582f2b2014-01-03 12:30:41 -0800309 passMin, passMax, passRipple, stopMax, stopRipple);
Andy Hung6bd378f2017-10-24 19:23:52 -0700310 ALOGD("passband(%lf, %lf): %.8lf %.8lf %.8lf\n", 0., fp, passMin, passMax, passRipple);
311 ALOGD("stopband(%lf, %lf): %.8lf %.3lf\n", fs, 0.5, stopMax, stopRipple);
Andy Hung86eae0e2013-12-09 12:12:46 -0800312#endif
313}
314
Andy Hung6582f2b2014-01-03 12:30:41 -0800315// recursive gcd. Using objdump, it appears the tail recursion is converted to a while loop.
Andy Hung771386e2014-04-08 18:44:38 -0700316static int gcd(int n, int m)
317{
Andy Hung86eae0e2013-12-09 12:12:46 -0800318 if (m == 0) {
319 return n;
320 }
321 return gcd(m, n % m);
322}
323
Andy Hung6582f2b2014-01-03 12:30:41 -0800324static bool isClose(int32_t newSampleRate, int32_t prevSampleRate,
Andy Hung771386e2014-04-08 18:44:38 -0700325 int32_t filterSampleRate, int32_t outSampleRate)
326{
Andy Hung6582f2b2014-01-03 12:30:41 -0800327
328 // different upsampling ratios do not need a filter change.
329 if (filterSampleRate != 0
330 && filterSampleRate < outSampleRate
331 && newSampleRate < outSampleRate)
332 return true;
333
334 // check design criteria again if downsampling is detected.
Andy Hung86eae0e2013-12-09 12:12:46 -0800335 int pdiff = absdiff(newSampleRate, prevSampleRate);
336 int adiff = absdiff(newSampleRate, filterSampleRate);
337
338 // allow up to 6% relative change increments.
339 // allow up to 12% absolute change increments (from filter design)
340 return pdiff < prevSampleRate>>4 && adiff < filterSampleRate>>3;
341}
342
Andy Hung771386e2014-04-08 18:44:38 -0700343template<typename TC, typename TI, typename TO>
344void AudioResamplerDyn<TC, TI, TO>::setSampleRate(int32_t inSampleRate)
345{
Andy Hung86eae0e2013-12-09 12:12:46 -0800346 if (mInSampleRate == inSampleRate) {
347 return;
348 }
349 int32_t oldSampleRate = mInSampleRate;
Andy Hung86eae0e2013-12-09 12:12:46 -0800350 uint32_t oldPhaseWrapLimit = mConstants.mL << mConstants.mShift;
351 bool useS32 = false;
352
353 mInSampleRate = inSampleRate;
354
355 // TODO: Add precalculated Equiripple filters
356
Andy Hung6582f2b2014-01-03 12:30:41 -0800357 if (mFilterQuality != getQuality() ||
358 !isClose(inSampleRate, oldSampleRate, mFilterSampleRate, mSampleRate)) {
Andy Hung86eae0e2013-12-09 12:12:46 -0800359 mFilterSampleRate = inSampleRate;
Andy Hung6582f2b2014-01-03 12:30:41 -0800360 mFilterQuality = getQuality();
Andy Hung86eae0e2013-12-09 12:12:46 -0800361
Andy Hung6bd378f2017-10-24 19:23:52 -0700362 double stopBandAtten;
363 double tbwCheat = 1.; // how much we "cheat" into aliasing
364 int halfLength;
365 double fcr = 0.;
366
Andy Hung86eae0e2013-12-09 12:12:46 -0800367 // Begin Kaiser Filter computation
368 //
369 // The quantization floor for S16 is about 96db - 10*log_10(#length) + 3dB.
370 // Keep the stop band attenuation no greater than 84-85dB for 32 length S16 filters
371 //
372 // For s32 we keep the stop band attenuation at the same as 16b resolution, about
373 // 96-98dB
374 //
375
Andy Hung6bd378f2017-10-24 19:23:52 -0700376 if (mPropertyEnableAtSampleRate >= 0 && mSampleRate >= mPropertyEnableAtSampleRate) {
377 // An alternative method which allows allows a greater fcr
378 // at the expense of potential aliasing.
379 halfLength = mPropertyHalfFilterLength;
380 stopBandAtten = mPropertyStopbandAttenuation;
Andy Hung86eae0e2013-12-09 12:12:46 -0800381 useS32 = true;
Andy Hung6bd378f2017-10-24 19:23:52 -0700382 fcr = mInSampleRate <= mSampleRate
383 ? 0.5 : 0.5 * mSampleRate / mInSampleRate;
384 fcr *= mPropertyCutoffPercent / 100.;
385 } else {
Andy Hung06b40f92019-03-26 15:51:41 -0700386 // Voice quality devices have lower sampling rates
387 // (and may be a consequence of downstream AMR-WB / G.722 codecs).
388 // For these devices, we ensure a wider resampler passband
389 // at the expense of aliasing noise (stopband attenuation
390 // and stopband frequency).
391 //
392 constexpr uint32_t kVoiceDeviceSampleRate = 16000;
393
Andy Hung6bd378f2017-10-24 19:23:52 -0700394 if (mFilterQuality == DYN_HIGH_QUALITY) {
Andy Hung06b40f92019-03-26 15:51:41 -0700395 // float or 32b coefficients
Andy Hung6bd378f2017-10-24 19:23:52 -0700396 useS32 = true;
397 stopBandAtten = 98.;
398 if (inSampleRate >= mSampleRate * 4) {
399 halfLength = 48;
400 } else if (inSampleRate >= mSampleRate * 2) {
401 halfLength = 40;
402 } else {
403 halfLength = 32;
404 }
Andy Hung06b40f92019-03-26 15:51:41 -0700405
406 if (mSampleRate <= kVoiceDeviceSampleRate) {
407 if (inSampleRate >= mSampleRate * 2) {
408 halfLength += 16;
409 } else {
410 halfLength += 8;
411 }
412 stopBandAtten = 84.;
413 tbwCheat = 1.05;
414 }
Andy Hung6bd378f2017-10-24 19:23:52 -0700415 } else if (mFilterQuality == DYN_LOW_QUALITY) {
Andy Hung06b40f92019-03-26 15:51:41 -0700416 // float or 16b coefficients
Andy Hung6bd378f2017-10-24 19:23:52 -0700417 useS32 = false;
418 stopBandAtten = 80.;
419 if (inSampleRate >= mSampleRate * 4) {
420 halfLength = 24;
421 } else if (inSampleRate >= mSampleRate * 2) {
422 halfLength = 16;
423 } else {
424 halfLength = 8;
425 }
Andy Hung06b40f92019-03-26 15:51:41 -0700426 if (mSampleRate <= kVoiceDeviceSampleRate) {
427 if (inSampleRate >= mSampleRate * 2) {
428 halfLength += 8;
429 }
430 tbwCheat = 1.05;
431 } else if (inSampleRate <= mSampleRate) {
Andy Hung6bd378f2017-10-24 19:23:52 -0700432 tbwCheat = 1.05;
433 } else {
434 tbwCheat = 1.03;
435 }
436 } else { // DYN_MED_QUALITY
Andy Hung06b40f92019-03-26 15:51:41 -0700437 // float or 16b coefficients
Andy Hung6bd378f2017-10-24 19:23:52 -0700438 // note: > 64 length filters with 16b coefs can have quantization noise problems
439 useS32 = false;
440 stopBandAtten = 84.;
441 if (inSampleRate >= mSampleRate * 4) {
442 halfLength = 32;
443 } else if (inSampleRate >= mSampleRate * 2) {
444 halfLength = 24;
445 } else {
446 halfLength = 16;
447 }
Andy Hung06b40f92019-03-26 15:51:41 -0700448
449 if (mSampleRate <= kVoiceDeviceSampleRate) {
450 if (inSampleRate >= mSampleRate * 2) {
451 halfLength += 16;
452 } else {
453 halfLength += 8;
454 }
455 tbwCheat = 1.05;
456 } else if (inSampleRate <= mSampleRate) {
Andy Hung6bd378f2017-10-24 19:23:52 -0700457 tbwCheat = 1.03;
458 } else {
459 tbwCheat = 1.01;
460 }
Andy Hung86eae0e2013-12-09 12:12:46 -0800461 }
462 }
463
Andy Hung06b40f92019-03-26 15:51:41 -0700464 if (fcr > 0.) {
465 ALOGV("%s: mFilterQuality:%d inSampleRate:%d mSampleRate:%d halfLength:%d "
466 "stopBandAtten:%lf fcr:%lf",
467 __func__, mFilterQuality, inSampleRate, mSampleRate, halfLength,
468 stopBandAtten, fcr);
469 } else {
470 ALOGV("%s: mFilterQuality:%d inSampleRate:%d mSampleRate:%d halfLength:%d "
471 "stopBandAtten:%lf tbwCheat:%lf",
472 __func__, mFilterQuality, inSampleRate, mSampleRate, halfLength,
473 stopBandAtten, tbwCheat);
474 }
475
476
Andy Hung86eae0e2013-12-09 12:12:46 -0800477 // determine the number of polyphases in the filterbank.
478 // for 16b, it is desirable to have 2^(16/2) = 256 phases.
479 // https://ccrma.stanford.edu/~jos/resample/Relation_Interpolation_Error_Quantization.html
480 //
481 // We are a bit more lax on this.
482
483 int phases = mSampleRate / gcd(mSampleRate, inSampleRate);
484
Andy Hung6582f2b2014-01-03 12:30:41 -0800485 // TODO: Once dynamic sample rate change is an option, the code below
486 // should be modified to execute only when dynamic sample rate change is enabled.
487 //
488 // as above, #phases less than 63 is too few phases for accurate linear interpolation.
489 // we increase the phases to compensate, but more phases means more memory per
490 // filter and more time to compute the filter.
491 //
492 // if we know that the filter will be used for dynamic sample rate changes,
493 // that would allow us skip this part for fixed sample rate resamplers.
494 //
495 while (phases<63) {
Andy Hung86eae0e2013-12-09 12:12:46 -0800496 phases *= 2; // this code only needed to support dynamic rate changes
497 }
Andy Hung6582f2b2014-01-03 12:30:41 -0800498
Andy Hung86eae0e2013-12-09 12:12:46 -0800499 if (phases>=256) { // too many phases, always interpolate
500 phases = 127;
501 }
502
503 // create the filter
504 mConstants.set(phases, halfLength, inSampleRate, mSampleRate);
Andy Hung6bd378f2017-10-24 19:23:52 -0700505 if (fcr > 0.) {
506 createKaiserFir(mConstants, stopBandAtten, fcr);
507 } else {
508 createKaiserFir(mConstants, stopBandAtten,
509 inSampleRate, mSampleRate, tbwCheat);
510 }
Andy Hung86eae0e2013-12-09 12:12:46 -0800511 } // End Kaiser filter
512
513 // update phase and state based on the new filter.
514 const Constants& c(mConstants);
515 mInBuffer.resize(mChannelCount, c.mHalfNumCoefs);
516 const uint32_t phaseWrapLimit = c.mL << c.mShift;
517 // try to preserve as much of the phase fraction as possible for on-the-fly changes
518 mPhaseFraction = static_cast<unsigned long long>(mPhaseFraction)
519 * phaseWrapLimit / oldPhaseWrapLimit;
520 mPhaseFraction %= phaseWrapLimit; // should not do anything, but just in case.
Andy Hungcd044842014-08-07 11:04:34 -0700521 mPhaseIncrement = static_cast<uint32_t>(static_cast<uint64_t>(phaseWrapLimit)
Andy Hung86eae0e2013-12-09 12:12:46 -0800522 * inSampleRate / mSampleRate);
523
524 // determine which resampler to use
525 // check if locked phase (works only if mPhaseIncrement has no "fractional phase bits")
526 int locked = (mPhaseIncrement << (sizeof(mPhaseIncrement)*8 - c.mShift)) == 0;
Andy Hung86eae0e2013-12-09 12:12:46 -0800527 if (locked) {
528 mPhaseFraction = mPhaseFraction >> c.mShift << c.mShift; // remove fractional phase
529 }
Andy Hung83be2562014-02-03 14:11:09 -0800530
Andy Hung075abae2014-04-09 19:36:43 -0700531 // stride is the minimum number of filter coefficients processed per loop iteration.
532 // We currently only allow a stride of 16 to match with SIMD processing.
533 // This means that the filter length must be a multiple of 16,
534 // or half the filter length (mHalfNumCoefs) must be a multiple of 8.
535 //
536 // Note: A stride of 2 is achieved with non-SIMD processing.
537 int stride = ((c.mHalfNumCoefs & 7) == 0) ? 16 : 2;
538 LOG_ALWAYS_FATAL_IF(stride < 16, "Resampler stride must be 16 or more");
Andy Hung5e58b0a2014-06-23 19:07:29 -0700539 LOG_ALWAYS_FATAL_IF(mChannelCount < 1 || mChannelCount > 8,
Andy Hung075abae2014-04-09 19:36:43 -0700540 "Resampler channels(%d) must be between 1 to 8", mChannelCount);
541 // stride 16 (falls back to stride 2 for machines that do not support NEON)
542 if (locked) {
543 switch (mChannelCount) {
544 case 1:
545 mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<1, true, 16>;
546 break;
547 case 2:
548 mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<2, true, 16>;
549 break;
550 case 3:
551 mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<3, true, 16>;
552 break;
553 case 4:
554 mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<4, true, 16>;
555 break;
556 case 5:
557 mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<5, true, 16>;
558 break;
559 case 6:
560 mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<6, true, 16>;
561 break;
562 case 7:
563 mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<7, true, 16>;
564 break;
565 case 8:
566 mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<8, true, 16>;
567 break;
568 }
569 } else {
570 switch (mChannelCount) {
571 case 1:
572 mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<1, false, 16>;
573 break;
574 case 2:
575 mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<2, false, 16>;
576 break;
577 case 3:
578 mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<3, false, 16>;
579 break;
580 case 4:
581 mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<4, false, 16>;
582 break;
583 case 5:
584 mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<5, false, 16>;
585 break;
586 case 6:
587 mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<6, false, 16>;
588 break;
589 case 7:
590 mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<7, false, 16>;
591 break;
592 case 8:
593 mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<8, false, 16>;
594 break;
595 }
596 }
Andy Hung86eae0e2013-12-09 12:12:46 -0800597#ifdef DEBUG_RESAMPLER
598 printf("channels:%d %s stride:%d %s coef:%d shift:%d\n",
599 mChannelCount, locked ? "locked" : "interpolated",
600 stride, useS32 ? "S32" : "S16", 2*c.mHalfNumCoefs, c.mShift);
601#endif
602}
603
Andy Hung771386e2014-04-08 18:44:38 -0700604template<typename TC, typename TI, typename TO>
Andy Hung6b3b7e32015-03-29 00:49:22 -0700605size_t AudioResamplerDyn<TC, TI, TO>::resample(int32_t* out, size_t outFrameCount,
Andy Hung86eae0e2013-12-09 12:12:46 -0800606 AudioBufferProvider* provider)
607{
Andy Hung6b3b7e32015-03-29 00:49:22 -0700608 return (this->*mResampleFunc)(reinterpret_cast<TO*>(out), outFrameCount, provider);
Andy Hung771386e2014-04-08 18:44:38 -0700609}
Andy Hung86eae0e2013-12-09 12:12:46 -0800610
Andy Hung771386e2014-04-08 18:44:38 -0700611template<typename TC, typename TI, typename TO>
Andy Hung771386e2014-04-08 18:44:38 -0700612template<int CHANNELS, bool LOCKED, int STRIDE>
Andy Hung6b3b7e32015-03-29 00:49:22 -0700613size_t AudioResamplerDyn<TC, TI, TO>::resample(TO* out, size_t outFrameCount,
Andy Hung771386e2014-04-08 18:44:38 -0700614 AudioBufferProvider* provider)
Andy Hung86eae0e2013-12-09 12:12:46 -0800615{
Andy Hung075abae2014-04-09 19:36:43 -0700616 // TODO Mono -> Mono is not supported. OUTPUT_CHANNELS reflects minimum of stereo out.
617 const int OUTPUT_CHANNELS = (CHANNELS < 2) ? 2 : CHANNELS;
Andy Hung86eae0e2013-12-09 12:12:46 -0800618 const Constants& c(mConstants);
Andy Hung771386e2014-04-08 18:44:38 -0700619 const TC* const coefs = mConstants.mFirCoefs;
620 TI* impulse = mInBuffer.getImpulse();
Andy Hung411cb8e2014-05-27 12:32:17 -0700621 size_t inputIndex = 0;
Andy Hung86eae0e2013-12-09 12:12:46 -0800622 uint32_t phaseFraction = mPhaseFraction;
623 const uint32_t phaseIncrement = mPhaseIncrement;
624 size_t outputIndex = 0;
Andy Hung075abae2014-04-09 19:36:43 -0700625 size_t outputSampleCount = outFrameCount * OUTPUT_CHANNELS;
Andy Hung86eae0e2013-12-09 12:12:46 -0800626 const uint32_t phaseWrapLimit = c.mL << c.mShift;
Andy Hung71700742014-06-02 18:54:08 -0700627 size_t inFrameCount = (phaseIncrement * (uint64_t)outFrameCount + phaseFraction)
628 / phaseWrapLimit;
629 // sanity check that inFrameCount is in signed 32 bit integer range.
630 ALOG_ASSERT(0 <= inFrameCount && inFrameCount < (1U << 31));
631
632 //ALOGV("inFrameCount:%d outFrameCount:%d"
633 // " phaseIncrement:%u phaseFraction:%u phaseWrapLimit:%u",
634 // inFrameCount, outFrameCount, phaseIncrement, phaseFraction, phaseWrapLimit);
Andy Hung86eae0e2013-12-09 12:12:46 -0800635
636 // NOTE: be very careful when modifying the code here. register
637 // pressure is very high and a small change might cause the compiler
638 // to generate far less efficient code.
639 // Always sanity check the result with objdump or test-resample.
640
641 // the following logic is a bit convoluted to keep the main processing loop
642 // as tight as possible with register allocation.
643 while (outputIndex < outputSampleCount) {
Andy Hung71700742014-06-02 18:54:08 -0700644 //ALOGV("LOOP: inFrameCount:%d outputIndex:%d outFrameCount:%d"
645 // " phaseFraction:%u phaseWrapLimit:%u",
646 // inFrameCount, outputIndex, outFrameCount, phaseFraction, phaseWrapLimit);
647
648 // check inputIndex overflow
Tobias Melin43489212016-09-16 10:04:26 +0200649 ALOG_ASSERT(inputIndex <= mBuffer.frameCount, "inputIndex%zu > frameCount%zu",
Andy Hung71700742014-06-02 18:54:08 -0700650 inputIndex, mBuffer.frameCount);
651 // Buffer is empty, fetch a new one if necessary (inFrameCount > 0).
652 // We may not fetch a new buffer if the existing data is sufficient.
653 while (mBuffer.frameCount == 0 && inFrameCount > 0) {
Andy Hung86eae0e2013-12-09 12:12:46 -0800654 mBuffer.frameCount = inFrameCount;
Glenn Kastend79072e2016-01-06 08:41:20 -0800655 provider->getNextBuffer(&mBuffer);
Andy Hung86eae0e2013-12-09 12:12:46 -0800656 if (mBuffer.raw == NULL) {
Hochi Huangbd179d12016-03-28 13:30:46 -0700657 // We are either at the end of playback or in an underrun situation.
658 // Reset buffer to prevent pop noise at the next buffer.
659 mInBuffer.reset();
Andy Hung86eae0e2013-12-09 12:12:46 -0800660 goto resample_exit;
661 }
Andy Hung411cb8e2014-05-27 12:32:17 -0700662 inFrameCount -= mBuffer.frameCount;
Andy Hung86eae0e2013-12-09 12:12:46 -0800663 if (phaseFraction >= phaseWrapLimit) { // read in data
Andy Hung771386e2014-04-08 18:44:38 -0700664 mInBuffer.template readAdvance<CHANNELS>(
665 impulse, c.mHalfNumCoefs,
666 reinterpret_cast<TI*>(mBuffer.raw), inputIndex);
Andy Hung71700742014-06-02 18:54:08 -0700667 inputIndex++;
Andy Hung86eae0e2013-12-09 12:12:46 -0800668 phaseFraction -= phaseWrapLimit;
669 while (phaseFraction >= phaseWrapLimit) {
Andy Hung86eae0e2013-12-09 12:12:46 -0800670 if (inputIndex >= mBuffer.frameCount) {
Andy Hung411cb8e2014-05-27 12:32:17 -0700671 inputIndex = 0;
Andy Hung86eae0e2013-12-09 12:12:46 -0800672 provider->releaseBuffer(&mBuffer);
673 break;
674 }
Andy Hung771386e2014-04-08 18:44:38 -0700675 mInBuffer.template readAdvance<CHANNELS>(
676 impulse, c.mHalfNumCoefs,
677 reinterpret_cast<TI*>(mBuffer.raw), inputIndex);
Andy Hung71700742014-06-02 18:54:08 -0700678 inputIndex++;
Andy Hung86eae0e2013-12-09 12:12:46 -0800679 phaseFraction -= phaseWrapLimit;
680 }
681 }
682 }
Andy Hung771386e2014-04-08 18:44:38 -0700683 const TI* const in = reinterpret_cast<const TI*>(mBuffer.raw);
Andy Hung86eae0e2013-12-09 12:12:46 -0800684 const size_t frameCount = mBuffer.frameCount;
685 const int coefShift = c.mShift;
686 const int halfNumCoefs = c.mHalfNumCoefs;
Andy Hung771386e2014-04-08 18:44:38 -0700687 const TO* const volumeSimd = mVolumeSimd;
Andy Hung86eae0e2013-12-09 12:12:46 -0800688
Andy Hung86eae0e2013-12-09 12:12:46 -0800689 // main processing loop
690 while (CC_LIKELY(outputIndex < outputSampleCount)) {
691 // caution: fir() is inlined and may be large.
692 // output will be loaded with the appropriate values
693 //
694 // from the input samples in impulse[-halfNumCoefs+1]... impulse[halfNumCoefs]
695 // from the polyphase filter of (phaseFraction / phaseWrapLimit) in coefs.
696 //
Andy Hung71700742014-06-02 18:54:08 -0700697 //ALOGV("LOOP2: inFrameCount:%d outputIndex:%d outFrameCount:%d"
698 // " phaseFraction:%u phaseWrapLimit:%u",
699 // inFrameCount, outputIndex, outFrameCount, phaseFraction, phaseWrapLimit);
700 ALOG_ASSERT(phaseFraction < phaseWrapLimit);
Andy Hung86eae0e2013-12-09 12:12:46 -0800701 fir<CHANNELS, LOCKED, STRIDE>(
702 &out[outputIndex],
703 phaseFraction, phaseWrapLimit,
704 coefShift, halfNumCoefs, coefs,
705 impulse, volumeSimd);
Andy Hung075abae2014-04-09 19:36:43 -0700706
707 outputIndex += OUTPUT_CHANNELS;
Andy Hung86eae0e2013-12-09 12:12:46 -0800708
709 phaseFraction += phaseIncrement;
710 while (phaseFraction >= phaseWrapLimit) {
Andy Hung86eae0e2013-12-09 12:12:46 -0800711 if (inputIndex >= frameCount) {
712 goto done; // need a new buffer
713 }
Andy Hung771386e2014-04-08 18:44:38 -0700714 mInBuffer.template readAdvance<CHANNELS>(impulse, halfNumCoefs, in, inputIndex);
Andy Hung71700742014-06-02 18:54:08 -0700715 inputIndex++;
Andy Hung86eae0e2013-12-09 12:12:46 -0800716 phaseFraction -= phaseWrapLimit;
717 }
718 }
719done:
Andy Hung71700742014-06-02 18:54:08 -0700720 // We arrive here when we're finished or when the input buffer runs out.
721 // Regardless we need to release the input buffer if we've acquired it.
722 if (inputIndex > 0) { // we've acquired a buffer (alternatively could check frameCount)
Tobias Melin43489212016-09-16 10:04:26 +0200723 ALOG_ASSERT(inputIndex == frameCount, "inputIndex(%zu) != frameCount(%zu)",
Andy Hung71700742014-06-02 18:54:08 -0700724 inputIndex, frameCount); // must have been fully read.
Andy Hung411cb8e2014-05-27 12:32:17 -0700725 inputIndex = 0;
Andy Hung86eae0e2013-12-09 12:12:46 -0800726 provider->releaseBuffer(&mBuffer);
Andy Hung411cb8e2014-05-27 12:32:17 -0700727 ALOG_ASSERT(mBuffer.frameCount == 0);
Andy Hung86eae0e2013-12-09 12:12:46 -0800728 }
729 }
730
731resample_exit:
Andy Hung71700742014-06-02 18:54:08 -0700732 // inputIndex must be zero in all three cases:
733 // (1) the buffer never was been acquired; (2) the buffer was
734 // released at "done:"; or (3) getNextBuffer() failed.
Tobias Melin43489212016-09-16 10:04:26 +0200735 ALOG_ASSERT(inputIndex == 0, "Releasing: inputindex:%zu frameCount:%zu phaseFraction:%u",
Andy Hung71700742014-06-02 18:54:08 -0700736 inputIndex, mBuffer.frameCount, phaseFraction);
737 ALOG_ASSERT(mBuffer.frameCount == 0); // there must be no frames in the buffer
Andy Hung86eae0e2013-12-09 12:12:46 -0800738 mInBuffer.setImpulse(impulse);
Andy Hung86eae0e2013-12-09 12:12:46 -0800739 mPhaseFraction = phaseFraction;
Andy Hung6b3b7e32015-03-29 00:49:22 -0700740 return outputIndex / OUTPUT_CHANNELS;
Andy Hung86eae0e2013-12-09 12:12:46 -0800741}
742
Andy Hung771386e2014-04-08 18:44:38 -0700743/* instantiate templates used by AudioResampler::create */
744template class AudioResamplerDyn<float, float, float>;
745template class AudioResamplerDyn<int16_t, int16_t, int32_t>;
746template class AudioResamplerDyn<int32_t, int16_t, int32_t>;
747
Andy Hung86eae0e2013-12-09 12:12:46 -0800748// ----------------------------------------------------------------------------
Glenn Kasten63238ef2015-03-02 15:50:29 -0800749} // namespace android