SoftAAC2.cpp revision 4edf384a512748b871f24e4c03afaa3c1151ca23
1/* 2 * Copyright (C) 2012 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_NDEBUG 0 18#define LOG_TAG "SoftAAC2" 19#include <utils/Log.h> 20 21#include "SoftAAC2.h" 22#include <OMX_AudioExt.h> 23#include <OMX_IndexExt.h> 24 25#include <cutils/properties.h> 26#include <media/stagefright/foundation/ADebug.h> 27#include <media/stagefright/foundation/hexdump.h> 28#include <media/stagefright/MediaErrors.h> 29 30#include <math.h> 31 32#define FILEREAD_MAX_LAYERS 2 33 34#define DRC_DEFAULT_MOBILE_REF_LEVEL 64 /* 64*-0.25dB = -16 dB below full scale for mobile conf */ 35#define DRC_DEFAULT_MOBILE_DRC_CUT 127 /* maximum compression of dynamic range for mobile conf */ 36#define DRC_DEFAULT_MOBILE_DRC_BOOST 127 /* maximum compression of dynamic range for mobile conf */ 37#define DRC_DEFAULT_MOBILE_DRC_HEAVY 1 /* switch for heavy compression for mobile conf */ 38#define DRC_DEFAULT_MOBILE_ENC_LEVEL -1 /* encoder target level; -1 => the value is unknown, otherwise dB step value (e.g. 64 for -16 dB) */ 39#define MAX_CHANNEL_COUNT 8 /* maximum number of audio channels that can be decoded */ 40// names of properties that can be used to override the default DRC settings 41#define PROP_DRC_OVERRIDE_REF_LEVEL "aac_drc_reference_level" 42#define PROP_DRC_OVERRIDE_CUT "aac_drc_cut" 43#define PROP_DRC_OVERRIDE_BOOST "aac_drc_boost" 44#define PROP_DRC_OVERRIDE_HEAVY "aac_drc_heavy" 45#define PROP_DRC_OVERRIDE_ENC_LEVEL "aac_drc_enc_target_level" 46 47namespace android { 48 49template<class T> 50static void InitOMXParams(T *params) { 51 params->nSize = sizeof(T); 52 params->nVersion.s.nVersionMajor = 1; 53 params->nVersion.s.nVersionMinor = 0; 54 params->nVersion.s.nRevision = 0; 55 params->nVersion.s.nStep = 0; 56} 57 58SoftAAC2::SoftAAC2( 59 const char *name, 60 const OMX_CALLBACKTYPE *callbacks, 61 OMX_PTR appData, 62 OMX_COMPONENTTYPE **component) 63 : SimpleSoftOMXComponent(name, callbacks, appData, component), 64 mAACDecoder(NULL), 65 mStreamInfo(NULL), 66 mIsADTS(false), 67 mInputBufferCount(0), 68 mOutputBufferCount(0), 69 mSignalledError(false), 70 mLastInHeader(NULL), 71 mOutputPortSettingsChange(NONE) { 72 initPorts(); 73 CHECK_EQ(initDecoder(), (status_t)OK); 74} 75 76SoftAAC2::~SoftAAC2() { 77 aacDecoder_Close(mAACDecoder); 78 delete mOutputDelayRingBuffer; 79} 80 81void SoftAAC2::initPorts() { 82 OMX_PARAM_PORTDEFINITIONTYPE def; 83 InitOMXParams(&def); 84 85 def.nPortIndex = 0; 86 def.eDir = OMX_DirInput; 87 def.nBufferCountMin = kNumInputBuffers; 88 def.nBufferCountActual = def.nBufferCountMin; 89 def.nBufferSize = 8192; 90 def.bEnabled = OMX_TRUE; 91 def.bPopulated = OMX_FALSE; 92 def.eDomain = OMX_PortDomainAudio; 93 def.bBuffersContiguous = OMX_FALSE; 94 def.nBufferAlignment = 1; 95 96 def.format.audio.cMIMEType = const_cast<char *>("audio/aac"); 97 def.format.audio.pNativeRender = NULL; 98 def.format.audio.bFlagErrorConcealment = OMX_FALSE; 99 def.format.audio.eEncoding = OMX_AUDIO_CodingAAC; 100 101 addPort(def); 102 103 def.nPortIndex = 1; 104 def.eDir = OMX_DirOutput; 105 def.nBufferCountMin = kNumOutputBuffers; 106 def.nBufferCountActual = def.nBufferCountMin; 107 def.nBufferSize = 4096 * MAX_CHANNEL_COUNT; 108 def.bEnabled = OMX_TRUE; 109 def.bPopulated = OMX_FALSE; 110 def.eDomain = OMX_PortDomainAudio; 111 def.bBuffersContiguous = OMX_FALSE; 112 def.nBufferAlignment = 2; 113 114 def.format.audio.cMIMEType = const_cast<char *>("audio/raw"); 115 def.format.audio.pNativeRender = NULL; 116 def.format.audio.bFlagErrorConcealment = OMX_FALSE; 117 def.format.audio.eEncoding = OMX_AUDIO_CodingPCM; 118 119 addPort(def); 120} 121 122status_t SoftAAC2::initDecoder() { 123 ALOGV("initDecoder()"); 124 status_t status = UNKNOWN_ERROR; 125 mAACDecoder = aacDecoder_Open(TT_MP4_ADIF, /* num layers */ 1); 126 if (mAACDecoder != NULL) { 127 mStreamInfo = aacDecoder_GetStreamInfo(mAACDecoder); 128 if (mStreamInfo != NULL) { 129 status = OK; 130 } 131 } 132 133 mEndOfInput = false; 134 mEndOfOutput = false; 135 mOutputDelayCompensated = 0; 136 mOutputDelayRingBufferSize = 2048 * MAX_CHANNEL_COUNT * kNumDelayBlocksMax; 137 mOutputDelayRingBuffer = new short[mOutputDelayRingBufferSize]; 138 mOutputDelayRingBufferWritePos = 0; 139 mOutputDelayRingBufferReadPos = 0; 140 mOutputDelayRingBufferFilled = 0; 141 142 if (mAACDecoder == NULL) { 143 ALOGE("AAC decoder is null. TODO: Can not call aacDecoder_SetParam in the following code"); 144 } 145 146 //aacDecoder_SetParam(mAACDecoder, AAC_PCM_LIMITER_ENABLE, 0); 147 148 //init DRC wrapper 149 mDrcWrap.setDecoderHandle(mAACDecoder); 150 mDrcWrap.submitStreamData(mStreamInfo); 151 152 // for streams that contain metadata, use the mobile profile DRC settings unless overridden by platform properties 153 // TODO: change the DRC settings depending on audio output device type (HDMI, loadspeaker, headphone) 154 char value[PROPERTY_VALUE_MAX]; 155 // DRC_PRES_MODE_WRAP_DESIRED_TARGET 156 if (property_get(PROP_DRC_OVERRIDE_REF_LEVEL, value, NULL)) { 157 unsigned refLevel = atoi(value); 158 ALOGV("AAC decoder using desired DRC target reference level of %d instead of %d", refLevel, 159 DRC_DEFAULT_MOBILE_REF_LEVEL); 160 mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_TARGET, refLevel); 161 } else { 162 mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_TARGET, DRC_DEFAULT_MOBILE_REF_LEVEL); 163 } 164 // DRC_PRES_MODE_WRAP_DESIRED_ATT_FACTOR 165 if (property_get(PROP_DRC_OVERRIDE_CUT, value, NULL)) { 166 unsigned cut = atoi(value); 167 ALOGV("AAC decoder using desired DRC attenuation factor of %d instead of %d", cut, 168 DRC_DEFAULT_MOBILE_DRC_CUT); 169 mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_ATT_FACTOR, cut); 170 } else { 171 mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_ATT_FACTOR, DRC_DEFAULT_MOBILE_DRC_CUT); 172 } 173 // DRC_PRES_MODE_WRAP_DESIRED_BOOST_FACTOR 174 if (property_get(PROP_DRC_OVERRIDE_BOOST, value, NULL)) { 175 unsigned boost = atoi(value); 176 ALOGV("AAC decoder using desired DRC boost factor of %d instead of %d", boost, 177 DRC_DEFAULT_MOBILE_DRC_BOOST); 178 mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_BOOST_FACTOR, boost); 179 } else { 180 mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_BOOST_FACTOR, DRC_DEFAULT_MOBILE_DRC_BOOST); 181 } 182 // DRC_PRES_MODE_WRAP_DESIRED_HEAVY 183 if (property_get(PROP_DRC_OVERRIDE_HEAVY, value, NULL)) { 184 unsigned heavy = atoi(value); 185 ALOGV("AAC decoder using desried DRC heavy compression switch of %d instead of %d", heavy, 186 DRC_DEFAULT_MOBILE_DRC_HEAVY); 187 mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_HEAVY, heavy); 188 } else { 189 mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_HEAVY, DRC_DEFAULT_MOBILE_DRC_HEAVY); 190 } 191 // DRC_PRES_MODE_WRAP_ENCODER_TARGET 192 if (property_get(PROP_DRC_OVERRIDE_ENC_LEVEL, value, NULL)) { 193 unsigned encoderRefLevel = atoi(value); 194 ALOGV("AAC decoder using encoder-side DRC reference level of %d instead of %d", 195 encoderRefLevel, DRC_DEFAULT_MOBILE_ENC_LEVEL); 196 mDrcWrap.setParam(DRC_PRES_MODE_WRAP_ENCODER_TARGET, encoderRefLevel); 197 } else { 198 mDrcWrap.setParam(DRC_PRES_MODE_WRAP_ENCODER_TARGET, DRC_DEFAULT_MOBILE_ENC_LEVEL); 199 } 200 201 return status; 202} 203 204OMX_ERRORTYPE SoftAAC2::internalGetParameter( 205 OMX_INDEXTYPE index, OMX_PTR params) { 206 switch (index) { 207 case OMX_IndexParamAudioAac: 208 { 209 OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = 210 (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; 211 212 if (aacParams->nPortIndex != 0) { 213 return OMX_ErrorUndefined; 214 } 215 216 aacParams->nBitRate = 0; 217 aacParams->nAudioBandWidth = 0; 218 aacParams->nAACtools = 0; 219 aacParams->nAACERtools = 0; 220 aacParams->eAACProfile = OMX_AUDIO_AACObjectMain; 221 222 aacParams->eAACStreamFormat = 223 mIsADTS 224 ? OMX_AUDIO_AACStreamFormatMP4ADTS 225 : OMX_AUDIO_AACStreamFormatMP4FF; 226 227 aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo; 228 229 if (!isConfigured()) { 230 aacParams->nChannels = 1; 231 aacParams->nSampleRate = 44100; 232 aacParams->nFrameLength = 0; 233 } else { 234 aacParams->nChannels = mStreamInfo->numChannels; 235 aacParams->nSampleRate = mStreamInfo->sampleRate; 236 aacParams->nFrameLength = mStreamInfo->frameSize; 237 } 238 239 return OMX_ErrorNone; 240 } 241 242 case OMX_IndexParamAudioPcm: 243 { 244 OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = 245 (OMX_AUDIO_PARAM_PCMMODETYPE *)params; 246 247 if (pcmParams->nPortIndex != 1) { 248 return OMX_ErrorUndefined; 249 } 250 251 pcmParams->eNumData = OMX_NumericalDataSigned; 252 pcmParams->eEndian = OMX_EndianBig; 253 pcmParams->bInterleaved = OMX_TRUE; 254 pcmParams->nBitPerSample = 16; 255 pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; 256 pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; 257 pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; 258 pcmParams->eChannelMapping[2] = OMX_AUDIO_ChannelCF; 259 pcmParams->eChannelMapping[3] = OMX_AUDIO_ChannelLFE; 260 pcmParams->eChannelMapping[4] = OMX_AUDIO_ChannelLS; 261 pcmParams->eChannelMapping[5] = OMX_AUDIO_ChannelRS; 262 263 if (!isConfigured()) { 264 pcmParams->nChannels = 1; 265 pcmParams->nSamplingRate = 44100; 266 } else { 267 pcmParams->nChannels = mStreamInfo->numChannels; 268 pcmParams->nSamplingRate = mStreamInfo->sampleRate; 269 } 270 271 return OMX_ErrorNone; 272 } 273 274 default: 275 return SimpleSoftOMXComponent::internalGetParameter(index, params); 276 } 277} 278 279OMX_ERRORTYPE SoftAAC2::internalSetParameter( 280 OMX_INDEXTYPE index, const OMX_PTR params) { 281 switch ((int)index) { 282 case OMX_IndexParamStandardComponentRole: 283 { 284 const OMX_PARAM_COMPONENTROLETYPE *roleParams = 285 (const OMX_PARAM_COMPONENTROLETYPE *)params; 286 287 if (strncmp((const char *)roleParams->cRole, 288 "audio_decoder.aac", 289 OMX_MAX_STRINGNAME_SIZE - 1)) { 290 return OMX_ErrorUndefined; 291 } 292 293 return OMX_ErrorNone; 294 } 295 296 case OMX_IndexParamAudioAac: 297 { 298 const OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = 299 (const OMX_AUDIO_PARAM_AACPROFILETYPE *)params; 300 301 if (aacParams->nPortIndex != 0) { 302 return OMX_ErrorUndefined; 303 } 304 305 if (aacParams->eAACStreamFormat == OMX_AUDIO_AACStreamFormatMP4FF) { 306 mIsADTS = false; 307 } else if (aacParams->eAACStreamFormat 308 == OMX_AUDIO_AACStreamFormatMP4ADTS) { 309 mIsADTS = true; 310 } else { 311 return OMX_ErrorUndefined; 312 } 313 314 return OMX_ErrorNone; 315 } 316 317 case OMX_IndexParamAudioAndroidAacPresentation: 318 { 319 const OMX_AUDIO_PARAM_ANDROID_AACPRESENTATIONTYPE *aacPresParams = 320 (const OMX_AUDIO_PARAM_ANDROID_AACPRESENTATIONTYPE *)params; 321 // for the following parameters of the OMX_AUDIO_PARAM_AACPROFILETYPE structure, 322 // a value of -1 implies the parameter is not set by the application: 323 // nMaxOutputChannels uses default platform properties, see configureDownmix() 324 // nDrcCut uses default platform properties, see initDecoder() 325 // nDrcBoost idem 326 // nHeavyCompression idem 327 // nTargetReferenceLevel idem 328 // nEncodedTargetLevel idem 329 if (aacPresParams->nMaxOutputChannels >= 0) { 330 int max; 331 if (aacPresParams->nMaxOutputChannels >= 8) { max = 8; } 332 else if (aacPresParams->nMaxOutputChannels >= 6) { max = 6; } 333 else if (aacPresParams->nMaxOutputChannels >= 2) { max = 2; } 334 else { 335 // -1 or 0: disable downmix, 1: mono 336 max = aacPresParams->nMaxOutputChannels; 337 } 338 ALOGV("set nMaxOutputChannels=%d", max); 339 aacDecoder_SetParam(mAACDecoder, AAC_PCM_MAX_OUTPUT_CHANNELS, max); 340 } 341 bool updateDrcWrapper = false; 342 if (aacPresParams->nDrcBoost >= 0) { 343 ALOGV("set nDrcBoost=%d", aacPresParams->nDrcBoost); 344 mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_BOOST_FACTOR, 345 aacPresParams->nDrcBoost); 346 updateDrcWrapper = true; 347 } 348 if (aacPresParams->nDrcCut >= 0) { 349 ALOGV("set nDrcCut=%d", aacPresParams->nDrcCut); 350 mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_ATT_FACTOR, aacPresParams->nDrcCut); 351 updateDrcWrapper = true; 352 } 353 if (aacPresParams->nHeavyCompression >= 0) { 354 ALOGV("set nHeavyCompression=%d", aacPresParams->nHeavyCompression); 355 mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_HEAVY, 356 aacPresParams->nHeavyCompression); 357 updateDrcWrapper = true; 358 } 359 if (aacPresParams->nTargetReferenceLevel >= 0) { 360 ALOGV("set nTargetReferenceLevel=%d", aacPresParams->nTargetReferenceLevel); 361 mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_TARGET, 362 aacPresParams->nTargetReferenceLevel); 363 updateDrcWrapper = true; 364 } 365 if (aacPresParams->nEncodedTargetLevel >= 0) { 366 ALOGV("set nEncodedTargetLevel=%d", aacPresParams->nEncodedTargetLevel); 367 mDrcWrap.setParam(DRC_PRES_MODE_WRAP_ENCODER_TARGET, 368 aacPresParams->nEncodedTargetLevel); 369 updateDrcWrapper = true; 370 } 371 if (updateDrcWrapper) { 372 mDrcWrap.update(); 373 } 374 375 return OMX_ErrorNone; 376 } 377 378 case OMX_IndexParamAudioPcm: 379 { 380 const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = 381 (OMX_AUDIO_PARAM_PCMMODETYPE *)params; 382 383 if (pcmParams->nPortIndex != 1) { 384 return OMX_ErrorUndefined; 385 } 386 387 return OMX_ErrorNone; 388 } 389 390 default: 391 return SimpleSoftOMXComponent::internalSetParameter(index, params); 392 } 393} 394 395bool SoftAAC2::isConfigured() const { 396 return mInputBufferCount > 0; 397} 398 399void SoftAAC2::configureDownmix() const { 400 char value[PROPERTY_VALUE_MAX]; 401 if (!(property_get("media.aac_51_output_enabled", value, NULL) 402 && (!strcmp(value, "1") || !strcasecmp(value, "true")))) { 403 ALOGI("limiting to stereo output"); 404 aacDecoder_SetParam(mAACDecoder, AAC_PCM_MAX_OUTPUT_CHANNELS, 2); 405 // By default, the decoder creates a 5.1 channel downmix signal 406 // for seven and eight channel input streams. To enable 6.1 and 7.1 channel output 407 // use aacDecoder_SetParam(mAACDecoder, AAC_PCM_MAX_OUTPUT_CHANNELS, -1) 408 } 409} 410 411bool SoftAAC2::outputDelayRingBufferPutSamples(INT_PCM *samples, int32_t numSamples) { 412 if (numSamples == 0) { 413 return true; 414 } 415 if (outputDelayRingBufferSpaceLeft() < numSamples) { 416 ALOGE("RING BUFFER WOULD OVERFLOW"); 417 return false; 418 } 419 if (mOutputDelayRingBufferWritePos + numSamples <= mOutputDelayRingBufferSize 420 && (mOutputDelayRingBufferReadPos <= mOutputDelayRingBufferWritePos 421 || mOutputDelayRingBufferReadPos > mOutputDelayRingBufferWritePos + numSamples)) { 422 // faster memcopy loop without checks, if the preconditions allow this 423 for (int32_t i = 0; i < numSamples; i++) { 424 mOutputDelayRingBuffer[mOutputDelayRingBufferWritePos++] = samples[i]; 425 } 426 427 if (mOutputDelayRingBufferWritePos >= mOutputDelayRingBufferSize) { 428 mOutputDelayRingBufferWritePos -= mOutputDelayRingBufferSize; 429 } 430 } else { 431 ALOGV("slow SoftAAC2::outputDelayRingBufferPutSamples()"); 432 433 for (int32_t i = 0; i < numSamples; i++) { 434 mOutputDelayRingBuffer[mOutputDelayRingBufferWritePos] = samples[i]; 435 mOutputDelayRingBufferWritePos++; 436 if (mOutputDelayRingBufferWritePos >= mOutputDelayRingBufferSize) { 437 mOutputDelayRingBufferWritePos -= mOutputDelayRingBufferSize; 438 } 439 } 440 } 441 mOutputDelayRingBufferFilled += numSamples; 442 return true; 443} 444 445int32_t SoftAAC2::outputDelayRingBufferGetSamples(INT_PCM *samples, int32_t numSamples) { 446 447 if (numSamples > mOutputDelayRingBufferFilled) { 448 ALOGE("RING BUFFER WOULD UNDERRUN"); 449 return -1; 450 } 451 452 if (mOutputDelayRingBufferReadPos + numSamples <= mOutputDelayRingBufferSize 453 && (mOutputDelayRingBufferWritePos < mOutputDelayRingBufferReadPos 454 || mOutputDelayRingBufferWritePos >= mOutputDelayRingBufferReadPos + numSamples)) { 455 // faster memcopy loop without checks, if the preconditions allow this 456 if (samples != 0) { 457 for (int32_t i = 0; i < numSamples; i++) { 458 samples[i] = mOutputDelayRingBuffer[mOutputDelayRingBufferReadPos++]; 459 } 460 } else { 461 mOutputDelayRingBufferReadPos += numSamples; 462 } 463 if (mOutputDelayRingBufferReadPos >= mOutputDelayRingBufferSize) { 464 mOutputDelayRingBufferReadPos -= mOutputDelayRingBufferSize; 465 } 466 } else { 467 ALOGV("slow SoftAAC2::outputDelayRingBufferGetSamples()"); 468 469 for (int32_t i = 0; i < numSamples; i++) { 470 if (samples != 0) { 471 samples[i] = mOutputDelayRingBuffer[mOutputDelayRingBufferReadPos]; 472 } 473 mOutputDelayRingBufferReadPos++; 474 if (mOutputDelayRingBufferReadPos >= mOutputDelayRingBufferSize) { 475 mOutputDelayRingBufferReadPos -= mOutputDelayRingBufferSize; 476 } 477 } 478 } 479 mOutputDelayRingBufferFilled -= numSamples; 480 return numSamples; 481} 482 483int32_t SoftAAC2::outputDelayRingBufferSamplesAvailable() { 484 return mOutputDelayRingBufferFilled; 485} 486 487int32_t SoftAAC2::outputDelayRingBufferSpaceLeft() { 488 return mOutputDelayRingBufferSize - outputDelayRingBufferSamplesAvailable(); 489} 490 491 492void SoftAAC2::onQueueFilled(OMX_U32 /* portIndex */) { 493 if (mSignalledError || mOutputPortSettingsChange != NONE) { 494 return; 495 } 496 497 UCHAR* inBuffer[FILEREAD_MAX_LAYERS]; 498 UINT inBufferLength[FILEREAD_MAX_LAYERS] = {0}; 499 UINT bytesValid[FILEREAD_MAX_LAYERS] = {0}; 500 501 List<BufferInfo *> &inQueue = getPortQueue(0); 502 List<BufferInfo *> &outQueue = getPortQueue(1); 503 504 while ((!inQueue.empty() || mEndOfInput) && !outQueue.empty()) { 505 if (!inQueue.empty()) { 506 INT_PCM tmpOutBuffer[2048 * MAX_CHANNEL_COUNT]; 507 BufferInfo *inInfo = *inQueue.begin(); 508 OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; 509 510 mEndOfInput = (inHeader->nFlags & OMX_BUFFERFLAG_EOS) != 0; 511 512 if (mInputBufferCount == 0 && !(inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG)) { 513 ALOGE("first buffer should have OMX_BUFFERFLAG_CODECCONFIG set"); 514 inHeader->nFlags |= OMX_BUFFERFLAG_CODECCONFIG; 515 } 516 if ((inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) != 0) { 517 BufferInfo *inInfo = *inQueue.begin(); 518 OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; 519 520 inBuffer[0] = inHeader->pBuffer + inHeader->nOffset; 521 inBufferLength[0] = inHeader->nFilledLen; 522 523 AAC_DECODER_ERROR decoderErr = 524 aacDecoder_ConfigRaw(mAACDecoder, 525 inBuffer, 526 inBufferLength); 527 528 if (decoderErr != AAC_DEC_OK) { 529 ALOGW("aacDecoder_ConfigRaw decoderErr = 0x%4.4x", decoderErr); 530 mSignalledError = true; 531 notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL); 532 return; 533 } 534 535 mInputBufferCount++; 536 mOutputBufferCount++; // fake increase of outputBufferCount to keep the counters aligned 537 538 inInfo->mOwnedByUs = false; 539 inQueue.erase(inQueue.begin()); 540 mLastInHeader = NULL; 541 inInfo = NULL; 542 notifyEmptyBufferDone(inHeader); 543 inHeader = NULL; 544 545 configureDownmix(); 546 // Only send out port settings changed event if both sample rate 547 // and numChannels are valid. 548 if (mStreamInfo->sampleRate && mStreamInfo->numChannels) { 549 ALOGI("Initially configuring decoder: %d Hz, %d channels", 550 mStreamInfo->sampleRate, 551 mStreamInfo->numChannels); 552 553 notify(OMX_EventPortSettingsChanged, 1, 0, NULL); 554 mOutputPortSettingsChange = AWAITING_DISABLED; 555 } 556 return; 557 } 558 559 if (inHeader->nFilledLen == 0) { 560 inInfo->mOwnedByUs = false; 561 inQueue.erase(inQueue.begin()); 562 mLastInHeader = NULL; 563 inInfo = NULL; 564 notifyEmptyBufferDone(inHeader); 565 inHeader = NULL; 566 continue; 567 } 568 569 if (mIsADTS) { 570 size_t adtsHeaderSize = 0; 571 // skip 30 bits, aac_frame_length follows. 572 // ssssssss ssssiiip ppffffPc ccohCCll llllllll lll????? 573 574 const uint8_t *adtsHeader = inHeader->pBuffer + inHeader->nOffset; 575 576 bool signalError = false; 577 if (inHeader->nFilledLen < 7) { 578 ALOGE("Audio data too short to contain even the ADTS header. " 579 "Got %d bytes.", inHeader->nFilledLen); 580 hexdump(adtsHeader, inHeader->nFilledLen); 581 signalError = true; 582 } else { 583 bool protectionAbsent = (adtsHeader[1] & 1); 584 585 unsigned aac_frame_length = 586 ((adtsHeader[3] & 3) << 11) 587 | (adtsHeader[4] << 3) 588 | (adtsHeader[5] >> 5); 589 590 if (inHeader->nFilledLen < aac_frame_length) { 591 ALOGE("Not enough audio data for the complete frame. " 592 "Got %d bytes, frame size according to the ADTS " 593 "header is %u bytes.", 594 inHeader->nFilledLen, aac_frame_length); 595 hexdump(adtsHeader, inHeader->nFilledLen); 596 signalError = true; 597 } else { 598 adtsHeaderSize = (protectionAbsent ? 7 : 9); 599 600 inBuffer[0] = (UCHAR *)adtsHeader + adtsHeaderSize; 601 inBufferLength[0] = aac_frame_length - adtsHeaderSize; 602 603 inHeader->nOffset += adtsHeaderSize; 604 inHeader->nFilledLen -= adtsHeaderSize; 605 } 606 } 607 608 if (signalError) { 609 mSignalledError = true; 610 notify(OMX_EventError, OMX_ErrorStreamCorrupt, ERROR_MALFORMED, NULL); 611 return; 612 } 613 614 // insert buffer size and time stamp 615 mBufferSizes.add(inBufferLength[0]); 616 if (mLastInHeader != inHeader) { 617 mBufferTimestamps.add(inHeader->nTimeStamp); 618 mLastInHeader = inHeader; 619 } else { 620 int64_t currentTime = mBufferTimestamps.top(); 621 currentTime += mStreamInfo->aacSamplesPerFrame * 622 1000000ll / mStreamInfo->sampleRate; 623 mBufferTimestamps.add(currentTime); 624 } 625 } else { 626 inBuffer[0] = inHeader->pBuffer + inHeader->nOffset; 627 inBufferLength[0] = inHeader->nFilledLen; 628 mLastInHeader = inHeader; 629 mBufferTimestamps.add(inHeader->nTimeStamp); 630 mBufferSizes.add(inHeader->nFilledLen); 631 } 632 633 // Fill and decode 634 bytesValid[0] = inBufferLength[0]; 635 636 INT prevSampleRate = mStreamInfo->sampleRate; 637 INT prevNumChannels = mStreamInfo->numChannels; 638 639 aacDecoder_Fill(mAACDecoder, 640 inBuffer, 641 inBufferLength, 642 bytesValid); 643 644 // run DRC check 645 mDrcWrap.submitStreamData(mStreamInfo); 646 mDrcWrap.update(); 647 648 UINT inBufferUsedLength = inBufferLength[0] - bytesValid[0]; 649 inHeader->nFilledLen -= inBufferUsedLength; 650 inHeader->nOffset += inBufferUsedLength; 651 652 AAC_DECODER_ERROR decoderErr; 653 do { 654 if (outputDelayRingBufferSpaceLeft() < 655 (mStreamInfo->frameSize * mStreamInfo->numChannels)) { 656 ALOGV("skipping decode: not enough space left in ringbuffer"); 657 break; 658 } 659 660 int numconsumed = mStreamInfo->numTotalBytes + mStreamInfo->numBadBytes; 661 decoderErr = aacDecoder_DecodeFrame(mAACDecoder, 662 tmpOutBuffer, 663 2048 * MAX_CHANNEL_COUNT, 664 0 /* flags */); 665 666 numconsumed = (mStreamInfo->numTotalBytes + mStreamInfo->numBadBytes) - numconsumed; 667 if (numconsumed != 0) { 668 mDecodedSizes.add(numconsumed); 669 } 670 671 if (decoderErr == AAC_DEC_NOT_ENOUGH_BITS) { 672 break; 673 } 674 675 if (decoderErr != AAC_DEC_OK) { 676 ALOGW("aacDecoder_DecodeFrame decoderErr = 0x%4.4x", decoderErr); 677 } 678 679 if (bytesValid[0] != 0) { 680 ALOGE("bytesValid[0] != 0 should never happen"); 681 mSignalledError = true; 682 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); 683 return; 684 } 685 686 size_t numOutBytes = 687 mStreamInfo->frameSize * sizeof(int16_t) * mStreamInfo->numChannels; 688 689 if (decoderErr == AAC_DEC_OK) { 690 if (!outputDelayRingBufferPutSamples(tmpOutBuffer, 691 mStreamInfo->frameSize * mStreamInfo->numChannels)) { 692 mSignalledError = true; 693 notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL); 694 return; 695 } 696 } else { 697 ALOGW("AAC decoder returned error 0x%4.4x, substituting silence", decoderErr); 698 699 memset(tmpOutBuffer, 0, numOutBytes); // TODO: check for overflow 700 701 if (!outputDelayRingBufferPutSamples(tmpOutBuffer, 702 mStreamInfo->frameSize * mStreamInfo->numChannels)) { 703 mSignalledError = true; 704 notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL); 705 return; 706 } 707 708 // Discard input buffer. 709 if (inHeader) { 710 inHeader->nFilledLen = 0; 711 } 712 713 aacDecoder_SetParam(mAACDecoder, AAC_TPDEC_CLEAR_BUFFER, 1); 714 715 // fall through 716 } 717 718 /* 719 * AAC+/eAAC+ streams can be signalled in two ways: either explicitly 720 * or implicitly, according to MPEG4 spec. AAC+/eAAC+ is a dual 721 * rate system and the sampling rate in the final output is actually 722 * doubled compared with the core AAC decoder sampling rate. 723 * 724 * Explicit signalling is done by explicitly defining SBR audio object 725 * type in the bitstream. Implicit signalling is done by embedding 726 * SBR content in AAC extension payload specific to SBR, and hence 727 * requires an AAC decoder to perform pre-checks on actual audio frames. 728 * 729 * Thus, we could not say for sure whether a stream is 730 * AAC+/eAAC+ until the first data frame is decoded. 731 */ 732 if (mInputBufferCount <= 2 || mOutputBufferCount > 1) { // TODO: <= 1 733 if (mStreamInfo->sampleRate != prevSampleRate || 734 mStreamInfo->numChannels != prevNumChannels) { 735 ALOGI("Reconfiguring decoder: %d->%d Hz, %d->%d channels", 736 prevSampleRate, mStreamInfo->sampleRate, 737 prevNumChannels, mStreamInfo->numChannels); 738 739 notify(OMX_EventPortSettingsChanged, 1, 0, NULL); 740 mOutputPortSettingsChange = AWAITING_DISABLED; 741 742 if (inHeader && inHeader->nFilledLen == 0) { 743 inInfo->mOwnedByUs = false; 744 mInputBufferCount++; 745 inQueue.erase(inQueue.begin()); 746 mLastInHeader = NULL; 747 inInfo = NULL; 748 notifyEmptyBufferDone(inHeader); 749 inHeader = NULL; 750 } 751 return; 752 } 753 } else if (!mStreamInfo->sampleRate || !mStreamInfo->numChannels) { 754 ALOGW("Invalid AAC stream"); 755 mSignalledError = true; 756 notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL); 757 return; 758 } 759 if (inHeader && inHeader->nFilledLen == 0) { 760 inInfo->mOwnedByUs = false; 761 mInputBufferCount++; 762 inQueue.erase(inQueue.begin()); 763 mLastInHeader = NULL; 764 inInfo = NULL; 765 notifyEmptyBufferDone(inHeader); 766 inHeader = NULL; 767 } else { 768 ALOGV("inHeader->nFilledLen = %d", inHeader ? inHeader->nFilledLen : 0); 769 } 770 } while (decoderErr == AAC_DEC_OK); 771 } 772 773 int32_t outputDelay = mStreamInfo->outputDelay * mStreamInfo->numChannels; 774 775 if (!mEndOfInput && mOutputDelayCompensated < outputDelay) { 776 // discard outputDelay at the beginning 777 int32_t toCompensate = outputDelay - mOutputDelayCompensated; 778 int32_t discard = outputDelayRingBufferSamplesAvailable(); 779 if (discard > toCompensate) { 780 discard = toCompensate; 781 } 782 int32_t discarded = outputDelayRingBufferGetSamples(0, discard); 783 mOutputDelayCompensated += discarded; 784 continue; 785 } 786 787 if (mEndOfInput) { 788 while (mOutputDelayCompensated > 0) { 789 // a buffer big enough for MAX_CHANNEL_COUNT channels of decoded HE-AAC 790 INT_PCM tmpOutBuffer[2048 * MAX_CHANNEL_COUNT]; 791 792 // run DRC check 793 mDrcWrap.submitStreamData(mStreamInfo); 794 mDrcWrap.update(); 795 796 AAC_DECODER_ERROR decoderErr = 797 aacDecoder_DecodeFrame(mAACDecoder, 798 tmpOutBuffer, 799 2048 * MAX_CHANNEL_COUNT, 800 AACDEC_FLUSH); 801 if (decoderErr != AAC_DEC_OK) { 802 ALOGW("aacDecoder_DecodeFrame decoderErr = 0x%4.4x", decoderErr); 803 } 804 805 int32_t tmpOutBufferSamples = mStreamInfo->frameSize * mStreamInfo->numChannels; 806 if (tmpOutBufferSamples > mOutputDelayCompensated) { 807 tmpOutBufferSamples = mOutputDelayCompensated; 808 } 809 outputDelayRingBufferPutSamples(tmpOutBuffer, tmpOutBufferSamples); 810 mOutputDelayCompensated -= tmpOutBufferSamples; 811 } 812 } 813 814 while (!outQueue.empty() 815 && outputDelayRingBufferSamplesAvailable() 816 >= mStreamInfo->frameSize * mStreamInfo->numChannels) { 817 BufferInfo *outInfo = *outQueue.begin(); 818 OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; 819 820 if (outHeader->nOffset != 0) { 821 ALOGE("outHeader->nOffset != 0 is not handled"); 822 mSignalledError = true; 823 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); 824 return; 825 } 826 827 INT_PCM *outBuffer = 828 reinterpret_cast<INT_PCM *>(outHeader->pBuffer + outHeader->nOffset); 829 int samplesize = mStreamInfo->numChannels * sizeof(int16_t); 830 if (outHeader->nOffset 831 + mStreamInfo->frameSize * samplesize 832 > outHeader->nAllocLen) { 833 ALOGE("buffer overflow"); 834 mSignalledError = true; 835 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); 836 return; 837 838 } 839 840 int available = outputDelayRingBufferSamplesAvailable(); 841 int numSamples = outHeader->nAllocLen / sizeof(int16_t); 842 if (numSamples > available) { 843 numSamples = available; 844 } 845 int64_t currentTime = 0; 846 if (available) { 847 848 int numFrames = numSamples / (mStreamInfo->frameSize * mStreamInfo->numChannels); 849 numSamples = numFrames * (mStreamInfo->frameSize * mStreamInfo->numChannels); 850 851 ALOGV("%d samples available (%d), or %d frames", 852 numSamples, available, numFrames); 853 int64_t *nextTimeStamp = &mBufferTimestamps.editItemAt(0); 854 currentTime = *nextTimeStamp; 855 int32_t *currentBufLeft = &mBufferSizes.editItemAt(0); 856 for (int i = 0; i < numFrames; i++) { 857 int32_t decodedSize = mDecodedSizes.itemAt(0); 858 mDecodedSizes.removeAt(0); 859 ALOGV("decoded %d of %d", decodedSize, *currentBufLeft); 860 if (*currentBufLeft > decodedSize) { 861 // adjust/interpolate next time stamp 862 *currentBufLeft -= decodedSize; 863 *nextTimeStamp += mStreamInfo->aacSamplesPerFrame * 864 1000000ll / mStreamInfo->sampleRate; 865 ALOGV("adjusted nextTimeStamp/size to %lld/%d", 866 *nextTimeStamp, *currentBufLeft); 867 } else { 868 // move to next timestamp in list 869 if (mBufferTimestamps.size() > 0) { 870 mBufferTimestamps.removeAt(0); 871 nextTimeStamp = &mBufferTimestamps.editItemAt(0); 872 mBufferSizes.removeAt(0); 873 currentBufLeft = &mBufferSizes.editItemAt(0); 874 ALOGV("moved to next time/size: %lld/%d", 875 *nextTimeStamp, *currentBufLeft); 876 } 877 // try to limit output buffer size to match input buffers 878 // (e.g when an input buffer contained 4 "sub" frames, output 879 // at most 4 decoded units in the corresponding output buffer) 880 // This is optional. Remove the next three lines to fill the output 881 // buffer with as many units as available. 882 numFrames = i + 1; 883 numSamples = numFrames * mStreamInfo->frameSize * mStreamInfo->numChannels; 884 break; 885 } 886 } 887 888 ALOGV("getting %d from ringbuffer", numSamples); 889 int32_t ns = outputDelayRingBufferGetSamples(outBuffer, numSamples); 890 if (ns != numSamples) { 891 ALOGE("not a complete frame of samples available"); 892 mSignalledError = true; 893 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); 894 return; 895 } 896 } 897 898 outHeader->nFilledLen = numSamples * sizeof(int16_t); 899 900 if (mEndOfInput && !outQueue.empty() && outputDelayRingBufferSamplesAvailable() == 0) { 901 outHeader->nFlags = OMX_BUFFERFLAG_EOS; 902 mEndOfOutput = true; 903 } else { 904 outHeader->nFlags = 0; 905 } 906 907 outHeader->nTimeStamp = currentTime; 908 909 mOutputBufferCount++; 910 outInfo->mOwnedByUs = false; 911 outQueue.erase(outQueue.begin()); 912 outInfo = NULL; 913 ALOGV("out timestamp %lld / %d", outHeader->nTimeStamp, outHeader->nFilledLen); 914 notifyFillBufferDone(outHeader); 915 outHeader = NULL; 916 } 917 918 if (mEndOfInput) { 919 if (outputDelayRingBufferSamplesAvailable() > 0 920 && outputDelayRingBufferSamplesAvailable() 921 < mStreamInfo->frameSize * mStreamInfo->numChannels) { 922 ALOGE("not a complete frame of samples available"); 923 mSignalledError = true; 924 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); 925 return; 926 } 927 928 if (mEndOfInput && !outQueue.empty() && outputDelayRingBufferSamplesAvailable() == 0) { 929 if (!mEndOfOutput) { 930 // send empty block signaling EOS 931 mEndOfOutput = true; 932 BufferInfo *outInfo = *outQueue.begin(); 933 OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; 934 935 if (outHeader->nOffset != 0) { 936 ALOGE("outHeader->nOffset != 0 is not handled"); 937 mSignalledError = true; 938 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); 939 return; 940 } 941 942 INT_PCM *outBuffer = reinterpret_cast<INT_PCM *>(outHeader->pBuffer 943 + outHeader->nOffset); 944 int32_t ns = 0; 945 outHeader->nFilledLen = 0; 946 outHeader->nFlags = OMX_BUFFERFLAG_EOS; 947 948 outHeader->nTimeStamp = mBufferTimestamps.itemAt(0); 949 mBufferTimestamps.clear(); 950 mBufferSizes.clear(); 951 mDecodedSizes.clear(); 952 953 mOutputBufferCount++; 954 outInfo->mOwnedByUs = false; 955 outQueue.erase(outQueue.begin()); 956 outInfo = NULL; 957 notifyFillBufferDone(outHeader); 958 outHeader = NULL; 959 } 960 break; // if outQueue not empty but no more output 961 } 962 } 963 } 964} 965 966void SoftAAC2::onPortFlushCompleted(OMX_U32 portIndex) { 967 if (portIndex == 0) { 968 // Make sure that the next buffer output does not still 969 // depend on fragments from the last one decoded. 970 // drain all existing data 971 drainDecoder(); 972 mBufferTimestamps.clear(); 973 mBufferSizes.clear(); 974 mDecodedSizes.clear(); 975 mLastInHeader = NULL; 976 } else { 977 int avail; 978 while ((avail = outputDelayRingBufferSamplesAvailable()) > 0) { 979 if (avail > mStreamInfo->frameSize * mStreamInfo->numChannels) { 980 avail = mStreamInfo->frameSize * mStreamInfo->numChannels; 981 } 982 int32_t ns = outputDelayRingBufferGetSamples(0, avail); 983 if (ns != avail) { 984 ALOGE("not a complete frame of samples available"); 985 break; 986 } 987 mOutputBufferCount++; 988 } 989 mOutputDelayRingBufferReadPos = mOutputDelayRingBufferWritePos; 990 } 991} 992 993void SoftAAC2::drainDecoder() { 994 int32_t outputDelay = mStreamInfo->outputDelay * mStreamInfo->numChannels; 995 996 // flush decoder until outputDelay is compensated 997 while (mOutputDelayCompensated > 0) { 998 // a buffer big enough for MAX_CHANNEL_COUNT channels of decoded HE-AAC 999 INT_PCM tmpOutBuffer[2048 * MAX_CHANNEL_COUNT]; 1000 1001 // run DRC check 1002 mDrcWrap.submitStreamData(mStreamInfo); 1003 mDrcWrap.update(); 1004 1005 AAC_DECODER_ERROR decoderErr = 1006 aacDecoder_DecodeFrame(mAACDecoder, 1007 tmpOutBuffer, 1008 2048 * MAX_CHANNEL_COUNT, 1009 AACDEC_FLUSH); 1010 if (decoderErr != AAC_DEC_OK) { 1011 ALOGW("aacDecoder_DecodeFrame decoderErr = 0x%4.4x", decoderErr); 1012 } 1013 1014 int32_t tmpOutBufferSamples = mStreamInfo->frameSize * mStreamInfo->numChannels; 1015 if (tmpOutBufferSamples > mOutputDelayCompensated) { 1016 tmpOutBufferSamples = mOutputDelayCompensated; 1017 } 1018 outputDelayRingBufferPutSamples(tmpOutBuffer, tmpOutBufferSamples); 1019 1020 mOutputDelayCompensated -= tmpOutBufferSamples; 1021 } 1022} 1023 1024void SoftAAC2::onReset() { 1025 drainDecoder(); 1026 // reset the "configured" state 1027 mInputBufferCount = 0; 1028 mOutputBufferCount = 0; 1029 mOutputDelayCompensated = 0; 1030 mOutputDelayRingBufferWritePos = 0; 1031 mOutputDelayRingBufferReadPos = 0; 1032 mOutputDelayRingBufferFilled = 0; 1033 mEndOfInput = false; 1034 mEndOfOutput = false; 1035 mBufferTimestamps.clear(); 1036 mBufferSizes.clear(); 1037 mDecodedSizes.clear(); 1038 mLastInHeader = NULL; 1039 1040 // To make the codec behave the same before and after a reset, we need to invalidate the 1041 // streaminfo struct. This does that: 1042 mStreamInfo->sampleRate = 0; // TODO: mStreamInfo is read only 1043 1044 mSignalledError = false; 1045 mOutputPortSettingsChange = NONE; 1046} 1047 1048void SoftAAC2::onPortEnableCompleted(OMX_U32 portIndex, bool enabled) { 1049 if (portIndex != 1) { 1050 return; 1051 } 1052 1053 switch (mOutputPortSettingsChange) { 1054 case NONE: 1055 break; 1056 1057 case AWAITING_DISABLED: 1058 { 1059 CHECK(!enabled); 1060 mOutputPortSettingsChange = AWAITING_ENABLED; 1061 break; 1062 } 1063 1064 default: 1065 { 1066 CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED); 1067 CHECK(enabled); 1068 mOutputPortSettingsChange = NONE; 1069 break; 1070 } 1071 } 1072} 1073 1074} // namespace android 1075 1076android::SoftOMXComponent *createSoftOMXComponent( 1077 const char *name, const OMX_CALLBACKTYPE *callbacks, 1078 OMX_PTR appData, OMX_COMPONENTTYPE **component) { 1079 return new android::SoftAAC2(name, callbacks, appData, component); 1080} 1081