AudioMixer.cpp revision 9c56d4ae6212c21ce5fd71ed534eb195983a07c1
1/* //device/include/server/AudioFlinger/AudioMixer.cpp
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 <assert.h>
22#include <stdint.h>
23#include <string.h>
24#include <stdlib.h>
25#include <sys/types.h>
26
27#include <utils/Errors.h>
28#include <utils/Log.h>
29
30#include <cutils/bitops.h>
31
32#include <system/audio.h>
33
34#include <audio_utils/primitives.h>
35
36#include "AudioMixer.h"
37
38namespace android {
39
40// ----------------------------------------------------------------------------
41
42AudioMixer::AudioMixer(size_t frameCount, uint32_t sampleRate)
43    :   mTrackNames(0), mSampleRate(sampleRate)
44{
45    // AudioMixer is not yet capable of multi-channel beyond stereo
46    assert(2 == MAX_NUM_CHANNELS);
47    mState.enabledTracks= 0;
48    mState.needsChanged = 0;
49    mState.frameCount   = frameCount;
50    mState.outputTemp   = NULL;
51    mState.resampleTemp = NULL;
52    mState.hook         = process__nop;
53    track_t* t = mState.tracks;
54    for (unsigned i=0 ; i < MAX_NUM_TRACKS ; i++) {
55        t->needs = 0;
56        t->volume[0] = UNITY_GAIN;
57        t->volume[1] = UNITY_GAIN;
58        // no initialization needed
59        // t->prevVolume[0]
60        // t->prevVolume[1]
61        t->volumeInc[0] = 0;
62        t->volumeInc[1] = 0;
63        t->auxLevel = 0;
64        t->auxInc = 0;
65        // no initialization needed
66        // t->prevAuxLevel
67        // t->frameCount
68        t->channelCount = 2;
69        t->enabled = 0;
70        t->format = 16;
71        t->channelMask = AUDIO_CHANNEL_OUT_STEREO;
72        t->buffer.raw = 0;
73        t->bufferProvider = NULL;
74        t->hook = NULL;
75        t->resampler = NULL;
76        t->sampleRate = mSampleRate;
77        t->in = NULL;
78        t->mainBuffer = NULL;
79        t->auxBuffer = NULL;
80        t++;
81    }
82}
83
84AudioMixer::~AudioMixer()
85{
86    track_t* t = mState.tracks;
87    for (unsigned i=0 ; i < MAX_NUM_TRACKS ; i++) {
88        delete t->resampler;
89        t++;
90    }
91    delete [] mState.outputTemp;
92    delete [] mState.resampleTemp;
93}
94
95int AudioMixer::getTrackName()
96{
97    uint32_t names = mTrackNames;
98    uint32_t mask = 1;
99    int n = 0;
100    while (names & mask) {
101        mask <<= 1;
102        n++;
103    }
104    if (mask) {
105        ALOGV("add track (%d)", n);
106        mTrackNames |= mask;
107        return TRACK0 + n;
108    }
109    return -1;
110}
111
112void AudioMixer::invalidateState(uint32_t mask)
113{
114    if (mask) {
115        mState.needsChanged |= mask;
116        mState.hook = process__validate;
117    }
118 }
119
120void AudioMixer::deleteTrackName(int name)
121{
122    name -= TRACK0;
123    assert(uint32_t(name) < MAX_NUM_TRACKS);
124    ALOGV("deleteTrackName(%d)", name);
125    track_t& track(mState.tracks[ name ]);
126    if (track.enabled != 0) {
127        track.enabled = 0;
128        invalidateState(1<<name);
129    }
130    if (track.resampler) {
131        // delete  the resampler
132        delete track.resampler;
133        track.resampler = NULL;
134        track.sampleRate = mSampleRate;
135        invalidateState(1<<name);
136    }
137    track.volumeInc[0] = 0;
138    track.volumeInc[1] = 0;
139    mTrackNames &= ~(1<<name);
140}
141
142void AudioMixer::enable(int name)
143{
144    name -= TRACK0;
145    assert(uint32_t(name) < MAX_NUM_TRACKS);
146    track_t& track = mState.tracks[name];
147
148    if (track.enabled != 1) {
149        track.enabled = 1;
150        ALOGV("enable(%d)", name);
151        invalidateState(1 << name);
152    }
153}
154
155void AudioMixer::disable(int name)
156{
157    name -= TRACK0;
158    assert(uint32_t(name) < MAX_NUM_TRACKS);
159    track_t& track = mState.tracks[name];
160
161    if (track.enabled != 0) {
162        track.enabled = 0;
163        ALOGV("disable(%d)", name);
164        invalidateState(1 << name);
165    }
166}
167
168void AudioMixer::setParameter(int name, int target, int param, void *value)
169{
170    name -= TRACK0;
171    assert(uint32_t(name) < MAX_NUM_TRACKS);
172    track_t& track = mState.tracks[name];
173
174    int valueInt = (int)value;
175    int32_t *valueBuf = (int32_t *)value;
176
177    switch (target) {
178
179    case TRACK:
180        switch (param) {
181        case CHANNEL_MASK: {
182            uint32_t mask = (uint32_t)value;
183            if (track.channelMask != mask) {
184                uint8_t channelCount = popcount(mask);
185                assert((channelCount <= MAX_NUM_CHANNELS) && (channelCount));
186                track.channelMask = mask;
187                track.channelCount = channelCount;
188                ALOGV("setParameter(TRACK, CHANNEL_MASK, %x)", mask);
189                invalidateState(1 << name);
190            }
191            } break;
192        case MAIN_BUFFER:
193            if (track.mainBuffer != valueBuf) {
194                track.mainBuffer = valueBuf;
195                ALOGV("setParameter(TRACK, MAIN_BUFFER, %p)", valueBuf);
196                invalidateState(1 << name);
197            }
198            break;
199        case AUX_BUFFER:
200            if (track.auxBuffer != valueBuf) {
201                track.auxBuffer = valueBuf;
202                ALOGV("setParameter(TRACK, AUX_BUFFER, %p)", valueBuf);
203                invalidateState(1 << name);
204            }
205            break;
206        default:
207            // bad param
208            assert(false);
209        }
210        break;
211
212    case RESAMPLE:
213        switch (param) {
214        case SAMPLE_RATE:
215            assert(valueInt > 0);
216            if (track.setResampler(uint32_t(valueInt), mSampleRate)) {
217                ALOGV("setParameter(RESAMPLE, SAMPLE_RATE, %u)",
218                        uint32_t(valueInt));
219                invalidateState(1 << name);
220            }
221            break;
222        case RESET:
223            track.resetResampler();
224            invalidateState(1 << name);
225            break;
226        default:
227            // bad param
228            assert(false);
229        }
230        break;
231
232    case RAMP_VOLUME:
233    case VOLUME:
234        switch (param) {
235        case VOLUME0:
236        case VOLUME1:
237            if (track.volume[param-VOLUME0] != valueInt) {
238                ALOGV("setParameter(VOLUME, VOLUME0/1: %04x)", valueInt);
239                track.prevVolume[param-VOLUME0] = track.volume[param-VOLUME0] << 16;
240                track.volume[param-VOLUME0] = valueInt;
241                if (target == VOLUME) {
242                    track.prevVolume[param-VOLUME0] = valueInt << 16;
243                    track.volumeInc[param-VOLUME0] = 0;
244                } else {
245                    int32_t d = (valueInt<<16) - track.prevVolume[param-VOLUME0];
246                    int32_t volInc = d / int32_t(mState.frameCount);
247                    track.volumeInc[param-VOLUME0] = volInc;
248                    if (volInc == 0) {
249                        track.prevVolume[param-VOLUME0] = valueInt << 16;
250                    }
251                }
252                invalidateState(1 << name);
253            }
254            break;
255        case AUXLEVEL:
256            if (track.auxLevel != valueInt) {
257                ALOGV("setParameter(VOLUME, AUXLEVEL: %04x)", valueInt);
258                track.prevAuxLevel = track.auxLevel << 16;
259                track.auxLevel = valueInt;
260                if (target == VOLUME) {
261                    track.prevAuxLevel = valueInt << 16;
262                    track.auxInc = 0;
263                } else {
264                    int32_t d = (valueInt<<16) - track.prevAuxLevel;
265                    int32_t volInc = d / int32_t(mState.frameCount);
266                    track.auxInc = volInc;
267                    if (volInc == 0) {
268                        track.prevAuxLevel = valueInt << 16;
269                    }
270                }
271                invalidateState(1 << name);
272            }
273            break;
274        default:
275            // bad param
276            assert(false);
277        }
278        break;
279
280    default:
281        // bad target
282        assert(false);
283    }
284}
285
286bool AudioMixer::track_t::setResampler(uint32_t value, uint32_t devSampleRate)
287{
288    if (value!=devSampleRate || resampler) {
289        if (sampleRate != value) {
290            sampleRate = value;
291            if (resampler == NULL) {
292                resampler = AudioResampler::create(
293                        format, channelCount, devSampleRate);
294            }
295            return true;
296        }
297    }
298    return false;
299}
300
301bool AudioMixer::track_t::doesResample() const
302{
303    return resampler != NULL;
304}
305
306void AudioMixer::track_t::resetResampler()
307{
308    if (resampler != NULL) {
309        resampler->reset();
310    }
311}
312
313inline
314void AudioMixer::track_t::adjustVolumeRamp(bool aux)
315{
316    for (int i=0 ; i<MAX_NUM_CHANNELS ; i++) {
317        if (((volumeInc[i]>0) && (((prevVolume[i]+volumeInc[i])>>16) >= volume[i])) ||
318            ((volumeInc[i]<0) && (((prevVolume[i]+volumeInc[i])>>16) <= volume[i]))) {
319            volumeInc[i] = 0;
320            prevVolume[i] = volume[i]<<16;
321        }
322    }
323    if (aux) {
324        if (((auxInc>0) && (((prevAuxLevel+auxInc)>>16) >= auxLevel)) ||
325            ((auxInc<0) && (((prevAuxLevel+auxInc)>>16) <= auxLevel))) {
326            auxInc = 0;
327            prevAuxLevel = auxLevel<<16;
328        }
329    }
330}
331
332
333void AudioMixer::setBufferProvider(int name, AudioBufferProvider* buffer)
334{
335    name -= TRACK0;
336    assert(uint32_t(name) < MAX_NUM_TRACKS);
337    mState.tracks[name].bufferProvider = buffer;
338}
339
340
341
342void AudioMixer::process()
343{
344    mState.hook(&mState);
345}
346
347
348void AudioMixer::process__validate(state_t* state)
349{
350    LOGW_IF(!state->needsChanged,
351        "in process__validate() but nothing's invalid");
352
353    uint32_t changed = state->needsChanged;
354    state->needsChanged = 0; // clear the validation flag
355
356    // recompute which tracks are enabled / disabled
357    uint32_t enabled = 0;
358    uint32_t disabled = 0;
359    while (changed) {
360        const int i = 31 - __builtin_clz(changed);
361        const uint32_t mask = 1<<i;
362        changed &= ~mask;
363        track_t& t = state->tracks[i];
364        (t.enabled ? enabled : disabled) |= mask;
365    }
366    state->enabledTracks &= ~disabled;
367    state->enabledTracks |=  enabled;
368
369    // compute everything we need...
370    int countActiveTracks = 0;
371    int all16BitsStereoNoResample = 1;
372    int resampling = 0;
373    int volumeRamp = 0;
374    uint32_t en = state->enabledTracks;
375    while (en) {
376        const int i = 31 - __builtin_clz(en);
377        en &= ~(1<<i);
378
379        countActiveTracks++;
380        track_t& t = state->tracks[i];
381        uint32_t n = 0;
382        n |= NEEDS_CHANNEL_1 + t.channelCount - 1;
383        n |= NEEDS_FORMAT_16;
384        n |= t.doesResample() ? NEEDS_RESAMPLE_ENABLED : NEEDS_RESAMPLE_DISABLED;
385        if (t.auxLevel != 0 && t.auxBuffer != NULL) {
386            n |= NEEDS_AUX_ENABLED;
387        }
388
389        if (t.volumeInc[0]|t.volumeInc[1]) {
390            volumeRamp = 1;
391        } else if (!t.doesResample() && t.volumeRL == 0) {
392            n |= NEEDS_MUTE_ENABLED;
393        }
394        t.needs = n;
395
396        if ((n & NEEDS_MUTE__MASK) == NEEDS_MUTE_ENABLED) {
397            t.hook = track__nop;
398        } else {
399            if ((n & NEEDS_AUX__MASK) == NEEDS_AUX_ENABLED) {
400                all16BitsStereoNoResample = 0;
401            }
402            if ((n & NEEDS_RESAMPLE__MASK) == NEEDS_RESAMPLE_ENABLED) {
403                all16BitsStereoNoResample = 0;
404                resampling = 1;
405                t.hook = track__genericResample;
406            } else {
407                if ((n & NEEDS_CHANNEL_COUNT__MASK) == NEEDS_CHANNEL_1){
408                    t.hook = track__16BitsMono;
409                    all16BitsStereoNoResample = 0;
410                }
411                if ((n & NEEDS_CHANNEL_COUNT__MASK) == NEEDS_CHANNEL_2){
412                    t.hook = track__16BitsStereo;
413                }
414            }
415        }
416    }
417
418    // select the processing hooks
419    state->hook = process__nop;
420    if (countActiveTracks) {
421        if (resampling) {
422            if (!state->outputTemp) {
423                state->outputTemp = new int32_t[MAX_NUM_CHANNELS * state->frameCount];
424            }
425            if (!state->resampleTemp) {
426                state->resampleTemp = new int32_t[MAX_NUM_CHANNELS * state->frameCount];
427            }
428            state->hook = process__genericResampling;
429        } else {
430            if (state->outputTemp) {
431                delete [] state->outputTemp;
432                state->outputTemp = NULL;
433            }
434            if (state->resampleTemp) {
435                delete [] state->resampleTemp;
436                state->resampleTemp = NULL;
437            }
438            state->hook = process__genericNoResampling;
439            if (all16BitsStereoNoResample && !volumeRamp) {
440                if (countActiveTracks == 1) {
441                    state->hook = process__OneTrack16BitsStereoNoResampling;
442                }
443            }
444        }
445    }
446
447    ALOGV("mixer configuration change: %d activeTracks (%08x) "
448        "all16BitsStereoNoResample=%d, resampling=%d, volumeRamp=%d",
449        countActiveTracks, state->enabledTracks,
450        all16BitsStereoNoResample, resampling, volumeRamp);
451
452    state->hook(state);
453
454    // Now that the volume ramp has been done, set optimal state and
455    // track hooks for subsequent mixer process
456    if (countActiveTracks) {
457        int allMuted = 1;
458        uint32_t en = state->enabledTracks;
459        while (en) {
460            const int i = 31 - __builtin_clz(en);
461            en &= ~(1<<i);
462            track_t& t = state->tracks[i];
463            if (!t.doesResample() && t.volumeRL == 0)
464            {
465                t.needs |= NEEDS_MUTE_ENABLED;
466                t.hook = track__nop;
467            } else {
468                allMuted = 0;
469            }
470        }
471        if (allMuted) {
472            state->hook = process__nop;
473        } else if (all16BitsStereoNoResample) {
474            if (countActiveTracks == 1) {
475                state->hook = process__OneTrack16BitsStereoNoResampling;
476            }
477        }
478    }
479}
480
481
482void AudioMixer::track__genericResample(track_t* t, int32_t* out, size_t outFrameCount, int32_t* temp, int32_t* aux)
483{
484    t->resampler->setSampleRate(t->sampleRate);
485
486    // ramp gain - resample to temp buffer and scale/mix in 2nd step
487    if (aux != NULL) {
488        // always resample with unity gain when sending to auxiliary buffer to be able
489        // to apply send level after resampling
490        // TODO: modify each resampler to support aux channel?
491        t->resampler->setVolume(UNITY_GAIN, UNITY_GAIN);
492        memset(temp, 0, outFrameCount * MAX_NUM_CHANNELS * sizeof(int32_t));
493        t->resampler->resample(temp, outFrameCount, t->bufferProvider);
494        if UNLIKELY(t->volumeInc[0]|t->volumeInc[1]|t->auxInc) {
495            volumeRampStereo(t, out, outFrameCount, temp, aux);
496        } else {
497            volumeStereo(t, out, outFrameCount, temp, aux);
498        }
499    } else {
500        if UNLIKELY(t->volumeInc[0]|t->volumeInc[1]) {
501            t->resampler->setVolume(UNITY_GAIN, UNITY_GAIN);
502            memset(temp, 0, outFrameCount * MAX_NUM_CHANNELS * sizeof(int32_t));
503            t->resampler->resample(temp, outFrameCount, t->bufferProvider);
504            volumeRampStereo(t, out, outFrameCount, temp, aux);
505        }
506
507        // constant gain
508        else {
509            t->resampler->setVolume(t->volume[0], t->volume[1]);
510            t->resampler->resample(out, outFrameCount, t->bufferProvider);
511        }
512    }
513}
514
515void AudioMixer::track__nop(track_t* t, int32_t* out, size_t outFrameCount, int32_t* temp, int32_t* aux)
516{
517}
518
519void AudioMixer::volumeRampStereo(track_t* t, int32_t* out, size_t frameCount, int32_t* temp, int32_t* aux)
520{
521    int32_t vl = t->prevVolume[0];
522    int32_t vr = t->prevVolume[1];
523    const int32_t vlInc = t->volumeInc[0];
524    const int32_t vrInc = t->volumeInc[1];
525
526    //LOGD("[0] %p: inc=%f, v0=%f, v1=%d, final=%f, count=%d",
527    //        t, vlInc/65536.0f, vl/65536.0f, t->volume[0],
528    //       (vl + vlInc*frameCount)/65536.0f, frameCount);
529
530    // ramp volume
531    if UNLIKELY(aux != NULL) {
532        int32_t va = t->prevAuxLevel;
533        const int32_t vaInc = t->auxInc;
534        int32_t l;
535        int32_t r;
536
537        do {
538            l = (*temp++ >> 12);
539            r = (*temp++ >> 12);
540            *out++ += (vl >> 16) * l;
541            *out++ += (vr >> 16) * r;
542            *aux++ += (va >> 17) * (l + r);
543            vl += vlInc;
544            vr += vrInc;
545            va += vaInc;
546        } while (--frameCount);
547        t->prevAuxLevel = va;
548    } else {
549        do {
550            *out++ += (vl >> 16) * (*temp++ >> 12);
551            *out++ += (vr >> 16) * (*temp++ >> 12);
552            vl += vlInc;
553            vr += vrInc;
554        } while (--frameCount);
555    }
556    t->prevVolume[0] = vl;
557    t->prevVolume[1] = vr;
558    t->adjustVolumeRamp((aux != NULL));
559}
560
561void AudioMixer::volumeStereo(track_t* t, int32_t* out, size_t frameCount, int32_t* temp, int32_t* aux)
562{
563    const int16_t vl = t->volume[0];
564    const int16_t vr = t->volume[1];
565
566    if UNLIKELY(aux != NULL) {
567        const int16_t va = (int16_t)t->auxLevel;
568        do {
569            int16_t l = (int16_t)(*temp++ >> 12);
570            int16_t r = (int16_t)(*temp++ >> 12);
571            out[0] = mulAdd(l, vl, out[0]);
572            int16_t a = (int16_t)(((int32_t)l + r) >> 1);
573            out[1] = mulAdd(r, vr, out[1]);
574            out += 2;
575            aux[0] = mulAdd(a, va, aux[0]);
576            aux++;
577        } while (--frameCount);
578    } else {
579        do {
580            int16_t l = (int16_t)(*temp++ >> 12);
581            int16_t r = (int16_t)(*temp++ >> 12);
582            out[0] = mulAdd(l, vl, out[0]);
583            out[1] = mulAdd(r, vr, out[1]);
584            out += 2;
585        } while (--frameCount);
586    }
587}
588
589void AudioMixer::track__16BitsStereo(track_t* t, int32_t* out, size_t frameCount, int32_t* temp, int32_t* aux)
590{
591    int16_t const *in = static_cast<int16_t const *>(t->in);
592
593    if UNLIKELY(aux != NULL) {
594        int32_t l;
595        int32_t r;
596        // ramp gain
597        if UNLIKELY(t->volumeInc[0]|t->volumeInc[1]|t->auxInc) {
598            int32_t vl = t->prevVolume[0];
599            int32_t vr = t->prevVolume[1];
600            int32_t va = t->prevAuxLevel;
601            const int32_t vlInc = t->volumeInc[0];
602            const int32_t vrInc = t->volumeInc[1];
603            const int32_t vaInc = t->auxInc;
604            // LOGD("[1] %p: inc=%f, v0=%f, v1=%d, final=%f, count=%d",
605            //        t, vlInc/65536.0f, vl/65536.0f, t->volume[0],
606            //        (vl + vlInc*frameCount)/65536.0f, frameCount);
607
608            do {
609                l = (int32_t)*in++;
610                r = (int32_t)*in++;
611                *out++ += (vl >> 16) * l;
612                *out++ += (vr >> 16) * r;
613                *aux++ += (va >> 17) * (l + r);
614                vl += vlInc;
615                vr += vrInc;
616                va += vaInc;
617            } while (--frameCount);
618
619            t->prevVolume[0] = vl;
620            t->prevVolume[1] = vr;
621            t->prevAuxLevel = va;
622            t->adjustVolumeRamp(true);
623        }
624
625        // constant gain
626        else {
627            const uint32_t vrl = t->volumeRL;
628            const int16_t va = (int16_t)t->auxLevel;
629            do {
630                uint32_t rl = *reinterpret_cast<uint32_t const *>(in);
631                int16_t a = (int16_t)(((int32_t)in[0] + in[1]) >> 1);
632                in += 2;
633                out[0] = mulAddRL(1, rl, vrl, out[0]);
634                out[1] = mulAddRL(0, rl, vrl, out[1]);
635                out += 2;
636                aux[0] = mulAdd(a, va, aux[0]);
637                aux++;
638            } while (--frameCount);
639        }
640    } else {
641        // ramp gain
642        if UNLIKELY(t->volumeInc[0]|t->volumeInc[1]) {
643            int32_t vl = t->prevVolume[0];
644            int32_t vr = t->prevVolume[1];
645            const int32_t vlInc = t->volumeInc[0];
646            const int32_t vrInc = t->volumeInc[1];
647
648            // LOGD("[1] %p: inc=%f, v0=%f, v1=%d, final=%f, count=%d",
649            //        t, vlInc/65536.0f, vl/65536.0f, t->volume[0],
650            //        (vl + vlInc*frameCount)/65536.0f, frameCount);
651
652            do {
653                *out++ += (vl >> 16) * (int32_t) *in++;
654                *out++ += (vr >> 16) * (int32_t) *in++;
655                vl += vlInc;
656                vr += vrInc;
657            } while (--frameCount);
658
659            t->prevVolume[0] = vl;
660            t->prevVolume[1] = vr;
661            t->adjustVolumeRamp(false);
662        }
663
664        // constant gain
665        else {
666            const uint32_t vrl = t->volumeRL;
667            do {
668                uint32_t rl = *reinterpret_cast<uint32_t const *>(in);
669                in += 2;
670                out[0] = mulAddRL(1, rl, vrl, out[0]);
671                out[1] = mulAddRL(0, rl, vrl, out[1]);
672                out += 2;
673            } while (--frameCount);
674        }
675    }
676    t->in = in;
677}
678
679void AudioMixer::track__16BitsMono(track_t* t, int32_t* out, size_t frameCount, int32_t* temp, int32_t* aux)
680{
681    int16_t const *in = static_cast<int16_t const *>(t->in);
682
683    if UNLIKELY(aux != NULL) {
684        // ramp gain
685        if UNLIKELY(t->volumeInc[0]|t->volumeInc[1]|t->auxInc) {
686            int32_t vl = t->prevVolume[0];
687            int32_t vr = t->prevVolume[1];
688            int32_t va = t->prevAuxLevel;
689            const int32_t vlInc = t->volumeInc[0];
690            const int32_t vrInc = t->volumeInc[1];
691            const int32_t vaInc = t->auxInc;
692
693            // LOGD("[2] %p: inc=%f, v0=%f, v1=%d, final=%f, count=%d",
694            //         t, vlInc/65536.0f, vl/65536.0f, t->volume[0],
695            //         (vl + vlInc*frameCount)/65536.0f, frameCount);
696
697            do {
698                int32_t l = *in++;
699                *out++ += (vl >> 16) * l;
700                *out++ += (vr >> 16) * l;
701                *aux++ += (va >> 16) * l;
702                vl += vlInc;
703                vr += vrInc;
704                va += vaInc;
705            } while (--frameCount);
706
707            t->prevVolume[0] = vl;
708            t->prevVolume[1] = vr;
709            t->prevAuxLevel = va;
710            t->adjustVolumeRamp(true);
711        }
712        // constant gain
713        else {
714            const int16_t vl = t->volume[0];
715            const int16_t vr = t->volume[1];
716            const int16_t va = (int16_t)t->auxLevel;
717            do {
718                int16_t l = *in++;
719                out[0] = mulAdd(l, vl, out[0]);
720                out[1] = mulAdd(l, vr, out[1]);
721                out += 2;
722                aux[0] = mulAdd(l, va, aux[0]);
723                aux++;
724            } while (--frameCount);
725        }
726    } else {
727        // ramp gain
728        if UNLIKELY(t->volumeInc[0]|t->volumeInc[1]) {
729            int32_t vl = t->prevVolume[0];
730            int32_t vr = t->prevVolume[1];
731            const int32_t vlInc = t->volumeInc[0];
732            const int32_t vrInc = t->volumeInc[1];
733
734            // LOGD("[2] %p: inc=%f, v0=%f, v1=%d, final=%f, count=%d",
735            //         t, vlInc/65536.0f, vl/65536.0f, t->volume[0],
736            //         (vl + vlInc*frameCount)/65536.0f, frameCount);
737
738            do {
739                int32_t l = *in++;
740                *out++ += (vl >> 16) * l;
741                *out++ += (vr >> 16) * l;
742                vl += vlInc;
743                vr += vrInc;
744            } while (--frameCount);
745
746            t->prevVolume[0] = vl;
747            t->prevVolume[1] = vr;
748            t->adjustVolumeRamp(false);
749        }
750        // constant gain
751        else {
752            const int16_t vl = t->volume[0];
753            const int16_t vr = t->volume[1];
754            do {
755                int16_t l = *in++;
756                out[0] = mulAdd(l, vl, out[0]);
757                out[1] = mulAdd(l, vr, out[1]);
758                out += 2;
759            } while (--frameCount);
760        }
761    }
762    t->in = in;
763}
764
765// no-op case
766void AudioMixer::process__nop(state_t* state)
767{
768    uint32_t e0 = state->enabledTracks;
769    size_t bufSize = state->frameCount * sizeof(int16_t) * MAX_NUM_CHANNELS;
770    while (e0) {
771        // process by group of tracks with same output buffer to
772        // avoid multiple memset() on same buffer
773        uint32_t e1 = e0, e2 = e0;
774        int i = 31 - __builtin_clz(e1);
775        track_t& t1 = state->tracks[i];
776        e2 &= ~(1<<i);
777        while (e2) {
778            i = 31 - __builtin_clz(e2);
779            e2 &= ~(1<<i);
780            track_t& t2 = state->tracks[i];
781            if UNLIKELY(t2.mainBuffer != t1.mainBuffer) {
782                e1 &= ~(1<<i);
783            }
784        }
785        e0 &= ~(e1);
786
787        memset(t1.mainBuffer, 0, bufSize);
788
789        while (e1) {
790            i = 31 - __builtin_clz(e1);
791            e1 &= ~(1<<i);
792            t1 = state->tracks[i];
793            size_t outFrames = state->frameCount;
794            while (outFrames) {
795                t1.buffer.frameCount = outFrames;
796                t1.bufferProvider->getNextBuffer(&t1.buffer);
797                if (!t1.buffer.raw) break;
798                outFrames -= t1.buffer.frameCount;
799                t1.bufferProvider->releaseBuffer(&t1.buffer);
800            }
801        }
802    }
803}
804
805// generic code without resampling
806void AudioMixer::process__genericNoResampling(state_t* state)
807{
808    int32_t outTemp[BLOCKSIZE * MAX_NUM_CHANNELS] __attribute__((aligned(32)));
809
810    // acquire each track's buffer
811    uint32_t enabledTracks = state->enabledTracks;
812    uint32_t e0 = enabledTracks;
813    while (e0) {
814        const int i = 31 - __builtin_clz(e0);
815        e0 &= ~(1<<i);
816        track_t& t = state->tracks[i];
817        t.buffer.frameCount = state->frameCount;
818        t.bufferProvider->getNextBuffer(&t.buffer);
819        t.frameCount = t.buffer.frameCount;
820        t.in = t.buffer.raw;
821        // t.in == NULL can happen if the track was flushed just after having
822        // been enabled for mixing.
823        if (t.in == NULL)
824            enabledTracks &= ~(1<<i);
825    }
826
827    e0 = enabledTracks;
828    while (e0) {
829        // process by group of tracks with same output buffer to
830        // optimize cache use
831        uint32_t e1 = e0, e2 = e0;
832        int j = 31 - __builtin_clz(e1);
833        track_t& t1 = state->tracks[j];
834        e2 &= ~(1<<j);
835        while (e2) {
836            j = 31 - __builtin_clz(e2);
837            e2 &= ~(1<<j);
838            track_t& t2 = state->tracks[j];
839            if UNLIKELY(t2.mainBuffer != t1.mainBuffer) {
840                e1 &= ~(1<<j);
841            }
842        }
843        e0 &= ~(e1);
844        // this assumes output 16 bits stereo, no resampling
845        int32_t *out = t1.mainBuffer;
846        size_t numFrames = 0;
847        do {
848            memset(outTemp, 0, sizeof(outTemp));
849            e2 = e1;
850            while (e2) {
851                const int i = 31 - __builtin_clz(e2);
852                e2 &= ~(1<<i);
853                track_t& t = state->tracks[i];
854                size_t outFrames = BLOCKSIZE;
855                int32_t *aux = NULL;
856                if UNLIKELY((t.needs & NEEDS_AUX__MASK) == NEEDS_AUX_ENABLED) {
857                    aux = t.auxBuffer + numFrames;
858                }
859                while (outFrames) {
860                    size_t inFrames = (t.frameCount > outFrames)?outFrames:t.frameCount;
861                    if (inFrames) {
862                        (t.hook)(&t, outTemp + (BLOCKSIZE-outFrames)*MAX_NUM_CHANNELS, inFrames, state->resampleTemp, aux);
863                        t.frameCount -= inFrames;
864                        outFrames -= inFrames;
865                        if UNLIKELY(aux != NULL) {
866                            aux += inFrames;
867                        }
868                    }
869                    if (t.frameCount == 0 && outFrames) {
870                        t.bufferProvider->releaseBuffer(&t.buffer);
871                        t.buffer.frameCount = (state->frameCount - numFrames) - (BLOCKSIZE - outFrames);
872                        t.bufferProvider->getNextBuffer(&t.buffer);
873                        t.in = t.buffer.raw;
874                        if (t.in == NULL) {
875                            enabledTracks &= ~(1<<i);
876                            e1 &= ~(1<<i);
877                            break;
878                        }
879                        t.frameCount = t.buffer.frameCount;
880                    }
881                }
882            }
883            ditherAndClamp(out, outTemp, BLOCKSIZE);
884            out += BLOCKSIZE;
885            numFrames += BLOCKSIZE;
886        } while (numFrames < state->frameCount);
887    }
888
889    // release each track's buffer
890    e0 = enabledTracks;
891    while (e0) {
892        const int i = 31 - __builtin_clz(e0);
893        e0 &= ~(1<<i);
894        track_t& t = state->tracks[i];
895        t.bufferProvider->releaseBuffer(&t.buffer);
896    }
897}
898
899
900// generic code with resampling
901void AudioMixer::process__genericResampling(state_t* state)
902{
903    int32_t* const outTemp = state->outputTemp;
904    const size_t size = sizeof(int32_t) * MAX_NUM_CHANNELS * state->frameCount;
905
906    size_t numFrames = state->frameCount;
907
908    uint32_t e0 = state->enabledTracks;
909    while (e0) {
910        // process by group of tracks with same output buffer
911        // to optimize cache use
912        uint32_t e1 = e0, e2 = e0;
913        int j = 31 - __builtin_clz(e1);
914        track_t& t1 = state->tracks[j];
915        e2 &= ~(1<<j);
916        while (e2) {
917            j = 31 - __builtin_clz(e2);
918            e2 &= ~(1<<j);
919            track_t& t2 = state->tracks[j];
920            if UNLIKELY(t2.mainBuffer != t1.mainBuffer) {
921                e1 &= ~(1<<j);
922            }
923        }
924        e0 &= ~(e1);
925        int32_t *out = t1.mainBuffer;
926        memset(outTemp, 0, size);
927        while (e1) {
928            const int i = 31 - __builtin_clz(e1);
929            e1 &= ~(1<<i);
930            track_t& t = state->tracks[i];
931            int32_t *aux = NULL;
932            if UNLIKELY((t.needs & NEEDS_AUX__MASK) == NEEDS_AUX_ENABLED) {
933                aux = t.auxBuffer;
934            }
935
936            // this is a little goofy, on the resampling case we don't
937            // acquire/release the buffers because it's done by
938            // the resampler.
939            if ((t.needs & NEEDS_RESAMPLE__MASK) == NEEDS_RESAMPLE_ENABLED) {
940                (t.hook)(&t, outTemp, numFrames, state->resampleTemp, aux);
941            } else {
942
943                size_t outFrames = 0;
944
945                while (outFrames < numFrames) {
946                    t.buffer.frameCount = numFrames - outFrames;
947                    t.bufferProvider->getNextBuffer(&t.buffer);
948                    t.in = t.buffer.raw;
949                    // t.in == NULL can happen if the track was flushed just after having
950                    // been enabled for mixing.
951                    if (t.in == NULL) break;
952
953                    if UNLIKELY(aux != NULL) {
954                        aux += outFrames;
955                    }
956                    (t.hook)(&t, outTemp + outFrames*MAX_NUM_CHANNELS, t.buffer.frameCount, state->resampleTemp, aux);
957                    outFrames += t.buffer.frameCount;
958                    t.bufferProvider->releaseBuffer(&t.buffer);
959                }
960            }
961        }
962        ditherAndClamp(out, outTemp, numFrames);
963    }
964}
965
966// one track, 16 bits stereo without resampling is the most common case
967void AudioMixer::process__OneTrack16BitsStereoNoResampling(state_t* state)
968{
969    const int i = 31 - __builtin_clz(state->enabledTracks);
970    const track_t& t = state->tracks[i];
971
972    AudioBufferProvider::Buffer& b(t.buffer);
973
974    int32_t* out = t.mainBuffer;
975    size_t numFrames = state->frameCount;
976
977    const int16_t vl = t.volume[0];
978    const int16_t vr = t.volume[1];
979    const uint32_t vrl = t.volumeRL;
980    while (numFrames) {
981        b.frameCount = numFrames;
982        t.bufferProvider->getNextBuffer(&b);
983        int16_t const *in = b.i16;
984
985        // in == NULL can happen if the track was flushed just after having
986        // been enabled for mixing.
987        if (in == NULL || ((unsigned long)in & 3)) {
988            memset(out, 0, numFrames*MAX_NUM_CHANNELS*sizeof(int16_t));
989            LOGE_IF(((unsigned long)in & 3), "process stereo track: input buffer alignment pb: buffer %p track %d, channels %d, needs %08x",
990                    in, i, t.channelCount, t.needs);
991            return;
992        }
993        size_t outFrames = b.frameCount;
994
995        if (UNLIKELY(uint32_t(vl) > UNITY_GAIN || uint32_t(vr) > UNITY_GAIN)) {
996            // volume is boosted, so we might need to clamp even though
997            // we process only one track.
998            do {
999                uint32_t rl = *reinterpret_cast<uint32_t const *>(in);
1000                in += 2;
1001                int32_t l = mulRL(1, rl, vrl) >> 12;
1002                int32_t r = mulRL(0, rl, vrl) >> 12;
1003                // clamping...
1004                l = clamp16(l);
1005                r = clamp16(r);
1006                *out++ = (r<<16) | (l & 0xFFFF);
1007            } while (--outFrames);
1008        } else {
1009            do {
1010                uint32_t rl = *reinterpret_cast<uint32_t const *>(in);
1011                in += 2;
1012                int32_t l = mulRL(1, rl, vrl) >> 12;
1013                int32_t r = mulRL(0, rl, vrl) >> 12;
1014                *out++ = (r<<16) | (l & 0xFFFF);
1015            } while (--outFrames);
1016        }
1017        numFrames -= b.frameCount;
1018        t.bufferProvider->releaseBuffer(&b);
1019    }
1020}
1021
1022// 2 tracks is also a common case
1023// NEVER used in current implementation of process__validate()
1024// only use if the 2 tracks have the same output buffer
1025void AudioMixer::process__TwoTracks16BitsStereoNoResampling(state_t* state)
1026{
1027    int i;
1028    uint32_t en = state->enabledTracks;
1029
1030    i = 31 - __builtin_clz(en);
1031    const track_t& t0 = state->tracks[i];
1032    AudioBufferProvider::Buffer& b0(t0.buffer);
1033
1034    en &= ~(1<<i);
1035    i = 31 - __builtin_clz(en);
1036    const track_t& t1 = state->tracks[i];
1037    AudioBufferProvider::Buffer& b1(t1.buffer);
1038
1039    int16_t const *in0;
1040    const int16_t vl0 = t0.volume[0];
1041    const int16_t vr0 = t0.volume[1];
1042    size_t frameCount0 = 0;
1043
1044    int16_t const *in1;
1045    const int16_t vl1 = t1.volume[0];
1046    const int16_t vr1 = t1.volume[1];
1047    size_t frameCount1 = 0;
1048
1049    //FIXME: only works if two tracks use same buffer
1050    int32_t* out = t0.mainBuffer;
1051    size_t numFrames = state->frameCount;
1052    int16_t const *buff = NULL;
1053
1054
1055    while (numFrames) {
1056
1057        if (frameCount0 == 0) {
1058            b0.frameCount = numFrames;
1059            t0.bufferProvider->getNextBuffer(&b0);
1060            if (b0.i16 == NULL) {
1061                if (buff == NULL) {
1062                    buff = new int16_t[MAX_NUM_CHANNELS * state->frameCount];
1063                }
1064                in0 = buff;
1065                b0.frameCount = numFrames;
1066            } else {
1067                in0 = b0.i16;
1068            }
1069            frameCount0 = b0.frameCount;
1070        }
1071        if (frameCount1 == 0) {
1072            b1.frameCount = numFrames;
1073            t1.bufferProvider->getNextBuffer(&b1);
1074            if (b1.i16 == NULL) {
1075                if (buff == NULL) {
1076                    buff = new int16_t[MAX_NUM_CHANNELS * state->frameCount];
1077                }
1078                in1 = buff;
1079                b1.frameCount = numFrames;
1080            } else {
1081                in1 = b1.i16;
1082            }
1083            frameCount1 = b1.frameCount;
1084        }
1085
1086        size_t outFrames = frameCount0 < frameCount1?frameCount0:frameCount1;
1087
1088        numFrames -= outFrames;
1089        frameCount0 -= outFrames;
1090        frameCount1 -= outFrames;
1091
1092        do {
1093            int32_t l0 = *in0++;
1094            int32_t r0 = *in0++;
1095            l0 = mul(l0, vl0);
1096            r0 = mul(r0, vr0);
1097            int32_t l = *in1++;
1098            int32_t r = *in1++;
1099            l = mulAdd(l, vl1, l0) >> 12;
1100            r = mulAdd(r, vr1, r0) >> 12;
1101            // clamping...
1102            l = clamp16(l);
1103            r = clamp16(r);
1104            *out++ = (r<<16) | (l & 0xFFFF);
1105        } while (--outFrames);
1106
1107        if (frameCount0 == 0) {
1108            t0.bufferProvider->releaseBuffer(&b0);
1109        }
1110        if (frameCount1 == 0) {
1111            t1.bufferProvider->releaseBuffer(&b1);
1112        }
1113    }
1114
1115    if (buff != NULL) {
1116        delete [] buff;
1117    }
1118}
1119
1120// ----------------------------------------------------------------------------
1121}; // namespace android
1122