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 "C2SoftVorbisDec"
19 #include <log/log.h>
20
21 #include <media/stagefright/foundation/MediaDefs.h>
22
23 #include <C2PlatformSupport.h>
24 #include <SimpleC2Interface.h>
25
26 #include "C2SoftVorbisDec.h"
27
28 extern "C" {
29 #include <Tremolo/codec_internal.h>
30
31 int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb);
32 int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb);
33 int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb);
34 }
35
36 namespace android {
37
38 constexpr char COMPONENT_NAME[] = "c2.android.vorbis.decoder";
39
40 class C2SoftVorbisDec::IntfImpl : public C2InterfaceHelper {
41 public:
IntfImpl(const std::shared_ptr<C2ReflectorHelper> & helper)42 explicit IntfImpl(const std::shared_ptr<C2ReflectorHelper> &helper)
43 : C2InterfaceHelper(helper) {
44
45 setDerivedInstance(this);
46
47 addParameter(
48 DefineParam(mInputFormat, C2_NAME_INPUT_STREAM_FORMAT_SETTING)
49 .withConstValue(new C2StreamFormatConfig::input(0u, C2FormatCompressed))
50 .build());
51
52 addParameter(
53 DefineParam(mOutputFormat, C2_NAME_OUTPUT_STREAM_FORMAT_SETTING)
54 .withConstValue(new C2StreamFormatConfig::output(0u, C2FormatAudio))
55 .build());
56
57 addParameter(
58 DefineParam(mInputMediaType, C2_NAME_INPUT_PORT_MIME_SETTING)
59 .withConstValue(AllocSharedString<C2PortMimeConfig::input>(
60 MEDIA_MIMETYPE_AUDIO_VORBIS))
61 .build());
62
63 addParameter(
64 DefineParam(mOutputMediaType, C2_NAME_OUTPUT_PORT_MIME_SETTING)
65 .withConstValue(AllocSharedString<C2PortMimeConfig::output>(
66 MEDIA_MIMETYPE_AUDIO_RAW))
67 .build());
68
69 addParameter(
70 DefineParam(mSampleRate, C2_NAME_STREAM_SAMPLE_RATE_SETTING)
71 .withDefault(new C2StreamSampleRateInfo::output(0u, 48000))
72 .withFields({C2F(mSampleRate, value).inRange(8000, 96000)})
73 .withSetter((Setter<decltype(*mSampleRate)>::StrictValueWithNoDeps))
74 .build());
75
76 addParameter(
77 DefineParam(mChannelCount, C2_NAME_STREAM_CHANNEL_COUNT_SETTING)
78 .withDefault(new C2StreamChannelCountInfo::output(0u, 1))
79 .withFields({C2F(mChannelCount, value).inRange(1, 8)})
80 .withSetter(Setter<decltype(*mChannelCount)>::StrictValueWithNoDeps)
81 .build());
82
83 addParameter(
84 DefineParam(mBitrate, C2_NAME_STREAM_BITRATE_SETTING)
85 .withDefault(new C2BitrateTuning::input(0u, 64000))
86 .withFields({C2F(mBitrate, value).inRange(32000, 500000)})
87 .withSetter(Setter<decltype(*mBitrate)>::NonStrictValueWithNoDeps)
88 .build());
89 }
90
91 private:
92 std::shared_ptr<C2StreamFormatConfig::input> mInputFormat;
93 std::shared_ptr<C2StreamFormatConfig::output> mOutputFormat;
94 std::shared_ptr<C2PortMimeConfig::input> mInputMediaType;
95 std::shared_ptr<C2PortMimeConfig::output> mOutputMediaType;
96 std::shared_ptr<C2StreamSampleRateInfo::output> mSampleRate;
97 std::shared_ptr<C2StreamChannelCountInfo::output> mChannelCount;
98 std::shared_ptr<C2BitrateTuning::input> mBitrate;
99 };
100
C2SoftVorbisDec(const char * name,c2_node_id_t id,const std::shared_ptr<IntfImpl> & intfImpl)101 C2SoftVorbisDec::C2SoftVorbisDec(
102 const char *name,
103 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 mState(nullptr),
108 mVi(nullptr) {
109 }
110
~C2SoftVorbisDec()111 C2SoftVorbisDec::~C2SoftVorbisDec() {
112 onRelease();
113 }
114
onInit()115 c2_status_t C2SoftVorbisDec::onInit() {
116 status_t err = initDecoder();
117 return err == OK ? C2_OK : C2_NO_MEMORY;
118 }
119
onStop()120 c2_status_t C2SoftVorbisDec::onStop() {
121 if (mState) {
122 vorbis_dsp_clear(mState);
123 delete mState;
124 mState = nullptr;
125 }
126
127 if (mVi) {
128 vorbis_info_clear(mVi);
129 delete mVi;
130 mVi = nullptr;
131 }
132 mNumFramesLeftOnPage = -1;
133 mSignalledOutputEos = false;
134 mSignalledError = false;
135
136 return (initDecoder() == OK ? C2_OK : C2_CORRUPTED);
137 }
138
onReset()139 void C2SoftVorbisDec::onReset() {
140 (void)onStop();
141 }
142
onRelease()143 void C2SoftVorbisDec::onRelease() {
144 if (mState) {
145 vorbis_dsp_clear(mState);
146 delete mState;
147 mState = nullptr;
148 }
149
150 if (mVi) {
151 vorbis_info_clear(mVi);
152 delete mVi;
153 mVi = nullptr;
154 }
155 }
156
initDecoder()157 status_t C2SoftVorbisDec::initDecoder() {
158 mVi = new vorbis_info{};
159 if (!mVi) return NO_MEMORY;
160 vorbis_info_clear(mVi);
161
162 mState = new vorbis_dsp_state{};
163 if (!mState) return NO_MEMORY;
164 vorbis_dsp_clear(mState);
165
166 mNumFramesLeftOnPage = -1;
167 mSignalledError = false;
168 mSignalledOutputEos = false;
169 mInfoUnpacked = false;
170 mBooksUnpacked = false;
171 return OK;
172 }
173
onFlush_sm()174 c2_status_t C2SoftVorbisDec::onFlush_sm() {
175 mNumFramesLeftOnPage = -1;
176 mSignalledOutputEos = false;
177 if (mState) vorbis_dsp_restart(mState);
178
179 return C2_OK;
180 }
181
drain(uint32_t drainMode,const std::shared_ptr<C2BlockPool> & pool)182 c2_status_t C2SoftVorbisDec::drain(
183 uint32_t drainMode,
184 const std::shared_ptr<C2BlockPool> &pool) {
185 (void) pool;
186 if (drainMode == NO_DRAIN) {
187 ALOGW("drain with NO_DRAIN: no-op");
188 return C2_OK;
189 }
190 if (drainMode == DRAIN_CHAIN) {
191 ALOGW("DRAIN_CHAIN not supported");
192 return C2_OMITTED;
193 }
194
195 return C2_OK;
196 }
197
fillEmptyWork(const std::unique_ptr<C2Work> & work)198 static void fillEmptyWork(const std::unique_ptr<C2Work> &work) {
199 work->worklets.front()->output.flags = work->input.flags;
200 work->worklets.front()->output.buffers.clear();
201 work->worklets.front()->output.ordinal = work->input.ordinal;
202 work->workletsProcessed = 1u;
203 }
204
makeBitReader(const void * data,size_t size,ogg_buffer * buf,ogg_reference * ref,oggpack_buffer * bits)205 static void makeBitReader(
206 const void *data, size_t size,
207 ogg_buffer *buf, ogg_reference *ref, oggpack_buffer *bits) {
208 buf->data = (uint8_t *)data;
209 buf->size = size;
210 buf->refcount = 1;
211 buf->ptr.owner = nullptr;
212
213 ref->buffer = buf;
214 ref->begin = 0;
215 ref->length = size;
216 ref->next = nullptr;
217
218 oggpack_readinit(bits, ref);
219 }
220
221 // (CHECK!) multiframe is tricky. decode call doesnt return the number of bytes
222 // consumed by the component. Also it is unclear why numPageFrames is being
223 // tagged at the end of input buffers for new pages. Refer lines 297-300 in
224 // SimpleDecodingSource.cpp
process(const std::unique_ptr<C2Work> & work,const std::shared_ptr<C2BlockPool> & pool)225 void C2SoftVorbisDec::process(
226 const std::unique_ptr<C2Work> &work,
227 const std::shared_ptr<C2BlockPool> &pool) {
228 work->result = C2_OK;
229 work->workletsProcessed = 0u;
230 work->worklets.front()->output.configUpdate.clear();
231 if (mSignalledError || mSignalledOutputEos) {
232 work->result = C2_BAD_VALUE;
233 return;
234 }
235
236 bool eos = ((work->input.flags & C2FrameData::FLAG_END_OF_STREAM) != 0);
237 size_t inOffset = 0u;
238 size_t inSize = 0u;
239 C2ReadView rView = mDummyReadView;
240 if (!work->input.buffers.empty()) {
241 rView = work->input.buffers[0]->data().linearBlocks().front().map().get();
242 inSize = rView.capacity();
243 if (inSize && rView.error()) {
244 ALOGE("read view map failed %d", rView.error());
245 work->result = rView.error();
246 return;
247 }
248 }
249
250 if (inSize == 0) {
251 fillEmptyWork(work);
252 if (eos) {
253 mSignalledOutputEos = true;
254 ALOGV("signalled EOS");
255 }
256 return;
257 }
258
259 ALOGV("in buffer attr. size %zu timestamp %d frameindex %d", inSize,
260 (int)work->input.ordinal.timestamp.peeku(), (int)work->input.ordinal.frameIndex.peeku());
261 const uint8_t *data = rView.data() + inOffset;
262 int32_t numChannels = mVi->channels;
263 int32_t samplingRate = mVi->rate;
264 if (inSize > 7 && !memcmp(&data[1], "vorbis", 6)) {
265 if ((data[0] != 1) && (data[0] != 5)) {
266 ALOGE("unexpected type received %d", data[0]);
267 mSignalledError = true;
268 work->result = C2_CORRUPTED;
269 return;
270 }
271
272 ogg_buffer buf;
273 ogg_reference ref;
274 oggpack_buffer bits;
275
276 // skip 7 <type + "vorbis"> bytes
277 makeBitReader((const uint8_t *)data + 7, inSize - 7, &buf, &ref, &bits);
278 if (data[0] == 1) {
279 vorbis_info_init(mVi);
280 if (0 != _vorbis_unpack_info(mVi, &bits)) {
281 ALOGE("Encountered error while unpacking info");
282 mSignalledError = true;
283 work->result = C2_CORRUPTED;
284 return;
285 }
286 if (mVi->rate != samplingRate ||
287 mVi->channels != numChannels) {
288 ALOGV("vorbis: rate/channels changed: %ld/%d", mVi->rate, mVi->channels);
289 samplingRate = mVi->rate;
290 numChannels = mVi->channels;
291
292 C2StreamSampleRateInfo::output sampleRateInfo(0u, samplingRate);
293 C2StreamChannelCountInfo::output channelCountInfo(0u, numChannels);
294 std::vector<std::unique_ptr<C2SettingResult>> failures;
295 c2_status_t err = mIntf->config(
296 { &sampleRateInfo, &channelCountInfo },
297 C2_MAY_BLOCK,
298 &failures);
299 if (err == OK) {
300 work->worklets.front()->output.configUpdate.push_back(C2Param::Copy(sampleRateInfo));
301 work->worklets.front()->output.configUpdate.push_back(C2Param::Copy(channelCountInfo));
302 } else {
303 ALOGE("Config Update failed");
304 mSignalledError = true;
305 work->result = C2_CORRUPTED;
306 return;
307 }
308 }
309 mInfoUnpacked = true;
310 } else {
311 if (!mInfoUnpacked) {
312 ALOGE("Data with type:5 sent before sending type:1");
313 mSignalledError = true;
314 work->result = C2_CORRUPTED;
315 return;
316 }
317 if (0 != _vorbis_unpack_books(mVi, &bits)) {
318 ALOGE("Encountered error while unpacking books");
319 mSignalledError = true;
320 work->result = C2_CORRUPTED;
321 return;
322 }
323 if (0 != vorbis_dsp_init(mState, mVi)) {
324 ALOGE("Encountered error while dsp init");
325 mSignalledError = true;
326 work->result = C2_CORRUPTED;
327 return;
328 }
329 mBooksUnpacked = true;
330 }
331 fillEmptyWork(work);
332 if (eos) {
333 mSignalledOutputEos = true;
334 ALOGV("signalled EOS");
335 }
336 return;
337 }
338
339 if (!mInfoUnpacked || !mBooksUnpacked) {
340 ALOGE("Missing CODEC_CONFIG data mInfoUnpacked: %d mBooksUnpack %d", mInfoUnpacked, mBooksUnpacked);
341 mSignalledError = true;
342 work->result = C2_CORRUPTED;
343 return;
344 }
345
346 int32_t numPageFrames = 0;
347 if (inSize < sizeof(numPageFrames)) {
348 ALOGE("input header has size %zu, expected %zu", inSize, sizeof(numPageFrames));
349 mSignalledError = true;
350 work->result = C2_CORRUPTED;
351 return;
352 }
353 memcpy(&numPageFrames, data + inSize - sizeof(numPageFrames), sizeof(numPageFrames));
354 inSize -= sizeof(numPageFrames);
355 if (numPageFrames >= 0) {
356 mNumFramesLeftOnPage = numPageFrames;
357 }
358
359 ogg_buffer buf;
360 buf.data = const_cast<unsigned char*>(data);
361 buf.size = inSize;
362 buf.refcount = 1;
363 buf.ptr.owner = nullptr;
364
365 ogg_reference ref;
366 ref.buffer = &buf;
367 ref.begin = 0;
368 ref.length = buf.size;
369 ref.next = nullptr;
370
371 ogg_packet pack;
372 pack.packet = &ref;
373 pack.bytes = ref.length;
374 pack.b_o_s = 0;
375 pack.e_o_s = 0;
376 pack.granulepos = 0;
377 pack.packetno = 0;
378
379 size_t maxSamplesInBuffer = kMaxNumSamplesPerChannel * mVi->channels;
380 size_t outCapacity = maxSamplesInBuffer * sizeof(int16_t);
381 std::shared_ptr<C2LinearBlock> block;
382 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
383 c2_status_t err = pool->fetchLinearBlock(outCapacity, usage, &block);
384 if (err != C2_OK) {
385 ALOGE("fetchLinearBlock for Output failed with status %d", err);
386 work->result = C2_NO_MEMORY;
387 return;
388 }
389 C2WriteView wView = block->map().get();
390 if (wView.error()) {
391 ALOGE("write view map failed %d", wView.error());
392 work->result = wView.error();
393 return;
394 }
395
396 int numFrames = 0;
397 int ret = vorbis_dsp_synthesis(mState, &pack, 1);
398 if (0 != ret) {
399 ALOGE("vorbis_dsp_synthesis returned %d", ret);
400 mSignalledError = true;
401 work->result = C2_CORRUPTED;
402 return;
403 } else {
404 numFrames = vorbis_dsp_pcmout(
405 mState, reinterpret_cast<int16_t *> (wView.data()),
406 kMaxNumSamplesPerChannel);
407 if (numFrames < 0) {
408 ALOGD("vorbis_dsp_pcmout returned %d", numFrames);
409 numFrames = 0;
410 }
411 }
412
413 if (mNumFramesLeftOnPage >= 0) {
414 if (numFrames > mNumFramesLeftOnPage) {
415 ALOGV("discarding %d frames at end of page", numFrames - mNumFramesLeftOnPage);
416 numFrames = mNumFramesLeftOnPage;
417 }
418 mNumFramesLeftOnPage -= numFrames;
419 }
420
421 if (numFrames) {
422 int outSize = numFrames * sizeof(int16_t) * mVi->channels;
423
424 work->worklets.front()->output.flags = work->input.flags;
425 work->worklets.front()->output.buffers.clear();
426 work->worklets.front()->output.buffers.push_back(createLinearBuffer(block, 0, outSize));
427 work->worklets.front()->output.ordinal = work->input.ordinal;
428 work->workletsProcessed = 1u;
429 } else {
430 fillEmptyWork(work);
431 block.reset();
432 }
433 if (eos) {
434 mSignalledOutputEos = true;
435 ALOGV("signalled EOS");
436 }
437 }
438
439 class C2SoftVorbisDecFactory : public C2ComponentFactory {
440 public:
C2SoftVorbisDecFactory()441 C2SoftVorbisDecFactory() : mHelper(std::static_pointer_cast<C2ReflectorHelper>(
442 GetCodec2PlatformComponentStore()->getParamReflector())) {
443 }
444
createComponent(c2_node_id_t id,std::shared_ptr<C2Component> * const component,std::function<void (C2Component *)> deleter)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 C2SoftVorbisDec(COMPONENT_NAME,
451 id,
452 std::make_shared<C2SoftVorbisDec::IntfImpl>(mHelper)),
453 deleter);
454 return C2_OK;
455 }
456
createInterface(c2_node_id_t id,std::shared_ptr<C2ComponentInterface> * const interface,std::function<void (C2ComponentInterface *)> deleter)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<C2SoftVorbisDec::IntfImpl>(
463 COMPONENT_NAME, id, std::make_shared<C2SoftVorbisDec::IntfImpl>(mHelper)),
464 deleter);
465 return C2_OK;
466 }
467
468 virtual ~C2SoftVorbisDecFactory() override = default;
469
470 private:
471 std::shared_ptr<C2ReflectorHelper> mHelper;
472 };
473
474 } // namespace android
475
CreateCodec2Factory()476 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
477 ALOGV("in %s", __func__);
478 return new ::android::C2SoftVorbisDecFactory();
479 }
480
DestroyCodec2Factory(::C2ComponentFactory * factory)481 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
482 ALOGV("in %s", __func__);
483 delete factory;
484 }
485