• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "BufferProvider"
18 //#define LOG_NDEBUG 0
19 
20 #include <algorithm>
21 
22 #include <audio_utils/primitives.h>
23 #include <audio_utils/format.h>
24 #include <audio_utils/channels.h>
25 #include <sonic.h>
26 #include <media/audiohal/EffectBufferHalInterface.h>
27 #include <media/audiohal/EffectHalInterface.h>
28 #include <media/audiohal/EffectsFactoryHalInterface.h>
29 #include <media/AudioResamplerPublic.h>
30 #include <media/BufferProviders.h>
31 #include <system/audio_effects/effect_downmix.h>
32 #include <utils/Log.h>
33 
34 #ifndef ARRAY_SIZE
35 #define ARRAY_SIZE(x) (sizeof(x)/sizeof((x)[0]))
36 #endif
37 
38 namespace android {
39 
40 // ----------------------------------------------------------------------------
CopyBufferProvider(size_t inputFrameSize,size_t outputFrameSize,size_t bufferFrameCount)41 CopyBufferProvider::CopyBufferProvider(size_t inputFrameSize,
42         size_t outputFrameSize, size_t bufferFrameCount) :
43         mInputFrameSize(inputFrameSize),
44         mOutputFrameSize(outputFrameSize),
45         mLocalBufferFrameCount(bufferFrameCount),
46         mLocalBufferData(NULL),
47         mConsumed(0)
48 {
49     ALOGV("CopyBufferProvider(%p)(%zu, %zu, %zu)", this,
50             inputFrameSize, outputFrameSize, bufferFrameCount);
51     LOG_ALWAYS_FATAL_IF(inputFrameSize < outputFrameSize && bufferFrameCount == 0,
52             "Requires local buffer if inputFrameSize(%zu) < outputFrameSize(%zu)",
53             inputFrameSize, outputFrameSize);
54     if (mLocalBufferFrameCount) {
55         (void)posix_memalign(&mLocalBufferData, 32, mLocalBufferFrameCount * mOutputFrameSize);
56     }
57     mBuffer.frameCount = 0;
58 }
59 
~CopyBufferProvider()60 CopyBufferProvider::~CopyBufferProvider()
61 {
62     ALOGV("%s(%p) %zu %p %p",
63            __func__, this, mBuffer.frameCount, mTrackBufferProvider, mLocalBufferData);
64     if (mBuffer.frameCount != 0) {
65         mTrackBufferProvider->releaseBuffer(&mBuffer);
66     }
67     free(mLocalBufferData);
68 }
69 
getNextBuffer(AudioBufferProvider::Buffer * pBuffer)70 status_t CopyBufferProvider::getNextBuffer(AudioBufferProvider::Buffer *pBuffer)
71 {
72     //ALOGV("CopyBufferProvider(%p)::getNextBuffer(%p (%zu))",
73     //        this, pBuffer, pBuffer->frameCount);
74     if (mLocalBufferFrameCount == 0) {
75         status_t res = mTrackBufferProvider->getNextBuffer(pBuffer);
76         if (res == OK) {
77             copyFrames(pBuffer->raw, pBuffer->raw, pBuffer->frameCount);
78         }
79         return res;
80     }
81     if (mBuffer.frameCount == 0) {
82         mBuffer.frameCount = pBuffer->frameCount;
83         status_t res = mTrackBufferProvider->getNextBuffer(&mBuffer);
84         // At one time an upstream buffer provider had
85         // res == OK and mBuffer.frameCount == 0, doesn't seem to happen now 7/18/2014.
86         //
87         // By API spec, if res != OK, then mBuffer.frameCount == 0.
88         // but there may be improper implementations.
89         ALOG_ASSERT(res == OK || mBuffer.frameCount == 0);
90         if (res != OK || mBuffer.frameCount == 0) { // not needed by API spec, but to be safe.
91             pBuffer->raw = NULL;
92             pBuffer->frameCount = 0;
93             return res;
94         }
95         mConsumed = 0;
96     }
97     ALOG_ASSERT(mConsumed < mBuffer.frameCount);
98     size_t count = std::min(mLocalBufferFrameCount, mBuffer.frameCount - mConsumed);
99     count = std::min(count, pBuffer->frameCount);
100     pBuffer->raw = mLocalBufferData;
101     pBuffer->frameCount = count;
102     copyFrames(pBuffer->raw, (uint8_t*)mBuffer.raw + mConsumed * mInputFrameSize,
103             pBuffer->frameCount);
104     return OK;
105 }
106 
releaseBuffer(AudioBufferProvider::Buffer * pBuffer)107 void CopyBufferProvider::releaseBuffer(AudioBufferProvider::Buffer *pBuffer)
108 {
109     //ALOGV("CopyBufferProvider(%p)::releaseBuffer(%p(%zu))",
110     //        this, pBuffer, pBuffer->frameCount);
111     if (mLocalBufferFrameCount == 0) {
112         mTrackBufferProvider->releaseBuffer(pBuffer);
113         return;
114     }
115     // LOG_ALWAYS_FATAL_IF(pBuffer->frameCount == 0, "Invalid framecount");
116     mConsumed += pBuffer->frameCount; // TODO: update for efficiency to reuse existing content
117     if (mConsumed != 0 && mConsumed >= mBuffer.frameCount) {
118         mTrackBufferProvider->releaseBuffer(&mBuffer);
119         ALOG_ASSERT(mBuffer.frameCount == 0);
120     }
121     pBuffer->raw = NULL;
122     pBuffer->frameCount = 0;
123 }
124 
reset()125 void CopyBufferProvider::reset()
126 {
127     if (mBuffer.frameCount != 0) {
128         mTrackBufferProvider->releaseBuffer(&mBuffer);
129     }
130     mConsumed = 0;
131 }
132 
setBufferProvider(AudioBufferProvider * p)133 void CopyBufferProvider::setBufferProvider(AudioBufferProvider *p) {
134     ALOGV("%s(%p): mTrackBufferProvider:%p  mBuffer.frameCount:%zu",
135             __func__, p, mTrackBufferProvider, mBuffer.frameCount);
136     if (mTrackBufferProvider == p) {
137         return;
138     }
139     mBuffer.frameCount = 0;
140     PassthruBufferProvider::setBufferProvider(p);
141 }
142 
DownmixerBufferProvider(audio_channel_mask_t inputChannelMask,audio_channel_mask_t outputChannelMask,audio_format_t format,uint32_t sampleRate,int32_t sessionId,size_t bufferFrameCount)143 DownmixerBufferProvider::DownmixerBufferProvider(
144         audio_channel_mask_t inputChannelMask,
145         audio_channel_mask_t outputChannelMask, audio_format_t format,
146         uint32_t sampleRate, int32_t sessionId, size_t bufferFrameCount) :
147         CopyBufferProvider(
148             audio_bytes_per_sample(format) * audio_channel_count_from_out_mask(inputChannelMask),
149             audio_bytes_per_sample(format) * audio_channel_count_from_out_mask(outputChannelMask),
150             bufferFrameCount)  // set bufferFrameCount to 0 to do in-place
151 {
152     ALOGV("DownmixerBufferProvider(%p)(%#x, %#x, %#x %u %d %d)",
153             this, inputChannelMask, outputChannelMask, format,
154             sampleRate, sessionId, (int)bufferFrameCount);
155     if (!sIsMultichannelCapable) {
156         ALOGE("DownmixerBufferProvider() error: not multichannel capable");
157         return;
158     }
159     mEffectsFactory = EffectsFactoryHalInterface::create();
160     if (mEffectsFactory == 0) {
161         ALOGE("DownmixerBufferProvider() error: could not obtain the effects factory");
162         return;
163     }
164     if (mEffectsFactory->createEffect(&sDwnmFxDesc.uuid,
165                                       sessionId,
166                                       SESSION_ID_INVALID_AND_IGNORED,
167                                       AUDIO_PORT_HANDLE_NONE,
168                                       &mDownmixInterface) != 0) {
169          ALOGE("DownmixerBufferProvider() error creating downmixer effect");
170          mDownmixInterface.clear();
171          mEffectsFactory.clear();
172          return;
173      }
174      // channel input configuration will be overridden per-track
175      mDownmixConfig.inputCfg.channels = inputChannelMask;   // FIXME: Should be bits
176      mDownmixConfig.outputCfg.channels = outputChannelMask; // FIXME: should be bits
177      mDownmixConfig.inputCfg.format = format;
178      mDownmixConfig.outputCfg.format = format;
179      mDownmixConfig.inputCfg.samplingRate = sampleRate;
180      mDownmixConfig.outputCfg.samplingRate = sampleRate;
181      mDownmixConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
182      mDownmixConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
183      // input and output buffer provider, and frame count will not be used as the downmix effect
184      // process() function is called directly (see DownmixerBufferProvider::getNextBuffer())
185      mDownmixConfig.inputCfg.mask = EFFECT_CONFIG_SMP_RATE | EFFECT_CONFIG_CHANNELS |
186              EFFECT_CONFIG_FORMAT | EFFECT_CONFIG_ACC_MODE;
187      mDownmixConfig.outputCfg.mask = mDownmixConfig.inputCfg.mask;
188 
189      mInFrameSize =
190              audio_bytes_per_sample(format) * audio_channel_count_from_out_mask(inputChannelMask);
191      mOutFrameSize =
192              audio_bytes_per_sample(format) * audio_channel_count_from_out_mask(outputChannelMask);
193      status_t status;
194      status = mEffectsFactory->mirrorBuffer(
195              nullptr, mInFrameSize * bufferFrameCount, &mInBuffer);
196      if (status != 0) {
197          ALOGE("DownmixerBufferProvider() error %d while creating input buffer", status);
198          mDownmixInterface.clear();
199          mEffectsFactory.clear();
200          return;
201      }
202      status = mEffectsFactory->mirrorBuffer(
203              nullptr, mOutFrameSize * bufferFrameCount, &mOutBuffer);
204      if (status != 0) {
205          ALOGE("DownmixerBufferProvider() error %d while creating output buffer", status);
206          mInBuffer.clear();
207          mDownmixInterface.clear();
208          mEffectsFactory.clear();
209          return;
210      }
211      mDownmixInterface->setInBuffer(mInBuffer);
212      mDownmixInterface->setOutBuffer(mOutBuffer);
213 
214      int cmdStatus;
215      uint32_t replySize = sizeof(int);
216 
217      // Configure downmixer
218      status = mDownmixInterface->command(
219              EFFECT_CMD_SET_CONFIG /*cmdCode*/, sizeof(effect_config_t) /*cmdSize*/,
220              &mDownmixConfig /*pCmdData*/,
221              &replySize, &cmdStatus /*pReplyData*/);
222      if (status != 0 || cmdStatus != 0) {
223          ALOGE("DownmixerBufferProvider() error %d cmdStatus %d while configuring downmixer",
224                  status, cmdStatus);
225          mOutBuffer.clear();
226          mInBuffer.clear();
227          mDownmixInterface.clear();
228          mEffectsFactory.clear();
229          return;
230      }
231 
232      // Enable downmixer
233      replySize = sizeof(int);
234      status = mDownmixInterface->command(
235              EFFECT_CMD_ENABLE /*cmdCode*/, 0 /*cmdSize*/, NULL /*pCmdData*/,
236              &replySize, &cmdStatus /*pReplyData*/);
237      if (status != 0 || cmdStatus != 0) {
238          ALOGE("DownmixerBufferProvider() error %d cmdStatus %d while enabling downmixer",
239                  status, cmdStatus);
240          mOutBuffer.clear();
241          mInBuffer.clear();
242          mDownmixInterface.clear();
243          mEffectsFactory.clear();
244          return;
245      }
246 
247      // Set downmix type
248      // parameter size rounded for padding on 32bit boundary
249      const int psizePadded = ((sizeof(downmix_params_t) - 1)/sizeof(int) + 1) * sizeof(int);
250      const int downmixParamSize =
251              sizeof(effect_param_t) + psizePadded + sizeof(downmix_type_t);
252      effect_param_t * const param = (effect_param_t *) malloc(downmixParamSize);
253      param->psize = sizeof(downmix_params_t);
254      const downmix_params_t downmixParam = DOWNMIX_PARAM_TYPE;
255      memcpy(param->data, &downmixParam, param->psize);
256      const downmix_type_t downmixType = DOWNMIX_TYPE_FOLD;
257      param->vsize = sizeof(downmix_type_t);
258      memcpy(param->data + psizePadded, &downmixType, param->vsize);
259      replySize = sizeof(int);
260      status = mDownmixInterface->command(
261              EFFECT_CMD_SET_PARAM /* cmdCode */, downmixParamSize /* cmdSize */,
262              param /*pCmdData*/, &replySize, &cmdStatus /*pReplyData*/);
263      free(param);
264      if (status != 0 || cmdStatus != 0) {
265          ALOGE("DownmixerBufferProvider() error %d cmdStatus %d while setting downmix type",
266                  status, cmdStatus);
267          mOutBuffer.clear();
268          mInBuffer.clear();
269          mDownmixInterface.clear();
270          mEffectsFactory.clear();
271          return;
272      }
273      ALOGV("DownmixerBufferProvider() downmix type set to %d", (int) downmixType);
274 }
275 
~DownmixerBufferProvider()276 DownmixerBufferProvider::~DownmixerBufferProvider()
277 {
278     ALOGV("~DownmixerBufferProvider (%p)", this);
279     if (mDownmixInterface != 0) {
280         mDownmixInterface->close();
281     }
282 }
283 
copyFrames(void * dst,const void * src,size_t frames)284 void DownmixerBufferProvider::copyFrames(void *dst, const void *src, size_t frames)
285 {
286     mInBuffer->setExternalData(const_cast<void*>(src));
287     mInBuffer->setFrameCount(frames);
288     mInBuffer->update(mInFrameSize * frames);
289     mOutBuffer->setFrameCount(frames);
290     mOutBuffer->setExternalData(dst);
291     if (dst != src) {
292         // Downmix may be accumulating, need to populate the output buffer
293         // with the dst data.
294         mOutBuffer->update(mOutFrameSize * frames);
295     }
296     // may be in-place if src == dst.
297     status_t res = mDownmixInterface->process();
298     if (res == OK) {
299         mOutBuffer->commit(mOutFrameSize * frames);
300     } else {
301         ALOGE("DownmixBufferProvider error %d", res);
302     }
303 }
304 
305 /* call once in a pthread_once handler. */
init()306 /*static*/ status_t DownmixerBufferProvider::init()
307 {
308     // find multichannel downmix effect if we have to play multichannel content
309     sp<EffectsFactoryHalInterface> effectsFactory = EffectsFactoryHalInterface::create();
310     if (effectsFactory == 0) {
311         ALOGE("AudioMixer() error: could not obtain the effects factory");
312         return NO_INIT;
313     }
314     uint32_t numEffects = 0;
315     int ret = effectsFactory->queryNumberEffects(&numEffects);
316     if (ret != 0) {
317         ALOGE("AudioMixer() error %d querying number of effects", ret);
318         return NO_INIT;
319     }
320     ALOGV("EffectQueryNumberEffects() numEffects=%d", numEffects);
321 
322     for (uint32_t i = 0 ; i < numEffects ; i++) {
323         if (effectsFactory->getDescriptor(i, &sDwnmFxDesc) == 0) {
324             ALOGV("effect %d is called %s", i, sDwnmFxDesc.name);
325             if (memcmp(&sDwnmFxDesc.type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
326                 ALOGI("found effect \"%s\" from %s",
327                         sDwnmFxDesc.name, sDwnmFxDesc.implementor);
328                 sIsMultichannelCapable = true;
329                 break;
330             }
331         }
332     }
333     ALOGW_IF(!sIsMultichannelCapable, "unable to find downmix effect");
334     return NO_INIT;
335 }
336 
337 /*static*/ bool DownmixerBufferProvider::sIsMultichannelCapable = false;
338 /*static*/ effect_descriptor_t DownmixerBufferProvider::sDwnmFxDesc;
339 
RemixBufferProvider(audio_channel_mask_t inputChannelMask,audio_channel_mask_t outputChannelMask,audio_format_t format,size_t bufferFrameCount)340 RemixBufferProvider::RemixBufferProvider(audio_channel_mask_t inputChannelMask,
341         audio_channel_mask_t outputChannelMask, audio_format_t format,
342         size_t bufferFrameCount) :
343         CopyBufferProvider(
344                 audio_bytes_per_sample(format)
345                     * audio_channel_count_from_out_mask(inputChannelMask),
346                 audio_bytes_per_sample(format)
347                     * audio_channel_count_from_out_mask(outputChannelMask),
348                 bufferFrameCount),
349         mFormat(format),
350         mSampleSize(audio_bytes_per_sample(format)),
351         mInputChannels(audio_channel_count_from_out_mask(inputChannelMask)),
352         mOutputChannels(audio_channel_count_from_out_mask(outputChannelMask))
353 {
354     ALOGV("RemixBufferProvider(%p)(%#x, %#x, %#x) %zu %zu",
355             this, format, inputChannelMask, outputChannelMask,
356             mInputChannels, mOutputChannels);
357     (void) memcpy_by_index_array_initialization_from_channel_mask(
358             mIdxAry, ARRAY_SIZE(mIdxAry), outputChannelMask, inputChannelMask);
359 }
360 
copyFrames(void * dst,const void * src,size_t frames)361 void RemixBufferProvider::copyFrames(void *dst, const void *src, size_t frames)
362 {
363     memcpy_by_index_array(dst, mOutputChannels,
364             src, mInputChannels, mIdxAry, mSampleSize, frames);
365 }
366 
ChannelMixBufferProvider(audio_channel_mask_t inputChannelMask,audio_channel_mask_t outputChannelMask,audio_format_t format,size_t bufferFrameCount)367 ChannelMixBufferProvider::ChannelMixBufferProvider(audio_channel_mask_t inputChannelMask,
368         audio_channel_mask_t outputChannelMask, audio_format_t format,
369         size_t bufferFrameCount) :
370         CopyBufferProvider(
371                 audio_bytes_per_sample(format)
372                     * audio_channel_count_from_out_mask(inputChannelMask),
373                 audio_bytes_per_sample(format)
374                     * audio_channel_count_from_out_mask(outputChannelMask),
375                 bufferFrameCount)
376 {
377     ALOGV("ChannelMixBufferProvider(%p)(%#x, %#x, %#x)",
378             this, format, inputChannelMask, outputChannelMask);
379     if (outputChannelMask == AUDIO_CHANNEL_OUT_STEREO && format == AUDIO_FORMAT_PCM_FLOAT) {
380         mIsValid = mChannelMix.setInputChannelMask(inputChannelMask);
381     }
382 }
383 
copyFrames(void * dst,const void * src,size_t frames)384 void ChannelMixBufferProvider::copyFrames(void *dst, const void *src, size_t frames)
385 {
386     mChannelMix.process(static_cast<const float *>(src), static_cast<float *>(dst),
387             frames, false /* accumulate */);
388 }
389 
ReformatBufferProvider(int32_t channelCount,audio_format_t inputFormat,audio_format_t outputFormat,size_t bufferFrameCount)390 ReformatBufferProvider::ReformatBufferProvider(int32_t channelCount,
391         audio_format_t inputFormat, audio_format_t outputFormat,
392         size_t bufferFrameCount) :
393         CopyBufferProvider(
394                 channelCount * audio_bytes_per_sample(inputFormat),
395                 channelCount * audio_bytes_per_sample(outputFormat),
396                 bufferFrameCount),
397         mChannelCount(channelCount),
398         mInputFormat(inputFormat),
399         mOutputFormat(outputFormat)
400 {
401     ALOGV("ReformatBufferProvider(%p)(%u, %#x, %#x)",
402             this, channelCount, inputFormat, outputFormat);
403 }
404 
copyFrames(void * dst,const void * src,size_t frames)405 void ReformatBufferProvider::copyFrames(void *dst, const void *src, size_t frames)
406 {
407     memcpy_by_audio_format(dst, mOutputFormat, src, mInputFormat, frames * mChannelCount);
408 }
409 
ClampFloatBufferProvider(int32_t channelCount,size_t bufferFrameCount)410 ClampFloatBufferProvider::ClampFloatBufferProvider(int32_t channelCount, size_t bufferFrameCount) :
411         CopyBufferProvider(
412                 channelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT),
413                 channelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT),
414                 bufferFrameCount),
415         mChannelCount(channelCount)
416 {
417     ALOGV("ClampFloatBufferProvider(%p)(%u)", this, channelCount);
418 }
419 
copyFrames(void * dst,const void * src,size_t frames)420 void ClampFloatBufferProvider::copyFrames(void *dst, const void *src, size_t frames)
421 {
422     memcpy_to_float_from_float_with_clamping((float*)dst, (const float*)src,
423                                              frames * mChannelCount,
424                                              FLOAT_NOMINAL_RANGE_HEADROOM);
425 }
426 
TimestretchBufferProvider(int32_t channelCount,audio_format_t format,uint32_t sampleRate,const AudioPlaybackRate & playbackRate)427 TimestretchBufferProvider::TimestretchBufferProvider(int32_t channelCount,
428         audio_format_t format, uint32_t sampleRate, const AudioPlaybackRate &playbackRate) :
429         mChannelCount(channelCount),
430         mFormat(format),
431         mSampleRate(sampleRate),
432         mFrameSize(channelCount * audio_bytes_per_sample(format)),
433         mLocalBufferFrameCount(0),
434         mLocalBufferData(NULL),
435         mRemaining(0),
436         mSonicStream(sonicCreateStream(sampleRate, mChannelCount)),
437         mFallbackFailErrorShown(false),
438         mAudioPlaybackRateValid(false)
439 {
440     LOG_ALWAYS_FATAL_IF(mSonicStream == NULL,
441             "TimestretchBufferProvider can't allocate Sonic stream");
442 
443     setPlaybackRate(playbackRate);
444     ALOGV("TimestretchBufferProvider(%p)(%u, %#x, %u %f %f %d %d)",
445             this, channelCount, format, sampleRate, playbackRate.mSpeed,
446             playbackRate.mPitch, playbackRate.mStretchMode, playbackRate.mFallbackMode);
447     mBuffer.frameCount = 0;
448 }
449 
~TimestretchBufferProvider()450 TimestretchBufferProvider::~TimestretchBufferProvider()
451 {
452     ALOGV("~TimestretchBufferProvider(%p)", this);
453     sonicDestroyStream(mSonicStream);
454     if (mBuffer.frameCount != 0) {
455         mTrackBufferProvider->releaseBuffer(&mBuffer);
456     }
457     free(mLocalBufferData);
458 }
459 
getNextBuffer(AudioBufferProvider::Buffer * pBuffer)460 status_t TimestretchBufferProvider::getNextBuffer(
461         AudioBufferProvider::Buffer *pBuffer)
462 {
463     ALOGV("TimestretchBufferProvider(%p)::getNextBuffer(%p (%zu))",
464             this, pBuffer, pBuffer->frameCount);
465 
466     // BYPASS
467     //return mTrackBufferProvider->getNextBuffer(pBuffer);
468 
469     // check if previously processed data is sufficient.
470     if (pBuffer->frameCount <= mRemaining) {
471         ALOGV("previous sufficient");
472         pBuffer->raw = mLocalBufferData;
473         return OK;
474     }
475 
476     // do we need to resize our buffer?
477     if (pBuffer->frameCount > mLocalBufferFrameCount) {
478         void *newmem;
479         if (posix_memalign(&newmem, 32, pBuffer->frameCount * mFrameSize) == OK) {
480             if (mRemaining != 0) {
481                 memcpy(newmem, mLocalBufferData, mRemaining * mFrameSize);
482             }
483             free(mLocalBufferData);
484             mLocalBufferData = newmem;
485             mLocalBufferFrameCount = pBuffer->frameCount;
486         }
487     }
488 
489     // need to fetch more data
490     const size_t outputDesired = pBuffer->frameCount - mRemaining;
491     size_t dstAvailable;
492     do {
493         mBuffer.frameCount = mPlaybackRate.mSpeed == AUDIO_TIMESTRETCH_SPEED_NORMAL
494                 ? outputDesired : outputDesired * mPlaybackRate.mSpeed + 1;
495 
496         status_t res = mTrackBufferProvider->getNextBuffer(&mBuffer);
497 
498         ALOG_ASSERT(res == OK || mBuffer.frameCount == 0);
499         if (res != OK || mBuffer.frameCount == 0) { // not needed by API spec, but to be safe.
500             ALOGV("upstream provider cannot provide data");
501             if (mRemaining == 0) {
502                 pBuffer->raw = NULL;
503                 pBuffer->frameCount = 0;
504                 return res;
505             } else { // return partial count
506                 pBuffer->raw = mLocalBufferData;
507                 pBuffer->frameCount = mRemaining;
508                 return OK;
509             }
510         }
511 
512         // time-stretch the data
513         dstAvailable = std::min(mLocalBufferFrameCount - mRemaining, outputDesired);
514         size_t srcAvailable = mBuffer.frameCount;
515         processFrames((uint8_t*)mLocalBufferData + mRemaining * mFrameSize, &dstAvailable,
516                 mBuffer.raw, &srcAvailable);
517 
518         // release all data consumed
519         mBuffer.frameCount = srcAvailable;
520         mTrackBufferProvider->releaseBuffer(&mBuffer);
521     } while (dstAvailable == 0); // try until we get output data or upstream provider fails.
522 
523     // update buffer vars with the actual data processed and return with buffer
524     mRemaining += dstAvailable;
525 
526     pBuffer->raw = mLocalBufferData;
527     pBuffer->frameCount = mRemaining;
528 
529     return OK;
530 }
531 
releaseBuffer(AudioBufferProvider::Buffer * pBuffer)532 void TimestretchBufferProvider::releaseBuffer(AudioBufferProvider::Buffer *pBuffer)
533 {
534     ALOGV("TimestretchBufferProvider(%p)::releaseBuffer(%p (%zu))",
535        this, pBuffer, pBuffer->frameCount);
536 
537     // BYPASS
538     //return mTrackBufferProvider->releaseBuffer(pBuffer);
539 
540     // LOG_ALWAYS_FATAL_IF(pBuffer->frameCount == 0, "Invalid framecount");
541     if (pBuffer->frameCount < mRemaining) {
542         memcpy(mLocalBufferData,
543                 (uint8_t*)mLocalBufferData + pBuffer->frameCount * mFrameSize,
544                 (mRemaining - pBuffer->frameCount) * mFrameSize);
545         mRemaining -= pBuffer->frameCount;
546     } else if (pBuffer->frameCount == mRemaining) {
547         mRemaining = 0;
548     } else {
549         LOG_ALWAYS_FATAL("Releasing more frames(%zu) than available(%zu)",
550                 pBuffer->frameCount, mRemaining);
551     }
552 
553     pBuffer->raw = NULL;
554     pBuffer->frameCount = 0;
555 }
556 
reset()557 void TimestretchBufferProvider::reset()
558 {
559     mRemaining = 0;
560 }
561 
setBufferProvider(AudioBufferProvider * p)562 void TimestretchBufferProvider::setBufferProvider(AudioBufferProvider *p) {
563     ALOGV("%s(%p): mTrackBufferProvider:%p  mBuffer.frameCount:%zu",
564             __func__, p, mTrackBufferProvider, mBuffer.frameCount);
565     if (mTrackBufferProvider == p) {
566         return;
567     }
568     mBuffer.frameCount = 0;
569     PassthruBufferProvider::setBufferProvider(p);
570 }
571 
setPlaybackRate(const AudioPlaybackRate & playbackRate)572 status_t TimestretchBufferProvider::setPlaybackRate(const AudioPlaybackRate &playbackRate)
573 {
574     mPlaybackRate = playbackRate;
575     mFallbackFailErrorShown = false;
576     sonicSetSpeed(mSonicStream, mPlaybackRate.mSpeed);
577     //TODO: pitch is ignored for now
578     //TODO: optimize: if parameters are the same, don't do any extra computation.
579 
580     mAudioPlaybackRateValid = isAudioPlaybackRateValid(mPlaybackRate);
581     return OK;
582 }
583 
processFrames(void * dstBuffer,size_t * dstFrames,const void * srcBuffer,size_t * srcFrames)584 void TimestretchBufferProvider::processFrames(void *dstBuffer, size_t *dstFrames,
585         const void *srcBuffer, size_t *srcFrames)
586 {
587     ALOGV("processFrames(%zu %zu)  remaining(%zu)", *dstFrames, *srcFrames, mRemaining);
588     // Note dstFrames is the required number of frames.
589 
590     if (!mAudioPlaybackRateValid) {
591         //fallback mode
592         // Ensure consumption from src is as expected.
593         // TODO: add logic to track "very accurate" consumption related to speed, original sampling
594         // rate, actual frames processed.
595 
596         const size_t targetSrc = *dstFrames * mPlaybackRate.mSpeed;
597         if (*srcFrames < targetSrc) { // limit dst frames to that possible
598             *dstFrames = *srcFrames / mPlaybackRate.mSpeed;
599         } else if (*srcFrames > targetSrc + 1) {
600             *srcFrames = targetSrc + 1;
601         }
602         if (*dstFrames > 0) {
603             switch(mPlaybackRate.mFallbackMode) {
604             case AUDIO_TIMESTRETCH_FALLBACK_CUT_REPEAT:
605                 if (*dstFrames <= *srcFrames) {
606                       size_t copySize = mFrameSize * *dstFrames;
607                       memcpy(dstBuffer, srcBuffer, copySize);
608                   } else {
609                       // cyclically repeat the source.
610                       for (size_t count = 0; count < *dstFrames; count += *srcFrames) {
611                           size_t remaining = std::min(*srcFrames, *dstFrames - count);
612                           memcpy((uint8_t*)dstBuffer + mFrameSize * count,
613                                   srcBuffer, mFrameSize * remaining);
614                       }
615                   }
616                 break;
617             case AUDIO_TIMESTRETCH_FALLBACK_DEFAULT:
618             case AUDIO_TIMESTRETCH_FALLBACK_MUTE:
619                 memset(dstBuffer,0, mFrameSize * *dstFrames);
620                 break;
621             case AUDIO_TIMESTRETCH_FALLBACK_FAIL:
622             default:
623                 if(!mFallbackFailErrorShown) {
624                     ALOGE("invalid parameters in TimestretchBufferProvider fallbackMode:%d",
625                             mPlaybackRate.mFallbackMode);
626                     mFallbackFailErrorShown = true;
627                 }
628                 break;
629             }
630         }
631     } else {
632         switch (mFormat) {
633         case AUDIO_FORMAT_PCM_FLOAT:
634             if (sonicWriteFloatToStream(mSonicStream, (float*)srcBuffer, *srcFrames) != 1) {
635                 ALOGE("sonicWriteFloatToStream cannot realloc");
636                 *srcFrames = 0; // cannot consume all of srcBuffer
637             }
638             *dstFrames = sonicReadFloatFromStream(mSonicStream, (float*)dstBuffer, *dstFrames);
639             break;
640         case AUDIO_FORMAT_PCM_16_BIT:
641             if (sonicWriteShortToStream(mSonicStream, (short*)srcBuffer, *srcFrames) != 1) {
642                 ALOGE("sonicWriteShortToStream cannot realloc");
643                 *srcFrames = 0; // cannot consume all of srcBuffer
644             }
645             *dstFrames = sonicReadShortFromStream(mSonicStream, (short*)dstBuffer, *dstFrames);
646             break;
647         default:
648             // could also be caught on construction
649             LOG_ALWAYS_FATAL("invalid format %#x for TimestretchBufferProvider", mFormat);
650         }
651     }
652 }
653 
AdjustChannelsBufferProvider(audio_format_t format,size_t inChannelCount,size_t outChannelCount,size_t frameCount,audio_format_t contractedFormat,void * contractedBuffer,size_t contractedOutChannelCount)654 AdjustChannelsBufferProvider::AdjustChannelsBufferProvider(
655         audio_format_t format, size_t inChannelCount, size_t outChannelCount,
656         size_t frameCount, audio_format_t contractedFormat, void* contractedBuffer,
657         size_t contractedOutChannelCount) :
658         CopyBufferProvider(
659                 audio_bytes_per_frame(inChannelCount, format),
660                 audio_bytes_per_frame(std::max(inChannelCount, outChannelCount), format),
661                 frameCount),
662         mFormat(format),
663         mInChannelCount(inChannelCount),
664         mOutChannelCount(outChannelCount),
665         mSampleSizeInBytes(audio_bytes_per_sample(format)),
666         mFrameCount(frameCount),
667         mContractedFormat(inChannelCount > outChannelCount
668                 ? contractedFormat : AUDIO_FORMAT_INVALID),
669         mContractedInChannelCount(inChannelCount > outChannelCount
670                 ? inChannelCount - outChannelCount : 0),
671         mContractedOutChannelCount(contractedOutChannelCount),
672         mContractedSampleSizeInBytes(audio_bytes_per_sample(contractedFormat)),
673         mContractedInputFrameSize(mContractedInChannelCount * mContractedSampleSizeInBytes),
674         mContractedBuffer(contractedBuffer),
675         mContractedWrittenFrames(0)
676 {
677     ALOGV("AdjustChannelsBufferProvider(%p)(%#x, %zu, %zu, %zu, %#x, %p, %zu)",
678           this, format, inChannelCount, outChannelCount, frameCount, contractedFormat,
679           contractedBuffer, contractedOutChannelCount);
680     if (mContractedFormat != AUDIO_FORMAT_INVALID && mInChannelCount > mOutChannelCount) {
681         mContractedOutputFrameSize =
682                 audio_bytes_per_frame(mContractedOutChannelCount, mContractedFormat);
683     }
684 }
685 
getNextBuffer(AudioBufferProvider::Buffer * pBuffer)686 status_t AdjustChannelsBufferProvider::getNextBuffer(AudioBufferProvider::Buffer* pBuffer)
687 {
688     if (mContractedBuffer != nullptr) {
689         // Restrict frame count only when it is needed to save contracted frames.
690         const size_t outFramesLeft = mFrameCount - mContractedWrittenFrames;
691         if (outFramesLeft < pBuffer->frameCount) {
692             // Restrict the frame count so that we don't write over the size of the output buffer.
693             pBuffer->frameCount = outFramesLeft;
694         }
695     }
696     return CopyBufferProvider::getNextBuffer(pBuffer);
697 }
698 
copyFrames(void * dst,const void * src,size_t frames)699 void AdjustChannelsBufferProvider::copyFrames(void *dst, const void *src, size_t frames)
700 {
701     // For case multi to mono, adjust_channels has special logic that will mix first two input
702     // channels into a single output channel. In that case, use adjust_channels_non_destructive
703     // to keep only one channel data even when contracting to mono.
704     adjust_channels_non_destructive(src, mInChannelCount, dst, mOutChannelCount,
705             mSampleSizeInBytes, frames * mInChannelCount * mSampleSizeInBytes);
706     if (mContractedFormat != AUDIO_FORMAT_INVALID
707         && mContractedBuffer != nullptr) {
708         const size_t contractedIdx = frames * mOutChannelCount * mSampleSizeInBytes;
709         uint8_t* oriBuf = (uint8_t*) dst + contractedIdx;
710         uint8_t* buf = (uint8_t*) mContractedBuffer
711                 + mContractedWrittenFrames * mContractedOutputFrameSize;
712         if (mContractedInChannelCount > mContractedOutChannelCount) {
713             // Adjust the channels first as the contracted buffer may not have enough
714             // space for the data.
715             // Use adjust_channels_non_destructive to avoid mix first two channels into one single
716             // output channel when it is multi to mono.
717             adjust_channels_non_destructive(
718                     oriBuf, mContractedInChannelCount, oriBuf, mContractedOutChannelCount,
719                     mSampleSizeInBytes, frames * mContractedInChannelCount * mSampleSizeInBytes);
720             memcpy_by_audio_format(
721                     buf, mContractedFormat, oriBuf, mFormat, mContractedOutChannelCount * frames);
722         } else {
723             // Copy the data first as the dst buffer may not have enough space for extra channel.
724             memcpy_by_audio_format(
725                 buf, mContractedFormat, oriBuf, mFormat, mContractedInChannelCount * frames);
726             // Note that if the contracted data is from MONO to MULTICHANNEL, the first 2 channels
727             // will be duplicated with the original single input channel and all the other channels
728             // will be 0-filled.
729             adjust_channels(
730                     buf, mContractedInChannelCount, buf, mContractedOutChannelCount,
731                     mContractedSampleSizeInBytes, mContractedInputFrameSize * frames);
732         }
733         mContractedWrittenFrames += frames;
734     }
735 }
736 
reset()737 void AdjustChannelsBufferProvider::reset()
738 {
739     mContractedWrittenFrames = 0;
740     CopyBufferProvider::reset();
741 }
742 // ----------------------------------------------------------------------------
743 } // namespace android
744