blob: cf34dffacb0e684f5d4af39dfdded7a1e37178aa [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright (C) 2018 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 "C2SoftFlacEnc"
19#include <log/log.h>
20
Andy Hung1188a052019-01-02 13:09:52 -080021#include <audio_utils/primitives.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080022#include <media/stagefright/foundation/MediaDefs.h>
23
24#include <C2PlatformSupport.h>
25#include <SimpleC2Interface.h>
26
27#include "C2SoftFlacEnc.h"
28
29namespace android {
30
Rakesh Kumar66d9d062019-03-12 17:46:17 +053031namespace {
32
33constexpr char COMPONENT_NAME[] = "c2.android.flac.encoder";
34
35} // namespace
36
37class C2SoftFlacEnc::IntfImpl : public SimpleInterface<void>::BaseParams {
Pawin Vongmasa36653902018-11-15 00:10:25 -080038public:
39 explicit IntfImpl(const std::shared_ptr<C2ReflectorHelper> &helper)
Rakesh Kumar66d9d062019-03-12 17:46:17 +053040 : SimpleInterface<void>::BaseParams(
41 helper,
42 COMPONENT_NAME,
43 C2Component::KIND_ENCODER,
44 C2Component::DOMAIN_AUDIO,
45 MEDIA_MIMETYPE_AUDIO_FLAC) {
46 noPrivateBuffers();
47 noInputReferences();
48 noOutputReferences();
49 noInputLatency();
50 noTimeStretch();
Pawin Vongmasa36653902018-11-15 00:10:25 -080051 setDerivedInstance(this);
Rakesh Kumar66d9d062019-03-12 17:46:17 +053052
Pawin Vongmasa36653902018-11-15 00:10:25 -080053 addParameter(
Rakesh Kumar66d9d062019-03-12 17:46:17 +053054 DefineParam(mAttrib, C2_PARAMKEY_COMPONENT_ATTRIBUTES)
55 .withConstValue(new C2ComponentAttributesSetting(
56 C2Component::ATTRIB_IS_TEMPORAL))
Pawin Vongmasa36653902018-11-15 00:10:25 -080057 .build());
58 addParameter(
Lajos Molnar3bb81cd2019-02-20 15:10:30 -080059 DefineParam(mSampleRate, C2_PARAMKEY_SAMPLE_RATE)
Pawin Vongmasa36653902018-11-15 00:10:25 -080060 .withDefault(new C2StreamSampleRateInfo::input(0u, 44100))
61 .withFields({C2F(mSampleRate, value).inRange(1, 655350)})
62 .withSetter((Setter<decltype(*mSampleRate)>::StrictValueWithNoDeps))
63 .build());
64 addParameter(
Lajos Molnar3bb81cd2019-02-20 15:10:30 -080065 DefineParam(mChannelCount, C2_PARAMKEY_CHANNEL_COUNT)
Pawin Vongmasa36653902018-11-15 00:10:25 -080066 .withDefault(new C2StreamChannelCountInfo::input(0u, 1))
67 .withFields({C2F(mChannelCount, value).inRange(1, 2)})
68 .withSetter(Setter<decltype(*mChannelCount)>::StrictValueWithNoDeps)
69 .build());
70 addParameter(
Lajos Molnar3bb81cd2019-02-20 15:10:30 -080071 DefineParam(mBitrate, C2_PARAMKEY_BITRATE)
72 .withDefault(new C2StreamBitrateInfo::output(0u, 768000))
Pawin Vongmasa36653902018-11-15 00:10:25 -080073 .withFields({C2F(mBitrate, value).inRange(1, 21000000)})
74 .withSetter(Setter<decltype(*mBitrate)>::NonStrictValueWithNoDeps)
75 .build());
76 addParameter(
77 DefineParam(mInputMaxBufSize, C2_PARAMKEY_INPUT_MAX_BUFFER_SIZE)
78 .withConstValue(new C2StreamMaxBufferSizeInfo::input(0u, 4608))
79 .build());
Andy Hung1188a052019-01-02 13:09:52 -080080
81 addParameter(
82 DefineParam(mPcmEncodingInfo, C2_PARAMKEY_PCM_ENCODING)
83 .withDefault(new C2StreamPcmEncodingInfo::input(0u, C2Config::PCM_16))
84 .withFields({C2F(mPcmEncodingInfo, value).oneOf({
85 C2Config::PCM_16,
86 // C2Config::PCM_8,
87 C2Config::PCM_FLOAT})
88 })
89 .withSetter((Setter<decltype(*mPcmEncodingInfo)>::StrictValueWithNoDeps))
90 .build());
Pawin Vongmasa36653902018-11-15 00:10:25 -080091 }
92
93 uint32_t getSampleRate() const { return mSampleRate->value; }
94 uint32_t getChannelCount() const { return mChannelCount->value; }
95 uint32_t getBitrate() const { return mBitrate->value; }
Andy Hung1188a052019-01-02 13:09:52 -080096 int32_t getPcmEncodingInfo() const { return mPcmEncodingInfo->value; }
Pawin Vongmasa36653902018-11-15 00:10:25 -080097
98private:
Pawin Vongmasa36653902018-11-15 00:10:25 -080099 std::shared_ptr<C2StreamSampleRateInfo::input> mSampleRate;
100 std::shared_ptr<C2StreamChannelCountInfo::input> mChannelCount;
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800101 std::shared_ptr<C2StreamBitrateInfo::output> mBitrate;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800102 std::shared_ptr<C2StreamMaxBufferSizeInfo::input> mInputMaxBufSize;
Andy Hung1188a052019-01-02 13:09:52 -0800103 std::shared_ptr<C2StreamPcmEncodingInfo::input> mPcmEncodingInfo;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800104};
Pawin Vongmasa36653902018-11-15 00:10:25 -0800105
106C2SoftFlacEnc::C2SoftFlacEnc(
107 const char *name,
108 c2_node_id_t id,
109 const std::shared_ptr<IntfImpl> &intfImpl)
110 : SimpleC2Component(std::make_shared<SimpleInterface<IntfImpl>>(name, id, intfImpl)),
111 mIntf(intfImpl),
112 mFlacStreamEncoder(nullptr),
113 mInputBufferPcm32(nullptr) {
114}
115
116C2SoftFlacEnc::~C2SoftFlacEnc() {
117 onRelease();
118}
119
120c2_status_t C2SoftFlacEnc::onInit() {
121 mFlacStreamEncoder = FLAC__stream_encoder_new();
122 if (!mFlacStreamEncoder) return C2_CORRUPTED;
123
124 mInputBufferPcm32 = (FLAC__int32*) malloc(
125 kInBlockSize * kMaxNumChannels * sizeof(FLAC__int32));
126 if (!mInputBufferPcm32) return C2_NO_MEMORY;
127
128 mSignalledError = false;
129 mSignalledOutputEos = false;
130 mCompressionLevel = FLAC_COMPRESSION_LEVEL_DEFAULT;
131 mIsFirstFrame = true;
132 mAnchorTimeStamp = 0ull;
133 mProcessedSamples = 0u;
134 mEncoderWriteData = false;
135 mEncoderReturnedNbBytes = 0;
136 mHeaderOffset = 0;
137 mWroteHeader = false;
138
139 status_t err = configureEncoder();
140 return err == OK ? C2_OK : C2_CORRUPTED;
141}
142
143void C2SoftFlacEnc::onRelease() {
144 if (mFlacStreamEncoder) {
145 FLAC__stream_encoder_delete(mFlacStreamEncoder);
146 mFlacStreamEncoder = nullptr;
147 }
148
149 if (mInputBufferPcm32) {
150 free(mInputBufferPcm32);
151 mInputBufferPcm32 = nullptr;
152 }
153}
154
155void C2SoftFlacEnc::onReset() {
156 mCompressionLevel = FLAC_COMPRESSION_LEVEL_DEFAULT;
157 (void) onStop();
158}
159
160c2_status_t C2SoftFlacEnc::onStop() {
161 mSignalledError = false;
162 mSignalledOutputEos = false;
163 mIsFirstFrame = true;
164 mAnchorTimeStamp = 0ull;
165 mProcessedSamples = 0u;
166 mEncoderWriteData = false;
167 mEncoderReturnedNbBytes = 0;
168 mHeaderOffset = 0;
169 mWroteHeader = false;
170
171 c2_status_t status = drain(DRAIN_COMPONENT_NO_EOS, nullptr);
172 if (C2_OK != status) return status;
173
174 status_t err = configureEncoder();
175 if (err != OK) mSignalledError = true;
176 return C2_OK;
177}
178
179c2_status_t C2SoftFlacEnc::onFlush_sm() {
180 return onStop();
181}
182
183static void fillEmptyWork(const std::unique_ptr<C2Work> &work) {
184 work->worklets.front()->output.flags = work->input.flags;
185 work->worklets.front()->output.buffers.clear();
186 work->worklets.front()->output.ordinal = work->input.ordinal;
187}
188
189void C2SoftFlacEnc::process(
190 const std::unique_ptr<C2Work> &work,
191 const std::shared_ptr<C2BlockPool> &pool) {
192 // Initialize output work
193 work->result = C2_OK;
194 work->workletsProcessed = 1u;
195 work->worklets.front()->output.flags = work->input.flags;
196
197 if (mSignalledError || mSignalledOutputEos) {
198 work->result = C2_BAD_VALUE;
199 return;
200 }
201
202 bool eos = ((work->input.flags & C2FrameData::FLAG_END_OF_STREAM) != 0);
203 C2ReadView rView = mDummyReadView;
204 size_t inOffset = 0u;
205 size_t inSize = 0u;
206 if (!work->input.buffers.empty()) {
207 rView = work->input.buffers[0]->data().linearBlocks().front().map().get();
208 inSize = rView.capacity();
209 if (inSize && rView.error()) {
210 ALOGE("read view map failed %d", rView.error());
211 work->result = C2_CORRUPTED;
212 return;
213 }
214 }
215
216 ALOGV("in buffer attr. size %zu timestamp %d frameindex %d, flags %x",
217 inSize, (int)work->input.ordinal.timestamp.peeku(),
218 (int)work->input.ordinal.frameIndex.peeku(), work->input.flags);
219 if (mIsFirstFrame && inSize) {
220 mAnchorTimeStamp = work->input.ordinal.timestamp.peekull();
221 mIsFirstFrame = false;
222 }
223
224 if (!mWroteHeader) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800225 std::unique_ptr<C2StreamInitDataInfo::output> csd =
226 C2StreamInitDataInfo::output::AllocUnique(mHeaderOffset, 0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800227 if (!csd) {
228 ALOGE("CSD allocation failed");
229 mSignalledError = true;
230 work->result = C2_NO_MEMORY;
231 return;
232 }
233 memcpy(csd->m.value, mHeader, mHeaderOffset);
234 ALOGV("put csd, %d bytes", mHeaderOffset);
235
236 work->worklets.front()->output.configUpdate.push_back(std::move(csd));
237 mWroteHeader = true;
238 }
239
Andy Hung1188a052019-01-02 13:09:52 -0800240 const uint32_t sampleRate = mIntf->getSampleRate();
241 const uint32_t channelCount = mIntf->getChannelCount();
242 const bool inputFloat = mIntf->getPcmEncodingInfo() == C2Config::PCM_FLOAT;
243 const unsigned sampleSize = inputFloat ? sizeof(float) : sizeof(int16_t);
244 const unsigned frameSize = channelCount * sampleSize;
245 const uint64_t outTimeStamp = mProcessedSamples * 1000000ll / sampleRate;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800246
247 size_t outCapacity = inSize;
Andy Hung1188a052019-01-02 13:09:52 -0800248 outCapacity += mBlockSize * frameSize;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800249
250 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
251 c2_status_t err = pool->fetchLinearBlock(outCapacity, usage, &mOutputBlock);
252 if (err != C2_OK) {
253 ALOGE("fetchLinearBlock for Output failed with status %d", err);
254 work->result = C2_NO_MEMORY;
255 return;
256 }
257 C2WriteView wView = mOutputBlock->map().get();
258 if (wView.error()) {
259 ALOGE("write view map failed %d", wView.error());
260 work->result = C2_CORRUPTED;
261 return;
262 }
263
264 mEncoderWriteData = true;
265 mEncoderReturnedNbBytes = 0;
266 size_t inPos = 0;
267 while (inPos < inSize) {
268 const uint8_t *inPtr = rView.data() + inOffset;
Andy Hung1188a052019-01-02 13:09:52 -0800269 const size_t processSize = MIN(kInBlockSize * frameSize, (inSize - inPos));
270 const unsigned nbInputFrames = processSize / frameSize;
271 const unsigned nbInputSamples = processSize / sampleSize;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800272
Andy Hung1188a052019-01-02 13:09:52 -0800273 ALOGV("about to encode %zu bytes", processSize);
274 if (inputFloat) {
275 const float * const pcmFloat = reinterpret_cast<const float *>(inPtr + inPos);
276 memcpy_to_q8_23_from_float_with_clamp(mInputBufferPcm32, pcmFloat, nbInputSamples);
277 } else {
278 const int16_t * const pcm16 = reinterpret_cast<const int16_t *>(inPtr + inPos);
279 for (unsigned i = 0; i < nbInputSamples; i++) {
280 mInputBufferPcm32[i] = (FLAC__int32) pcm16[i];
281 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800282 }
283
284 FLAC__bool ok = FLAC__stream_encoder_process_interleaved(
285 mFlacStreamEncoder, mInputBufferPcm32, nbInputFrames);
286 if (!ok) {
287 ALOGE("error encountered during encoding");
288 mSignalledError = true;
289 work->result = C2_CORRUPTED;
290 mOutputBlock.reset();
291 return;
292 }
293 inPos += processSize;
294 }
295 if (eos && (C2_OK != drain(DRAIN_COMPONENT_WITH_EOS, pool))) {
296 ALOGE("error encountered during encoding");
297 mSignalledError = true;
298 work->result = C2_CORRUPTED;
299 mOutputBlock.reset();
300 return;
301 }
302 fillEmptyWork(work);
303 if (mEncoderReturnedNbBytes != 0) {
304 std::shared_ptr<C2Buffer> buffer = createLinearBuffer(std::move(mOutputBlock), 0, mEncoderReturnedNbBytes);
305 work->worklets.front()->output.buffers.push_back(buffer);
306 work->worklets.front()->output.ordinal.timestamp = mAnchorTimeStamp + outTimeStamp;
307 } else {
308 ALOGV("encoder process_interleaved returned without data to write");
309 }
310 mOutputBlock = nullptr;
311 if (eos) {
312 mSignalledOutputEos = true;
313 ALOGV("signalled EOS");
314 }
315 mEncoderWriteData = false;
316 mEncoderReturnedNbBytes = 0;
317}
318
319FLAC__StreamEncoderWriteStatus C2SoftFlacEnc::onEncodedFlacAvailable(
320 const FLAC__byte buffer[], size_t bytes, unsigned samples,
321 unsigned current_frame) {
322 (void) current_frame;
323 ALOGV("%s (bytes=%zu, samples=%u, curr_frame=%u)", __func__, bytes, samples,
324 current_frame);
325
326 if (samples == 0) {
327 ALOGI("saving %zu bytes of header", bytes);
328 memcpy(mHeader + mHeaderOffset, buffer, bytes);
329 mHeaderOffset += bytes;// will contain header size when finished receiving header
330 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
331 }
332
333 if ((samples == 0) || !mEncoderWriteData) {
334 // called by the encoder because there's header data to save, but it's not the role
335 // of this component (unless WRITE_FLAC_HEADER_IN_FIRST_BUFFER is defined)
336 ALOGV("ignoring %zu bytes of header data (samples=%d)", bytes, samples);
337 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
338 }
339
340 // write encoded data
341 C2WriteView wView = mOutputBlock->map().get();
342 uint8_t* outData = wView.data();
343 ALOGV("writing %zu bytes of encoded data on output", bytes);
344 // increment mProcessedSamples to maintain audio synchronization during
345 // play back
346 mProcessedSamples += samples;
347 if (bytes + mEncoderReturnedNbBytes > mOutputBlock->capacity()) {
348 ALOGE("not enough space left to write encoded data, dropping %zu bytes", bytes);
349 // a fatal error would stop the encoding
350 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
351 }
352 memcpy(outData + mEncoderReturnedNbBytes, buffer, bytes);
353 mEncoderReturnedNbBytes += bytes;
354 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
355}
356
357
358status_t C2SoftFlacEnc::configureEncoder() {
359 ALOGV("%s numChannel=%d, sampleRate=%d", __func__, mIntf->getChannelCount(), mIntf->getSampleRate());
360
361 if (mSignalledError || !mFlacStreamEncoder) {
362 ALOGE("can't configure encoder: no encoder or invalid state");
363 return UNKNOWN_ERROR;
364 }
365
Andy Hung1188a052019-01-02 13:09:52 -0800366 const bool inputFloat = mIntf->getPcmEncodingInfo() == C2Config::PCM_FLOAT;
367 const int bitsPerSample = inputFloat ? 24 : 16;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800368 FLAC__bool ok = true;
369 ok = ok && FLAC__stream_encoder_set_channels(mFlacStreamEncoder, mIntf->getChannelCount());
370 ok = ok && FLAC__stream_encoder_set_sample_rate(mFlacStreamEncoder, mIntf->getSampleRate());
Andy Hung1188a052019-01-02 13:09:52 -0800371 ok = ok && FLAC__stream_encoder_set_bits_per_sample(mFlacStreamEncoder, bitsPerSample);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800372 ok = ok && FLAC__stream_encoder_set_compression_level(mFlacStreamEncoder, mCompressionLevel);
373 ok = ok && FLAC__stream_encoder_set_verify(mFlacStreamEncoder, false);
374 if (!ok) {
375 ALOGE("unknown error when configuring encoder");
376 return UNKNOWN_ERROR;
377 }
378
379 ok &= FLAC__STREAM_ENCODER_INIT_STATUS_OK ==
380 FLAC__stream_encoder_init_stream(mFlacStreamEncoder,
381 flacEncoderWriteCallback /*write_callback*/,
382 nullptr /*seek_callback*/,
383 nullptr /*tell_callback*/,
384 nullptr /*metadata_callback*/,
385 (void *) this /*client_data*/);
386
387 if (!ok) {
388 ALOGE("unknown error when configuring encoder");
389 return UNKNOWN_ERROR;
390 }
391
392 mBlockSize = FLAC__stream_encoder_get_blocksize(mFlacStreamEncoder);
393
394 ALOGV("encoder successfully configured");
395 return OK;
396}
397
398FLAC__StreamEncoderWriteStatus C2SoftFlacEnc::flacEncoderWriteCallback(
399 const FLAC__StreamEncoder *,
400 const FLAC__byte buffer[],
401 size_t bytes,
402 unsigned samples,
403 unsigned current_frame,
404 void *client_data) {
405 return ((C2SoftFlacEnc*) client_data)->onEncodedFlacAvailable(
406 buffer, bytes, samples, current_frame);
407}
408
409c2_status_t C2SoftFlacEnc::drain(
410 uint32_t drainMode,
411 const std::shared_ptr<C2BlockPool> &pool) {
412 (void) pool;
413 switch (drainMode) {
414 case NO_DRAIN:
415 ALOGW("drain with NO_DRAIN: no-op");
416 return C2_OK;
417 case DRAIN_CHAIN:
418 ALOGW("DRAIN_CHAIN not supported");
419 return C2_OMITTED;
420 case DRAIN_COMPONENT_WITH_EOS:
421 // TODO: This flag is not being sent back to the client
422 // because there are no items in PendingWork queue as all the
423 // inputs are being sent back with emptywork or valid encoded data
424 // mSignalledOutputEos = true;
425 case DRAIN_COMPONENT_NO_EOS:
426 break;
427 default:
428 return C2_BAD_VALUE;
429 }
430 FLAC__bool ok = FLAC__stream_encoder_finish(mFlacStreamEncoder);
431 if (!ok) return C2_CORRUPTED;
432 mIsFirstFrame = true;
433 mAnchorTimeStamp = 0ull;
434 mProcessedSamples = 0u;
435
436 return C2_OK;
437}
438
439class C2SoftFlacEncFactory : public C2ComponentFactory {
440public:
441 C2SoftFlacEncFactory() : mHelper(std::static_pointer_cast<C2ReflectorHelper>(
442 GetCodec2PlatformComponentStore()->getParamReflector())) {
443 }
444
445 virtual c2_status_t createComponent(
446 c2_node_id_t id,
447 std::shared_ptr<C2Component>* const component,
448 std::function<void(C2Component*)> deleter) override {
449 *component = std::shared_ptr<C2Component>(
450 new C2SoftFlacEnc(COMPONENT_NAME,
451 id,
452 std::make_shared<C2SoftFlacEnc::IntfImpl>(mHelper)),
453 deleter);
454 return C2_OK;
455 }
456
457 virtual c2_status_t createInterface(
458 c2_node_id_t id,
459 std::shared_ptr<C2ComponentInterface>* const interface,
460 std::function<void(C2ComponentInterface*)> deleter) override {
461 *interface = std::shared_ptr<C2ComponentInterface>(
462 new SimpleInterface<C2SoftFlacEnc::IntfImpl>(
463 COMPONENT_NAME, id, std::make_shared<C2SoftFlacEnc::IntfImpl>(mHelper)),
464 deleter);
465 return C2_OK;
466 }
467
468 virtual ~C2SoftFlacEncFactory() override = default;
469private:
470 std::shared_ptr<C2ReflectorHelper> mHelper;
471};
472
473} // namespace android
474
475extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
476 ALOGV("in %s", __func__);
477 return new ::android::C2SoftFlacEncFactory();
478}
479
480extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
481 ALOGV("in %s", __func__);
482 delete factory;
483}