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 "MP3Extractor"
19 #include <utils/Log.h>
20 
21 #include "MP3Extractor.h"
22 
23 #include "ID3.h"
24 #include "VBRISeeker.h"
25 #include "XINGSeeker.h"
26 
27 #include <media/stagefright/foundation/ADebug.h>
28 #include <media/stagefright/foundation/AMessage.h>
29 #include <media/stagefright/foundation/avc_utils.h>
30 #include <media/stagefright/foundation/ByteUtils.h>
31 #include <media/stagefright/MediaBufferBase.h>
32 #include <media/stagefright/MediaBufferGroup.h>
33 #include <media/stagefright/MediaDefs.h>
34 #include <media/stagefright/MediaErrors.h>
35 #include <media/stagefright/MetaData.h>
36 #include <utils/String8.h>
37 
38 namespace android {
39 
40 // Everything must match except for
41 // protection, bitrate, padding, private bits, mode, mode extension,
42 // copyright bit, original bit and emphasis.
43 // Yes ... there are things that must indeed match...
44 static const uint32_t kMask = 0xfffe0c00;
45 
Resync(DataSourceHelper * source,uint32_t match_header,off64_t * inout_pos,off64_t * post_id3_pos,uint32_t * out_header)46 static bool Resync(
47         DataSourceHelper *source, uint32_t match_header,
48         off64_t *inout_pos, off64_t *post_id3_pos, uint32_t *out_header) {
49     if (post_id3_pos != NULL) {
50         *post_id3_pos = 0;
51     }
52 
53     if (*inout_pos == 0) {
54         // Skip an optional ID3 header if syncing at the very beginning
55         // of the datasource.
56 
57         for (;;) {
58             uint8_t id3header[10];
59             if (source->readAt(*inout_pos, id3header, sizeof(id3header))
60                     < (ssize_t)sizeof(id3header)) {
61                 // If we can't even read these 10 bytes, we might as well bail
62                 // out, even if there _were_ 10 bytes of valid mp3 audio data...
63                 return false;
64             }
65 
66             if (memcmp("ID3", id3header, 3)) {
67                 break;
68             }
69 
70             // Skip the ID3v2 header.
71 
72             size_t len =
73                 ((id3header[6] & 0x7f) << 21)
74                 | ((id3header[7] & 0x7f) << 14)
75                 | ((id3header[8] & 0x7f) << 7)
76                 | (id3header[9] & 0x7f);
77 
78             len += 10;
79 
80             *inout_pos += len;
81 
82             ALOGV("skipped ID3 tag, new starting offset is %lld (0x%016llx)",
83                     (long long)*inout_pos, (long long)*inout_pos);
84         }
85 
86         if (post_id3_pos != NULL) {
87             *post_id3_pos = *inout_pos;
88         }
89     }
90 
91     off64_t pos = *inout_pos;
92     bool valid = false;
93 
94     const size_t kMaxReadBytes = 1024;
95     const size_t kMaxBytesChecked = 128 * 1024;
96     uint8_t buf[kMaxReadBytes];
97     ssize_t bytesToRead = kMaxReadBytes;
98     ssize_t totalBytesRead = 0;
99     ssize_t remainingBytes = 0;
100     bool reachEOS = false;
101     uint8_t *tmp = buf;
102 
103     do {
104         if (pos >= (off64_t)(*inout_pos + kMaxBytesChecked)) {
105             // Don't scan forever.
106             ALOGV("giving up at offset %lld", (long long)pos);
107             break;
108         }
109 
110         if (remainingBytes < 4) {
111             if (reachEOS) {
112                 break;
113             } else {
114                 memcpy(buf, tmp, remainingBytes);
115                 bytesToRead = kMaxReadBytes - remainingBytes;
116 
117                 /*
118                  * The next read position should start from the end of
119                  * the last buffer, and thus should include the remaining
120                  * bytes in the buffer.
121                  */
122                 totalBytesRead = source->readAt(pos + remainingBytes,
123                                                 buf + remainingBytes,
124                                                 bytesToRead);
125                 if (totalBytesRead <= 0) {
126                     break;
127                 }
128                 reachEOS = (totalBytesRead != bytesToRead);
129                 totalBytesRead += remainingBytes;
130                 remainingBytes = totalBytesRead;
131                 tmp = buf;
132                 continue;
133             }
134         }
135 
136         uint32_t header = U32_AT(tmp);
137 
138         if (match_header != 0 && (header & kMask) != (match_header & kMask)) {
139             ++pos;
140             ++tmp;
141             --remainingBytes;
142             continue;
143         }
144 
145         size_t frame_size;
146         int sample_rate, num_channels, bitrate;
147         if (!GetMPEGAudioFrameSize(
148                     header, &frame_size,
149                     &sample_rate, &num_channels, &bitrate)) {
150             ++pos;
151             ++tmp;
152             --remainingBytes;
153             continue;
154         }
155 
156         ALOGV("found possible 1st frame at %lld (header = 0x%08x)", (long long)pos, header);
157 
158         // We found what looks like a valid frame,
159         // now find its successors.
160 
161         off64_t test_pos = pos + frame_size;
162 
163         valid = true;
164         for (int j = 0; j < 3; ++j) {
165             uint8_t tmp[4];
166             if (source->readAt(test_pos, tmp, 4) < 4) {
167                 valid = false;
168                 break;
169             }
170 
171             uint32_t test_header = U32_AT(tmp);
172 
173             ALOGV("subsequent header is %08x", test_header);
174 
175             if ((test_header & kMask) != (header & kMask)) {
176                 valid = false;
177                 break;
178             }
179 
180             size_t test_frame_size;
181             if (!GetMPEGAudioFrameSize(
182                         test_header, &test_frame_size)) {
183                 valid = false;
184                 break;
185             }
186 
187             ALOGV("found subsequent frame #%d at %lld", j + 2, (long long)test_pos);
188 
189             test_pos += test_frame_size;
190         }
191 
192         if (valid) {
193             *inout_pos = pos;
194 
195             if (out_header != NULL) {
196                 *out_header = header;
197             }
198         } else {
199             ALOGV("no dice, no valid sequence of frames found.");
200         }
201 
202         ++pos;
203         ++tmp;
204         --remainingBytes;
205     } while (!valid);
206 
207     return valid;
208 }
209 
210 class MP3Source : public MediaTrackHelper {
211 public:
212     MP3Source(
213             AMediaFormat *meta, DataSourceHelper *source,
214             off64_t first_frame_pos, uint32_t fixed_header,
215             MP3Seeker *seeker);
216 
217     virtual media_status_t start();
218     virtual media_status_t stop();
219 
220     virtual media_status_t getFormat(AMediaFormat *meta);
221 
222     virtual media_status_t read(
223             MediaBufferHelper **buffer, const ReadOptions *options = NULL);
224 
225 protected:
226     virtual ~MP3Source();
227 
228 private:
229     static const size_t kMaxFrameSize;
230     AMediaFormat *mMeta = NULL;
231     DataSourceHelper *mDataSource = NULL;
232     off64_t mFirstFramePos = 0;
233     uint32_t mFixedHeader = 0;
234     off64_t mCurrentPos = 0;
235     int64_t mCurrentTimeUs = 0;
236     bool mStarted = false;
237     MP3Seeker *mSeeker = NULL;
238 
239     int64_t mBasisTimeUs = 0;
240     int64_t mSamplesRead = 0;
241 
242     MP3Source(const MP3Source &);
243     MP3Source &operator=(const MP3Source &);
244 };
245 
246 struct Mp3Meta {
247     off64_t pos;
248     off64_t post_id3_pos;
249     uint32_t header;
250 };
251 
MP3Extractor(DataSourceHelper * source,Mp3Meta * meta)252 MP3Extractor::MP3Extractor(
253         DataSourceHelper *source, Mp3Meta *meta)
254     : mDataSource(source) {
255 
256     off64_t pos = 0;
257     off64_t post_id3_pos;
258     uint32_t header;
259     bool success;
260 
261     if (meta != NULL) {
262         // The sniffer has already done all the hard work for us, simply
263         // accept its judgement.
264         pos = meta->pos;
265         header = meta->header;
266         post_id3_pos = meta->post_id3_pos;
267         success = true;
268     } else {
269         success = Resync(mDataSource, 0, &pos, &post_id3_pos, &header);
270     }
271 
272     if (!success) {
273         // mInitCheck will remain NO_INIT
274         return;
275     }
276 
277     mFirstFramePos = pos;
278     mFixedHeader = header;
279     XINGSeeker *seeker = XINGSeeker::CreateFromSource(mDataSource, mFirstFramePos);
280 
281     mMeta = AMediaFormat_new();
282     if (seeker == NULL) {
283         mSeeker = VBRISeeker::CreateFromSource(mDataSource, post_id3_pos);
284     } else {
285         mSeeker = seeker;
286         int encd = seeker->getEncoderDelay();
287         int encp = seeker->getEncoderPadding();
288         if (encd != 0 || encp != 0) {
289             AMediaFormat_setInt32(mMeta, AMEDIAFORMAT_KEY_ENCODER_DELAY, encd);
290             AMediaFormat_setInt32(mMeta, AMEDIAFORMAT_KEY_ENCODER_PADDING, encp);
291         }
292     }
293 
294     if (mSeeker != NULL) {
295         // While it is safe to send the XING/VBRI frame to the decoder, this will
296         // result in an extra 1152 samples being output. In addition, the bitrate
297         // of the Xing header might not match the rest of the file, which could
298         // lead to problems when seeking. The real first frame to decode is after
299         // the XING/VBRI frame, so skip there.
300         size_t frame_size;
301         int sample_rate;
302         int num_channels;
303         int bitrate;
304         GetMPEGAudioFrameSize(
305                 header, &frame_size, &sample_rate, &num_channels, &bitrate);
306         pos += frame_size;
307         if (!Resync(mDataSource, 0, &pos, &post_id3_pos, &header)) {
308             // mInitCheck will remain NO_INIT
309             return;
310         }
311         mFirstFramePos = pos;
312         mFixedHeader = header;
313     }
314 
315     size_t frame_size;
316     int sample_rate;
317     int num_channels;
318     int bitrate;
319     GetMPEGAudioFrameSize(
320             header, &frame_size, &sample_rate, &num_channels, &bitrate);
321 
322     unsigned layer = 4 - ((header >> 17) & 3);
323 
324     switch (layer) {
325         case 1:
326             AMediaFormat_setString(mMeta,
327                     AMEDIAFORMAT_KEY_MIME, MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I);
328             break;
329         case 2:
330             AMediaFormat_setString(mMeta,
331                     AMEDIAFORMAT_KEY_MIME, MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II);
332             break;
333         case 3:
334             AMediaFormat_setString(mMeta, AMEDIAFORMAT_KEY_MIME, MEDIA_MIMETYPE_AUDIO_MPEG);
335             break;
336         default:
337             TRESPASS();
338     }
339 
340     AMediaFormat_setInt32(mMeta, AMEDIAFORMAT_KEY_SAMPLE_RATE, sample_rate);
341     AMediaFormat_setInt32(mMeta, AMEDIAFORMAT_KEY_BIT_RATE, bitrate * 1000);
342     AMediaFormat_setInt32(mMeta, AMEDIAFORMAT_KEY_CHANNEL_COUNT, num_channels);
343 
344     int64_t durationUs;
345 
346     if (mSeeker == NULL || !mSeeker->getDuration(&durationUs)) {
347         off64_t fileSize;
348         if (mDataSource->getSize(&fileSize) == OK) {
349             off64_t dataLength = fileSize - mFirstFramePos;
350             if (dataLength > INT64_MAX / 8000LL) {
351                 // duration would overflow
352                 durationUs = INT64_MAX;
353             } else {
354                 durationUs = 8000LL * dataLength / bitrate;
355             }
356         } else {
357             durationUs = -1;
358         }
359     }
360 
361     if (durationUs >= 0) {
362         AMediaFormat_setInt64(mMeta, AMEDIAFORMAT_KEY_DURATION, durationUs);
363     }
364 
365     mInitCheck = OK;
366 
367     // Get iTunes-style gapless info if present.
368     // When getting the id3 tag, skip the V1 tags to prevent the source cache
369     // from being iterated to the end of the file.
370     DataSourceHelper helper(mDataSource);
371     ID3 id3(&helper, true);
372     if (id3.isValid()) {
373         ID3::Iterator *com = new ID3::Iterator(id3, "COM");
374         if (com->done()) {
375             delete com;
376             com = new ID3::Iterator(id3, "COMM");
377         }
378         while(!com->done()) {
379             String8 commentdesc;
380             String8 commentvalue;
381             com->getString(&commentdesc, &commentvalue);
382             const char * desc = commentdesc.c_str();
383             const char * value = commentvalue.c_str();
384 
385             // first 3 characters are the language, which we don't care about
386             if(strlen(desc) > 3 && strcmp(desc + 3, "iTunSMPB") == 0) {
387 
388                 int32_t delay, padding;
389                 if (sscanf(value, " %*x %x %x %*x", &delay, &padding) == 2) {
390                     AMediaFormat_setInt32(mMeta, AMEDIAFORMAT_KEY_ENCODER_DELAY, delay);
391                     AMediaFormat_setInt32(mMeta, AMEDIAFORMAT_KEY_ENCODER_PADDING, padding);
392                 }
393                 break;
394             }
395             com->next();
396         }
397         delete com;
398         com = NULL;
399     }
400 }
401 
~MP3Extractor()402 MP3Extractor::~MP3Extractor() {
403     delete mSeeker;
404     delete mDataSource;
405     AMediaFormat_delete(mMeta);
406 }
407 
countTracks()408 size_t MP3Extractor::countTracks() {
409     return mInitCheck != OK ? 0 : 1;
410 }
411 
getTrack(size_t index)412 MediaTrackHelper *MP3Extractor::getTrack(size_t index) {
413     if (mInitCheck != OK || index != 0) {
414         return NULL;
415     }
416 
417     return new MP3Source(
418             mMeta, mDataSource, mFirstFramePos, mFixedHeader,
419             mSeeker);
420 }
421 
getTrackMetaData(AMediaFormat * meta,size_t index,uint32_t)422 media_status_t MP3Extractor::getTrackMetaData(
423         AMediaFormat *meta,
424         size_t index, uint32_t /* flags */) {
425     if (mInitCheck != OK || index != 0) {
426         return AMEDIA_ERROR_UNKNOWN;
427     }
428     return AMediaFormat_copy(meta, mMeta);
429 }
430 
431 ////////////////////////////////////////////////////////////////////////////////
432 
433 // The theoretical maximum frame size for an MPEG audio stream should occur
434 // while playing a Layer 2, MPEGv2.5 audio stream at 160kbps (with padding).
435 // The size of this frame should be...
436 // ((1152 samples/frame * 160000 bits/sec) /
437 //  (8000 samples/sec * 8 bits/byte)) + 1 padding byte/frame = 2881 bytes/frame.
438 // Set our max frame size to the nearest power of 2 above this size (aka, 4kB)
439 const size_t MP3Source::kMaxFrameSize = (1 << 12); /* 4096 bytes */
440 
MP3Source(AMediaFormat * meta,DataSourceHelper * source,off64_t first_frame_pos,uint32_t fixed_header,MP3Seeker * seeker)441 MP3Source::MP3Source(
442         AMediaFormat *meta, DataSourceHelper *source,
443         off64_t first_frame_pos, uint32_t fixed_header,
444         MP3Seeker *seeker)
445     : mMeta(meta),
446       mDataSource(source),
447       mFirstFramePos(first_frame_pos),
448       mFixedHeader(fixed_header),
449       mSeeker(seeker) {
450 }
451 
~MP3Source()452 MP3Source::~MP3Source() {
453     if (mStarted) {
454         stop();
455     }
456 }
457 
start()458 media_status_t MP3Source::start() {
459     CHECK(!mStarted);
460 
461     mBufferGroup->add_buffer(kMaxFrameSize);
462 
463     mCurrentPos = mFirstFramePos;
464     mCurrentTimeUs = 0;
465 
466     mBasisTimeUs = mCurrentTimeUs;
467     mSamplesRead = 0;
468 
469     mStarted = true;
470 
471     return AMEDIA_OK;
472 }
473 
stop()474 media_status_t MP3Source::stop() {
475     CHECK(mStarted);
476 
477     mStarted = false;
478 
479     return AMEDIA_OK;
480 }
481 
getFormat(AMediaFormat * meta)482 media_status_t MP3Source::getFormat(AMediaFormat *meta) {
483     return AMediaFormat_copy(meta, mMeta);
484 }
485 
read(MediaBufferHelper ** out,const ReadOptions * options)486 media_status_t MP3Source::read(
487         MediaBufferHelper **out, const ReadOptions *options) {
488     *out = NULL;
489 
490     int64_t seekTimeUs;
491     ReadOptions::SeekMode mode;
492     bool seekCBR = false;
493 
494     if (options != NULL && options->getSeekTo(&seekTimeUs, &mode)) {
495         int64_t actualSeekTimeUs = seekTimeUs;
496         if (mSeeker == NULL
497                 || !mSeeker->getOffsetForTime(&actualSeekTimeUs, &mCurrentPos)) {
498             int32_t bitrate;
499             if (!AMediaFormat_getInt32(mMeta, AMEDIAFORMAT_KEY_BIT_RATE, &bitrate)) {
500                 // bitrate is in bits/sec.
501                 ALOGI("no bitrate");
502 
503                 return AMEDIA_ERROR_UNSUPPORTED;
504             }
505 
506             mCurrentTimeUs = seekTimeUs;
507             int64_t seekTimeUsTimesBitrate;
508             if (__builtin_mul_overflow(seekTimeUs, bitrate, &seekTimeUsTimesBitrate)) {
509               return AMEDIA_ERROR_UNSUPPORTED;
510             }
511             if (__builtin_add_overflow(
512                     mFirstFramePos, seekTimeUsTimesBitrate / 8000000, &mCurrentPos)) {
513                 return AMEDIA_ERROR_UNSUPPORTED;
514             }
515             seekCBR = true;
516         } else {
517             mCurrentTimeUs = actualSeekTimeUs;
518         }
519 
520         mBasisTimeUs = mCurrentTimeUs;
521         mSamplesRead = 0;
522     }
523 
524     MediaBufferHelper *buffer = nullptr;
525     status_t err = mBufferGroup->acquire_buffer(&buffer);
526     if (err != OK || buffer == nullptr) {
527         return AMEDIA_ERROR_UNKNOWN;
528     }
529 
530     size_t frame_size;
531     int bitrate;
532     int num_samples;
533     int sample_rate;
534     for (;;) {
535         ssize_t n = mDataSource->readAt(mCurrentPos, buffer->data(), 4);
536         if (n < 4) {
537             buffer->release();
538             buffer = NULL;
539 
540             return ((n < 0 && n != ERROR_END_OF_STREAM) ?
541                     AMEDIA_ERROR_UNKNOWN : AMEDIA_ERROR_END_OF_STREAM);
542         }
543 
544         uint32_t header = U32_AT((const uint8_t *)buffer->data());
545 
546         if ((header & kMask) == (mFixedHeader & kMask)
547             && GetMPEGAudioFrameSize(
548                 header, &frame_size, &sample_rate, NULL,
549                 &bitrate, &num_samples)) {
550 
551             // re-calculate mCurrentTimeUs because we might have called Resync()
552             if (seekCBR) {
553                 mCurrentTimeUs = (mCurrentPos - mFirstFramePos) * 8000 / bitrate;
554                 mBasisTimeUs = mCurrentTimeUs;
555             }
556 
557             break;
558         }
559 
560         // Lost sync.
561         ALOGV("lost sync! header = 0x%08x, old header = 0x%08x\n", header, mFixedHeader);
562 
563         off64_t pos = mCurrentPos;
564         if (!Resync(mDataSource, mFixedHeader, &pos, NULL, NULL)) {
565             ALOGE("Unable to resync. Signalling end of stream.");
566 
567             buffer->release();
568             buffer = NULL;
569 
570             return AMEDIA_ERROR_END_OF_STREAM;
571         }
572 
573         mCurrentPos = pos;
574 
575         // Try again with the new position.
576     }
577 
578     CHECK(frame_size <= buffer->size());
579 
580     ssize_t n = mDataSource->readAt(mCurrentPos, buffer->data(), frame_size);
581     if (n < (ssize_t)frame_size) {
582         buffer->release();
583         buffer = NULL;
584 
585         return ((n < 0 && n != ERROR_END_OF_STREAM) ?
586                 AMEDIA_ERROR_UNKNOWN : AMEDIA_ERROR_END_OF_STREAM);
587     }
588 
589     buffer->set_range(0, frame_size);
590 
591     AMediaFormat *meta = buffer->meta_data();
592     AMediaFormat_setInt64(meta, AMEDIAFORMAT_KEY_TIME_US, mCurrentTimeUs);
593     AMediaFormat_setInt32(meta, AMEDIAFORMAT_KEY_IS_SYNC_FRAME, 1);
594 
595     mCurrentPos += frame_size;
596 
597     mSamplesRead += num_samples;
598     mCurrentTimeUs = mBasisTimeUs + ((mSamplesRead * 1000000) / sample_rate);
599 
600     *out = buffer;
601 
602     return AMEDIA_OK;
603 }
604 
getMetaData(AMediaFormat * meta)605 media_status_t MP3Extractor::getMetaData(AMediaFormat *meta) {
606     AMediaFormat_clear(meta);
607     if (mInitCheck != OK) {
608         return AMEDIA_ERROR_UNKNOWN;
609     }
610     AMediaFormat_setString(meta, AMEDIAFORMAT_KEY_MIME, MEDIA_MIMETYPE_AUDIO_MPEG);
611 
612     DataSourceHelper helper(mDataSource);
613     ID3 id3(&helper);
614 
615     if (!id3.isValid()) {
616         return AMEDIA_OK;
617     }
618 
619     struct Map {
620         const char *key;
621         const char *tag1;
622         const char *tag2;
623     };
624     static const Map kMap[] = {
625         { AMEDIAFORMAT_KEY_ALBUM, "TALB", "TAL" },
626         { AMEDIAFORMAT_KEY_ARTIST, "TPE1", "TP1" },
627         { AMEDIAFORMAT_KEY_ALBUMARTIST, "TPE2", "TP2" },
628         { AMEDIAFORMAT_KEY_COMPOSER, "TCOM", "TCM" },
629         { AMEDIAFORMAT_KEY_GENRE, "TCON", "TCO" },
630         { AMEDIAFORMAT_KEY_TITLE, "TIT2", "TT2" },
631         { AMEDIAFORMAT_KEY_YEAR, "TYE", "TYER" },
632         { AMEDIAFORMAT_KEY_AUTHOR, "TXT", "TEXT" },
633         { AMEDIAFORMAT_KEY_CDTRACKNUMBER, "TRK", "TRCK" },
634         { AMEDIAFORMAT_KEY_DISCNUMBER, "TPA", "TPOS" },
635         { AMEDIAFORMAT_KEY_COMPILATION, "TCP", "TCMP" },
636     };
637     static const size_t kNumMapEntries = sizeof(kMap) / sizeof(kMap[0]);
638 
639     for (size_t i = 0; i < kNumMapEntries; ++i) {
640         ID3::Iterator *it = new ID3::Iterator(id3, kMap[i].tag1);
641         if (it->done()) {
642             delete it;
643             it = new ID3::Iterator(id3, kMap[i].tag2);
644         }
645 
646         if (it->done()) {
647             delete it;
648             continue;
649         }
650 
651         String8 s;
652         it->getString(&s);
653         delete it;
654 
655         AMediaFormat_setString(meta, kMap[i].key, s.c_str());
656     }
657 
658     size_t dataSize;
659     String8 mime;
660     const void *data = id3.getAlbumArt(&dataSize, &mime);
661 
662     if (data) {
663         AMediaFormat_setBuffer(meta, AMEDIAFORMAT_KEY_ALBUMART, data, dataSize);
664     }
665 
666     return AMEDIA_OK;
667 }
668 
CreateExtractor(CDataSource * source,void * meta)669 static CMediaExtractor* CreateExtractor(
670         CDataSource *source,
671         void *meta) {
672     Mp3Meta *metaData = static_cast<Mp3Meta *>(meta);
673     return wrap(new MP3Extractor(new DataSourceHelper(source), metaData));
674 }
675 
Sniff(CDataSource * source,float * confidence,void ** meta,FreeMetaFunc * freeMeta)676 static CreatorFunc Sniff(
677         CDataSource *source, float *confidence, void **meta,
678         FreeMetaFunc *freeMeta) {
679     off64_t pos = 0;
680     off64_t post_id3_pos;
681     uint32_t header;
682     uint8_t mpeg_header[5];
683     DataSourceHelper helper(source);
684     if (helper.readAt(0, mpeg_header, sizeof(mpeg_header)) < (ssize_t)sizeof(mpeg_header)) {
685         return NULL;
686     }
687 
688     if (!memcmp("\x00\x00\x01\xba", mpeg_header, 4) && (mpeg_header[4] >> 4) == 2) {
689         ALOGV("MPEG1PS container is not supported!");
690         return NULL;
691     }
692     if (!Resync(&helper, 0, &pos, &post_id3_pos, &header)) {
693         return NULL;
694     }
695 
696     Mp3Meta *mp3Meta = new Mp3Meta;
697     mp3Meta->pos = pos;
698     mp3Meta->header = header;
699     mp3Meta->post_id3_pos = post_id3_pos;
700     *meta = mp3Meta;
701     *freeMeta = ::free;
702 
703     *confidence = 0.2f;
704 
705     return CreateExtractor;
706 }
707 
708 static const char *extensions[] = {
709     "mp2",
710     "mp3",
711     "mpeg",
712     "mpg",
713     "mpga",
714     NULL
715 };
716 
717 extern "C" {
718 // This is the only symbol that needs to be exported
719 __attribute__ ((visibility ("default")))
GETEXTRACTORDEF()720 ExtractorDef GETEXTRACTORDEF() {
721     return {
722         EXTRACTORDEF_VERSION,
723         UUID("812a3f6c-c8cf-46de-b529-3774b14103d4"),
724         1, // version
725         "MP3 Extractor",
726         { .v3 = {Sniff, extensions} }
727     };
728 }
729 
730 } // extern "C"
731 
732 }  // namespace android
733