1 /*
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 "C2SoftMp3Dec"
19 #include <inttypes.h>
20 #include <log/log.h>
21
22 #include <numeric>
23
24 #include <media/stagefright/foundation/MediaDefs.h>
25
26 #include <C2PlatformSupport.h>
27 #include <SimpleC2Interface.h>
28
29 #include "C2SoftMp3Dec.h"
30 #include "pvmp3decoder_api.h"
31
32 namespace android {
33
34 namespace {
35
36 constexpr char COMPONENT_NAME[] = "c2.android.mp3.decoder";
37
38 } // namespace
39
40 class C2SoftMP3::IntfImpl : public SimpleInterface<void>::BaseParams {
41 public:
IntfImpl(const std::shared_ptr<C2ReflectorHelper> & helper)42 explicit IntfImpl(const std::shared_ptr<C2ReflectorHelper> &helper)
43 : SimpleInterface<void>::BaseParams(
44 helper,
45 COMPONENT_NAME,
46 C2Component::KIND_DECODER,
47 C2Component::DOMAIN_AUDIO,
48 MEDIA_MIMETYPE_AUDIO_MPEG) {
49 noPrivateBuffers();
50 noInputReferences();
51 noOutputReferences();
52 noInputLatency();
53 noTimeStretch();
54 setDerivedInstance(this);
55
56 addParameter(
57 DefineParam(mAttrib, C2_PARAMKEY_COMPONENT_ATTRIBUTES)
58 .withConstValue(new C2ComponentAttributesSetting(
59 C2Component::ATTRIB_IS_TEMPORAL))
60 .build());
61
62 addParameter(
63 DefineParam(mSampleRate, C2_PARAMKEY_SAMPLE_RATE)
64 .withDefault(new C2StreamSampleRateInfo::output(0u, 44100))
65 .withFields({C2F(mSampleRate, value).oneOf({8000, 11025, 12000, 16000,
66 22050, 24000, 32000, 44100, 48000})})
67 .withSetter((Setter<decltype(*mSampleRate)>::StrictValueWithNoDeps))
68 .build());
69
70 addParameter(
71 DefineParam(mChannelCount, C2_PARAMKEY_CHANNEL_COUNT)
72 .withDefault(new C2StreamChannelCountInfo::output(0u, 2))
73 .withFields({C2F(mChannelCount, value).inRange(1, 2)})
74 .withSetter(Setter<decltype(*mChannelCount)>::StrictValueWithNoDeps)
75 .build());
76
77 addParameter(
78 DefineParam(mBitrate, C2_PARAMKEY_BITRATE)
79 .withDefault(new C2StreamBitrateInfo::input(0u, 64000))
80 .withFields({C2F(mBitrate, value).inRange(8000, 320000)})
81 .withSetter(Setter<decltype(*mBitrate)>::NonStrictValueWithNoDeps)
82 .build());
83
84 addParameter(
85 DefineParam(mInputMaxBufSize, C2_PARAMKEY_INPUT_MAX_BUFFER_SIZE)
86 .withConstValue(new C2StreamMaxBufferSizeInfo::input(0u, 8192))
87 .build());
88 }
89
90 private:
91 std::shared_ptr<C2StreamSampleRateInfo::output> mSampleRate;
92 std::shared_ptr<C2StreamChannelCountInfo::output> mChannelCount;
93 std::shared_ptr<C2StreamBitrateInfo::input> mBitrate;
94 std::shared_ptr<C2StreamMaxBufferSizeInfo::input> mInputMaxBufSize;
95 };
96
C2SoftMP3(const char * name,c2_node_id_t id,const std::shared_ptr<IntfImpl> & intfImpl)97 C2SoftMP3::C2SoftMP3(const char *name, c2_node_id_t id,
98 const std::shared_ptr<IntfImpl> &intfImpl)
99 : SimpleC2Component(std::make_shared<SimpleInterface<IntfImpl>>(name, id, intfImpl)),
100 mIntf(intfImpl),
101 mConfig(nullptr),
102 mDecoderBuf(nullptr) {
103 }
104
C2SoftMP3(const char * name,c2_node_id_t id,const std::shared_ptr<C2ReflectorHelper> & helper)105 C2SoftMP3::C2SoftMP3(const char *name, c2_node_id_t id,
106 const std::shared_ptr<C2ReflectorHelper> &helper)
107 : C2SoftMP3(name, id, std::make_shared<IntfImpl>(helper)) {
108 }
109
~C2SoftMP3()110 C2SoftMP3::~C2SoftMP3() {
111 onRelease();
112 }
113
onInit()114 c2_status_t C2SoftMP3::onInit() {
115 status_t err = initDecoder();
116 return err == OK ? C2_OK : C2_NO_MEMORY;
117 }
118
onStop()119 c2_status_t C2SoftMP3::onStop() {
120 // Make sure that the next buffer output does not still
121 // depend on fragments from the last one decoded.
122 if (mDecoderBuf) {
123 pvmp3_InitDecoder(mConfig, mDecoderBuf);
124 }
125 mSignalledError = false;
126 mIsFirst = true;
127 mSignalledOutputEos = false;
128 mAnchorTimeStamp = 0;
129 mProcessedSamples = 0;
130
131 return C2_OK;
132 }
133
onReset()134 void C2SoftMP3::onReset() {
135 (void)onStop();
136 }
137
onRelease()138 void C2SoftMP3::onRelease() {
139 mGaplessBytes = false;
140 if (mDecoderBuf) {
141 free(mDecoderBuf);
142 mDecoderBuf = nullptr;
143 }
144
145 if (mConfig) {
146 delete mConfig;
147 mConfig = nullptr;
148 }
149 }
150
initDecoder()151 status_t C2SoftMP3::initDecoder() {
152 mConfig = new tPVMP3DecoderExternal{};
153 if (!mConfig) return NO_MEMORY;
154 mConfig->equalizerType = flat;
155 mConfig->crcEnabled = false;
156
157 size_t memRequirements = pvmp3_decoderMemRequirements();
158 mDecoderBuf = malloc(memRequirements);
159 if (!mDecoderBuf) return NO_MEMORY;
160
161 pvmp3_InitDecoder(mConfig, mDecoderBuf);
162
163 mIsFirst = true;
164 mGaplessBytes = false;
165 mSignalledError = false;
166 mSignalledOutputEos = false;
167 mAnchorTimeStamp = 0;
168 mProcessedSamples = 0;
169
170 return OK;
171 }
172
173 /* The below code is borrowed from ./test/mp3reader.cpp */
parseMp3Header(uint32_t header,size_t * frame_size,uint32_t * out_sampling_rate=nullptr,uint32_t * out_channels=nullptr,uint32_t * out_bitrate=nullptr,uint32_t * out_num_samples=nullptr)174 static bool parseMp3Header(uint32_t header, size_t *frame_size,
175 uint32_t *out_sampling_rate = nullptr,
176 uint32_t *out_channels = nullptr,
177 uint32_t *out_bitrate = nullptr,
178 uint32_t *out_num_samples = nullptr) {
179 *frame_size = 0;
180 if (out_sampling_rate) *out_sampling_rate = 0;
181 if (out_channels) *out_channels = 0;
182 if (out_bitrate) *out_bitrate = 0;
183 if (out_num_samples) *out_num_samples = 1152;
184
185 if ((header & 0xffe00000) != 0xffe00000) return false;
186
187 unsigned version = (header >> 19) & 3;
188 if (version == 0x01) return false;
189
190 unsigned layer = (header >> 17) & 3;
191 if (layer == 0x00) return false;
192
193 unsigned bitrate_index = (header >> 12) & 0x0f;
194 if (bitrate_index == 0 || bitrate_index == 0x0f) return false;
195
196 unsigned sampling_rate_index = (header >> 10) & 3;
197 if (sampling_rate_index == 3) return false;
198
199 static const int kSamplingRateV1[] = { 44100, 48000, 32000 };
200 int sampling_rate = kSamplingRateV1[sampling_rate_index];
201 if (version == 2 /* V2 */) {
202 sampling_rate /= 2;
203 } else if (version == 0 /* V2.5 */) {
204 sampling_rate /= 4;
205 }
206
207 unsigned padding = (header >> 9) & 1;
208
209 if (layer == 3) { // layer I
210 static const int kBitrateV1[] =
211 {
212 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448
213 };
214 static const int kBitrateV2[] =
215 {
216 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256
217 };
218
219 int bitrate = (version == 3 /* V1 */) ? kBitrateV1[bitrate_index - 1] :
220 kBitrateV2[bitrate_index - 1];
221
222 if (out_bitrate) {
223 *out_bitrate = bitrate;
224 }
225 *frame_size = (12000 * bitrate / sampling_rate + padding) * 4;
226 if (out_num_samples) {
227 *out_num_samples = 384;
228 }
229 } else { // layer II or III
230 static const int kBitrateV1L2[] =
231 {
232 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384
233 };
234
235 static const int kBitrateV1L3[] =
236 {
237 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320
238 };
239
240 static const int kBitrateV2[] =
241 {
242 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160
243 };
244
245 int bitrate;
246 if (version == 3 /* V1 */) {
247 bitrate = (layer == 2 /* L2 */) ? kBitrateV1L2[bitrate_index - 1] :
248 kBitrateV1L3[bitrate_index - 1];
249
250 if (out_num_samples) {
251 *out_num_samples = 1152;
252 }
253 } else { // V2 (or 2.5)
254 bitrate = kBitrateV2[bitrate_index - 1];
255 if (out_num_samples) {
256 *out_num_samples = (layer == 1 /* L3 */) ? 576 : 1152;
257 }
258 }
259
260 if (out_bitrate) {
261 *out_bitrate = bitrate;
262 }
263
264 if (version == 3 /* V1 */) {
265 *frame_size = 144000 * bitrate / sampling_rate + padding;
266 } else { // V2 or V2.5
267 size_t tmp = (layer == 1 /* L3 */) ? 72000 : 144000;
268 *frame_size = tmp * bitrate / sampling_rate + padding;
269 }
270 }
271
272 if (out_sampling_rate) {
273 *out_sampling_rate = sampling_rate;
274 }
275
276 if (out_channels) {
277 int channel_mode = (header >> 6) & 3;
278
279 *out_channels = (channel_mode == 3) ? 1 : 2;
280 }
281
282 return true;
283 }
284
U32_AT(const uint8_t * ptr)285 static uint32_t U32_AT(const uint8_t *ptr) {
286 return ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
287 }
288
calculateOutSize(uint8 * header,size_t inSize,std::vector<size_t> * decodedSizes)289 static status_t calculateOutSize(uint8 *header, size_t inSize,
290 std::vector<size_t> *decodedSizes) {
291 uint32_t channels;
292 uint32_t numSamples;
293 size_t frameSize;
294 size_t totalInSize = 0;
295
296 while (totalInSize + 4 < inSize) {
297 if (!parseMp3Header(U32_AT(header + totalInSize), &frameSize,
298 nullptr, &channels, nullptr, &numSamples)) {
299 ALOGE("Error in parse mp3 header during outSize estimation");
300 return UNKNOWN_ERROR;
301 }
302 totalInSize += frameSize;
303 decodedSizes->push_back(numSamples * channels * sizeof(int16_t));
304 }
305
306 if (decodedSizes->empty()) return UNKNOWN_ERROR;
307
308 return OK;
309 }
310
onFlush_sm()311 c2_status_t C2SoftMP3::onFlush_sm() {
312 return onStop();
313 }
314
drain(uint32_t drainMode,const std::shared_ptr<C2BlockPool> & pool)315 c2_status_t C2SoftMP3::drain(
316 uint32_t drainMode,
317 const std::shared_ptr<C2BlockPool> &pool) {
318 (void) pool;
319 if (drainMode == NO_DRAIN) {
320 ALOGW("drain with NO_DRAIN: no-op");
321 return C2_OK;
322 }
323 if (drainMode == DRAIN_CHAIN) {
324 ALOGW("DRAIN_CHAIN not supported");
325 return C2_OMITTED;
326 }
327
328 return C2_OK;
329 }
330
fillEmptyWork(const std::unique_ptr<C2Work> & work)331 static void fillEmptyWork(const std::unique_ptr<C2Work> &work) {
332 work->worklets.front()->output.flags = work->input.flags;
333 work->worklets.front()->output.buffers.clear();
334 work->worklets.front()->output.ordinal = work->input.ordinal;
335 work->workletsProcessed = 1u;
336 }
337
338 // TODO: Can overall error checking be improved? As in the check for validity of
339 // work, pool ptr, work->input.buffers.size() == 1, ...
340 // TODO: Blind removal of 529 samples from the output may not work. Because
341 // mpeg layer 1 frame size is 384 samples per frame. This should introduce
342 // negative values and can cause SEG faults. Soft omx mp3 plugin can have
343 // this problem (CHECK!)
process(const std::unique_ptr<C2Work> & work,const std::shared_ptr<C2BlockPool> & pool)344 void C2SoftMP3::process(
345 const std::unique_ptr<C2Work> &work,
346 const std::shared_ptr<C2BlockPool> &pool) {
347 // Initialize output work
348 work->result = C2_OK;
349 work->workletsProcessed = 1u;
350 work->worklets.front()->output.configUpdate.clear();
351 work->worklets.front()->output.flags = work->input.flags;
352
353 if (mSignalledError || mSignalledOutputEos) {
354 work->result = C2_BAD_VALUE;
355 return;
356 }
357
358 bool eos = ((work->input.flags & C2FrameData::FLAG_END_OF_STREAM) != 0);
359 size_t inSize = 0u;
360 C2ReadView rView = mDummyReadView;
361 if (!work->input.buffers.empty()) {
362 rView = work->input.buffers[0]->data().linearBlocks().front().map().get();
363 inSize = rView.capacity();
364 if (inSize && rView.error()) {
365 ALOGE("read view map failed %d", rView.error());
366 work->result = rView.error();
367 return;
368 }
369 }
370
371 if (inSize == 0 && (!mGaplessBytes || !eos)) {
372 work->worklets.front()->output.flags = work->input.flags;
373 work->worklets.front()->output.buffers.clear();
374 work->worklets.front()->output.ordinal = work->input.ordinal;
375 return;
376 }
377 ALOGV("in buffer attr. size %zu timestamp %d frameindex %d", inSize,
378 (int)work->input.ordinal.timestamp.peeku(), (int)work->input.ordinal.frameIndex.peeku());
379
380 int32_t numChannels = mConfig->num_channels;
381 size_t calOutSize;
382 std::vector<size_t> decodedSizes;
383 if (inSize && OK != calculateOutSize(const_cast<uint8 *>(rView.data()),
384 inSize, &decodedSizes)) {
385 work->result = C2_CORRUPTED;
386 return;
387 }
388 calOutSize = std::accumulate(decodedSizes.begin(), decodedSizes.end(), 0);
389 if (eos) {
390 calOutSize += kPVMP3DecoderDelay * numChannels * sizeof(int16_t);
391 }
392
393 std::shared_ptr<C2LinearBlock> block;
394 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
395 c2_status_t err = pool->fetchLinearBlock(calOutSize, usage, &block);
396 if (err != C2_OK) {
397 ALOGE("fetchLinearBlock for Output failed with status %d", err);
398 work->result = C2_NO_MEMORY;
399 return;
400 }
401 C2WriteView wView = block->map().get();
402 if (wView.error()) {
403 ALOGE("write view map failed %d", wView.error());
404 work->result = wView.error();
405 return;
406 }
407
408 int outSize = 0;
409 int outOffset = 0;
410 auto it = decodedSizes.begin();
411 size_t inPos = 0;
412 int32_t samplingRate = mConfig->samplingRate;
413 while (inPos < inSize) {
414 if (it == decodedSizes.end()) {
415 ALOGE("unexpected trailing bytes, ignoring them");
416 break;
417 }
418
419 mConfig->pInputBuffer = const_cast<uint8 *>(rView.data() + inPos);
420 mConfig->inputBufferCurrentLength = (inSize - inPos);
421 mConfig->inputBufferMaxLength = 0;
422 mConfig->inputBufferUsedLength = 0;
423 mConfig->outputFrameSize = (calOutSize - outSize) / sizeof(int16_t);
424 mConfig->pOutputBuffer = reinterpret_cast<int16_t *> (wView.data() + outSize);
425
426 ERROR_CODE decoderErr;
427 if ((decoderErr = pvmp3_framedecoder(mConfig, mDecoderBuf))
428 != NO_DECODING_ERROR) {
429 ALOGE("mp3 decoder returned error %d", decoderErr);
430 if (decoderErr != NO_ENOUGH_MAIN_DATA_ERROR
431 && decoderErr != SIDE_INFO_ERROR) {
432 mSignalledError = true;
433 work->result = C2_CORRUPTED;
434 return;
435 }
436
437 // This is recoverable, just ignore the current frame and
438 // play silence instead.
439 ALOGV("ignoring error and sending silence");
440 if (mConfig->outputFrameSize == 0) {
441 mConfig->outputFrameSize = *it / sizeof(int16_t);
442 }
443 memset(mConfig->pOutputBuffer, 0, mConfig->outputFrameSize * sizeof(int16_t));
444 } else if (mConfig->samplingRate != samplingRate
445 || mConfig->num_channels != numChannels) {
446 ALOGI("Reconfiguring decoder: %d->%d Hz, %d->%d channels",
447 samplingRate, mConfig->samplingRate,
448 numChannels, mConfig->num_channels);
449 samplingRate = mConfig->samplingRate;
450 numChannels = mConfig->num_channels;
451
452 C2StreamSampleRateInfo::output sampleRateInfo(0u, samplingRate);
453 C2StreamChannelCountInfo::output channelCountInfo(0u, numChannels);
454 std::vector<std::unique_ptr<C2SettingResult>> failures;
455 c2_status_t err = mIntf->config(
456 { &sampleRateInfo, &channelCountInfo },
457 C2_MAY_BLOCK,
458 &failures);
459 if (err == OK) {
460 work->worklets.front()->output.configUpdate.push_back(C2Param::Copy(sampleRateInfo));
461 work->worklets.front()->output.configUpdate.push_back(C2Param::Copy(channelCountInfo));
462 } else {
463 ALOGE("Config Update failed");
464 mSignalledError = true;
465 work->result = C2_CORRUPTED;
466 return;
467 }
468 }
469 if (*it != mConfig->outputFrameSize * sizeof(int16_t)) {
470 ALOGE("panic, parsed size does not match decoded size");
471 mSignalledError = true;
472 work->result = C2_CORRUPTED;
473 return;
474 }
475 outSize += mConfig->outputFrameSize * sizeof(int16_t);
476 inPos += mConfig->inputBufferUsedLength;
477 it++;
478 }
479 if (mIsFirst) {
480 mIsFirst = false;
481 mGaplessBytes = true;
482 // The decoder delay is 529 samples, so trim that many samples off
483 // the start of the first output buffer. This essentially makes this
484 // decoder have zero delay, which the rest of the pipeline assumes.
485 outOffset = kPVMP3DecoderDelay * numChannels * sizeof(int16_t);
486 mAnchorTimeStamp = work->input.ordinal.timestamp.peekull();
487 }
488 if (eos) {
489 if (calOutSize >=
490 outSize + kPVMP3DecoderDelay * numChannels * sizeof(int16_t)) {
491 if (!memset(reinterpret_cast<int16_t*>(wView.data() + outSize), 0,
492 kPVMP3DecoderDelay * numChannels * sizeof(int16_t))) {
493 mSignalledError = true;
494 work->result = C2_CORRUPTED;
495 return;
496 }
497 ALOGV("Adding 529 samples at end");
498 mGaplessBytes = false;
499 outSize += kPVMP3DecoderDelay * numChannels * sizeof(int16_t);
500 }
501 }
502
503 fillEmptyWork(work);
504 if (samplingRate && numChannels) {
505 int64_t outTimeStamp = mProcessedSamples * 1000000ll / samplingRate;
506 mProcessedSamples += ((outSize - outOffset) / (numChannels * sizeof(int16_t)));
507 ALOGV("out buffer attr. offset %d size %d timestamp %" PRId64 " ", outOffset,
508 outSize - outOffset, mAnchorTimeStamp + outTimeStamp);
509 decodedSizes.clear();
510 work->worklets.front()->output.buffers.push_back(
511 createLinearBuffer(block, outOffset, outSize - outOffset));
512 work->worklets.front()->output.ordinal.timestamp = mAnchorTimeStamp + outTimeStamp;
513 }
514 if (eos) {
515 mSignalledOutputEos = true;
516 ALOGV("signalled EOS");
517 }
518 }
519
520 class C2SoftMp3DecFactory : public C2ComponentFactory {
521 public:
C2SoftMp3DecFactory()522 C2SoftMp3DecFactory() : mHelper(std::static_pointer_cast<C2ReflectorHelper>(
523 GetCodec2PlatformComponentStore()->getParamReflector())) {
524 }
525
createComponent(c2_node_id_t id,std::shared_ptr<C2Component> * const component,std::function<void (C2Component *)> deleter)526 virtual c2_status_t createComponent(
527 c2_node_id_t id,
528 std::shared_ptr<C2Component>* const component,
529 std::function<void(C2Component*)> deleter) override {
530 *component = std::shared_ptr<C2Component>(
531 new C2SoftMP3(COMPONENT_NAME,
532 id,
533 std::make_shared<C2SoftMP3::IntfImpl>(mHelper)),
534 deleter);
535 return C2_OK;
536 }
537
createInterface(c2_node_id_t id,std::shared_ptr<C2ComponentInterface> * const interface,std::function<void (C2ComponentInterface *)> deleter)538 virtual c2_status_t createInterface(
539 c2_node_id_t id,
540 std::shared_ptr<C2ComponentInterface>* const interface,
541 std::function<void(C2ComponentInterface*)> deleter) override {
542 *interface = std::shared_ptr<C2ComponentInterface>(
543 new SimpleInterface<C2SoftMP3::IntfImpl>(
544 COMPONENT_NAME, id, std::make_shared<C2SoftMP3::IntfImpl>(mHelper)),
545 deleter);
546 return C2_OK;
547 }
548
549 virtual ~C2SoftMp3DecFactory() override = default;
550
551 private:
552 std::shared_ptr<C2ReflectorHelper> mHelper;
553 };
554
555 } // namespace android
556
557 __attribute__((cfi_canonical_jump_table))
CreateCodec2Factory()558 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
559 ALOGV("in %s", __func__);
560 return new ::android::C2SoftMp3DecFactory();
561 }
562
563 __attribute__((cfi_canonical_jump_table))
DestroyCodec2Factory(::C2ComponentFactory * factory)564 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
565 ALOGV("in %s", __func__);
566 delete factory;
567 }
568