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