1 /*
2  * Copyright (C) 2009 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 "AMRExtractor"
19 #include <utils/Log.h>
20 
21 #include "AMRExtractor.h"
22 
23 #include <media/stagefright/foundation/ADebug.h>
24 #include <media/stagefright/MediaBufferGroup.h>
25 #include <media/stagefright/MediaDefs.h>
26 #include <media/stagefright/MediaErrors.h>
27 #include <media/stagefright/MetaData.h>
28 #include <utils/String8.h>
29 
30 namespace android {
31 
32 class AMRSource : public MediaTrackHelper {
33 public:
34     AMRSource(
35             DataSourceHelper *source,
36             AMediaFormat *meta,
37             bool isWide,
38             const off64_t *offset_table,
39             size_t offset_table_length);
40 
41     virtual media_status_t start();
42     virtual media_status_t stop();
43 
44     virtual media_status_t getFormat(AMediaFormat *);
45 
46     virtual media_status_t read(
47             MediaBufferHelper **buffer, const ReadOptions *options = NULL);
48 
49 protected:
50     virtual ~AMRSource();
51 
52 private:
53     DataSourceHelper *mDataSource;
54     AMediaFormat *mMeta;
55     bool mIsWide;
56 
57     off64_t mOffset;
58     int64_t mCurrentTimeUs;
59     bool mStarted;
60     MediaBufferGroup *mGroup;
61 
62     off64_t mOffsetTable[OFFSET_TABLE_LEN];
63     size_t mOffsetTableLength;
64 
65     AMRSource(const AMRSource &);
66     AMRSource &operator=(const AMRSource &);
67 };
68 
69 ////////////////////////////////////////////////////////////////////////////////
70 
getFrameSize(bool isWide,unsigned FT)71 static size_t getFrameSize(bool isWide, unsigned FT) {
72     static const size_t kFrameSizeNB[16] = {
73         95, 103, 118, 134, 148, 159, 204, 244,
74         39, 43, 38, 37, // SID
75         0, 0, 0, // future use
76         0 // no data
77     };
78     static const size_t kFrameSizeWB[16] = {
79         132, 177, 253, 285, 317, 365, 397, 461, 477,
80         40, // SID
81         0, 0, 0, 0, // future use
82         0, // speech lost
83         0 // no data
84     };
85 
86     if (FT > 15 || (isWide && FT > 9 && FT < 14) || (!isWide && FT > 11 && FT < 15)) {
87         ALOGE("illegal AMR frame type %d", FT);
88         return 0;
89     }
90 
91     size_t frameSize = isWide ? kFrameSizeWB[FT] : kFrameSizeNB[FT];
92 
93     // Round up bits to bytes and add 1 for the header byte.
94     frameSize = (frameSize + 7) / 8 + 1;
95 
96     return frameSize;
97 }
98 
getFrameSizeByOffset(DataSourceHelper * source,off64_t offset,bool isWide,size_t * frameSize)99 static media_status_t getFrameSizeByOffset(DataSourceHelper *source,
100         off64_t offset, bool isWide, size_t *frameSize) {
101     uint8_t header;
102     ssize_t count = source->readAt(offset, &header, 1);
103     if (count == 0) {
104         return AMEDIA_ERROR_END_OF_STREAM;
105     } else if (count < 0) {
106         return AMEDIA_ERROR_IO;
107     }
108 
109     unsigned FT = (header >> 3) & 0x0f;
110 
111     *frameSize = getFrameSize(isWide, FT);
112     if (*frameSize == 0) {
113         return AMEDIA_ERROR_MALFORMED;
114     }
115     return AMEDIA_OK;
116 }
117 
SniffAMR(DataSourceHelper * source,bool * isWide,float * confidence)118 static bool SniffAMR(
119         DataSourceHelper *source, bool *isWide, float *confidence) {
120     char header[9];
121 
122     if (source->readAt(0, header, sizeof(header)) != sizeof(header)) {
123         return false;
124     }
125 
126     if (!memcmp(header, "#!AMR\n", 6)) {
127         if (isWide != nullptr) {
128             *isWide = false;
129         }
130         *confidence = 0.5;
131 
132         return true;
133     } else if (!memcmp(header, "#!AMR-WB\n", 9)) {
134         if (isWide != nullptr) {
135             *isWide = true;
136         }
137         *confidence = 0.5;
138 
139         return true;
140     }
141 
142     return false;
143 }
144 
AMRExtractor(DataSourceHelper * source)145 AMRExtractor::AMRExtractor(DataSourceHelper *source)
146     : mDataSource(source),
147       mMeta(NULL),
148       mInitCheck(NO_INIT),
149       mOffsetTableLength(0) {
150     float confidence;
151     if (!SniffAMR(mDataSource, &mIsWide, &confidence)) {
152         return;
153     }
154 
155     mMeta = AMediaFormat_new();
156     AMediaFormat_setString(mMeta, AMEDIAFORMAT_KEY_MIME,
157             mIsWide ? MEDIA_MIMETYPE_AUDIO_AMR_WB : MEDIA_MIMETYPE_AUDIO_AMR_NB);
158 
159     AMediaFormat_setInt32(mMeta, AMEDIAFORMAT_KEY_CHANNEL_COUNT, 1);
160     AMediaFormat_setInt32(mMeta, AMEDIAFORMAT_KEY_SAMPLE_RATE, mIsWide ? 16000 : 8000);
161 
162     off64_t offset = mIsWide ? 9 : 6;
163     off64_t streamSize;
164     size_t frameSize, numFrames = 0;
165     int64_t duration = 0;
166 
167     if (mDataSource->getSize(&streamSize) == OK) {
168         while (offset < streamSize) {
169             status_t status = getFrameSizeByOffset(source, offset, mIsWide, &frameSize);
170             if (status == ERROR_END_OF_STREAM) {
171                 break;
172             } else if (status != OK) {
173                 return;
174             }
175 
176             if ((numFrames % 50 == 0) && (numFrames / 50 < OFFSET_TABLE_LEN)) {
177                 CHECK_EQ(mOffsetTableLength, numFrames / 50);
178                 mOffsetTable[mOffsetTableLength] = offset - (mIsWide ? 9: 6);
179                 mOffsetTableLength ++;
180             }
181 
182             offset += frameSize;
183             duration += 20000;  // Each frame is 20ms
184             numFrames ++;
185         }
186 
187         AMediaFormat_setInt64(mMeta, AMEDIAFORMAT_KEY_DURATION, duration);
188     }
189 
190     mInitCheck = OK;
191 }
192 
~AMRExtractor()193 AMRExtractor::~AMRExtractor() {
194     delete mDataSource;
195     if (mMeta) {
196         AMediaFormat_delete(mMeta);
197     }
198 }
199 
getMetaData(AMediaFormat * meta)200 media_status_t AMRExtractor::getMetaData(AMediaFormat *meta) {
201     AMediaFormat_clear(meta);
202 
203     if (mInitCheck == OK) {
204         AMediaFormat_setString(meta,
205                 AMEDIAFORMAT_KEY_MIME, mIsWide ? MEDIA_MIMETYPE_AUDIO_AMR_WB : "audio/amr");
206     }
207 
208     return AMEDIA_OK;
209 }
210 
countTracks()211 size_t AMRExtractor::countTracks() {
212     return mInitCheck == OK ? 1 : 0;
213 }
214 
getTrack(size_t index)215 MediaTrackHelper *AMRExtractor::getTrack(size_t index) {
216     if (mInitCheck != OK || index != 0) {
217         return NULL;
218     }
219 
220     return new AMRSource(mDataSource, mMeta, mIsWide,
221             mOffsetTable, mOffsetTableLength);
222 }
223 
getTrackMetaData(AMediaFormat * meta,size_t index,uint32_t)224 media_status_t AMRExtractor::getTrackMetaData(AMediaFormat *meta, size_t index, uint32_t /* flags */) {
225     if (mInitCheck != OK || index != 0) {
226         return AMEDIA_ERROR_UNKNOWN;
227     }
228 
229     return AMediaFormat_copy(meta, mMeta);
230 }
231 
232 ////////////////////////////////////////////////////////////////////////////////
233 
AMRSource(DataSourceHelper * source,AMediaFormat * meta,bool isWide,const off64_t * offset_table,size_t offset_table_length)234 AMRSource::AMRSource(
235         DataSourceHelper *source, AMediaFormat *meta,
236         bool isWide, const off64_t *offset_table, size_t offset_table_length)
237     : mDataSource(source),
238       mMeta(meta),
239       mIsWide(isWide),
240       mOffset(mIsWide ? 9 : 6),
241       mCurrentTimeUs(0),
242       mStarted(false),
243       mGroup(NULL),
244       mOffsetTableLength(offset_table_length) {
245     if (mOffsetTableLength > 0 && mOffsetTableLength <= OFFSET_TABLE_LEN) {
246         memcpy ((char*)mOffsetTable, (char*)offset_table, sizeof(off64_t) * mOffsetTableLength);
247     }
248 }
249 
~AMRSource()250 AMRSource::~AMRSource() {
251     if (mStarted) {
252         stop();
253     }
254 }
255 
start()256 media_status_t AMRSource::start() {
257     CHECK(!mStarted);
258 
259     mOffset = mIsWide ? 9 : 6;
260     mCurrentTimeUs = 0;
261     mBufferGroup->add_buffer(128);
262     mStarted = true;
263 
264     return AMEDIA_OK;
265 }
266 
stop()267 media_status_t AMRSource::stop() {
268     CHECK(mStarted);
269 
270     mStarted = false;
271     return AMEDIA_OK;
272 }
273 
getFormat(AMediaFormat * meta)274 media_status_t AMRSource::getFormat(AMediaFormat *meta) {
275     return AMediaFormat_copy(meta, mMeta);
276 }
277 
read(MediaBufferHelper ** out,const ReadOptions * options)278 media_status_t AMRSource::read(
279         MediaBufferHelper **out, const ReadOptions *options) {
280     *out = NULL;
281 
282     int64_t seekTimeUs;
283     ReadOptions::SeekMode mode;
284     if (mOffsetTableLength > 0 && options && options->getSeekTo(&seekTimeUs, &mode)) {
285         size_t size;
286         int64_t seekFrame = seekTimeUs / 20000LL;  // 20ms per frame.
287         mCurrentTimeUs = seekFrame * 20000LL;
288 
289         size_t index = seekFrame < 0 ? 0 : seekFrame / 50;
290         if (index >= mOffsetTableLength) {
291             index = mOffsetTableLength - 1;
292         }
293 
294         mOffset = mOffsetTable[index] + (mIsWide ? 9 : 6);
295 
296         for (size_t i = 0; i< seekFrame - index * 50; i++) {
297             media_status_t err;
298             if ((err = getFrameSizeByOffset(mDataSource, mOffset,
299                             mIsWide, &size)) != OK) {
300                 return err;
301             }
302             mOffset += size;
303         }
304     }
305 
306     uint8_t header;
307     ssize_t n = mDataSource->readAt(mOffset, &header, 1);
308 
309     if (n < 1) {
310         return AMEDIA_ERROR_END_OF_STREAM;
311     }
312 
313     if (header & 0x83) {
314         // Padding bits must be 0.
315 
316         ALOGE("padding bits must be 0, header is 0x%02x", header);
317 
318         return AMEDIA_ERROR_MALFORMED;
319     }
320 
321     unsigned FT = (header >> 3) & 0x0f;
322 
323     size_t frameSize = getFrameSize(mIsWide, FT);
324     if (frameSize == 0) {
325         return AMEDIA_ERROR_MALFORMED;
326     }
327 
328     MediaBufferHelper *buffer;
329     status_t err = mBufferGroup->acquire_buffer(&buffer);
330     if (err != OK) {
331         return AMEDIA_ERROR_UNKNOWN;
332     }
333 
334     n = mDataSource->readAt(mOffset, buffer->data(), frameSize);
335 
336     if (n != (ssize_t)frameSize) {
337         buffer->release();
338         buffer = NULL;
339 
340         if (n < 0) {
341             return AMEDIA_ERROR_IO;
342         } else {
343             // only partial frame is available, treat it as EOS.
344             mOffset += n;
345             return AMEDIA_ERROR_END_OF_STREAM;
346         }
347     }
348 
349     buffer->set_range(0, frameSize);
350     AMediaFormat *meta = buffer->meta_data();
351     AMediaFormat_setInt64(meta, AMEDIAFORMAT_KEY_TIME_US, mCurrentTimeUs);
352     AMediaFormat_setInt32(meta, AMEDIAFORMAT_KEY_IS_SYNC_FRAME, 1);
353 
354     mOffset += frameSize;
355     mCurrentTimeUs += 20000;  // Each frame is 20ms
356 
357     *out = buffer;
358 
359     return AMEDIA_OK;
360 }
361 
362 ////////////////////////////////////////////////////////////////////////////////
363 
364 static const char *extensions[] = {
365     "amr",
366     "awb",
367     NULL
368 };
369 
370 extern "C" {
371 // This is the only symbol that needs to be exported
372 __attribute__ ((visibility ("default")))
GETEXTRACTORDEF()373 ExtractorDef GETEXTRACTORDEF() {
374     return {
375         EXTRACTORDEF_VERSION,
376         UUID("c86639c9-2f31-40ac-a715-fa01b4493aaf"),
377         1,
378         "AMR Extractor",
379         {
380            .v3 = {
381                [](
382                    CDataSource *source,
383                    float *confidence,
384                    void **,
385                    FreeMetaFunc *) -> CreatorFunc {
386                    DataSourceHelper helper(source);
387                    if (SniffAMR(&helper, nullptr, confidence)) {
388                        return [](
389                                CDataSource *source,
390                                void *) -> CMediaExtractor* {
391                            return wrap(new AMRExtractor(new DataSourceHelper(source)));};
392                    }
393                    return NULL;
394                },
395                extensions
396            },
397         },
398     };
399 }
400 
401 } // extern "C"
402 
403 }  // namespace android
404