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