MP3Extractor.cpp revision b636abde14f2612ea236257846b9ab15d87d4623
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 "include/MP3Extractor.h"
22
23#include "include/avc_utils.h"
24#include "include/ID3.h"
25#include "include/VBRISeeker.h"
26#include "include/XINGSeeker.h"
27
28#include <media/stagefright/foundation/ADebug.h>
29#include <media/stagefright/foundation/AMessage.h>
30#include <media/stagefright/DataSource.h>
31#include <media/stagefright/MediaBuffer.h>
32#include <media/stagefright/MediaBufferGroup.h>
33#include <media/stagefright/MediaDefs.h>
34#include <media/stagefright/MediaErrors.h>
35#include <media/stagefright/MediaSource.h>
36#include <media/stagefright/MetaData.h>
37#include <media/stagefright/Utils.h>
38#include <utils/String8.h>
39
40namespace android {
41
42// Everything must match except for
43// protection, bitrate, padding, private bits, mode, mode extension,
44// copyright bit, original bit and emphasis.
45// Yes ... there are things that must indeed match...
46static const uint32_t kMask = 0xfffe0c00;
47
48static bool Resync(
49        const sp<DataSource> &source, uint32_t match_header,
50        off64_t *inout_pos, off64_t *post_id3_pos, uint32_t *out_header) {
51    if (post_id3_pos != NULL) {
52        *post_id3_pos = 0;
53    }
54
55    if (*inout_pos == 0) {
56        // Skip an optional ID3 header if syncing at the very beginning
57        // of the datasource.
58
59        for (;;) {
60            uint8_t id3header[10];
61            if (source->readAt(*inout_pos, id3header, sizeof(id3header))
62                    < (ssize_t)sizeof(id3header)) {
63                // If we can't even read these 10 bytes, we might as well bail
64                // out, even if there _were_ 10 bytes of valid mp3 audio data...
65                return false;
66            }
67
68            if (memcmp("ID3", id3header, 3)) {
69                break;
70            }
71
72            // Skip the ID3v2 header.
73
74            size_t len =
75                ((id3header[6] & 0x7f) << 21)
76                | ((id3header[7] & 0x7f) << 14)
77                | ((id3header[8] & 0x7f) << 7)
78                | (id3header[9] & 0x7f);
79
80            len += 10;
81
82            *inout_pos += len;
83
84            ALOGV("skipped ID3 tag, new starting offset is %lld (0x%016llx)",
85                 *inout_pos, *inout_pos);
86        }
87
88        if (post_id3_pos != NULL) {
89            *post_id3_pos = *inout_pos;
90        }
91    }
92
93    off64_t pos = *inout_pos;
94    bool valid = false;
95
96    const size_t kMaxReadBytes = 1024;
97    const size_t kMaxBytesChecked = 128 * 1024;
98    uint8_t buf[kMaxReadBytes];
99    ssize_t bytesToRead = kMaxReadBytes;
100    ssize_t totalBytesRead = 0;
101    ssize_t remainingBytes = 0;
102    bool reachEOS = false;
103    uint8_t *tmp = buf;
104
105    do {
106        if (pos >= *inout_pos + kMaxBytesChecked) {
107            // Don't scan forever.
108            ALOGV("giving up at offset %lld", pos);
109            break;
110        }
111
112        if (remainingBytes < 4) {
113            if (reachEOS) {
114                break;
115            } else {
116                memcpy(buf, tmp, remainingBytes);
117                bytesToRead = kMaxReadBytes - remainingBytes;
118
119                /*
120                 * The next read position should start from the end of
121                 * the last buffer, and thus should include the remaining
122                 * bytes in the buffer.
123                 */
124                totalBytesRead = source->readAt(pos + remainingBytes,
125                                                buf + remainingBytes,
126                                                bytesToRead);
127                if (totalBytesRead <= 0) {
128                    break;
129                }
130                reachEOS = (totalBytesRead != bytesToRead);
131                totalBytesRead += remainingBytes;
132                remainingBytes = totalBytesRead;
133                tmp = buf;
134                continue;
135            }
136        }
137
138        uint32_t header = U32_AT(tmp);
139
140        if (match_header != 0 && (header & kMask) != (match_header & kMask)) {
141            ++pos;
142            ++tmp;
143            --remainingBytes;
144            continue;
145        }
146
147        size_t frame_size;
148        int sample_rate, num_channels, bitrate;
149        if (!GetMPEGAudioFrameSize(
150                    header, &frame_size,
151                    &sample_rate, &num_channels, &bitrate)) {
152            ++pos;
153            ++tmp;
154            --remainingBytes;
155            continue;
156        }
157
158        ALOGV("found possible 1st frame at %lld (header = 0x%08x)", pos, header);
159
160        // We found what looks like a valid frame,
161        // now find its successors.
162
163        off64_t test_pos = pos + frame_size;
164
165        valid = true;
166        for (int j = 0; j < 3; ++j) {
167            uint8_t tmp[4];
168            if (source->readAt(test_pos, tmp, 4) < 4) {
169                valid = false;
170                break;
171            }
172
173            uint32_t test_header = U32_AT(tmp);
174
175            ALOGV("subsequent header is %08x", test_header);
176
177            if ((test_header & kMask) != (header & kMask)) {
178                valid = false;
179                break;
180            }
181
182            size_t test_frame_size;
183            if (!GetMPEGAudioFrameSize(
184                        test_header, &test_frame_size)) {
185                valid = false;
186                break;
187            }
188
189            ALOGV("found subsequent frame #%d at %lld", j + 2, test_pos);
190
191            test_pos += test_frame_size;
192        }
193
194        if (valid) {
195            *inout_pos = pos;
196
197            if (out_header != NULL) {
198                *out_header = header;
199            }
200        } else {
201            ALOGV("no dice, no valid sequence of frames found.");
202        }
203
204        ++pos;
205        ++tmp;
206        --remainingBytes;
207    } while (!valid);
208
209    return valid;
210}
211
212class MP3Source : public MediaSource {
213public:
214    MP3Source(
215            const sp<MetaData> &meta, const sp<DataSource> &source,
216            off64_t first_frame_pos, uint32_t fixed_header,
217            const sp<MP3Seeker> &seeker);
218
219    virtual status_t start(MetaData *params = NULL);
220    virtual status_t stop();
221
222    virtual sp<MetaData> getFormat();
223
224    virtual status_t read(
225            MediaBuffer **buffer, const ReadOptions *options = NULL);
226
227protected:
228    virtual ~MP3Source();
229
230private:
231    sp<MetaData> mMeta;
232    sp<DataSource> mDataSource;
233    off64_t mFirstFramePos;
234    uint32_t mFixedHeader;
235    off64_t mCurrentPos;
236    int64_t mCurrentTimeUs;
237    bool mStarted;
238    sp<MP3Seeker> mSeeker;
239    MediaBufferGroup *mGroup;
240
241    int64_t mBasisTimeUs;
242    int64_t mSamplesRead;
243
244    MP3Source(const MP3Source &);
245    MP3Source &operator=(const MP3Source &);
246};
247
248MP3Extractor::MP3Extractor(
249        const sp<DataSource> &source, const sp<AMessage> &meta)
250    : mInitCheck(NO_INIT),
251      mDataSource(source),
252      mFirstFramePos(-1),
253      mFixedHeader(0) {
254    off64_t pos = 0;
255    off64_t post_id3_pos;
256    uint32_t header;
257    bool success;
258
259    int64_t meta_offset;
260    uint32_t meta_header;
261    int64_t meta_post_id3_offset;
262    if (meta != NULL
263            && meta->findInt64("offset", &meta_offset)
264            && meta->findInt32("header", (int32_t *)&meta_header)
265            && meta->findInt64("post-id3-offset", &meta_post_id3_offset)) {
266        // The sniffer has already done all the hard work for us, simply
267        // accept its judgement.
268        pos = (off64_t)meta_offset;
269        header = meta_header;
270        post_id3_pos = (off64_t)meta_post_id3_offset;
271
272        success = true;
273    } else {
274        success = Resync(mDataSource, 0, &pos, &post_id3_pos, &header);
275    }
276
277    if (!success) {
278        // mInitCheck will remain NO_INIT
279        return;
280    }
281
282    mFirstFramePos = pos;
283    mFixedHeader = header;
284
285    size_t frame_size;
286    int sample_rate;
287    int num_channels;
288    int bitrate;
289    GetMPEGAudioFrameSize(
290            header, &frame_size, &sample_rate, &num_channels, &bitrate);
291
292    unsigned layer = 4 - ((header >> 17) & 3);
293
294    mMeta = new MetaData;
295
296    switch (layer) {
297        case 1:
298            mMeta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I);
299            break;
300        case 2:
301            mMeta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II);
302            break;
303        case 3:
304            mMeta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG);
305            break;
306        default:
307            TRESPASS();
308    }
309
310    mMeta->setInt32(kKeySampleRate, sample_rate);
311    mMeta->setInt32(kKeyBitRate, bitrate * 1000);
312    mMeta->setInt32(kKeyChannelCount, num_channels);
313
314    sp<XINGSeeker> seeker = XINGSeeker::CreateFromSource(mDataSource, mFirstFramePos);
315
316    if (seeker == NULL) {
317        mSeeker = VBRISeeker::CreateFromSource(mDataSource, post_id3_pos);
318    } else {
319        mSeeker = seeker;
320        int encd = seeker->getEncoderDelay();
321        int encp = seeker->getEncoderPadding();
322        if (encd != 0 || encp != 0) {
323            mMeta->setInt32(kKeyEncoderDelay, encd);
324            mMeta->setInt32(kKeyEncoderPadding, encp);
325        }
326    }
327
328    if (mSeeker != NULL) {
329        // While it is safe to send the XING/VBRI frame to the decoder, this will
330        // result in an extra 1152 samples being output. The real first frame to
331        // decode is after the XING/VBRI frame, so skip there.
332        mFirstFramePos += frame_size;
333    }
334
335    int64_t durationUs;
336
337    if (mSeeker == NULL || !mSeeker->getDuration(&durationUs)) {
338        off64_t fileSize;
339        if (mDataSource->getSize(&fileSize) == OK) {
340            durationUs = 8000LL * (fileSize - mFirstFramePos) / bitrate;
341        } else {
342            durationUs = -1;
343        }
344    }
345
346    if (durationUs >= 0) {
347        mMeta->setInt64(kKeyDuration, durationUs);
348    }
349
350    mInitCheck = OK;
351}
352
353size_t MP3Extractor::countTracks() {
354    return mInitCheck != OK ? 0 : 1;
355}
356
357sp<MediaSource> MP3Extractor::getTrack(size_t index) {
358    if (mInitCheck != OK || index != 0) {
359        return NULL;
360    }
361
362    return new MP3Source(
363            mMeta, mDataSource, mFirstFramePos, mFixedHeader,
364            mSeeker);
365}
366
367sp<MetaData> MP3Extractor::getTrackMetaData(size_t index, uint32_t flags) {
368    if (mInitCheck != OK || index != 0) {
369        return NULL;
370    }
371
372    return mMeta;
373}
374
375////////////////////////////////////////////////////////////////////////////////
376
377MP3Source::MP3Source(
378        const sp<MetaData> &meta, const sp<DataSource> &source,
379        off64_t first_frame_pos, uint32_t fixed_header,
380        const sp<MP3Seeker> &seeker)
381    : mMeta(meta),
382      mDataSource(source),
383      mFirstFramePos(first_frame_pos),
384      mFixedHeader(fixed_header),
385      mCurrentPos(0),
386      mCurrentTimeUs(0),
387      mStarted(false),
388      mSeeker(seeker),
389      mGroup(NULL),
390      mBasisTimeUs(0),
391      mSamplesRead(0) {
392}
393
394MP3Source::~MP3Source() {
395    if (mStarted) {
396        stop();
397    }
398}
399
400status_t MP3Source::start(MetaData *) {
401    CHECK(!mStarted);
402
403    mGroup = new MediaBufferGroup;
404
405    const size_t kMaxFrameSize = 32768;
406    mGroup->add_buffer(new MediaBuffer(kMaxFrameSize));
407
408    mCurrentPos = mFirstFramePos;
409    mCurrentTimeUs = 0;
410
411    mBasisTimeUs = mCurrentTimeUs;
412    mSamplesRead = 0;
413
414    mStarted = true;
415
416    return OK;
417}
418
419status_t MP3Source::stop() {
420    CHECK(mStarted);
421
422    delete mGroup;
423    mGroup = NULL;
424
425    mStarted = false;
426
427    return OK;
428}
429
430sp<MetaData> MP3Source::getFormat() {
431    return mMeta;
432}
433
434status_t MP3Source::read(
435        MediaBuffer **out, const ReadOptions *options) {
436    *out = NULL;
437
438    int64_t seekTimeUs;
439    ReadOptions::SeekMode mode;
440    bool seekCBR = false;
441
442    if (options != NULL && options->getSeekTo(&seekTimeUs, &mode)) {
443        int64_t actualSeekTimeUs = seekTimeUs;
444        if (mSeeker == NULL
445                || !mSeeker->getOffsetForTime(&actualSeekTimeUs, &mCurrentPos)) {
446            int32_t bitrate;
447            if (!mMeta->findInt32(kKeyBitRate, &bitrate)) {
448                // bitrate is in bits/sec.
449                ALOGI("no bitrate");
450
451                return ERROR_UNSUPPORTED;
452            }
453
454            mCurrentTimeUs = seekTimeUs;
455            mCurrentPos = mFirstFramePos + seekTimeUs * bitrate / 8000000;
456            seekCBR = true;
457        } else {
458            mCurrentTimeUs = actualSeekTimeUs;
459        }
460
461        mBasisTimeUs = mCurrentTimeUs;
462        mSamplesRead = 0;
463    }
464
465    MediaBuffer *buffer;
466    status_t err = mGroup->acquire_buffer(&buffer);
467    if (err != OK) {
468        return err;
469    }
470
471    size_t frame_size;
472    int bitrate;
473    int num_samples;
474    int sample_rate;
475    for (;;) {
476        ssize_t n = mDataSource->readAt(mCurrentPos, buffer->data(), 4);
477        if (n < 4) {
478            buffer->release();
479            buffer = NULL;
480
481            return ERROR_END_OF_STREAM;
482        }
483
484        uint32_t header = U32_AT((const uint8_t *)buffer->data());
485
486        if ((header & kMask) == (mFixedHeader & kMask)
487            && GetMPEGAudioFrameSize(
488                header, &frame_size, &sample_rate, NULL,
489                &bitrate, &num_samples)) {
490
491            // re-calculate mCurrentTimeUs because we might have called Resync()
492            if (seekCBR) {
493                mCurrentTimeUs = (mCurrentPos - mFirstFramePos) * 8000 / bitrate;
494                mBasisTimeUs = mCurrentTimeUs;
495            }
496
497            break;
498        }
499
500        // Lost sync.
501        ALOGV("lost sync! header = 0x%08x, old header = 0x%08x\n", header, mFixedHeader);
502
503        off64_t pos = mCurrentPos;
504        if (!Resync(mDataSource, mFixedHeader, &pos, NULL, NULL)) {
505            ALOGE("Unable to resync. Signalling end of stream.");
506
507            buffer->release();
508            buffer = NULL;
509
510            return ERROR_END_OF_STREAM;
511        }
512
513        mCurrentPos = pos;
514
515        // Try again with the new position.
516    }
517
518    CHECK(frame_size <= buffer->size());
519
520    ssize_t n = mDataSource->readAt(mCurrentPos, buffer->data(), frame_size);
521    if (n < (ssize_t)frame_size) {
522        buffer->release();
523        buffer = NULL;
524
525        return ERROR_END_OF_STREAM;
526    }
527
528    buffer->set_range(0, frame_size);
529
530    buffer->meta_data()->setInt64(kKeyTime, mCurrentTimeUs);
531    buffer->meta_data()->setInt32(kKeyIsSyncFrame, 1);
532
533    mCurrentPos += frame_size;
534
535    mSamplesRead += num_samples;
536    mCurrentTimeUs = mBasisTimeUs + ((mSamplesRead * 1000000) / sample_rate);
537
538    *out = buffer;
539
540    return OK;
541}
542
543sp<MetaData> MP3Extractor::getMetaData() {
544    sp<MetaData> meta = new MetaData;
545
546    if (mInitCheck != OK) {
547        return meta;
548    }
549
550    meta->setCString(kKeyMIMEType, "audio/mpeg");
551
552    ID3 id3(mDataSource);
553
554    if (!id3.isValid()) {
555        return meta;
556    }
557
558    ID3::Iterator *com = new ID3::Iterator(id3, "COM");
559    if (com->done()) {
560        delete com;
561        com = new ID3::Iterator(id3, "COMM");
562    }
563    while(!com->done()) {
564        String8 commentdesc;
565        String8 commentvalue;
566        com->getString(&commentdesc, &commentvalue);
567        const char * desc = commentdesc.string();
568        const char * value = commentvalue.string();
569
570        // first 3 characters are the language, which we don't care about
571        if(strlen(desc) > 3 && strcmp(desc + 3, "iTunSMPB") == 0) {
572
573            int32_t delay, padding;
574            if (sscanf(value, " %*x %x %x %*x", &delay, &padding) == 2) {
575                mMeta->setInt32(kKeyEncoderDelay, delay);
576                mMeta->setInt32(kKeyEncoderPadding, padding);
577            }
578            break;
579        }
580        com->next();
581    }
582    delete com;
583    com = NULL;
584
585    struct Map {
586        int key;
587        const char *tag1;
588        const char *tag2;
589    };
590    static const Map kMap[] = {
591        { kKeyAlbum, "TALB", "TAL" },
592        { kKeyArtist, "TPE1", "TP1" },
593        { kKeyAlbumArtist, "TPE2", "TP2" },
594        { kKeyComposer, "TCOM", "TCM" },
595        { kKeyGenre, "TCON", "TCO" },
596        { kKeyTitle, "TIT2", "TT2" },
597        { kKeyYear, "TYE", "TYER" },
598        { kKeyAuthor, "TXT", "TEXT" },
599        { kKeyCDTrackNumber, "TRK", "TRCK" },
600        { kKeyDiscNumber, "TPA", "TPOS" },
601        { kKeyCompilation, "TCP", "TCMP" },
602    };
603    static const size_t kNumMapEntries = sizeof(kMap) / sizeof(kMap[0]);
604
605    for (size_t i = 0; i < kNumMapEntries; ++i) {
606        ID3::Iterator *it = new ID3::Iterator(id3, kMap[i].tag1);
607        if (it->done()) {
608            delete it;
609            it = new ID3::Iterator(id3, kMap[i].tag2);
610        }
611
612        if (it->done()) {
613            delete it;
614            continue;
615        }
616
617        String8 s;
618        it->getString(&s);
619        delete it;
620
621        meta->setCString(kMap[i].key, s);
622    }
623
624    size_t dataSize;
625    String8 mime;
626    const void *data = id3.getAlbumArt(&dataSize, &mime);
627
628    if (data) {
629        meta->setData(kKeyAlbumArt, MetaData::TYPE_NONE, data, dataSize);
630        meta->setCString(kKeyAlbumArtMIME, mime.string());
631    }
632
633    return meta;
634}
635
636bool SniffMP3(
637        const sp<DataSource> &source, String8 *mimeType,
638        float *confidence, sp<AMessage> *meta) {
639    off64_t pos = 0;
640    off64_t post_id3_pos;
641    uint32_t header;
642    if (!Resync(source, 0, &pos, &post_id3_pos, &header)) {
643        return false;
644    }
645
646    *meta = new AMessage;
647    (*meta)->setInt64("offset", pos);
648    (*meta)->setInt32("header", header);
649    (*meta)->setInt64("post-id3-offset", post_id3_pos);
650
651    *mimeType = MEDIA_MIMETYPE_AUDIO_MPEG;
652    *confidence = 0.2f;
653
654    return true;
655}
656
657}  // namespace android
658