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