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 "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 
30 namespace android {
31 
32 namespace {
33 
34 constexpr char COMPONENT_NAME[] = "c2.android.aac.encoder";
35 
36 }  // namespace
37 
38 class C2SoftAacEnc::IntfImpl : public SimpleInterface<void>::BaseParams {
39 public:
IntfImpl(const std::shared_ptr<C2ReflectorHelper> & helper)40     explicit IntfImpl(const std::shared_ptr<C2ReflectorHelper> &helper)
41         : 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();
52         setDerivedInstance(this);
53 
54         addParameter(
55                 DefineParam(mAttrib, C2_PARAMKEY_COMPONENT_ATTRIBUTES)
56                 .withConstValue(new C2ComponentAttributesSetting(
57                     C2Component::ATTRIB_IS_TEMPORAL))
58                 .build());
59 
60         addParameter(
61                 DefineParam(mSampleRate, C2_PARAMKEY_SAMPLE_RATE)
62                 .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(
70                 DefineParam(mChannelCount, C2_PARAMKEY_CHANNEL_COUNT)
71                 .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(
77                 DefineParam(mBitrate, C2_PARAMKEY_BITRATE)
78                 .withDefault(new C2StreamBitrateInfo::output(0u, 64000))
79                 .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());
106 
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());
117     }
118 
getSampleRate() const119     uint32_t getSampleRate() const { return mSampleRate->value; }
getChannelCount() const120     uint32_t getChannelCount() const { return mChannelCount->value; }
getBitrate() const121     uint32_t getBitrate() const { return mBitrate->value; }
getSBRMode() const122     uint32_t getSBRMode() const { return mSBRMode->value; }
getProfile() const123     uint32_t getProfile() const { return mProfileLevel->profile; }
ProfileLevelSetter(bool mayBlock,C2P<C2StreamProfileLevelInfo::output> & me)124     static C2R ProfileLevelSetter(bool mayBlock, C2P<C2StreamProfileLevelInfo::output> &me) {
125         (void)mayBlock;
126         (void)me;  // TODO: validate
127         return C2R::Ok();
128     }
129 
MaxBufSizeCalculator(bool mayBlock,C2P<C2StreamMaxBufferSizeInfo::input> & me,const C2P<C2StreamChannelCountInfo::input> & channelCount)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 
139 private:
140     std::shared_ptr<C2StreamSampleRateInfo::input> mSampleRate;
141     std::shared_ptr<C2StreamChannelCountInfo::input> mChannelCount;
142     std::shared_ptr<C2StreamBitrateInfo::output> mBitrate;
143     std::shared_ptr<C2StreamMaxBufferSizeInfo::input> mInputMaxBufSize;
144     std::shared_ptr<C2StreamProfileLevelInfo::output> mProfileLevel;
145     std::shared_ptr<C2StreamAacSbrModeTuning::input> mSBRMode;
146 };
147 
C2SoftAacEnc(const char * name,c2_node_id_t id,const std::shared_ptr<IntfImpl> & intfImpl)148 C2SoftAacEnc::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),
155       mNumBytesPerInputFrame(0u),
156       mOutBufferSize(0u),
157       mSentCodecSpecificData(false),
158       mInputSize(0),
159       mSignalledError(false),
160       mOutIndex(0u),
161       mRemainderLen(0u) {
162 }
163 
~C2SoftAacEnc()164 C2SoftAacEnc::~C2SoftAacEnc() {
165     onReset();
166 }
167 
onInit()168 c2_status_t C2SoftAacEnc::onInit() {
169     status_t err = initEncoder();
170     return err == OK ? C2_OK : C2_CORRUPTED;
171 }
172 
initEncoder()173 status_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 
onStop()181 c2_status_t C2SoftAacEnc::onStop() {
182     mSentCodecSpecificData = false;
183     mInputSize = 0u;
184     mNextFrameTimestampUs.reset();
185     mLastFrameEndTimestampUs.reset();
186     mSignalledError = false;
187     mRemainderLen = 0;
188     return C2_OK;
189 }
190 
onReset()191 void C2SoftAacEnc::onReset() {
192     (void)onStop();
193     aacEncClose(&mAACEncoder);
194 }
195 
onRelease()196 void C2SoftAacEnc::onRelease() {
197     // no-op
198 }
199 
onFlush_sm()200 c2_status_t C2SoftAacEnc::onFlush_sm() {
201     mSentCodecSpecificData = false;
202     mInputSize = 0u;
203     mNextFrameTimestampUs.reset();
204     mLastFrameEndTimestampUs.reset();
205     return C2_OK;
206 }
207 
getChannelMode(uint32_t nChannels)208 static 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 
getAOTFromProfile(uint32_t profile)222 static 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 }
238 
setAudioParams()239 status_t C2SoftAacEnc::setAudioParams() {
240     // We call this whenever sample rate, number of channels, bitrate or SBR mode change
241     // in reponse to setParameter calls.
242     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;
246 
247     ALOGV("setAudioParams: %u Hz, %u channels, %u bps, %i sbr mode, %i sbr ratio",
248          mIntf->getSampleRate(), mIntf->getChannelCount(), mIntf->getBitrate(),
249          sbrMode, sbrRatio);
250 
251     uint32_t aacProfile = mIntf->getProfile();
252     if (AACENC_OK != aacEncoder_SetParam(mAACEncoder, AACENC_AOT, getAOTFromProfile(aacProfile))) {
253         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 
275     if (sbrMode != -1 && aacProfile == C2Config::PROFILE_AAC_ELD) {
276         if (AACENC_OK != aacEncoder_SetParam(mAACEncoder, AACENC_SBR_MODE, sbrMode)) {
277             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      */
288     if (AACENC_OK != aacEncoder_SetParam(mAACEncoder, AACENC_SBR_RATIO, sbrRatio)) {
289         ALOGE("Failed to set AAC encoder parameters");
290         return UNKNOWN_ERROR;
291     }
292 
293     return OK;
294 }
295 
MaybeLogTimestampWarning(long long lastFrameEndTimestampUs,long long inputTimestampUs)296 static void MaybeLogTimestampWarning(
297         long long lastFrameEndTimestampUs, long long inputTimestampUs) {
298     using Clock = std::chrono::steady_clock;
299     thread_local Clock::time_point sLastLogTimestamp{};
300     thread_local int32_t sOverlapCount = -1;
301     if (Clock::now() - sLastLogTimestamp > std::chrono::minutes(1) || sOverlapCount < 0) {
302         AString countMessage = "";
303         if (sOverlapCount > 0) {
304             countMessage = AStringPrintf(
305                     "(%d overlapping timestamp detected since last log)", sOverlapCount);
306         }
307         ALOGI("Correcting overlapping timestamp: last frame ended at %lldus but "
308                 "current frame is starting at %lldus. Using the last frame's end timestamp %s",
309                 lastFrameEndTimestampUs, inputTimestampUs, countMessage.c_str());
310         sLastLogTimestamp = Clock::now();
311         sOverlapCount = 0;
312     } else {
313         ALOGV("Correcting overlapping timestamp: last frame ended at %lldus but "
314                 "current frame is starting at %lldus. Using the last frame's end timestamp",
315                 lastFrameEndTimestampUs, inputTimestampUs);
316         ++sOverlapCount;
317     }
318 }
319 
process(const std::unique_ptr<C2Work> & work,const std::shared_ptr<C2BlockPool> & pool)320 void C2SoftAacEnc::process(
321         const std::unique_ptr<C2Work> &work,
322         const std::shared_ptr<C2BlockPool> &pool) {
323     // Initialize output work
324     work->result = C2_OK;
325     work->workletsProcessed = 1u;
326     work->worklets.front()->output.flags = work->input.flags;
327 
328     if (mSignalledError) {
329         return;
330     }
331     bool eos = (work->input.flags & C2FrameData::FLAG_END_OF_STREAM) != 0;
332 
333     uint32_t sampleRate = mIntf->getSampleRate();
334     uint32_t channelCount = mIntf->getChannelCount();
335 
336     if (!mSentCodecSpecificData) {
337         // The very first thing we want to output is the codec specific
338         // data.
339 
340         if (AACENC_OK != aacEncEncode(mAACEncoder, nullptr, nullptr, nullptr, nullptr)) {
341             ALOGE("Unable to initialize encoder for profile / sample-rate / bit-rate / channels");
342             mSignalledError = true;
343             work->result = C2_CORRUPTED;
344             return;
345         }
346 
347         uint32_t bitrate = mIntf->getBitrate();
348         uint32_t actualBitRate = aacEncoder_GetParam(mAACEncoder, AACENC_BITRATE);
349         if (bitrate != actualBitRate) {
350             ALOGW("Requested bitrate %u unsupported, using %u", bitrate, actualBitRate);
351         }
352 
353         AACENC_InfoStruct encInfo;
354         if (AACENC_OK != aacEncInfo(mAACEncoder, &encInfo)) {
355             ALOGE("Failed to get AAC encoder info");
356             mSignalledError = true;
357             work->result = C2_CORRUPTED;
358             return;
359         }
360 
361         std::unique_ptr<C2StreamInitDataInfo::output> csd =
362             C2StreamInitDataInfo::output::AllocUnique(encInfo.confSize, 0u);
363         if (!csd) {
364             ALOGE("CSD allocation failed");
365             mSignalledError = true;
366             work->result = C2_NO_MEMORY;
367             return;
368         }
369         memcpy(csd->m.value, encInfo.confBuf, encInfo.confSize);
370         ALOGV("put csd");
371 #if defined(LOG_NDEBUG) && !LOG_NDEBUG
372         hexdump(csd->m.value, csd->flexCount());
373 #endif
374         work->worklets.front()->output.configUpdate.push_back(std::move(csd));
375 
376         mOutBufferSize = encInfo.maxOutBufBytes;
377         mNumBytesPerInputFrame = encInfo.frameLength * channelCount * sizeof(int16_t);
378 
379         mSentCodecSpecificData = true;
380     }
381 
382     uint8_t temp[1];
383     C2ReadView view = mDummyReadView;
384     const uint8_t *data = temp;
385     size_t capacity = 0u;
386     if (!work->input.buffers.empty()) {
387         view = work->input.buffers[0]->data().linearBlocks().front().map().get();
388         data = view.data();
389         capacity = view.capacity();
390     }
391     c2_cntr64_t inputTimestampUs = work->input.ordinal.timestamp;
392     if (inputTimestampUs < mLastFrameEndTimestampUs.value_or(inputTimestampUs)) {
393         MaybeLogTimestampWarning(mLastFrameEndTimestampUs->peekll(), inputTimestampUs.peekll());
394         inputTimestampUs = *mLastFrameEndTimestampUs;
395     }
396     if (capacity > 0) {
397         if (!mNextFrameTimestampUs) {
398             mNextFrameTimestampUs = work->input.ordinal.timestamp;
399         }
400         mLastFrameEndTimestampUs = inputTimestampUs
401                 + (capacity / sizeof(int16_t) * 1000000ll / channelCount / sampleRate);
402     }
403 
404     size_t numFrames =
405         (mRemainderLen + capacity + mInputSize + (eos ? mNumBytesPerInputFrame - 1 : 0))
406         / mNumBytesPerInputFrame;
407     ALOGV("capacity = %zu; mInputSize = %zu; numFrames = %zu "
408           "mNumBytesPerInputFrame = %u inputTS = %lld remaining = %zu",
409           capacity, mInputSize, numFrames, mNumBytesPerInputFrame, inputTimestampUs.peekll(),
410           mRemainderLen);
411 
412     std::shared_ptr<C2LinearBlock> block;
413     std::unique_ptr<C2WriteView> wView;
414     uint8_t *outPtr = temp;
415     size_t outAvailable = 0u;
416     uint64_t inputIndex = work->input.ordinal.frameIndex.peeku();
417     size_t bytesPerSample = channelCount * sizeof(int16_t);
418 
419     AACENC_InArgs inargs;
420     AACENC_OutArgs outargs;
421     memset(&inargs, 0, sizeof(inargs));
422     memset(&outargs, 0, sizeof(outargs));
423     inargs.numInSamples = capacity / sizeof(int16_t);
424 
425     void* inBuffer[]        = { (unsigned char *)data };
426     INT   inBufferIds[]     = { IN_AUDIO_DATA };
427     INT   inBufferSize[]    = { (INT)capacity };
428     INT   inBufferElSize[]  = { sizeof(int16_t) };
429 
430     AACENC_BufDesc inBufDesc;
431     inBufDesc.numBufs           = sizeof(inBuffer) / sizeof(void*);
432     inBufDesc.bufs              = (void**)&inBuffer;
433     inBufDesc.bufferIdentifiers = inBufferIds;
434     inBufDesc.bufSizes          = inBufferSize;
435     inBufDesc.bufElSizes        = inBufferElSize;
436 
437     void* outBuffer[]       = { outPtr };
438     INT   outBufferIds[]    = { OUT_BITSTREAM_DATA };
439     INT   outBufferSize[]   = { 0 };
440     INT   outBufferElSize[] = { sizeof(UCHAR) };
441 
442     AACENC_BufDesc outBufDesc;
443     outBufDesc.numBufs           = sizeof(outBuffer) / sizeof(void*);
444     outBufDesc.bufs              = (void**)&outBuffer;
445     outBufDesc.bufferIdentifiers = outBufferIds;
446     outBufDesc.bufSizes          = outBufferSize;
447     outBufDesc.bufElSizes        = outBufferElSize;
448 
449     AACENC_ERROR encoderErr = AACENC_OK;
450 
451     class FillWork {
452     public:
453         FillWork(uint32_t flags, C2WorkOrdinalStruct ordinal,
454                  const std::shared_ptr<C2Buffer> &buffer)
455             : mFlags(flags), mOrdinal(ordinal), mBuffer(buffer) {
456         }
457         ~FillWork() = default;
458 
459         void operator()(const std::unique_ptr<C2Work> &work) {
460             work->worklets.front()->output.flags = (C2FrameData::flags_t)mFlags;
461             work->worklets.front()->output.buffers.clear();
462             work->worklets.front()->output.ordinal = mOrdinal;
463             work->workletsProcessed = 1u;
464             work->result = C2_OK;
465             if (mBuffer) {
466                 work->worklets.front()->output.buffers.push_back(mBuffer);
467             }
468             ALOGV("timestamp = %lld, index = %lld, w/%s buffer",
469                   mOrdinal.timestamp.peekll(),
470                   mOrdinal.frameIndex.peekll(),
471                   mBuffer ? "" : "o");
472         }
473 
474     private:
475         const uint32_t mFlags;
476         const C2WorkOrdinalStruct mOrdinal;
477         const std::shared_ptr<C2Buffer> mBuffer;
478     };
479 
480     struct OutputBuffer {
481         std::shared_ptr<C2Buffer> buffer;
482         c2_cntr64_t timestampUs;
483     };
484     std::list<OutputBuffer> outputBuffers;
485 
486     if (mRemainderLen > 0) {
487         size_t offset = 0;
488         for (; mRemainderLen < bytesPerSample && offset < capacity; ++offset) {
489             mRemainder[mRemainderLen++] = data[offset];
490         }
491         data += offset;
492         capacity -= offset;
493         if (mRemainderLen == bytesPerSample) {
494             inBuffer[0] = mRemainder;
495             inBufferSize[0] = bytesPerSample;
496             inargs.numInSamples = channelCount;
497             mRemainderLen = 0;
498             ALOGV("Processing remainder");
499         } else {
500             // We have exhausted the input already
501             inargs.numInSamples = 0;
502         }
503     }
504     while (encoderErr == AACENC_OK && inargs.numInSamples >= channelCount) {
505         if (numFrames && !block) {
506             C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
507             // TODO: error handling, proper usage, etc.
508             c2_status_t err = pool->fetchLinearBlock(mOutBufferSize, usage, &block);
509             if (err != C2_OK) {
510                 ALOGE("fetchLinearBlock failed : err = %d", err);
511                 work->result = C2_NO_MEMORY;
512                 return;
513             }
514 
515             wView.reset(new C2WriteView(block->map().get()));
516             outPtr = wView->data();
517             outAvailable = wView->size();
518             --numFrames;
519         }
520 
521         memset(&outargs, 0, sizeof(outargs));
522 
523         outBuffer[0] = outPtr;
524         outBufferSize[0] = outAvailable;
525 
526         encoderErr = aacEncEncode(mAACEncoder,
527                                   &inBufDesc,
528                                   &outBufDesc,
529                                   &inargs,
530                                   &outargs);
531 
532         if (encoderErr == AACENC_OK) {
533             if (outargs.numOutBytes > 0) {
534                 mInputSize = 0;
535                 int consumed = (capacity / sizeof(int16_t)) - inargs.numInSamples
536                         + outargs.numInSamples;
537                 ALOGV("consumed = %d, capacity = %zu, inSamples = %d, outSamples = %d",
538                       consumed, capacity, inargs.numInSamples, outargs.numInSamples);
539                 c2_cntr64_t currentFrameTimestampUs = *mNextFrameTimestampUs;
540                 mNextFrameTimestampUs = inputTimestampUs
541                         + (consumed * 1000000ll / channelCount / sampleRate);
542                 std::shared_ptr<C2Buffer> buffer = createLinearBuffer(block, 0, outargs.numOutBytes);
543 #if 0
544                 hexdump(outPtr, std::min(outargs.numOutBytes, 256));
545 #endif
546                 outPtr = temp;
547                 outAvailable = 0;
548                 block.reset();
549 
550                 outputBuffers.push_back({buffer, currentFrameTimestampUs});
551             } else {
552                 mInputSize += outargs.numInSamples * sizeof(int16_t);
553             }
554 
555             if (inBuffer[0] == mRemainder) {
556                 inBuffer[0] = const_cast<uint8_t *>(data);
557                 inBufferSize[0] = capacity;
558                 inargs.numInSamples = capacity / sizeof(int16_t);
559             } else if (outargs.numInSamples > 0) {
560                 inBuffer[0] = (int16_t *)inBuffer[0] + outargs.numInSamples;
561                 inBufferSize[0] -= outargs.numInSamples * sizeof(int16_t);
562                 inargs.numInSamples -= outargs.numInSamples;
563             }
564         }
565         ALOGV("encoderErr = %d mInputSize = %zu "
566               "inargs.numInSamples = %d, mNextFrameTimestampUs = %lld",
567               encoderErr, mInputSize, inargs.numInSamples, mNextFrameTimestampUs->peekll());
568     }
569     if (eos && inBufferSize[0] > 0) {
570         if (numFrames && !block) {
571             C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
572             // TODO: error handling, proper usage, etc.
573             c2_status_t err = pool->fetchLinearBlock(mOutBufferSize, usage, &block);
574             if (err != C2_OK) {
575                 ALOGE("fetchLinearBlock failed : err = %d", err);
576                 work->result = C2_NO_MEMORY;
577                 return;
578             }
579 
580             wView.reset(new C2WriteView(block->map().get()));
581             outPtr = wView->data();
582             outAvailable = wView->size();
583             --numFrames;
584         }
585 
586         memset(&outargs, 0, sizeof(outargs));
587 
588         outBuffer[0] = outPtr;
589         outBufferSize[0] = outAvailable;
590 
591         // Flush
592         inargs.numInSamples = -1;
593 
594         (void)aacEncEncode(mAACEncoder,
595                            &inBufDesc,
596                            &outBufDesc,
597                            &inargs,
598                            &outargs);
599         inBufferSize[0] = 0;
600     }
601 
602     if (inBufferSize[0] > 0) {
603         for (size_t i = 0; i < inBufferSize[0]; ++i) {
604             mRemainder[i] = static_cast<uint8_t *>(inBuffer[0])[i];
605         }
606         mRemainderLen = inBufferSize[0];
607     }
608 
609     while (outputBuffers.size() > 1) {
610         const OutputBuffer& front = outputBuffers.front();
611         C2WorkOrdinalStruct ordinal = work->input.ordinal;
612         ordinal.frameIndex = mOutIndex++;
613         ordinal.timestamp = front.timestampUs;
614         cloneAndSend(
615                 inputIndex,
616                 work,
617                 FillWork(C2FrameData::FLAG_INCOMPLETE, ordinal, front.buffer));
618         outputBuffers.pop_front();
619     }
620     std::shared_ptr<C2Buffer> buffer;
621     C2WorkOrdinalStruct ordinal = work->input.ordinal;
622     ordinal.frameIndex = mOutIndex++;
623     if (!outputBuffers.empty()) {
624         ordinal.timestamp = outputBuffers.front().timestampUs;
625         buffer = outputBuffers.front().buffer;
626     }
627     // Mark the end of frame
628     FillWork((C2FrameData::flags_t)(eos ? C2FrameData::FLAG_END_OF_STREAM : 0),
629              ordinal, buffer)(work);
630 }
631 
drain(uint32_t drainMode,const std::shared_ptr<C2BlockPool> & pool)632 c2_status_t C2SoftAacEnc::drain(
633         uint32_t drainMode,
634         const std::shared_ptr<C2BlockPool> &pool) {
635     switch (drainMode) {
636         case DRAIN_COMPONENT_NO_EOS:
637             [[fallthrough]];
638         case NO_DRAIN:
639             // no-op
640             return C2_OK;
641         case DRAIN_CHAIN:
642             return C2_OMITTED;
643         case DRAIN_COMPONENT_WITH_EOS:
644             break;
645         default:
646             return C2_BAD_VALUE;
647     }
648 
649     (void)pool;
650     mSentCodecSpecificData = false;
651     mInputSize = 0u;
652     mNextFrameTimestampUs.reset();
653     mLastFrameEndTimestampUs.reset();
654 
655     // TODO: we don't have any pending work at this time to drain.
656     return C2_OK;
657 }
658 
659 class C2SoftAacEncFactory : public C2ComponentFactory {
660 public:
C2SoftAacEncFactory()661     C2SoftAacEncFactory() : mHelper(std::static_pointer_cast<C2ReflectorHelper>(
662             GetCodec2PlatformComponentStore()->getParamReflector())) {
663     }
664 
createComponent(c2_node_id_t id,std::shared_ptr<C2Component> * const component,std::function<void (C2Component *)> deleter)665     virtual c2_status_t createComponent(
666             c2_node_id_t id,
667             std::shared_ptr<C2Component>* const component,
668             std::function<void(C2Component*)> deleter) override {
669         *component = std::shared_ptr<C2Component>(
670                 new C2SoftAacEnc(COMPONENT_NAME,
671                                  id,
672                                  std::make_shared<C2SoftAacEnc::IntfImpl>(mHelper)),
673                 deleter);
674         return C2_OK;
675     }
676 
createInterface(c2_node_id_t id,std::shared_ptr<C2ComponentInterface> * const interface,std::function<void (C2ComponentInterface *)> deleter)677     virtual c2_status_t createInterface(
678             c2_node_id_t id, std::shared_ptr<C2ComponentInterface>* const interface,
679             std::function<void(C2ComponentInterface*)> deleter) override {
680         *interface = std::shared_ptr<C2ComponentInterface>(
681                 new SimpleInterface<C2SoftAacEnc::IntfImpl>(
682                         COMPONENT_NAME, id, std::make_shared<C2SoftAacEnc::IntfImpl>(mHelper)),
683                 deleter);
684         return C2_OK;
685     }
686 
687     virtual ~C2SoftAacEncFactory() override = default;
688 
689 private:
690     std::shared_ptr<C2ReflectorHelper> mHelper;
691 };
692 
693 }  // namespace android
694 
CreateCodec2Factory()695 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
696     ALOGV("in %s", __func__);
697     return new ::android::C2SoftAacEncFactory();
698 }
699 
DestroyCodec2Factory(::C2ComponentFactory * factory)700 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
701     ALOGV("in %s", __func__);
702     delete factory;
703 }
704