1 /*
2 **
3 ** Copyright 2019, 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 <sstream>
22 #include <string.h>
23 
24 #include <audio_utils/primitives.h>
25 #include <cutils/compiler.h>
26 #include <media/AudioMixerBase.h>
27 #include <utils/Log.h>
28 
29 #include "AudioMixerOps.h"
30 
31 // The FCC_2 macro refers to the Fixed Channel Count of 2 for the legacy integer mixer.
32 #ifndef FCC_2
33 #define FCC_2 2
34 #endif
35 
36 // Look for MONO_HACK for any Mono hack involving legacy mono channel to
37 // stereo channel conversion.
38 
39 /* VERY_VERY_VERBOSE_LOGGING will show exactly which process hook and track hook is
40  * being used. This is a considerable amount of log spam, so don't enable unless you
41  * are verifying the hook based code.
42  */
43 //#define VERY_VERY_VERBOSE_LOGGING
44 #ifdef VERY_VERY_VERBOSE_LOGGING
45 #define ALOGVV ALOGV
46 //define ALOGVV printf  // for test-mixer.cpp
47 #else
48 #define ALOGVV(a...) do { } while (0)
49 #endif
50 
51 // TODO: remove BLOCKSIZE unit of processing - it isn't needed anymore.
52 static constexpr int BLOCKSIZE = 16;
53 
54 namespace android {
55 
56 // ----------------------------------------------------------------------------
57 
isValidFormat(audio_format_t format) const58 bool AudioMixerBase::isValidFormat(audio_format_t format) const
59 {
60     switch (format) {
61     case AUDIO_FORMAT_PCM_8_BIT:
62     case AUDIO_FORMAT_PCM_16_BIT:
63     case AUDIO_FORMAT_PCM_24_BIT_PACKED:
64     case AUDIO_FORMAT_PCM_32_BIT:
65     case AUDIO_FORMAT_PCM_FLOAT:
66         return true;
67     default:
68         return false;
69     }
70 }
71 
isValidChannelMask(audio_channel_mask_t channelMask) const72 bool AudioMixerBase::isValidChannelMask(audio_channel_mask_t channelMask) const
73 {
74     return audio_channel_count_from_out_mask(channelMask) <= MAX_NUM_CHANNELS;
75 }
76 
preCreateTrack()77 std::shared_ptr<AudioMixerBase::TrackBase> AudioMixerBase::preCreateTrack()
78 {
79     return std::make_shared<TrackBase>();
80 }
81 
create(int name,audio_channel_mask_t channelMask,audio_format_t format,int sessionId)82 status_t AudioMixerBase::create(
83         int name, audio_channel_mask_t channelMask, audio_format_t format, int sessionId)
84 {
85     LOG_ALWAYS_FATAL_IF(exists(name), "name %d already exists", name);
86 
87     if (!isValidChannelMask(channelMask)) {
88         ALOGE("%s invalid channelMask: %#x", __func__, channelMask);
89         return BAD_VALUE;
90     }
91     if (!isValidFormat(format)) {
92         ALOGE("%s invalid format: %#x", __func__, format);
93         return BAD_VALUE;
94     }
95 
96     auto t = preCreateTrack();
97     {
98         // TODO: move initialization to the Track constructor.
99         // assume default parameters for the track, except where noted below
100         t->needs = 0;
101 
102         // Integer volume.
103         // Currently integer volume is kept for the legacy integer mixer.
104         // Will be removed when the legacy mixer path is removed.
105         t->volume[0] = 0;
106         t->volume[1] = 0;
107         t->prevVolume[0] = 0 << 16;
108         t->prevVolume[1] = 0 << 16;
109         t->volumeInc[0] = 0;
110         t->volumeInc[1] = 0;
111         t->auxLevel = 0;
112         t->auxInc = 0;
113         t->prevAuxLevel = 0;
114 
115         // Floating point volume.
116         t->mVolume[0] = 0.f;
117         t->mVolume[1] = 0.f;
118         t->mPrevVolume[0] = 0.f;
119         t->mPrevVolume[1] = 0.f;
120         t->mVolumeInc[0] = 0.;
121         t->mVolumeInc[1] = 0.;
122         t->mAuxLevel = 0.;
123         t->mAuxInc = 0.;
124         t->mPrevAuxLevel = 0.;
125 
126         // no initialization needed
127         // t->frameCount
128         t->channelCount = audio_channel_count_from_out_mask(channelMask);
129         t->enabled = false;
130         ALOGV_IF(audio_channel_mask_get_bits(channelMask) != AUDIO_CHANNEL_OUT_STEREO,
131                 "Non-stereo channel mask: %d\n", channelMask);
132         t->channelMask = channelMask;
133         t->sessionId = sessionId;
134         // setBufferProvider(name, AudioBufferProvider *) is required before enable(name)
135         t->bufferProvider = NULL;
136         t->buffer.raw = NULL;
137         // no initialization needed
138         // t->buffer.frameCount
139         t->hook = NULL;
140         t->mIn = NULL;
141         t->sampleRate = mSampleRate;
142         // setParameter(name, TRACK, MAIN_BUFFER, mixBuffer) is required before enable(name)
143         t->mainBuffer = NULL;
144         t->auxBuffer = NULL;
145         t->mMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
146         t->mFormat = format;
147         t->mMixerInFormat = kUseFloat && kUseNewMixer ?
148                 AUDIO_FORMAT_PCM_FLOAT : AUDIO_FORMAT_PCM_16_BIT;
149         t->mMixerChannelMask = audio_channel_mask_from_representation_and_bits(
150                 AUDIO_CHANNEL_REPRESENTATION_POSITION, AUDIO_CHANNEL_OUT_STEREO);
151         t->mMixerChannelCount = audio_channel_count_from_out_mask(t->mMixerChannelMask);
152         status_t status = postCreateTrack(t.get());
153         if (status != OK) return status;
154         mTracks[name] = t;
155         return OK;
156     }
157 }
158 
159 // Called when channel masks have changed for a track name
setChannelMasks(int name,audio_channel_mask_t trackChannelMask,audio_channel_mask_t mixerChannelMask)160 bool AudioMixerBase::setChannelMasks(int name,
161         audio_channel_mask_t trackChannelMask, audio_channel_mask_t mixerChannelMask)
162 {
163     LOG_ALWAYS_FATAL_IF(!exists(name), "invalid name: %d", name);
164     const std::shared_ptr<TrackBase> &track = mTracks[name];
165 
166     if (trackChannelMask == track->channelMask && mixerChannelMask == track->mMixerChannelMask) {
167         return false;  // no need to change
168     }
169     // always recompute for both channel masks even if only one has changed.
170     const uint32_t trackChannelCount = audio_channel_count_from_out_mask(trackChannelMask);
171     const uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mixerChannelMask);
172 
173     ALOG_ASSERT(trackChannelCount && mixerChannelCount);
174     track->channelMask = trackChannelMask;
175     track->channelCount = trackChannelCount;
176     track->mMixerChannelMask = mixerChannelMask;
177     track->mMixerChannelCount = mixerChannelCount;
178 
179     // Resampler channels may have changed.
180     track->recreateResampler(mSampleRate);
181     return true;
182 }
183 
destroy(int name)184 void AudioMixerBase::destroy(int name)
185 {
186     LOG_ALWAYS_FATAL_IF(!exists(name), "invalid name: %d", name);
187     ALOGV("deleteTrackName(%d)", name);
188 
189     if (mTracks[name]->enabled) {
190         invalidate();
191     }
192     mTracks.erase(name); // deallocate track
193 }
194 
enable(int name)195 void AudioMixerBase::enable(int name)
196 {
197     LOG_ALWAYS_FATAL_IF(!exists(name), "invalid name: %d", name);
198     const std::shared_ptr<TrackBase> &track = mTracks[name];
199 
200     if (!track->enabled) {
201         track->enabled = true;
202         ALOGV("enable(%d)", name);
203         invalidate();
204     }
205 }
206 
disable(int name)207 void AudioMixerBase::disable(int name)
208 {
209     LOG_ALWAYS_FATAL_IF(!exists(name), "invalid name: %d", name);
210     const std::shared_ptr<TrackBase> &track = mTracks[name];
211 
212     if (track->enabled) {
213         track->enabled = false;
214         ALOGV("disable(%d)", name);
215         invalidate();
216     }
217 }
218 
219 /* Sets the volume ramp variables for the AudioMixer.
220  *
221  * The volume ramp variables are used to transition from the previous
222  * volume to the set volume.  ramp controls the duration of the transition.
223  * Its value is typically one state framecount period, but may also be 0,
224  * meaning "immediate."
225  *
226  * FIXME: 1) Volume ramp is enabled only if there is a nonzero integer increment
227  * even if there is a nonzero floating point increment (in that case, the volume
228  * change is immediate).  This restriction should be changed when the legacy mixer
229  * is removed (see #2).
230  * FIXME: 2) Integer volume variables are used for Legacy mixing and should be removed
231  * when no longer needed.
232  *
233  * @param newVolume set volume target in floating point [0.0, 1.0].
234  * @param ramp number of frames to increment over. if ramp is 0, the volume
235  * should be set immediately.  Currently ramp should not exceed 65535 (frames).
236  * @param pIntSetVolume pointer to the U4.12 integer target volume, set on return.
237  * @param pIntPrevVolume pointer to the U4.28 integer previous volume, set on return.
238  * @param pIntVolumeInc pointer to the U4.28 increment per output audio frame, set on return.
239  * @param pSetVolume pointer to the float target volume, set on return.
240  * @param pPrevVolume pointer to the float previous volume, set on return.
241  * @param pVolumeInc pointer to the float increment per output audio frame, set on return.
242  * @return true if the volume has changed, false if volume is same.
243  */
setVolumeRampVariables(float newVolume,int32_t ramp,int16_t * pIntSetVolume,int32_t * pIntPrevVolume,int32_t * pIntVolumeInc,float * pSetVolume,float * pPrevVolume,float * pVolumeInc)244 static inline bool setVolumeRampVariables(float newVolume, int32_t ramp,
245         int16_t *pIntSetVolume, int32_t *pIntPrevVolume, int32_t *pIntVolumeInc,
246         float *pSetVolume, float *pPrevVolume, float *pVolumeInc) {
247     // check floating point volume to see if it is identical to the previously
248     // set volume.
249     // We do not use a tolerance here (and reject changes too small)
250     // as it may be confusing to use a different value than the one set.
251     // If the resulting volume is too small to ramp, it is a direct set of the volume.
252     if (newVolume == *pSetVolume) {
253         return false;
254     }
255     if (newVolume < 0) {
256         newVolume = 0; // should not have negative volumes
257     } else {
258         switch (fpclassify(newVolume)) {
259         case FP_SUBNORMAL:
260         case FP_NAN:
261             newVolume = 0;
262             break;
263         case FP_ZERO:
264             break; // zero volume is fine
265         case FP_INFINITE:
266             // Infinite volume could be handled consistently since
267             // floating point math saturates at infinities,
268             // but we limit volume to unity gain float.
269             // ramp = 0; break;
270             //
271             newVolume = AudioMixerBase::UNITY_GAIN_FLOAT;
272             break;
273         case FP_NORMAL:
274         default:
275             // Floating point does not have problems with overflow wrap
276             // that integer has.  However, we limit the volume to
277             // unity gain here.
278             // TODO: Revisit the volume limitation and perhaps parameterize.
279             if (newVolume > AudioMixerBase::UNITY_GAIN_FLOAT) {
280                 newVolume = AudioMixerBase::UNITY_GAIN_FLOAT;
281             }
282             break;
283         }
284     }
285 
286     // set floating point volume ramp
287     if (ramp != 0) {
288         // when the ramp completes, *pPrevVolume is set to *pSetVolume, so there
289         // is no computational mismatch; hence equality is checked here.
290         ALOGD_IF(*pPrevVolume != *pSetVolume, "previous float ramp hasn't finished,"
291                 " prev:%f  set_to:%f", *pPrevVolume, *pSetVolume);
292         const float inc = (newVolume - *pPrevVolume) / ramp; // could be inf, nan, subnormal
293         // could be inf, cannot be nan, subnormal
294         const float maxv = std::max(newVolume, *pPrevVolume);
295 
296         if (isnormal(inc) // inc must be a normal number (no subnormals, infinite, nan)
297                 && maxv + inc != maxv) { // inc must make forward progress
298             *pVolumeInc = inc;
299             // ramp is set now.
300             // Note: if newVolume is 0, then near the end of the ramp,
301             // it may be possible that the ramped volume may be subnormal or
302             // temporarily negative by a small amount or subnormal due to floating
303             // point inaccuracies.
304         } else {
305             ramp = 0; // ramp not allowed
306         }
307     }
308 
309     // compute and check integer volume, no need to check negative values
310     // The integer volume is limited to "unity_gain" to avoid wrapping and other
311     // audio artifacts, so it never reaches the range limit of U4.28.
312     // We safely use signed 16 and 32 bit integers here.
313     const float scaledVolume = newVolume * AudioMixerBase::UNITY_GAIN_INT; // not neg, subnormal, nan
314     const int32_t intVolume = (scaledVolume >= (float)AudioMixerBase::UNITY_GAIN_INT) ?
315             AudioMixerBase::UNITY_GAIN_INT : (int32_t)scaledVolume;
316 
317     // set integer volume ramp
318     if (ramp != 0) {
319         // integer volume is U4.12 (to use 16 bit multiplies), but ramping uses U4.28.
320         // when the ramp completes, *pIntPrevVolume is set to *pIntSetVolume << 16, so there
321         // is no computational mismatch; hence equality is checked here.
322         ALOGD_IF(*pIntPrevVolume != *pIntSetVolume << 16, "previous int ramp hasn't finished,"
323                 " prev:%d  set_to:%d", *pIntPrevVolume, *pIntSetVolume << 16);
324         const int32_t inc = ((intVolume << 16) - *pIntPrevVolume) / ramp;
325 
326         if (inc != 0) { // inc must make forward progress
327             *pIntVolumeInc = inc;
328         } else {
329             ramp = 0; // ramp not allowed
330         }
331     }
332 
333     // if no ramp, or ramp not allowed, then clear float and integer increments
334     if (ramp == 0) {
335         *pVolumeInc = 0;
336         *pPrevVolume = newVolume;
337         *pIntVolumeInc = 0;
338         *pIntPrevVolume = intVolume << 16;
339     }
340     *pSetVolume = newVolume;
341     *pIntSetVolume = intVolume;
342     return true;
343 }
344 
setParameter(int name,int target,int param,void * value)345 void AudioMixerBase::setParameter(int name, int target, int param, void *value)
346 {
347     LOG_ALWAYS_FATAL_IF(!exists(name), "invalid name: %d", name);
348     const std::shared_ptr<TrackBase> &track = mTracks[name];
349 
350     int valueInt = static_cast<int>(reinterpret_cast<uintptr_t>(value));
351     int32_t *valueBuf = reinterpret_cast<int32_t*>(value);
352 
353     switch (target) {
354 
355     case TRACK:
356         switch (param) {
357         case CHANNEL_MASK: {
358             const audio_channel_mask_t trackChannelMask =
359                 static_cast<audio_channel_mask_t>(valueInt);
360             if (setChannelMasks(name, trackChannelMask, track->mMixerChannelMask)) {
361                 ALOGV("setParameter(TRACK, CHANNEL_MASK, %x)", trackChannelMask);
362                 invalidate();
363             }
364             } break;
365         case MAIN_BUFFER:
366             if (track->mainBuffer != valueBuf) {
367                 track->mainBuffer = valueBuf;
368                 ALOGV("setParameter(TRACK, MAIN_BUFFER, %p)", valueBuf);
369                 invalidate();
370             }
371             break;
372         case AUX_BUFFER:
373             if (track->auxBuffer != valueBuf) {
374                 track->auxBuffer = valueBuf;
375                 ALOGV("setParameter(TRACK, AUX_BUFFER, %p)", valueBuf);
376                 invalidate();
377             }
378             break;
379         case FORMAT: {
380             audio_format_t format = static_cast<audio_format_t>(valueInt);
381             if (track->mFormat != format) {
382                 ALOG_ASSERT(audio_is_linear_pcm(format), "Invalid format %#x", format);
383                 track->mFormat = format;
384                 ALOGV("setParameter(TRACK, FORMAT, %#x)", format);
385                 invalidate();
386             }
387             } break;
388         case MIXER_FORMAT: {
389             audio_format_t format = static_cast<audio_format_t>(valueInt);
390             if (track->mMixerFormat != format) {
391                 track->mMixerFormat = format;
392                 ALOGV("setParameter(TRACK, MIXER_FORMAT, %#x)", format);
393             }
394             } break;
395         case MIXER_CHANNEL_MASK: {
396             const audio_channel_mask_t mixerChannelMask =
397                     static_cast<audio_channel_mask_t>(valueInt);
398             if (setChannelMasks(name, track->channelMask, mixerChannelMask)) {
399                 ALOGV("setParameter(TRACK, MIXER_CHANNEL_MASK, %#x)", mixerChannelMask);
400                 invalidate();
401             }
402             } break;
403         default:
404             LOG_ALWAYS_FATAL("setParameter track: bad param %d", param);
405         }
406         break;
407 
408     case RESAMPLE:
409         switch (param) {
410         case SAMPLE_RATE:
411             ALOG_ASSERT(valueInt > 0, "bad sample rate %d", valueInt);
412             if (track->setResampler(uint32_t(valueInt), mSampleRate)) {
413                 ALOGV("setParameter(RESAMPLE, SAMPLE_RATE, %u)",
414                         uint32_t(valueInt));
415                 invalidate();
416             }
417             break;
418         case RESET:
419             track->resetResampler();
420             invalidate();
421             break;
422         case REMOVE:
423             track->mResampler.reset(nullptr);
424             track->sampleRate = mSampleRate;
425             invalidate();
426             break;
427         default:
428             LOG_ALWAYS_FATAL("setParameter resample: bad param %d", param);
429         }
430         break;
431 
432     case RAMP_VOLUME:
433     case VOLUME:
434         switch (param) {
435         case AUXLEVEL:
436             if (setVolumeRampVariables(*reinterpret_cast<float*>(value),
437                     target == RAMP_VOLUME ? mFrameCount : 0,
438                     &track->auxLevel, &track->prevAuxLevel, &track->auxInc,
439                     &track->mAuxLevel, &track->mPrevAuxLevel, &track->mAuxInc)) {
440                 ALOGV("setParameter(%s, AUXLEVEL: %04x)",
441                         target == VOLUME ? "VOLUME" : "RAMP_VOLUME", track->auxLevel);
442                 invalidate();
443             }
444             break;
445         default:
446             if ((unsigned)param >= VOLUME0 && (unsigned)param < VOLUME0 + MAX_NUM_VOLUMES) {
447                 if (setVolumeRampVariables(*reinterpret_cast<float*>(value),
448                         target == RAMP_VOLUME ? mFrameCount : 0,
449                         &track->volume[param - VOLUME0],
450                         &track->prevVolume[param - VOLUME0],
451                         &track->volumeInc[param - VOLUME0],
452                         &track->mVolume[param - VOLUME0],
453                         &track->mPrevVolume[param - VOLUME0],
454                         &track->mVolumeInc[param - VOLUME0])) {
455                     ALOGV("setParameter(%s, VOLUME%d: %04x)",
456                             target == VOLUME ? "VOLUME" : "RAMP_VOLUME", param - VOLUME0,
457                                     track->volume[param - VOLUME0]);
458                     invalidate();
459                 }
460             } else {
461                 LOG_ALWAYS_FATAL("setParameter volume: bad param %d", param);
462             }
463         }
464         break;
465 
466     default:
467         LOG_ALWAYS_FATAL("setParameter: bad target %d", target);
468     }
469 }
470 
setResampler(uint32_t trackSampleRate,uint32_t devSampleRate)471 bool AudioMixerBase::TrackBase::setResampler(uint32_t trackSampleRate, uint32_t devSampleRate)
472 {
473     if (trackSampleRate != devSampleRate || mResampler.get() != nullptr) {
474         if (sampleRate != trackSampleRate) {
475             sampleRate = trackSampleRate;
476             if (mResampler.get() == nullptr) {
477                 ALOGV("Creating resampler from track %d Hz to device %d Hz",
478                         trackSampleRate, devSampleRate);
479                 AudioResampler::src_quality quality;
480                 // force lowest quality level resampler if use case isn't music or video
481                 // FIXME this is flawed for dynamic sample rates, as we choose the resampler
482                 // quality level based on the initial ratio, but that could change later.
483                 // Should have a way to distinguish tracks with static ratios vs. dynamic ratios.
484                 if (isMusicRate(trackSampleRate)) {
485                     quality = AudioResampler::DEFAULT_QUALITY;
486                 } else {
487                     quality = AudioResampler::DYN_LOW_QUALITY;
488                 }
489 
490                 // TODO: Remove MONO_HACK. Resampler sees #channels after the downmixer
491                 // but if none exists, it is the channel count (1 for mono).
492                 const int resamplerChannelCount = getOutputChannelCount();
493                 ALOGVV("Creating resampler:"
494                         " format(%#x) channels(%d) devSampleRate(%u) quality(%d)\n",
495                         mMixerInFormat, resamplerChannelCount, devSampleRate, quality);
496                 mResampler.reset(AudioResampler::create(
497                         mMixerInFormat,
498                         resamplerChannelCount,
499                         devSampleRate, quality));
500             }
501             return true;
502         }
503     }
504     return false;
505 }
506 
507 /* Checks to see if the volume ramp has completed and clears the increment
508  * variables appropriately.
509  *
510  * FIXME: There is code to handle int/float ramp variable switchover should it not
511  * complete within a mixer buffer processing call, but it is preferred to avoid switchover
512  * due to precision issues.  The switchover code is included for legacy code purposes
513  * and can be removed once the integer volume is removed.
514  *
515  * It is not sufficient to clear only the volumeInc integer variable because
516  * if one channel requires ramping, all channels are ramped.
517  *
518  * There is a bit of duplicated code here, but it keeps backward compatibility.
519  */
adjustVolumeRamp(bool aux,bool useFloat)520 void AudioMixerBase::TrackBase::adjustVolumeRamp(bool aux, bool useFloat)
521 {
522     if (useFloat) {
523         for (uint32_t i = 0; i < MAX_NUM_VOLUMES; i++) {
524             if ((mVolumeInc[i] > 0 && mPrevVolume[i] + mVolumeInc[i] >= mVolume[i]) ||
525                      (mVolumeInc[i] < 0 && mPrevVolume[i] + mVolumeInc[i] <= mVolume[i])) {
526                 volumeInc[i] = 0;
527                 prevVolume[i] = volume[i] << 16;
528                 mVolumeInc[i] = 0.;
529                 mPrevVolume[i] = mVolume[i];
530             } else {
531                 //ALOGV("ramp: %f %f %f", mVolume[i], mPrevVolume[i], mVolumeInc[i]);
532                 prevVolume[i] = u4_28_from_float(mPrevVolume[i]);
533             }
534         }
535     } else {
536         for (uint32_t i = 0; i < MAX_NUM_VOLUMES; i++) {
537             if (((volumeInc[i]>0) && (((prevVolume[i]+volumeInc[i])>>16) >= volume[i])) ||
538                     ((volumeInc[i]<0) && (((prevVolume[i]+volumeInc[i])>>16) <= volume[i]))) {
539                 volumeInc[i] = 0;
540                 prevVolume[i] = volume[i] << 16;
541                 mVolumeInc[i] = 0.;
542                 mPrevVolume[i] = mVolume[i];
543             } else {
544                 //ALOGV("ramp: %d %d %d", volume[i] << 16, prevVolume[i], volumeInc[i]);
545                 mPrevVolume[i]  = float_from_u4_28(prevVolume[i]);
546             }
547         }
548     }
549 
550     if (aux) {
551 #ifdef FLOAT_AUX
552         if (useFloat) {
553             if ((mAuxInc > 0.f && mPrevAuxLevel + mAuxInc >= mAuxLevel) ||
554                     (mAuxInc < 0.f && mPrevAuxLevel + mAuxInc <= mAuxLevel)) {
555                 auxInc = 0;
556                 prevAuxLevel = auxLevel << 16;
557                 mAuxInc = 0.f;
558                 mPrevAuxLevel = mAuxLevel;
559             }
560         } else
561 #endif
562         if ((auxInc > 0 && ((prevAuxLevel + auxInc) >> 16) >= auxLevel) ||
563                 (auxInc < 0 && ((prevAuxLevel + auxInc) >> 16) <= auxLevel)) {
564             auxInc = 0;
565             prevAuxLevel = auxLevel << 16;
566             mAuxInc = 0.f;
567             mPrevAuxLevel = mAuxLevel;
568         }
569     }
570 }
571 
recreateResampler(uint32_t devSampleRate)572 void AudioMixerBase::TrackBase::recreateResampler(uint32_t devSampleRate)
573 {
574     if (mResampler.get() != nullptr) {
575         const uint32_t resetToSampleRate = sampleRate;
576         mResampler.reset(nullptr);
577         sampleRate = devSampleRate; // without resampler, track rate is device sample rate.
578         // recreate the resampler with updated format, channels, saved sampleRate.
579         setResampler(resetToSampleRate /*trackSampleRate*/, devSampleRate);
580     }
581 }
582 
getUnreleasedFrames(int name) const583 size_t AudioMixerBase::getUnreleasedFrames(int name) const
584 {
585     const auto it = mTracks.find(name);
586     if (it != mTracks.end()) {
587         return it->second->getUnreleasedFrames();
588     }
589     return 0;
590 }
591 
trackNames() const592 std::string AudioMixerBase::trackNames() const
593 {
594     std::stringstream ss;
595     for (const auto &pair : mTracks) {
596         ss << pair.first << " ";
597     }
598     return ss.str();
599 }
600 
process__validate()601 void AudioMixerBase::process__validate()
602 {
603     // TODO: fix all16BitsStereNoResample logic to
604     // either properly handle muted tracks (it should ignore them)
605     // or remove altogether as an obsolete optimization.
606     bool all16BitsStereoNoResample = true;
607     bool resampling = false;
608     bool volumeRamp = false;
609 
610     mEnabled.clear();
611     mGroups.clear();
612     for (const auto &pair : mTracks) {
613         const int name = pair.first;
614         const std::shared_ptr<TrackBase> &t = pair.second;
615         if (!t->enabled) continue;
616 
617         mEnabled.emplace_back(name);  // we add to mEnabled in order of name.
618         mGroups[t->mainBuffer].emplace_back(name); // mGroups also in order of name.
619 
620         uint32_t n = 0;
621         // FIXME can overflow (mask is only 3 bits)
622         n |= NEEDS_CHANNEL_1 + t->channelCount - 1;
623         if (t->doesResample()) {
624             n |= NEEDS_RESAMPLE;
625         }
626         if (t->auxLevel != 0 && t->auxBuffer != NULL) {
627             n |= NEEDS_AUX;
628         }
629 
630         if (t->volumeInc[0]|t->volumeInc[1]) {
631             volumeRamp = true;
632         } else if (!t->doesResample() && t->volumeRL == 0) {
633             n |= NEEDS_MUTE;
634         }
635         t->needs = n;
636 
637         if (n & NEEDS_MUTE) {
638             t->hook = &TrackBase::track__nop;
639         } else {
640             if (n & NEEDS_AUX) {
641                 all16BitsStereoNoResample = false;
642             }
643             if (n & NEEDS_RESAMPLE) {
644                 all16BitsStereoNoResample = false;
645                 resampling = true;
646                 t->hook = TrackBase::getTrackHook(TRACKTYPE_RESAMPLE, t->mMixerChannelCount,
647                         t->mMixerInFormat, t->mMixerFormat);
648                 ALOGV_IF((n & NEEDS_CHANNEL_COUNT__MASK) > NEEDS_CHANNEL_2,
649                         "Track %d needs downmix + resample", name);
650             } else {
651                 if ((n & NEEDS_CHANNEL_COUNT__MASK) == NEEDS_CHANNEL_1){
652                     t->hook = TrackBase::getTrackHook(
653                             (t->mMixerChannelMask == AUDIO_CHANNEL_OUT_STEREO  // TODO: MONO_HACK
654                                     && t->channelMask == AUDIO_CHANNEL_OUT_MONO)
655                                 ? TRACKTYPE_NORESAMPLEMONO : TRACKTYPE_NORESAMPLE,
656                             t->mMixerChannelCount,
657                             t->mMixerInFormat, t->mMixerFormat);
658                     all16BitsStereoNoResample = false;
659                 }
660                 if ((n & NEEDS_CHANNEL_COUNT__MASK) >= NEEDS_CHANNEL_2){
661                     t->hook = TrackBase::getTrackHook(TRACKTYPE_NORESAMPLE, t->mMixerChannelCount,
662                             t->mMixerInFormat, t->mMixerFormat);
663                     ALOGV_IF((n & NEEDS_CHANNEL_COUNT__MASK) > NEEDS_CHANNEL_2,
664                             "Track %d needs downmix", name);
665                 }
666             }
667         }
668     }
669 
670     // select the processing hooks
671     mHook = &AudioMixerBase::process__nop;
672     if (mEnabled.size() > 0) {
673         if (resampling) {
674             if (mOutputTemp.get() == nullptr) {
675                 mOutputTemp.reset(new int32_t[MAX_NUM_CHANNELS * mFrameCount]);
676             }
677             if (mResampleTemp.get() == nullptr) {
678                 mResampleTemp.reset(new int32_t[MAX_NUM_CHANNELS * mFrameCount]);
679             }
680             mHook = &AudioMixerBase::process__genericResampling;
681         } else {
682             // we keep temp arrays around.
683             mHook = &AudioMixerBase::process__genericNoResampling;
684             if (all16BitsStereoNoResample && !volumeRamp) {
685                 if (mEnabled.size() == 1) {
686                     const std::shared_ptr<TrackBase> &t = mTracks[mEnabled[0]];
687                     if ((t->needs & NEEDS_MUTE) == 0) {
688                         // The check prevents a muted track from acquiring a process hook.
689                         //
690                         // This is dangerous if the track is MONO as that requires
691                         // special case handling due to implicit channel duplication.
692                         // Stereo or Multichannel should actually be fine here.
693                         mHook = getProcessHook(PROCESSTYPE_NORESAMPLEONETRACK,
694                                 t->mMixerChannelCount, t->mMixerInFormat, t->mMixerFormat);
695                     }
696                 }
697             }
698         }
699     }
700 
701     ALOGV("mixer configuration change: %zu "
702         "all16BitsStereoNoResample=%d, resampling=%d, volumeRamp=%d",
703         mEnabled.size(), all16BitsStereoNoResample, resampling, volumeRamp);
704 
705     process();
706 
707     // Now that the volume ramp has been done, set optimal state and
708     // track hooks for subsequent mixer process
709     if (mEnabled.size() > 0) {
710         bool allMuted = true;
711 
712         for (const int name : mEnabled) {
713             const std::shared_ptr<TrackBase> &t = mTracks[name];
714             if (!t->doesResample() && t->volumeRL == 0) {
715                 t->needs |= NEEDS_MUTE;
716                 t->hook = &TrackBase::track__nop;
717             } else {
718                 allMuted = false;
719             }
720         }
721         if (allMuted) {
722             mHook = &AudioMixerBase::process__nop;
723         } else if (all16BitsStereoNoResample) {
724             if (mEnabled.size() == 1) {
725                 //const int i = 31 - __builtin_clz(enabledTracks);
726                 const std::shared_ptr<TrackBase> &t = mTracks[mEnabled[0]];
727                 // Muted single tracks handled by allMuted above.
728                 mHook = getProcessHook(PROCESSTYPE_NORESAMPLEONETRACK,
729                         t->mMixerChannelCount, t->mMixerInFormat, t->mMixerFormat);
730             }
731         }
732     }
733 }
734 
track__genericResample(int32_t * out,size_t outFrameCount,int32_t * temp,int32_t * aux)735 void AudioMixerBase::TrackBase::track__genericResample(
736         int32_t* out, size_t outFrameCount, int32_t* temp, int32_t* aux)
737 {
738     ALOGVV("track__genericResample\n");
739     mResampler->setSampleRate(sampleRate);
740 
741     // ramp gain - resample to temp buffer and scale/mix in 2nd step
742     if (aux != NULL) {
743         // always resample with unity gain when sending to auxiliary buffer to be able
744         // to apply send level after resampling
745         mResampler->setVolume(UNITY_GAIN_FLOAT, UNITY_GAIN_FLOAT);
746         memset(temp, 0, outFrameCount * mMixerChannelCount * sizeof(int32_t));
747         mResampler->resample(temp, outFrameCount, bufferProvider);
748         if (CC_UNLIKELY(volumeInc[0]|volumeInc[1]|auxInc)) {
749             volumeRampStereo(out, outFrameCount, temp, aux);
750         } else {
751             volumeStereo(out, outFrameCount, temp, aux);
752         }
753     } else {
754         if (CC_UNLIKELY(volumeInc[0]|volumeInc[1])) {
755             mResampler->setVolume(UNITY_GAIN_FLOAT, UNITY_GAIN_FLOAT);
756             memset(temp, 0, outFrameCount * MAX_NUM_CHANNELS * sizeof(int32_t));
757             mResampler->resample(temp, outFrameCount, bufferProvider);
758             volumeRampStereo(out, outFrameCount, temp, aux);
759         }
760 
761         // constant gain
762         else {
763             mResampler->setVolume(mVolume[0], mVolume[1]);
764             mResampler->resample(out, outFrameCount, bufferProvider);
765         }
766     }
767 }
768 
track__nop(int32_t * out __unused,size_t outFrameCount __unused,int32_t * temp __unused,int32_t * aux __unused)769 void AudioMixerBase::TrackBase::track__nop(int32_t* out __unused,
770         size_t outFrameCount __unused, int32_t* temp __unused, int32_t* aux __unused)
771 {
772 }
773 
volumeRampStereo(int32_t * out,size_t frameCount,int32_t * temp,int32_t * aux)774 void AudioMixerBase::TrackBase::volumeRampStereo(
775         int32_t* out, size_t frameCount, int32_t* temp, int32_t* aux)
776 {
777     int32_t vl = prevVolume[0];
778     int32_t vr = prevVolume[1];
779     const int32_t vlInc = volumeInc[0];
780     const int32_t vrInc = volumeInc[1];
781 
782     //ALOGD("[0] %p: inc=%f, v0=%f, v1=%d, final=%f, count=%d",
783     //        t, vlInc/65536.0f, vl/65536.0f, volume[0],
784     //       (vl + vlInc*frameCount)/65536.0f, frameCount);
785 
786     // ramp volume
787     if (CC_UNLIKELY(aux != NULL)) {
788         int32_t va = prevAuxLevel;
789         const int32_t vaInc = auxInc;
790         int32_t l;
791         int32_t r;
792 
793         do {
794             l = (*temp++ >> 12);
795             r = (*temp++ >> 12);
796             *out++ += (vl >> 16) * l;
797             *out++ += (vr >> 16) * r;
798             *aux++ += (va >> 17) * (l + r);
799             vl += vlInc;
800             vr += vrInc;
801             va += vaInc;
802         } while (--frameCount);
803         prevAuxLevel = va;
804     } else {
805         do {
806             *out++ += (vl >> 16) * (*temp++ >> 12);
807             *out++ += (vr >> 16) * (*temp++ >> 12);
808             vl += vlInc;
809             vr += vrInc;
810         } while (--frameCount);
811     }
812     prevVolume[0] = vl;
813     prevVolume[1] = vr;
814     adjustVolumeRamp(aux != NULL);
815 }
816 
volumeStereo(int32_t * out,size_t frameCount,int32_t * temp,int32_t * aux)817 void AudioMixerBase::TrackBase::volumeStereo(
818         int32_t* out, size_t frameCount, int32_t* temp, int32_t* aux)
819 {
820     const int16_t vl = volume[0];
821     const int16_t vr = volume[1];
822 
823     if (CC_UNLIKELY(aux != NULL)) {
824         const int16_t va = auxLevel;
825         do {
826             int16_t l = (int16_t)(*temp++ >> 12);
827             int16_t r = (int16_t)(*temp++ >> 12);
828             out[0] = mulAdd(l, vl, out[0]);
829             int16_t a = (int16_t)(((int32_t)l + r) >> 1);
830             out[1] = mulAdd(r, vr, out[1]);
831             out += 2;
832             aux[0] = mulAdd(a, va, aux[0]);
833             aux++;
834         } while (--frameCount);
835     } else {
836         do {
837             int16_t l = (int16_t)(*temp++ >> 12);
838             int16_t r = (int16_t)(*temp++ >> 12);
839             out[0] = mulAdd(l, vl, out[0]);
840             out[1] = mulAdd(r, vr, out[1]);
841             out += 2;
842         } while (--frameCount);
843     }
844 }
845 
track__16BitsStereo(int32_t * out,size_t frameCount,int32_t * temp __unused,int32_t * aux)846 void AudioMixerBase::TrackBase::track__16BitsStereo(
847         int32_t* out, size_t frameCount, int32_t* temp __unused, int32_t* aux)
848 {
849     ALOGVV("track__16BitsStereo\n");
850     const int16_t *in = static_cast<const int16_t *>(mIn);
851 
852     if (CC_UNLIKELY(aux != NULL)) {
853         int32_t l;
854         int32_t r;
855         // ramp gain
856         if (CC_UNLIKELY(volumeInc[0]|volumeInc[1]|auxInc)) {
857             int32_t vl = prevVolume[0];
858             int32_t vr = prevVolume[1];
859             int32_t va = prevAuxLevel;
860             const int32_t vlInc = volumeInc[0];
861             const int32_t vrInc = volumeInc[1];
862             const int32_t vaInc = auxInc;
863             // ALOGD("[1] %p: inc=%f, v0=%f, v1=%d, final=%f, count=%d",
864             //        t, vlInc/65536.0f, vl/65536.0f, volume[0],
865             //        (vl + vlInc*frameCount)/65536.0f, frameCount);
866 
867             do {
868                 l = (int32_t)*in++;
869                 r = (int32_t)*in++;
870                 *out++ += (vl >> 16) * l;
871                 *out++ += (vr >> 16) * r;
872                 *aux++ += (va >> 17) * (l + r);
873                 vl += vlInc;
874                 vr += vrInc;
875                 va += vaInc;
876             } while (--frameCount);
877 
878             prevVolume[0] = vl;
879             prevVolume[1] = vr;
880             prevAuxLevel = va;
881             adjustVolumeRamp(true);
882         }
883 
884         // constant gain
885         else {
886             const uint32_t vrl = volumeRL;
887             const int16_t va = (int16_t)auxLevel;
888             do {
889                 uint32_t rl = *reinterpret_cast<const uint32_t *>(in);
890                 int16_t a = (int16_t)(((int32_t)in[0] + in[1]) >> 1);
891                 in += 2;
892                 out[0] = mulAddRL(1, rl, vrl, out[0]);
893                 out[1] = mulAddRL(0, rl, vrl, out[1]);
894                 out += 2;
895                 aux[0] = mulAdd(a, va, aux[0]);
896                 aux++;
897             } while (--frameCount);
898         }
899     } else {
900         // ramp gain
901         if (CC_UNLIKELY(volumeInc[0]|volumeInc[1])) {
902             int32_t vl = prevVolume[0];
903             int32_t vr = prevVolume[1];
904             const int32_t vlInc = volumeInc[0];
905             const int32_t vrInc = volumeInc[1];
906 
907             // ALOGD("[1] %p: inc=%f, v0=%f, v1=%d, final=%f, count=%d",
908             //        t, vlInc/65536.0f, vl/65536.0f, volume[0],
909             //        (vl + vlInc*frameCount)/65536.0f, frameCount);
910 
911             do {
912                 *out++ += (vl >> 16) * (int32_t) *in++;
913                 *out++ += (vr >> 16) * (int32_t) *in++;
914                 vl += vlInc;
915                 vr += vrInc;
916             } while (--frameCount);
917 
918             prevVolume[0] = vl;
919             prevVolume[1] = vr;
920             adjustVolumeRamp(false);
921         }
922 
923         // constant gain
924         else {
925             const uint32_t vrl = volumeRL;
926             do {
927                 uint32_t rl = *reinterpret_cast<const uint32_t *>(in);
928                 in += 2;
929                 out[0] = mulAddRL(1, rl, vrl, out[0]);
930                 out[1] = mulAddRL(0, rl, vrl, out[1]);
931                 out += 2;
932             } while (--frameCount);
933         }
934     }
935     mIn = in;
936 }
937 
track__16BitsMono(int32_t * out,size_t frameCount,int32_t * temp __unused,int32_t * aux)938 void AudioMixerBase::TrackBase::track__16BitsMono(
939         int32_t* out, size_t frameCount, int32_t* temp __unused, int32_t* aux)
940 {
941     ALOGVV("track__16BitsMono\n");
942     const int16_t *in = static_cast<int16_t const *>(mIn);
943 
944     if (CC_UNLIKELY(aux != NULL)) {
945         // ramp gain
946         if (CC_UNLIKELY(volumeInc[0]|volumeInc[1]|auxInc)) {
947             int32_t vl = prevVolume[0];
948             int32_t vr = prevVolume[1];
949             int32_t va = prevAuxLevel;
950             const int32_t vlInc = volumeInc[0];
951             const int32_t vrInc = volumeInc[1];
952             const int32_t vaInc = auxInc;
953 
954             // ALOGD("[2] %p: inc=%f, v0=%f, v1=%d, final=%f, count=%d",
955             //         t, vlInc/65536.0f, vl/65536.0f, volume[0],
956             //         (vl + vlInc*frameCount)/65536.0f, frameCount);
957 
958             do {
959                 int32_t l = *in++;
960                 *out++ += (vl >> 16) * l;
961                 *out++ += (vr >> 16) * l;
962                 *aux++ += (va >> 16) * l;
963                 vl += vlInc;
964                 vr += vrInc;
965                 va += vaInc;
966             } while (--frameCount);
967 
968             prevVolume[0] = vl;
969             prevVolume[1] = vr;
970             prevAuxLevel = va;
971             adjustVolumeRamp(true);
972         }
973         // constant gain
974         else {
975             const int16_t vl = volume[0];
976             const int16_t vr = volume[1];
977             const int16_t va = (int16_t)auxLevel;
978             do {
979                 int16_t l = *in++;
980                 out[0] = mulAdd(l, vl, out[0]);
981                 out[1] = mulAdd(l, vr, out[1]);
982                 out += 2;
983                 aux[0] = mulAdd(l, va, aux[0]);
984                 aux++;
985             } while (--frameCount);
986         }
987     } else {
988         // ramp gain
989         if (CC_UNLIKELY(volumeInc[0]|volumeInc[1])) {
990             int32_t vl = prevVolume[0];
991             int32_t vr = prevVolume[1];
992             const int32_t vlInc = volumeInc[0];
993             const int32_t vrInc = volumeInc[1];
994 
995             // ALOGD("[2] %p: inc=%f, v0=%f, v1=%d, final=%f, count=%d",
996             //         t, vlInc/65536.0f, vl/65536.0f, volume[0],
997             //         (vl + vlInc*frameCount)/65536.0f, frameCount);
998 
999             do {
1000                 int32_t l = *in++;
1001                 *out++ += (vl >> 16) * l;
1002                 *out++ += (vr >> 16) * l;
1003                 vl += vlInc;
1004                 vr += vrInc;
1005             } while (--frameCount);
1006 
1007             prevVolume[0] = vl;
1008             prevVolume[1] = vr;
1009             adjustVolumeRamp(false);
1010         }
1011         // constant gain
1012         else {
1013             const int16_t vl = volume[0];
1014             const int16_t vr = volume[1];
1015             do {
1016                 int16_t l = *in++;
1017                 out[0] = mulAdd(l, vl, out[0]);
1018                 out[1] = mulAdd(l, vr, out[1]);
1019                 out += 2;
1020             } while (--frameCount);
1021         }
1022     }
1023     mIn = in;
1024 }
1025 
1026 // no-op case
process__nop()1027 void AudioMixerBase::process__nop()
1028 {
1029     ALOGVV("process__nop\n");
1030 
1031     for (const auto &pair : mGroups) {
1032         // process by group of tracks with same output buffer to
1033         // avoid multiple memset() on same buffer
1034         const auto &group = pair.second;
1035 
1036         const std::shared_ptr<TrackBase> &t = mTracks[group[0]];
1037         memset(t->mainBuffer, 0,
1038                 mFrameCount * audio_bytes_per_frame(t->getMixerChannelCount(), t->mMixerFormat));
1039 
1040         // now consume data
1041         for (const int name : group) {
1042             const std::shared_ptr<TrackBase> &t = mTracks[name];
1043             size_t outFrames = mFrameCount;
1044             while (outFrames) {
1045                 t->buffer.frameCount = outFrames;
1046                 t->bufferProvider->getNextBuffer(&t->buffer);
1047                 if (t->buffer.raw == NULL) break;
1048                 outFrames -= t->buffer.frameCount;
1049                 t->bufferProvider->releaseBuffer(&t->buffer);
1050             }
1051         }
1052     }
1053 }
1054 
1055 // generic code without resampling
process__genericNoResampling()1056 void AudioMixerBase::process__genericNoResampling()
1057 {
1058     ALOGVV("process__genericNoResampling\n");
1059     int32_t outTemp[BLOCKSIZE * MAX_NUM_CHANNELS] __attribute__((aligned(32)));
1060 
1061     for (const auto &pair : mGroups) {
1062         // process by group of tracks with same output main buffer to
1063         // avoid multiple memset() on same buffer
1064         const auto &group = pair.second;
1065 
1066         // acquire buffer
1067         for (const int name : group) {
1068             const std::shared_ptr<TrackBase> &t = mTracks[name];
1069             t->buffer.frameCount = mFrameCount;
1070             t->bufferProvider->getNextBuffer(&t->buffer);
1071             t->frameCount = t->buffer.frameCount;
1072             t->mIn = t->buffer.raw;
1073         }
1074 
1075         int32_t *out = (int *)pair.first;
1076         size_t numFrames = 0;
1077         do {
1078             const size_t frameCount = std::min((size_t)BLOCKSIZE, mFrameCount - numFrames);
1079             memset(outTemp, 0, sizeof(outTemp));
1080             for (const int name : group) {
1081                 const std::shared_ptr<TrackBase> &t = mTracks[name];
1082                 int32_t *aux = NULL;
1083                 if (CC_UNLIKELY(t->needs & NEEDS_AUX)) {
1084                     aux = t->auxBuffer + numFrames;
1085                 }
1086                 for (int outFrames = frameCount; outFrames > 0; ) {
1087                     // t->in == nullptr can happen if the track was flushed just after having
1088                     // been enabled for mixing.
1089                     if (t->mIn == nullptr) {
1090                         break;
1091                     }
1092                     size_t inFrames = (t->frameCount > outFrames)?outFrames:t->frameCount;
1093                     if (inFrames > 0) {
1094                         (t.get()->*t->hook)(
1095                                 outTemp + (frameCount - outFrames) * t->mMixerChannelCount,
1096                                 inFrames, mResampleTemp.get() /* naked ptr */, aux);
1097                         t->frameCount -= inFrames;
1098                         outFrames -= inFrames;
1099                         if (CC_UNLIKELY(aux != NULL)) {
1100                             aux += inFrames;
1101                         }
1102                     }
1103                     if (t->frameCount == 0 && outFrames) {
1104                         t->bufferProvider->releaseBuffer(&t->buffer);
1105                         t->buffer.frameCount = (mFrameCount - numFrames) -
1106                                 (frameCount - outFrames);
1107                         t->bufferProvider->getNextBuffer(&t->buffer);
1108                         t->mIn = t->buffer.raw;
1109                         if (t->mIn == nullptr) {
1110                             break;
1111                         }
1112                         t->frameCount = t->buffer.frameCount;
1113                     }
1114                 }
1115             }
1116 
1117             const std::shared_ptr<TrackBase> &t1 = mTracks[group[0]];
1118             convertMixerFormat(out, t1->mMixerFormat, outTemp, t1->mMixerInFormat,
1119                     frameCount * t1->mMixerChannelCount);
1120             // TODO: fix ugly casting due to choice of out pointer type
1121             out = reinterpret_cast<int32_t*>((uint8_t*)out
1122                     + frameCount * t1->mMixerChannelCount
1123                     * audio_bytes_per_sample(t1->mMixerFormat));
1124             numFrames += frameCount;
1125         } while (numFrames < mFrameCount);
1126 
1127         // release each track's buffer
1128         for (const int name : group) {
1129             const std::shared_ptr<TrackBase> &t = mTracks[name];
1130             t->bufferProvider->releaseBuffer(&t->buffer);
1131         }
1132     }
1133 }
1134 
1135 // generic code with resampling
process__genericResampling()1136 void AudioMixerBase::process__genericResampling()
1137 {
1138     ALOGVV("process__genericResampling\n");
1139     int32_t * const outTemp = mOutputTemp.get(); // naked ptr
1140     size_t numFrames = mFrameCount;
1141 
1142     for (const auto &pair : mGroups) {
1143         const auto &group = pair.second;
1144         const std::shared_ptr<TrackBase> &t1 = mTracks[group[0]];
1145 
1146         // clear temp buffer
1147         memset(outTemp, 0, sizeof(*outTemp) * t1->mMixerChannelCount * mFrameCount);
1148         for (const int name : group) {
1149             const std::shared_ptr<TrackBase> &t = mTracks[name];
1150             int32_t *aux = NULL;
1151             if (CC_UNLIKELY(t->needs & NEEDS_AUX)) {
1152                 aux = t->auxBuffer;
1153             }
1154 
1155             // this is a little goofy, on the resampling case we don't
1156             // acquire/release the buffers because it's done by
1157             // the resampler.
1158             if (t->needs & NEEDS_RESAMPLE) {
1159                 (t.get()->*t->hook)(outTemp, numFrames, mResampleTemp.get() /* naked ptr */, aux);
1160             } else {
1161 
1162                 size_t outFrames = 0;
1163 
1164                 while (outFrames < numFrames) {
1165                     t->buffer.frameCount = numFrames - outFrames;
1166                     t->bufferProvider->getNextBuffer(&t->buffer);
1167                     t->mIn = t->buffer.raw;
1168                     // t->mIn == nullptr can happen if the track was flushed just after having
1169                     // been enabled for mixing.
1170                     if (t->mIn == nullptr) break;
1171 
1172                     (t.get()->*t->hook)(
1173                             outTemp + outFrames * t->mMixerChannelCount, t->buffer.frameCount,
1174                             mResampleTemp.get() /* naked ptr */,
1175                             aux != nullptr ? aux + outFrames : nullptr);
1176                     outFrames += t->buffer.frameCount;
1177 
1178                     t->bufferProvider->releaseBuffer(&t->buffer);
1179                 }
1180             }
1181         }
1182         convertMixerFormat(t1->mainBuffer, t1->mMixerFormat,
1183                 outTemp, t1->mMixerInFormat, numFrames * t1->mMixerChannelCount);
1184     }
1185 }
1186 
1187 // one track, 16 bits stereo without resampling is the most common case
process__oneTrack16BitsStereoNoResampling()1188 void AudioMixerBase::process__oneTrack16BitsStereoNoResampling()
1189 {
1190     ALOGVV("process__oneTrack16BitsStereoNoResampling\n");
1191     LOG_ALWAYS_FATAL_IF(mEnabled.size() != 0,
1192             "%zu != 1 tracks enabled", mEnabled.size());
1193     const int name = mEnabled[0];
1194     const std::shared_ptr<TrackBase> &t = mTracks[name];
1195 
1196     AudioBufferProvider::Buffer& b(t->buffer);
1197 
1198     int32_t* out = t->mainBuffer;
1199     float *fout = reinterpret_cast<float*>(out);
1200     size_t numFrames = mFrameCount;
1201 
1202     const int16_t vl = t->volume[0];
1203     const int16_t vr = t->volume[1];
1204     const uint32_t vrl = t->volumeRL;
1205     while (numFrames) {
1206         b.frameCount = numFrames;
1207         t->bufferProvider->getNextBuffer(&b);
1208         const int16_t *in = b.i16;
1209 
1210         // in == NULL can happen if the track was flushed just after having
1211         // been enabled for mixing.
1212         if (in == NULL || (((uintptr_t)in) & 3)) {
1213             if ( AUDIO_FORMAT_PCM_FLOAT == t->mMixerFormat ) {
1214                  memset((char*)fout, 0, numFrames
1215                          * t->mMixerChannelCount * audio_bytes_per_sample(t->mMixerFormat));
1216             } else {
1217                  memset((char*)out, 0, numFrames
1218                          * t->mMixerChannelCount * audio_bytes_per_sample(t->mMixerFormat));
1219             }
1220             ALOGE_IF((((uintptr_t)in) & 3),
1221                     "process__oneTrack16BitsStereoNoResampling: misaligned buffer"
1222                     " %p track %d, channels %d, needs %08x, volume %08x vfl %f vfr %f",
1223                     in, name, t->channelCount, t->needs, vrl, t->mVolume[0], t->mVolume[1]);
1224             return;
1225         }
1226         size_t outFrames = b.frameCount;
1227 
1228         switch (t->mMixerFormat) {
1229         case AUDIO_FORMAT_PCM_FLOAT:
1230             do {
1231                 uint32_t rl = *reinterpret_cast<const uint32_t *>(in);
1232                 in += 2;
1233                 int32_t l = mulRL(1, rl, vrl);
1234                 int32_t r = mulRL(0, rl, vrl);
1235                 *fout++ = float_from_q4_27(l);
1236                 *fout++ = float_from_q4_27(r);
1237                 // Note: In case of later int16_t sink output,
1238                 // conversion and clamping is done by memcpy_to_i16_from_float().
1239             } while (--outFrames);
1240             break;
1241         case AUDIO_FORMAT_PCM_16_BIT:
1242             if (CC_UNLIKELY(uint32_t(vl) > UNITY_GAIN_INT || uint32_t(vr) > UNITY_GAIN_INT)) {
1243                 // volume is boosted, so we might need to clamp even though
1244                 // we process only one track.
1245                 do {
1246                     uint32_t rl = *reinterpret_cast<const uint32_t *>(in);
1247                     in += 2;
1248                     int32_t l = mulRL(1, rl, vrl) >> 12;
1249                     int32_t r = mulRL(0, rl, vrl) >> 12;
1250                     // clamping...
1251                     l = clamp16(l);
1252                     r = clamp16(r);
1253                     *out++ = (r<<16) | (l & 0xFFFF);
1254                 } while (--outFrames);
1255             } else {
1256                 do {
1257                     uint32_t rl = *reinterpret_cast<const uint32_t *>(in);
1258                     in += 2;
1259                     int32_t l = mulRL(1, rl, vrl) >> 12;
1260                     int32_t r = mulRL(0, rl, vrl) >> 12;
1261                     *out++ = (r<<16) | (l & 0xFFFF);
1262                 } while (--outFrames);
1263             }
1264             break;
1265         default:
1266             LOG_ALWAYS_FATAL("bad mixer format: %d", t->mMixerFormat);
1267         }
1268         numFrames -= b.frameCount;
1269         t->bufferProvider->releaseBuffer(&b);
1270     }
1271 }
1272 
1273 /* TODO: consider whether this level of optimization is necessary.
1274  * Perhaps just stick with a single for loop.
1275  */
1276 
1277 // Needs to derive a compile time constant (constexpr).  Could be targeted to go
1278 // to a MONOVOL mixtype based on MAX_NUM_VOLUMES, but that's an unnecessary complication.
1279 #define MIXTYPE_MONOVOL(mixtype) ((mixtype) == MIXTYPE_MULTI ? MIXTYPE_MULTI_MONOVOL : \
1280         (mixtype) == MIXTYPE_MULTI_SAVEONLY ? MIXTYPE_MULTI_SAVEONLY_MONOVOL : (mixtype))
1281 
1282 /* MIXTYPE     (see AudioMixerOps.h MIXTYPE_* enumeration)
1283  * TO: int32_t (Q4.27) or float
1284  * TI: int32_t (Q4.27) or int16_t (Q0.15) or float
1285  * TA: int32_t (Q4.27) or float
1286  */
1287 template <int MIXTYPE,
1288         typename TO, typename TI, typename TV, typename TA, typename TAV>
volumeRampMulti(uint32_t channels,TO * out,size_t frameCount,const TI * in,TA * aux,TV * vol,const TV * volinc,TAV * vola,TAV volainc)1289 static void volumeRampMulti(uint32_t channels, TO* out, size_t frameCount,
1290         const TI* in, TA* aux, TV *vol, const TV *volinc, TAV *vola, TAV volainc)
1291 {
1292     switch (channels) {
1293     case 1:
1294         volumeRampMulti<MIXTYPE, 1>(out, frameCount, in, aux, vol, volinc, vola, volainc);
1295         break;
1296     case 2:
1297         volumeRampMulti<MIXTYPE, 2>(out, frameCount, in, aux, vol, volinc, vola, volainc);
1298         break;
1299     case 3:
1300         volumeRampMulti<MIXTYPE_MONOVOL(MIXTYPE), 3>(out,
1301                 frameCount, in, aux, vol, volinc, vola, volainc);
1302         break;
1303     case 4:
1304         volumeRampMulti<MIXTYPE_MONOVOL(MIXTYPE), 4>(out,
1305                 frameCount, in, aux, vol, volinc, vola, volainc);
1306         break;
1307     case 5:
1308         volumeRampMulti<MIXTYPE_MONOVOL(MIXTYPE), 5>(out,
1309                 frameCount, in, aux, vol, volinc, vola, volainc);
1310         break;
1311     case 6:
1312         volumeRampMulti<MIXTYPE_MONOVOL(MIXTYPE), 6>(out,
1313                 frameCount, in, aux, vol, volinc, vola, volainc);
1314         break;
1315     case 7:
1316         volumeRampMulti<MIXTYPE_MONOVOL(MIXTYPE), 7>(out,
1317                 frameCount, in, aux, vol, volinc, vola, volainc);
1318         break;
1319     case 8:
1320         volumeRampMulti<MIXTYPE_MONOVOL(MIXTYPE), 8>(out,
1321                 frameCount, in, aux, vol, volinc, vola, volainc);
1322         break;
1323     }
1324 }
1325 
1326 /* MIXTYPE     (see AudioMixerOps.h MIXTYPE_* enumeration)
1327  * TO: int32_t (Q4.27) or float
1328  * TI: int32_t (Q4.27) or int16_t (Q0.15) or float
1329  * TA: int32_t (Q4.27) or float
1330  */
1331 template <int MIXTYPE,
1332         typename TO, typename TI, typename TV, typename TA, typename TAV>
volumeMulti(uint32_t channels,TO * out,size_t frameCount,const TI * in,TA * aux,const TV * vol,TAV vola)1333 static void volumeMulti(uint32_t channels, TO* out, size_t frameCount,
1334         const TI* in, TA* aux, const TV *vol, TAV vola)
1335 {
1336     switch (channels) {
1337     case 1:
1338         volumeMulti<MIXTYPE, 1>(out, frameCount, in, aux, vol, vola);
1339         break;
1340     case 2:
1341         volumeMulti<MIXTYPE, 2>(out, frameCount, in, aux, vol, vola);
1342         break;
1343     case 3:
1344         volumeMulti<MIXTYPE_MONOVOL(MIXTYPE), 3>(out, frameCount, in, aux, vol, vola);
1345         break;
1346     case 4:
1347         volumeMulti<MIXTYPE_MONOVOL(MIXTYPE), 4>(out, frameCount, in, aux, vol, vola);
1348         break;
1349     case 5:
1350         volumeMulti<MIXTYPE_MONOVOL(MIXTYPE), 5>(out, frameCount, in, aux, vol, vola);
1351         break;
1352     case 6:
1353         volumeMulti<MIXTYPE_MONOVOL(MIXTYPE), 6>(out, frameCount, in, aux, vol, vola);
1354         break;
1355     case 7:
1356         volumeMulti<MIXTYPE_MONOVOL(MIXTYPE), 7>(out, frameCount, in, aux, vol, vola);
1357         break;
1358     case 8:
1359         volumeMulti<MIXTYPE_MONOVOL(MIXTYPE), 8>(out, frameCount, in, aux, vol, vola);
1360         break;
1361     }
1362 }
1363 
1364 /* MIXTYPE     (see AudioMixerOps.h MIXTYPE_* enumeration)
1365  * USEFLOATVOL (set to true if float volume is used)
1366  * ADJUSTVOL   (set to true if volume ramp parameters needs adjustment afterwards)
1367  * TO: int32_t (Q4.27) or float
1368  * TI: int32_t (Q4.27) or int16_t (Q0.15) or float
1369  * TA: int32_t (Q4.27) or float
1370  */
1371 template <int MIXTYPE, bool USEFLOATVOL, bool ADJUSTVOL,
1372     typename TO, typename TI, typename TA>
volumeMix(TO * out,size_t outFrames,const TI * in,TA * aux,bool ramp)1373 void AudioMixerBase::TrackBase::volumeMix(TO *out, size_t outFrames,
1374         const TI *in, TA *aux, bool ramp)
1375 {
1376     if (USEFLOATVOL) {
1377         if (ramp) {
1378             volumeRampMulti<MIXTYPE>(mMixerChannelCount, out, outFrames, in, aux,
1379                     mPrevVolume, mVolumeInc,
1380 #ifdef FLOAT_AUX
1381                     &mPrevAuxLevel, mAuxInc
1382 #else
1383                     &prevAuxLevel, auxInc
1384 #endif
1385                 );
1386             if (ADJUSTVOL) {
1387                 adjustVolumeRamp(aux != NULL, true);
1388             }
1389         } else {
1390             volumeMulti<MIXTYPE>(mMixerChannelCount, out, outFrames, in, aux,
1391                     mVolume,
1392 #ifdef FLOAT_AUX
1393                     mAuxLevel
1394 #else
1395                     auxLevel
1396 #endif
1397             );
1398         }
1399     } else {
1400         if (ramp) {
1401             volumeRampMulti<MIXTYPE>(mMixerChannelCount, out, outFrames, in, aux,
1402                     prevVolume, volumeInc, &prevAuxLevel, auxInc);
1403             if (ADJUSTVOL) {
1404                 adjustVolumeRamp(aux != NULL);
1405             }
1406         } else {
1407             volumeMulti<MIXTYPE>(mMixerChannelCount, out, outFrames, in, aux,
1408                     volume, auxLevel);
1409         }
1410     }
1411 }
1412 
1413 /* This process hook is called when there is a single track without
1414  * aux buffer, volume ramp, or resampling.
1415  * TODO: Update the hook selection: this can properly handle aux and ramp.
1416  *
1417  * MIXTYPE     (see AudioMixerOps.h MIXTYPE_* enumeration)
1418  * TO: int32_t (Q4.27) or float
1419  * TI: int32_t (Q4.27) or int16_t (Q0.15) or float
1420  * TA: int32_t (Q4.27)
1421  */
1422 template <int MIXTYPE, typename TO, typename TI, typename TA>
process__noResampleOneTrack()1423 void AudioMixerBase::process__noResampleOneTrack()
1424 {
1425     ALOGVV("process__noResampleOneTrack\n");
1426     LOG_ALWAYS_FATAL_IF(mEnabled.size() != 1,
1427             "%zu != 1 tracks enabled", mEnabled.size());
1428     const std::shared_ptr<TrackBase> &t = mTracks[mEnabled[0]];
1429     const uint32_t channels = t->mMixerChannelCount;
1430     TO* out = reinterpret_cast<TO*>(t->mainBuffer);
1431     TA* aux = reinterpret_cast<TA*>(t->auxBuffer);
1432     const bool ramp = t->needsRamp();
1433 
1434     for (size_t numFrames = mFrameCount; numFrames > 0; ) {
1435         AudioBufferProvider::Buffer& b(t->buffer);
1436         // get input buffer
1437         b.frameCount = numFrames;
1438         t->bufferProvider->getNextBuffer(&b);
1439         const TI *in = reinterpret_cast<TI*>(b.raw);
1440 
1441         // in == NULL can happen if the track was flushed just after having
1442         // been enabled for mixing.
1443         if (in == NULL || (((uintptr_t)in) & 3)) {
1444             memset(out, 0, numFrames
1445                     * channels * audio_bytes_per_sample(t->mMixerFormat));
1446             ALOGE_IF((((uintptr_t)in) & 3), "process__noResampleOneTrack: bus error: "
1447                     "buffer %p track %p, channels %d, needs %#x",
1448                     in, &t, t->channelCount, t->needs);
1449             return;
1450         }
1451 
1452         const size_t outFrames = b.frameCount;
1453         t->volumeMix<MIXTYPE, is_same<TI, float>::value /* USEFLOATVOL */, false /* ADJUSTVOL */> (
1454                 out, outFrames, in, aux, ramp);
1455 
1456         out += outFrames * channels;
1457         if (aux != NULL) {
1458             aux += outFrames;
1459         }
1460         numFrames -= b.frameCount;
1461 
1462         // release buffer
1463         t->bufferProvider->releaseBuffer(&b);
1464     }
1465     if (ramp) {
1466         t->adjustVolumeRamp(aux != NULL, is_same<TI, float>::value);
1467     }
1468 }
1469 
1470 /* This track hook is called to do resampling then mixing,
1471  * pulling from the track's upstream AudioBufferProvider.
1472  *
1473  * MIXTYPE     (see AudioMixerOps.h MIXTYPE_* enumeration)
1474  * TO: int32_t (Q4.27) or float
1475  * TI: int32_t (Q4.27) or int16_t (Q0.15) or float
1476  * TA: int32_t (Q4.27) or float
1477  */
1478 template <int MIXTYPE, typename TO, typename TI, typename TA>
track__Resample(TO * out,size_t outFrameCount,TO * temp,TA * aux)1479 void AudioMixerBase::TrackBase::track__Resample(TO* out, size_t outFrameCount, TO* temp, TA* aux)
1480 {
1481     ALOGVV("track__Resample\n");
1482     mResampler->setSampleRate(sampleRate);
1483     const bool ramp = needsRamp();
1484     if (ramp || aux != NULL) {
1485         // if ramp:        resample with unity gain to temp buffer and scale/mix in 2nd step.
1486         // if aux != NULL: resample with unity gain to temp buffer then apply send level.
1487 
1488         mResampler->setVolume(UNITY_GAIN_FLOAT, UNITY_GAIN_FLOAT);
1489         memset(temp, 0, outFrameCount * mMixerChannelCount * sizeof(TO));
1490         mResampler->resample((int32_t*)temp, outFrameCount, bufferProvider);
1491 
1492         volumeMix<MIXTYPE, is_same<TI, float>::value /* USEFLOATVOL */, true /* ADJUSTVOL */>(
1493                 out, outFrameCount, temp, aux, ramp);
1494 
1495     } else { // constant volume gain
1496         mResampler->setVolume(mVolume[0], mVolume[1]);
1497         mResampler->resample((int32_t*)out, outFrameCount, bufferProvider);
1498     }
1499 }
1500 
1501 /* This track hook is called to mix a track, when no resampling is required.
1502  * The input buffer should be present in in.
1503  *
1504  * MIXTYPE     (see AudioMixerOps.h MIXTYPE_* enumeration)
1505  * TO: int32_t (Q4.27) or float
1506  * TI: int32_t (Q4.27) or int16_t (Q0.15) or float
1507  * TA: int32_t (Q4.27) or float
1508  */
1509 template <int MIXTYPE, typename TO, typename TI, typename TA>
track__NoResample(TO * out,size_t frameCount,TO * temp __unused,TA * aux)1510 void AudioMixerBase::TrackBase::track__NoResample(
1511         TO* out, size_t frameCount, TO* temp __unused, TA* aux)
1512 {
1513     ALOGVV("track__NoResample\n");
1514     const TI *in = static_cast<const TI *>(mIn);
1515 
1516     volumeMix<MIXTYPE, is_same<TI, float>::value /* USEFLOATVOL */, true /* ADJUSTVOL */>(
1517             out, frameCount, in, aux, needsRamp());
1518 
1519     // MIXTYPE_MONOEXPAND reads a single input channel and expands to NCHAN output channels.
1520     // MIXTYPE_MULTI reads NCHAN input channels and places to NCHAN output channels.
1521     in += (MIXTYPE == MIXTYPE_MONOEXPAND) ? frameCount : frameCount * mMixerChannelCount;
1522     mIn = in;
1523 }
1524 
1525 /* The Mixer engine generates either int32_t (Q4_27) or float data.
1526  * We use this function to convert the engine buffers
1527  * to the desired mixer output format, either int16_t (Q.15) or float.
1528  */
1529 /* static */
convertMixerFormat(void * out,audio_format_t mixerOutFormat,void * in,audio_format_t mixerInFormat,size_t sampleCount)1530 void AudioMixerBase::convertMixerFormat(void *out, audio_format_t mixerOutFormat,
1531         void *in, audio_format_t mixerInFormat, size_t sampleCount)
1532 {
1533     switch (mixerInFormat) {
1534     case AUDIO_FORMAT_PCM_FLOAT:
1535         switch (mixerOutFormat) {
1536         case AUDIO_FORMAT_PCM_FLOAT:
1537             memcpy(out, in, sampleCount * sizeof(float)); // MEMCPY. TODO optimize out
1538             break;
1539         case AUDIO_FORMAT_PCM_16_BIT:
1540             memcpy_to_i16_from_float((int16_t*)out, (float*)in, sampleCount);
1541             break;
1542         default:
1543             LOG_ALWAYS_FATAL("bad mixerOutFormat: %#x", mixerOutFormat);
1544             break;
1545         }
1546         break;
1547     case AUDIO_FORMAT_PCM_16_BIT:
1548         switch (mixerOutFormat) {
1549         case AUDIO_FORMAT_PCM_FLOAT:
1550             memcpy_to_float_from_q4_27((float*)out, (const int32_t*)in, sampleCount);
1551             break;
1552         case AUDIO_FORMAT_PCM_16_BIT:
1553             memcpy_to_i16_from_q4_27((int16_t*)out, (const int32_t*)in, sampleCount);
1554             break;
1555         default:
1556             LOG_ALWAYS_FATAL("bad mixerOutFormat: %#x", mixerOutFormat);
1557             break;
1558         }
1559         break;
1560     default:
1561         LOG_ALWAYS_FATAL("bad mixerInFormat: %#x", mixerInFormat);
1562         break;
1563     }
1564 }
1565 
1566 /* Returns the proper track hook to use for mixing the track into the output buffer.
1567  */
1568 /* static */
getTrackHook(int trackType,uint32_t channelCount,audio_format_t mixerInFormat,audio_format_t mixerOutFormat __unused)1569 AudioMixerBase::hook_t AudioMixerBase::TrackBase::getTrackHook(int trackType, uint32_t channelCount,
1570         audio_format_t mixerInFormat, audio_format_t mixerOutFormat __unused)
1571 {
1572     if (!kUseNewMixer && channelCount == FCC_2 && mixerInFormat == AUDIO_FORMAT_PCM_16_BIT) {
1573         switch (trackType) {
1574         case TRACKTYPE_NOP:
1575             return &TrackBase::track__nop;
1576         case TRACKTYPE_RESAMPLE:
1577             return &TrackBase::track__genericResample;
1578         case TRACKTYPE_NORESAMPLEMONO:
1579             return &TrackBase::track__16BitsMono;
1580         case TRACKTYPE_NORESAMPLE:
1581             return &TrackBase::track__16BitsStereo;
1582         default:
1583             LOG_ALWAYS_FATAL("bad trackType: %d", trackType);
1584             break;
1585         }
1586     }
1587     LOG_ALWAYS_FATAL_IF(channelCount > MAX_NUM_CHANNELS);
1588     switch (trackType) {
1589     case TRACKTYPE_NOP:
1590         return &TrackBase::track__nop;
1591     case TRACKTYPE_RESAMPLE:
1592         switch (mixerInFormat) {
1593         case AUDIO_FORMAT_PCM_FLOAT:
1594             return (AudioMixerBase::hook_t) &TrackBase::track__Resample<
1595                     MIXTYPE_MULTI, float /*TO*/, float /*TI*/, TYPE_AUX>;
1596         case AUDIO_FORMAT_PCM_16_BIT:
1597             return (AudioMixerBase::hook_t) &TrackBase::track__Resample<
1598                     MIXTYPE_MULTI, int32_t /*TO*/, int16_t /*TI*/, TYPE_AUX>;
1599         default:
1600             LOG_ALWAYS_FATAL("bad mixerInFormat: %#x", mixerInFormat);
1601             break;
1602         }
1603         break;
1604     case TRACKTYPE_NORESAMPLEMONO:
1605         switch (mixerInFormat) {
1606         case AUDIO_FORMAT_PCM_FLOAT:
1607             return (AudioMixerBase::hook_t) &TrackBase::track__NoResample<
1608                             MIXTYPE_MONOEXPAND, float /*TO*/, float /*TI*/, TYPE_AUX>;
1609         case AUDIO_FORMAT_PCM_16_BIT:
1610             return (AudioMixerBase::hook_t) &TrackBase::track__NoResample<
1611                             MIXTYPE_MONOEXPAND, int32_t /*TO*/, int16_t /*TI*/, TYPE_AUX>;
1612         default:
1613             LOG_ALWAYS_FATAL("bad mixerInFormat: %#x", mixerInFormat);
1614             break;
1615         }
1616         break;
1617     case TRACKTYPE_NORESAMPLE:
1618         switch (mixerInFormat) {
1619         case AUDIO_FORMAT_PCM_FLOAT:
1620             return (AudioMixerBase::hook_t) &TrackBase::track__NoResample<
1621                     MIXTYPE_MULTI, float /*TO*/, float /*TI*/, TYPE_AUX>;
1622         case AUDIO_FORMAT_PCM_16_BIT:
1623             return (AudioMixerBase::hook_t) &TrackBase::track__NoResample<
1624                     MIXTYPE_MULTI, int32_t /*TO*/, int16_t /*TI*/, TYPE_AUX>;
1625         default:
1626             LOG_ALWAYS_FATAL("bad mixerInFormat: %#x", mixerInFormat);
1627             break;
1628         }
1629         break;
1630     default:
1631         LOG_ALWAYS_FATAL("bad trackType: %d", trackType);
1632         break;
1633     }
1634     return NULL;
1635 }
1636 
1637 /* Returns the proper process hook for mixing tracks. Currently works only for
1638  * PROCESSTYPE_NORESAMPLEONETRACK, a mix involving one track, no resampling.
1639  *
1640  * TODO: Due to the special mixing considerations of duplicating to
1641  * a stereo output track, the input track cannot be MONO.  This should be
1642  * prevented by the caller.
1643  */
1644 /* static */
getProcessHook(int processType,uint32_t channelCount,audio_format_t mixerInFormat,audio_format_t mixerOutFormat)1645 AudioMixerBase::process_hook_t AudioMixerBase::getProcessHook(
1646         int processType, uint32_t channelCount,
1647         audio_format_t mixerInFormat, audio_format_t mixerOutFormat)
1648 {
1649     if (processType != PROCESSTYPE_NORESAMPLEONETRACK) { // Only NORESAMPLEONETRACK
1650         LOG_ALWAYS_FATAL("bad processType: %d", processType);
1651         return NULL;
1652     }
1653     if (!kUseNewMixer && channelCount == FCC_2 && mixerInFormat == AUDIO_FORMAT_PCM_16_BIT) {
1654         return &AudioMixerBase::process__oneTrack16BitsStereoNoResampling;
1655     }
1656     LOG_ALWAYS_FATAL_IF(channelCount > MAX_NUM_CHANNELS);
1657     switch (mixerInFormat) {
1658     case AUDIO_FORMAT_PCM_FLOAT:
1659         switch (mixerOutFormat) {
1660         case AUDIO_FORMAT_PCM_FLOAT:
1661             return &AudioMixerBase::process__noResampleOneTrack<
1662                     MIXTYPE_MULTI_SAVEONLY, float /*TO*/, float /*TI*/, TYPE_AUX>;
1663         case AUDIO_FORMAT_PCM_16_BIT:
1664             return &AudioMixerBase::process__noResampleOneTrack<
1665                     MIXTYPE_MULTI_SAVEONLY, int16_t /*TO*/, float /*TI*/, TYPE_AUX>;
1666         default:
1667             LOG_ALWAYS_FATAL("bad mixerOutFormat: %#x", mixerOutFormat);
1668             break;
1669         }
1670         break;
1671     case AUDIO_FORMAT_PCM_16_BIT:
1672         switch (mixerOutFormat) {
1673         case AUDIO_FORMAT_PCM_FLOAT:
1674             return &AudioMixerBase::process__noResampleOneTrack<
1675                     MIXTYPE_MULTI_SAVEONLY, float /*TO*/, int16_t /*TI*/, TYPE_AUX>;
1676         case AUDIO_FORMAT_PCM_16_BIT:
1677             return &AudioMixerBase::process__noResampleOneTrack<
1678                     MIXTYPE_MULTI_SAVEONLY, int16_t /*TO*/, int16_t /*TI*/, TYPE_AUX>;
1679         default:
1680             LOG_ALWAYS_FATAL("bad mixerOutFormat: %#x", mixerOutFormat);
1681             break;
1682         }
1683         break;
1684     default:
1685         LOG_ALWAYS_FATAL("bad mixerInFormat: %#x", mixerInFormat);
1686         break;
1687     }
1688     return NULL;
1689 }
1690 
1691 // ----------------------------------------------------------------------------
1692 } // namespace android
1693