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