1 /*
2 * Copyright (C) 2019 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 "C2SoftOpusEnc"
19 #include <utils/Log.h>
20
21 #include <C2PlatformSupport.h>
22 #include <SimpleC2Interface.h>
23 #include <media/stagefright/foundation/MediaDefs.h>
24 #include <media/stagefright/foundation/OpusHeader.h>
25 #include "C2SoftOpusEnc.h"
26
27 extern "C" {
28 #include <opus.h>
29 #include <opus_multistream.h>
30 }
31
32 namespace android {
33
34 namespace {
35
36 constexpr char COMPONENT_NAME[] = "c2.android.opus.encoder";
37
38 } // namespace
39
40
41 class C2SoftOpusEnc::IntfImpl : public SimpleInterface<void>::BaseParams {
42 public:
IntfImpl(const std::shared_ptr<C2ReflectorHelper> & helper)43 explicit IntfImpl(const std::shared_ptr<C2ReflectorHelper> &helper)
44 : SimpleInterface<void>::BaseParams(
45 helper,
46 COMPONENT_NAME,
47 C2Component::KIND_ENCODER,
48 C2Component::DOMAIN_AUDIO,
49 MEDIA_MIMETYPE_AUDIO_OPUS) {
50 noPrivateBuffers();
51 noInputReferences();
52 noOutputReferences();
53 noInputLatency();
54 noTimeStretch();
55 setDerivedInstance(this);
56
57 addParameter(
58 DefineParam(mAttrib, C2_PARAMKEY_COMPONENT_ATTRIBUTES)
59 .withConstValue(new C2ComponentAttributesSetting(
60 C2Component::ATTRIB_IS_TEMPORAL))
61 .build());
62
63 addParameter(
64 DefineParam(mSampleRate, C2_PARAMKEY_SAMPLE_RATE)
65 .withDefault(new C2StreamSampleRateInfo::input(0u, 48000))
66 .withFields({C2F(mSampleRate, value).oneOf({
67 8000, 12000, 16000, 24000, 48000})})
68 .withSetter((Setter<decltype(*mSampleRate)>::StrictValueWithNoDeps))
69 .build());
70
71 addParameter(
72 DefineParam(mChannelCount, C2_PARAMKEY_CHANNEL_COUNT)
73 .withDefault(new C2StreamChannelCountInfo::input(0u, 1))
74 .withFields({C2F(mChannelCount, value).inRange(1, kMaxNumChannelsSupported)})
75 .withSetter((Setter<decltype(*mChannelCount)>::StrictValueWithNoDeps))
76 .build());
77
78 addParameter(
79 DefineParam(mBitrateMode, C2_PARAMKEY_BITRATE_MODE)
80 .withDefault(new C2StreamBitrateModeTuning::output(
81 0u, C2Config::BITRATE_VARIABLE))
82 .withFields({
83 C2F(mBitrateMode, value).oneOf({
84 C2Config::BITRATE_CONST,
85 C2Config::BITRATE_VARIABLE})
86 })
87 .withSetter(
88 Setter<decltype(*mBitrateMode)>::StrictValueWithNoDeps)
89 .build());
90
91 addParameter(
92 DefineParam(mBitrate, C2_PARAMKEY_BITRATE)
93 .withDefault(new C2StreamBitrateInfo::output(0u, 128000))
94 .withFields({C2F(mBitrate, value).inRange(500, 512000)})
95 .withSetter(Setter<decltype(*mBitrate)>::NonStrictValueWithNoDeps)
96 .build());
97
98 addParameter(
99 DefineParam(mComplexity, C2_PARAMKEY_COMPLEXITY)
100 .withDefault(new C2StreamComplexityTuning::output(0u, 10))
101 .withFields({C2F(mComplexity, value).inRange(1, 10)})
102 .withSetter(Setter<decltype(*mComplexity)>::NonStrictValueWithNoDeps)
103 .build());
104
105 addParameter(
106 DefineParam(mInputMaxBufSize, C2_PARAMKEY_INPUT_MAX_BUFFER_SIZE)
107 .withConstValue(new C2StreamMaxBufferSizeInfo::input(0u, 3840))
108 .build());
109 }
110
getSampleRate() const111 uint32_t getSampleRate() const { return mSampleRate->value; }
getChannelCount() const112 uint32_t getChannelCount() const { return mChannelCount->value; }
getBitrate() const113 uint32_t getBitrate() const { return mBitrate->value; }
getBitrateMode() const114 uint32_t getBitrateMode() const { return mBitrateMode->value; }
getComplexity() const115 uint32_t getComplexity() const { return mComplexity->value; }
116
117 private:
118 std::shared_ptr<C2StreamSampleRateInfo::input> mSampleRate;
119 std::shared_ptr<C2StreamChannelCountInfo::input> mChannelCount;
120 std::shared_ptr<C2StreamBitrateInfo::output> mBitrate;
121 std::shared_ptr<C2StreamBitrateModeTuning::output> mBitrateMode;
122 std::shared_ptr<C2StreamComplexityTuning::output> mComplexity;
123 std::shared_ptr<C2StreamMaxBufferSizeInfo::input> mInputMaxBufSize;
124 };
125
C2SoftOpusEnc(const char * name,c2_node_id_t id,const std::shared_ptr<IntfImpl> & intfImpl)126 C2SoftOpusEnc::C2SoftOpusEnc(const char* name, c2_node_id_t id,
127 const std::shared_ptr<IntfImpl>& intfImpl)
128 : SimpleC2Component(
129 std::make_shared<SimpleInterface<IntfImpl>>(name, id, intfImpl)),
130 mIntf(intfImpl),
131 mOutputBlock(nullptr),
132 mEncoder(nullptr),
133 mInputBufferPcm16(nullptr),
134 mOutIndex(0u) {
135 }
136
~C2SoftOpusEnc()137 C2SoftOpusEnc::~C2SoftOpusEnc() {
138 onRelease();
139 }
140
onInit()141 c2_status_t C2SoftOpusEnc::onInit() {
142 return initEncoder();
143 }
144
configureEncoder()145 c2_status_t C2SoftOpusEnc::configureEncoder() {
146 static const unsigned char mono_mapping[256] = {0};
147 static const unsigned char stereo_mapping[256] = {0, 1};
148 mSampleRate = mIntf->getSampleRate();
149 mChannelCount = mIntf->getChannelCount();
150 uint32_t bitrate = mIntf->getBitrate();
151 uint32_t bitrateMode = mIntf->getBitrateMode();
152 int complexity = mIntf->getComplexity();
153 mNumSamplesPerFrame = mSampleRate / (1000 / mFrameDurationMs);
154 mNumPcmBytesPerInputFrame =
155 mChannelCount * mNumSamplesPerFrame * sizeof(int16_t);
156 int err = C2_OK;
157
158 const unsigned char* mapping;
159 if (mChannelCount == 1) {
160 mapping = mono_mapping;
161 } else if (mChannelCount == 2) {
162 mapping = stereo_mapping;
163 } else {
164 ALOGE("Number of channels (%d) is not supported", mChannelCount);
165 return C2_BAD_VALUE;
166 }
167
168 if (mEncoder != nullptr) {
169 opus_multistream_encoder_destroy(mEncoder);
170 }
171
172 mEncoder = opus_multistream_encoder_create(mSampleRate, mChannelCount,
173 1, mChannelCount - 1, mapping, OPUS_APPLICATION_AUDIO, &err);
174 if (err) {
175 ALOGE("Could not create libopus encoder. Error code: %i", err);
176 return C2_CORRUPTED;
177 }
178
179 // Complexity
180 if (opus_multistream_encoder_ctl(
181 mEncoder, OPUS_SET_COMPLEXITY(complexity)) != OPUS_OK) {
182 ALOGE("failed to set complexity");
183 return C2_BAD_VALUE;
184 }
185
186 // DTX
187 if (opus_multistream_encoder_ctl(mEncoder, OPUS_SET_DTX(0) != OPUS_OK)) {
188 ALOGE("failed to set dtx");
189 return C2_BAD_VALUE;
190 }
191
192 // Application
193 if (opus_multistream_encoder_ctl(mEncoder,
194 OPUS_SET_APPLICATION(OPUS_APPLICATION_AUDIO)) != OPUS_OK) {
195 ALOGE("failed to set application");
196 return C2_BAD_VALUE;
197 }
198
199 // Signal type
200 if (opus_multistream_encoder_ctl(mEncoder, OPUS_SET_SIGNAL(OPUS_AUTO)) !=
201 OPUS_OK) {
202 ALOGE("failed to set signal");
203 return C2_BAD_VALUE;
204 }
205
206 if (bitrateMode == C2Config::BITRATE_VARIABLE) {
207 // Constrained VBR
208 if (opus_multistream_encoder_ctl(mEncoder, OPUS_SET_VBR(1) != OPUS_OK)) {
209 ALOGE("failed to set vbr type");
210 return C2_BAD_VALUE;
211 }
212 if (opus_multistream_encoder_ctl(mEncoder, OPUS_SET_VBR_CONSTRAINT(1) !=
213 OPUS_OK)) {
214 ALOGE("failed to set vbr constraint");
215 return C2_BAD_VALUE;
216 }
217 } else if (bitrateMode == C2Config::BITRATE_CONST) {
218 if (opus_multistream_encoder_ctl(mEncoder, OPUS_SET_VBR(0) != OPUS_OK)) {
219 ALOGE("failed to set cbr type");
220 return C2_BAD_VALUE;
221 }
222 } else {
223 ALOGE("unknown bitrate mode");
224 return C2_BAD_VALUE;
225 }
226
227 // Bitrate
228 if (opus_multistream_encoder_ctl(mEncoder, OPUS_SET_BITRATE(bitrate)) !=
229 OPUS_OK) {
230 ALOGE("failed to set bitrate");
231 return C2_BAD_VALUE;
232 }
233
234 // Set seek preroll to 80 ms
235 mSeekPreRoll = 80000000;
236 return C2_OK;
237 }
238
initEncoder()239 c2_status_t C2SoftOpusEnc::initEncoder() {
240 mSignalledEos = false;
241 mSignalledError = false;
242 mHeaderGenerated = false;
243 mIsFirstFrame = true;
244 mEncoderFlushed = false;
245 mBufferAvailable = false;
246 mAnchorTimeStamp = 0;
247 mProcessedSamples = 0;
248 mFilledLen = 0;
249 mFrameDurationMs = kDefaultFrameDurationMs;
250 if (!mInputBufferPcm16) {
251 size_t frameSize = (mFrameDurationMs * kMaxSampleRateSupported) / 1000;
252 mInputBufferPcm16 =
253 (int16_t*)malloc(frameSize * kMaxNumChannelsSupported * sizeof(int16_t));
254 }
255 if (!mInputBufferPcm16) return C2_NO_MEMORY;
256
257 /* Default Configurations */
258 c2_status_t status = configureEncoder();
259 return status;
260 }
261
onStop()262 c2_status_t C2SoftOpusEnc::onStop() {
263 mSignalledEos = false;
264 mSignalledError = false;
265 mIsFirstFrame = true;
266 mEncoderFlushed = false;
267 mBufferAvailable = false;
268 mAnchorTimeStamp = 0;
269 mProcessedSamples = 0u;
270 mFilledLen = 0;
271 if (mEncoder) {
272 int status = opus_multistream_encoder_ctl(mEncoder, OPUS_RESET_STATE);
273 if (status != OPUS_OK) {
274 ALOGE("OPUS_RESET_STATE failed status = %s", opus_strerror(status));
275 mSignalledError = true;
276 return C2_CORRUPTED;
277 }
278 }
279 if (mOutputBlock) mOutputBlock.reset();
280 mOutputBlock = nullptr;
281
282 return C2_OK;
283 }
284
onReset()285 void C2SoftOpusEnc::onReset() {
286 (void)onStop();
287 }
288
onRelease()289 void C2SoftOpusEnc::onRelease() {
290 (void)onStop();
291 if (mInputBufferPcm16) {
292 free(mInputBufferPcm16);
293 mInputBufferPcm16 = nullptr;
294 }
295 if (mEncoder) {
296 opus_multistream_encoder_destroy(mEncoder);
297 mEncoder = nullptr;
298 }
299 }
300
onFlush_sm()301 c2_status_t C2SoftOpusEnc::onFlush_sm() {
302 return onStop();
303 }
304
305 // Drain the encoder to get last frames (if any)
drainEncoder(uint8_t * outPtr)306 int C2SoftOpusEnc::drainEncoder(uint8_t* outPtr) {
307 memset((uint8_t *)mInputBufferPcm16 + mFilledLen, 0,
308 (mNumPcmBytesPerInputFrame - mFilledLen));
309 int encodedBytes = opus_multistream_encode(
310 mEncoder, mInputBufferPcm16, mNumSamplesPerFrame, outPtr, kMaxPayload);
311 if (encodedBytes > mOutputBlock->capacity()) {
312 ALOGE("not enough space left to write encoded data, dropping %d bytes",
313 mBytesEncoded);
314 // a fatal error would stop the encoding
315 return -1;
316 }
317 ALOGV("encoded %i Opus bytes from %zu PCM bytes", encodedBytes,
318 mNumPcmBytesPerInputFrame);
319 mEncoderFlushed = true;
320 mFilledLen = 0;
321 return encodedBytes;
322 }
323
process(const std::unique_ptr<C2Work> & work,const std::shared_ptr<C2BlockPool> & pool)324 void C2SoftOpusEnc::process(const std::unique_ptr<C2Work>& work,
325 const std::shared_ptr<C2BlockPool>& pool) {
326 // Initialize output work
327 work->result = C2_OK;
328 work->workletsProcessed = 1u;
329 work->worklets.front()->output.flags = work->input.flags;
330
331 if (mSignalledError || mSignalledEos) {
332 work->result = C2_BAD_VALUE;
333 return;
334 }
335
336 bool eos = (work->input.flags & C2FrameData::FLAG_END_OF_STREAM) != 0;
337 C2ReadView rView = mDummyReadView;
338 size_t inOffset = 0u;
339 size_t inSize = 0u;
340 c2_status_t err = C2_OK;
341 if (!work->input.buffers.empty()) {
342 rView =
343 work->input.buffers[0]->data().linearBlocks().front().map().get();
344 inSize = rView.capacity();
345 if (inSize && rView.error()) {
346 ALOGE("read view map failed %d", rView.error());
347 work->result = C2_CORRUPTED;
348 return;
349 }
350 }
351
352 ALOGV("in buffer attr. size %zu timestamp %d frameindex %d, flags %x",
353 inSize, (int)work->input.ordinal.timestamp.peeku(),
354 (int)work->input.ordinal.frameIndex.peeku(), work->input.flags);
355
356 if (!mEncoder) {
357 if (initEncoder() != C2_OK) {
358 ALOGE("initEncoder failed with status %d", err);
359 work->result = err;
360 mSignalledError = true;
361 return;
362 }
363 }
364 if (mIsFirstFrame && inSize > 0) {
365 mAnchorTimeStamp = work->input.ordinal.timestamp.peekll();
366 mIsFirstFrame = false;
367 }
368
369 C2MemoryUsage usage = {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
370 int outCapacity =
371 kMaxPayload * ((inSize + mNumPcmBytesPerInputFrame) / mNumPcmBytesPerInputFrame);
372 err = pool->fetchLinearBlock(outCapacity, usage, &mOutputBlock);
373 if (err != C2_OK) {
374 ALOGE("fetchLinearBlock for Output failed with status %d", err);
375 work->result = C2_NO_MEMORY;
376 return;
377 }
378
379 C2WriteView wView = mOutputBlock->map().get();
380 if (wView.error()) {
381 ALOGE("write view map failed %d", wView.error());
382 work->result = C2_CORRUPTED;
383 mOutputBlock.reset();
384 return;
385 }
386
387 size_t inPos = 0;
388 size_t processSize = 0;
389 mBytesEncoded = 0;
390 int64_t outTimeStamp = 0;
391 std::shared_ptr<C2Buffer> buffer;
392 uint64_t inputIndex = work->input.ordinal.frameIndex.peeku();
393 const uint8_t* inPtr = rView.data() + inOffset;
394
395 class FillWork {
396 public:
397 FillWork(uint32_t flags, C2WorkOrdinalStruct ordinal,
398 const std::shared_ptr<C2Buffer> &buffer)
399 : mFlags(flags), mOrdinal(ordinal), mBuffer(buffer) {
400 }
401 ~FillWork() = default;
402
403 void operator()(const std::unique_ptr<C2Work>& work) {
404 work->worklets.front()->output.flags = (C2FrameData::flags_t)mFlags;
405 work->worklets.front()->output.buffers.clear();
406 work->worklets.front()->output.ordinal = mOrdinal;
407 work->workletsProcessed = 1u;
408 work->result = C2_OK;
409 if (mBuffer) {
410 work->worklets.front()->output.buffers.push_back(mBuffer);
411 }
412 ALOGV("timestamp = %lld, index = %lld, w/%s buffer",
413 mOrdinal.timestamp.peekll(),
414 mOrdinal.frameIndex.peekll(),
415 mBuffer ? "" : "o");
416 }
417
418 private:
419 const uint32_t mFlags;
420 const C2WorkOrdinalStruct mOrdinal;
421 const std::shared_ptr<C2Buffer> mBuffer;
422 };
423
424 C2WorkOrdinalStruct outOrdinal = work->input.ordinal;
425
426 if (!mHeaderGenerated) {
427 uint8_t header[AOPUS_UNIFIED_CSD_MAXSIZE];
428 memset(header, 0, sizeof(header));
429
430 // Get codecDelay
431 int32_t lookahead;
432 if (opus_multistream_encoder_ctl(mEncoder, OPUS_GET_LOOKAHEAD(&lookahead)) !=
433 OPUS_OK) {
434 ALOGE("failed to get lookahead");
435 mSignalledError = true;
436 work->result = C2_CORRUPTED;
437 return;
438 }
439 mCodecDelay = lookahead * 1000000000ll / mSampleRate;
440
441 OpusHeader opusHeader;
442 memset(&opusHeader, 0, sizeof(opusHeader));
443 opusHeader.channels = mChannelCount;
444 opusHeader.num_streams = mChannelCount;
445 opusHeader.num_coupled = 0;
446 opusHeader.channel_mapping = ((mChannelCount > 8) ? 255 : (mChannelCount > 2));
447 opusHeader.gain_db = 0;
448 opusHeader.skip_samples = lookahead;
449 int headerLen = WriteOpusHeaders(opusHeader, mSampleRate, header,
450 sizeof(header), mCodecDelay, mSeekPreRoll);
451
452 std::unique_ptr<C2StreamInitDataInfo::output> csd =
453 C2StreamInitDataInfo::output::AllocUnique(headerLen, 0u);
454 if (!csd) {
455 ALOGE("CSD allocation failed");
456 mSignalledError = true;
457 work->result = C2_NO_MEMORY;
458 return;
459 }
460 ALOGV("put csd, %d bytes", headerLen);
461 memcpy(csd->m.value, header, headerLen);
462 work->worklets.front()->output.configUpdate.push_back(std::move(csd));
463 mHeaderGenerated = true;
464 }
465
466 /*
467 * For buffer size which is not a multiple of mNumPcmBytesPerInputFrame, we will
468 * accumulate the input and keep it. Once the input is filled with expected number
469 * of bytes, we will send it to encoder. mFilledLen manages the bytes of input yet
470 * to be processed. The next call will fill mNumPcmBytesPerInputFrame - mFilledLen
471 * bytes to input and send it to the encoder.
472 */
473 while (inPos < inSize) {
474 const uint8_t* pcmBytes = inPtr + inPos;
475 int filledSamples = mFilledLen / sizeof(int16_t);
476 if ((inPos + (mNumPcmBytesPerInputFrame - mFilledLen)) <= inSize) {
477 processSize = mNumPcmBytesPerInputFrame - mFilledLen;
478 mBufferAvailable = true;
479 } else {
480 processSize = inSize - inPos;
481 mBufferAvailable = false;
482 if (eos) {
483 memset(mInputBufferPcm16 + filledSamples, 0,
484 (mNumPcmBytesPerInputFrame - mFilledLen));
485 mBufferAvailable = true;
486 }
487 }
488 const unsigned nInputSamples = processSize / sizeof(int16_t);
489
490 for (unsigned i = 0; i < nInputSamples; i++) {
491 int32_t data = pcmBytes[2 * i + 1] << 8 | pcmBytes[2 * i];
492 data = ((data & 0xFFFF) ^ 0x8000) - 0x8000;
493 mInputBufferPcm16[i + filledSamples] = data;
494 }
495 inPos += processSize;
496 mFilledLen += processSize;
497 if (!mBufferAvailable) break;
498 uint8_t* outPtr = wView.data() + mBytesEncoded;
499 int encodedBytes =
500 opus_multistream_encode(mEncoder, mInputBufferPcm16,
501 mNumSamplesPerFrame, outPtr, outCapacity - mBytesEncoded);
502 ALOGV("encoded %i Opus bytes from %zu PCM bytes", encodedBytes,
503 processSize);
504
505 if (encodedBytes < 0 || encodedBytes > (outCapacity - mBytesEncoded)) {
506 ALOGE("opus_encode failed, encodedBytes : %d", encodedBytes);
507 mSignalledError = true;
508 work->result = C2_CORRUPTED;
509 return;
510 }
511 if (buffer) {
512 outOrdinal.frameIndex = mOutIndex++;
513 outOrdinal.timestamp = mAnchorTimeStamp + outTimeStamp;
514 cloneAndSend(
515 inputIndex, work,
516 FillWork(C2FrameData::FLAG_INCOMPLETE, outOrdinal, buffer));
517 buffer.reset();
518 }
519 if (encodedBytes > 0) {
520 buffer =
521 createLinearBuffer(mOutputBlock, mBytesEncoded, encodedBytes);
522 }
523 mBytesEncoded += encodedBytes;
524 mProcessedSamples += (filledSamples + nInputSamples);
525 outTimeStamp =
526 mProcessedSamples * 1000000ll / mChannelCount / mSampleRate;
527 if ((processSize + mFilledLen) < mNumPcmBytesPerInputFrame)
528 mEncoderFlushed = true;
529 mFilledLen = 0;
530 }
531
532 uint32_t flags = 0;
533 if (eos) {
534 ALOGV("signalled eos");
535 mSignalledEos = true;
536 if (!mEncoderFlushed) {
537 if (buffer) {
538 outOrdinal.frameIndex = mOutIndex++;
539 outOrdinal.timestamp = mAnchorTimeStamp + outTimeStamp;
540 cloneAndSend(
541 inputIndex, work,
542 FillWork(C2FrameData::FLAG_INCOMPLETE, outOrdinal, buffer));
543 buffer.reset();
544 }
545 // drain the encoder for last buffer
546 drainInternal(pool, work);
547 }
548 flags = C2FrameData::FLAG_END_OF_STREAM;
549 }
550 if (buffer) {
551 outOrdinal.frameIndex = mOutIndex++;
552 outOrdinal.timestamp = mAnchorTimeStamp + outTimeStamp;
553 FillWork((C2FrameData::flags_t)(flags), outOrdinal, buffer)(work);
554 buffer.reset();
555 }
556 mOutputBlock = nullptr;
557 }
558
drainInternal(const std::shared_ptr<C2BlockPool> & pool,const std::unique_ptr<C2Work> & work)559 c2_status_t C2SoftOpusEnc::drainInternal(
560 const std::shared_ptr<C2BlockPool>& pool,
561 const std::unique_ptr<C2Work>& work) {
562 mBytesEncoded = 0;
563 std::shared_ptr<C2Buffer> buffer = nullptr;
564 C2WorkOrdinalStruct outOrdinal = work->input.ordinal;
565 bool eos = (work->input.flags & C2FrameData::FLAG_END_OF_STREAM) != 0;
566
567 C2MemoryUsage usage = {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
568 c2_status_t err = pool->fetchLinearBlock(kMaxPayload, usage, &mOutputBlock);
569 if (err != C2_OK) {
570 ALOGE("fetchLinearBlock for Output failed with status %d", err);
571 return C2_NO_MEMORY;
572 }
573
574 C2WriteView wView = mOutputBlock->map().get();
575 if (wView.error()) {
576 ALOGE("write view map failed %d", wView.error());
577 mOutputBlock.reset();
578 return C2_CORRUPTED;
579 }
580
581 int encBytes = drainEncoder(wView.data());
582 if (encBytes > 0) mBytesEncoded += encBytes;
583 if (mBytesEncoded > 0) {
584 buffer = createLinearBuffer(mOutputBlock, 0, mBytesEncoded);
585 mOutputBlock.reset();
586 }
587 mProcessedSamples += (mNumPcmBytesPerInputFrame / sizeof(int16_t));
588 int64_t outTimeStamp =
589 mProcessedSamples * 1000000ll / mChannelCount / mSampleRate;
590 outOrdinal.frameIndex = mOutIndex++;
591 outOrdinal.timestamp = mAnchorTimeStamp + outTimeStamp;
592 work->worklets.front()->output.flags =
593 (C2FrameData::flags_t)(eos ? C2FrameData::FLAG_END_OF_STREAM : 0);
594 work->worklets.front()->output.buffers.clear();
595 work->worklets.front()->output.ordinal = outOrdinal;
596 work->workletsProcessed = 1u;
597 work->result = C2_OK;
598 if (buffer) {
599 work->worklets.front()->output.buffers.push_back(buffer);
600 }
601 mOutputBlock = nullptr;
602 return C2_OK;
603 }
604
drain(uint32_t drainMode,const std::shared_ptr<C2BlockPool> & pool)605 c2_status_t C2SoftOpusEnc::drain(uint32_t drainMode,
606 const std::shared_ptr<C2BlockPool>& pool) {
607 if (drainMode == NO_DRAIN) {
608 ALOGW("drain with NO_DRAIN: no-op");
609 return C2_OK;
610 }
611 if (drainMode == DRAIN_CHAIN) {
612 ALOGW("DRAIN_CHAIN not supported");
613 return C2_OMITTED;
614 }
615 mIsFirstFrame = true;
616 mAnchorTimeStamp = 0;
617 mProcessedSamples = 0u;
618 return drainInternal(pool, nullptr);
619 }
620
621 class C2SoftOpusEncFactory : public C2ComponentFactory {
622 public:
C2SoftOpusEncFactory()623 C2SoftOpusEncFactory()
624 : mHelper(std::static_pointer_cast<C2ReflectorHelper>(
625 GetCodec2PlatformComponentStore()->getParamReflector())) {}
626
createComponent(c2_node_id_t id,std::shared_ptr<C2Component> * const component,std::function<void (C2Component *)> deleter)627 virtual c2_status_t createComponent(
628 c2_node_id_t id, std::shared_ptr<C2Component>* const component,
629 std::function<void(C2Component*)> deleter) override {
630 *component = std::shared_ptr<C2Component>(
631 new C2SoftOpusEnc(
632 COMPONENT_NAME, id,
633 std::make_shared<C2SoftOpusEnc::IntfImpl>(mHelper)),
634 deleter);
635 return C2_OK;
636 }
637
createInterface(c2_node_id_t id,std::shared_ptr<C2ComponentInterface> * const interface,std::function<void (C2ComponentInterface *)> deleter)638 virtual c2_status_t createInterface(
639 c2_node_id_t id, std::shared_ptr<C2ComponentInterface>* const interface,
640 std::function<void(C2ComponentInterface*)> deleter) override {
641 *interface = std::shared_ptr<C2ComponentInterface>(
642 new SimpleInterface<C2SoftOpusEnc::IntfImpl>(
643 COMPONENT_NAME, id,
644 std::make_shared<C2SoftOpusEnc::IntfImpl>(mHelper)),
645 deleter);
646 return C2_OK;
647 }
648
649 virtual ~C2SoftOpusEncFactory() override = default;
650 private:
651 std::shared_ptr<C2ReflectorHelper> mHelper;
652 };
653
654 } // namespace android
655
656 __attribute__((cfi_canonical_jump_table))
CreateCodec2Factory()657 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
658 ALOGV("in %s", __func__);
659 return new ::android::C2SoftOpusEncFactory();
660 }
661
662 __attribute__((cfi_canonical_jump_table))
DestroyCodec2Factory(::C2ComponentFactory * factory)663 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
664 ALOGV("in %s", __func__);
665 delete factory;
666 }
667