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