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