blob: 4db94f51cdc03a1e37bab966c257ecd1eb5892b1 [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
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 "C2SoftAacEnc"
19#include <utils/Log.h>
20
21#include <inttypes.h>
22
23#include <C2PlatformSupport.h>
24#include <SimpleC2Interface.h>
25#include <media/stagefright/foundation/MediaDefs.h>
26#include <media/stagefright/foundation/hexdump.h>
27
28#include "C2SoftAacEnc.h"
29
30namespace android {
31
Rakesh Kumar66d9d062019-03-12 17:46:17 +053032namespace {
33
34constexpr char COMPONENT_NAME[] = "c2.android.aac.encoder";
35
36} // namespace
37
38class C2SoftAacEnc::IntfImpl : public SimpleInterface<void>::BaseParams {
Pawin Vongmasa36653902018-11-15 00:10:25 -080039public:
40 explicit IntfImpl(const std::shared_ptr<C2ReflectorHelper> &helper)
Rakesh Kumar66d9d062019-03-12 17:46:17 +053041 : SimpleInterface<void>::BaseParams(
42 helper,
43 COMPONENT_NAME,
44 C2Component::KIND_ENCODER,
45 C2Component::DOMAIN_AUDIO,
46 MEDIA_MIMETYPE_AUDIO_AAC) {
47 noPrivateBuffers();
48 noInputReferences();
49 noOutputReferences();
50 noInputLatency();
51 noTimeStretch();
Pawin Vongmasa36653902018-11-15 00:10:25 -080052 setDerivedInstance(this);
53
54 addParameter(
Rakesh Kumar66d9d062019-03-12 17:46:17 +053055 DefineParam(mAttrib, C2_PARAMKEY_COMPONENT_ATTRIBUTES)
56 .withConstValue(new C2ComponentAttributesSetting(
57 C2Component::ATTRIB_IS_TEMPORAL))
Pawin Vongmasa36653902018-11-15 00:10:25 -080058 .build());
59
60 addParameter(
Lajos Molnar3bb81cd2019-02-20 15:10:30 -080061 DefineParam(mSampleRate, C2_PARAMKEY_SAMPLE_RATE)
Pawin Vongmasa36653902018-11-15 00:10:25 -080062 .withDefault(new C2StreamSampleRateInfo::input(0u, 44100))
63 .withFields({C2F(mSampleRate, value).oneOf({
64 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000
65 })})
66 .withSetter((Setter<decltype(*mSampleRate)>::StrictValueWithNoDeps))
67 .build());
68
69 addParameter(
Lajos Molnar3bb81cd2019-02-20 15:10:30 -080070 DefineParam(mChannelCount, C2_PARAMKEY_CHANNEL_COUNT)
Pawin Vongmasa36653902018-11-15 00:10:25 -080071 .withDefault(new C2StreamChannelCountInfo::input(0u, 1))
72 .withFields({C2F(mChannelCount, value).inRange(1, 6)})
73 .withSetter(Setter<decltype(*mChannelCount)>::StrictValueWithNoDeps)
74 .build());
75
76 addParameter(
Lajos Molnar3bb81cd2019-02-20 15:10:30 -080077 DefineParam(mBitrate, C2_PARAMKEY_BITRATE)
78 .withDefault(new C2StreamBitrateInfo::output(0u, 64000))
Pawin Vongmasa36653902018-11-15 00:10:25 -080079 .withFields({C2F(mBitrate, value).inRange(8000, 960000)})
80 .withSetter(Setter<decltype(*mBitrate)>::NonStrictValueWithNoDeps)
81 .build());
82
83 addParameter(
84 DefineParam(mInputMaxBufSize, C2_PARAMKEY_INPUT_MAX_BUFFER_SIZE)
85 .withDefault(new C2StreamMaxBufferSizeInfo::input(0u, 8192))
86 .calculatedAs(MaxBufSizeCalculator, mChannelCount)
87 .build());
88
89 addParameter(
90 DefineParam(mProfileLevel, C2_PARAMKEY_PROFILE_LEVEL)
91 .withDefault(new C2StreamProfileLevelInfo::output(0u,
92 C2Config::PROFILE_AAC_LC, C2Config::LEVEL_UNUSED))
93 .withFields({
94 C2F(mProfileLevel, profile).oneOf({
95 C2Config::PROFILE_AAC_LC,
96 C2Config::PROFILE_AAC_HE,
97 C2Config::PROFILE_AAC_HE_PS,
98 C2Config::PROFILE_AAC_LD,
99 C2Config::PROFILE_AAC_ELD}),
100 C2F(mProfileLevel, level).oneOf({
101 C2Config::LEVEL_UNUSED
102 })
103 })
104 .withSetter(ProfileLevelSetter)
105 .build());
Manisha Jajoob09409a2019-05-23 18:57:52 +0530106
107 addParameter(
108 DefineParam(mSBRMode, C2_PARAMKEY_AAC_SBR_MODE)
109 .withDefault(new C2StreamAacSbrModeTuning::input(0u, AAC_SBR_AUTO))
110 .withFields({C2F(mSBRMode, value).oneOf({
111 C2Config::AAC_SBR_OFF,
112 C2Config::AAC_SBR_SINGLE_RATE,
113 C2Config::AAC_SBR_DUAL_RATE,
114 C2Config::AAC_SBR_AUTO })})
115 .withSetter(Setter<decltype(*mSBRMode)>::NonStrictValueWithNoDeps)
116 .build());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800117 }
118
119 uint32_t getSampleRate() const { return mSampleRate->value; }
120 uint32_t getChannelCount() const { return mChannelCount->value; }
121 uint32_t getBitrate() const { return mBitrate->value; }
Manisha Jajoob09409a2019-05-23 18:57:52 +0530122 uint32_t getSBRMode() const { return mSBRMode->value; }
123 uint32_t getProfile() const { return mProfileLevel->profile; }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800124 static C2R ProfileLevelSetter(bool mayBlock, C2P<C2StreamProfileLevelInfo::output> &me) {
125 (void)mayBlock;
126 (void)me; // TODO: validate
127 return C2R::Ok();
128 }
129
130 static C2R MaxBufSizeCalculator(
131 bool mayBlock,
132 C2P<C2StreamMaxBufferSizeInfo::input> &me,
133 const C2P<C2StreamChannelCountInfo::input> &channelCount) {
134 (void)mayBlock;
135 me.set().value = 1024 * sizeof(short) * channelCount.v.value;
136 return C2R::Ok();
137 }
138
139private:
Pawin Vongmasa36653902018-11-15 00:10:25 -0800140 std::shared_ptr<C2StreamSampleRateInfo::input> mSampleRate;
141 std::shared_ptr<C2StreamChannelCountInfo::input> mChannelCount;
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800142 std::shared_ptr<C2StreamBitrateInfo::output> mBitrate;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800143 std::shared_ptr<C2StreamMaxBufferSizeInfo::input> mInputMaxBufSize;
144 std::shared_ptr<C2StreamProfileLevelInfo::output> mProfileLevel;
Manisha Jajoob09409a2019-05-23 18:57:52 +0530145 std::shared_ptr<C2StreamAacSbrModeTuning::input> mSBRMode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800146};
147
Pawin Vongmasa36653902018-11-15 00:10:25 -0800148C2SoftAacEnc::C2SoftAacEnc(
149 const char *name,
150 c2_node_id_t id,
151 const std::shared_ptr<IntfImpl> &intfImpl)
152 : SimpleC2Component(std::make_shared<SimpleInterface<IntfImpl>>(name, id, intfImpl)),
153 mIntf(intfImpl),
154 mAACEncoder(nullptr),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800155 mNumBytesPerInputFrame(0u),
156 mOutBufferSize(0u),
157 mSentCodecSpecificData(false),
158 mInputSize(0),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800159 mSignalledError(false),
Wonsik Kim3dd7bd32019-08-09 10:35:55 -0700160 mOutIndex(0u),
161 mRemainderLen(0u) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800162}
163
164C2SoftAacEnc::~C2SoftAacEnc() {
165 onReset();
166}
167
168c2_status_t C2SoftAacEnc::onInit() {
169 status_t err = initEncoder();
170 return err == OK ? C2_OK : C2_CORRUPTED;
171}
172
173status_t C2SoftAacEnc::initEncoder() {
174 if (AACENC_OK != aacEncOpen(&mAACEncoder, 0, 0)) {
175 ALOGE("Failed to init AAC encoder");
176 return UNKNOWN_ERROR;
177 }
178 return setAudioParams();
179}
180
181c2_status_t C2SoftAacEnc::onStop() {
182 mSentCodecSpecificData = false;
183 mInputSize = 0u;
Wonsik Kim22748042019-11-01 10:33:16 -0700184 mNextFrameTimestampUs.reset();
185 mLastFrameEndTimestampUs.reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800186 mSignalledError = false;
Wonsik Kim3dd7bd32019-08-09 10:35:55 -0700187 mRemainderLen = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800188 return C2_OK;
189}
190
191void C2SoftAacEnc::onReset() {
192 (void)onStop();
193 aacEncClose(&mAACEncoder);
194}
195
196void C2SoftAacEnc::onRelease() {
197 // no-op
198}
199
200c2_status_t C2SoftAacEnc::onFlush_sm() {
201 mSentCodecSpecificData = false;
202 mInputSize = 0u;
Wonsik Kim22748042019-11-01 10:33:16 -0700203 mNextFrameTimestampUs.reset();
204 mLastFrameEndTimestampUs.reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800205 return C2_OK;
206}
207
208static CHANNEL_MODE getChannelMode(uint32_t nChannels) {
209 CHANNEL_MODE chMode = MODE_INVALID;
210 switch (nChannels) {
211 case 1: chMode = MODE_1; break;
212 case 2: chMode = MODE_2; break;
213 case 3: chMode = MODE_1_2; break;
214 case 4: chMode = MODE_1_2_1; break;
215 case 5: chMode = MODE_1_2_2; break;
216 case 6: chMode = MODE_1_2_2_1; break;
217 default: chMode = MODE_INVALID;
218 }
219 return chMode;
220}
221
Manisha Jajoob09409a2019-05-23 18:57:52 +0530222static AUDIO_OBJECT_TYPE getAOTFromProfile(uint32_t profile) {
223 if (profile == C2Config::PROFILE_AAC_LC) {
224 return AOT_AAC_LC;
225 } else if (profile == C2Config::PROFILE_AAC_HE) {
226 return AOT_SBR;
227 } else if (profile == C2Config::PROFILE_AAC_HE_PS) {
228 return AOT_PS;
229 } else if (profile == C2Config::PROFILE_AAC_LD) {
230 return AOT_ER_AAC_LD;
231 } else if (profile == C2Config::PROFILE_AAC_ELD) {
232 return AOT_ER_AAC_ELD;
233 } else {
234 ALOGW("Unsupported AAC profile - defaulting to AAC-LC");
235 return AOT_AAC_LC;
236 }
237}
Pawin Vongmasa36653902018-11-15 00:10:25 -0800238
239status_t C2SoftAacEnc::setAudioParams() {
240 // We call this whenever sample rate, number of channels, bitrate or SBR mode change
241 // in reponse to setParameter calls.
Manisha Jajoob09409a2019-05-23 18:57:52 +0530242 int32_t sbrRatio = 0;
243 uint32_t sbrMode = mIntf->getSBRMode();
244 if (sbrMode == AAC_SBR_SINGLE_RATE) sbrRatio = 1;
245 else if (sbrMode == AAC_SBR_DUAL_RATE) sbrRatio = 2;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800246
247 ALOGV("setAudioParams: %u Hz, %u channels, %u bps, %i sbr mode, %i sbr ratio",
Manisha Jajoob09409a2019-05-23 18:57:52 +0530248 mIntf->getSampleRate(), mIntf->getChannelCount(), mIntf->getBitrate(),
249 sbrMode, sbrRatio);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800250
Manisha Jajoob09409a2019-05-23 18:57:52 +0530251 uint32_t aacProfile = mIntf->getProfile();
252 if (AACENC_OK != aacEncoder_SetParam(mAACEncoder, AACENC_AOT, getAOTFromProfile(aacProfile))) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800253 ALOGE("Failed to set AAC encoder parameters");
254 return UNKNOWN_ERROR;
255 }
256
257 if (AACENC_OK != aacEncoder_SetParam(mAACEncoder, AACENC_SAMPLERATE, mIntf->getSampleRate())) {
258 ALOGE("Failed to set AAC encoder parameters");
259 return UNKNOWN_ERROR;
260 }
261 if (AACENC_OK != aacEncoder_SetParam(mAACEncoder, AACENC_BITRATE, mIntf->getBitrate())) {
262 ALOGE("Failed to set AAC encoder parameters");
263 return UNKNOWN_ERROR;
264 }
265 if (AACENC_OK != aacEncoder_SetParam(mAACEncoder, AACENC_CHANNELMODE,
266 getChannelMode(mIntf->getChannelCount()))) {
267 ALOGE("Failed to set AAC encoder parameters");
268 return UNKNOWN_ERROR;
269 }
270 if (AACENC_OK != aacEncoder_SetParam(mAACEncoder, AACENC_TRANSMUX, TT_MP4_RAW)) {
271 ALOGE("Failed to set AAC encoder parameters");
272 return UNKNOWN_ERROR;
273 }
274
Manisha Jajoob09409a2019-05-23 18:57:52 +0530275 if (sbrMode != -1 && aacProfile == C2Config::PROFILE_AAC_ELD) {
276 if (AACENC_OK != aacEncoder_SetParam(mAACEncoder, AACENC_SBR_MODE, sbrMode)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800277 ALOGE("Failed to set AAC encoder parameters");
278 return UNKNOWN_ERROR;
279 }
280 }
281
282 /* SBR ratio parameter configurations:
283 0: Default configuration wherein SBR ratio is configured depending on audio object type by
284 the FDK.
285 1: Downsampled SBR (default for ELD)
286 2: Dualrate SBR (default for HE-AAC)
287 */
Manisha Jajoob09409a2019-05-23 18:57:52 +0530288 if (AACENC_OK != aacEncoder_SetParam(mAACEncoder, AACENC_SBR_RATIO, sbrRatio)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800289 ALOGE("Failed to set AAC encoder parameters");
290 return UNKNOWN_ERROR;
291 }
292
293 return OK;
294}
295
296void C2SoftAacEnc::process(
297 const std::unique_ptr<C2Work> &work,
298 const std::shared_ptr<C2BlockPool> &pool) {
299 // Initialize output work
300 work->result = C2_OK;
301 work->workletsProcessed = 1u;
302 work->worklets.front()->output.flags = work->input.flags;
303
304 if (mSignalledError) {
305 return;
306 }
307 bool eos = (work->input.flags & C2FrameData::FLAG_END_OF_STREAM) != 0;
308
309 uint32_t sampleRate = mIntf->getSampleRate();
310 uint32_t channelCount = mIntf->getChannelCount();
311
312 if (!mSentCodecSpecificData) {
313 // The very first thing we want to output is the codec specific
314 // data.
315
316 if (AACENC_OK != aacEncEncode(mAACEncoder, nullptr, nullptr, nullptr, nullptr)) {
317 ALOGE("Unable to initialize encoder for profile / sample-rate / bit-rate / channels");
318 mSignalledError = true;
319 work->result = C2_CORRUPTED;
320 return;
321 }
322
323 uint32_t bitrate = mIntf->getBitrate();
324 uint32_t actualBitRate = aacEncoder_GetParam(mAACEncoder, AACENC_BITRATE);
325 if (bitrate != actualBitRate) {
326 ALOGW("Requested bitrate %u unsupported, using %u", bitrate, actualBitRate);
327 }
328
329 AACENC_InfoStruct encInfo;
330 if (AACENC_OK != aacEncInfo(mAACEncoder, &encInfo)) {
331 ALOGE("Failed to get AAC encoder info");
332 mSignalledError = true;
333 work->result = C2_CORRUPTED;
334 return;
335 }
336
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800337 std::unique_ptr<C2StreamInitDataInfo::output> csd =
338 C2StreamInitDataInfo::output::AllocUnique(encInfo.confSize, 0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800339 if (!csd) {
340 ALOGE("CSD allocation failed");
341 mSignalledError = true;
342 work->result = C2_NO_MEMORY;
343 return;
344 }
345 memcpy(csd->m.value, encInfo.confBuf, encInfo.confSize);
346 ALOGV("put csd");
347#if defined(LOG_NDEBUG) && !LOG_NDEBUG
348 hexdump(csd->m.value, csd->flexCount());
349#endif
350 work->worklets.front()->output.configUpdate.push_back(std::move(csd));
351
352 mOutBufferSize = encInfo.maxOutBufBytes;
353 mNumBytesPerInputFrame = encInfo.frameLength * channelCount * sizeof(int16_t);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800354
355 mSentCodecSpecificData = true;
356 }
357
358 uint8_t temp[1];
359 C2ReadView view = mDummyReadView;
360 const uint8_t *data = temp;
361 size_t capacity = 0u;
362 if (!work->input.buffers.empty()) {
363 view = work->input.buffers[0]->data().linearBlocks().front().map().get();
364 data = view.data();
365 capacity = view.capacity();
366 }
Wonsik Kim22748042019-11-01 10:33:16 -0700367 c2_cntr64_t inputTimestampUs = work->input.ordinal.timestamp;
368 if (inputTimestampUs < mLastFrameEndTimestampUs.value_or(inputTimestampUs)) {
369 ALOGW("Correcting overlapping timestamp: last frame ended at %lldus but "
370 "current frame is starting at %lldus. Using the last frame's end timestamp",
371 mLastFrameEndTimestampUs->peekll(), inputTimestampUs.peekll());
372 inputTimestampUs = *mLastFrameEndTimestampUs;
373 }
374 if (capacity > 0) {
375 if (!mNextFrameTimestampUs) {
376 mNextFrameTimestampUs = work->input.ordinal.timestamp;
377 }
378 mLastFrameEndTimestampUs = inputTimestampUs
379 + (capacity / sizeof(int16_t) * 1000000ll / channelCount / sampleRate);
Wonsik Kim353e1672019-01-07 16:31:29 -0800380 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800381
Wonsik Kim3dd7bd32019-08-09 10:35:55 -0700382 size_t numFrames =
383 (mRemainderLen + capacity + mInputSize + (eos ? mNumBytesPerInputFrame - 1 : 0))
384 / mNumBytesPerInputFrame;
Wonsik Kim8c886ae2019-07-15 12:36:22 -0700385 ALOGV("capacity = %zu; mInputSize = %zu; numFrames = %zu "
Wonsik Kim3dd7bd32019-08-09 10:35:55 -0700386 "mNumBytesPerInputFrame = %u inputTS = %lld remaining = %zu",
Wonsik Kim22748042019-11-01 10:33:16 -0700387 capacity, mInputSize, numFrames, mNumBytesPerInputFrame, inputTimestampUs.peekll(),
Wonsik Kim3dd7bd32019-08-09 10:35:55 -0700388 mRemainderLen);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800389
390 std::shared_ptr<C2LinearBlock> block;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800391 std::unique_ptr<C2WriteView> wView;
392 uint8_t *outPtr = temp;
393 size_t outAvailable = 0u;
394 uint64_t inputIndex = work->input.ordinal.frameIndex.peeku();
Wonsik Kim3dd7bd32019-08-09 10:35:55 -0700395 size_t bytesPerSample = channelCount * sizeof(int16_t);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800396
397 AACENC_InArgs inargs;
398 AACENC_OutArgs outargs;
399 memset(&inargs, 0, sizeof(inargs));
400 memset(&outargs, 0, sizeof(outargs));
401 inargs.numInSamples = capacity / sizeof(int16_t);
402
403 void* inBuffer[] = { (unsigned char *)data };
404 INT inBufferIds[] = { IN_AUDIO_DATA };
405 INT inBufferSize[] = { (INT)capacity };
406 INT inBufferElSize[] = { sizeof(int16_t) };
407
408 AACENC_BufDesc inBufDesc;
409 inBufDesc.numBufs = sizeof(inBuffer) / sizeof(void*);
410 inBufDesc.bufs = (void**)&inBuffer;
411 inBufDesc.bufferIdentifiers = inBufferIds;
412 inBufDesc.bufSizes = inBufferSize;
413 inBufDesc.bufElSizes = inBufferElSize;
414
415 void* outBuffer[] = { outPtr };
416 INT outBufferIds[] = { OUT_BITSTREAM_DATA };
417 INT outBufferSize[] = { 0 };
418 INT outBufferElSize[] = { sizeof(UCHAR) };
419
420 AACENC_BufDesc outBufDesc;
421 outBufDesc.numBufs = sizeof(outBuffer) / sizeof(void*);
422 outBufDesc.bufs = (void**)&outBuffer;
423 outBufDesc.bufferIdentifiers = outBufferIds;
424 outBufDesc.bufSizes = outBufferSize;
425 outBufDesc.bufElSizes = outBufferElSize;
426
427 AACENC_ERROR encoderErr = AACENC_OK;
428
429 class FillWork {
430 public:
431 FillWork(uint32_t flags, C2WorkOrdinalStruct ordinal,
432 const std::shared_ptr<C2Buffer> &buffer)
433 : mFlags(flags), mOrdinal(ordinal), mBuffer(buffer) {
434 }
435 ~FillWork() = default;
436
437 void operator()(const std::unique_ptr<C2Work> &work) {
438 work->worklets.front()->output.flags = (C2FrameData::flags_t)mFlags;
439 work->worklets.front()->output.buffers.clear();
440 work->worklets.front()->output.ordinal = mOrdinal;
441 work->workletsProcessed = 1u;
442 work->result = C2_OK;
443 if (mBuffer) {
444 work->worklets.front()->output.buffers.push_back(mBuffer);
445 }
446 ALOGV("timestamp = %lld, index = %lld, w/%s buffer",
447 mOrdinal.timestamp.peekll(),
448 mOrdinal.frameIndex.peekll(),
449 mBuffer ? "" : "o");
450 }
451
452 private:
453 const uint32_t mFlags;
454 const C2WorkOrdinalStruct mOrdinal;
455 const std::shared_ptr<C2Buffer> mBuffer;
456 };
457
Wonsik Kim8c886ae2019-07-15 12:36:22 -0700458 struct OutputBuffer {
459 std::shared_ptr<C2Buffer> buffer;
460 c2_cntr64_t timestampUs;
461 };
462 std::list<OutputBuffer> outputBuffers;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800463
Wonsik Kim3dd7bd32019-08-09 10:35:55 -0700464 if (mRemainderLen > 0) {
465 size_t offset = 0;
466 for (; mRemainderLen < bytesPerSample && offset < capacity; ++offset) {
467 mRemainder[mRemainderLen++] = data[offset];
468 }
469 data += offset;
470 capacity -= offset;
471 if (mRemainderLen == bytesPerSample) {
472 inBuffer[0] = mRemainder;
473 inBufferSize[0] = bytesPerSample;
474 inargs.numInSamples = channelCount;
475 mRemainderLen = 0;
476 ALOGV("Processing remainder");
477 } else {
478 // We have exhausted the input already
479 inargs.numInSamples = 0;
480 }
481 }
482 while (encoderErr == AACENC_OK && inargs.numInSamples >= channelCount) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800483 if (numFrames && !block) {
484 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
485 // TODO: error handling, proper usage, etc.
486 c2_status_t err = pool->fetchLinearBlock(mOutBufferSize, usage, &block);
487 if (err != C2_OK) {
488 ALOGE("fetchLinearBlock failed : err = %d", err);
489 work->result = C2_NO_MEMORY;
490 return;
491 }
492
493 wView.reset(new C2WriteView(block->map().get()));
494 outPtr = wView->data();
495 outAvailable = wView->size();
496 --numFrames;
497 }
498
499 memset(&outargs, 0, sizeof(outargs));
500
501 outBuffer[0] = outPtr;
502 outBufferSize[0] = outAvailable;
503
504 encoderErr = aacEncEncode(mAACEncoder,
505 &inBufDesc,
506 &outBufDesc,
507 &inargs,
508 &outargs);
509
510 if (encoderErr == AACENC_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800511 if (outargs.numOutBytes > 0) {
512 mInputSize = 0;
Wonsik Kim84889cb2019-01-03 17:07:54 -0800513 int consumed = (capacity / sizeof(int16_t)) - inargs.numInSamples
514 + outargs.numInSamples;
Wonsik Kim22748042019-11-01 10:33:16 -0700515 ALOGV("consumed = %d, capacity = %zu, inSamples = %d, outSamples = %d",
516 consumed, capacity, inargs.numInSamples, outargs.numInSamples);
517 c2_cntr64_t currentFrameTimestampUs = *mNextFrameTimestampUs;
518 mNextFrameTimestampUs = inputTimestampUs
Pawin Vongmasa36653902018-11-15 00:10:25 -0800519 + (consumed * 1000000ll / channelCount / sampleRate);
Wonsik Kim8c886ae2019-07-15 12:36:22 -0700520 std::shared_ptr<C2Buffer> buffer = createLinearBuffer(block, 0, outargs.numOutBytes);
Wonsik Kim3dd7bd32019-08-09 10:35:55 -0700521#if 0
Pawin Vongmasa36653902018-11-15 00:10:25 -0800522 hexdump(outPtr, std::min(outargs.numOutBytes, 256));
523#endif
524 outPtr = temp;
525 outAvailable = 0;
526 block.reset();
Wonsik Kim8c886ae2019-07-15 12:36:22 -0700527
528 outputBuffers.push_back({buffer, currentFrameTimestampUs});
Pawin Vongmasa36653902018-11-15 00:10:25 -0800529 } else {
530 mInputSize += outargs.numInSamples * sizeof(int16_t);
531 }
532
Wonsik Kim3dd7bd32019-08-09 10:35:55 -0700533 if (inBuffer[0] == mRemainder) {
534 inBuffer[0] = const_cast<uint8_t *>(data);
535 inBufferSize[0] = capacity;
536 inargs.numInSamples = capacity / sizeof(int16_t);
Wonsik Kimf15bccb2019-10-23 14:18:39 -0700537 } else if (outargs.numInSamples > 0) {
538 inBuffer[0] = (int16_t *)inBuffer[0] + outargs.numInSamples;
539 inBufferSize[0] -= outargs.numInSamples * sizeof(int16_t);
540 inargs.numInSamples -= outargs.numInSamples;
Wonsik Kim3dd7bd32019-08-09 10:35:55 -0700541 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800542 }
Wonsik Kim8c886ae2019-07-15 12:36:22 -0700543 ALOGV("encoderErr = %d mInputSize = %zu "
544 "inargs.numInSamples = %d, mNextFrameTimestampUs = %lld",
Wonsik Kim22748042019-11-01 10:33:16 -0700545 encoderErr, mInputSize, inargs.numInSamples, mNextFrameTimestampUs->peekll());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800546 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800547 if (eos && inBufferSize[0] > 0) {
548 if (numFrames && !block) {
549 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
550 // TODO: error handling, proper usage, etc.
551 c2_status_t err = pool->fetchLinearBlock(mOutBufferSize, usage, &block);
552 if (err != C2_OK) {
553 ALOGE("fetchLinearBlock failed : err = %d", err);
554 work->result = C2_NO_MEMORY;
555 return;
556 }
557
558 wView.reset(new C2WriteView(block->map().get()));
559 outPtr = wView->data();
560 outAvailable = wView->size();
561 --numFrames;
562 }
563
564 memset(&outargs, 0, sizeof(outargs));
565
566 outBuffer[0] = outPtr;
567 outBufferSize[0] = outAvailable;
568
569 // Flush
570 inargs.numInSamples = -1;
571
572 (void)aacEncEncode(mAACEncoder,
573 &inBufDesc,
574 &outBufDesc,
575 &inargs,
576 &outargs);
Wonsik Kim3dd7bd32019-08-09 10:35:55 -0700577 inBufferSize[0] = 0;
578 }
579
580 if (inBufferSize[0] > 0) {
581 for (size_t i = 0; i < inBufferSize[0]; ++i) {
582 mRemainder[i] = static_cast<uint8_t *>(inBuffer[0])[i];
583 }
584 mRemainderLen = inBufferSize[0];
Pawin Vongmasa36653902018-11-15 00:10:25 -0800585 }
586
Wonsik Kim8c886ae2019-07-15 12:36:22 -0700587 while (outputBuffers.size() > 1) {
588 const OutputBuffer& front = outputBuffers.front();
589 C2WorkOrdinalStruct ordinal = work->input.ordinal;
590 ordinal.frameIndex = mOutIndex++;
591 ordinal.timestamp = front.timestampUs;
592 cloneAndSend(
593 inputIndex,
594 work,
595 FillWork(C2FrameData::FLAG_INCOMPLETE, ordinal, front.buffer));
596 outputBuffers.pop_front();
597 }
598 std::shared_ptr<C2Buffer> buffer;
599 C2WorkOrdinalStruct ordinal = work->input.ordinal;
600 ordinal.frameIndex = mOutIndex++;
601 if (!outputBuffers.empty()) {
602 ordinal.timestamp = outputBuffers.front().timestampUs;
603 buffer = outputBuffers.front().buffer;
604 }
605 // Mark the end of frame
Pawin Vongmasa36653902018-11-15 00:10:25 -0800606 FillWork((C2FrameData::flags_t)(eos ? C2FrameData::FLAG_END_OF_STREAM : 0),
Wonsik Kim8c886ae2019-07-15 12:36:22 -0700607 ordinal, buffer)(work);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800608}
609
610c2_status_t C2SoftAacEnc::drain(
611 uint32_t drainMode,
612 const std::shared_ptr<C2BlockPool> &pool) {
613 switch (drainMode) {
614 case DRAIN_COMPONENT_NO_EOS:
615 [[fallthrough]];
616 case NO_DRAIN:
617 // no-op
618 return C2_OK;
619 case DRAIN_CHAIN:
620 return C2_OMITTED;
621 case DRAIN_COMPONENT_WITH_EOS:
622 break;
623 default:
624 return C2_BAD_VALUE;
625 }
626
627 (void)pool;
628 mSentCodecSpecificData = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800629 mInputSize = 0u;
Wonsik Kim22748042019-11-01 10:33:16 -0700630 mNextFrameTimestampUs.reset();
631 mLastFrameEndTimestampUs.reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800632
633 // TODO: we don't have any pending work at this time to drain.
634 return C2_OK;
635}
636
637class C2SoftAacEncFactory : public C2ComponentFactory {
638public:
639 C2SoftAacEncFactory() : mHelper(std::static_pointer_cast<C2ReflectorHelper>(
640 GetCodec2PlatformComponentStore()->getParamReflector())) {
641 }
642
643 virtual c2_status_t createComponent(
644 c2_node_id_t id,
645 std::shared_ptr<C2Component>* const component,
646 std::function<void(C2Component*)> deleter) override {
647 *component = std::shared_ptr<C2Component>(
648 new C2SoftAacEnc(COMPONENT_NAME,
649 id,
650 std::make_shared<C2SoftAacEnc::IntfImpl>(mHelper)),
651 deleter);
652 return C2_OK;
653 }
654
655 virtual c2_status_t createInterface(
656 c2_node_id_t id, std::shared_ptr<C2ComponentInterface>* const interface,
657 std::function<void(C2ComponentInterface*)> deleter) override {
658 *interface = std::shared_ptr<C2ComponentInterface>(
659 new SimpleInterface<C2SoftAacEnc::IntfImpl>(
660 COMPONENT_NAME, id, std::make_shared<C2SoftAacEnc::IntfImpl>(mHelper)),
661 deleter);
662 return C2_OK;
663 }
664
665 virtual ~C2SoftAacEncFactory() override = default;
666
667private:
668 std::shared_ptr<C2ReflectorHelper> mHelper;
669};
670
671} // namespace android
672
673extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
674 ALOGV("in %s", __func__);
675 return new ::android::C2SoftAacEncFactory();
676}
677
678extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
679 ALOGV("in %s", __func__);
680 delete factory;
681}