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 "C2SoftG711Dec"
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 "C2SoftG711Dec.h"
27 
28 namespace android {
29 
30 #ifdef ALAW
31 constexpr char COMPONENT_NAME[] = "c2.android.g711.alaw.decoder";
32 #else
33 constexpr char COMPONENT_NAME[] = "c2.android.g711.mlaw.decoder";
34 #endif
35 
36 class C2SoftG711Dec::IntfImpl : public C2InterfaceHelper {
37 public:
IntfImpl(const std::shared_ptr<C2ReflectorHelper> & helper)38     explicit IntfImpl(const std::shared_ptr<C2ReflectorHelper> &helper)
39         : C2InterfaceHelper(helper) {
40 
41         setDerivedInstance(this);
42 
43         addParameter(
44                 DefineParam(mInputFormat, C2_NAME_INPUT_STREAM_FORMAT_SETTING)
45                 .withConstValue(new C2StreamFormatConfig::input(0u, C2FormatCompressed))
46                 .build());
47 
48         addParameter(
49                 DefineParam(mOutputFormat, C2_NAME_OUTPUT_STREAM_FORMAT_SETTING)
50                 .withConstValue(new C2StreamFormatConfig::output(0u, C2FormatAudio))
51                 .build());
52 
53         addParameter(
54                 DefineParam(mInputMediaType, C2_NAME_INPUT_PORT_MIME_SETTING)
55                 .withConstValue(AllocSharedString<C2PortMimeConfig::input>(
56 #ifdef ALAW
57                         MEDIA_MIMETYPE_AUDIO_G711_ALAW
58 #else
59                         MEDIA_MIMETYPE_AUDIO_G711_MLAW
60 #endif
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, 8000))
72                 .withFields({C2F(mSampleRate, value).inRange(8000, 48000)})
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).equalTo(1)})
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).equalTo(64000)})
87                 .withSetter(Setter<decltype(*mBitrate)>::NonStrictValueWithNoDeps)
88                 .build());
89 
90         addParameter(
91                 DefineParam(mInputMaxBufSize, C2_PARAMKEY_INPUT_MAX_BUFFER_SIZE)
92                 .withConstValue(new C2StreamMaxBufferSizeInfo::input(0u, 8192))
93                 .build());
94     }
95 
96 private:
97     std::shared_ptr<C2StreamFormatConfig::input> mInputFormat;
98     std::shared_ptr<C2StreamFormatConfig::output> mOutputFormat;
99     std::shared_ptr<C2PortMimeConfig::input> mInputMediaType;
100     std::shared_ptr<C2PortMimeConfig::output> mOutputMediaType;
101     std::shared_ptr<C2StreamSampleRateInfo::output> mSampleRate;
102     std::shared_ptr<C2StreamChannelCountInfo::output> mChannelCount;
103     std::shared_ptr<C2BitrateTuning::input> mBitrate;
104     std::shared_ptr<C2StreamMaxBufferSizeInfo::input> mInputMaxBufSize;
105 };
106 
C2SoftG711Dec(const char * name,c2_node_id_t id,const std::shared_ptr<IntfImpl> & intfImpl)107 C2SoftG711Dec::C2SoftG711Dec(
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 }
114 
~C2SoftG711Dec()115 C2SoftG711Dec::~C2SoftG711Dec() {
116     onRelease();
117 }
118 
onInit()119 c2_status_t C2SoftG711Dec::onInit() {
120     mSignalledOutputEos = false;
121     return C2_OK;
122 }
123 
onStop()124 c2_status_t C2SoftG711Dec::onStop() {
125     mSignalledOutputEos = false;
126     return C2_OK;
127 }
128 
onReset()129 void C2SoftG711Dec::onReset() {
130     (void)onStop();
131 }
132 
onRelease()133 void C2SoftG711Dec::onRelease() {
134 }
135 
onFlush_sm()136 c2_status_t C2SoftG711Dec::onFlush_sm() {
137     return onStop();
138 }
139 
process(const std::unique_ptr<C2Work> & work,const std::shared_ptr<C2BlockPool> & pool)140 void C2SoftG711Dec::process(
141         const std::unique_ptr<C2Work> &work,
142         const std::shared_ptr<C2BlockPool> &pool) {
143     // Initialize output work
144     work->result = C2_OK;
145     work->workletsProcessed = 1u;
146     work->worklets.front()->output.flags = work->input.flags;
147 
148     if (mSignalledOutputEos) {
149         work->result = C2_BAD_VALUE;
150         return;
151     }
152 
153     C2ReadView rView = mDummyReadView;
154     size_t inOffset = 0u;
155     size_t inSize = 0u;
156     if (!work->input.buffers.empty()) {
157         rView = work->input.buffers[0]->data().linearBlocks().front().map().get();
158         inSize = rView.capacity();
159         if (inSize && rView.error()) {
160             ALOGE("read view map failed %d", rView.error());
161             work->result = C2_CORRUPTED;
162             return;
163         }
164     }
165     bool eos = (work->input.flags & C2FrameData::FLAG_END_OF_STREAM) != 0;
166     int outSize = inSize * sizeof(int16_t);
167 
168     ALOGV("in buffer attr. size %zu timestamp %d frameindex %d", inSize,
169           (int)work->input.ordinal.timestamp.peeku(), (int)work->input.ordinal.frameIndex.peeku());
170 
171     if (inSize == 0) {
172         work->worklets.front()->output.flags = work->input.flags;
173         work->worklets.front()->output.buffers.clear();
174         work->worklets.front()->output.ordinal = work->input.ordinal;
175         if (eos) {
176             mSignalledOutputEos = true;
177             ALOGV("signalled EOS");
178         }
179         return;
180     }
181 
182     uint8_t *inputptr = const_cast<uint8_t *>(rView.data() + inOffset);
183 
184     std::shared_ptr<C2LinearBlock> block;
185     C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
186     c2_status_t err = pool->fetchLinearBlock(outSize, usage, &block);
187     if (err != C2_OK) {
188         ALOGE("fetchLinearBlock for Output failed with status %d", err);
189         work->result = C2_NO_MEMORY;
190         return;
191     }
192     C2WriteView wView = block->map().get();
193     if (wView.error()) {
194         ALOGE("write view map failed %d", wView.error());
195         work->result = C2_CORRUPTED;
196         return;
197     }
198     int16_t *outputptr = reinterpret_cast<int16_t *>(wView.data());
199 
200 #ifdef ALAW
201     DecodeALaw(outputptr, inputptr, inSize);
202 #else
203     DecodeMLaw(outputptr, inputptr, inSize);
204 #endif
205 
206     work->worklets.front()->output.flags = work->input.flags;
207     work->worklets.front()->output.buffers.clear();
208     work->worklets.front()->output.buffers.push_back(createLinearBuffer(block));
209     work->worklets.front()->output.ordinal = work->input.ordinal;
210 
211     if (eos) {
212         mSignalledOutputEos = true;
213         ALOGV("signalled EOS");
214     }
215 }
216 
drain(uint32_t drainMode,const std::shared_ptr<C2BlockPool> & pool)217 c2_status_t C2SoftG711Dec::drain(
218         uint32_t drainMode,
219         const std::shared_ptr<C2BlockPool> &pool) {
220     (void) pool;
221     if (drainMode == NO_DRAIN) {
222         ALOGW("drain with NO_DRAIN: no-op");
223         return C2_OK;
224     }
225     if (drainMode == DRAIN_CHAIN) {
226         ALOGW("DRAIN_CHAIN not supported");
227         return C2_OMITTED;
228     }
229 
230     return C2_OK;
231 }
232 
233 #ifdef ALAW
DecodeALaw(int16_t * out,const uint8_t * in,size_t inSize)234 void C2SoftG711Dec::DecodeALaw(
235         int16_t *out, const uint8_t *in, size_t inSize) {
236     while (inSize > 0) {
237         inSize--;
238         int32_t x = *in++;
239 
240         int32_t ix = x ^ 0x55;
241         ix &= 0x7f;
242 
243         int32_t iexp = ix >> 4;
244         int32_t mant = ix & 0x0f;
245 
246         if (iexp > 0) {
247             mant += 16;
248         }
249 
250         mant = (mant << 4) + 8;
251 
252         if (iexp > 1) {
253             mant = mant << (iexp - 1);
254         }
255 
256         *out++ = (x > 127) ? mant : -mant;
257     }
258 }
259 #else
DecodeMLaw(int16_t * out,const uint8_t * in,size_t inSize)260 void C2SoftG711Dec::DecodeMLaw(
261         int16_t *out, const uint8_t *in, size_t inSize) {
262     while (inSize > 0) {
263         inSize--;
264         int32_t x = *in++;
265 
266         int32_t mantissa = ~x;
267         int32_t exponent = (mantissa >> 4) & 7;
268         int32_t segment = exponent + 1;
269         mantissa &= 0x0f;
270 
271         int32_t step = 4 << segment;
272 
273         int32_t abs = (0x80l << exponent) + step * mantissa + step / 2 - 4 * 33;
274 
275         *out++ = (x < 0x80) ? -abs : abs;
276     }
277 }
278 #endif
279 
280 class C2SoftG711DecFactory : public C2ComponentFactory {
281 public:
C2SoftG711DecFactory()282     C2SoftG711DecFactory() : mHelper(std::static_pointer_cast<C2ReflectorHelper>(
283             GetCodec2PlatformComponentStore()->getParamReflector())) {
284     }
285 
createComponent(c2_node_id_t id,std::shared_ptr<C2Component> * const component,std::function<void (C2Component *)> deleter)286     virtual c2_status_t createComponent(
287             c2_node_id_t id,
288             std::shared_ptr<C2Component>* const component,
289             std::function<void(C2Component*)> deleter) override {
290         *component = std::shared_ptr<C2Component>(
291                 new C2SoftG711Dec(COMPONENT_NAME, id,
292                                std::make_shared<C2SoftG711Dec::IntfImpl>(mHelper)),
293                 deleter);
294         return C2_OK;
295     }
296 
createInterface(c2_node_id_t id,std::shared_ptr<C2ComponentInterface> * const interface,std::function<void (C2ComponentInterface *)> deleter)297     virtual c2_status_t createInterface(
298             c2_node_id_t id, std::shared_ptr<C2ComponentInterface>* const interface,
299             std::function<void(C2ComponentInterface*)> deleter) override {
300         *interface = std::shared_ptr<C2ComponentInterface>(
301                 new SimpleInterface<C2SoftG711Dec::IntfImpl>(
302                         COMPONENT_NAME, id, std::make_shared<C2SoftG711Dec::IntfImpl>(mHelper)),
303                 deleter);
304         return C2_OK;
305     }
306 
307     virtual ~C2SoftG711DecFactory() override = default;
308 
309 private:
310     std::shared_ptr<C2ReflectorHelper> mHelper;
311 };
312 
313 }  // namespace android
314 
CreateCodec2Factory()315 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
316     ALOGV("in %s", __func__);
317     return new ::android::C2SoftG711DecFactory();
318 }
319 
DestroyCodec2Factory(::C2ComponentFactory * factory)320 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
321     ALOGV("in %s", __func__);
322     delete factory;
323 }
324