• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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       mInitCheck(NO_INIT),
148       mOffsetTableLength(0) {
149     float confidence;
150     if (!SniffAMR(mDataSource, &mIsWide, &confidence)) {
151         return;
152     }
153 
154     mMeta = AMediaFormat_new();
155     AMediaFormat_setString(mMeta, AMEDIAFORMAT_KEY_MIME,
156             mIsWide ? MEDIA_MIMETYPE_AUDIO_AMR_WB : MEDIA_MIMETYPE_AUDIO_AMR_NB);
157 
158     AMediaFormat_setInt32(mMeta, AMEDIAFORMAT_KEY_CHANNEL_COUNT, 1);
159     AMediaFormat_setInt32(mMeta, AMEDIAFORMAT_KEY_SAMPLE_RATE, mIsWide ? 16000 : 8000);
160 
161     off64_t offset = mIsWide ? 9 : 6;
162     off64_t streamSize;
163     size_t frameSize, numFrames = 0;
164     int64_t duration = 0;
165 
166     if (mDataSource->getSize(&streamSize) == OK) {
167         while (offset < streamSize) {
168             status_t status = getFrameSizeByOffset(source, offset, mIsWide, &frameSize);
169             if (status == ERROR_END_OF_STREAM) {
170                 break;
171             } else if (status != OK) {
172                 return;
173             }
174 
175             if ((numFrames % 50 == 0) && (numFrames / 50 < OFFSET_TABLE_LEN)) {
176                 CHECK_EQ(mOffsetTableLength, numFrames / 50);
177                 mOffsetTable[mOffsetTableLength] = offset - (mIsWide ? 9: 6);
178                 mOffsetTableLength ++;
179             }
180 
181             offset += frameSize;
182             duration += 20000;  // Each frame is 20ms
183             numFrames ++;
184         }
185 
186         AMediaFormat_setInt64(mMeta, AMEDIAFORMAT_KEY_DURATION, duration);
187     }
188 
189     mInitCheck = OK;
190 }
191 
~AMRExtractor()192 AMRExtractor::~AMRExtractor() {
193     delete mDataSource;
194     AMediaFormat_delete(mMeta);
195 }
196 
getMetaData(AMediaFormat * meta)197 media_status_t AMRExtractor::getMetaData(AMediaFormat *meta) {
198     AMediaFormat_clear(meta);
199 
200     if (mInitCheck == OK) {
201         AMediaFormat_setString(meta,
202                 AMEDIAFORMAT_KEY_MIME, mIsWide ? MEDIA_MIMETYPE_AUDIO_AMR_WB : "audio/amr");
203     }
204 
205     return AMEDIA_OK;
206 }
207 
countTracks()208 size_t AMRExtractor::countTracks() {
209     return mInitCheck == OK ? 1 : 0;
210 }
211 
getTrack(size_t index)212 MediaTrackHelper *AMRExtractor::getTrack(size_t index) {
213     if (mInitCheck != OK || index != 0) {
214         return NULL;
215     }
216 
217     return new AMRSource(mDataSource, mMeta, mIsWide,
218             mOffsetTable, mOffsetTableLength);
219 }
220 
getTrackMetaData(AMediaFormat * meta,size_t index,uint32_t)221 media_status_t AMRExtractor::getTrackMetaData(AMediaFormat *meta, size_t index, uint32_t /* flags */) {
222     if (mInitCheck != OK || index != 0) {
223         return AMEDIA_ERROR_UNKNOWN;
224     }
225 
226     return AMediaFormat_copy(meta, mMeta);
227 }
228 
229 ////////////////////////////////////////////////////////////////////////////////
230 
AMRSource(DataSourceHelper * source,AMediaFormat * meta,bool isWide,const off64_t * offset_table,size_t offset_table_length)231 AMRSource::AMRSource(
232         DataSourceHelper *source, AMediaFormat *meta,
233         bool isWide, const off64_t *offset_table, size_t offset_table_length)
234     : mDataSource(source),
235       mMeta(meta),
236       mIsWide(isWide),
237       mOffset(mIsWide ? 9 : 6),
238       mCurrentTimeUs(0),
239       mStarted(false),
240       mGroup(NULL),
241       mOffsetTableLength(offset_table_length) {
242     if (mOffsetTableLength > 0 && mOffsetTableLength <= OFFSET_TABLE_LEN) {
243         memcpy ((char*)mOffsetTable, (char*)offset_table, sizeof(off64_t) * mOffsetTableLength);
244     }
245 }
246 
~AMRSource()247 AMRSource::~AMRSource() {
248     if (mStarted) {
249         stop();
250     }
251 }
252 
start()253 media_status_t AMRSource::start() {
254     CHECK(!mStarted);
255 
256     mOffset = mIsWide ? 9 : 6;
257     mCurrentTimeUs = 0;
258     mBufferGroup->add_buffer(128);
259     mStarted = true;
260 
261     return AMEDIA_OK;
262 }
263 
stop()264 media_status_t AMRSource::stop() {
265     CHECK(mStarted);
266 
267     mStarted = false;
268     return AMEDIA_OK;
269 }
270 
getFormat(AMediaFormat * meta)271 media_status_t AMRSource::getFormat(AMediaFormat *meta) {
272     return AMediaFormat_copy(meta, mMeta);
273 }
274 
read(MediaBufferHelper ** out,const ReadOptions * options)275 media_status_t AMRSource::read(
276         MediaBufferHelper **out, const ReadOptions *options) {
277     *out = NULL;
278 
279     int64_t seekTimeUs;
280     ReadOptions::SeekMode mode;
281     if (mOffsetTableLength > 0 && options && options->getSeekTo(&seekTimeUs, &mode)) {
282         size_t size;
283         int64_t seekFrame = seekTimeUs / 20000LL;  // 20ms per frame.
284         mCurrentTimeUs = seekFrame * 20000LL;
285 
286         size_t index = seekFrame < 0 ? 0 : seekFrame / 50;
287         if (index >= mOffsetTableLength) {
288             index = mOffsetTableLength - 1;
289         }
290 
291         mOffset = mOffsetTable[index] + (mIsWide ? 9 : 6);
292 
293         for (size_t i = 0; i< seekFrame - index * 50; i++) {
294             media_status_t err;
295             if ((err = getFrameSizeByOffset(mDataSource, mOffset,
296                             mIsWide, &size)) != OK) {
297                 return err;
298             }
299             mOffset += size;
300         }
301     }
302 
303     uint8_t header;
304     ssize_t n = mDataSource->readAt(mOffset, &header, 1);
305 
306     if (n < 1) {
307         return AMEDIA_ERROR_END_OF_STREAM;
308     }
309 
310     if (header & 0x83) {
311         // Padding bits must be 0.
312 
313         ALOGE("padding bits must be 0, header is 0x%02x", header);
314 
315         return AMEDIA_ERROR_MALFORMED;
316     }
317 
318     unsigned FT = (header >> 3) & 0x0f;
319 
320     size_t frameSize = getFrameSize(mIsWide, FT);
321     if (frameSize == 0) {
322         return AMEDIA_ERROR_MALFORMED;
323     }
324 
325     MediaBufferHelper *buffer;
326     status_t err = mBufferGroup->acquire_buffer(&buffer);
327     if (err != OK) {
328         return AMEDIA_ERROR_UNKNOWN;
329     }
330 
331     n = mDataSource->readAt(mOffset, buffer->data(), frameSize);
332 
333     if (n != (ssize_t)frameSize) {
334         buffer->release();
335         buffer = NULL;
336 
337         if (n < 0) {
338             return AMEDIA_ERROR_IO;
339         } else {
340             // only partial frame is available, treat it as EOS.
341             mOffset += n;
342             return AMEDIA_ERROR_END_OF_STREAM;
343         }
344     }
345 
346     buffer->set_range(0, frameSize);
347     AMediaFormat *meta = buffer->meta_data();
348     AMediaFormat_setInt64(meta, AMEDIAFORMAT_KEY_TIME_US, mCurrentTimeUs);
349     AMediaFormat_setInt32(meta, AMEDIAFORMAT_KEY_IS_SYNC_FRAME, 1);
350 
351     mOffset += frameSize;
352     mCurrentTimeUs += 20000;  // Each frame is 20ms
353 
354     *out = buffer;
355 
356     return AMEDIA_OK;
357 }
358 
359 ////////////////////////////////////////////////////////////////////////////////
360 
361 static const char *extensions[] = {
362     "amr",
363     "awb",
364     NULL
365 };
366 
367 extern "C" {
368 // This is the only symbol that needs to be exported
369 __attribute__ ((visibility ("default")))
GETEXTRACTORDEF()370 ExtractorDef GETEXTRACTORDEF() {
371     return {
372         EXTRACTORDEF_VERSION,
373         UUID("c86639c9-2f31-40ac-a715-fa01b4493aaf"),
374         1,
375         "AMR Extractor",
376         {
377            .v3 = {
378                [](
379                    CDataSource *source,
380                    float *confidence,
381                    void **,
382                    FreeMetaFunc *) -> CreatorFunc {
383                    DataSourceHelper helper(source);
384                    if (SniffAMR(&helper, nullptr, confidence)) {
385                        return [](
386                                CDataSource *source,
387                                void *) -> CMediaExtractor* {
388                            return wrap(new AMRExtractor(new DataSourceHelper(source)));};
389                    }
390                    return NULL;
391                },
392                extensions
393            },
394         },
395     };
396 }
397 
398 } // extern "C"
399 
400 }  // namespace android
401