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