SoftAAC2.cpp revision a3d078b02d22ee2329e3778f63974be59296f64f
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 inHeader->nFilledLen = 0; 709 710 aacDecoder_SetParam(mAACDecoder, AAC_TPDEC_CLEAR_BUFFER, 1); 711 712 // fall through 713 } 714 715 /* 716 * AAC+/eAAC+ streams can be signalled in two ways: either explicitly 717 * or implicitly, according to MPEG4 spec. AAC+/eAAC+ is a dual 718 * rate system and the sampling rate in the final output is actually 719 * doubled compared with the core AAC decoder sampling rate. 720 * 721 * Explicit signalling is done by explicitly defining SBR audio object 722 * type in the bitstream. Implicit signalling is done by embedding 723 * SBR content in AAC extension payload specific to SBR, and hence 724 * requires an AAC decoder to perform pre-checks on actual audio frames. 725 * 726 * Thus, we could not say for sure whether a stream is 727 * AAC+/eAAC+ until the first data frame is decoded. 728 */ 729 if (mInputBufferCount <= 2 || mOutputBufferCount > 1) { // TODO: <= 1 730 if (mStreamInfo->sampleRate != prevSampleRate || 731 mStreamInfo->numChannels != prevNumChannels) { 732 ALOGI("Reconfiguring decoder: %d->%d Hz, %d->%d channels", 733 prevSampleRate, mStreamInfo->sampleRate, 734 prevNumChannels, mStreamInfo->numChannels); 735 736 notify(OMX_EventPortSettingsChanged, 1, 0, NULL); 737 mOutputPortSettingsChange = AWAITING_DISABLED; 738 739 if (inHeader->nFilledLen == 0) { 740 inInfo->mOwnedByUs = false; 741 mInputBufferCount++; 742 inQueue.erase(inQueue.begin()); 743 mLastInHeader = NULL; 744 inInfo = NULL; 745 notifyEmptyBufferDone(inHeader); 746 inHeader = NULL; 747 } 748 return; 749 } 750 } else if (!mStreamInfo->sampleRate || !mStreamInfo->numChannels) { 751 ALOGW("Invalid AAC stream"); 752 mSignalledError = true; 753 notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL); 754 return; 755 } 756 if (inHeader && inHeader->nFilledLen == 0) { 757 inInfo->mOwnedByUs = false; 758 mInputBufferCount++; 759 inQueue.erase(inQueue.begin()); 760 mLastInHeader = NULL; 761 inInfo = NULL; 762 notifyEmptyBufferDone(inHeader); 763 inHeader = NULL; 764 } else { 765 ALOGV("inHeader->nFilledLen = %d", inHeader ? inHeader->nFilledLen : 0); 766 } 767 } while (decoderErr == AAC_DEC_OK); 768 } 769 770 int32_t outputDelay = mStreamInfo->outputDelay * mStreamInfo->numChannels; 771 772 if (!mEndOfInput && mOutputDelayCompensated < outputDelay) { 773 // discard outputDelay at the beginning 774 int32_t toCompensate = outputDelay - mOutputDelayCompensated; 775 int32_t discard = outputDelayRingBufferSamplesAvailable(); 776 if (discard > toCompensate) { 777 discard = toCompensate; 778 } 779 int32_t discarded = outputDelayRingBufferGetSamples(0, discard); 780 mOutputDelayCompensated += discarded; 781 continue; 782 } 783 784 if (mEndOfInput) { 785 while (mOutputDelayCompensated > 0) { 786 // a buffer big enough for MAX_CHANNEL_COUNT channels of decoded HE-AAC 787 INT_PCM tmpOutBuffer[2048 * MAX_CHANNEL_COUNT]; 788 789 // run DRC check 790 mDrcWrap.submitStreamData(mStreamInfo); 791 mDrcWrap.update(); 792 793 AAC_DECODER_ERROR decoderErr = 794 aacDecoder_DecodeFrame(mAACDecoder, 795 tmpOutBuffer, 796 2048 * MAX_CHANNEL_COUNT, 797 AACDEC_FLUSH); 798 if (decoderErr != AAC_DEC_OK) { 799 ALOGW("aacDecoder_DecodeFrame decoderErr = 0x%4.4x", decoderErr); 800 } 801 802 int32_t tmpOutBufferSamples = mStreamInfo->frameSize * mStreamInfo->numChannels; 803 if (tmpOutBufferSamples > mOutputDelayCompensated) { 804 tmpOutBufferSamples = mOutputDelayCompensated; 805 } 806 outputDelayRingBufferPutSamples(tmpOutBuffer, tmpOutBufferSamples); 807 mOutputDelayCompensated -= tmpOutBufferSamples; 808 } 809 } 810 811 while (!outQueue.empty() 812 && outputDelayRingBufferSamplesAvailable() 813 >= mStreamInfo->frameSize * mStreamInfo->numChannels) { 814 BufferInfo *outInfo = *outQueue.begin(); 815 OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; 816 817 if (outHeader->nOffset != 0) { 818 ALOGE("outHeader->nOffset != 0 is not handled"); 819 mSignalledError = true; 820 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); 821 return; 822 } 823 824 INT_PCM *outBuffer = 825 reinterpret_cast<INT_PCM *>(outHeader->pBuffer + outHeader->nOffset); 826 int samplesize = mStreamInfo->numChannels * sizeof(int16_t); 827 if (outHeader->nOffset 828 + mStreamInfo->frameSize * samplesize 829 > outHeader->nAllocLen) { 830 ALOGE("buffer overflow"); 831 mSignalledError = true; 832 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); 833 return; 834 835 } 836 837 int available = outputDelayRingBufferSamplesAvailable(); 838 int numSamples = outHeader->nAllocLen / sizeof(int16_t); 839 if (numSamples > available) { 840 numSamples = available; 841 } 842 int64_t currentTime = 0; 843 if (available) { 844 845 int numFrames = numSamples / (mStreamInfo->frameSize * mStreamInfo->numChannels); 846 numSamples = numFrames * (mStreamInfo->frameSize * mStreamInfo->numChannels); 847 848 ALOGV("%d samples available (%d), or %d frames", 849 numSamples, available, numFrames); 850 int64_t *nextTimeStamp = &mBufferTimestamps.editItemAt(0); 851 currentTime = *nextTimeStamp; 852 int32_t *currentBufLeft = &mBufferSizes.editItemAt(0); 853 for (int i = 0; i < numFrames; i++) { 854 int32_t decodedSize = mDecodedSizes.itemAt(0); 855 mDecodedSizes.removeAt(0); 856 ALOGV("decoded %d of %d", decodedSize, *currentBufLeft); 857 if (*currentBufLeft > decodedSize) { 858 // adjust/interpolate next time stamp 859 *currentBufLeft -= decodedSize; 860 *nextTimeStamp += mStreamInfo->aacSamplesPerFrame * 861 1000000ll / mStreamInfo->sampleRate; 862 ALOGV("adjusted nextTimeStamp/size to %lld/%d", 863 *nextTimeStamp, *currentBufLeft); 864 } else { 865 // move to next timestamp in list 866 if (mBufferTimestamps.size() > 0) { 867 mBufferTimestamps.removeAt(0); 868 nextTimeStamp = &mBufferTimestamps.editItemAt(0); 869 mBufferSizes.removeAt(0); 870 currentBufLeft = &mBufferSizes.editItemAt(0); 871 ALOGV("moved to next time/size: %lld/%d", 872 *nextTimeStamp, *currentBufLeft); 873 } 874 // try to limit output buffer size to match input buffers 875 // (e.g when an input buffer contained 4 "sub" frames, output 876 // at most 4 decoded units in the corresponding output buffer) 877 // This is optional. Remove the next three lines to fill the output 878 // buffer with as many units as available. 879 numFrames = i + 1; 880 numSamples = numFrames * mStreamInfo->frameSize * mStreamInfo->numChannels; 881 break; 882 } 883 } 884 885 ALOGV("getting %d from ringbuffer", numSamples); 886 int32_t ns = outputDelayRingBufferGetSamples(outBuffer, numSamples); 887 if (ns != numSamples) { 888 ALOGE("not a complete frame of samples available"); 889 mSignalledError = true; 890 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); 891 return; 892 } 893 } 894 895 outHeader->nFilledLen = numSamples * sizeof(int16_t); 896 897 if (mEndOfInput && !outQueue.empty() && outputDelayRingBufferSamplesAvailable() == 0) { 898 outHeader->nFlags = OMX_BUFFERFLAG_EOS; 899 mEndOfOutput = true; 900 } else { 901 outHeader->nFlags = 0; 902 } 903 904 outHeader->nTimeStamp = currentTime; 905 906 mOutputBufferCount++; 907 outInfo->mOwnedByUs = false; 908 outQueue.erase(outQueue.begin()); 909 outInfo = NULL; 910 ALOGV("out timestamp %lld / %d", outHeader->nTimeStamp, outHeader->nFilledLen); 911 notifyFillBufferDone(outHeader); 912 outHeader = NULL; 913 } 914 915 if (mEndOfInput) { 916 if (outputDelayRingBufferSamplesAvailable() > 0 917 && outputDelayRingBufferSamplesAvailable() 918 < mStreamInfo->frameSize * mStreamInfo->numChannels) { 919 ALOGE("not a complete frame of samples available"); 920 mSignalledError = true; 921 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); 922 return; 923 } 924 925 if (mEndOfInput && !outQueue.empty() && outputDelayRingBufferSamplesAvailable() == 0) { 926 if (!mEndOfOutput) { 927 // send empty block signaling EOS 928 mEndOfOutput = true; 929 BufferInfo *outInfo = *outQueue.begin(); 930 OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; 931 932 if (outHeader->nOffset != 0) { 933 ALOGE("outHeader->nOffset != 0 is not handled"); 934 mSignalledError = true; 935 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); 936 return; 937 } 938 939 INT_PCM *outBuffer = reinterpret_cast<INT_PCM *>(outHeader->pBuffer 940 + outHeader->nOffset); 941 int32_t ns = 0; 942 outHeader->nFilledLen = 0; 943 outHeader->nFlags = OMX_BUFFERFLAG_EOS; 944 945 outHeader->nTimeStamp = mBufferTimestamps.itemAt(0); 946 mBufferTimestamps.clear(); 947 mBufferSizes.clear(); 948 mDecodedSizes.clear(); 949 950 mOutputBufferCount++; 951 outInfo->mOwnedByUs = false; 952 outQueue.erase(outQueue.begin()); 953 outInfo = NULL; 954 notifyFillBufferDone(outHeader); 955 outHeader = NULL; 956 } 957 break; // if outQueue not empty but no more output 958 } 959 } 960 } 961} 962 963void SoftAAC2::onPortFlushCompleted(OMX_U32 portIndex) { 964 if (portIndex == 0) { 965 // Make sure that the next buffer output does not still 966 // depend on fragments from the last one decoded. 967 // drain all existing data 968 drainDecoder(); 969 mBufferTimestamps.clear(); 970 mBufferSizes.clear(); 971 mDecodedSizes.clear(); 972 mLastInHeader = NULL; 973 } else { 974 while (outputDelayRingBufferSamplesAvailable() > 0) { 975 int32_t ns = outputDelayRingBufferGetSamples(0, 976 mStreamInfo->frameSize * mStreamInfo->numChannels); 977 if (ns != mStreamInfo->frameSize * mStreamInfo->numChannels) { 978 ALOGE("not a complete frame of samples available"); 979 } 980 mOutputBufferCount++; 981 } 982 mOutputDelayRingBufferReadPos = mOutputDelayRingBufferWritePos; 983 } 984} 985 986void SoftAAC2::drainDecoder() { 987 int32_t outputDelay = mStreamInfo->outputDelay * mStreamInfo->numChannels; 988 989 // flush decoder until outputDelay is compensated 990 while (mOutputDelayCompensated > 0) { 991 // a buffer big enough for MAX_CHANNEL_COUNT channels of decoded HE-AAC 992 INT_PCM tmpOutBuffer[2048 * MAX_CHANNEL_COUNT]; 993 994 // run DRC check 995 mDrcWrap.submitStreamData(mStreamInfo); 996 mDrcWrap.update(); 997 998 AAC_DECODER_ERROR decoderErr = 999 aacDecoder_DecodeFrame(mAACDecoder, 1000 tmpOutBuffer, 1001 2048 * MAX_CHANNEL_COUNT, 1002 AACDEC_FLUSH); 1003 if (decoderErr != AAC_DEC_OK) { 1004 ALOGW("aacDecoder_DecodeFrame decoderErr = 0x%4.4x", decoderErr); 1005 } 1006 1007 int32_t tmpOutBufferSamples = mStreamInfo->frameSize * mStreamInfo->numChannels; 1008 if (tmpOutBufferSamples > mOutputDelayCompensated) { 1009 tmpOutBufferSamples = mOutputDelayCompensated; 1010 } 1011 outputDelayRingBufferPutSamples(tmpOutBuffer, tmpOutBufferSamples); 1012 1013 mOutputDelayCompensated -= tmpOutBufferSamples; 1014 } 1015} 1016 1017void SoftAAC2::onReset() { 1018 drainDecoder(); 1019 // reset the "configured" state 1020 mInputBufferCount = 0; 1021 mOutputBufferCount = 0; 1022 mOutputDelayCompensated = 0; 1023 mOutputDelayRingBufferWritePos = 0; 1024 mOutputDelayRingBufferReadPos = 0; 1025 mEndOfInput = false; 1026 mEndOfOutput = false; 1027 mBufferTimestamps.clear(); 1028 mBufferSizes.clear(); 1029 mDecodedSizes.clear(); 1030 mLastInHeader = NULL; 1031 1032 // To make the codec behave the same before and after a reset, we need to invalidate the 1033 // streaminfo struct. This does that: 1034 mStreamInfo->sampleRate = 0; // TODO: mStreamInfo is read only 1035 1036 mSignalledError = false; 1037 mOutputPortSettingsChange = NONE; 1038} 1039 1040void SoftAAC2::onPortEnableCompleted(OMX_U32 portIndex, bool enabled) { 1041 if (portIndex != 1) { 1042 return; 1043 } 1044 1045 switch (mOutputPortSettingsChange) { 1046 case NONE: 1047 break; 1048 1049 case AWAITING_DISABLED: 1050 { 1051 CHECK(!enabled); 1052 mOutputPortSettingsChange = AWAITING_ENABLED; 1053 break; 1054 } 1055 1056 default: 1057 { 1058 CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED); 1059 CHECK(enabled); 1060 mOutputPortSettingsChange = NONE; 1061 break; 1062 } 1063 } 1064} 1065 1066} // namespace android 1067 1068android::SoftOMXComponent *createSoftOMXComponent( 1069 const char *name, const OMX_CALLBACKTYPE *callbacks, 1070 OMX_PTR appData, OMX_COMPONENTTYPE **component) { 1071 return new android::SoftAAC2(name, callbacks, appData, component); 1072} 1073