• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <stdint.h>
22 #include <string.h>
23 #include <stdlib.h>
24 #include <sys/types.h>
25 
26 #include <utils/Errors.h>
27 #include <utils/Log.h>
28 
29 #include "AudioMixer.h"
30 
31 namespace android {
32 // ----------------------------------------------------------------------------
33 
clamp16(int32_t sample)34 static inline int16_t clamp16(int32_t sample)
35 {
36     if ((sample>>15) ^ (sample>>31))
37         sample = 0x7FFF ^ (sample>>31);
38     return sample;
39 }
40 
41 // ----------------------------------------------------------------------------
42 
AudioMixer(size_t frameCount,uint32_t sampleRate)43 AudioMixer::AudioMixer(size_t frameCount, uint32_t sampleRate)
44     :   mActiveTrack(0), mTrackNames(0), mSampleRate(sampleRate)
45 {
46     mState.enabledTracks= 0;
47     mState.needsChanged = 0;
48     mState.frameCount   = frameCount;
49     mState.outputTemp   = 0;
50     mState.resampleTemp = 0;
51     mState.hook         = process__nop;
52     track_t* t = mState.tracks;
53     for (int i=0 ; i<32 ; i++) {
54         t->needs = 0;
55         t->volume[0] = UNITY_GAIN;
56         t->volume[1] = UNITY_GAIN;
57         t->volumeInc[0] = 0;
58         t->volumeInc[1] = 0;
59         t->channelCount = 2;
60         t->enabled = 0;
61         t->format = 16;
62         t->buffer.raw = 0;
63         t->bufferProvider = 0;
64         t->hook = 0;
65         t->resampler = 0;
66         t->sampleRate = mSampleRate;
67         t->in = 0;
68         t++;
69     }
70 }
71 
~AudioMixer()72  AudioMixer::~AudioMixer()
73  {
74      track_t* t = mState.tracks;
75      for (int i=0 ; i<32 ; i++) {
76          delete t->resampler;
77          t++;
78      }
79      delete [] mState.outputTemp;
80      delete [] mState.resampleTemp;
81  }
82 
getTrackName()83  int AudioMixer::getTrackName()
84  {
85     uint32_t names = mTrackNames;
86     uint32_t mask = 1;
87     int n = 0;
88     while (names & mask) {
89         mask <<= 1;
90         n++;
91     }
92     if (mask) {
93         LOGV("add track (%d)", n);
94         mTrackNames |= mask;
95         return TRACK0 + n;
96     }
97     return -1;
98  }
99 
invalidateState(uint32_t mask)100  void AudioMixer::invalidateState(uint32_t mask)
101  {
102     if (mask) {
103         mState.needsChanged |= mask;
104         mState.hook = process__validate;
105     }
106  }
107 
deleteTrackName(int name)108  void AudioMixer::deleteTrackName(int name)
109  {
110     name -= TRACK0;
111     if (uint32_t(name) < MAX_NUM_TRACKS) {
112         LOGV("deleteTrackName(%d)", name);
113         track_t& track(mState.tracks[ name ]);
114         if (track.enabled != 0) {
115             track.enabled = 0;
116             invalidateState(1<<name);
117         }
118         if (track.resampler) {
119             // delete  the resampler
120             delete track.resampler;
121             track.resampler = 0;
122             track.sampleRate = mSampleRate;
123             invalidateState(1<<name);
124         }
125         track.volumeInc[0] = 0;
126         track.volumeInc[1] = 0;
127         mTrackNames &= ~(1<<name);
128     }
129  }
130 
enable(int name)131 status_t AudioMixer::enable(int name)
132 {
133     switch (name) {
134         case MIXING: {
135             if (mState.tracks[ mActiveTrack ].enabled != 1) {
136                 mState.tracks[ mActiveTrack ].enabled = 1;
137                 LOGV("enable(%d)", mActiveTrack);
138                 invalidateState(1<<mActiveTrack);
139             }
140         } break;
141         default:
142             return NAME_NOT_FOUND;
143     }
144     return NO_ERROR;
145 }
146 
disable(int name)147 status_t AudioMixer::disable(int name)
148 {
149     switch (name) {
150         case MIXING: {
151             if (mState.tracks[ mActiveTrack ].enabled != 0) {
152                 mState.tracks[ mActiveTrack ].enabled = 0;
153                 LOGV("disable(%d)", mActiveTrack);
154                 invalidateState(1<<mActiveTrack);
155             }
156         } break;
157         default:
158             return NAME_NOT_FOUND;
159     }
160     return NO_ERROR;
161 }
162 
setActiveTrack(int track)163 status_t AudioMixer::setActiveTrack(int track)
164 {
165     if (uint32_t(track-TRACK0) >= MAX_NUM_TRACKS) {
166         return BAD_VALUE;
167     }
168     mActiveTrack = track - TRACK0;
169     return NO_ERROR;
170 }
171 
setParameter(int target,int name,int value)172 status_t AudioMixer::setParameter(int target, int name, int value)
173 {
174     switch (target) {
175     case TRACK:
176         if (name == CHANNEL_COUNT) {
177             if ((uint32_t(value) <= MAX_NUM_CHANNELS) && (value)) {
178                 if (mState.tracks[ mActiveTrack ].channelCount != value) {
179                     mState.tracks[ mActiveTrack ].channelCount = value;
180                     LOGV("setParameter(TRACK, CHANNEL_COUNT, %d)", value);
181                     invalidateState(1<<mActiveTrack);
182                 }
183                 return NO_ERROR;
184             }
185         }
186         break;
187     case RESAMPLE:
188         if (name == SAMPLE_RATE) {
189             if (value > 0) {
190                 track_t& track = mState.tracks[ mActiveTrack ];
191                 if (track.setResampler(uint32_t(value), mSampleRate)) {
192                     LOGV("setParameter(RESAMPLE, SAMPLE_RATE, %u)",
193                             uint32_t(value));
194                     invalidateState(1<<mActiveTrack);
195                 }
196                 return NO_ERROR;
197             }
198         }
199         break;
200     case RAMP_VOLUME:
201     case VOLUME:
202         if ((uint32_t(name-VOLUME0) < MAX_NUM_CHANNELS)) {
203             track_t& track = mState.tracks[ mActiveTrack ];
204             if (track.volume[name-VOLUME0] != value) {
205                 track.prevVolume[name-VOLUME0] = track.volume[name-VOLUME0] << 16;
206                 track.volume[name-VOLUME0] = value;
207                 if (target == VOLUME) {
208                     track.prevVolume[name-VOLUME0] = value << 16;
209                     track.volumeInc[name-VOLUME0] = 0;
210                 } else {
211                     int32_t d = (value<<16) - track.prevVolume[name-VOLUME0];
212                     int32_t volInc = d / int32_t(mState.frameCount);
213                     track.volumeInc[name-VOLUME0] = volInc;
214                     if (volInc == 0) {
215                         track.prevVolume[name-VOLUME0] = value << 16;
216                     }
217                 }
218                 invalidateState(1<<mActiveTrack);
219             }
220             return NO_ERROR;
221         }
222         break;
223     }
224     return BAD_VALUE;
225 }
226 
setResampler(uint32_t value,uint32_t devSampleRate)227 bool AudioMixer::track_t::setResampler(uint32_t value, uint32_t devSampleRate)
228 {
229     if (value!=devSampleRate || resampler) {
230         if (sampleRate != value) {
231             sampleRate = value;
232             if (resampler == 0) {
233                 resampler = AudioResampler::create(
234                         format, channelCount, devSampleRate);
235             }
236             return true;
237         }
238     }
239     return false;
240 }
241 
doesResample() const242 bool AudioMixer::track_t::doesResample() const
243 {
244     return resampler != 0;
245 }
246 
247 inline
adjustVolumeRamp()248 void AudioMixer::track_t::adjustVolumeRamp()
249 {
250     for (int i=0 ; i<2 ; i++) {
251         if (((volumeInc[i]>0) && (((prevVolume[i]+volumeInc[i])>>16) >= volume[i])) ||
252             ((volumeInc[i]<0) && (((prevVolume[i]+volumeInc[i])>>16) <= volume[i]))) {
253             volumeInc[i] = 0;
254             prevVolume[i] = volume[i]<<16;
255         }
256     }
257 }
258 
259 
setBufferProvider(AudioBufferProvider * buffer)260 status_t AudioMixer::setBufferProvider(AudioBufferProvider* buffer)
261 {
262     mState.tracks[ mActiveTrack ].bufferProvider = buffer;
263     return NO_ERROR;
264 }
265 
266 
267 
process(void * output)268 void AudioMixer::process(void* output)
269 {
270     mState.hook(&mState, output);
271 }
272 
273 
process__validate(state_t * state,void * output)274 void AudioMixer::process__validate(state_t* state, void* output)
275 {
276     LOGW_IF(!state->needsChanged,
277         "in process__validate() but nothing's invalid");
278 
279     uint32_t changed = state->needsChanged;
280     state->needsChanged = 0; // clear the validation flag
281 
282     // recompute which tracks are enabled / disabled
283     uint32_t enabled = 0;
284     uint32_t disabled = 0;
285     while (changed) {
286         const int i = 31 - __builtin_clz(changed);
287         const uint32_t mask = 1<<i;
288         changed &= ~mask;
289         track_t& t = state->tracks[i];
290         (t.enabled ? enabled : disabled) |= mask;
291     }
292     state->enabledTracks &= ~disabled;
293     state->enabledTracks |=  enabled;
294 
295     // compute everything we need...
296     int countActiveTracks = 0;
297     int all16BitsStereoNoResample = 1;
298     int resampling = 0;
299     int volumeRamp = 0;
300     uint32_t en = state->enabledTracks;
301     while (en) {
302         const int i = 31 - __builtin_clz(en);
303         en &= ~(1<<i);
304 
305         countActiveTracks++;
306         track_t& t = state->tracks[i];
307         uint32_t n = 0;
308         n |= NEEDS_CHANNEL_1 + t.channelCount - 1;
309         n |= NEEDS_FORMAT_16;
310         n |= t.doesResample() ? NEEDS_RESAMPLE_ENABLED : NEEDS_RESAMPLE_DISABLED;
311 
312         if (t.volumeInc[0]|t.volumeInc[1]) {
313             volumeRamp = 1;
314         } else if (!t.doesResample() && t.volumeRL == 0) {
315             n |= NEEDS_MUTE_ENABLED;
316         }
317         t.needs = n;
318 
319         if ((n & NEEDS_MUTE__MASK) == NEEDS_MUTE_ENABLED) {
320             t.hook = track__nop;
321         } else {
322             if ((n & NEEDS_RESAMPLE__MASK) == NEEDS_RESAMPLE_ENABLED) {
323                 all16BitsStereoNoResample = 0;
324                 resampling = 1;
325                 t.hook = track__genericResample;
326             } else {
327                 if ((n & NEEDS_CHANNEL_COUNT__MASK) == NEEDS_CHANNEL_1){
328                     t.hook = track__16BitsMono;
329                     all16BitsStereoNoResample = 0;
330                 }
331                 if ((n & NEEDS_CHANNEL_COUNT__MASK) == NEEDS_CHANNEL_2){
332                     t.hook = track__16BitsStereo;
333                 }
334             }
335         }
336     }
337 
338     // select the processing hooks
339     state->hook = process__nop;
340     if (countActiveTracks) {
341         if (resampling) {
342             if (!state->outputTemp) {
343                 state->outputTemp = new int32_t[MAX_NUM_CHANNELS * state->frameCount];
344             }
345             if (!state->resampleTemp) {
346                 state->resampleTemp = new int32_t[MAX_NUM_CHANNELS * state->frameCount];
347             }
348             state->hook = process__genericResampling;
349         } else {
350             if (state->outputTemp) {
351                 delete [] state->outputTemp;
352                 state->outputTemp = 0;
353             }
354             if (state->resampleTemp) {
355                 delete [] state->resampleTemp;
356                 state->resampleTemp = 0;
357             }
358             state->hook = process__genericNoResampling;
359             if (all16BitsStereoNoResample && !volumeRamp) {
360                 if (countActiveTracks == 1) {
361                     state->hook = process__OneTrack16BitsStereoNoResampling;
362                 }
363             }
364         }
365     }
366 
367     LOGV("mixer configuration change: %d activeTracks (%08x) "
368         "all16BitsStereoNoResample=%d, resampling=%d, volumeRamp=%d",
369         countActiveTracks, state->enabledTracks,
370         all16BitsStereoNoResample, resampling, volumeRamp);
371 
372    state->hook(state, output);
373 
374    // Now that the volume ramp has been done, set optimal state and
375    // track hooks for subsequent mixer process
376    if (countActiveTracks) {
377        int allMuted = 1;
378        uint32_t en = state->enabledTracks;
379        while (en) {
380            const int i = 31 - __builtin_clz(en);
381            en &= ~(1<<i);
382            track_t& t = state->tracks[i];
383            if (!t.doesResample() && t.volumeRL == 0)
384            {
385                t.needs |= NEEDS_MUTE_ENABLED;
386                t.hook = track__nop;
387            } else {
388                allMuted = 0;
389            }
390        }
391        if (allMuted) {
392            state->hook = process__nop;
393        } else if (!resampling && all16BitsStereoNoResample) {
394            if (countActiveTracks == 1) {
395               state->hook = process__OneTrack16BitsStereoNoResampling;
396            }
397        }
398    }
399 }
400 
401 static inline
mulAdd(int16_t in,int16_t v,int32_t a)402 int32_t mulAdd(int16_t in, int16_t v, int32_t a)
403 {
404 #if defined(__arm__) && !defined(__thumb__)
405     int32_t out;
406     asm( "smlabb %[out], %[in], %[v], %[a] \n"
407          : [out]"=r"(out)
408          : [in]"%r"(in), [v]"r"(v), [a]"r"(a)
409          : );
410     return out;
411 #else
412     return a + in * int32_t(v);
413 #endif
414 }
415 
416 static inline
mul(int16_t in,int16_t v)417 int32_t mul(int16_t in, int16_t v)
418 {
419 #if defined(__arm__) && !defined(__thumb__)
420     int32_t out;
421     asm( "smulbb %[out], %[in], %[v] \n"
422          : [out]"=r"(out)
423          : [in]"%r"(in), [v]"r"(v)
424          : );
425     return out;
426 #else
427     return in * int32_t(v);
428 #endif
429 }
430 
431 static inline
mulAddRL(int left,uint32_t inRL,uint32_t vRL,int32_t a)432 int32_t mulAddRL(int left, uint32_t inRL, uint32_t vRL, int32_t a)
433 {
434 #if defined(__arm__) && !defined(__thumb__)
435     int32_t out;
436     if (left) {
437         asm( "smlabb %[out], %[inRL], %[vRL], %[a] \n"
438              : [out]"=r"(out)
439              : [inRL]"%r"(inRL), [vRL]"r"(vRL), [a]"r"(a)
440              : );
441     } else {
442         asm( "smlatt %[out], %[inRL], %[vRL], %[a] \n"
443              : [out]"=r"(out)
444              : [inRL]"%r"(inRL), [vRL]"r"(vRL), [a]"r"(a)
445              : );
446     }
447     return out;
448 #else
449     if (left) {
450         return a + int16_t(inRL&0xFFFF) * int16_t(vRL&0xFFFF);
451     } else {
452         return a + int16_t(inRL>>16) * int16_t(vRL>>16);
453     }
454 #endif
455 }
456 
457 static inline
mulRL(int left,uint32_t inRL,uint32_t vRL)458 int32_t mulRL(int left, uint32_t inRL, uint32_t vRL)
459 {
460 #if defined(__arm__) && !defined(__thumb__)
461     int32_t out;
462     if (left) {
463         asm( "smulbb %[out], %[inRL], %[vRL] \n"
464              : [out]"=r"(out)
465              : [inRL]"%r"(inRL), [vRL]"r"(vRL)
466              : );
467     } else {
468         asm( "smultt %[out], %[inRL], %[vRL] \n"
469              : [out]"=r"(out)
470              : [inRL]"%r"(inRL), [vRL]"r"(vRL)
471              : );
472     }
473     return out;
474 #else
475     if (left) {
476         return int16_t(inRL&0xFFFF) * int16_t(vRL&0xFFFF);
477     } else {
478         return int16_t(inRL>>16) * int16_t(vRL>>16);
479     }
480 #endif
481 }
482 
483 
track__genericResample(track_t * t,int32_t * out,size_t outFrameCount,int32_t * temp)484 void AudioMixer::track__genericResample(track_t* t, int32_t* out, size_t outFrameCount, int32_t* temp)
485 {
486     t->resampler->setSampleRate(t->sampleRate);
487 
488     // ramp gain - resample to temp buffer and scale/mix in 2nd step
489     if UNLIKELY(t->volumeInc[0]|t->volumeInc[1]) {
490         t->resampler->setVolume(UNITY_GAIN, UNITY_GAIN);
491         memset(temp, 0, outFrameCount * MAX_NUM_CHANNELS * sizeof(int32_t));
492         t->resampler->resample(temp, outFrameCount, t->bufferProvider);
493         volumeRampStereo(t, out, outFrameCount, temp);
494     }
495 
496     // constant gain
497     else {
498         t->resampler->setVolume(t->volume[0], t->volume[1]);
499         t->resampler->resample(out, outFrameCount, t->bufferProvider);
500     }
501 }
502 
track__nop(track_t * t,int32_t * out,size_t outFrameCount,int32_t * temp)503 void AudioMixer::track__nop(track_t* t, int32_t* out, size_t outFrameCount, int32_t* temp)
504 {
505 }
506 
volumeRampStereo(track_t * t,int32_t * out,size_t frameCount,int32_t * temp)507 void AudioMixer::volumeRampStereo(track_t* t, int32_t* out, size_t frameCount, int32_t* temp)
508 {
509     int32_t vl = t->prevVolume[0];
510     int32_t vr = t->prevVolume[1];
511     const int32_t vlInc = t->volumeInc[0];
512     const int32_t vrInc = t->volumeInc[1];
513 
514     //LOGD("[0] %p: inc=%f, v0=%f, v1=%d, final=%f, count=%d",
515     //        t, vlInc/65536.0f, vl/65536.0f, t->volume[0],
516     //       (vl + vlInc*frameCount)/65536.0f, frameCount);
517 
518     // ramp volume
519     do {
520         *out++ += (vl >> 16) * (*temp++ >> 12);
521         *out++ += (vr >> 16) * (*temp++ >> 12);
522         vl += vlInc;
523         vr += vrInc;
524     } while (--frameCount);
525 
526     t->prevVolume[0] = vl;
527     t->prevVolume[1] = vr;
528     t->adjustVolumeRamp();
529 }
530 
track__16BitsStereo(track_t * t,int32_t * out,size_t frameCount,int32_t * temp)531 void AudioMixer::track__16BitsStereo(track_t* t, int32_t* out, size_t frameCount, int32_t* temp)
532 {
533     int16_t const *in = static_cast<int16_t const *>(t->in);
534 
535     // ramp gain
536     if UNLIKELY(t->volumeInc[0]|t->volumeInc[1]) {
537         int32_t vl = t->prevVolume[0];
538         int32_t vr = t->prevVolume[1];
539         const int32_t vlInc = t->volumeInc[0];
540         const int32_t vrInc = t->volumeInc[1];
541 
542         // LOGD("[1] %p: inc=%f, v0=%f, v1=%d, final=%f, count=%d",
543         //        t, vlInc/65536.0f, vl/65536.0f, t->volume[0],
544         //        (vl + vlInc*frameCount)/65536.0f, frameCount);
545 
546         do {
547             *out++ += (vl >> 16) * (int32_t) *in++;
548             *out++ += (vr >> 16) * (int32_t) *in++;
549             vl += vlInc;
550             vr += vrInc;
551         } while (--frameCount);
552 
553         t->prevVolume[0] = vl;
554         t->prevVolume[1] = vr;
555         t->adjustVolumeRamp();
556     }
557 
558     // constant gain
559     else {
560         const uint32_t vrl = t->volumeRL;
561         do {
562             uint32_t rl = *reinterpret_cast<uint32_t const *>(in);
563             in += 2;
564             out[0] = mulAddRL(1, rl, vrl, out[0]);
565             out[1] = mulAddRL(0, rl, vrl, out[1]);
566             out += 2;
567         } while (--frameCount);
568     }
569     t->in = in;
570 }
571 
track__16BitsMono(track_t * t,int32_t * out,size_t frameCount,int32_t * temp)572 void AudioMixer::track__16BitsMono(track_t* t, int32_t* out, size_t frameCount, int32_t* temp)
573 {
574     int16_t const *in = static_cast<int16_t const *>(t->in);
575 
576     // ramp gain
577     if UNLIKELY(t->volumeInc[0]|t->volumeInc[1]) {
578         int32_t vl = t->prevVolume[0];
579         int32_t vr = t->prevVolume[1];
580         const int32_t vlInc = t->volumeInc[0];
581         const int32_t vrInc = t->volumeInc[1];
582 
583         // LOGD("[2] %p: inc=%f, v0=%f, v1=%d, final=%f, count=%d",
584         //         t, vlInc/65536.0f, vl/65536.0f, t->volume[0],
585         //         (vl + vlInc*frameCount)/65536.0f, frameCount);
586 
587         do {
588             int32_t l = *in++;
589             *out++ += (vl >> 16) * l;
590             *out++ += (vr >> 16) * l;
591             vl += vlInc;
592             vr += vrInc;
593         } while (--frameCount);
594 
595         t->prevVolume[0] = vl;
596         t->prevVolume[1] = vr;
597         t->adjustVolumeRamp();
598     }
599     // constant gain
600     else {
601         const int16_t vl = t->volume[0];
602         const int16_t vr = t->volume[1];
603         do {
604             int16_t l = *in++;
605             out[0] = mulAdd(l, vl, out[0]);
606             out[1] = mulAdd(l, vr, out[1]);
607             out += 2;
608         } while (--frameCount);
609     }
610     t->in = in;
611 }
612 
ditherAndClamp(int32_t * out,int32_t const * sums,size_t c)613 void AudioMixer::ditherAndClamp(int32_t* out, int32_t const *sums, size_t c)
614 {
615     for (size_t i=0 ; i<c ; i++) {
616         int32_t l = *sums++;
617         int32_t r = *sums++;
618         int32_t nl = l >> 12;
619         int32_t nr = r >> 12;
620         l = clamp16(nl);
621         r = clamp16(nr);
622         *out++ = (r<<16) | (l & 0xFFFF);
623     }
624 }
625 
626 // no-op case
process__nop(state_t * state,void * output)627 void AudioMixer::process__nop(state_t* state, void* output)
628 {
629     // this assumes output 16 bits stereo, no resampling
630     memset(output, 0, state->frameCount*4);
631     uint32_t en = state->enabledTracks;
632     while (en) {
633         const int i = 31 - __builtin_clz(en);
634         en &= ~(1<<i);
635         track_t& t = state->tracks[i];
636         size_t outFrames = state->frameCount;
637         while (outFrames) {
638             t.buffer.frameCount = outFrames;
639             t.bufferProvider->getNextBuffer(&t.buffer);
640             if (!t.buffer.raw) break;
641             outFrames -= t.buffer.frameCount;
642             t.bufferProvider->releaseBuffer(&t.buffer);
643         }
644     }
645 }
646 
647 // generic code without resampling
process__genericNoResampling(state_t * state,void * output)648 void AudioMixer::process__genericNoResampling(state_t* state, void* output)
649 {
650     int32_t outTemp[BLOCKSIZE * MAX_NUM_CHANNELS] __attribute__((aligned(32)));
651 
652     // acquire each track's buffer
653     uint32_t enabledTracks = state->enabledTracks;
654     uint32_t en = enabledTracks;
655     while (en) {
656         const int i = 31 - __builtin_clz(en);
657         en &= ~(1<<i);
658         track_t& t = state->tracks[i];
659         t.buffer.frameCount = state->frameCount;
660         t.bufferProvider->getNextBuffer(&t.buffer);
661         t.frameCount = t.buffer.frameCount;
662         t.in = t.buffer.raw;
663         // t.in == NULL can happen if the track was flushed just after having
664         // been enabled for mixing.
665         if (t.in == NULL)
666             enabledTracks &= ~(1<<i);
667     }
668 
669     // this assumes output 16 bits stereo, no resampling
670     int32_t* out = static_cast<int32_t*>(output);
671     size_t numFrames = state->frameCount;
672     do {
673         memset(outTemp, 0, sizeof(outTemp));
674 
675         en = enabledTracks;
676         while (en) {
677             const int i = 31 - __builtin_clz(en);
678             en &= ~(1<<i);
679             track_t& t = state->tracks[i];
680             size_t outFrames = BLOCKSIZE;
681 
682             while (outFrames) {
683                 size_t inFrames = (t.frameCount > outFrames)?outFrames:t.frameCount;
684                 if (inFrames) {
685                     (t.hook)(&t, outTemp + (BLOCKSIZE-outFrames)*MAX_NUM_CHANNELS, inFrames, state->resampleTemp);
686                     t.frameCount -= inFrames;
687                     outFrames -= inFrames;
688                 }
689                 if (t.frameCount == 0 && outFrames) {
690                     t.bufferProvider->releaseBuffer(&t.buffer);
691                     t.buffer.frameCount = numFrames - (BLOCKSIZE - outFrames);
692                     t.bufferProvider->getNextBuffer(&t.buffer);
693                     t.in = t.buffer.raw;
694                     if (t.in == NULL) {
695                         enabledTracks &= ~(1<<i);
696                         break;
697                     }
698                     t.frameCount = t.buffer.frameCount;
699                  }
700             }
701         }
702 
703         ditherAndClamp(out, outTemp, BLOCKSIZE);
704         out += BLOCKSIZE;
705         numFrames -= BLOCKSIZE;
706     } while (numFrames);
707 
708 
709     // release each track's buffer
710     en = enabledTracks;
711     while (en) {
712         const int i = 31 - __builtin_clz(en);
713         en &= ~(1<<i);
714         track_t& t = state->tracks[i];
715         t.bufferProvider->releaseBuffer(&t.buffer);
716     }
717 }
718 
719 // generic code with resampling
process__genericResampling(state_t * state,void * output)720 void AudioMixer::process__genericResampling(state_t* state, void* output)
721 {
722     int32_t* const outTemp = state->outputTemp;
723     const size_t size = sizeof(int32_t) * MAX_NUM_CHANNELS * state->frameCount;
724     memset(outTemp, 0, size);
725 
726     int32_t* out = static_cast<int32_t*>(output);
727     size_t numFrames = state->frameCount;
728 
729     uint32_t en = state->enabledTracks;
730     while (en) {
731         const int i = 31 - __builtin_clz(en);
732         en &= ~(1<<i);
733         track_t& t = state->tracks[i];
734 
735         // this is a little goofy, on the resampling case we don't
736         // acquire/release the buffers because it's done by
737         // the resampler.
738         if ((t.needs & NEEDS_RESAMPLE__MASK) == NEEDS_RESAMPLE_ENABLED) {
739             (t.hook)(&t, outTemp, numFrames, state->resampleTemp);
740         } else {
741 
742             size_t outFrames = numFrames;
743 
744             while (outFrames) {
745                 t.buffer.frameCount = outFrames;
746                 t.bufferProvider->getNextBuffer(&t.buffer);
747                 t.in = t.buffer.raw;
748                 // t.in == NULL can happen if the track was flushed just after having
749                 // been enabled for mixing.
750                 if (t.in == NULL) break;
751 
752                 (t.hook)(&t, outTemp + (numFrames-outFrames)*MAX_NUM_CHANNELS, t.buffer.frameCount, state->resampleTemp);
753                 outFrames -= t.buffer.frameCount;
754                 t.bufferProvider->releaseBuffer(&t.buffer);
755             }
756         }
757     }
758 
759     ditherAndClamp(out, outTemp, numFrames);
760 }
761 
762 // one track, 16 bits stereo without resampling is the most common case
process__OneTrack16BitsStereoNoResampling(state_t * state,void * output)763 void AudioMixer::process__OneTrack16BitsStereoNoResampling(state_t* state, void* output)
764 {
765     const int i = 31 - __builtin_clz(state->enabledTracks);
766     const track_t& t = state->tracks[i];
767 
768     AudioBufferProvider::Buffer& b(t.buffer);
769 
770     int32_t* out = static_cast<int32_t*>(output);
771     size_t numFrames = state->frameCount;
772 
773     const int16_t vl = t.volume[0];
774     const int16_t vr = t.volume[1];
775     const uint32_t vrl = t.volumeRL;
776     while (numFrames) {
777         b.frameCount = numFrames;
778         t.bufferProvider->getNextBuffer(&b);
779         int16_t const *in = b.i16;
780 
781         // in == NULL can happen if the track was flushed just after having
782         // been enabled for mixing.
783         if (in == NULL || ((unsigned long)in & 3)) {
784             memset(out, 0, numFrames*MAX_NUM_CHANNELS*sizeof(int16_t));
785             LOGE_IF(((unsigned long)in & 3), "process stereo track: input buffer alignment pb: buffer %p track %d, channels %d, needs %08x",
786                     in, i, t.channelCount, t.needs);
787             return;
788         }
789         size_t outFrames = b.frameCount;
790 
791         if (UNLIKELY(uint32_t(vl) > UNITY_GAIN || uint32_t(vr) > UNITY_GAIN)) {
792             // volume is boosted, so we might need to clamp even though
793             // we process only one track.
794             do {
795                 uint32_t rl = *reinterpret_cast<uint32_t const *>(in);
796                 in += 2;
797                 int32_t l = mulRL(1, rl, vrl) >> 12;
798                 int32_t r = mulRL(0, rl, vrl) >> 12;
799                 // clamping...
800                 l = clamp16(l);
801                 r = clamp16(r);
802                 *out++ = (r<<16) | (l & 0xFFFF);
803             } while (--outFrames);
804         } else {
805             do {
806                 uint32_t rl = *reinterpret_cast<uint32_t const *>(in);
807                 in += 2;
808                 int32_t l = mulRL(1, rl, vrl) >> 12;
809                 int32_t r = mulRL(0, rl, vrl) >> 12;
810                 *out++ = (r<<16) | (l & 0xFFFF);
811             } while (--outFrames);
812         }
813         numFrames -= b.frameCount;
814         t.bufferProvider->releaseBuffer(&b);
815     }
816 }
817 
818 // 2 tracks is also a common case
process__TwoTracks16BitsStereoNoResampling(state_t * state,void * output)819 void AudioMixer::process__TwoTracks16BitsStereoNoResampling(state_t* state, void* output)
820 {
821     int i;
822     uint32_t en = state->enabledTracks;
823 
824     i = 31 - __builtin_clz(en);
825     const track_t& t0 = state->tracks[i];
826     AudioBufferProvider::Buffer& b0(t0.buffer);
827 
828     en &= ~(1<<i);
829     i = 31 - __builtin_clz(en);
830     const track_t& t1 = state->tracks[i];
831     AudioBufferProvider::Buffer& b1(t1.buffer);
832 
833     int16_t const *in0;
834     const int16_t vl0 = t0.volume[0];
835     const int16_t vr0 = t0.volume[1];
836     size_t frameCount0 = 0;
837 
838     int16_t const *in1;
839     const int16_t vl1 = t1.volume[0];
840     const int16_t vr1 = t1.volume[1];
841     size_t frameCount1 = 0;
842 
843     int32_t* out = static_cast<int32_t*>(output);
844     size_t numFrames = state->frameCount;
845     int16_t const *buff = NULL;
846 
847 
848     while (numFrames) {
849 
850         if (frameCount0 == 0) {
851             b0.frameCount = numFrames;
852             t0.bufferProvider->getNextBuffer(&b0);
853             if (b0.i16 == NULL) {
854                 if (buff == NULL) {
855                     buff = new int16_t[MAX_NUM_CHANNELS * state->frameCount];
856                 }
857                 in0 = buff;
858                 b0.frameCount = numFrames;
859             } else {
860                 in0 = b0.i16;
861             }
862             frameCount0 = b0.frameCount;
863         }
864         if (frameCount1 == 0) {
865             b1.frameCount = numFrames;
866             t1.bufferProvider->getNextBuffer(&b1);
867             if (b1.i16 == NULL) {
868                 if (buff == NULL) {
869                     buff = new int16_t[MAX_NUM_CHANNELS * state->frameCount];
870                 }
871                 in1 = buff;
872                 b1.frameCount = numFrames;
873                } else {
874                 in1 = b1.i16;
875             }
876             frameCount1 = b1.frameCount;
877         }
878 
879         size_t outFrames = frameCount0 < frameCount1?frameCount0:frameCount1;
880 
881         numFrames -= outFrames;
882         frameCount0 -= outFrames;
883         frameCount1 -= outFrames;
884 
885         do {
886             int32_t l0 = *in0++;
887             int32_t r0 = *in0++;
888             l0 = mul(l0, vl0);
889             r0 = mul(r0, vr0);
890             int32_t l = *in1++;
891             int32_t r = *in1++;
892             l = mulAdd(l, vl1, l0) >> 12;
893             r = mulAdd(r, vr1, r0) >> 12;
894             // clamping...
895             l = clamp16(l);
896             r = clamp16(r);
897             *out++ = (r<<16) | (l & 0xFFFF);
898         } while (--outFrames);
899 
900         if (frameCount0 == 0) {
901             t0.bufferProvider->releaseBuffer(&b0);
902         }
903         if (frameCount1 == 0) {
904             t1.bufferProvider->releaseBuffer(&b1);
905         }
906     }
907 
908     if (buff != NULL) {
909         delete [] buff;
910     }
911 }
912 
913 // ----------------------------------------------------------------------------
914 }; // namespace android
915 
916