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