AACEncoder.cpp revision 065d1aff96818df54456053f1574aec8a234d0de
1/*
2 * Copyright (C) 2010 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 "AACEncoder"
19#include <utils/Log.h>
20
21#include "AACEncoder.h"
22#include "voAAC.h"
23#include "cmnMemory.h"
24
25#include <media/stagefright/MediaBufferGroup.h>
26#include <media/stagefright/MediaDebug.h>
27#include <media/stagefright/MediaDefs.h>
28#include <media/stagefright/MediaErrors.h>
29#include <media/stagefright/MetaData.h>
30
31namespace android {
32
33AACEncoder::AACEncoder(const sp<MediaSource> &source, const sp<MetaData> &meta)
34    : mSource(source),
35      mMeta(meta),
36      mStarted(false),
37      mBufferGroup(NULL),
38      mInputBuffer(NULL),
39      mEncoderHandle(NULL),
40      mApiHandle(NULL),
41      mMemOperator(NULL) {
42}
43
44status_t AACEncoder::initCheck() {
45    CHECK(mApiHandle == NULL && mEncoderHandle == NULL);
46    CHECK(mMeta->findInt32(kKeySampleRate, &mSampleRate));
47    CHECK(mMeta->findInt32(kKeyChannelCount, &mChannels));
48    CHECK(mMeta->findInt32(kKeyBitRate, &mBitRate));
49
50    mApiHandle = new VO_AUDIO_CODECAPI;
51    CHECK(mApiHandle);
52
53    if (VO_ERR_NONE != voGetAACEncAPI(mApiHandle)) {
54        LOGE("Failed to get api handle");
55        return UNKNOWN_ERROR;
56    }
57
58    mMemOperator = new VO_MEM_OPERATOR;
59    CHECK(mMemOperator != NULL);
60    mMemOperator->Alloc = cmnMemAlloc;
61    mMemOperator->Copy = cmnMemCopy;
62    mMemOperator->Free = cmnMemFree;
63    mMemOperator->Set = cmnMemSet;
64    mMemOperator->Check = cmnMemCheck;
65
66    VO_CODEC_INIT_USERDATA userData;
67    memset(&userData, 0, sizeof(userData));
68    userData.memflag = VO_IMF_USERMEMOPERATOR;
69    userData.memData = (VO_PTR) mMemOperator;
70    if (VO_ERR_NONE != mApiHandle->Init(&mEncoderHandle, VO_AUDIO_CodingAAC, &userData)) {
71        LOGE("Failed to init AAC encoder");
72        return UNKNOWN_ERROR;
73    }
74    if (OK != setAudioSpecificConfigData()) {
75        LOGE("Failed to configure AAC encoder");
76        return UNKNOWN_ERROR;
77    }
78
79    // Configure AAC encoder$
80    AACENC_PARAM params;
81    memset(&params, 0, sizeof(params));
82    params.sampleRate = mSampleRate;
83    params.bitRate = mBitRate;
84    params.nChannels = mChannels;
85    params.adtsUsed = 0;  // For MP4 file, don't use adts format$
86    if (VO_ERR_NONE != mApiHandle->SetParam(mEncoderHandle, VO_PID_AAC_ENCPARAM,  &params)) {
87        LOGE("Failed to set AAC encoder parameters");
88        return UNKNOWN_ERROR;
89    }
90
91    return OK;
92}
93
94static status_t getSampleRateTableIndex(int32_t sampleRate, int32_t &index) {
95    static const int32_t kSampleRateTable[] = {
96        96000, 88200, 64000, 48000, 44100, 32000,
97        24000, 22050, 16000, 12000, 11025, 8000
98    };
99    const int32_t tableSize = sizeof(kSampleRateTable) / sizeof(kSampleRateTable[0]);
100    for (int32_t i = 0; i < tableSize; ++i) {
101        if (sampleRate == kSampleRateTable[i]) {
102            index = i;
103            return OK;
104        }
105    }
106
107    LOGE("Sampling rate %d bps is not supported", sampleRate);
108    return UNKNOWN_ERROR;
109}
110
111status_t AACEncoder::setAudioSpecificConfigData() {
112    LOGV("setAudioSpecificConfigData: %d hz, %d bps, and %d channels",
113         mSampleRate, mBitRate, mChannels);
114
115    int32_t index;
116    CHECK_EQ(OK, getSampleRateTableIndex(mSampleRate, index));
117    if (mChannels > 2 || mChannels <= 0) {
118        LOGE("Unsupported number of channels(%d)", mChannels);
119        return UNKNOWN_ERROR;
120    }
121
122    // OMX_AUDIO_AACObjectLC
123    mAudioSpecificConfigData[0] = ((0x02 << 3) | (index >> 1));
124    mAudioSpecificConfigData[1] = ((index & 0x01) << 7) | (mChannels << 3);
125    return OK;
126}
127
128AACEncoder::~AACEncoder() {
129    if (mStarted) {
130        stop();
131    }
132}
133
134status_t AACEncoder::start(MetaData *params) {
135    CHECK(!mStarted);
136
137    mBufferGroup = new MediaBufferGroup;
138    mBufferGroup->add_buffer(new MediaBuffer(2048));
139
140    CHECK_EQ(OK, initCheck());
141
142    mNumInputSamples = 0;
143    mAnchorTimeUs = 0;
144    mFrameCount = 0;
145    mSource->start(params);
146
147    mStarted = true;
148
149    return OK;
150}
151
152status_t AACEncoder::stop() {
153    CHECK(mStarted);
154
155    if (mInputBuffer) {
156        mInputBuffer->release();
157        mInputBuffer = NULL;
158    }
159
160    delete mBufferGroup;
161    mBufferGroup = NULL;
162
163    mSource->stop();
164
165    if (mEncoderHandle) {
166        CHECK_EQ(VO_ERR_NONE, mApiHandle->Uninit(mEncoderHandle));
167        mEncoderHandle = NULL;
168    }
169    delete mApiHandle;
170    mApiHandle = NULL;
171
172    mStarted = false;
173
174    return OK;
175}
176
177sp<MetaData> AACEncoder::getFormat() {
178    sp<MetaData> srcFormat = mSource->getFormat();
179
180    mMeta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
181
182    int64_t durationUs;
183    if (srcFormat->findInt64(kKeyDuration, &durationUs)) {
184        mMeta->setInt64(kKeyDuration, durationUs);
185    }
186
187    mMeta->setCString(kKeyDecoderComponent, "AACEncoder");
188
189    return mMeta;
190}
191
192status_t AACEncoder::read(
193        MediaBuffer **out, const ReadOptions *options) {
194    status_t err;
195
196    *out = NULL;
197
198    int64_t seekTimeUs;
199    CHECK(options == NULL || !options->getSeekTo(&seekTimeUs));
200
201    MediaBuffer *buffer;
202    CHECK_EQ(mBufferGroup->acquire_buffer(&buffer), OK);
203    uint8_t *outPtr = (uint8_t *)buffer->data();
204
205    if (mFrameCount == 0) {
206        memcpy(outPtr, mAudioSpecificConfigData, 2);
207        buffer->set_range(0, 2);
208        buffer->meta_data()->setInt32(kKeyIsCodecConfig, true);
209        *out = buffer;
210        ++mFrameCount;
211        return OK;
212    } else if (mFrameCount == 1) {
213        buffer->meta_data()->setInt32(kKeyIsCodecConfig, false);
214    }
215
216    while (mNumInputSamples < kNumSamplesPerFrame) {
217        if (mInputBuffer == NULL) {
218            if (mSource->read(&mInputBuffer, options) != OK) {
219                if (mNumInputSamples == 0) {
220                    return ERROR_END_OF_STREAM;
221                }
222                memset(&mInputFrame[mNumInputSamples],
223                       0,
224                       sizeof(int16_t) * (kNumSamplesPerFrame - mNumInputSamples));
225                mNumInputSamples = 0;
226                break;
227            }
228
229            size_t align = mInputBuffer->range_length() % sizeof(int16_t);
230            CHECK_EQ(align, 0);
231
232            int64_t timeUs;
233            if (mInputBuffer->meta_data()->findInt64(kKeyTime, &timeUs)) {
234                mAnchorTimeUs = timeUs;
235            }
236        }
237        size_t copy =
238            (kNumSamplesPerFrame - mNumInputSamples) * sizeof(int16_t);
239
240        if (copy > mInputBuffer->range_length()) {
241            copy = mInputBuffer->range_length();
242        }
243
244        memcpy(&mInputFrame[mNumInputSamples],
245               (const uint8_t *) mInputBuffer->data()
246                    + mInputBuffer->range_offset(),
247               copy);
248
249        mInputBuffer->set_range(
250               mInputBuffer->range_offset() + copy,
251               mInputBuffer->range_length() - copy);
252
253        if (mInputBuffer->range_length() == 0) {
254            mInputBuffer->release();
255            mInputBuffer = NULL;
256        }
257        mNumInputSamples += copy / sizeof(int16_t);
258        if (mNumInputSamples >= kNumSamplesPerFrame) {
259            mNumInputSamples %= kNumSamplesPerFrame;
260            break;
261        }
262    }
263
264    VO_CODECBUFFER inputData;
265    memset(&inputData, 0, sizeof(inputData));
266    inputData.Buffer = (unsigned char*) mInputFrame;
267    inputData.Length = kNumSamplesPerFrame * sizeof(int16_t);
268    CHECK(VO_ERR_NONE == mApiHandle->SetInputData(mEncoderHandle,&inputData));
269
270    VO_CODECBUFFER outputData;
271    memset(&outputData, 0, sizeof(outputData));
272    VO_AUDIO_OUTPUTINFO outputInfo;
273    memset(&outputInfo, 0, sizeof(outputInfo));
274
275    VO_U32 ret = VO_ERR_NONE;
276    outputData.Buffer = outPtr;
277    outputData.Length = buffer->size();
278    ret = mApiHandle->GetOutputData(mEncoderHandle, &outputData, &outputInfo);
279    CHECK(ret == VO_ERR_NONE || ret == VO_ERR_INPUT_BUFFER_SMALL);
280    CHECK(outputData.Length != 0);
281    buffer->set_range(0, outputData.Length);
282
283    int64_t timestampUs = ((mFrameCount - 1) * 1000000LL * kNumSamplesPerFrame) / mSampleRate;
284    ++mFrameCount;
285    buffer->meta_data()->setInt64(kKeyTime, timestampUs);
286
287    *out = buffer;
288    return OK;
289}
290
291}  // namespace android
292