SoftAAC2.cpp revision 8484830a6b488b41da0e32acacf2e6b68060d9d0
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_TAG "SoftAAC2" 18//#define LOG_NDEBUG 0 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 mCurrentInputTime(0), 72 mOutputPortSettingsChange(NONE) { 73 initPorts(); 74 CHECK_EQ(initDecoder(), (status_t)OK); 75} 76 77SoftAAC2::~SoftAAC2() { 78 aacDecoder_Close(mAACDecoder); 79 delete mOutputDelayRingBuffer; 80} 81 82void SoftAAC2::initPorts() { 83 OMX_PARAM_PORTDEFINITIONTYPE def; 84 InitOMXParams(&def); 85 86 def.nPortIndex = 0; 87 def.eDir = OMX_DirInput; 88 def.nBufferCountMin = kNumInputBuffers; 89 def.nBufferCountActual = def.nBufferCountMin; 90 def.nBufferSize = 8192; 91 def.bEnabled = OMX_TRUE; 92 def.bPopulated = OMX_FALSE; 93 def.eDomain = OMX_PortDomainAudio; 94 def.bBuffersContiguous = OMX_FALSE; 95 def.nBufferAlignment = 1; 96 97 def.format.audio.cMIMEType = const_cast<char *>("audio/aac"); 98 def.format.audio.pNativeRender = NULL; 99 def.format.audio.bFlagErrorConcealment = OMX_FALSE; 100 def.format.audio.eEncoding = OMX_AUDIO_CodingAAC; 101 102 addPort(def); 103 104 def.nPortIndex = 1; 105 def.eDir = OMX_DirOutput; 106 def.nBufferCountMin = kNumOutputBuffers; 107 def.nBufferCountActual = def.nBufferCountMin; 108 def.nBufferSize = 4096 * MAX_CHANNEL_COUNT; 109 def.bEnabled = OMX_TRUE; 110 def.bPopulated = OMX_FALSE; 111 def.eDomain = OMX_PortDomainAudio; 112 def.bBuffersContiguous = OMX_FALSE; 113 def.nBufferAlignment = 2; 114 115 def.format.audio.cMIMEType = const_cast<char *>("audio/raw"); 116 def.format.audio.pNativeRender = NULL; 117 def.format.audio.bFlagErrorConcealment = OMX_FALSE; 118 def.format.audio.eEncoding = OMX_AUDIO_CodingPCM; 119 120 addPort(def); 121} 122 123status_t SoftAAC2::initDecoder() { 124 ALOGV("initDecoder()"); 125 status_t status = UNKNOWN_ERROR; 126 mAACDecoder = aacDecoder_Open(TT_MP4_ADIF, /* num layers */ 1); 127 if (mAACDecoder != NULL) { 128 mStreamInfo = aacDecoder_GetStreamInfo(mAACDecoder); 129 if (mStreamInfo != NULL) { 130 status = OK; 131 } 132 } 133 134 mEndOfInput = false; 135 mEndOfOutput = false; 136 mOutputDelayCompensated = 0; 137 mOutputDelayRingBufferSize = 2048 * MAX_CHANNEL_COUNT * kNumDelayBlocksMax; 138 mOutputDelayRingBuffer = new short[mOutputDelayRingBufferSize]; 139 mOutputDelayRingBufferWritePos = 0; 140 mOutputDelayRingBufferReadPos = 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 (mOutputDelayRingBufferWritePos + numSamples <= mOutputDelayRingBufferSize 413 && (mOutputDelayRingBufferReadPos <= mOutputDelayRingBufferWritePos 414 || mOutputDelayRingBufferReadPos > mOutputDelayRingBufferWritePos + numSamples)) { 415 // faster memcopy loop without checks, if the preconditions allow this 416 for (int32_t i = 0; i < numSamples; i++) { 417 mOutputDelayRingBuffer[mOutputDelayRingBufferWritePos++] = samples[i]; 418 } 419 420 if (mOutputDelayRingBufferWritePos >= mOutputDelayRingBufferSize) { 421 mOutputDelayRingBufferWritePos -= mOutputDelayRingBufferSize; 422 } 423 if (mOutputDelayRingBufferWritePos == mOutputDelayRingBufferReadPos) { 424 ALOGE("RING BUFFER OVERFLOW"); 425 return false; 426 } 427 } else { 428 ALOGV("slow SoftAAC2::outputDelayRingBufferPutSamples()"); 429 430 for (int32_t i = 0; i < numSamples; i++) { 431 mOutputDelayRingBuffer[mOutputDelayRingBufferWritePos] = samples[i]; 432 mOutputDelayRingBufferWritePos++; 433 if (mOutputDelayRingBufferWritePos >= mOutputDelayRingBufferSize) { 434 mOutputDelayRingBufferWritePos -= mOutputDelayRingBufferSize; 435 } 436 if (mOutputDelayRingBufferWritePos == mOutputDelayRingBufferReadPos) { 437 ALOGE("RING BUFFER OVERFLOW"); 438 return false; 439 } 440 } 441 } 442 return true; 443} 444 445int32_t SoftAAC2::outputDelayRingBufferGetSamples(INT_PCM *samples, int32_t numSamples) { 446 if (mOutputDelayRingBufferReadPos + numSamples <= mOutputDelayRingBufferSize 447 && (mOutputDelayRingBufferWritePos < mOutputDelayRingBufferReadPos 448 || mOutputDelayRingBufferWritePos >= mOutputDelayRingBufferReadPos + numSamples)) { 449 // faster memcopy loop without checks, if the preconditions allow this 450 if (samples != 0) { 451 for (int32_t i = 0; i < numSamples; i++) { 452 samples[i] = mOutputDelayRingBuffer[mOutputDelayRingBufferReadPos++]; 453 } 454 } else { 455 mOutputDelayRingBufferReadPos += numSamples; 456 } 457 if (mOutputDelayRingBufferReadPos >= mOutputDelayRingBufferSize) { 458 mOutputDelayRingBufferReadPos -= mOutputDelayRingBufferSize; 459 } 460 } else { 461 ALOGV("slow SoftAAC2::outputDelayRingBufferGetSamples()"); 462 463 for (int32_t i = 0; i < numSamples; i++) { 464 if (mOutputDelayRingBufferWritePos == mOutputDelayRingBufferReadPos) { 465 ALOGE("RING BUFFER UNDERRUN"); 466 return -1; 467 } 468 if (samples != 0) { 469 samples[i] = mOutputDelayRingBuffer[mOutputDelayRingBufferReadPos]; 470 } 471 mOutputDelayRingBufferReadPos++; 472 if (mOutputDelayRingBufferReadPos >= mOutputDelayRingBufferSize) { 473 mOutputDelayRingBufferReadPos -= mOutputDelayRingBufferSize; 474 } 475 } 476 } 477 return numSamples; 478} 479 480int32_t SoftAAC2::outputDelayRingBufferSamplesAvailable() { 481 int32_t available = mOutputDelayRingBufferWritePos - mOutputDelayRingBufferReadPos; 482 if (available < 0) { 483 available += mOutputDelayRingBufferSize; 484 } 485 if (available < 0) { 486 ALOGE("FATAL RING BUFFER ERROR"); 487 return 0; 488 } 489 return available; 490} 491 492int32_t SoftAAC2::outputDelayRingBufferSamplesLeft() { 493 return mOutputDelayRingBufferSize - outputDelayRingBufferSamplesAvailable(); 494} 495 496 497void SoftAAC2::onQueueFilled(OMX_U32 /* portIndex */) { 498 if (mSignalledError || mOutputPortSettingsChange != NONE) { 499 return; 500 } 501 502 UCHAR* inBuffer[FILEREAD_MAX_LAYERS]; 503 UINT inBufferLength[FILEREAD_MAX_LAYERS] = {0}; 504 UINT bytesValid[FILEREAD_MAX_LAYERS] = {0}; 505 506 List<BufferInfo *> &inQueue = getPortQueue(0); 507 List<BufferInfo *> &outQueue = getPortQueue(1); 508 509 while ((!inQueue.empty() || mEndOfInput) && !outQueue.empty()) { 510 if (!inQueue.empty()) { 511 INT_PCM tmpOutBuffer[2048 * MAX_CHANNEL_COUNT]; 512 BufferInfo *inInfo = *inQueue.begin(); 513 OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; 514 515 mEndOfInput = (inHeader->nFlags & OMX_BUFFERFLAG_EOS) != 0; 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 } else { 614 inBuffer[0] = inHeader->pBuffer + inHeader->nOffset; 615 inBufferLength[0] = inHeader->nFilledLen; 616 } 617 618 // Fill and decode 619 bytesValid[0] = inBufferLength[0]; 620 621 INT prevSampleRate = mStreamInfo->sampleRate; 622 INT prevNumChannels = mStreamInfo->numChannels; 623 624 if (inHeader != mLastInHeader) { 625 mLastInHeader = inHeader; 626 mCurrentInputTime = inHeader->nTimeStamp; 627 } else { 628 if (mStreamInfo->sampleRate) { 629 mCurrentInputTime += mStreamInfo->aacSamplesPerFrame * 630 1000000ll / mStreamInfo->sampleRate; 631 } else { 632 ALOGW("no sample rate yet"); 633 } 634 } 635 mAnchorTimes.add(mCurrentInputTime); 636 aacDecoder_Fill(mAACDecoder, 637 inBuffer, 638 inBufferLength, 639 bytesValid); 640 641 // run DRC check 642 mDrcWrap.submitStreamData(mStreamInfo); 643 mDrcWrap.update(); 644 645 AAC_DECODER_ERROR decoderErr = 646 aacDecoder_DecodeFrame(mAACDecoder, 647 tmpOutBuffer, 648 2048 * MAX_CHANNEL_COUNT, 649 0 /* flags */); 650 651 if (decoderErr != AAC_DEC_OK) { 652 ALOGW("aacDecoder_DecodeFrame decoderErr = 0x%4.4x", decoderErr); 653 } 654 655 if (decoderErr == AAC_DEC_NOT_ENOUGH_BITS) { 656 ALOGE("AAC_DEC_NOT_ENOUGH_BITS should never happen"); 657 mSignalledError = true; 658 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); 659 return; 660 } 661 662 if (bytesValid[0] != 0) { 663 ALOGE("bytesValid[0] != 0 should never happen"); 664 mSignalledError = true; 665 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); 666 return; 667 } 668 669 size_t numOutBytes = 670 mStreamInfo->frameSize * sizeof(int16_t) * mStreamInfo->numChannels; 671 672 if (decoderErr == AAC_DEC_OK) { 673 if (!outputDelayRingBufferPutSamples(tmpOutBuffer, 674 mStreamInfo->frameSize * mStreamInfo->numChannels)) { 675 mSignalledError = true; 676 notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL); 677 return; 678 } 679 UINT inBufferUsedLength = inBufferLength[0] - bytesValid[0]; 680 inHeader->nFilledLen -= inBufferUsedLength; 681 inHeader->nOffset += inBufferUsedLength; 682 } else { 683 ALOGW("AAC decoder returned error 0x%4.4x, substituting silence", decoderErr); 684 685 memset(tmpOutBuffer, 0, numOutBytes); // TODO: check for overflow 686 687 if (!outputDelayRingBufferPutSamples(tmpOutBuffer, 688 mStreamInfo->frameSize * mStreamInfo->numChannels)) { 689 mSignalledError = true; 690 notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL); 691 return; 692 } 693 694 // Discard input buffer. 695 inHeader->nFilledLen = 0; 696 697 aacDecoder_SetParam(mAACDecoder, AAC_TPDEC_CLEAR_BUFFER, 1); 698 699 // fall through 700 } 701 702 /* 703 * AAC+/eAAC+ streams can be signalled in two ways: either explicitly 704 * or implicitly, according to MPEG4 spec. AAC+/eAAC+ is a dual 705 * rate system and the sampling rate in the final output is actually 706 * doubled compared with the core AAC decoder sampling rate. 707 * 708 * Explicit signalling is done by explicitly defining SBR audio object 709 * type in the bitstream. Implicit signalling is done by embedding 710 * SBR content in AAC extension payload specific to SBR, and hence 711 * requires an AAC decoder to perform pre-checks on actual audio frames. 712 * 713 * Thus, we could not say for sure whether a stream is 714 * AAC+/eAAC+ until the first data frame is decoded. 715 */ 716 if (mInputBufferCount <= 2 || mOutputBufferCount > 1) { // TODO: <= 1 717 if (mStreamInfo->sampleRate != prevSampleRate || 718 mStreamInfo->numChannels != prevNumChannels) { 719 ALOGI("Reconfiguring decoder: %d->%d Hz, %d->%d channels", 720 prevSampleRate, mStreamInfo->sampleRate, 721 prevNumChannels, mStreamInfo->numChannels); 722 723 notify(OMX_EventPortSettingsChanged, 1, 0, NULL); 724 mOutputPortSettingsChange = AWAITING_DISABLED; 725 726 if (inHeader->nFilledLen == 0) { 727 inInfo->mOwnedByUs = false; 728 mInputBufferCount++; 729 inQueue.erase(inQueue.begin()); 730 mLastInHeader = NULL; 731 inInfo = NULL; 732 notifyEmptyBufferDone(inHeader); 733 inHeader = NULL; 734 } 735 return; 736 } 737 } else if (!mStreamInfo->sampleRate || !mStreamInfo->numChannels) { 738 ALOGW("Invalid AAC stream"); 739 mSignalledError = true; 740 notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL); 741 return; 742 } 743 if (inHeader->nFilledLen == 0) { 744 inInfo->mOwnedByUs = false; 745 mInputBufferCount++; 746 inQueue.erase(inQueue.begin()); 747 mLastInHeader = NULL; 748 inInfo = NULL; 749 notifyEmptyBufferDone(inHeader); 750 inHeader = NULL; 751 } else { 752 ALOGV("inHeader->nFilledLen = %d", inHeader->nFilledLen); 753 } 754 } 755 756 int32_t outputDelay = mStreamInfo->outputDelay * mStreamInfo->numChannels; 757 758 if (!mEndOfInput && mOutputDelayCompensated < outputDelay) { 759 // discard outputDelay at the beginning 760 int32_t toCompensate = outputDelay - mOutputDelayCompensated; 761 int32_t discard = outputDelayRingBufferSamplesAvailable(); 762 if (discard > toCompensate) { 763 discard = toCompensate; 764 } 765 int32_t discarded = outputDelayRingBufferGetSamples(0, discard); 766 mOutputDelayCompensated += discarded; 767 continue; 768 } 769 770 if (mEndOfInput) { 771 while (mOutputDelayCompensated > 0) { 772 // a buffer big enough for MAX_CHANNEL_COUNT channels of decoded HE-AAC 773 INT_PCM tmpOutBuffer[2048 * MAX_CHANNEL_COUNT]; 774 775 // run DRC check 776 mDrcWrap.submitStreamData(mStreamInfo); 777 mDrcWrap.update(); 778 779 AAC_DECODER_ERROR decoderErr = 780 aacDecoder_DecodeFrame(mAACDecoder, 781 tmpOutBuffer, 782 2048 * MAX_CHANNEL_COUNT, 783 AACDEC_FLUSH); 784 if (decoderErr != AAC_DEC_OK) { 785 ALOGW("aacDecoder_DecodeFrame decoderErr = 0x%4.4x", decoderErr); 786 } 787 788 int32_t tmpOutBufferSamples = mStreamInfo->frameSize * mStreamInfo->numChannels; 789 if (tmpOutBufferSamples > mOutputDelayCompensated) { 790 tmpOutBufferSamples = mOutputDelayCompensated; 791 } 792 outputDelayRingBufferPutSamples(tmpOutBuffer, tmpOutBufferSamples); 793 mOutputDelayCompensated -= tmpOutBufferSamples; 794 } 795 } 796 797 while (!outQueue.empty() 798 && outputDelayRingBufferSamplesAvailable() 799 >= mStreamInfo->frameSize * mStreamInfo->numChannels) { 800 BufferInfo *outInfo = *outQueue.begin(); 801 OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; 802 803 if (outHeader->nOffset != 0) { 804 ALOGE("outHeader->nOffset != 0 is not handled"); 805 mSignalledError = true; 806 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); 807 return; 808 } 809 810 INT_PCM *outBuffer = 811 reinterpret_cast<INT_PCM *>(outHeader->pBuffer + outHeader->nOffset); 812 if (outHeader->nOffset 813 + mStreamInfo->frameSize * mStreamInfo->numChannels * sizeof(int16_t) 814 > outHeader->nAllocLen) { 815 ALOGE("buffer overflow"); 816 mSignalledError = true; 817 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); 818 return; 819 820 } 821 int32_t ns = outputDelayRingBufferGetSamples(outBuffer, 822 mStreamInfo->frameSize * mStreamInfo->numChannels); // TODO: check for overflow 823 if (ns != mStreamInfo->frameSize * mStreamInfo->numChannels) { 824 ALOGE("not a complete frame of samples available"); 825 mSignalledError = true; 826 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); 827 return; 828 } 829 830 outHeader->nFilledLen = mStreamInfo->frameSize * mStreamInfo->numChannels 831 * sizeof(int16_t); 832 if (mEndOfInput && !outQueue.empty() && outputDelayRingBufferSamplesAvailable() == 0) { 833 outHeader->nFlags = OMX_BUFFERFLAG_EOS; 834 mEndOfOutput = true; 835 } else { 836 outHeader->nFlags = 0; 837 } 838 839 outHeader->nTimeStamp = mAnchorTimes.isEmpty() ? 0 : mAnchorTimes.itemAt(0); 840 mAnchorTimes.removeAt(0); 841 842 mOutputBufferCount++; 843 outInfo->mOwnedByUs = false; 844 outQueue.erase(outQueue.begin()); 845 outInfo = NULL; 846 notifyFillBufferDone(outHeader); 847 outHeader = NULL; 848 } 849 850 if (mEndOfInput) { 851 if (outputDelayRingBufferSamplesAvailable() > 0 852 && outputDelayRingBufferSamplesAvailable() 853 < mStreamInfo->frameSize * mStreamInfo->numChannels) { 854 ALOGE("not a complete frame of samples available"); 855 mSignalledError = true; 856 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); 857 return; 858 } 859 860 if (mEndOfInput && !outQueue.empty() && outputDelayRingBufferSamplesAvailable() == 0) { 861 if (!mEndOfOutput) { 862 // send empty block signaling EOS 863 mEndOfOutput = true; 864 BufferInfo *outInfo = *outQueue.begin(); 865 OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; 866 867 if (outHeader->nOffset != 0) { 868 ALOGE("outHeader->nOffset != 0 is not handled"); 869 mSignalledError = true; 870 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); 871 return; 872 } 873 874 INT_PCM *outBuffer = reinterpret_cast<INT_PCM *>(outHeader->pBuffer 875 + outHeader->nOffset); 876 int32_t ns = 0; 877 outHeader->nFilledLen = 0; 878 outHeader->nFlags = OMX_BUFFERFLAG_EOS; 879 880 outHeader->nTimeStamp = mAnchorTimes.itemAt(0); 881 mAnchorTimes.removeAt(0); 882 883 mOutputBufferCount++; 884 outInfo->mOwnedByUs = false; 885 outQueue.erase(outQueue.begin()); 886 outInfo = NULL; 887 notifyFillBufferDone(outHeader); 888 outHeader = NULL; 889 } 890 break; // if outQueue not empty but no more output 891 } 892 } 893 } 894} 895 896void SoftAAC2::onPortFlushCompleted(OMX_U32 portIndex) { 897 if (portIndex == 0) { 898 // Make sure that the next buffer output does not still 899 // depend on fragments from the last one decoded. 900 // drain all existing data 901 drainDecoder(); 902 mAnchorTimes.clear(); 903 mLastInHeader = NULL; 904 } else { 905 while (outputDelayRingBufferSamplesAvailable() > 0) { 906 int32_t ns = outputDelayRingBufferGetSamples(0, 907 mStreamInfo->frameSize * mStreamInfo->numChannels); 908 if (ns != mStreamInfo->frameSize * mStreamInfo->numChannels) { 909 ALOGE("not a complete frame of samples available"); 910 } 911 mOutputBufferCount++; 912 } 913 mOutputDelayRingBufferReadPos = mOutputDelayRingBufferWritePos; 914 } 915} 916 917void SoftAAC2::drainDecoder() { 918 int32_t outputDelay = mStreamInfo->outputDelay * mStreamInfo->numChannels; 919 920 // flush decoder until outputDelay is compensated 921 while (mOutputDelayCompensated > 0) { 922 // a buffer big enough for MAX_CHANNEL_COUNT channels of decoded HE-AAC 923 INT_PCM tmpOutBuffer[2048 * MAX_CHANNEL_COUNT]; 924 925 // run DRC check 926 mDrcWrap.submitStreamData(mStreamInfo); 927 mDrcWrap.update(); 928 929 AAC_DECODER_ERROR decoderErr = 930 aacDecoder_DecodeFrame(mAACDecoder, 931 tmpOutBuffer, 932 2048 * MAX_CHANNEL_COUNT, 933 AACDEC_FLUSH); 934 if (decoderErr != AAC_DEC_OK) { 935 ALOGW("aacDecoder_DecodeFrame decoderErr = 0x%4.4x", decoderErr); 936 } 937 938 int32_t tmpOutBufferSamples = mStreamInfo->frameSize * mStreamInfo->numChannels; 939 if (tmpOutBufferSamples > mOutputDelayCompensated) { 940 tmpOutBufferSamples = mOutputDelayCompensated; 941 } 942 outputDelayRingBufferPutSamples(tmpOutBuffer, tmpOutBufferSamples); 943 944 mOutputDelayCompensated -= tmpOutBufferSamples; 945 } 946} 947 948void SoftAAC2::onReset() { 949 drainDecoder(); 950 // reset the "configured" state 951 mInputBufferCount = 0; 952 mOutputBufferCount = 0; 953 mOutputDelayCompensated = 0; 954 mOutputDelayRingBufferWritePos = 0; 955 mOutputDelayRingBufferReadPos = 0; 956 mEndOfInput = false; 957 mEndOfOutput = false; 958 mAnchorTimes.clear(); 959 mLastInHeader = NULL; 960 961 // To make the codec behave the same before and after a reset, we need to invalidate the 962 // streaminfo struct. This does that: 963 mStreamInfo->sampleRate = 0; // TODO: mStreamInfo is read only 964 965 mSignalledError = false; 966 mOutputPortSettingsChange = NONE; 967} 968 969void SoftAAC2::onPortEnableCompleted(OMX_U32 portIndex, bool enabled) { 970 if (portIndex != 1) { 971 return; 972 } 973 974 switch (mOutputPortSettingsChange) { 975 case NONE: 976 break; 977 978 case AWAITING_DISABLED: 979 { 980 CHECK(!enabled); 981 mOutputPortSettingsChange = AWAITING_ENABLED; 982 break; 983 } 984 985 default: 986 { 987 CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED); 988 CHECK(enabled); 989 mOutputPortSettingsChange = NONE; 990 break; 991 } 992 } 993} 994 995} // namespace android 996 997android::SoftOMXComponent *createSoftOMXComponent( 998 const char *name, const OMX_CALLBACKTYPE *callbacks, 999 OMX_PTR appData, OMX_COMPONENTTYPE **component) { 1000 return new android::SoftAAC2(name, callbacks, appData, component); 1001} 1002