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 , mChannelMix{format == AUDIO_FORMAT_PCM_FLOAT
377 ? audio_utils::channels::IChannelMix::create(outputChannelMask) : nullptr}
378 , mIsValid{mChannelMix && mChannelMix->setInputChannelMask(inputChannelMask)}
379 {
380 ALOGV("ChannelMixBufferProvider(%p)(%#x, %#x, %#x)",
381 this, format, inputChannelMask, outputChannelMask);
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 if (mIsValid) {
387 mChannelMix->process(static_cast<const float *>(src), static_cast<float *>(dst),
388 frames, false /* accumulate */);
389 } else {
390 // Should fall back to a different BufferProvider if not valid.
391 ALOGE("%s: Use without being valid!", __func__);
392 }
393 }
394
ReformatBufferProvider(int32_t channelCount,audio_format_t inputFormat,audio_format_t outputFormat,size_t bufferFrameCount)395 ReformatBufferProvider::ReformatBufferProvider(int32_t channelCount,
396 audio_format_t inputFormat, audio_format_t outputFormat,
397 size_t bufferFrameCount) :
398 CopyBufferProvider(
399 channelCount * audio_bytes_per_sample(inputFormat),
400 channelCount * audio_bytes_per_sample(outputFormat),
401 bufferFrameCount),
402 mChannelCount(channelCount),
403 mInputFormat(inputFormat),
404 mOutputFormat(outputFormat)
405 {
406 ALOGV("ReformatBufferProvider(%p)(%u, %#x, %#x)",
407 this, channelCount, inputFormat, outputFormat);
408 }
409
copyFrames(void * dst,const void * src,size_t frames)410 void ReformatBufferProvider::copyFrames(void *dst, const void *src, size_t frames)
411 {
412 memcpy_by_audio_format(dst, mOutputFormat, src, mInputFormat, frames * mChannelCount);
413 }
414
ClampFloatBufferProvider(int32_t channelCount,size_t bufferFrameCount)415 ClampFloatBufferProvider::ClampFloatBufferProvider(int32_t channelCount, size_t bufferFrameCount) :
416 CopyBufferProvider(
417 channelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT),
418 channelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT),
419 bufferFrameCount),
420 mChannelCount(channelCount)
421 {
422 ALOGV("ClampFloatBufferProvider(%p)(%u)", this, channelCount);
423 }
424
copyFrames(void * dst,const void * src,size_t frames)425 void ClampFloatBufferProvider::copyFrames(void *dst, const void *src, size_t frames)
426 {
427 memcpy_to_float_from_float_with_clamping((float*)dst, (const float*)src,
428 frames * mChannelCount,
429 FLOAT_NOMINAL_RANGE_HEADROOM);
430 }
431
TimestretchBufferProvider(int32_t channelCount,audio_format_t format,uint32_t sampleRate,const AudioPlaybackRate & playbackRate)432 TimestretchBufferProvider::TimestretchBufferProvider(int32_t channelCount,
433 audio_format_t format, uint32_t sampleRate, const AudioPlaybackRate &playbackRate) :
434 mChannelCount(channelCount),
435 mFormat(format),
436 mSampleRate(sampleRate),
437 mFrameSize(channelCount * audio_bytes_per_sample(format)),
438 mLocalBufferFrameCount(0),
439 mLocalBufferData(NULL),
440 mRemaining(0),
441 mSonicStream(sonicCreateStream(sampleRate, mChannelCount)),
442 mFallbackFailErrorShown(false),
443 mAudioPlaybackRateValid(false)
444 {
445 LOG_ALWAYS_FATAL_IF(mSonicStream == NULL,
446 "TimestretchBufferProvider can't allocate Sonic stream");
447
448 setPlaybackRate(playbackRate);
449 ALOGV("TimestretchBufferProvider(%p)(%u, %#x, %u %f %f %d %d)",
450 this, channelCount, format, sampleRate, playbackRate.mSpeed,
451 playbackRate.mPitch, playbackRate.mStretchMode, playbackRate.mFallbackMode);
452 mBuffer.frameCount = 0;
453 }
454
~TimestretchBufferProvider()455 TimestretchBufferProvider::~TimestretchBufferProvider()
456 {
457 ALOGV("~TimestretchBufferProvider(%p)", this);
458 sonicDestroyStream(mSonicStream);
459 if (mBuffer.frameCount != 0) {
460 mTrackBufferProvider->releaseBuffer(&mBuffer);
461 }
462 free(mLocalBufferData);
463 }
464
getNextBuffer(AudioBufferProvider::Buffer * pBuffer)465 status_t TimestretchBufferProvider::getNextBuffer(
466 AudioBufferProvider::Buffer *pBuffer)
467 {
468 ALOGV("TimestretchBufferProvider(%p)::getNextBuffer(%p (%zu))",
469 this, pBuffer, pBuffer->frameCount);
470
471 // BYPASS
472 //return mTrackBufferProvider->getNextBuffer(pBuffer);
473
474 // check if previously processed data is sufficient.
475 if (pBuffer->frameCount <= mRemaining) {
476 ALOGV("previous sufficient");
477 pBuffer->raw = mLocalBufferData;
478 return OK;
479 }
480
481 // do we need to resize our buffer?
482 if (pBuffer->frameCount > mLocalBufferFrameCount) {
483 void *newmem;
484 if (posix_memalign(&newmem, 32, pBuffer->frameCount * mFrameSize) == OK) {
485 if (mRemaining != 0) {
486 memcpy(newmem, mLocalBufferData, mRemaining * mFrameSize);
487 }
488 free(mLocalBufferData);
489 mLocalBufferData = newmem;
490 mLocalBufferFrameCount = pBuffer->frameCount;
491 }
492 }
493
494 // need to fetch more data
495 const size_t outputDesired = pBuffer->frameCount - mRemaining;
496 size_t dstAvailable;
497 do {
498 mBuffer.frameCount = mPlaybackRate.mSpeed == AUDIO_TIMESTRETCH_SPEED_NORMAL
499 ? outputDesired : outputDesired * mPlaybackRate.mSpeed + 1;
500
501 status_t res = mTrackBufferProvider->getNextBuffer(&mBuffer);
502
503 ALOG_ASSERT(res == OK || mBuffer.frameCount == 0);
504 if (res != OK || mBuffer.frameCount == 0) { // not needed by API spec, but to be safe.
505 ALOGV("upstream provider cannot provide data");
506 if (mRemaining == 0) {
507 pBuffer->raw = NULL;
508 pBuffer->frameCount = 0;
509 return res;
510 } else { // return partial count
511 pBuffer->raw = mLocalBufferData;
512 pBuffer->frameCount = mRemaining;
513 return OK;
514 }
515 }
516
517 // time-stretch the data
518 dstAvailable = std::min(mLocalBufferFrameCount - mRemaining, outputDesired);
519 size_t srcAvailable = mBuffer.frameCount;
520 processFrames((uint8_t*)mLocalBufferData + mRemaining * mFrameSize, &dstAvailable,
521 mBuffer.raw, &srcAvailable);
522
523 // release all data consumed
524 mBuffer.frameCount = srcAvailable;
525 mTrackBufferProvider->releaseBuffer(&mBuffer);
526 } while (dstAvailable == 0); // try until we get output data or upstream provider fails.
527
528 // update buffer vars with the actual data processed and return with buffer
529 mRemaining += dstAvailable;
530
531 pBuffer->raw = mLocalBufferData;
532 pBuffer->frameCount = mRemaining;
533
534 return OK;
535 }
536
releaseBuffer(AudioBufferProvider::Buffer * pBuffer)537 void TimestretchBufferProvider::releaseBuffer(AudioBufferProvider::Buffer *pBuffer)
538 {
539 ALOGV("TimestretchBufferProvider(%p)::releaseBuffer(%p (%zu))",
540 this, pBuffer, pBuffer->frameCount);
541
542 // BYPASS
543 //return mTrackBufferProvider->releaseBuffer(pBuffer);
544
545 // LOG_ALWAYS_FATAL_IF(pBuffer->frameCount == 0, "Invalid framecount");
546 if (pBuffer->frameCount < mRemaining) {
547 memcpy(mLocalBufferData,
548 (uint8_t*)mLocalBufferData + pBuffer->frameCount * mFrameSize,
549 (mRemaining - pBuffer->frameCount) * mFrameSize);
550 mRemaining -= pBuffer->frameCount;
551 } else if (pBuffer->frameCount == mRemaining) {
552 mRemaining = 0;
553 } else {
554 LOG_ALWAYS_FATAL("Releasing more frames(%zu) than available(%zu)",
555 pBuffer->frameCount, mRemaining);
556 }
557
558 pBuffer->raw = NULL;
559 pBuffer->frameCount = 0;
560 }
561
reset()562 void TimestretchBufferProvider::reset()
563 {
564 mRemaining = 0;
565 }
566
setBufferProvider(AudioBufferProvider * p)567 void TimestretchBufferProvider::setBufferProvider(AudioBufferProvider *p) {
568 ALOGV("%s(%p): mTrackBufferProvider:%p mBuffer.frameCount:%zu",
569 __func__, p, mTrackBufferProvider, mBuffer.frameCount);
570 if (mTrackBufferProvider == p) {
571 return;
572 }
573 mBuffer.frameCount = 0;
574 PassthruBufferProvider::setBufferProvider(p);
575 }
576
setPlaybackRate(const AudioPlaybackRate & playbackRate)577 status_t TimestretchBufferProvider::setPlaybackRate(const AudioPlaybackRate &playbackRate)
578 {
579 mPlaybackRate = playbackRate;
580 mFallbackFailErrorShown = false;
581 sonicSetSpeed(mSonicStream, mPlaybackRate.mSpeed);
582 //TODO: pitch is ignored for now
583 //TODO: optimize: if parameters are the same, don't do any extra computation.
584
585 mAudioPlaybackRateValid = isAudioPlaybackRateValid(mPlaybackRate);
586 return OK;
587 }
588
processFrames(void * dstBuffer,size_t * dstFrames,const void * srcBuffer,size_t * srcFrames)589 void TimestretchBufferProvider::processFrames(void *dstBuffer, size_t *dstFrames,
590 const void *srcBuffer, size_t *srcFrames)
591 {
592 ALOGV("processFrames(%zu %zu) remaining(%zu)", *dstFrames, *srcFrames, mRemaining);
593 // Note dstFrames is the required number of frames.
594
595 if (!mAudioPlaybackRateValid) {
596 //fallback mode
597 // Ensure consumption from src is as expected.
598 // TODO: add logic to track "very accurate" consumption related to speed, original sampling
599 // rate, actual frames processed.
600
601 const size_t targetSrc = *dstFrames * mPlaybackRate.mSpeed;
602 if (*srcFrames < targetSrc) { // limit dst frames to that possible
603 *dstFrames = *srcFrames / mPlaybackRate.mSpeed;
604 } else if (*srcFrames > targetSrc + 1) {
605 *srcFrames = targetSrc + 1;
606 }
607 if (*dstFrames > 0) {
608 switch(mPlaybackRate.mFallbackMode) {
609 case AUDIO_TIMESTRETCH_FALLBACK_CUT_REPEAT:
610 if (*dstFrames <= *srcFrames) {
611 size_t copySize = mFrameSize * *dstFrames;
612 memcpy(dstBuffer, srcBuffer, copySize);
613 } else {
614 // cyclically repeat the source.
615 for (size_t count = 0; count < *dstFrames; count += *srcFrames) {
616 size_t remaining = std::min(*srcFrames, *dstFrames - count);
617 memcpy((uint8_t*)dstBuffer + mFrameSize * count,
618 srcBuffer, mFrameSize * remaining);
619 }
620 }
621 break;
622 case AUDIO_TIMESTRETCH_FALLBACK_DEFAULT:
623 case AUDIO_TIMESTRETCH_FALLBACK_MUTE:
624 memset(dstBuffer,0, mFrameSize * *dstFrames);
625 break;
626 case AUDIO_TIMESTRETCH_FALLBACK_FAIL:
627 default:
628 if(!mFallbackFailErrorShown) {
629 ALOGE("invalid parameters in TimestretchBufferProvider fallbackMode:%d",
630 mPlaybackRate.mFallbackMode);
631 mFallbackFailErrorShown = true;
632 }
633 break;
634 }
635 }
636 } else {
637 switch (mFormat) {
638 case AUDIO_FORMAT_PCM_FLOAT:
639 if (sonicWriteFloatToStream(mSonicStream, (float*)srcBuffer, *srcFrames) != 1) {
640 ALOGE("sonicWriteFloatToStream cannot realloc");
641 *srcFrames = 0; // cannot consume all of srcBuffer
642 }
643 *dstFrames = sonicReadFloatFromStream(mSonicStream, (float*)dstBuffer, *dstFrames);
644 break;
645 case AUDIO_FORMAT_PCM_16_BIT:
646 if (sonicWriteShortToStream(mSonicStream, (short*)srcBuffer, *srcFrames) != 1) {
647 ALOGE("sonicWriteShortToStream cannot realloc");
648 *srcFrames = 0; // cannot consume all of srcBuffer
649 }
650 *dstFrames = sonicReadShortFromStream(mSonicStream, (short*)dstBuffer, *dstFrames);
651 break;
652 default:
653 // could also be caught on construction
654 LOG_ALWAYS_FATAL("invalid format %#x for TimestretchBufferProvider", mFormat);
655 }
656 }
657 }
658
AdjustChannelsBufferProvider(audio_format_t format,size_t inChannelCount,size_t outChannelCount,size_t frameCount,audio_format_t contractedFormat,void * contractedBuffer,size_t contractedOutChannelCount)659 AdjustChannelsBufferProvider::AdjustChannelsBufferProvider(
660 audio_format_t format, size_t inChannelCount, size_t outChannelCount,
661 size_t frameCount, audio_format_t contractedFormat, void* contractedBuffer,
662 size_t contractedOutChannelCount) :
663 CopyBufferProvider(
664 audio_bytes_per_frame(inChannelCount, format),
665 audio_bytes_per_frame(std::max(inChannelCount, outChannelCount), format),
666 frameCount),
667 mFormat(format),
668 mInChannelCount(inChannelCount),
669 mOutChannelCount(outChannelCount),
670 mSampleSizeInBytes(audio_bytes_per_sample(format)),
671 mFrameCount(frameCount),
672 mContractedFormat(inChannelCount > outChannelCount
673 ? contractedFormat : AUDIO_FORMAT_INVALID),
674 mContractedInChannelCount(inChannelCount > outChannelCount
675 ? inChannelCount - outChannelCount : 0),
676 mContractedOutChannelCount(contractedOutChannelCount),
677 mContractedSampleSizeInBytes(audio_bytes_per_sample(contractedFormat)),
678 mContractedInputFrameSize(mContractedInChannelCount * mContractedSampleSizeInBytes),
679 mContractedBuffer(contractedBuffer),
680 mContractedWrittenFrames(0)
681 {
682 ALOGV("AdjustChannelsBufferProvider(%p)(%#x, %zu, %zu, %zu, %#x, %p, %zu)",
683 this, format, inChannelCount, outChannelCount, frameCount, contractedFormat,
684 contractedBuffer, contractedOutChannelCount);
685 if (mContractedFormat != AUDIO_FORMAT_INVALID && mInChannelCount > mOutChannelCount) {
686 mContractedOutputFrameSize =
687 audio_bytes_per_frame(mContractedOutChannelCount, mContractedFormat);
688 }
689 }
690
getNextBuffer(AudioBufferProvider::Buffer * pBuffer)691 status_t AdjustChannelsBufferProvider::getNextBuffer(AudioBufferProvider::Buffer* pBuffer)
692 {
693 if (mContractedBuffer != nullptr) {
694 // Restrict frame count only when it is needed to save contracted frames.
695 const size_t outFramesLeft = mFrameCount - mContractedWrittenFrames;
696 if (outFramesLeft < pBuffer->frameCount) {
697 // Restrict the frame count so that we don't write over the size of the output buffer.
698 pBuffer->frameCount = outFramesLeft;
699 }
700 }
701 return CopyBufferProvider::getNextBuffer(pBuffer);
702 }
703
copyFrames(void * dst,const void * src,size_t frames)704 void AdjustChannelsBufferProvider::copyFrames(void *dst, const void *src, size_t frames)
705 {
706 // For case multi to mono, adjust_channels has special logic that will mix first two input
707 // channels into a single output channel. In that case, use adjust_channels_non_destructive
708 // to keep only one channel data even when contracting to mono.
709 adjust_channels_non_destructive(src, mInChannelCount, dst, mOutChannelCount,
710 mSampleSizeInBytes, frames * mInChannelCount * mSampleSizeInBytes);
711 if (mContractedFormat != AUDIO_FORMAT_INVALID
712 && mContractedBuffer != nullptr) {
713 const size_t contractedIdx = frames * mOutChannelCount * mSampleSizeInBytes;
714 uint8_t* oriBuf = (uint8_t*) dst + contractedIdx;
715 uint8_t* buf = (uint8_t*) mContractedBuffer
716 + mContractedWrittenFrames * mContractedOutputFrameSize;
717 if (mContractedInChannelCount > mContractedOutChannelCount) {
718 // Adjust the channels first as the contracted buffer may not have enough
719 // space for the data.
720 // Use adjust_channels_non_destructive to avoid mix first two channels into one single
721 // output channel when it is multi to mono.
722 adjust_channels_non_destructive(
723 oriBuf, mContractedInChannelCount, oriBuf, mContractedOutChannelCount,
724 mSampleSizeInBytes, frames * mContractedInChannelCount * mSampleSizeInBytes);
725 memcpy_by_audio_format(
726 buf, mContractedFormat, oriBuf, mFormat, mContractedOutChannelCount * frames);
727 } else {
728 // Copy the data first as the dst buffer may not have enough space for extra channel.
729 memcpy_by_audio_format(
730 buf, mContractedFormat, oriBuf, mFormat, mContractedInChannelCount * frames);
731 // Note that if the contracted data is from MONO to MULTICHANNEL, the first 2 channels
732 // will be duplicated with the original single input channel and all the other channels
733 // will be 0-filled.
734 adjust_channels(
735 buf, mContractedInChannelCount, buf, mContractedOutChannelCount,
736 mContractedSampleSizeInBytes, mContractedInputFrameSize * frames);
737 }
738 mContractedWrittenFrames += frames;
739 }
740 }
741
reset()742 void AdjustChannelsBufferProvider::reset()
743 {
744 mContractedWrittenFrames = 0;
745 CopyBufferProvider::reset();
746 }
747
copyFrames(void * dst,const void * src,size_t frames)748 void TeeBufferProvider::copyFrames(void *dst, const void *src, size_t frames) {
749 memcpy(dst, src, frames * mInputFrameSize);
750 if (int teeBufferFrameLeft = mTeeBufferFrameCount - mFrameCopied; teeBufferFrameLeft < frames) {
751 ALOGW("Unable to copy all frames to tee buffer, %d frames dropped",
752 (int)frames - teeBufferFrameLeft);
753 frames = teeBufferFrameLeft;
754 }
755 memcpy(mTeeBuffer + mFrameCopied * mInputFrameSize, src, frames * mInputFrameSize);
756 mFrameCopied += frames;
757 }
758
clearFramesCopied()759 void TeeBufferProvider::clearFramesCopied() {
760 mFrameCopied = 0;
761 }
762
763 // ----------------------------------------------------------------------------
764 } // namespace android
765