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