AudioMixer.cpp revision e93b6b7347a7846c8fd746542364ec11b0cd5124
1/*
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9**     http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18#define LOG_TAG "AudioMixer"
19//#define LOG_NDEBUG 0
20
21#include "Configuration.h"
22#include <stdint.h>
23#include <string.h>
24#include <stdlib.h>
25#include <math.h>
26#include <sys/types.h>
27
28#include <utils/Errors.h>
29#include <utils/Log.h>
30
31#include <cutils/bitops.h>
32#include <cutils/compiler.h>
33#include <utils/Debug.h>
34
35#include <system/audio.h>
36
37#include <audio_utils/primitives.h>
38#include <audio_utils/format.h>
39#include <common_time/local_clock.h>
40#include <common_time/cc_helper.h>
41
42#include <media/EffectsFactoryApi.h>
43
44#include "AudioMixerOps.h"
45#include "AudioMixer.h"
46
47// The FCC_2 macro refers to the Fixed Channel Count of 2 for the legacy integer mixer.
48#ifndef FCC_2
49#define FCC_2 2
50#endif
51
52// Look for MONO_HACK for any Mono hack involving legacy mono channel to
53// stereo channel conversion.
54
55/* VERY_VERY_VERBOSE_LOGGING will show exactly which process hook and track hook is
56 * being used. This is a considerable amount of log spam, so don't enable unless you
57 * are verifying the hook based code.
58 */
59//#define VERY_VERY_VERBOSE_LOGGING
60#ifdef VERY_VERY_VERBOSE_LOGGING
61#define ALOGVV ALOGV
62//define ALOGVV printf  // for test-mixer.cpp
63#else
64#define ALOGVV(a...) do { } while (0)
65#endif
66
67#ifndef ARRAY_SIZE
68#define ARRAY_SIZE(x) (sizeof(x)/sizeof((x)[0]))
69#endif
70
71// Set kUseNewMixer to true to use the new mixer engine. Otherwise the
72// original code will be used.  This is false for now.
73static const bool kUseNewMixer = false;
74
75// Set kUseFloat to true to allow floating input into the mixer engine.
76// If kUseNewMixer is false, this is ignored or may be overridden internally
77// because of downmix/upmix support.
78static const bool kUseFloat = true;
79
80// Set to default copy buffer size in frames for input processing.
81static const size_t kCopyBufferFrameCount = 256;
82
83namespace android {
84
85// ----------------------------------------------------------------------------
86
87template <typename T>
88T min(const T& a, const T& b)
89{
90    return a < b ? a : b;
91}
92
93AudioMixer::CopyBufferProvider::CopyBufferProvider(size_t inputFrameSize,
94        size_t outputFrameSize, size_t bufferFrameCount) :
95        mInputFrameSize(inputFrameSize),
96        mOutputFrameSize(outputFrameSize),
97        mLocalBufferFrameCount(bufferFrameCount),
98        mLocalBufferData(NULL),
99        mConsumed(0)
100{
101    ALOGV("CopyBufferProvider(%p)(%zu, %zu, %zu)", this,
102            inputFrameSize, outputFrameSize, bufferFrameCount);
103    LOG_ALWAYS_FATAL_IF(inputFrameSize < outputFrameSize && bufferFrameCount == 0,
104            "Requires local buffer if inputFrameSize(%zu) < outputFrameSize(%zu)",
105            inputFrameSize, outputFrameSize);
106    if (mLocalBufferFrameCount) {
107        (void)posix_memalign(&mLocalBufferData, 32, mLocalBufferFrameCount * mOutputFrameSize);
108    }
109    mBuffer.frameCount = 0;
110}
111
112AudioMixer::CopyBufferProvider::~CopyBufferProvider()
113{
114    ALOGV("~CopyBufferProvider(%p)", this);
115    if (mBuffer.frameCount != 0) {
116        mTrackBufferProvider->releaseBuffer(&mBuffer);
117    }
118    free(mLocalBufferData);
119}
120
121status_t AudioMixer::CopyBufferProvider::getNextBuffer(AudioBufferProvider::Buffer *pBuffer,
122        int64_t pts)
123{
124    //ALOGV("CopyBufferProvider(%p)::getNextBuffer(%p (%zu), %lld)",
125    //        this, pBuffer, pBuffer->frameCount, pts);
126    if (mLocalBufferFrameCount == 0) {
127        status_t res = mTrackBufferProvider->getNextBuffer(pBuffer, pts);
128        if (res == OK) {
129            copyFrames(pBuffer->raw, pBuffer->raw, pBuffer->frameCount);
130        }
131        return res;
132    }
133    if (mBuffer.frameCount == 0) {
134        mBuffer.frameCount = pBuffer->frameCount;
135        status_t res = mTrackBufferProvider->getNextBuffer(&mBuffer, pts);
136        // At one time an upstream buffer provider had
137        // res == OK and mBuffer.frameCount == 0, doesn't seem to happen now 7/18/2014.
138        //
139        // By API spec, if res != OK, then mBuffer.frameCount == 0.
140        // but there may be improper implementations.
141        ALOG_ASSERT(res == OK || mBuffer.frameCount == 0);
142        if (res != OK || mBuffer.frameCount == 0) { // not needed by API spec, but to be safe.
143            pBuffer->raw = NULL;
144            pBuffer->frameCount = 0;
145            return res;
146        }
147        mConsumed = 0;
148    }
149    ALOG_ASSERT(mConsumed < mBuffer.frameCount);
150    size_t count = min(mLocalBufferFrameCount, mBuffer.frameCount - mConsumed);
151    count = min(count, pBuffer->frameCount);
152    pBuffer->raw = mLocalBufferData;
153    pBuffer->frameCount = count;
154    copyFrames(pBuffer->raw, (uint8_t*)mBuffer.raw + mConsumed * mInputFrameSize,
155            pBuffer->frameCount);
156    return OK;
157}
158
159void AudioMixer::CopyBufferProvider::releaseBuffer(AudioBufferProvider::Buffer *pBuffer)
160{
161    //ALOGV("CopyBufferProvider(%p)::releaseBuffer(%p(%zu))",
162    //        this, pBuffer, pBuffer->frameCount);
163    if (mLocalBufferFrameCount == 0) {
164        mTrackBufferProvider->releaseBuffer(pBuffer);
165        return;
166    }
167    // LOG_ALWAYS_FATAL_IF(pBuffer->frameCount == 0, "Invalid framecount");
168    mConsumed += pBuffer->frameCount; // TODO: update for efficiency to reuse existing content
169    if (mConsumed != 0 && mConsumed >= mBuffer.frameCount) {
170        mTrackBufferProvider->releaseBuffer(&mBuffer);
171        ALOG_ASSERT(mBuffer.frameCount == 0);
172    }
173    pBuffer->raw = NULL;
174    pBuffer->frameCount = 0;
175}
176
177void AudioMixer::CopyBufferProvider::reset()
178{
179    if (mBuffer.frameCount != 0) {
180        mTrackBufferProvider->releaseBuffer(&mBuffer);
181    }
182    mConsumed = 0;
183}
184
185AudioMixer::DownmixerBufferProvider::DownmixerBufferProvider(
186        audio_channel_mask_t inputChannelMask,
187        audio_channel_mask_t outputChannelMask, audio_format_t format,
188        uint32_t sampleRate, int32_t sessionId, size_t bufferFrameCount) :
189        CopyBufferProvider(
190            audio_bytes_per_sample(format) * audio_channel_count_from_out_mask(inputChannelMask),
191            audio_bytes_per_sample(format) * audio_channel_count_from_out_mask(outputChannelMask),
192            bufferFrameCount)  // set bufferFrameCount to 0 to do in-place
193{
194    ALOGV("DownmixerBufferProvider(%p)(%#x, %#x, %#x %u %d)",
195            this, inputChannelMask, outputChannelMask, format,
196            sampleRate, sessionId);
197    if (!sIsMultichannelCapable
198            || EffectCreate(&sDwnmFxDesc.uuid,
199                    sessionId,
200                    SESSION_ID_INVALID_AND_IGNORED,
201                    &mDownmixHandle) != 0) {
202         ALOGE("DownmixerBufferProvider() error creating downmixer effect");
203         mDownmixHandle = NULL;
204         return;
205     }
206     // channel input configuration will be overridden per-track
207     mDownmixConfig.inputCfg.channels = inputChannelMask;   // FIXME: Should be bits
208     mDownmixConfig.outputCfg.channels = outputChannelMask; // FIXME: should be bits
209     mDownmixConfig.inputCfg.format = format;
210     mDownmixConfig.outputCfg.format = format;
211     mDownmixConfig.inputCfg.samplingRate = sampleRate;
212     mDownmixConfig.outputCfg.samplingRate = sampleRate;
213     mDownmixConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
214     mDownmixConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
215     // input and output buffer provider, and frame count will not be used as the downmix effect
216     // process() function is called directly (see DownmixerBufferProvider::getNextBuffer())
217     mDownmixConfig.inputCfg.mask = EFFECT_CONFIG_SMP_RATE | EFFECT_CONFIG_CHANNELS |
218             EFFECT_CONFIG_FORMAT | EFFECT_CONFIG_ACC_MODE;
219     mDownmixConfig.outputCfg.mask = mDownmixConfig.inputCfg.mask;
220
221     int cmdStatus;
222     uint32_t replySize = sizeof(int);
223
224     // Configure downmixer
225     status_t status = (*mDownmixHandle)->command(mDownmixHandle,
226             EFFECT_CMD_SET_CONFIG /*cmdCode*/, sizeof(effect_config_t) /*cmdSize*/,
227             &mDownmixConfig /*pCmdData*/,
228             &replySize, &cmdStatus /*pReplyData*/);
229     if (status != 0 || cmdStatus != 0) {
230         ALOGE("DownmixerBufferProvider() error %d cmdStatus %d while configuring downmixer",
231                 status, cmdStatus);
232         EffectRelease(mDownmixHandle);
233         mDownmixHandle = NULL;
234         return;
235     }
236
237     // Enable downmixer
238     replySize = sizeof(int);
239     status = (*mDownmixHandle)->command(mDownmixHandle,
240             EFFECT_CMD_ENABLE /*cmdCode*/, 0 /*cmdSize*/, NULL /*pCmdData*/,
241             &replySize, &cmdStatus /*pReplyData*/);
242     if (status != 0 || cmdStatus != 0) {
243         ALOGE("DownmixerBufferProvider() error %d cmdStatus %d while enabling downmixer",
244                 status, cmdStatus);
245         EffectRelease(mDownmixHandle);
246         mDownmixHandle = NULL;
247         return;
248     }
249
250     // Set downmix type
251     // parameter size rounded for padding on 32bit boundary
252     const int psizePadded = ((sizeof(downmix_params_t) - 1)/sizeof(int) + 1) * sizeof(int);
253     const int downmixParamSize =
254             sizeof(effect_param_t) + psizePadded + sizeof(downmix_type_t);
255     effect_param_t * const param = (effect_param_t *) malloc(downmixParamSize);
256     param->psize = sizeof(downmix_params_t);
257     const downmix_params_t downmixParam = DOWNMIX_PARAM_TYPE;
258     memcpy(param->data, &downmixParam, param->psize);
259     const downmix_type_t downmixType = DOWNMIX_TYPE_FOLD;
260     param->vsize = sizeof(downmix_type_t);
261     memcpy(param->data + psizePadded, &downmixType, param->vsize);
262     replySize = sizeof(int);
263     status = (*mDownmixHandle)->command(mDownmixHandle,
264             EFFECT_CMD_SET_PARAM /* cmdCode */, downmixParamSize /* cmdSize */,
265             param /*pCmdData*/, &replySize, &cmdStatus /*pReplyData*/);
266     free(param);
267     if (status != 0 || cmdStatus != 0) {
268         ALOGE("DownmixerBufferProvider() error %d cmdStatus %d while setting downmix type",
269                 status, cmdStatus);
270         EffectRelease(mDownmixHandle);
271         mDownmixHandle = NULL;
272         return;
273     }
274     ALOGV("DownmixerBufferProvider() downmix type set to %d", (int) downmixType);
275}
276
277AudioMixer::DownmixerBufferProvider::~DownmixerBufferProvider()
278{
279    ALOGV("~DownmixerBufferProvider (%p)", this);
280    EffectRelease(mDownmixHandle);
281    mDownmixHandle = NULL;
282}
283
284void AudioMixer::DownmixerBufferProvider::copyFrames(void *dst, const void *src, size_t frames)
285{
286    mDownmixConfig.inputCfg.buffer.frameCount = frames;
287    mDownmixConfig.inputCfg.buffer.raw = const_cast<void *>(src);
288    mDownmixConfig.outputCfg.buffer.frameCount = frames;
289    mDownmixConfig.outputCfg.buffer.raw = dst;
290    // may be in-place if src == dst.
291    status_t res = (*mDownmixHandle)->process(mDownmixHandle,
292            &mDownmixConfig.inputCfg.buffer, &mDownmixConfig.outputCfg.buffer);
293    ALOGE_IF(res != OK, "DownmixBufferProvider error %d", res);
294}
295
296/* call once in a pthread_once handler. */
297/*static*/ status_t AudioMixer::DownmixerBufferProvider::init()
298{
299    // find multichannel downmix effect if we have to play multichannel content
300    uint32_t numEffects = 0;
301    int ret = EffectQueryNumberEffects(&numEffects);
302    if (ret != 0) {
303        ALOGE("AudioMixer() error %d querying number of effects", ret);
304        return NO_INIT;
305    }
306    ALOGV("EffectQueryNumberEffects() numEffects=%d", numEffects);
307
308    for (uint32_t i = 0 ; i < numEffects ; i++) {
309        if (EffectQueryEffect(i, &sDwnmFxDesc) == 0) {
310            ALOGV("effect %d is called %s", i, sDwnmFxDesc.name);
311            if (memcmp(&sDwnmFxDesc.type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
312                ALOGI("found effect \"%s\" from %s",
313                        sDwnmFxDesc.name, sDwnmFxDesc.implementor);
314                sIsMultichannelCapable = true;
315                break;
316            }
317        }
318    }
319    ALOGW_IF(!sIsMultichannelCapable, "unable to find downmix effect");
320    return NO_INIT;
321}
322
323/*static*/ bool AudioMixer::DownmixerBufferProvider::sIsMultichannelCapable = false;
324/*static*/ effect_descriptor_t AudioMixer::DownmixerBufferProvider::sDwnmFxDesc;
325
326AudioMixer::RemixBufferProvider::RemixBufferProvider(audio_channel_mask_t inputChannelMask,
327        audio_channel_mask_t outputChannelMask, audio_format_t format,
328        size_t bufferFrameCount) :
329        CopyBufferProvider(
330                audio_bytes_per_sample(format)
331                    * audio_channel_count_from_out_mask(inputChannelMask),
332                audio_bytes_per_sample(format)
333                    * audio_channel_count_from_out_mask(outputChannelMask),
334                bufferFrameCount),
335        mFormat(format),
336        mSampleSize(audio_bytes_per_sample(format)),
337        mInputChannels(audio_channel_count_from_out_mask(inputChannelMask)),
338        mOutputChannels(audio_channel_count_from_out_mask(outputChannelMask))
339{
340    ALOGV("RemixBufferProvider(%p)(%#x, %#x, %#x) %zu %zu",
341            this, format, inputChannelMask, outputChannelMask,
342            mInputChannels, mOutputChannels);
343    // TODO: consider channel representation in index array formulation
344    // We ignore channel representation, and just use the bits.
345    memcpy_by_index_array_initialization(mIdxAry, ARRAY_SIZE(mIdxAry),
346            audio_channel_mask_get_bits(outputChannelMask),
347            audio_channel_mask_get_bits(inputChannelMask));
348}
349
350void AudioMixer::RemixBufferProvider::copyFrames(void *dst, const void *src, size_t frames)
351{
352    memcpy_by_index_array(dst, mOutputChannels,
353            src, mInputChannels, mIdxAry, mSampleSize, frames);
354}
355
356AudioMixer::ReformatBufferProvider::ReformatBufferProvider(int32_t channels,
357        audio_format_t inputFormat, audio_format_t outputFormat,
358        size_t bufferFrameCount) :
359        CopyBufferProvider(
360            channels * audio_bytes_per_sample(inputFormat),
361            channels * audio_bytes_per_sample(outputFormat),
362            bufferFrameCount),
363        mChannels(channels),
364        mInputFormat(inputFormat),
365        mOutputFormat(outputFormat)
366{
367    ALOGV("ReformatBufferProvider(%p)(%d, %#x, %#x)", this, channels, inputFormat, outputFormat);
368}
369
370void AudioMixer::ReformatBufferProvider::copyFrames(void *dst, const void *src, size_t frames)
371{
372    memcpy_by_audio_format(dst, mOutputFormat, src, mInputFormat, frames * mChannels);
373}
374
375// ----------------------------------------------------------------------------
376
377// Ensure mConfiguredNames bitmask is initialized properly on all architectures.
378// The value of 1 << x is undefined in C when x >= 32.
379
380AudioMixer::AudioMixer(size_t frameCount, uint32_t sampleRate, uint32_t maxNumTracks)
381    :   mTrackNames(0), mConfiguredNames((maxNumTracks >= 32 ? 0 : 1 << maxNumTracks) - 1),
382        mSampleRate(sampleRate)
383{
384    ALOG_ASSERT(maxNumTracks <= MAX_NUM_TRACKS, "maxNumTracks %u > MAX_NUM_TRACKS %u",
385            maxNumTracks, MAX_NUM_TRACKS);
386
387    // AudioMixer is not yet capable of more than 32 active track inputs
388    ALOG_ASSERT(32 >= MAX_NUM_TRACKS, "bad MAX_NUM_TRACKS %d", MAX_NUM_TRACKS);
389
390    pthread_once(&sOnceControl, &sInitRoutine);
391
392    mState.enabledTracks= 0;
393    mState.needsChanged = 0;
394    mState.frameCount   = frameCount;
395    mState.hook         = process__nop;
396    mState.outputTemp   = NULL;
397    mState.resampleTemp = NULL;
398    mState.mLog         = &mDummyLog;
399    // mState.reserved
400
401    // FIXME Most of the following initialization is probably redundant since
402    // tracks[i] should only be referenced if (mTrackNames & (1 << i)) != 0
403    // and mTrackNames is initially 0.  However, leave it here until that's verified.
404    track_t* t = mState.tracks;
405    for (unsigned i=0 ; i < MAX_NUM_TRACKS ; i++) {
406        t->resampler = NULL;
407        t->downmixerBufferProvider = NULL;
408        t->mReformatBufferProvider = NULL;
409        t++;
410    }
411
412}
413
414AudioMixer::~AudioMixer()
415{
416    track_t* t = mState.tracks;
417    for (unsigned i=0 ; i < MAX_NUM_TRACKS ; i++) {
418        delete t->resampler;
419        delete t->downmixerBufferProvider;
420        delete t->mReformatBufferProvider;
421        t++;
422    }
423    delete [] mState.outputTemp;
424    delete [] mState.resampleTemp;
425}
426
427void AudioMixer::setLog(NBLog::Writer *log)
428{
429    mState.mLog = log;
430}
431
432int AudioMixer::getTrackName(audio_channel_mask_t channelMask,
433        audio_format_t format, int sessionId)
434{
435    if (!isValidPcmTrackFormat(format)) {
436        ALOGE("AudioMixer::getTrackName invalid format (%#x)", format);
437        return -1;
438    }
439    uint32_t names = (~mTrackNames) & mConfiguredNames;
440    if (names != 0) {
441        int n = __builtin_ctz(names);
442        ALOGV("add track (%d)", n);
443        // assume default parameters for the track, except where noted below
444        track_t* t = &mState.tracks[n];
445        t->needs = 0;
446
447        // Integer volume.
448        // Currently integer volume is kept for the legacy integer mixer.
449        // Will be removed when the legacy mixer path is removed.
450        t->volume[0] = UNITY_GAIN_INT;
451        t->volume[1] = UNITY_GAIN_INT;
452        t->prevVolume[0] = UNITY_GAIN_INT << 16;
453        t->prevVolume[1] = UNITY_GAIN_INT << 16;
454        t->volumeInc[0] = 0;
455        t->volumeInc[1] = 0;
456        t->auxLevel = 0;
457        t->auxInc = 0;
458        t->prevAuxLevel = 0;
459
460        // Floating point volume.
461        t->mVolume[0] = UNITY_GAIN_FLOAT;
462        t->mVolume[1] = UNITY_GAIN_FLOAT;
463        t->mPrevVolume[0] = UNITY_GAIN_FLOAT;
464        t->mPrevVolume[1] = UNITY_GAIN_FLOAT;
465        t->mVolumeInc[0] = 0.;
466        t->mVolumeInc[1] = 0.;
467        t->mAuxLevel = 0.;
468        t->mAuxInc = 0.;
469        t->mPrevAuxLevel = 0.;
470
471        // no initialization needed
472        // t->frameCount
473        t->channelCount = audio_channel_count_from_out_mask(channelMask);
474        t->enabled = false;
475        ALOGV_IF(audio_channel_mask_get_bits(channelMask) != AUDIO_CHANNEL_OUT_STEREO,
476                "Non-stereo channel mask: %d\n", channelMask);
477        t->channelMask = channelMask;
478        t->sessionId = sessionId;
479        // setBufferProvider(name, AudioBufferProvider *) is required before enable(name)
480        t->bufferProvider = NULL;
481        t->buffer.raw = NULL;
482        // no initialization needed
483        // t->buffer.frameCount
484        t->hook = NULL;
485        t->in = NULL;
486        t->resampler = NULL;
487        t->sampleRate = mSampleRate;
488        // setParameter(name, TRACK, MAIN_BUFFER, mixBuffer) is required before enable(name)
489        t->mainBuffer = NULL;
490        t->auxBuffer = NULL;
491        t->mInputBufferProvider = NULL;
492        t->mReformatBufferProvider = NULL;
493        t->downmixerBufferProvider = NULL;
494        t->mMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
495        t->mFormat = format;
496        t->mMixerInFormat = kUseFloat && kUseNewMixer
497                ? AUDIO_FORMAT_PCM_FLOAT : AUDIO_FORMAT_PCM_16_BIT;
498        t->mMixerChannelMask = audio_channel_mask_from_representation_and_bits(
499                AUDIO_CHANNEL_REPRESENTATION_POSITION, AUDIO_CHANNEL_OUT_STEREO);
500        t->mMixerChannelCount = audio_channel_count_from_out_mask(t->mMixerChannelMask);
501        // Check the downmixing (or upmixing) requirements.
502        status_t status = initTrackDownmix(t, n);
503        if (status != OK) {
504            ALOGE("AudioMixer::getTrackName invalid channelMask (%#x)", channelMask);
505            return -1;
506        }
507        // initTrackDownmix() may change the input format requirement.
508        // If you desire floating point input to the mixer, it may change
509        // to integer because the downmixer requires integer to process.
510        ALOGVV("mMixerFormat:%#x  mMixerInFormat:%#x\n", t->mMixerFormat, t->mMixerInFormat);
511        prepareTrackForReformat(t, n);
512        mTrackNames |= 1 << n;
513        return TRACK0 + n;
514    }
515    ALOGE("AudioMixer::getTrackName out of available tracks");
516    return -1;
517}
518
519void AudioMixer::invalidateState(uint32_t mask)
520{
521    if (mask != 0) {
522        mState.needsChanged |= mask;
523        mState.hook = process__validate;
524    }
525 }
526
527// Called when channel masks have changed for a track name
528// TODO: Fix Downmixbufferprofider not to (possibly) change mixer input format,
529// which will simplify this logic.
530bool AudioMixer::setChannelMasks(int name,
531        audio_channel_mask_t trackChannelMask, audio_channel_mask_t mixerChannelMask) {
532    track_t &track = mState.tracks[name];
533
534    if (trackChannelMask == track.channelMask
535            && mixerChannelMask == track.mMixerChannelMask) {
536        return false;  // no need to change
537    }
538    // always recompute for both channel masks even if only one has changed.
539    const uint32_t trackChannelCount = audio_channel_count_from_out_mask(trackChannelMask);
540    const uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mixerChannelMask);
541    const bool mixerChannelCountChanged = track.mMixerChannelCount != mixerChannelCount;
542
543    ALOG_ASSERT((trackChannelCount <= MAX_NUM_CHANNELS_TO_DOWNMIX)
544            && trackChannelCount
545            && mixerChannelCount);
546    track.channelMask = trackChannelMask;
547    track.channelCount = trackChannelCount;
548    track.mMixerChannelMask = mixerChannelMask;
549    track.mMixerChannelCount = mixerChannelCount;
550
551    // channel masks have changed, does this track need a downmixer?
552    // update to try using our desired format (if we aren't already using it)
553    const audio_format_t prevMixerInFormat = track.mMixerInFormat;
554    track.mMixerInFormat = kUseFloat && kUseNewMixer
555            ? AUDIO_FORMAT_PCM_FLOAT : AUDIO_FORMAT_PCM_16_BIT;
556    const status_t status = initTrackDownmix(&mState.tracks[name], name);
557    ALOGE_IF(status != OK,
558            "initTrackDownmix error %d, track channel mask %#x, mixer channel mask %#x",
559            status, track.channelMask, track.mMixerChannelMask);
560
561    const bool mixerInFormatChanged = prevMixerInFormat != track.mMixerInFormat;
562    if (mixerInFormatChanged) {
563        prepareTrackForReformat(&track, name); // because of downmixer, track format may change!
564    }
565
566    if (track.resampler && (mixerInFormatChanged || mixerChannelCountChanged)) {
567        // resampler input format or channels may have changed.
568        const uint32_t resetToSampleRate = track.sampleRate;
569        delete track.resampler;
570        track.resampler = NULL;
571        track.sampleRate = mSampleRate; // without resampler, track rate is device sample rate.
572        // recreate the resampler with updated format, channels, saved sampleRate.
573        track.setResampler(resetToSampleRate /*trackSampleRate*/, mSampleRate /*devSampleRate*/);
574    }
575    return true;
576}
577
578status_t AudioMixer::initTrackDownmix(track_t* pTrack, int trackName)
579{
580    // Only remix (upmix or downmix) if the track and mixer/device channel masks
581    // are not the same and not handled internally, as mono -> stereo currently is.
582    if (pTrack->channelMask != pTrack->mMixerChannelMask
583            && !(pTrack->channelMask == AUDIO_CHANNEL_OUT_MONO
584                    && pTrack->mMixerChannelMask == AUDIO_CHANNEL_OUT_STEREO)) {
585        return prepareTrackForDownmix(pTrack, trackName);
586    }
587    // no remix necessary
588    unprepareTrackForDownmix(pTrack, trackName);
589    return NO_ERROR;
590}
591
592void AudioMixer::unprepareTrackForDownmix(track_t* pTrack, int trackName __unused) {
593    ALOGV("AudioMixer::unprepareTrackForDownmix(%d)", trackName);
594
595    if (pTrack->downmixerBufferProvider != NULL) {
596        // this track had previously been configured with a downmixer, delete it
597        ALOGV(" deleting old downmixer");
598        delete pTrack->downmixerBufferProvider;
599        pTrack->downmixerBufferProvider = NULL;
600        reconfigureBufferProviders(pTrack);
601    } else {
602        ALOGV(" nothing to do, no downmixer to delete");
603    }
604}
605
606status_t AudioMixer::prepareTrackForDownmix(track_t* pTrack, int trackName)
607{
608    ALOGV("AudioMixer::prepareTrackForDownmix(%d) with mask 0x%x", trackName, pTrack->channelMask);
609
610    // discard the previous downmixer if there was one
611    unprepareTrackForDownmix(pTrack, trackName);
612    if (DownmixerBufferProvider::isMultichannelCapable()) {
613        DownmixerBufferProvider* pDbp = new DownmixerBufferProvider(pTrack->channelMask,
614                pTrack->mMixerChannelMask,
615                AUDIO_FORMAT_PCM_16_BIT /* TODO: use pTrack->mMixerInFormat, now only PCM 16 */,
616                pTrack->sampleRate, pTrack->sessionId, kCopyBufferFrameCount);
617
618        if (pDbp->isValid()) { // if constructor completed properly
619            pTrack->mMixerInFormat = AUDIO_FORMAT_PCM_16_BIT; // PCM 16 bit required for downmix
620            pTrack->downmixerBufferProvider = pDbp;
621            reconfigureBufferProviders(pTrack);
622            return NO_ERROR;
623        }
624        delete pDbp;
625    }
626
627    // Effect downmixer does not accept the channel conversion.  Let's use our remixer.
628    RemixBufferProvider* pRbp = new RemixBufferProvider(pTrack->channelMask,
629            pTrack->mMixerChannelMask, pTrack->mMixerInFormat, kCopyBufferFrameCount);
630    // Remix always finds a conversion whereas Downmixer effect above may fail.
631    pTrack->downmixerBufferProvider = pRbp;
632    reconfigureBufferProviders(pTrack);
633    return NO_ERROR;
634}
635
636void AudioMixer::unprepareTrackForReformat(track_t* pTrack, int trackName __unused) {
637    ALOGV("AudioMixer::unprepareTrackForReformat(%d)", trackName);
638    if (pTrack->mReformatBufferProvider != NULL) {
639        delete pTrack->mReformatBufferProvider;
640        pTrack->mReformatBufferProvider = NULL;
641        reconfigureBufferProviders(pTrack);
642    }
643}
644
645status_t AudioMixer::prepareTrackForReformat(track_t* pTrack, int trackName)
646{
647    ALOGV("AudioMixer::prepareTrackForReformat(%d) with format %#x", trackName, pTrack->mFormat);
648    // discard the previous reformatter if there was one
649    unprepareTrackForReformat(pTrack, trackName);
650    // only configure reformatter if needed
651    if (pTrack->mFormat != pTrack->mMixerInFormat) {
652        pTrack->mReformatBufferProvider = new ReformatBufferProvider(
653                audio_channel_count_from_out_mask(pTrack->channelMask),
654                pTrack->mFormat, pTrack->mMixerInFormat,
655                kCopyBufferFrameCount);
656        reconfigureBufferProviders(pTrack);
657    }
658    return NO_ERROR;
659}
660
661void AudioMixer::reconfigureBufferProviders(track_t* pTrack)
662{
663    pTrack->bufferProvider = pTrack->mInputBufferProvider;
664    if (pTrack->mReformatBufferProvider) {
665        pTrack->mReformatBufferProvider->setBufferProvider(pTrack->bufferProvider);
666        pTrack->bufferProvider = pTrack->mReformatBufferProvider;
667    }
668    if (pTrack->downmixerBufferProvider) {
669        pTrack->downmixerBufferProvider->setBufferProvider(pTrack->bufferProvider);
670        pTrack->bufferProvider = pTrack->downmixerBufferProvider;
671    }
672}
673
674void AudioMixer::deleteTrackName(int name)
675{
676    ALOGV("AudioMixer::deleteTrackName(%d)", name);
677    name -= TRACK0;
678    ALOG_ASSERT(uint32_t(name) < MAX_NUM_TRACKS, "bad track name %d", name);
679    ALOGV("deleteTrackName(%d)", name);
680    track_t& track(mState.tracks[ name ]);
681    if (track.enabled) {
682        track.enabled = false;
683        invalidateState(1<<name);
684    }
685    // delete the resampler
686    delete track.resampler;
687    track.resampler = NULL;
688    // delete the downmixer
689    unprepareTrackForDownmix(&mState.tracks[name], name);
690    // delete the reformatter
691    unprepareTrackForReformat(&mState.tracks[name], name);
692
693    mTrackNames &= ~(1<<name);
694}
695
696void AudioMixer::enable(int name)
697{
698    name -= TRACK0;
699    ALOG_ASSERT(uint32_t(name) < MAX_NUM_TRACKS, "bad track name %d", name);
700    track_t& track = mState.tracks[name];
701
702    if (!track.enabled) {
703        track.enabled = true;
704        ALOGV("enable(%d)", name);
705        invalidateState(1 << name);
706    }
707}
708
709void AudioMixer::disable(int name)
710{
711    name -= TRACK0;
712    ALOG_ASSERT(uint32_t(name) < MAX_NUM_TRACKS, "bad track name %d", name);
713    track_t& track = mState.tracks[name];
714
715    if (track.enabled) {
716        track.enabled = false;
717        ALOGV("disable(%d)", name);
718        invalidateState(1 << name);
719    }
720}
721
722/* Sets the volume ramp variables for the AudioMixer.
723 *
724 * The volume ramp variables are used to transition from the previous
725 * volume to the set volume.  ramp controls the duration of the transition.
726 * Its value is typically one state framecount period, but may also be 0,
727 * meaning "immediate."
728 *
729 * FIXME: 1) Volume ramp is enabled only if there is a nonzero integer increment
730 * even if there is a nonzero floating point increment (in that case, the volume
731 * change is immediate).  This restriction should be changed when the legacy mixer
732 * is removed (see #2).
733 * FIXME: 2) Integer volume variables are used for Legacy mixing and should be removed
734 * when no longer needed.
735 *
736 * @param newVolume set volume target in floating point [0.0, 1.0].
737 * @param ramp number of frames to increment over. if ramp is 0, the volume
738 * should be set immediately.  Currently ramp should not exceed 65535 (frames).
739 * @param pIntSetVolume pointer to the U4.12 integer target volume, set on return.
740 * @param pIntPrevVolume pointer to the U4.28 integer previous volume, set on return.
741 * @param pIntVolumeInc pointer to the U4.28 increment per output audio frame, set on return.
742 * @param pSetVolume pointer to the float target volume, set on return.
743 * @param pPrevVolume pointer to the float previous volume, set on return.
744 * @param pVolumeInc pointer to the float increment per output audio frame, set on return.
745 * @return true if the volume has changed, false if volume is same.
746 */
747static inline bool setVolumeRampVariables(float newVolume, int32_t ramp,
748        int16_t *pIntSetVolume, int32_t *pIntPrevVolume, int32_t *pIntVolumeInc,
749        float *pSetVolume, float *pPrevVolume, float *pVolumeInc) {
750    if (newVolume == *pSetVolume) {
751        return false;
752    }
753    /* set the floating point volume variables */
754    if (ramp != 0) {
755        *pVolumeInc = (newVolume - *pSetVolume) / ramp;
756        *pPrevVolume = *pSetVolume;
757    } else {
758        *pVolumeInc = 0;
759        *pPrevVolume = newVolume;
760    }
761    *pSetVolume = newVolume;
762
763    /* set the legacy integer volume variables */
764    int32_t intVolume = newVolume * AudioMixer::UNITY_GAIN_INT;
765    if (intVolume > AudioMixer::UNITY_GAIN_INT) {
766        intVolume = AudioMixer::UNITY_GAIN_INT;
767    } else if (intVolume < 0) {
768        ALOGE("negative volume %.7g", newVolume);
769        intVolume = 0; // should never happen, but for safety check.
770    }
771    if (intVolume == *pIntSetVolume) {
772        *pIntVolumeInc = 0;
773        /* TODO: integer/float workaround: ignore floating volume ramp */
774        *pVolumeInc = 0;
775        *pPrevVolume = newVolume;
776        return true;
777    }
778    if (ramp != 0) {
779        *pIntVolumeInc = ((intVolume - *pIntSetVolume) << 16) / ramp;
780        *pIntPrevVolume = (*pIntVolumeInc == 0 ? intVolume : *pIntSetVolume) << 16;
781    } else {
782        *pIntVolumeInc = 0;
783        *pIntPrevVolume = intVolume << 16;
784    }
785    *pIntSetVolume = intVolume;
786    return true;
787}
788
789void AudioMixer::setParameter(int name, int target, int param, void *value)
790{
791    name -= TRACK0;
792    ALOG_ASSERT(uint32_t(name) < MAX_NUM_TRACKS, "bad track name %d", name);
793    track_t& track = mState.tracks[name];
794
795    int valueInt = static_cast<int>(reinterpret_cast<uintptr_t>(value));
796    int32_t *valueBuf = reinterpret_cast<int32_t*>(value);
797
798    switch (target) {
799
800    case TRACK:
801        switch (param) {
802        case CHANNEL_MASK: {
803            const audio_channel_mask_t trackChannelMask =
804                static_cast<audio_channel_mask_t>(valueInt);
805            if (setChannelMasks(name, trackChannelMask, track.mMixerChannelMask)) {
806                ALOGV("setParameter(TRACK, CHANNEL_MASK, %x)", trackChannelMask);
807                invalidateState(1 << name);
808            }
809            } break;
810        case MAIN_BUFFER:
811            if (track.mainBuffer != valueBuf) {
812                track.mainBuffer = valueBuf;
813                ALOGV("setParameter(TRACK, MAIN_BUFFER, %p)", valueBuf);
814                invalidateState(1 << name);
815            }
816            break;
817        case AUX_BUFFER:
818            if (track.auxBuffer != valueBuf) {
819                track.auxBuffer = valueBuf;
820                ALOGV("setParameter(TRACK, AUX_BUFFER, %p)", valueBuf);
821                invalidateState(1 << name);
822            }
823            break;
824        case FORMAT: {
825            audio_format_t format = static_cast<audio_format_t>(valueInt);
826            if (track.mFormat != format) {
827                ALOG_ASSERT(audio_is_linear_pcm(format), "Invalid format %#x", format);
828                track.mFormat = format;
829                ALOGV("setParameter(TRACK, FORMAT, %#x)", format);
830                prepareTrackForReformat(&track, name);
831                invalidateState(1 << name);
832            }
833            } break;
834        // FIXME do we want to support setting the downmix type from AudioFlinger?
835        //         for a specific track? or per mixer?
836        /* case DOWNMIX_TYPE:
837            break          */
838        case MIXER_FORMAT: {
839            audio_format_t format = static_cast<audio_format_t>(valueInt);
840            if (track.mMixerFormat != format) {
841                track.mMixerFormat = format;
842                ALOGV("setParameter(TRACK, MIXER_FORMAT, %#x)", format);
843            }
844            } break;
845        case MIXER_CHANNEL_MASK: {
846            const audio_channel_mask_t mixerChannelMask =
847                    static_cast<audio_channel_mask_t>(valueInt);
848            if (setChannelMasks(name, track.channelMask, mixerChannelMask)) {
849                ALOGV("setParameter(TRACK, MIXER_CHANNEL_MASK, %#x)", mixerChannelMask);
850                invalidateState(1 << name);
851            }
852            } break;
853        default:
854            LOG_ALWAYS_FATAL("setParameter track: bad param %d", param);
855        }
856        break;
857
858    case RESAMPLE:
859        switch (param) {
860        case SAMPLE_RATE:
861            ALOG_ASSERT(valueInt > 0, "bad sample rate %d", valueInt);
862            if (track.setResampler(uint32_t(valueInt), mSampleRate)) {
863                ALOGV("setParameter(RESAMPLE, SAMPLE_RATE, %u)",
864                        uint32_t(valueInt));
865                invalidateState(1 << name);
866            }
867            break;
868        case RESET:
869            track.resetResampler();
870            invalidateState(1 << name);
871            break;
872        case REMOVE:
873            delete track.resampler;
874            track.resampler = NULL;
875            track.sampleRate = mSampleRate;
876            invalidateState(1 << name);
877            break;
878        default:
879            LOG_ALWAYS_FATAL("setParameter resample: bad param %d", param);
880        }
881        break;
882
883    case RAMP_VOLUME:
884    case VOLUME:
885        switch (param) {
886        case AUXLEVEL:
887            if (setVolumeRampVariables(*reinterpret_cast<float*>(value),
888                    target == RAMP_VOLUME ? mState.frameCount : 0,
889                    &track.auxLevel, &track.prevAuxLevel, &track.auxInc,
890                    &track.mAuxLevel, &track.mPrevAuxLevel, &track.mAuxInc)) {
891                ALOGV("setParameter(%s, AUXLEVEL: %04x)",
892                        target == VOLUME ? "VOLUME" : "RAMP_VOLUME", track.auxLevel);
893                invalidateState(1 << name);
894            }
895            break;
896        default:
897            if ((unsigned)param >= VOLUME0 && (unsigned)param < VOLUME0 + MAX_NUM_VOLUMES) {
898                if (setVolumeRampVariables(*reinterpret_cast<float*>(value),
899                        target == RAMP_VOLUME ? mState.frameCount : 0,
900                        &track.volume[param - VOLUME0], &track.prevVolume[param - VOLUME0],
901                        &track.volumeInc[param - VOLUME0],
902                        &track.mVolume[param - VOLUME0], &track.mPrevVolume[param - VOLUME0],
903                        &track.mVolumeInc[param - VOLUME0])) {
904                    ALOGV("setParameter(%s, VOLUME%d: %04x)",
905                            target == VOLUME ? "VOLUME" : "RAMP_VOLUME", param - VOLUME0,
906                                    track.volume[param - VOLUME0]);
907                    invalidateState(1 << name);
908                }
909            } else {
910                LOG_ALWAYS_FATAL("setParameter volume: bad param %d", param);
911            }
912        }
913        break;
914
915    default:
916        LOG_ALWAYS_FATAL("setParameter: bad target %d", target);
917    }
918}
919
920bool AudioMixer::track_t::setResampler(uint32_t trackSampleRate, uint32_t devSampleRate)
921{
922    if (trackSampleRate != devSampleRate || resampler != NULL) {
923        if (sampleRate != trackSampleRate) {
924            sampleRate = trackSampleRate;
925            if (resampler == NULL) {
926                ALOGV("Creating resampler from track %d Hz to device %d Hz",
927                        trackSampleRate, devSampleRate);
928                AudioResampler::src_quality quality;
929                // force lowest quality level resampler if use case isn't music or video
930                // FIXME this is flawed for dynamic sample rates, as we choose the resampler
931                // quality level based on the initial ratio, but that could change later.
932                // Should have a way to distinguish tracks with static ratios vs. dynamic ratios.
933                if (!((trackSampleRate == 44100 && devSampleRate == 48000) ||
934                      (trackSampleRate == 48000 && devSampleRate == 44100))) {
935                    quality = AudioResampler::DYN_LOW_QUALITY;
936                } else {
937                    quality = AudioResampler::DEFAULT_QUALITY;
938                }
939
940                // TODO: Remove MONO_HACK. Resampler sees #channels after the downmixer
941                // but if none exists, it is the channel count (1 for mono).
942                const int resamplerChannelCount = downmixerBufferProvider != NULL
943                        ? mMixerChannelCount : channelCount;
944                ALOGVV("Creating resampler with %#x format\n", mMixerInFormat);
945                resampler = AudioResampler::create(
946                        mMixerInFormat,
947                        resamplerChannelCount,
948                        devSampleRate, quality);
949                resampler->setLocalTimeFreq(sLocalTimeFreq);
950            }
951            return true;
952        }
953    }
954    return false;
955}
956
957/* Checks to see if the volume ramp has completed and clears the increment
958 * variables appropriately.
959 *
960 * FIXME: There is code to handle int/float ramp variable switchover should it not
961 * complete within a mixer buffer processing call, but it is preferred to avoid switchover
962 * due to precision issues.  The switchover code is included for legacy code purposes
963 * and can be removed once the integer volume is removed.
964 *
965 * It is not sufficient to clear only the volumeInc integer variable because
966 * if one channel requires ramping, all channels are ramped.
967 *
968 * There is a bit of duplicated code here, but it keeps backward compatibility.
969 */
970inline void AudioMixer::track_t::adjustVolumeRamp(bool aux, bool useFloat)
971{
972    if (useFloat) {
973        for (uint32_t i = 0; i < MAX_NUM_VOLUMES; i++) {
974            if (mVolumeInc[i] != 0 && fabs(mVolume[i] - mPrevVolume[i]) <= fabs(mVolumeInc[i])) {
975                volumeInc[i] = 0;
976                prevVolume[i] = volume[i] << 16;
977                mVolumeInc[i] = 0.;
978                mPrevVolume[i] = mVolume[i];
979            } else {
980                //ALOGV("ramp: %f %f %f", mVolume[i], mPrevVolume[i], mVolumeInc[i]);
981                prevVolume[i] = u4_28_from_float(mPrevVolume[i]);
982            }
983        }
984    } else {
985        for (uint32_t i = 0; i < MAX_NUM_VOLUMES; i++) {
986            if (((volumeInc[i]>0) && (((prevVolume[i]+volumeInc[i])>>16) >= volume[i])) ||
987                    ((volumeInc[i]<0) && (((prevVolume[i]+volumeInc[i])>>16) <= volume[i]))) {
988                volumeInc[i] = 0;
989                prevVolume[i] = volume[i] << 16;
990                mVolumeInc[i] = 0.;
991                mPrevVolume[i] = mVolume[i];
992            } else {
993                //ALOGV("ramp: %d %d %d", volume[i] << 16, prevVolume[i], volumeInc[i]);
994                mPrevVolume[i]  = float_from_u4_28(prevVolume[i]);
995            }
996        }
997    }
998    /* TODO: aux is always integer regardless of output buffer type */
999    if (aux) {
1000        if (((auxInc>0) && (((prevAuxLevel+auxInc)>>16) >= auxLevel)) ||
1001                ((auxInc<0) && (((prevAuxLevel+auxInc)>>16) <= auxLevel))) {
1002            auxInc = 0;
1003            prevAuxLevel = auxLevel << 16;
1004            mAuxInc = 0.;
1005            mPrevAuxLevel = mAuxLevel;
1006        } else {
1007            //ALOGV("aux ramp: %d %d %d", auxLevel << 16, prevAuxLevel, auxInc);
1008        }
1009    }
1010}
1011
1012size_t AudioMixer::getUnreleasedFrames(int name) const
1013{
1014    name -= TRACK0;
1015    if (uint32_t(name) < MAX_NUM_TRACKS) {
1016        return mState.tracks[name].getUnreleasedFrames();
1017    }
1018    return 0;
1019}
1020
1021void AudioMixer::setBufferProvider(int name, AudioBufferProvider* bufferProvider)
1022{
1023    name -= TRACK0;
1024    ALOG_ASSERT(uint32_t(name) < MAX_NUM_TRACKS, "bad track name %d", name);
1025
1026    if (mState.tracks[name].mInputBufferProvider == bufferProvider) {
1027        return; // don't reset any buffer providers if identical.
1028    }
1029    if (mState.tracks[name].mReformatBufferProvider != NULL) {
1030        mState.tracks[name].mReformatBufferProvider->reset();
1031    } else if (mState.tracks[name].downmixerBufferProvider != NULL) {
1032    }
1033
1034    mState.tracks[name].mInputBufferProvider = bufferProvider;
1035    reconfigureBufferProviders(&mState.tracks[name]);
1036}
1037
1038
1039void AudioMixer::process(int64_t pts)
1040{
1041    mState.hook(&mState, pts);
1042}
1043
1044
1045void AudioMixer::process__validate(state_t* state, int64_t pts)
1046{
1047    ALOGW_IF(!state->needsChanged,
1048        "in process__validate() but nothing's invalid");
1049
1050    uint32_t changed = state->needsChanged;
1051    state->needsChanged = 0; // clear the validation flag
1052
1053    // recompute which tracks are enabled / disabled
1054    uint32_t enabled = 0;
1055    uint32_t disabled = 0;
1056    while (changed) {
1057        const int i = 31 - __builtin_clz(changed);
1058        const uint32_t mask = 1<<i;
1059        changed &= ~mask;
1060        track_t& t = state->tracks[i];
1061        (t.enabled ? enabled : disabled) |= mask;
1062    }
1063    state->enabledTracks &= ~disabled;
1064    state->enabledTracks |=  enabled;
1065
1066    // compute everything we need...
1067    int countActiveTracks = 0;
1068    bool all16BitsStereoNoResample = true;
1069    bool resampling = false;
1070    bool volumeRamp = false;
1071    uint32_t en = state->enabledTracks;
1072    while (en) {
1073        const int i = 31 - __builtin_clz(en);
1074        en &= ~(1<<i);
1075
1076        countActiveTracks++;
1077        track_t& t = state->tracks[i];
1078        uint32_t n = 0;
1079        // FIXME can overflow (mask is only 3 bits)
1080        n |= NEEDS_CHANNEL_1 + t.channelCount - 1;
1081        if (t.doesResample()) {
1082            n |= NEEDS_RESAMPLE;
1083        }
1084        if (t.auxLevel != 0 && t.auxBuffer != NULL) {
1085            n |= NEEDS_AUX;
1086        }
1087
1088        if (t.volumeInc[0]|t.volumeInc[1]) {
1089            volumeRamp = true;
1090        } else if (!t.doesResample() && t.volumeRL == 0) {
1091            n |= NEEDS_MUTE;
1092        }
1093        t.needs = n;
1094
1095        if (n & NEEDS_MUTE) {
1096            t.hook = track__nop;
1097        } else {
1098            if (n & NEEDS_AUX) {
1099                all16BitsStereoNoResample = false;
1100            }
1101            if (n & NEEDS_RESAMPLE) {
1102                all16BitsStereoNoResample = false;
1103                resampling = true;
1104                t.hook = getTrackHook(TRACKTYPE_RESAMPLE, t.mMixerChannelCount,
1105                        t.mMixerInFormat, t.mMixerFormat);
1106                ALOGV_IF((n & NEEDS_CHANNEL_COUNT__MASK) > NEEDS_CHANNEL_2,
1107                        "Track %d needs downmix + resample", i);
1108            } else {
1109                if ((n & NEEDS_CHANNEL_COUNT__MASK) == NEEDS_CHANNEL_1){
1110                    t.hook = getTrackHook(
1111                            t.mMixerChannelCount == 2 // TODO: MONO_HACK.
1112                                ? TRACKTYPE_NORESAMPLEMONO : TRACKTYPE_NORESAMPLE,
1113                            t.mMixerChannelCount,
1114                            t.mMixerInFormat, t.mMixerFormat);
1115                    all16BitsStereoNoResample = false;
1116                }
1117                if ((n & NEEDS_CHANNEL_COUNT__MASK) >= NEEDS_CHANNEL_2){
1118                    t.hook = getTrackHook(TRACKTYPE_NORESAMPLE, t.mMixerChannelCount,
1119                            t.mMixerInFormat, t.mMixerFormat);
1120                    ALOGV_IF((n & NEEDS_CHANNEL_COUNT__MASK) > NEEDS_CHANNEL_2,
1121                            "Track %d needs downmix", i);
1122                }
1123            }
1124        }
1125    }
1126
1127    // select the processing hooks
1128    state->hook = process__nop;
1129    if (countActiveTracks > 0) {
1130        if (resampling) {
1131            if (!state->outputTemp) {
1132                state->outputTemp = new int32_t[MAX_NUM_CHANNELS * state->frameCount];
1133            }
1134            if (!state->resampleTemp) {
1135                state->resampleTemp = new int32_t[MAX_NUM_CHANNELS * state->frameCount];
1136            }
1137            state->hook = process__genericResampling;
1138        } else {
1139            if (state->outputTemp) {
1140                delete [] state->outputTemp;
1141                state->outputTemp = NULL;
1142            }
1143            if (state->resampleTemp) {
1144                delete [] state->resampleTemp;
1145                state->resampleTemp = NULL;
1146            }
1147            state->hook = process__genericNoResampling;
1148            if (all16BitsStereoNoResample && !volumeRamp) {
1149                if (countActiveTracks == 1) {
1150                    const int i = 31 - __builtin_clz(state->enabledTracks);
1151                    track_t& t = state->tracks[i];
1152                    state->hook = getProcessHook(PROCESSTYPE_NORESAMPLEONETRACK,
1153                            t.mMixerChannelCount, t.mMixerInFormat, t.mMixerFormat);
1154                }
1155            }
1156        }
1157    }
1158
1159    ALOGV("mixer configuration change: %d activeTracks (%08x) "
1160        "all16BitsStereoNoResample=%d, resampling=%d, volumeRamp=%d",
1161        countActiveTracks, state->enabledTracks,
1162        all16BitsStereoNoResample, resampling, volumeRamp);
1163
1164   state->hook(state, pts);
1165
1166    // Now that the volume ramp has been done, set optimal state and
1167    // track hooks for subsequent mixer process
1168    if (countActiveTracks > 0) {
1169        bool allMuted = true;
1170        uint32_t en = state->enabledTracks;
1171        while (en) {
1172            const int i = 31 - __builtin_clz(en);
1173            en &= ~(1<<i);
1174            track_t& t = state->tracks[i];
1175            if (!t.doesResample() && t.volumeRL == 0) {
1176                t.needs |= NEEDS_MUTE;
1177                t.hook = track__nop;
1178            } else {
1179                allMuted = false;
1180            }
1181        }
1182        if (allMuted) {
1183            state->hook = process__nop;
1184        } else if (all16BitsStereoNoResample) {
1185            if (countActiveTracks == 1) {
1186                const int i = 31 - __builtin_clz(state->enabledTracks);
1187                track_t& t = state->tracks[i];
1188                state->hook = getProcessHook(PROCESSTYPE_NORESAMPLEONETRACK,
1189                        t.mMixerChannelCount, t.mMixerInFormat, t.mMixerFormat);
1190            }
1191        }
1192    }
1193}
1194
1195
1196void AudioMixer::track__genericResample(track_t* t, int32_t* out, size_t outFrameCount,
1197        int32_t* temp, int32_t* aux)
1198{
1199    ALOGVV("track__genericResample\n");
1200    t->resampler->setSampleRate(t->sampleRate);
1201
1202    // ramp gain - resample to temp buffer and scale/mix in 2nd step
1203    if (aux != NULL) {
1204        // always resample with unity gain when sending to auxiliary buffer to be able
1205        // to apply send level after resampling
1206        t->resampler->setVolume(UNITY_GAIN_FLOAT, UNITY_GAIN_FLOAT);
1207        memset(temp, 0, outFrameCount * t->mMixerChannelCount * sizeof(int32_t));
1208        t->resampler->resample(temp, outFrameCount, t->bufferProvider);
1209        if (CC_UNLIKELY(t->volumeInc[0]|t->volumeInc[1]|t->auxInc)) {
1210            volumeRampStereo(t, out, outFrameCount, temp, aux);
1211        } else {
1212            volumeStereo(t, out, outFrameCount, temp, aux);
1213        }
1214    } else {
1215        if (CC_UNLIKELY(t->volumeInc[0]|t->volumeInc[1])) {
1216            t->resampler->setVolume(UNITY_GAIN_FLOAT, UNITY_GAIN_FLOAT);
1217            memset(temp, 0, outFrameCount * MAX_NUM_CHANNELS * sizeof(int32_t));
1218            t->resampler->resample(temp, outFrameCount, t->bufferProvider);
1219            volumeRampStereo(t, out, outFrameCount, temp, aux);
1220        }
1221
1222        // constant gain
1223        else {
1224            t->resampler->setVolume(t->mVolume[0], t->mVolume[1]);
1225            t->resampler->resample(out, outFrameCount, t->bufferProvider);
1226        }
1227    }
1228}
1229
1230void AudioMixer::track__nop(track_t* t __unused, int32_t* out __unused,
1231        size_t outFrameCount __unused, int32_t* temp __unused, int32_t* aux __unused)
1232{
1233}
1234
1235void AudioMixer::volumeRampStereo(track_t* t, int32_t* out, size_t frameCount, int32_t* temp,
1236        int32_t* aux)
1237{
1238    int32_t vl = t->prevVolume[0];
1239    int32_t vr = t->prevVolume[1];
1240    const int32_t vlInc = t->volumeInc[0];
1241    const int32_t vrInc = t->volumeInc[1];
1242
1243    //ALOGD("[0] %p: inc=%f, v0=%f, v1=%d, final=%f, count=%d",
1244    //        t, vlInc/65536.0f, vl/65536.0f, t->volume[0],
1245    //       (vl + vlInc*frameCount)/65536.0f, frameCount);
1246
1247    // ramp volume
1248    if (CC_UNLIKELY(aux != NULL)) {
1249        int32_t va = t->prevAuxLevel;
1250        const int32_t vaInc = t->auxInc;
1251        int32_t l;
1252        int32_t r;
1253
1254        do {
1255            l = (*temp++ >> 12);
1256            r = (*temp++ >> 12);
1257            *out++ += (vl >> 16) * l;
1258            *out++ += (vr >> 16) * r;
1259            *aux++ += (va >> 17) * (l + r);
1260            vl += vlInc;
1261            vr += vrInc;
1262            va += vaInc;
1263        } while (--frameCount);
1264        t->prevAuxLevel = va;
1265    } else {
1266        do {
1267            *out++ += (vl >> 16) * (*temp++ >> 12);
1268            *out++ += (vr >> 16) * (*temp++ >> 12);
1269            vl += vlInc;
1270            vr += vrInc;
1271        } while (--frameCount);
1272    }
1273    t->prevVolume[0] = vl;
1274    t->prevVolume[1] = vr;
1275    t->adjustVolumeRamp(aux != NULL);
1276}
1277
1278void AudioMixer::volumeStereo(track_t* t, int32_t* out, size_t frameCount, int32_t* temp,
1279        int32_t* aux)
1280{
1281    const int16_t vl = t->volume[0];
1282    const int16_t vr = t->volume[1];
1283
1284    if (CC_UNLIKELY(aux != NULL)) {
1285        const int16_t va = t->auxLevel;
1286        do {
1287            int16_t l = (int16_t)(*temp++ >> 12);
1288            int16_t r = (int16_t)(*temp++ >> 12);
1289            out[0] = mulAdd(l, vl, out[0]);
1290            int16_t a = (int16_t)(((int32_t)l + r) >> 1);
1291            out[1] = mulAdd(r, vr, out[1]);
1292            out += 2;
1293            aux[0] = mulAdd(a, va, aux[0]);
1294            aux++;
1295        } while (--frameCount);
1296    } else {
1297        do {
1298            int16_t l = (int16_t)(*temp++ >> 12);
1299            int16_t r = (int16_t)(*temp++ >> 12);
1300            out[0] = mulAdd(l, vl, out[0]);
1301            out[1] = mulAdd(r, vr, out[1]);
1302            out += 2;
1303        } while (--frameCount);
1304    }
1305}
1306
1307void AudioMixer::track__16BitsStereo(track_t* t, int32_t* out, size_t frameCount,
1308        int32_t* temp __unused, int32_t* aux)
1309{
1310    ALOGVV("track__16BitsStereo\n");
1311    const int16_t *in = static_cast<const int16_t *>(t->in);
1312
1313    if (CC_UNLIKELY(aux != NULL)) {
1314        int32_t l;
1315        int32_t r;
1316        // ramp gain
1317        if (CC_UNLIKELY(t->volumeInc[0]|t->volumeInc[1]|t->auxInc)) {
1318            int32_t vl = t->prevVolume[0];
1319            int32_t vr = t->prevVolume[1];
1320            int32_t va = t->prevAuxLevel;
1321            const int32_t vlInc = t->volumeInc[0];
1322            const int32_t vrInc = t->volumeInc[1];
1323            const int32_t vaInc = t->auxInc;
1324            // ALOGD("[1] %p: inc=%f, v0=%f, v1=%d, final=%f, count=%d",
1325            //        t, vlInc/65536.0f, vl/65536.0f, t->volume[0],
1326            //        (vl + vlInc*frameCount)/65536.0f, frameCount);
1327
1328            do {
1329                l = (int32_t)*in++;
1330                r = (int32_t)*in++;
1331                *out++ += (vl >> 16) * l;
1332                *out++ += (vr >> 16) * r;
1333                *aux++ += (va >> 17) * (l + r);
1334                vl += vlInc;
1335                vr += vrInc;
1336                va += vaInc;
1337            } while (--frameCount);
1338
1339            t->prevVolume[0] = vl;
1340            t->prevVolume[1] = vr;
1341            t->prevAuxLevel = va;
1342            t->adjustVolumeRamp(true);
1343        }
1344
1345        // constant gain
1346        else {
1347            const uint32_t vrl = t->volumeRL;
1348            const int16_t va = (int16_t)t->auxLevel;
1349            do {
1350                uint32_t rl = *reinterpret_cast<const uint32_t *>(in);
1351                int16_t a = (int16_t)(((int32_t)in[0] + in[1]) >> 1);
1352                in += 2;
1353                out[0] = mulAddRL(1, rl, vrl, out[0]);
1354                out[1] = mulAddRL(0, rl, vrl, out[1]);
1355                out += 2;
1356                aux[0] = mulAdd(a, va, aux[0]);
1357                aux++;
1358            } while (--frameCount);
1359        }
1360    } else {
1361        // ramp gain
1362        if (CC_UNLIKELY(t->volumeInc[0]|t->volumeInc[1])) {
1363            int32_t vl = t->prevVolume[0];
1364            int32_t vr = t->prevVolume[1];
1365            const int32_t vlInc = t->volumeInc[0];
1366            const int32_t vrInc = t->volumeInc[1];
1367
1368            // ALOGD("[1] %p: inc=%f, v0=%f, v1=%d, final=%f, count=%d",
1369            //        t, vlInc/65536.0f, vl/65536.0f, t->volume[0],
1370            //        (vl + vlInc*frameCount)/65536.0f, frameCount);
1371
1372            do {
1373                *out++ += (vl >> 16) * (int32_t) *in++;
1374                *out++ += (vr >> 16) * (int32_t) *in++;
1375                vl += vlInc;
1376                vr += vrInc;
1377            } while (--frameCount);
1378
1379            t->prevVolume[0] = vl;
1380            t->prevVolume[1] = vr;
1381            t->adjustVolumeRamp(false);
1382        }
1383
1384        // constant gain
1385        else {
1386            const uint32_t vrl = t->volumeRL;
1387            do {
1388                uint32_t rl = *reinterpret_cast<const uint32_t *>(in);
1389                in += 2;
1390                out[0] = mulAddRL(1, rl, vrl, out[0]);
1391                out[1] = mulAddRL(0, rl, vrl, out[1]);
1392                out += 2;
1393            } while (--frameCount);
1394        }
1395    }
1396    t->in = in;
1397}
1398
1399void AudioMixer::track__16BitsMono(track_t* t, int32_t* out, size_t frameCount,
1400        int32_t* temp __unused, int32_t* aux)
1401{
1402    ALOGVV("track__16BitsMono\n");
1403    const int16_t *in = static_cast<int16_t const *>(t->in);
1404
1405    if (CC_UNLIKELY(aux != NULL)) {
1406        // ramp gain
1407        if (CC_UNLIKELY(t->volumeInc[0]|t->volumeInc[1]|t->auxInc)) {
1408            int32_t vl = t->prevVolume[0];
1409            int32_t vr = t->prevVolume[1];
1410            int32_t va = t->prevAuxLevel;
1411            const int32_t vlInc = t->volumeInc[0];
1412            const int32_t vrInc = t->volumeInc[1];
1413            const int32_t vaInc = t->auxInc;
1414
1415            // ALOGD("[2] %p: inc=%f, v0=%f, v1=%d, final=%f, count=%d",
1416            //         t, vlInc/65536.0f, vl/65536.0f, t->volume[0],
1417            //         (vl + vlInc*frameCount)/65536.0f, frameCount);
1418
1419            do {
1420                int32_t l = *in++;
1421                *out++ += (vl >> 16) * l;
1422                *out++ += (vr >> 16) * l;
1423                *aux++ += (va >> 16) * l;
1424                vl += vlInc;
1425                vr += vrInc;
1426                va += vaInc;
1427            } while (--frameCount);
1428
1429            t->prevVolume[0] = vl;
1430            t->prevVolume[1] = vr;
1431            t->prevAuxLevel = va;
1432            t->adjustVolumeRamp(true);
1433        }
1434        // constant gain
1435        else {
1436            const int16_t vl = t->volume[0];
1437            const int16_t vr = t->volume[1];
1438            const int16_t va = (int16_t)t->auxLevel;
1439            do {
1440                int16_t l = *in++;
1441                out[0] = mulAdd(l, vl, out[0]);
1442                out[1] = mulAdd(l, vr, out[1]);
1443                out += 2;
1444                aux[0] = mulAdd(l, va, aux[0]);
1445                aux++;
1446            } while (--frameCount);
1447        }
1448    } else {
1449        // ramp gain
1450        if (CC_UNLIKELY(t->volumeInc[0]|t->volumeInc[1])) {
1451            int32_t vl = t->prevVolume[0];
1452            int32_t vr = t->prevVolume[1];
1453            const int32_t vlInc = t->volumeInc[0];
1454            const int32_t vrInc = t->volumeInc[1];
1455
1456            // ALOGD("[2] %p: inc=%f, v0=%f, v1=%d, final=%f, count=%d",
1457            //         t, vlInc/65536.0f, vl/65536.0f, t->volume[0],
1458            //         (vl + vlInc*frameCount)/65536.0f, frameCount);
1459
1460            do {
1461                int32_t l = *in++;
1462                *out++ += (vl >> 16) * l;
1463                *out++ += (vr >> 16) * l;
1464                vl += vlInc;
1465                vr += vrInc;
1466            } while (--frameCount);
1467
1468            t->prevVolume[0] = vl;
1469            t->prevVolume[1] = vr;
1470            t->adjustVolumeRamp(false);
1471        }
1472        // constant gain
1473        else {
1474            const int16_t vl = t->volume[0];
1475            const int16_t vr = t->volume[1];
1476            do {
1477                int16_t l = *in++;
1478                out[0] = mulAdd(l, vl, out[0]);
1479                out[1] = mulAdd(l, vr, out[1]);
1480                out += 2;
1481            } while (--frameCount);
1482        }
1483    }
1484    t->in = in;
1485}
1486
1487// no-op case
1488void AudioMixer::process__nop(state_t* state, int64_t pts)
1489{
1490    ALOGVV("process__nop\n");
1491    uint32_t e0 = state->enabledTracks;
1492    while (e0) {
1493        // process by group of tracks with same output buffer to
1494        // avoid multiple memset() on same buffer
1495        uint32_t e1 = e0, e2 = e0;
1496        int i = 31 - __builtin_clz(e1);
1497        {
1498            track_t& t1 = state->tracks[i];
1499            e2 &= ~(1<<i);
1500            while (e2) {
1501                i = 31 - __builtin_clz(e2);
1502                e2 &= ~(1<<i);
1503                track_t& t2 = state->tracks[i];
1504                if (CC_UNLIKELY(t2.mainBuffer != t1.mainBuffer)) {
1505                    e1 &= ~(1<<i);
1506                }
1507            }
1508            e0 &= ~(e1);
1509
1510            memset(t1.mainBuffer, 0, state->frameCount * t1.mMixerChannelCount
1511                    * audio_bytes_per_sample(t1.mMixerFormat));
1512        }
1513
1514        while (e1) {
1515            i = 31 - __builtin_clz(e1);
1516            e1 &= ~(1<<i);
1517            {
1518                track_t& t3 = state->tracks[i];
1519                size_t outFrames = state->frameCount;
1520                while (outFrames) {
1521                    t3.buffer.frameCount = outFrames;
1522                    int64_t outputPTS = calculateOutputPTS(
1523                        t3, pts, state->frameCount - outFrames);
1524                    t3.bufferProvider->getNextBuffer(&t3.buffer, outputPTS);
1525                    if (t3.buffer.raw == NULL) break;
1526                    outFrames -= t3.buffer.frameCount;
1527                    t3.bufferProvider->releaseBuffer(&t3.buffer);
1528                }
1529            }
1530        }
1531    }
1532}
1533
1534// generic code without resampling
1535void AudioMixer::process__genericNoResampling(state_t* state, int64_t pts)
1536{
1537    ALOGVV("process__genericNoResampling\n");
1538    int32_t outTemp[BLOCKSIZE * MAX_NUM_CHANNELS] __attribute__((aligned(32)));
1539
1540    // acquire each track's buffer
1541    uint32_t enabledTracks = state->enabledTracks;
1542    uint32_t e0 = enabledTracks;
1543    while (e0) {
1544        const int i = 31 - __builtin_clz(e0);
1545        e0 &= ~(1<<i);
1546        track_t& t = state->tracks[i];
1547        t.buffer.frameCount = state->frameCount;
1548        t.bufferProvider->getNextBuffer(&t.buffer, pts);
1549        t.frameCount = t.buffer.frameCount;
1550        t.in = t.buffer.raw;
1551    }
1552
1553    e0 = enabledTracks;
1554    while (e0) {
1555        // process by group of tracks with same output buffer to
1556        // optimize cache use
1557        uint32_t e1 = e0, e2 = e0;
1558        int j = 31 - __builtin_clz(e1);
1559        track_t& t1 = state->tracks[j];
1560        e2 &= ~(1<<j);
1561        while (e2) {
1562            j = 31 - __builtin_clz(e2);
1563            e2 &= ~(1<<j);
1564            track_t& t2 = state->tracks[j];
1565            if (CC_UNLIKELY(t2.mainBuffer != t1.mainBuffer)) {
1566                e1 &= ~(1<<j);
1567            }
1568        }
1569        e0 &= ~(e1);
1570        // this assumes output 16 bits stereo, no resampling
1571        int32_t *out = t1.mainBuffer;
1572        size_t numFrames = 0;
1573        do {
1574            memset(outTemp, 0, sizeof(outTemp));
1575            e2 = e1;
1576            while (e2) {
1577                const int i = 31 - __builtin_clz(e2);
1578                e2 &= ~(1<<i);
1579                track_t& t = state->tracks[i];
1580                size_t outFrames = BLOCKSIZE;
1581                int32_t *aux = NULL;
1582                if (CC_UNLIKELY(t.needs & NEEDS_AUX)) {
1583                    aux = t.auxBuffer + numFrames;
1584                }
1585                while (outFrames) {
1586                    // t.in == NULL can happen if the track was flushed just after having
1587                    // been enabled for mixing.
1588                   if (t.in == NULL) {
1589                        enabledTracks &= ~(1<<i);
1590                        e1 &= ~(1<<i);
1591                        break;
1592                    }
1593                    size_t inFrames = (t.frameCount > outFrames)?outFrames:t.frameCount;
1594                    if (inFrames > 0) {
1595                        t.hook(&t, outTemp + (BLOCKSIZE - outFrames) * t.mMixerChannelCount,
1596                                inFrames, state->resampleTemp, aux);
1597                        t.frameCount -= inFrames;
1598                        outFrames -= inFrames;
1599                        if (CC_UNLIKELY(aux != NULL)) {
1600                            aux += inFrames;
1601                        }
1602                    }
1603                    if (t.frameCount == 0 && outFrames) {
1604                        t.bufferProvider->releaseBuffer(&t.buffer);
1605                        t.buffer.frameCount = (state->frameCount - numFrames) -
1606                                (BLOCKSIZE - outFrames);
1607                        int64_t outputPTS = calculateOutputPTS(
1608                            t, pts, numFrames + (BLOCKSIZE - outFrames));
1609                        t.bufferProvider->getNextBuffer(&t.buffer, outputPTS);
1610                        t.in = t.buffer.raw;
1611                        if (t.in == NULL) {
1612                            enabledTracks &= ~(1<<i);
1613                            e1 &= ~(1<<i);
1614                            break;
1615                        }
1616                        t.frameCount = t.buffer.frameCount;
1617                    }
1618                }
1619            }
1620
1621            convertMixerFormat(out, t1.mMixerFormat, outTemp, t1.mMixerInFormat,
1622                    BLOCKSIZE * t1.mMixerChannelCount);
1623            // TODO: fix ugly casting due to choice of out pointer type
1624            out = reinterpret_cast<int32_t*>((uint8_t*)out
1625                    + BLOCKSIZE * t1.mMixerChannelCount
1626                        * audio_bytes_per_sample(t1.mMixerFormat));
1627            numFrames += BLOCKSIZE;
1628        } while (numFrames < state->frameCount);
1629    }
1630
1631    // release each track's buffer
1632    e0 = enabledTracks;
1633    while (e0) {
1634        const int i = 31 - __builtin_clz(e0);
1635        e0 &= ~(1<<i);
1636        track_t& t = state->tracks[i];
1637        t.bufferProvider->releaseBuffer(&t.buffer);
1638    }
1639}
1640
1641
1642// generic code with resampling
1643void AudioMixer::process__genericResampling(state_t* state, int64_t pts)
1644{
1645    ALOGVV("process__genericResampling\n");
1646    // this const just means that local variable outTemp doesn't change
1647    int32_t* const outTemp = state->outputTemp;
1648    size_t numFrames = state->frameCount;
1649
1650    uint32_t e0 = state->enabledTracks;
1651    while (e0) {
1652        // process by group of tracks with same output buffer
1653        // to optimize cache use
1654        uint32_t e1 = e0, e2 = e0;
1655        int j = 31 - __builtin_clz(e1);
1656        track_t& t1 = state->tracks[j];
1657        e2 &= ~(1<<j);
1658        while (e2) {
1659            j = 31 - __builtin_clz(e2);
1660            e2 &= ~(1<<j);
1661            track_t& t2 = state->tracks[j];
1662            if (CC_UNLIKELY(t2.mainBuffer != t1.mainBuffer)) {
1663                e1 &= ~(1<<j);
1664            }
1665        }
1666        e0 &= ~(e1);
1667        int32_t *out = t1.mainBuffer;
1668        memset(outTemp, 0, sizeof(*outTemp) * t1.mMixerChannelCount * state->frameCount);
1669        while (e1) {
1670            const int i = 31 - __builtin_clz(e1);
1671            e1 &= ~(1<<i);
1672            track_t& t = state->tracks[i];
1673            int32_t *aux = NULL;
1674            if (CC_UNLIKELY(t.needs & NEEDS_AUX)) {
1675                aux = t.auxBuffer;
1676            }
1677
1678            // this is a little goofy, on the resampling case we don't
1679            // acquire/release the buffers because it's done by
1680            // the resampler.
1681            if (t.needs & NEEDS_RESAMPLE) {
1682                t.resampler->setPTS(pts);
1683                t.hook(&t, outTemp, numFrames, state->resampleTemp, aux);
1684            } else {
1685
1686                size_t outFrames = 0;
1687
1688                while (outFrames < numFrames) {
1689                    t.buffer.frameCount = numFrames - outFrames;
1690                    int64_t outputPTS = calculateOutputPTS(t, pts, outFrames);
1691                    t.bufferProvider->getNextBuffer(&t.buffer, outputPTS);
1692                    t.in = t.buffer.raw;
1693                    // t.in == NULL can happen if the track was flushed just after having
1694                    // been enabled for mixing.
1695                    if (t.in == NULL) break;
1696
1697                    if (CC_UNLIKELY(aux != NULL)) {
1698                        aux += outFrames;
1699                    }
1700                    t.hook(&t, outTemp + outFrames * t.mMixerChannelCount, t.buffer.frameCount,
1701                            state->resampleTemp, aux);
1702                    outFrames += t.buffer.frameCount;
1703                    t.bufferProvider->releaseBuffer(&t.buffer);
1704                }
1705            }
1706        }
1707        convertMixerFormat(out, t1.mMixerFormat,
1708                outTemp, t1.mMixerInFormat, numFrames * t1.mMixerChannelCount);
1709    }
1710}
1711
1712// one track, 16 bits stereo without resampling is the most common case
1713void AudioMixer::process__OneTrack16BitsStereoNoResampling(state_t* state,
1714                                                           int64_t pts)
1715{
1716    ALOGVV("process__OneTrack16BitsStereoNoResampling\n");
1717    // This method is only called when state->enabledTracks has exactly
1718    // one bit set.  The asserts below would verify this, but are commented out
1719    // since the whole point of this method is to optimize performance.
1720    //ALOG_ASSERT(0 != state->enabledTracks, "no tracks enabled");
1721    const int i = 31 - __builtin_clz(state->enabledTracks);
1722    //ALOG_ASSERT((1 << i) == state->enabledTracks, "more than 1 track enabled");
1723    const track_t& t = state->tracks[i];
1724
1725    AudioBufferProvider::Buffer& b(t.buffer);
1726
1727    int32_t* out = t.mainBuffer;
1728    float *fout = reinterpret_cast<float*>(out);
1729    size_t numFrames = state->frameCount;
1730
1731    const int16_t vl = t.volume[0];
1732    const int16_t vr = t.volume[1];
1733    const uint32_t vrl = t.volumeRL;
1734    while (numFrames) {
1735        b.frameCount = numFrames;
1736        int64_t outputPTS = calculateOutputPTS(t, pts, out - t.mainBuffer);
1737        t.bufferProvider->getNextBuffer(&b, outputPTS);
1738        const int16_t *in = b.i16;
1739
1740        // in == NULL can happen if the track was flushed just after having
1741        // been enabled for mixing.
1742        if (in == NULL || (((uintptr_t)in) & 3)) {
1743            memset(out, 0, numFrames
1744                    * t.mMixerChannelCount * audio_bytes_per_sample(t.mMixerFormat));
1745            ALOGE_IF((((uintptr_t)in) & 3), "process stereo track: input buffer alignment pb: "
1746                                              "buffer %p track %d, channels %d, needs %08x",
1747                    in, i, t.channelCount, t.needs);
1748            return;
1749        }
1750        size_t outFrames = b.frameCount;
1751
1752        switch (t.mMixerFormat) {
1753        case AUDIO_FORMAT_PCM_FLOAT:
1754            do {
1755                uint32_t rl = *reinterpret_cast<const uint32_t *>(in);
1756                in += 2;
1757                int32_t l = mulRL(1, rl, vrl);
1758                int32_t r = mulRL(0, rl, vrl);
1759                *fout++ = float_from_q4_27(l);
1760                *fout++ = float_from_q4_27(r);
1761                // Note: In case of later int16_t sink output,
1762                // conversion and clamping is done by memcpy_to_i16_from_float().
1763            } while (--outFrames);
1764            break;
1765        case AUDIO_FORMAT_PCM_16_BIT:
1766            if (CC_UNLIKELY(uint32_t(vl) > UNITY_GAIN_INT || uint32_t(vr) > UNITY_GAIN_INT)) {
1767                // volume is boosted, so we might need to clamp even though
1768                // we process only one track.
1769                do {
1770                    uint32_t rl = *reinterpret_cast<const uint32_t *>(in);
1771                    in += 2;
1772                    int32_t l = mulRL(1, rl, vrl) >> 12;
1773                    int32_t r = mulRL(0, rl, vrl) >> 12;
1774                    // clamping...
1775                    l = clamp16(l);
1776                    r = clamp16(r);
1777                    *out++ = (r<<16) | (l & 0xFFFF);
1778                } while (--outFrames);
1779            } else {
1780                do {
1781                    uint32_t rl = *reinterpret_cast<const uint32_t *>(in);
1782                    in += 2;
1783                    int32_t l = mulRL(1, rl, vrl) >> 12;
1784                    int32_t r = mulRL(0, rl, vrl) >> 12;
1785                    *out++ = (r<<16) | (l & 0xFFFF);
1786                } while (--outFrames);
1787            }
1788            break;
1789        default:
1790            LOG_ALWAYS_FATAL("bad mixer format: %d", t.mMixerFormat);
1791        }
1792        numFrames -= b.frameCount;
1793        t.bufferProvider->releaseBuffer(&b);
1794    }
1795}
1796
1797#if 0
1798// 2 tracks is also a common case
1799// NEVER used in current implementation of process__validate()
1800// only use if the 2 tracks have the same output buffer
1801void AudioMixer::process__TwoTracks16BitsStereoNoResampling(state_t* state,
1802                                                            int64_t pts)
1803{
1804    int i;
1805    uint32_t en = state->enabledTracks;
1806
1807    i = 31 - __builtin_clz(en);
1808    const track_t& t0 = state->tracks[i];
1809    AudioBufferProvider::Buffer& b0(t0.buffer);
1810
1811    en &= ~(1<<i);
1812    i = 31 - __builtin_clz(en);
1813    const track_t& t1 = state->tracks[i];
1814    AudioBufferProvider::Buffer& b1(t1.buffer);
1815
1816    const int16_t *in0;
1817    const int16_t vl0 = t0.volume[0];
1818    const int16_t vr0 = t0.volume[1];
1819    size_t frameCount0 = 0;
1820
1821    const int16_t *in1;
1822    const int16_t vl1 = t1.volume[0];
1823    const int16_t vr1 = t1.volume[1];
1824    size_t frameCount1 = 0;
1825
1826    //FIXME: only works if two tracks use same buffer
1827    int32_t* out = t0.mainBuffer;
1828    size_t numFrames = state->frameCount;
1829    const int16_t *buff = NULL;
1830
1831
1832    while (numFrames) {
1833
1834        if (frameCount0 == 0) {
1835            b0.frameCount = numFrames;
1836            int64_t outputPTS = calculateOutputPTS(t0, pts,
1837                                                   out - t0.mainBuffer);
1838            t0.bufferProvider->getNextBuffer(&b0, outputPTS);
1839            if (b0.i16 == NULL) {
1840                if (buff == NULL) {
1841                    buff = new int16_t[MAX_NUM_CHANNELS * state->frameCount];
1842                }
1843                in0 = buff;
1844                b0.frameCount = numFrames;
1845            } else {
1846                in0 = b0.i16;
1847            }
1848            frameCount0 = b0.frameCount;
1849        }
1850        if (frameCount1 == 0) {
1851            b1.frameCount = numFrames;
1852            int64_t outputPTS = calculateOutputPTS(t1, pts,
1853                                                   out - t0.mainBuffer);
1854            t1.bufferProvider->getNextBuffer(&b1, outputPTS);
1855            if (b1.i16 == NULL) {
1856                if (buff == NULL) {
1857                    buff = new int16_t[MAX_NUM_CHANNELS * state->frameCount];
1858                }
1859                in1 = buff;
1860                b1.frameCount = numFrames;
1861            } else {
1862                in1 = b1.i16;
1863            }
1864            frameCount1 = b1.frameCount;
1865        }
1866
1867        size_t outFrames = frameCount0 < frameCount1?frameCount0:frameCount1;
1868
1869        numFrames -= outFrames;
1870        frameCount0 -= outFrames;
1871        frameCount1 -= outFrames;
1872
1873        do {
1874            int32_t l0 = *in0++;
1875            int32_t r0 = *in0++;
1876            l0 = mul(l0, vl0);
1877            r0 = mul(r0, vr0);
1878            int32_t l = *in1++;
1879            int32_t r = *in1++;
1880            l = mulAdd(l, vl1, l0) >> 12;
1881            r = mulAdd(r, vr1, r0) >> 12;
1882            // clamping...
1883            l = clamp16(l);
1884            r = clamp16(r);
1885            *out++ = (r<<16) | (l & 0xFFFF);
1886        } while (--outFrames);
1887
1888        if (frameCount0 == 0) {
1889            t0.bufferProvider->releaseBuffer(&b0);
1890        }
1891        if (frameCount1 == 0) {
1892            t1.bufferProvider->releaseBuffer(&b1);
1893        }
1894    }
1895
1896    delete [] buff;
1897}
1898#endif
1899
1900int64_t AudioMixer::calculateOutputPTS(const track_t& t, int64_t basePTS,
1901                                       int outputFrameIndex)
1902{
1903    if (AudioBufferProvider::kInvalidPTS == basePTS) {
1904        return AudioBufferProvider::kInvalidPTS;
1905    }
1906
1907    return basePTS + ((outputFrameIndex * sLocalTimeFreq) / t.sampleRate);
1908}
1909
1910/*static*/ uint64_t AudioMixer::sLocalTimeFreq;
1911/*static*/ pthread_once_t AudioMixer::sOnceControl = PTHREAD_ONCE_INIT;
1912
1913/*static*/ void AudioMixer::sInitRoutine()
1914{
1915    LocalClock lc;
1916    sLocalTimeFreq = lc.getLocalFreq(); // for the resampler
1917
1918    DownmixerBufferProvider::init(); // for the downmixer
1919}
1920
1921/* TODO: consider whether this level of optimization is necessary.
1922 * Perhaps just stick with a single for loop.
1923 */
1924
1925// Needs to derive a compile time constant (constexpr).  Could be targeted to go
1926// to a MONOVOL mixtype based on MAX_NUM_VOLUMES, but that's an unnecessary complication.
1927#define MIXTYPE_MONOVOL(mixtype) (mixtype == MIXTYPE_MULTI ? MIXTYPE_MULTI_MONOVOL : \
1928        mixtype == MIXTYPE_MULTI_SAVEONLY ? MIXTYPE_MULTI_SAVEONLY_MONOVOL : mixtype)
1929
1930/* MIXTYPE     (see AudioMixerOps.h MIXTYPE_* enumeration)
1931 * TO: int32_t (Q4.27) or float
1932 * TI: int32_t (Q4.27) or int16_t (Q0.15) or float
1933 * TA: int32_t (Q4.27)
1934 */
1935template <int MIXTYPE,
1936        typename TO, typename TI, typename TV, typename TA, typename TAV>
1937static void volumeRampMulti(uint32_t channels, TO* out, size_t frameCount,
1938        const TI* in, TA* aux, TV *vol, const TV *volinc, TAV *vola, TAV volainc)
1939{
1940    switch (channels) {
1941    case 1:
1942        volumeRampMulti<MIXTYPE, 1>(out, frameCount, in, aux, vol, volinc, vola, volainc);
1943        break;
1944    case 2:
1945        volumeRampMulti<MIXTYPE, 2>(out, frameCount, in, aux, vol, volinc, vola, volainc);
1946        break;
1947    case 3:
1948        volumeRampMulti<MIXTYPE_MONOVOL(MIXTYPE), 3>(out,
1949                frameCount, in, aux, vol, volinc, vola, volainc);
1950        break;
1951    case 4:
1952        volumeRampMulti<MIXTYPE_MONOVOL(MIXTYPE), 4>(out,
1953                frameCount, in, aux, vol, volinc, vola, volainc);
1954        break;
1955    case 5:
1956        volumeRampMulti<MIXTYPE_MONOVOL(MIXTYPE), 5>(out,
1957                frameCount, in, aux, vol, volinc, vola, volainc);
1958        break;
1959    case 6:
1960        volumeRampMulti<MIXTYPE_MONOVOL(MIXTYPE), 6>(out,
1961                frameCount, in, aux, vol, volinc, vola, volainc);
1962        break;
1963    case 7:
1964        volumeRampMulti<MIXTYPE_MONOVOL(MIXTYPE), 7>(out,
1965                frameCount, in, aux, vol, volinc, vola, volainc);
1966        break;
1967    case 8:
1968        volumeRampMulti<MIXTYPE_MONOVOL(MIXTYPE), 8>(out,
1969                frameCount, in, aux, vol, volinc, vola, volainc);
1970        break;
1971    }
1972}
1973
1974/* MIXTYPE     (see AudioMixerOps.h MIXTYPE_* enumeration)
1975 * TO: int32_t (Q4.27) or float
1976 * TI: int32_t (Q4.27) or int16_t (Q0.15) or float
1977 * TA: int32_t (Q4.27)
1978 */
1979template <int MIXTYPE,
1980        typename TO, typename TI, typename TV, typename TA, typename TAV>
1981static void volumeMulti(uint32_t channels, TO* out, size_t frameCount,
1982        const TI* in, TA* aux, const TV *vol, TAV vola)
1983{
1984    switch (channels) {
1985    case 1:
1986        volumeMulti<MIXTYPE, 1>(out, frameCount, in, aux, vol, vola);
1987        break;
1988    case 2:
1989        volumeMulti<MIXTYPE, 2>(out, frameCount, in, aux, vol, vola);
1990        break;
1991    case 3:
1992        volumeMulti<MIXTYPE_MONOVOL(MIXTYPE), 3>(out, frameCount, in, aux, vol, vola);
1993        break;
1994    case 4:
1995        volumeMulti<MIXTYPE_MONOVOL(MIXTYPE), 4>(out, frameCount, in, aux, vol, vola);
1996        break;
1997    case 5:
1998        volumeMulti<MIXTYPE_MONOVOL(MIXTYPE), 5>(out, frameCount, in, aux, vol, vola);
1999        break;
2000    case 6:
2001        volumeMulti<MIXTYPE_MONOVOL(MIXTYPE), 6>(out, frameCount, in, aux, vol, vola);
2002        break;
2003    case 7:
2004        volumeMulti<MIXTYPE_MONOVOL(MIXTYPE), 7>(out, frameCount, in, aux, vol, vola);
2005        break;
2006    case 8:
2007        volumeMulti<MIXTYPE_MONOVOL(MIXTYPE), 8>(out, frameCount, in, aux, vol, vola);
2008        break;
2009    }
2010}
2011
2012/* MIXTYPE     (see AudioMixerOps.h MIXTYPE_* enumeration)
2013 * USEFLOATVOL (set to true if float volume is used)
2014 * ADJUSTVOL   (set to true if volume ramp parameters needs adjustment afterwards)
2015 * TO: int32_t (Q4.27) or float
2016 * TI: int32_t (Q4.27) or int16_t (Q0.15) or float
2017 * TA: int32_t (Q4.27)
2018 */
2019template <int MIXTYPE, bool USEFLOATVOL, bool ADJUSTVOL,
2020    typename TO, typename TI, typename TA>
2021void AudioMixer::volumeMix(TO *out, size_t outFrames,
2022        const TI *in, TA *aux, bool ramp, AudioMixer::track_t *t)
2023{
2024    if (USEFLOATVOL) {
2025        if (ramp) {
2026            volumeRampMulti<MIXTYPE>(t->mMixerChannelCount, out, outFrames, in, aux,
2027                    t->mPrevVolume, t->mVolumeInc, &t->prevAuxLevel, t->auxInc);
2028            if (ADJUSTVOL) {
2029                t->adjustVolumeRamp(aux != NULL, true);
2030            }
2031        } else {
2032            volumeMulti<MIXTYPE>(t->mMixerChannelCount, out, outFrames, in, aux,
2033                    t->mVolume, t->auxLevel);
2034        }
2035    } else {
2036        if (ramp) {
2037            volumeRampMulti<MIXTYPE>(t->mMixerChannelCount, out, outFrames, in, aux,
2038                    t->prevVolume, t->volumeInc, &t->prevAuxLevel, t->auxInc);
2039            if (ADJUSTVOL) {
2040                t->adjustVolumeRamp(aux != NULL);
2041            }
2042        } else {
2043            volumeMulti<MIXTYPE>(t->mMixerChannelCount, out, outFrames, in, aux,
2044                    t->volume, t->auxLevel);
2045        }
2046    }
2047}
2048
2049/* This process hook is called when there is a single track without
2050 * aux buffer, volume ramp, or resampling.
2051 * TODO: Update the hook selection: this can properly handle aux and ramp.
2052 *
2053 * MIXTYPE     (see AudioMixerOps.h MIXTYPE_* enumeration)
2054 * TO: int32_t (Q4.27) or float
2055 * TI: int32_t (Q4.27) or int16_t (Q0.15) or float
2056 * TA: int32_t (Q4.27)
2057 */
2058template <int MIXTYPE, typename TO, typename TI, typename TA>
2059void AudioMixer::process_NoResampleOneTrack(state_t* state, int64_t pts)
2060{
2061    ALOGVV("process_NoResampleOneTrack\n");
2062    // CLZ is faster than CTZ on ARM, though really not sure if true after 31 - clz.
2063    const int i = 31 - __builtin_clz(state->enabledTracks);
2064    ALOG_ASSERT((1 << i) == state->enabledTracks, "more than 1 track enabled");
2065    track_t *t = &state->tracks[i];
2066    const uint32_t channels = t->mMixerChannelCount;
2067    TO* out = reinterpret_cast<TO*>(t->mainBuffer);
2068    TA* aux = reinterpret_cast<TA*>(t->auxBuffer);
2069    const bool ramp = t->needsRamp();
2070
2071    for (size_t numFrames = state->frameCount; numFrames; ) {
2072        AudioBufferProvider::Buffer& b(t->buffer);
2073        // get input buffer
2074        b.frameCount = numFrames;
2075        const int64_t outputPTS = calculateOutputPTS(*t, pts, state->frameCount - numFrames);
2076        t->bufferProvider->getNextBuffer(&b, outputPTS);
2077        const TI *in = reinterpret_cast<TI*>(b.raw);
2078
2079        // in == NULL can happen if the track was flushed just after having
2080        // been enabled for mixing.
2081        if (in == NULL || (((uintptr_t)in) & 3)) {
2082            memset(out, 0, numFrames
2083                    * channels * audio_bytes_per_sample(t->mMixerFormat));
2084            ALOGE_IF((((uintptr_t)in) & 3), "process_NoResampleOneTrack: bus error: "
2085                    "buffer %p track %p, channels %d, needs %#x",
2086                    in, t, t->channelCount, t->needs);
2087            return;
2088        }
2089
2090        const size_t outFrames = b.frameCount;
2091        volumeMix<MIXTYPE, is_same<TI, float>::value, false> (
2092                out, outFrames, in, aux, ramp, t);
2093
2094        out += outFrames * channels;
2095        if (aux != NULL) {
2096            aux += channels;
2097        }
2098        numFrames -= b.frameCount;
2099
2100        // release buffer
2101        t->bufferProvider->releaseBuffer(&b);
2102    }
2103    if (ramp) {
2104        t->adjustVolumeRamp(aux != NULL, is_same<TI, float>::value);
2105    }
2106}
2107
2108/* This track hook is called to do resampling then mixing,
2109 * pulling from the track's upstream AudioBufferProvider.
2110 *
2111 * MIXTYPE     (see AudioMixerOps.h MIXTYPE_* enumeration)
2112 * TO: int32_t (Q4.27) or float
2113 * TI: int32_t (Q4.27) or int16_t (Q0.15) or float
2114 * TA: int32_t (Q4.27)
2115 */
2116template <int MIXTYPE, typename TO, typename TI, typename TA>
2117void AudioMixer::track__Resample(track_t* t, TO* out, size_t outFrameCount, TO* temp, TA* aux)
2118{
2119    ALOGVV("track__Resample\n");
2120    t->resampler->setSampleRate(t->sampleRate);
2121    const bool ramp = t->needsRamp();
2122    if (ramp || aux != NULL) {
2123        // if ramp:        resample with unity gain to temp buffer and scale/mix in 2nd step.
2124        // if aux != NULL: resample with unity gain to temp buffer then apply send level.
2125
2126        t->resampler->setVolume(UNITY_GAIN_FLOAT, UNITY_GAIN_FLOAT);
2127        memset(temp, 0, outFrameCount * t->mMixerChannelCount * sizeof(TO));
2128        t->resampler->resample((int32_t*)temp, outFrameCount, t->bufferProvider);
2129
2130        volumeMix<MIXTYPE, is_same<TI, float>::value, true>(
2131                out, outFrameCount, temp, aux, ramp, t);
2132
2133    } else { // constant volume gain
2134        t->resampler->setVolume(t->mVolume[0], t->mVolume[1]);
2135        t->resampler->resample((int32_t*)out, outFrameCount, t->bufferProvider);
2136    }
2137}
2138
2139/* This track hook is called to mix a track, when no resampling is required.
2140 * The input buffer should be present in t->in.
2141 *
2142 * MIXTYPE     (see AudioMixerOps.h MIXTYPE_* enumeration)
2143 * TO: int32_t (Q4.27) or float
2144 * TI: int32_t (Q4.27) or int16_t (Q0.15) or float
2145 * TA: int32_t (Q4.27)
2146 */
2147template <int MIXTYPE, typename TO, typename TI, typename TA>
2148void AudioMixer::track__NoResample(track_t* t, TO* out, size_t frameCount,
2149        TO* temp __unused, TA* aux)
2150{
2151    ALOGVV("track__NoResample\n");
2152    const TI *in = static_cast<const TI *>(t->in);
2153
2154    volumeMix<MIXTYPE, is_same<TI, float>::value, true>(
2155            out, frameCount, in, aux, t->needsRamp(), t);
2156
2157    // MIXTYPE_MONOEXPAND reads a single input channel and expands to NCHAN output channels.
2158    // MIXTYPE_MULTI reads NCHAN input channels and places to NCHAN output channels.
2159    in += (MIXTYPE == MIXTYPE_MONOEXPAND) ? frameCount : frameCount * t->mMixerChannelCount;
2160    t->in = in;
2161}
2162
2163/* The Mixer engine generates either int32_t (Q4_27) or float data.
2164 * We use this function to convert the engine buffers
2165 * to the desired mixer output format, either int16_t (Q.15) or float.
2166 */
2167void AudioMixer::convertMixerFormat(void *out, audio_format_t mixerOutFormat,
2168        void *in, audio_format_t mixerInFormat, size_t sampleCount)
2169{
2170    switch (mixerInFormat) {
2171    case AUDIO_FORMAT_PCM_FLOAT:
2172        switch (mixerOutFormat) {
2173        case AUDIO_FORMAT_PCM_FLOAT:
2174            memcpy(out, in, sampleCount * sizeof(float)); // MEMCPY. TODO optimize out
2175            break;
2176        case AUDIO_FORMAT_PCM_16_BIT:
2177            memcpy_to_i16_from_float((int16_t*)out, (float*)in, sampleCount);
2178            break;
2179        default:
2180            LOG_ALWAYS_FATAL("bad mixerOutFormat: %#x", mixerOutFormat);
2181            break;
2182        }
2183        break;
2184    case AUDIO_FORMAT_PCM_16_BIT:
2185        switch (mixerOutFormat) {
2186        case AUDIO_FORMAT_PCM_FLOAT:
2187            memcpy_to_float_from_q4_27((float*)out, (int32_t*)in, sampleCount);
2188            break;
2189        case AUDIO_FORMAT_PCM_16_BIT:
2190            // two int16_t are produced per iteration
2191            ditherAndClamp((int32_t*)out, (int32_t*)in, sampleCount >> 1);
2192            break;
2193        default:
2194            LOG_ALWAYS_FATAL("bad mixerOutFormat: %#x", mixerOutFormat);
2195            break;
2196        }
2197        break;
2198    default:
2199        LOG_ALWAYS_FATAL("bad mixerInFormat: %#x", mixerInFormat);
2200        break;
2201    }
2202}
2203
2204/* Returns the proper track hook to use for mixing the track into the output buffer.
2205 */
2206AudioMixer::hook_t AudioMixer::getTrackHook(int trackType, uint32_t channelCount,
2207        audio_format_t mixerInFormat, audio_format_t mixerOutFormat __unused)
2208{
2209    if (!kUseNewMixer && channelCount == FCC_2 && mixerInFormat == AUDIO_FORMAT_PCM_16_BIT) {
2210        switch (trackType) {
2211        case TRACKTYPE_NOP:
2212            return track__nop;
2213        case TRACKTYPE_RESAMPLE:
2214            return track__genericResample;
2215        case TRACKTYPE_NORESAMPLEMONO:
2216            return track__16BitsMono;
2217        case TRACKTYPE_NORESAMPLE:
2218            return track__16BitsStereo;
2219        default:
2220            LOG_ALWAYS_FATAL("bad trackType: %d", trackType);
2221            break;
2222        }
2223    }
2224    LOG_ALWAYS_FATAL_IF(channelCount > MAX_NUM_CHANNELS);
2225    switch (trackType) {
2226    case TRACKTYPE_NOP:
2227        return track__nop;
2228    case TRACKTYPE_RESAMPLE:
2229        switch (mixerInFormat) {
2230        case AUDIO_FORMAT_PCM_FLOAT:
2231            return (AudioMixer::hook_t)
2232                    track__Resample<MIXTYPE_MULTI, float /*TO*/, float /*TI*/, int32_t /*TA*/>;
2233        case AUDIO_FORMAT_PCM_16_BIT:
2234            return (AudioMixer::hook_t)\
2235                    track__Resample<MIXTYPE_MULTI, int32_t, int16_t, int32_t>;
2236        default:
2237            LOG_ALWAYS_FATAL("bad mixerInFormat: %#x", mixerInFormat);
2238            break;
2239        }
2240        break;
2241    case TRACKTYPE_NORESAMPLEMONO:
2242        switch (mixerInFormat) {
2243        case AUDIO_FORMAT_PCM_FLOAT:
2244            return (AudioMixer::hook_t)
2245                    track__NoResample<MIXTYPE_MONOEXPAND, float, float, int32_t>;
2246        case AUDIO_FORMAT_PCM_16_BIT:
2247            return (AudioMixer::hook_t)
2248                    track__NoResample<MIXTYPE_MONOEXPAND, int32_t, int16_t, int32_t>;
2249        default:
2250            LOG_ALWAYS_FATAL("bad mixerInFormat: %#x", mixerInFormat);
2251            break;
2252        }
2253        break;
2254    case TRACKTYPE_NORESAMPLE:
2255        switch (mixerInFormat) {
2256        case AUDIO_FORMAT_PCM_FLOAT:
2257            return (AudioMixer::hook_t)
2258                    track__NoResample<MIXTYPE_MULTI, float, float, int32_t>;
2259        case AUDIO_FORMAT_PCM_16_BIT:
2260            return (AudioMixer::hook_t)
2261                    track__NoResample<MIXTYPE_MULTI, int32_t, int16_t, int32_t>;
2262        default:
2263            LOG_ALWAYS_FATAL("bad mixerInFormat: %#x", mixerInFormat);
2264            break;
2265        }
2266        break;
2267    default:
2268        LOG_ALWAYS_FATAL("bad trackType: %d", trackType);
2269        break;
2270    }
2271    return NULL;
2272}
2273
2274/* Returns the proper process hook for mixing tracks. Currently works only for
2275 * PROCESSTYPE_NORESAMPLEONETRACK, a mix involving one track, no resampling.
2276 */
2277AudioMixer::process_hook_t AudioMixer::getProcessHook(int processType, uint32_t channelCount,
2278        audio_format_t mixerInFormat, audio_format_t mixerOutFormat)
2279{
2280    if (processType != PROCESSTYPE_NORESAMPLEONETRACK) { // Only NORESAMPLEONETRACK
2281        LOG_ALWAYS_FATAL("bad processType: %d", processType);
2282        return NULL;
2283    }
2284    if (!kUseNewMixer && channelCount == FCC_2 && mixerInFormat == AUDIO_FORMAT_PCM_16_BIT) {
2285        return process__OneTrack16BitsStereoNoResampling;
2286    }
2287    LOG_ALWAYS_FATAL_IF(channelCount > MAX_NUM_CHANNELS);
2288    switch (mixerInFormat) {
2289    case AUDIO_FORMAT_PCM_FLOAT:
2290        switch (mixerOutFormat) {
2291        case AUDIO_FORMAT_PCM_FLOAT:
2292            return process_NoResampleOneTrack<MIXTYPE_MULTI_SAVEONLY,
2293                    float /*TO*/, float /*TI*/, int32_t /*TA*/>;
2294        case AUDIO_FORMAT_PCM_16_BIT:
2295            return process_NoResampleOneTrack<MIXTYPE_MULTI_SAVEONLY,
2296                    int16_t, float, int32_t>;
2297        default:
2298            LOG_ALWAYS_FATAL("bad mixerOutFormat: %#x", mixerOutFormat);
2299            break;
2300        }
2301        break;
2302    case AUDIO_FORMAT_PCM_16_BIT:
2303        switch (mixerOutFormat) {
2304        case AUDIO_FORMAT_PCM_FLOAT:
2305            return process_NoResampleOneTrack<MIXTYPE_MULTI_SAVEONLY,
2306                    float, int16_t, int32_t>;
2307        case AUDIO_FORMAT_PCM_16_BIT:
2308            return process_NoResampleOneTrack<MIXTYPE_MULTI_SAVEONLY,
2309                    int16_t, int16_t, int32_t>;
2310        default:
2311            LOG_ALWAYS_FATAL("bad mixerOutFormat: %#x", mixerOutFormat);
2312            break;
2313        }
2314        break;
2315    default:
2316        LOG_ALWAYS_FATAL("bad mixerInFormat: %#x", mixerInFormat);
2317        break;
2318    }
2319    return NULL;
2320}
2321
2322// ----------------------------------------------------------------------------
2323}; // namespace android
2324