AudioResampler.h revision 3348e36c51e91e78020bcc6578eda83d97c31bec
1/*
2 * Copyright (C) 2007 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 ANDROID_AUDIO_RESAMPLER_H
18#define ANDROID_AUDIO_RESAMPLER_H
19
20#include <stdint.h>
21#include <sys/types.h>
22#include <cutils/compiler.h>
23
24#include <media/AudioBufferProvider.h>
25#include <system/audio.h>
26
27namespace android {
28// ----------------------------------------------------------------------------
29
30class ANDROID_API AudioResampler {
31public:
32    // Determines quality of SRC.
33    //  LOW_QUALITY: linear interpolator (1st order)
34    //  MED_QUALITY: cubic interpolator (3rd order)
35    //  HIGH_QUALITY: fixed multi-tap FIR (e.g. 48KHz->44.1KHz)
36    // NOTE: high quality SRC will only be supported for
37    // certain fixed rate conversions. Sample rate cannot be
38    // changed dynamically.
39    enum src_quality {
40        DEFAULT_QUALITY=0,
41        LOW_QUALITY=1,
42        MED_QUALITY=2,
43        HIGH_QUALITY=3,
44        VERY_HIGH_QUALITY=4,
45        DYN_LOW_QUALITY=5,
46        DYN_MED_QUALITY=6,
47        DYN_HIGH_QUALITY=7,
48    };
49
50    static AudioResampler* create(audio_format_t format, int inChannelCount,
51            int32_t sampleRate, src_quality quality=DEFAULT_QUALITY);
52
53    virtual ~AudioResampler();
54
55    virtual void init() = 0;
56    virtual void setSampleRate(int32_t inSampleRate);
57    virtual void setVolume(int16_t left, int16_t right);
58    virtual void setLocalTimeFreq(uint64_t freq);
59
60    // set the PTS of the next buffer output by the resampler
61    virtual void setPTS(int64_t pts);
62
63    // Resample int16_t samples from provider and accumulate into 'out'.
64    // A mono provider delivers a sequence of samples.
65    // A stereo provider delivers a sequence of interleaved pairs of samples.
66    // Multi-channel providers are not supported.
67    // In either case, 'out' holds interleaved pairs of fixed-point Q4.27.
68    // That is, for a mono provider, there is an implicit up-channeling.
69    // Since this method accumulates, the caller is responsible for clearing 'out' initially.
70    // FIXME assumes provider is always successful; it should return the actual frame count.
71    virtual void resample(int32_t* out, size_t outFrameCount,
72            AudioBufferProvider* provider) = 0;
73
74    virtual void reset();
75    virtual size_t getUnreleasedFrames() const { return mInputIndex; }
76
77    // called from destructor, so must not be virtual
78    src_quality getQuality() const { return mQuality; }
79
80protected:
81    // number of bits for phase fraction - 30 bits allows nearly 2x downsampling
82    static const int kNumPhaseBits = 30;
83
84    // phase mask for fraction
85    static const uint32_t kPhaseMask = (1LU<<kNumPhaseBits)-1;
86
87    // multiplier to calculate fixed point phase increment
88    static const double kPhaseMultiplier;
89
90    AudioResampler(int inChannelCount, int32_t sampleRate, src_quality quality);
91
92    // prevent copying
93    AudioResampler(const AudioResampler&);
94    AudioResampler& operator=(const AudioResampler&);
95
96    int64_t calculateOutputPTS(int outputFrameIndex);
97
98    const int32_t mChannelCount;
99    const int32_t mSampleRate;
100    int32_t mInSampleRate;
101    AudioBufferProvider::Buffer mBuffer;
102    union {
103        int16_t mVolume[2];
104        uint32_t mVolumeRL;
105    };
106    int16_t mTargetVolume[2];
107    size_t mInputIndex;
108    int32_t mPhaseIncrement;
109    uint32_t mPhaseFraction;
110    uint64_t mLocalTimeFreq;
111    int64_t mPTS;
112
113    // returns the inFrameCount required to generate outFrameCount frames.
114    //
115    // Placed here to be a consistent for all resamplers.
116    //
117    // Right now, we use the upper bound without regards to the current state of the
118    // input buffer using integer arithmetic, as follows:
119    //
120    // (static_cast<uint64_t>(outFrameCount)*mInSampleRate + (mSampleRate - 1))/mSampleRate;
121    //
122    // The double precision equivalent (float may not be precise enough):
123    // ceil(static_cast<double>(outFrameCount) * mInSampleRate / mSampleRate);
124    //
125    // this relies on the fact that the mPhaseIncrement is rounded down from
126    // #phases * mInSampleRate/mSampleRate and the fact that Sum(Floor(x)) <= Floor(Sum(x)).
127    // http://www.proofwiki.org/wiki/Sum_of_Floors_Not_Greater_Than_Floor_of_Sums
128    //
129    // (so long as double precision is computed accurately enough to be considered
130    // greater than or equal to the Floor(x) value in int32_t arithmetic; thus this
131    // will not necessarily hold for floats).
132    //
133    // TODO:
134    // Greater accuracy and a tight bound is obtained by:
135    // 1) subtract and adjust for the current state of the AudioBufferProvider buffer.
136    // 2) using the exact integer formula where (ignoring 64b casting)
137    //  inFrameCount = (mPhaseIncrement * (outFrameCount - 1) + mPhaseFraction) / phaseWrapLimit;
138    //  phaseWrapLimit is the wraparound (1 << kNumPhaseBits), if not specified explicitly.
139    //
140    inline size_t getInFrameCountRequired(size_t outFrameCount) {
141        return (static_cast<uint64_t>(outFrameCount)*mInSampleRate
142                + (mSampleRate - 1))/mSampleRate;
143    }
144
145private:
146    const src_quality mQuality;
147
148    // Return 'true' if the quality level is supported without explicit request
149    static bool qualityIsSupported(src_quality quality);
150
151    // For pthread_once()
152    static void init_routine();
153
154    // Return the estimated CPU load for specific resampler in MHz.
155    // The absolute number is irrelevant, it's the relative values that matter.
156    static uint32_t qualityMHz(src_quality quality);
157};
158
159// ----------------------------------------------------------------------------
160}
161; // namespace android
162
163#endif // ANDROID_AUDIO_RESAMPLER_H
164