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;
231     DataSourceHelper *mDataSource;
232     off64_t mFirstFramePos;
233     uint32_t mFixedHeader;
234     off64_t mCurrentPos;
235     int64_t mCurrentTimeUs;
236     bool mStarted;
237     MP3Seeker *mSeeker;
238 
239     int64_t mBasisTimeUs;
240     int64_t mSamplesRead;
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     : mInitCheck(NO_INIT),
255       mDataSource(source),
256       mFirstFramePos(-1),
257       mFixedHeader(0),
258       mSeeker(NULL) {
259 
260     off64_t pos = 0;
261     off64_t post_id3_pos;
262     uint32_t header;
263     bool success;
264 
265     if (meta != NULL) {
266         // The sniffer has already done all the hard work for us, simply
267         // accept its judgement.
268         pos = meta->pos;
269         header = meta->header;
270         post_id3_pos = meta->post_id3_pos;
271         success = true;
272     } else {
273         success = Resync(mDataSource, 0, &pos, &post_id3_pos, &header);
274     }
275 
276     if (!success) {
277         // mInitCheck will remain NO_INIT
278         return;
279     }
280 
281     mFirstFramePos = pos;
282     mFixedHeader = header;
283     XINGSeeker *seeker = XINGSeeker::CreateFromSource(mDataSource, mFirstFramePos);
284 
285     mMeta = AMediaFormat_new();
286     if (seeker == NULL) {
287         mSeeker = VBRISeeker::CreateFromSource(mDataSource, post_id3_pos);
288     } else {
289         mSeeker = seeker;
290         int encd = seeker->getEncoderDelay();
291         int encp = seeker->getEncoderPadding();
292         if (encd != 0 || encp != 0) {
293             AMediaFormat_setInt32(mMeta, AMEDIAFORMAT_KEY_ENCODER_DELAY, encd);
294             AMediaFormat_setInt32(mMeta, AMEDIAFORMAT_KEY_ENCODER_PADDING, encp);
295         }
296     }
297 
298     if (mSeeker != NULL) {
299         // While it is safe to send the XING/VBRI frame to the decoder, this will
300         // result in an extra 1152 samples being output. In addition, the bitrate
301         // of the Xing header might not match the rest of the file, which could
302         // lead to problems when seeking. The real first frame to decode is after
303         // the XING/VBRI frame, so skip there.
304         size_t frame_size;
305         int sample_rate;
306         int num_channels;
307         int bitrate;
308         GetMPEGAudioFrameSize(
309                 header, &frame_size, &sample_rate, &num_channels, &bitrate);
310         pos += frame_size;
311         if (!Resync(mDataSource, 0, &pos, &post_id3_pos, &header)) {
312             // mInitCheck will remain NO_INIT
313             return;
314         }
315         mFirstFramePos = pos;
316         mFixedHeader = header;
317     }
318 
319     size_t frame_size;
320     int sample_rate;
321     int num_channels;
322     int bitrate;
323     GetMPEGAudioFrameSize(
324             header, &frame_size, &sample_rate, &num_channels, &bitrate);
325 
326     unsigned layer = 4 - ((header >> 17) & 3);
327 
328     switch (layer) {
329         case 1:
330             AMediaFormat_setString(mMeta,
331                     AMEDIAFORMAT_KEY_MIME, MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I);
332             break;
333         case 2:
334             AMediaFormat_setString(mMeta,
335                     AMEDIAFORMAT_KEY_MIME, MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II);
336             break;
337         case 3:
338             AMediaFormat_setString(mMeta, AMEDIAFORMAT_KEY_MIME, MEDIA_MIMETYPE_AUDIO_MPEG);
339             break;
340         default:
341             TRESPASS();
342     }
343 
344     AMediaFormat_setInt32(mMeta, AMEDIAFORMAT_KEY_SAMPLE_RATE, sample_rate);
345     AMediaFormat_setInt32(mMeta, AMEDIAFORMAT_KEY_BIT_RATE, bitrate * 1000);
346     AMediaFormat_setInt32(mMeta, AMEDIAFORMAT_KEY_CHANNEL_COUNT, num_channels);
347 
348     int64_t durationUs;
349 
350     if (mSeeker == NULL || !mSeeker->getDuration(&durationUs)) {
351         off64_t fileSize;
352         if (mDataSource->getSize(&fileSize) == OK) {
353             off64_t dataLength = fileSize - mFirstFramePos;
354             if (dataLength > INT64_MAX / 8000LL) {
355                 // duration would overflow
356                 durationUs = INT64_MAX;
357             } else {
358                 durationUs = 8000LL * dataLength / bitrate;
359             }
360         } else {
361             durationUs = -1;
362         }
363     }
364 
365     if (durationUs >= 0) {
366         AMediaFormat_setInt64(mMeta, AMEDIAFORMAT_KEY_DURATION, durationUs);
367     }
368 
369     mInitCheck = OK;
370 
371     // Get iTunes-style gapless info if present.
372     // When getting the id3 tag, skip the V1 tags to prevent the source cache
373     // from being iterated to the end of the file.
374     DataSourceHelper helper(mDataSource);
375     ID3 id3(&helper, true);
376     if (id3.isValid()) {
377         ID3::Iterator *com = new ID3::Iterator(id3, "COM");
378         if (com->done()) {
379             delete com;
380             com = new ID3::Iterator(id3, "COMM");
381         }
382         while(!com->done()) {
383             String8 commentdesc;
384             String8 commentvalue;
385             com->getString(&commentdesc, &commentvalue);
386             const char * desc = commentdesc.string();
387             const char * value = commentvalue.string();
388 
389             // first 3 characters are the language, which we don't care about
390             if(strlen(desc) > 3 && strcmp(desc + 3, "iTunSMPB") == 0) {
391 
392                 int32_t delay, padding;
393                 if (sscanf(value, " %*x %x %x %*x", &delay, &padding) == 2) {
394                     AMediaFormat_setInt32(mMeta, AMEDIAFORMAT_KEY_ENCODER_DELAY, delay);
395                     AMediaFormat_setInt32(mMeta, AMEDIAFORMAT_KEY_ENCODER_PADDING, padding);
396                 }
397                 break;
398             }
399             com->next();
400         }
401         delete com;
402         com = NULL;
403     }
404 }
405 
~MP3Extractor()406 MP3Extractor::~MP3Extractor() {
407     delete mSeeker;
408     delete mDataSource;
409     AMediaFormat_delete(mMeta);
410 }
411 
countTracks()412 size_t MP3Extractor::countTracks() {
413     return mInitCheck != OK ? 0 : 1;
414 }
415 
getTrack(size_t index)416 MediaTrackHelper *MP3Extractor::getTrack(size_t index) {
417     if (mInitCheck != OK || index != 0) {
418         return NULL;
419     }
420 
421     return new MP3Source(
422             mMeta, mDataSource, mFirstFramePos, mFixedHeader,
423             mSeeker);
424 }
425 
getTrackMetaData(AMediaFormat * meta,size_t index,uint32_t)426 media_status_t MP3Extractor::getTrackMetaData(
427         AMediaFormat *meta,
428         size_t index, uint32_t /* flags */) {
429     if (mInitCheck != OK || index != 0) {
430         return AMEDIA_ERROR_UNKNOWN;
431     }
432     AMediaFormat_copy(meta, mMeta);
433     return AMEDIA_OK;
434 }
435 
436 ////////////////////////////////////////////////////////////////////////////////
437 
438 // The theoretical maximum frame size for an MPEG audio stream should occur
439 // while playing a Layer 2, MPEGv2.5 audio stream at 160kbps (with padding).
440 // The size of this frame should be...
441 // ((1152 samples/frame * 160000 bits/sec) /
442 //  (8000 samples/sec * 8 bits/byte)) + 1 padding byte/frame = 2881 bytes/frame.
443 // Set our max frame size to the nearest power of 2 above this size (aka, 4kB)
444 const size_t MP3Source::kMaxFrameSize = (1 << 12); /* 4096 bytes */
MP3Source(AMediaFormat * meta,DataSourceHelper * source,off64_t first_frame_pos,uint32_t fixed_header,MP3Seeker * seeker)445 MP3Source::MP3Source(
446         AMediaFormat *meta, DataSourceHelper *source,
447         off64_t first_frame_pos, uint32_t fixed_header,
448         MP3Seeker *seeker)
449     : mMeta(meta),
450       mDataSource(source),
451       mFirstFramePos(first_frame_pos),
452       mFixedHeader(fixed_header),
453       mCurrentPos(0),
454       mCurrentTimeUs(0),
455       mStarted(false),
456       mSeeker(seeker),
457       mBasisTimeUs(0),
458       mSamplesRead(0) {
459 }
460 
~MP3Source()461 MP3Source::~MP3Source() {
462     if (mStarted) {
463         stop();
464     }
465 }
466 
start()467 media_status_t MP3Source::start() {
468     CHECK(!mStarted);
469 
470     mBufferGroup->add_buffer(kMaxFrameSize);
471 
472     mCurrentPos = mFirstFramePos;
473     mCurrentTimeUs = 0;
474 
475     mBasisTimeUs = mCurrentTimeUs;
476     mSamplesRead = 0;
477 
478     mStarted = true;
479 
480     return AMEDIA_OK;
481 }
482 
stop()483 media_status_t MP3Source::stop() {
484     CHECK(mStarted);
485 
486     mStarted = false;
487 
488     return AMEDIA_OK;
489 }
490 
getFormat(AMediaFormat * meta)491 media_status_t MP3Source::getFormat(AMediaFormat *meta) {
492     return AMediaFormat_copy(meta, mMeta);
493 }
494 
read(MediaBufferHelper ** out,const ReadOptions * options)495 media_status_t MP3Source::read(
496         MediaBufferHelper **out, const ReadOptions *options) {
497     *out = NULL;
498 
499     int64_t seekTimeUs;
500     ReadOptions::SeekMode mode;
501     bool seekCBR = false;
502 
503     if (options != NULL && options->getSeekTo(&seekTimeUs, &mode)) {
504         int64_t actualSeekTimeUs = seekTimeUs;
505         if (mSeeker == NULL
506                 || !mSeeker->getOffsetForTime(&actualSeekTimeUs, &mCurrentPos)) {
507             int32_t bitrate;
508             if (!AMediaFormat_getInt32(mMeta, AMEDIAFORMAT_KEY_BIT_RATE, &bitrate)) {
509                 // bitrate is in bits/sec.
510                 ALOGI("no bitrate");
511 
512                 return AMEDIA_ERROR_UNSUPPORTED;
513             }
514 
515             mCurrentTimeUs = seekTimeUs;
516             mCurrentPos = mFirstFramePos + seekTimeUs * bitrate / 8000000;
517             seekCBR = true;
518         } else {
519             mCurrentTimeUs = actualSeekTimeUs;
520         }
521 
522         mBasisTimeUs = mCurrentTimeUs;
523         mSamplesRead = 0;
524     }
525 
526     MediaBufferHelper *buffer;
527     status_t err = mBufferGroup->acquire_buffer(&buffer);
528     if (err != OK) {
529         return AMEDIA_ERROR_UNKNOWN;
530     }
531 
532     size_t frame_size;
533     int bitrate;
534     int num_samples;
535     int sample_rate;
536     for (;;) {
537         ssize_t n = mDataSource->readAt(mCurrentPos, buffer->data(), 4);
538         if (n < 4) {
539             buffer->release();
540             buffer = NULL;
541 
542             return ((n < 0 && n != ERROR_END_OF_STREAM) ?
543                     AMEDIA_ERROR_UNKNOWN : AMEDIA_ERROR_END_OF_STREAM);
544         }
545 
546         uint32_t header = U32_AT((const uint8_t *)buffer->data());
547 
548         if ((header & kMask) == (mFixedHeader & kMask)
549             && GetMPEGAudioFrameSize(
550                 header, &frame_size, &sample_rate, NULL,
551                 &bitrate, &num_samples)) {
552 
553             // re-calculate mCurrentTimeUs because we might have called Resync()
554             if (seekCBR) {
555                 mCurrentTimeUs = (mCurrentPos - mFirstFramePos) * 8000 / bitrate;
556                 mBasisTimeUs = mCurrentTimeUs;
557             }
558 
559             break;
560         }
561 
562         // Lost sync.
563         ALOGV("lost sync! header = 0x%08x, old header = 0x%08x\n", header, mFixedHeader);
564 
565         off64_t pos = mCurrentPos;
566         if (!Resync(mDataSource, mFixedHeader, &pos, NULL, NULL)) {
567             ALOGE("Unable to resync. Signalling end of stream.");
568 
569             buffer->release();
570             buffer = NULL;
571 
572             return AMEDIA_ERROR_END_OF_STREAM;
573         }
574 
575         mCurrentPos = pos;
576 
577         // Try again with the new position.
578     }
579 
580     CHECK(frame_size <= buffer->size());
581 
582     ssize_t n = mDataSource->readAt(mCurrentPos, buffer->data(), frame_size);
583     if (n < (ssize_t)frame_size) {
584         buffer->release();
585         buffer = NULL;
586 
587         return ((n < 0 && n != ERROR_END_OF_STREAM) ?
588                 AMEDIA_ERROR_UNKNOWN : AMEDIA_ERROR_END_OF_STREAM);
589     }
590 
591     buffer->set_range(0, frame_size);
592 
593     AMediaFormat *meta = buffer->meta_data();
594     AMediaFormat_setInt64(meta, AMEDIAFORMAT_KEY_TIME_US, mCurrentTimeUs);
595     AMediaFormat_setInt32(meta, AMEDIAFORMAT_KEY_IS_SYNC_FRAME, 1);
596 
597     mCurrentPos += frame_size;
598 
599     mSamplesRead += num_samples;
600     mCurrentTimeUs = mBasisTimeUs + ((mSamplesRead * 1000000) / sample_rate);
601 
602     *out = buffer;
603 
604     return AMEDIA_OK;
605 }
606 
getMetaData(AMediaFormat * meta)607 media_status_t MP3Extractor::getMetaData(AMediaFormat *meta) {
608     AMediaFormat_clear(meta);
609     if (mInitCheck != OK) {
610         return AMEDIA_ERROR_UNKNOWN;
611     }
612     AMediaFormat_setString(meta, AMEDIAFORMAT_KEY_MIME, MEDIA_MIMETYPE_AUDIO_MPEG);
613 
614     DataSourceHelper helper(mDataSource);
615     ID3 id3(&helper);
616 
617     if (!id3.isValid()) {
618         return AMEDIA_OK;
619     }
620 
621     struct Map {
622         const char *key;
623         const char *tag1;
624         const char *tag2;
625     };
626     static const Map kMap[] = {
627         { AMEDIAFORMAT_KEY_ALBUM, "TALB", "TAL" },
628         { AMEDIAFORMAT_KEY_ARTIST, "TPE1", "TP1" },
629         { AMEDIAFORMAT_KEY_ALBUMARTIST, "TPE2", "TP2" },
630         { AMEDIAFORMAT_KEY_COMPOSER, "TCOM", "TCM" },
631         { AMEDIAFORMAT_KEY_GENRE, "TCON", "TCO" },
632         { AMEDIAFORMAT_KEY_TITLE, "TIT2", "TT2" },
633         { AMEDIAFORMAT_KEY_YEAR, "TYE", "TYER" },
634         { AMEDIAFORMAT_KEY_AUTHOR, "TXT", "TEXT" },
635         { AMEDIAFORMAT_KEY_CDTRACKNUMBER, "TRK", "TRCK" },
636         { AMEDIAFORMAT_KEY_DISCNUMBER, "TPA", "TPOS" },
637         { AMEDIAFORMAT_KEY_COMPILATION, "TCP", "TCMP" },
638     };
639     static const size_t kNumMapEntries = sizeof(kMap) / sizeof(kMap[0]);
640 
641     for (size_t i = 0; i < kNumMapEntries; ++i) {
642         ID3::Iterator *it = new ID3::Iterator(id3, kMap[i].tag1);
643         if (it->done()) {
644             delete it;
645             it = new ID3::Iterator(id3, kMap[i].tag2);
646         }
647 
648         if (it->done()) {
649             delete it;
650             continue;
651         }
652 
653         String8 s;
654         it->getString(&s);
655         delete it;
656 
657         AMediaFormat_setString(meta, kMap[i].key, s.string());
658     }
659 
660     size_t dataSize;
661     String8 mime;
662     const void *data = id3.getAlbumArt(&dataSize, &mime);
663 
664     if (data) {
665         AMediaFormat_setBuffer(meta, AMEDIAFORMAT_KEY_ALBUMART, data, dataSize);
666     }
667 
668     return AMEDIA_OK;
669 }
670 
CreateExtractor(CDataSource * source,void * meta)671 static CMediaExtractor* CreateExtractor(
672         CDataSource *source,
673         void *meta) {
674     Mp3Meta *metaData = static_cast<Mp3Meta *>(meta);
675     return wrap(new MP3Extractor(new DataSourceHelper(source), metaData));
676 }
677 
Sniff(CDataSource * source,float * confidence,void ** meta,FreeMetaFunc * freeMeta)678 static CreatorFunc Sniff(
679         CDataSource *source, float *confidence, void **meta,
680         FreeMetaFunc *freeMeta) {
681     off64_t pos = 0;
682     off64_t post_id3_pos;
683     uint32_t header;
684     uint8_t mpeg_header[5];
685     DataSourceHelper helper(source);
686     if (helper.readAt(0, mpeg_header, sizeof(mpeg_header)) < (ssize_t)sizeof(mpeg_header)) {
687         return NULL;
688     }
689 
690     if (!memcmp("\x00\x00\x01\xba", mpeg_header, 4) && (mpeg_header[4] >> 4) == 2) {
691         ALOGV("MPEG1PS container is not supported!");
692         return NULL;
693     }
694     if (!Resync(&helper, 0, &pos, &post_id3_pos, &header)) {
695         return NULL;
696     }
697 
698     Mp3Meta *mp3Meta = new Mp3Meta;
699     mp3Meta->pos = pos;
700     mp3Meta->header = header;
701     mp3Meta->post_id3_pos = post_id3_pos;
702     *meta = mp3Meta;
703     *freeMeta = ::free;
704 
705     *confidence = 0.2f;
706 
707     return CreateExtractor;
708 }
709 
710 static const char *extensions[] = {
711     "mp2",
712     "mp3",
713     "mpeg",
714     "mpg",
715     "mpga",
716     NULL
717 };
718 
719 extern "C" {
720 // This is the only symbol that needs to be exported
721 __attribute__ ((visibility ("default")))
GETEXTRACTORDEF()722 ExtractorDef GETEXTRACTORDEF() {
723     return {
724         EXTRACTORDEF_VERSION,
725         UUID("812a3f6c-c8cf-46de-b529-3774b14103d4"),
726         1, // version
727         "MP3 Extractor",
728         { .v3 = {Sniff, extensions} }
729     };
730 }
731 
732 } // extern "C"
733 
734 }  // namespace android
735