MediaPlayerService.cpp revision b49676a55e7dce9710e1a10749a26997513c5ceb
1/* 2** 3** Copyright 2008, The Android Open Source Project 4** 5** Licensed under the Apache License, Version 2.0 (the "License"); 6** you may not use this file except in compliance with the License. 7** You may obtain a copy of the License at 8** 9** http://www.apache.org/licenses/LICENSE-2.0 10** 11** Unless required by applicable law or agreed to in writing, software 12** distributed under the License is distributed on an "AS IS" BASIS, 13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14** See the License for the specific language governing permissions and 15** limitations under the License. 16*/ 17 18// Proxy for media player implementations 19 20//#define LOG_NDEBUG 0 21#define LOG_TAG "MediaPlayerService" 22#include <utils/Log.h> 23 24#include <sys/types.h> 25#include <sys/stat.h> 26#include <dirent.h> 27#include <unistd.h> 28 29#include <string.h> 30 31#include <cutils/atomic.h> 32#include <cutils/properties.h> // for property_get 33 34#include <utils/misc.h> 35 36#include <android_runtime/ActivityManager.h> 37 38#include <binder/IPCThreadState.h> 39#include <binder/IServiceManager.h> 40#include <binder/MemoryHeapBase.h> 41#include <binder/MemoryBase.h> 42#include <utils/Errors.h> // for status_t 43#include <utils/String8.h> 44#include <utils/SystemClock.h> 45#include <utils/Vector.h> 46#include <cutils/properties.h> 47 48#include <media/MediaPlayerInterface.h> 49#include <media/mediarecorder.h> 50#include <media/MediaMetadataRetrieverInterface.h> 51#include <media/Metadata.h> 52#include <media/AudioTrack.h> 53 54#include "MediaRecorderClient.h" 55#include "MediaPlayerService.h" 56#include "MetadataRetrieverClient.h" 57 58#include "MidiFile.h" 59#include "VorbisPlayer.h" 60#include <media/PVPlayer.h> 61#include "TestPlayerStub.h" 62#include "StagefrightPlayer.h" 63 64#include <OMX.h> 65 66/* desktop Linux needs a little help with gettid() */ 67#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS) 68#define __KERNEL__ 69# include <linux/unistd.h> 70#ifdef _syscall0 71_syscall0(pid_t,gettid) 72#else 73pid_t gettid() { return syscall(__NR_gettid);} 74#endif 75#undef __KERNEL__ 76#endif 77 78namespace { 79using android::media::Metadata; 80using android::status_t; 81using android::OK; 82using android::BAD_VALUE; 83using android::NOT_ENOUGH_DATA; 84using android::Parcel; 85 86// Max number of entries in the filter. 87const int kMaxFilterSize = 64; // I pulled that out of thin air. 88 89// FIXME: Move all the metadata related function in the Metadata.cpp 90 91 92// Unmarshall a filter from a Parcel. 93// Filter format in a parcel: 94// 95// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 96// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 97// | number of entries (n) | 98// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 99// | metadata type 1 | 100// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 101// | metadata type 2 | 102// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 103// .... 104// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 105// | metadata type n | 106// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 107// 108// @param p Parcel that should start with a filter. 109// @param[out] filter On exit contains the list of metadata type to be 110// filtered. 111// @param[out] status On exit contains the status code to be returned. 112// @return true if the parcel starts with a valid filter. 113bool unmarshallFilter(const Parcel& p, 114 Metadata::Filter *filter, 115 status_t *status) 116{ 117 int32_t val; 118 if (p.readInt32(&val) != OK) 119 { 120 LOGE("Failed to read filter's length"); 121 *status = NOT_ENOUGH_DATA; 122 return false; 123 } 124 125 if( val > kMaxFilterSize || val < 0) 126 { 127 LOGE("Invalid filter len %d", val); 128 *status = BAD_VALUE; 129 return false; 130 } 131 132 const size_t num = val; 133 134 filter->clear(); 135 filter->setCapacity(num); 136 137 size_t size = num * sizeof(Metadata::Type); 138 139 140 if (p.dataAvail() < size) 141 { 142 LOGE("Filter too short expected %d but got %d", size, p.dataAvail()); 143 *status = NOT_ENOUGH_DATA; 144 return false; 145 } 146 147 const Metadata::Type *data = 148 static_cast<const Metadata::Type*>(p.readInplace(size)); 149 150 if (NULL == data) 151 { 152 LOGE("Filter had no data"); 153 *status = BAD_VALUE; 154 return false; 155 } 156 157 // TODO: The stl impl of vector would be more efficient here 158 // because it degenerates into a memcpy on pod types. Try to 159 // replace later or use stl::set. 160 for (size_t i = 0; i < num; ++i) 161 { 162 filter->add(*data); 163 ++data; 164 } 165 *status = OK; 166 return true; 167} 168 169// @param filter Of metadata type. 170// @param val To be searched. 171// @return true if a match was found. 172bool findMetadata(const Metadata::Filter& filter, const int32_t val) 173{ 174 // Deal with empty and ANY right away 175 if (filter.isEmpty()) return false; 176 if (filter[0] == Metadata::kAny) return true; 177 178 return filter.indexOf(val) >= 0; 179} 180 181} // anonymous namespace 182 183 184namespace android { 185 186// TODO: Temp hack until we can register players 187typedef struct { 188 const char *extension; 189 const player_type playertype; 190} extmap; 191extmap FILE_EXTS [] = { 192 {".mid", SONIVOX_PLAYER}, 193 {".midi", SONIVOX_PLAYER}, 194 {".smf", SONIVOX_PLAYER}, 195 {".xmf", SONIVOX_PLAYER}, 196 {".imy", SONIVOX_PLAYER}, 197 {".rtttl", SONIVOX_PLAYER}, 198 {".rtx", SONIVOX_PLAYER}, 199 {".ota", SONIVOX_PLAYER}, 200 {".ogg", VORBIS_PLAYER}, 201 {".oga", VORBIS_PLAYER}, 202#ifndef NO_OPENCORE 203 {".wma", PV_PLAYER}, 204 {".wmv", PV_PLAYER}, 205 {".asf", PV_PLAYER}, 206#endif 207}; 208 209// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround 210/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4; 211/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false; 212 213void MediaPlayerService::instantiate() { 214 defaultServiceManager()->addService( 215 String16("media.player"), new MediaPlayerService()); 216} 217 218MediaPlayerService::MediaPlayerService() 219{ 220 LOGV("MediaPlayerService created"); 221 mNextConnId = 1; 222} 223 224MediaPlayerService::~MediaPlayerService() 225{ 226 LOGV("MediaPlayerService destroyed"); 227} 228 229sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid) 230{ 231#ifndef NO_OPENCORE 232 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid); 233 wp<MediaRecorderClient> w = recorder; 234 Mutex::Autolock lock(mLock); 235 mMediaRecorderClients.add(w); 236#else 237 sp<MediaRecorderClient> recorder = NULL; 238#endif 239 LOGV("Create new media recorder client from pid %d", pid); 240 return recorder; 241} 242 243void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client) 244{ 245 Mutex::Autolock lock(mLock); 246 mMediaRecorderClients.remove(client); 247 LOGV("Delete media recorder client"); 248} 249 250sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid) 251{ 252 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid); 253 LOGV("Create new media retriever from pid %d", pid); 254 return retriever; 255} 256 257sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client, const char* url) 258{ 259 int32_t connId = android_atomic_inc(&mNextConnId); 260 sp<Client> c = new Client(this, pid, connId, client); 261 LOGV("Create new client(%d) from pid %d, url=%s, connId=%d", connId, pid, url, connId); 262 if (NO_ERROR != c->setDataSource(url)) 263 { 264 c.clear(); 265 return c; 266 } 267 wp<Client> w = c; 268 Mutex::Autolock lock(mLock); 269 mClients.add(w); 270 return c; 271} 272 273sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client, 274 int fd, int64_t offset, int64_t length) 275{ 276 int32_t connId = android_atomic_inc(&mNextConnId); 277 sp<Client> c = new Client(this, pid, connId, client); 278 LOGV("Create new client(%d) from pid %d, fd=%d, offset=%lld, length=%lld", 279 connId, pid, fd, offset, length); 280 if (NO_ERROR != c->setDataSource(fd, offset, length)) { 281 c.clear(); 282 } else { 283 wp<Client> w = c; 284 Mutex::Autolock lock(mLock); 285 mClients.add(w); 286 } 287 ::close(fd); 288 return c; 289} 290 291sp<IOMX> MediaPlayerService::getOMX() { 292 Mutex::Autolock autoLock(mLock); 293 294 if (mOMX.get() == NULL) { 295 mOMX = new OMX; 296 } 297 298 return mOMX; 299} 300 301status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const 302{ 303 const size_t SIZE = 256; 304 char buffer[SIZE]; 305 String8 result; 306 307 result.append(" AudioCache\n"); 308 if (mHeap != 0) { 309 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n", 310 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice()); 311 result.append(buffer); 312 } 313 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n", 314 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount); 315 result.append(buffer); 316 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n", 317 mSampleRate, mSize, mError, mCommandComplete?"true":"false"); 318 result.append(buffer); 319 ::write(fd, result.string(), result.size()); 320 return NO_ERROR; 321} 322 323status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const 324{ 325 const size_t SIZE = 256; 326 char buffer[SIZE]; 327 String8 result; 328 329 result.append(" AudioOutput\n"); 330 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", 331 mStreamType, mLeftVolume, mRightVolume); 332 result.append(buffer); 333 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n", 334 mMsecsPerFrame, mLatency); 335 result.append(buffer); 336 ::write(fd, result.string(), result.size()); 337 if (mTrack != 0) { 338 mTrack->dump(fd, args); 339 } 340 return NO_ERROR; 341} 342 343status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const 344{ 345 const size_t SIZE = 256; 346 char buffer[SIZE]; 347 String8 result; 348 result.append(" Client\n"); 349 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n", 350 mPid, mConnId, mStatus, mLoop?"true": "false"); 351 result.append(buffer); 352 write(fd, result.string(), result.size()); 353 if (mAudioOutput != 0) { 354 mAudioOutput->dump(fd, args); 355 } 356 write(fd, "\n", 1); 357 return NO_ERROR; 358} 359 360static int myTid() { 361#ifdef HAVE_GETTID 362 return gettid(); 363#else 364 return getpid(); 365#endif 366} 367 368#if defined(__arm__) 369extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize, 370 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize); 371extern "C" void free_malloc_leak_info(uint8_t* info); 372 373// Use the String-class below instead of String8 to allocate all memory 374// beforehand and not reenter the heap while we are examining it... 375struct MyString8 { 376 static const size_t MAX_SIZE = 256 * 1024; 377 378 MyString8() 379 : mPtr((char *)malloc(MAX_SIZE)) { 380 *mPtr = '\0'; 381 } 382 383 ~MyString8() { 384 free(mPtr); 385 } 386 387 void append(const char *s) { 388 strcat(mPtr, s); 389 } 390 391 const char *string() const { 392 return mPtr; 393 } 394 395 size_t size() const { 396 return strlen(mPtr); 397 } 398 399private: 400 char *mPtr; 401 402 MyString8(const MyString8 &); 403 MyString8 &operator=(const MyString8 &); 404}; 405 406void memStatus(int fd, const Vector<String16>& args) 407{ 408 const size_t SIZE = 256; 409 char buffer[SIZE]; 410 MyString8 result; 411 412 typedef struct { 413 size_t size; 414 size_t dups; 415 intptr_t * backtrace; 416 } AllocEntry; 417 418 uint8_t *info = NULL; 419 size_t overallSize = 0; 420 size_t infoSize = 0; 421 size_t totalMemory = 0; 422 size_t backtraceSize = 0; 423 424 get_malloc_leak_info(&info, &overallSize, &infoSize, &totalMemory, &backtraceSize); 425 if (info) { 426 uint8_t *ptr = info; 427 size_t count = overallSize / infoSize; 428 429 snprintf(buffer, SIZE, " Allocation count %i\n", count); 430 result.append(buffer); 431 432 AllocEntry * entries = new AllocEntry[count]; 433 434 for (size_t i = 0; i < count; i++) { 435 // Each entry should be size_t, size_t, intptr_t[backtraceSize] 436 AllocEntry *e = &entries[i]; 437 438 e->size = *reinterpret_cast<size_t *>(ptr); 439 ptr += sizeof(size_t); 440 441 e->dups = *reinterpret_cast<size_t *>(ptr); 442 ptr += sizeof(size_t); 443 444 e->backtrace = reinterpret_cast<intptr_t *>(ptr); 445 ptr += sizeof(intptr_t) * backtraceSize; 446 } 447 448 // Now we need to sort the entries. They come sorted by size but 449 // not by stack trace which causes problems using diff. 450 bool moved; 451 do { 452 moved = false; 453 for (size_t i = 0; i < (count - 1); i++) { 454 AllocEntry *e1 = &entries[i]; 455 AllocEntry *e2 = &entries[i+1]; 456 457 bool swap = e1->size < e2->size; 458 if (e1->size == e2->size) { 459 for(size_t j = 0; j < backtraceSize; j++) { 460 if (e1->backtrace[j] == e2->backtrace[j]) { 461 continue; 462 } 463 swap = e1->backtrace[j] < e2->backtrace[j]; 464 break; 465 } 466 } 467 if (swap) { 468 AllocEntry t = entries[i]; 469 entries[i] = entries[i+1]; 470 entries[i+1] = t; 471 moved = true; 472 } 473 } 474 } while (moved); 475 476 for (size_t i = 0; i < count; i++) { 477 AllocEntry *e = &entries[i]; 478 479 snprintf(buffer, SIZE, "size %8i, dup %4i", e->size, e->dups); 480 result.append(buffer); 481 for (size_t ct = 0; (ct < backtraceSize) && e->backtrace[ct]; ct++) { 482 if (ct) { 483 result.append(", "); 484 } 485 snprintf(buffer, SIZE, "0x%08x", e->backtrace[ct]); 486 result.append(buffer); 487 } 488 result.append("\n"); 489 } 490 491 delete[] entries; 492 free_malloc_leak_info(info); 493 } 494 495 write(fd, result.string(), result.size()); 496} 497#endif 498 499status_t MediaPlayerService::dump(int fd, const Vector<String16>& args) 500{ 501 const size_t SIZE = 256; 502 char buffer[SIZE]; 503 String8 result; 504 if (checkCallingPermission(String16("android.permission.DUMP")) == false) { 505 snprintf(buffer, SIZE, "Permission Denial: " 506 "can't dump MediaPlayerService from pid=%d, uid=%d\n", 507 IPCThreadState::self()->getCallingPid(), 508 IPCThreadState::self()->getCallingUid()); 509 result.append(buffer); 510 } else { 511 Mutex::Autolock lock(mLock); 512 for (int i = 0, n = mClients.size(); i < n; ++i) { 513 sp<Client> c = mClients[i].promote(); 514 if (c != 0) c->dump(fd, args); 515 } 516 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) { 517 result.append(" MediaRecorderClient\n"); 518 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote(); 519 snprintf(buffer, 255, " pid(%d)\n\n", c->mPid); 520 result.append(buffer); 521 } 522 523 result.append(" Files opened and/or mapped:\n"); 524 snprintf(buffer, SIZE, "/proc/%d/maps", myTid()); 525 FILE *f = fopen(buffer, "r"); 526 if (f) { 527 while (!feof(f)) { 528 fgets(buffer, SIZE, f); 529 if (strstr(buffer, " /sdcard/") || 530 strstr(buffer, " /system/sounds/") || 531 strstr(buffer, " /system/media/")) { 532 result.append(" "); 533 result.append(buffer); 534 } 535 } 536 fclose(f); 537 } else { 538 result.append("couldn't open "); 539 result.append(buffer); 540 result.append("\n"); 541 } 542 543 snprintf(buffer, SIZE, "/proc/%d/fd", myTid()); 544 DIR *d = opendir(buffer); 545 if (d) { 546 struct dirent *ent; 547 while((ent = readdir(d)) != NULL) { 548 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) { 549 snprintf(buffer, SIZE, "/proc/%d/fd/%s", myTid(), ent->d_name); 550 struct stat s; 551 if (lstat(buffer, &s) == 0) { 552 if ((s.st_mode & S_IFMT) == S_IFLNK) { 553 char linkto[256]; 554 int len = readlink(buffer, linkto, sizeof(linkto)); 555 if(len > 0) { 556 if(len > 255) { 557 linkto[252] = '.'; 558 linkto[253] = '.'; 559 linkto[254] = '.'; 560 linkto[255] = 0; 561 } else { 562 linkto[len] = 0; 563 } 564 if (strstr(linkto, "/sdcard/") == linkto || 565 strstr(linkto, "/system/sounds/") == linkto || 566 strstr(linkto, "/system/media/") == linkto) { 567 result.append(" "); 568 result.append(buffer); 569 result.append(" -> "); 570 result.append(linkto); 571 result.append("\n"); 572 } 573 } 574 } else { 575 result.append(" unexpected type for "); 576 result.append(buffer); 577 result.append("\n"); 578 } 579 } 580 } 581 } 582 closedir(d); 583 } else { 584 result.append("couldn't open "); 585 result.append(buffer); 586 result.append("\n"); 587 } 588 589#if defined(__arm__) 590 bool dumpMem = false; 591 for (size_t i = 0; i < args.size(); i++) { 592 if (args[i] == String16("-m")) { 593 dumpMem = true; 594 } 595 } 596 if (dumpMem) { 597 memStatus(fd, args); 598 } 599#endif 600 } 601 write(fd, result.string(), result.size()); 602 return NO_ERROR; 603} 604 605void MediaPlayerService::removeClient(wp<Client> client) 606{ 607 Mutex::Autolock lock(mLock); 608 mClients.remove(client); 609} 610 611MediaPlayerService::Client::Client(const sp<MediaPlayerService>& service, pid_t pid, 612 int32_t connId, const sp<IMediaPlayerClient>& client) 613{ 614 LOGV("Client(%d) constructor", connId); 615 mPid = pid; 616 mConnId = connId; 617 mService = service; 618 mClient = client; 619 mLoop = false; 620 mStatus = NO_INIT; 621#if CALLBACK_ANTAGONIZER 622 LOGD("create Antagonizer"); 623 mAntagonizer = new Antagonizer(notify, this); 624#endif 625} 626 627MediaPlayerService::Client::~Client() 628{ 629 LOGV("Client(%d) destructor pid = %d", mConnId, mPid); 630 mAudioOutput.clear(); 631 wp<Client> client(this); 632 disconnect(); 633 mService->removeClient(client); 634} 635 636void MediaPlayerService::Client::disconnect() 637{ 638 LOGV("disconnect(%d) from pid %d", mConnId, mPid); 639 // grab local reference and clear main reference to prevent future 640 // access to object 641 sp<MediaPlayerBase> p; 642 { 643 Mutex::Autolock l(mLock); 644 p = mPlayer; 645 } 646 mClient.clear(); 647 648 mPlayer.clear(); 649 650 // clear the notification to prevent callbacks to dead client 651 // and reset the player. We assume the player will serialize 652 // access to itself if necessary. 653 if (p != 0) { 654 p->setNotifyCallback(0, 0); 655#if CALLBACK_ANTAGONIZER 656 LOGD("kill Antagonizer"); 657 mAntagonizer->kill(); 658#endif 659 p->reset(); 660 } 661 662 IPCThreadState::self()->flushCommands(); 663} 664 665static player_type getDefaultPlayerType() { 666#if BUILD_WITH_FULL_STAGEFRIGHT 667 char value[PROPERTY_VALUE_MAX]; 668 if (property_get("media.stagefright.enable-player", value, NULL) 669 && (!strcmp(value, "1") || !strcasecmp(value, "true"))) { 670 return STAGEFRIGHT_PLAYER; 671 } 672#endif 673 674 return PV_PLAYER; 675} 676 677player_type getPlayerType(int fd, int64_t offset, int64_t length) 678{ 679 char buf[20]; 680 lseek(fd, offset, SEEK_SET); 681 read(fd, buf, sizeof(buf)); 682 lseek(fd, offset, SEEK_SET); 683 684 long ident = *((long*)buf); 685 686 // Ogg vorbis? 687 if (ident == 0x5367674f) // 'OggS' 688 return VORBIS_PLAYER; 689 690#ifndef NO_OPENCORE 691 if (ident == 0x75b22630) { 692 // The magic number for .asf files, i.e. wmv and wma content. 693 // These are not currently supported through stagefright. 694 return PV_PLAYER; 695 } 696#endif 697 698 // Some kind of MIDI? 699 EAS_DATA_HANDLE easdata; 700 if (EAS_Init(&easdata) == EAS_SUCCESS) { 701 EAS_FILE locator; 702 locator.path = NULL; 703 locator.fd = fd; 704 locator.offset = offset; 705 locator.length = length; 706 EAS_HANDLE eashandle; 707 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) { 708 EAS_CloseFile(easdata, eashandle); 709 EAS_Shutdown(easdata); 710 return SONIVOX_PLAYER; 711 } 712 EAS_Shutdown(easdata); 713 } 714 715 return getDefaultPlayerType(); 716} 717 718player_type getPlayerType(const char* url) 719{ 720 if (TestPlayerStub::canBeUsed(url)) { 721 return TEST_PLAYER; 722 } 723 724 // use MidiFile for MIDI extensions 725 int lenURL = strlen(url); 726 for (int i = 0; i < NELEM(FILE_EXTS); ++i) { 727 int len = strlen(FILE_EXTS[i].extension); 728 int start = lenURL - len; 729 if (start > 0) { 730 if (!strncmp(url + start, FILE_EXTS[i].extension, len)) { 731 return FILE_EXTS[i].playertype; 732 } 733 } 734 } 735 736 if (!strncasecmp(url, "http://", 7)) { 737 char value[PROPERTY_VALUE_MAX]; 738 if (!property_get("media.stagefright.enable-http", value, NULL) 739 || (strcmp(value, "1") && strcasecmp(value, "true"))) { 740 // For now, we're going to use PV for http-based playback 741 // by default until we can clear up a few more issues. 742 return PV_PLAYER; 743 } 744 } 745 746 return getDefaultPlayerType(); 747} 748 749static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie, 750 notify_callback_f notifyFunc) 751{ 752 sp<MediaPlayerBase> p; 753 switch (playerType) { 754#ifndef NO_OPENCORE 755 case PV_PLAYER: 756 LOGV(" create PVPlayer"); 757 p = new PVPlayer(); 758 break; 759#endif 760 case SONIVOX_PLAYER: 761 LOGV(" create MidiFile"); 762 p = new MidiFile(); 763 break; 764 case VORBIS_PLAYER: 765 LOGV(" create VorbisPlayer"); 766 p = new VorbisPlayer(); 767 break; 768#if BUILD_WITH_FULL_STAGEFRIGHT 769 case STAGEFRIGHT_PLAYER: 770 LOGV(" create StagefrightPlayer"); 771 p = new StagefrightPlayer; 772 break; 773#endif 774 case TEST_PLAYER: 775 LOGV("Create Test Player stub"); 776 p = new TestPlayerStub(); 777 break; 778 } 779 if (p != NULL) { 780 if (p->initCheck() == NO_ERROR) { 781 p->setNotifyCallback(cookie, notifyFunc); 782 } else { 783 p.clear(); 784 } 785 } 786 if (p == NULL) { 787 LOGE("Failed to create player object"); 788 } 789 return p; 790} 791 792sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType) 793{ 794 // determine if we have the right player type 795 sp<MediaPlayerBase> p = mPlayer; 796 if ((p != NULL) && (p->playerType() != playerType)) { 797 LOGV("delete player"); 798 p.clear(); 799 } 800 if (p == NULL) { 801 p = android::createPlayer(playerType, this, notify); 802 } 803 return p; 804} 805 806status_t MediaPlayerService::Client::setDataSource(const char *url) 807{ 808 LOGV("setDataSource(%s)", url); 809 if (url == NULL) 810 return UNKNOWN_ERROR; 811 812 if (strncmp(url, "content://", 10) == 0) { 813 // get a filedescriptor for the content Uri and 814 // pass it to the setDataSource(fd) method 815 816 String16 url16(url); 817 int fd = android::openContentProviderFile(url16); 818 if (fd < 0) 819 { 820 LOGE("Couldn't open fd for %s", url); 821 return UNKNOWN_ERROR; 822 } 823 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus 824 close(fd); 825 return mStatus; 826 } else { 827 player_type playerType = getPlayerType(url); 828 LOGV("player type = %d", playerType); 829 830 // create the right type of player 831 sp<MediaPlayerBase> p = createPlayer(playerType); 832 if (p == NULL) return NO_INIT; 833 834 if (!p->hardwareOutput()) { 835 mAudioOutput = new AudioOutput(); 836 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput); 837 } 838 839 // now set data source 840 LOGV(" setDataSource"); 841 mStatus = p->setDataSource(url); 842 if (mStatus == NO_ERROR) { 843 mPlayer = p; 844 } else { 845 LOGE(" error: %d", mStatus); 846 } 847 return mStatus; 848 } 849} 850 851status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length) 852{ 853 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length); 854 struct stat sb; 855 int ret = fstat(fd, &sb); 856 if (ret != 0) { 857 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno)); 858 return UNKNOWN_ERROR; 859 } 860 861 LOGV("st_dev = %llu", sb.st_dev); 862 LOGV("st_mode = %u", sb.st_mode); 863 LOGV("st_uid = %lu", sb.st_uid); 864 LOGV("st_gid = %lu", sb.st_gid); 865 LOGV("st_size = %llu", sb.st_size); 866 867 if (offset >= sb.st_size) { 868 LOGE("offset error"); 869 ::close(fd); 870 return UNKNOWN_ERROR; 871 } 872 if (offset + length > sb.st_size) { 873 length = sb.st_size - offset; 874 LOGV("calculated length = %lld", length); 875 } 876 877 player_type playerType = getPlayerType(fd, offset, length); 878 LOGV("player type = %d", playerType); 879 880 // create the right type of player 881 sp<MediaPlayerBase> p = createPlayer(playerType); 882 if (p == NULL) return NO_INIT; 883 884 if (!p->hardwareOutput()) { 885 mAudioOutput = new AudioOutput(); 886 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput); 887 } 888 889 // now set data source 890 mStatus = p->setDataSource(fd, offset, length); 891 if (mStatus == NO_ERROR) mPlayer = p; 892 return mStatus; 893} 894 895status_t MediaPlayerService::Client::setVideoSurface(const sp<ISurface>& surface) 896{ 897 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get()); 898 sp<MediaPlayerBase> p = getPlayer(); 899 if (p == 0) return UNKNOWN_ERROR; 900 return p->setVideoSurface(surface); 901} 902 903status_t MediaPlayerService::Client::invoke(const Parcel& request, 904 Parcel *reply) 905{ 906 sp<MediaPlayerBase> p = getPlayer(); 907 if (p == NULL) return UNKNOWN_ERROR; 908 return p->invoke(request, reply); 909} 910 911// This call doesn't need to access the native player. 912status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter) 913{ 914 status_t status; 915 media::Metadata::Filter allow, drop; 916 917 if (unmarshallFilter(filter, &allow, &status) && 918 unmarshallFilter(filter, &drop, &status)) { 919 Mutex::Autolock lock(mLock); 920 921 mMetadataAllow = allow; 922 mMetadataDrop = drop; 923 } 924 return status; 925} 926 927status_t MediaPlayerService::Client::getMetadata( 928 bool update_only, bool apply_filter, Parcel *reply) 929{ 930 sp<MediaPlayerBase> player = getPlayer(); 931 if (player == 0) return UNKNOWN_ERROR; 932 933 status_t status; 934 // Placeholder for the return code, updated by the caller. 935 reply->writeInt32(-1); 936 937 media::Metadata::Filter ids; 938 939 // We don't block notifications while we fetch the data. We clear 940 // mMetadataUpdated first so we don't lose notifications happening 941 // during the rest of this call. 942 { 943 Mutex::Autolock lock(mLock); 944 if (update_only) { 945 ids = mMetadataUpdated; 946 } 947 mMetadataUpdated.clear(); 948 } 949 950 media::Metadata metadata(reply); 951 952 metadata.appendHeader(); 953 status = player->getMetadata(ids, reply); 954 955 if (status != OK) { 956 metadata.resetParcel(); 957 LOGE("getMetadata failed %d", status); 958 return status; 959 } 960 961 // FIXME: Implement filtering on the result. Not critical since 962 // filtering takes place on the update notifications already. This 963 // would be when all the metadata are fetch and a filter is set. 964 965 // Everything is fine, update the metadata length. 966 metadata.updateLength(); 967 return OK; 968} 969 970status_t MediaPlayerService::Client::prepareAsync() 971{ 972 LOGV("[%d] prepareAsync", mConnId); 973 sp<MediaPlayerBase> p = getPlayer(); 974 if (p == 0) return UNKNOWN_ERROR; 975 status_t ret = p->prepareAsync(); 976#if CALLBACK_ANTAGONIZER 977 LOGD("start Antagonizer"); 978 if (ret == NO_ERROR) mAntagonizer->start(); 979#endif 980 return ret; 981} 982 983status_t MediaPlayerService::Client::start() 984{ 985 LOGV("[%d] start", mConnId); 986 sp<MediaPlayerBase> p = getPlayer(); 987 if (p == 0) return UNKNOWN_ERROR; 988 p->setLooping(mLoop); 989 return p->start(); 990} 991 992status_t MediaPlayerService::Client::stop() 993{ 994 LOGV("[%d] stop", mConnId); 995 sp<MediaPlayerBase> p = getPlayer(); 996 if (p == 0) return UNKNOWN_ERROR; 997 return p->stop(); 998} 999 1000status_t MediaPlayerService::Client::pause() 1001{ 1002 LOGV("[%d] pause", mConnId); 1003 sp<MediaPlayerBase> p = getPlayer(); 1004 if (p == 0) return UNKNOWN_ERROR; 1005 return p->pause(); 1006} 1007 1008status_t MediaPlayerService::Client::isPlaying(bool* state) 1009{ 1010 *state = false; 1011 sp<MediaPlayerBase> p = getPlayer(); 1012 if (p == 0) return UNKNOWN_ERROR; 1013 *state = p->isPlaying(); 1014 LOGV("[%d] isPlaying: %d", mConnId, *state); 1015 return NO_ERROR; 1016} 1017 1018status_t MediaPlayerService::Client::getCurrentPosition(int *msec) 1019{ 1020 LOGV("getCurrentPosition"); 1021 sp<MediaPlayerBase> p = getPlayer(); 1022 if (p == 0) return UNKNOWN_ERROR; 1023 status_t ret = p->getCurrentPosition(msec); 1024 if (ret == NO_ERROR) { 1025 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec); 1026 } else { 1027 LOGE("getCurrentPosition returned %d", ret); 1028 } 1029 return ret; 1030} 1031 1032status_t MediaPlayerService::Client::getDuration(int *msec) 1033{ 1034 LOGV("getDuration"); 1035 sp<MediaPlayerBase> p = getPlayer(); 1036 if (p == 0) return UNKNOWN_ERROR; 1037 status_t ret = p->getDuration(msec); 1038 if (ret == NO_ERROR) { 1039 LOGV("[%d] getDuration = %d", mConnId, *msec); 1040 } else { 1041 LOGE("getDuration returned %d", ret); 1042 } 1043 return ret; 1044} 1045 1046status_t MediaPlayerService::Client::seekTo(int msec) 1047{ 1048 LOGV("[%d] seekTo(%d)", mConnId, msec); 1049 sp<MediaPlayerBase> p = getPlayer(); 1050 if (p == 0) return UNKNOWN_ERROR; 1051 return p->seekTo(msec); 1052} 1053 1054status_t MediaPlayerService::Client::reset() 1055{ 1056 LOGV("[%d] reset", mConnId); 1057 sp<MediaPlayerBase> p = getPlayer(); 1058 if (p == 0) return UNKNOWN_ERROR; 1059 return p->reset(); 1060} 1061 1062status_t MediaPlayerService::Client::setAudioStreamType(int type) 1063{ 1064 LOGV("[%d] setAudioStreamType(%d)", mConnId, type); 1065 // TODO: for hardware output, call player instead 1066 Mutex::Autolock l(mLock); 1067 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type); 1068 return NO_ERROR; 1069} 1070 1071status_t MediaPlayerService::Client::setLooping(int loop) 1072{ 1073 LOGV("[%d] setLooping(%d)", mConnId, loop); 1074 mLoop = loop; 1075 sp<MediaPlayerBase> p = getPlayer(); 1076 if (p != 0) return p->setLooping(loop); 1077 return NO_ERROR; 1078} 1079 1080status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume) 1081{ 1082 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume); 1083 // TODO: for hardware output, call player instead 1084 Mutex::Autolock l(mLock); 1085 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume); 1086 return NO_ERROR; 1087} 1088 1089 1090void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2) 1091{ 1092 Client* client = static_cast<Client*>(cookie); 1093 1094 if (MEDIA_INFO == msg && 1095 MEDIA_INFO_METADATA_UPDATE == ext1) { 1096 const media::Metadata::Type metadata_type = ext2; 1097 1098 if(client->shouldDropMetadata(metadata_type)) { 1099 return; 1100 } 1101 1102 // Update the list of metadata that have changed. getMetadata 1103 // also access mMetadataUpdated and clears it. 1104 client->addNewMetadataUpdate(metadata_type); 1105 } 1106 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2); 1107 client->mClient->notify(msg, ext1, ext2); 1108} 1109 1110 1111bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const 1112{ 1113 Mutex::Autolock lock(mLock); 1114 1115 if (findMetadata(mMetadataDrop, code)) { 1116 return true; 1117 } 1118 1119 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) { 1120 return false; 1121 } else { 1122 return true; 1123 } 1124} 1125 1126 1127void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) { 1128 Mutex::Autolock lock(mLock); 1129 if (mMetadataUpdated.indexOf(metadata_type) < 0) { 1130 mMetadataUpdated.add(metadata_type); 1131 } 1132} 1133 1134#if CALLBACK_ANTAGONIZER 1135const int Antagonizer::interval = 10000; // 10 msecs 1136 1137Antagonizer::Antagonizer(notify_callback_f cb, void* client) : 1138 mExit(false), mActive(false), mClient(client), mCb(cb) 1139{ 1140 createThread(callbackThread, this); 1141} 1142 1143void Antagonizer::kill() 1144{ 1145 Mutex::Autolock _l(mLock); 1146 mActive = false; 1147 mExit = true; 1148 mCondition.wait(mLock); 1149} 1150 1151int Antagonizer::callbackThread(void* user) 1152{ 1153 LOGD("Antagonizer started"); 1154 Antagonizer* p = reinterpret_cast<Antagonizer*>(user); 1155 while (!p->mExit) { 1156 if (p->mActive) { 1157 LOGV("send event"); 1158 p->mCb(p->mClient, 0, 0, 0); 1159 } 1160 usleep(interval); 1161 } 1162 Mutex::Autolock _l(p->mLock); 1163 p->mCondition.signal(); 1164 LOGD("Antagonizer stopped"); 1165 return 0; 1166} 1167#endif 1168 1169static size_t kDefaultHeapSize = 1024 * 1024; // 1MB 1170 1171sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat) 1172{ 1173 LOGV("decode(%s)", url); 1174 sp<MemoryBase> mem; 1175 sp<MediaPlayerBase> player; 1176 1177 // Protect our precious, precious DRMd ringtones by only allowing 1178 // decoding of http, but not filesystem paths or content Uris. 1179 // If the application wants to decode those, it should open a 1180 // filedescriptor for them and use that. 1181 if (url != NULL && strncmp(url, "http://", 7) != 0) { 1182 LOGD("Can't decode %s by path, use filedescriptor instead", url); 1183 return mem; 1184 } 1185 1186 player_type playerType = getPlayerType(url); 1187 LOGV("player type = %d", playerType); 1188 1189 // create the right type of player 1190 sp<AudioCache> cache = new AudioCache(url); 1191 player = android::createPlayer(playerType, cache.get(), cache->notify); 1192 if (player == NULL) goto Exit; 1193 if (player->hardwareOutput()) goto Exit; 1194 1195 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache); 1196 1197 // set data source 1198 if (player->setDataSource(url) != NO_ERROR) goto Exit; 1199 1200 LOGV("prepare"); 1201 player->prepareAsync(); 1202 1203 LOGV("wait for prepare"); 1204 if (cache->wait() != NO_ERROR) goto Exit; 1205 1206 LOGV("start"); 1207 player->start(); 1208 1209 LOGV("wait for playback complete"); 1210 if (cache->wait() != NO_ERROR) goto Exit; 1211 1212 mem = new MemoryBase(cache->getHeap(), 0, cache->size()); 1213 *pSampleRate = cache->sampleRate(); 1214 *pNumChannels = cache->channelCount(); 1215 *pFormat = cache->format(); 1216 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat); 1217 1218Exit: 1219 if (player != 0) player->reset(); 1220 return mem; 1221} 1222 1223sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat) 1224{ 1225 LOGV("decode(%d, %lld, %lld)", fd, offset, length); 1226 sp<MemoryBase> mem; 1227 sp<MediaPlayerBase> player; 1228 1229 player_type playerType = getPlayerType(fd, offset, length); 1230 LOGV("player type = %d", playerType); 1231 1232 // create the right type of player 1233 sp<AudioCache> cache = new AudioCache("decode_fd"); 1234 player = android::createPlayer(playerType, cache.get(), cache->notify); 1235 if (player == NULL) goto Exit; 1236 if (player->hardwareOutput()) goto Exit; 1237 1238 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache); 1239 1240 // set data source 1241 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit; 1242 1243 LOGV("prepare"); 1244 player->prepareAsync(); 1245 1246 LOGV("wait for prepare"); 1247 if (cache->wait() != NO_ERROR) goto Exit; 1248 1249 LOGV("start"); 1250 player->start(); 1251 1252 LOGV("wait for playback complete"); 1253 if (cache->wait() != NO_ERROR) goto Exit; 1254 1255 mem = new MemoryBase(cache->getHeap(), 0, cache->size()); 1256 *pSampleRate = cache->sampleRate(); 1257 *pNumChannels = cache->channelCount(); 1258 *pFormat = cache->format(); 1259 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat); 1260 1261Exit: 1262 if (player != 0) player->reset(); 1263 ::close(fd); 1264 return mem; 1265} 1266 1267/* 1268 * Avert your eyes, ugly hack ahead. 1269 * The following is to support music visualizations. 1270 */ 1271 1272static const int NUMVIZBUF = 32; 1273static const int VIZBUFFRAMES = 1024; 1274static const int BUFTIMEMSEC = NUMVIZBUF * VIZBUFFRAMES * 1000 / 44100; 1275static const int TOTALBUFTIMEMSEC = NUMVIZBUF * BUFTIMEMSEC; 1276 1277static bool gotMem = false; 1278static sp<MemoryHeapBase> heap; 1279static sp<MemoryBase> mem[NUMVIZBUF]; 1280static uint64_t endTime; 1281static uint64_t lastReadTime; 1282static uint64_t lastWriteTime; 1283static int writeIdx = 0; 1284 1285static void allocVizBufs() { 1286 if (!gotMem) { 1287 heap = new MemoryHeapBase(NUMVIZBUF * VIZBUFFRAMES * 2, 0, "snooper"); 1288 for (int i=0;i<NUMVIZBUF;i++) { 1289 mem[i] = new MemoryBase(heap, VIZBUFFRAMES * 2 * i, VIZBUFFRAMES * 2); 1290 } 1291 endTime = 0; 1292 gotMem = true; 1293 } 1294} 1295 1296 1297/* 1298 * Get a buffer of audio data that is about to be played. 1299 * We don't synchronize this because in practice the writer 1300 * is ahead of the reader, and even if we did happen to catch 1301 * a buffer while it's being written, it's just a visualization, 1302 * so no harm done. 1303 */ 1304static sp<MemoryBase> getVizBuffer() { 1305 1306 allocVizBufs(); 1307 1308 lastReadTime = uptimeMillis(); 1309 1310 // if there is no recent buffer (yet), just return empty handed 1311 if (lastWriteTime + TOTALBUFTIMEMSEC < lastReadTime) { 1312 //LOGI("@@@@ no audio data to look at yet: %d + %d < %d", (int)lastWriteTime, TOTALBUFTIMEMSEC, (int)lastReadTime); 1313 return NULL; 1314 } 1315 1316 int timedelta = endTime - lastReadTime; 1317 if (timedelta < 0) timedelta = 0; 1318 int framedelta = timedelta * 44100 / 1000; 1319 int headIdx = (writeIdx - framedelta) / VIZBUFFRAMES - 1; 1320 while (headIdx < 0) { 1321 headIdx += NUMVIZBUF; 1322 } 1323 return mem[headIdx]; 1324} 1325 1326// Append the data to the vizualization buffer 1327static void makeVizBuffers(const char *data, int len, uint64_t time) { 1328 1329 allocVizBufs(); 1330 1331 uint64_t startTime = time; 1332 const int frameSize = 4; // 16 bit stereo sample is 4 bytes 1333 int offset = writeIdx; 1334 int maxoff = heap->getSize() / 2; // in shorts 1335 short *base = (short*)heap->getBase(); 1336 short *src = (short*)data; 1337 while (len > 0) { 1338 1339 // Degrade quality by mixing to mono and clearing the lowest 3 bits. 1340 // This should still be good enough for a visualization 1341 base[offset++] = ((int(src[0]) + int(src[1])) >> 1) & ~0x7; 1342 src += 2; 1343 len -= frameSize; 1344 if (offset >= maxoff) { 1345 offset = 0; 1346 } 1347 } 1348 writeIdx = offset; 1349 endTime = time + (len / frameSize) / 44; 1350 //LOGI("@@@ stored buffers from %d to %d", uint32_t(startTime), uint32_t(time)); 1351} 1352 1353sp<IMemory> MediaPlayerService::snoop() 1354{ 1355 sp<MemoryBase> mem = getVizBuffer(); 1356 return mem; 1357} 1358 1359 1360#undef LOG_TAG 1361#define LOG_TAG "AudioSink" 1362MediaPlayerService::AudioOutput::AudioOutput() 1363 : mCallback(NULL), 1364 mCallbackCookie(NULL) { 1365 mTrack = 0; 1366 mStreamType = AudioSystem::MUSIC; 1367 mLeftVolume = 1.0; 1368 mRightVolume = 1.0; 1369 mLatency = 0; 1370 mMsecsPerFrame = 0; 1371 mNumFramesWritten = 0; 1372 setMinBufferCount(); 1373} 1374 1375MediaPlayerService::AudioOutput::~AudioOutput() 1376{ 1377 close(); 1378} 1379 1380void MediaPlayerService::AudioOutput::setMinBufferCount() 1381{ 1382 char value[PROPERTY_VALUE_MAX]; 1383 if (property_get("ro.kernel.qemu", value, 0)) { 1384 mIsOnEmulator = true; 1385 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator 1386 } 1387} 1388 1389bool MediaPlayerService::AudioOutput::isOnEmulator() 1390{ 1391 setMinBufferCount(); 1392 return mIsOnEmulator; 1393} 1394 1395int MediaPlayerService::AudioOutput::getMinBufferCount() 1396{ 1397 setMinBufferCount(); 1398 return mMinBufferCount; 1399} 1400 1401ssize_t MediaPlayerService::AudioOutput::bufferSize() const 1402{ 1403 if (mTrack == 0) return NO_INIT; 1404 return mTrack->frameCount() * frameSize(); 1405} 1406 1407ssize_t MediaPlayerService::AudioOutput::frameCount() const 1408{ 1409 if (mTrack == 0) return NO_INIT; 1410 return mTrack->frameCount(); 1411} 1412 1413ssize_t MediaPlayerService::AudioOutput::channelCount() const 1414{ 1415 if (mTrack == 0) return NO_INIT; 1416 return mTrack->channelCount(); 1417} 1418 1419ssize_t MediaPlayerService::AudioOutput::frameSize() const 1420{ 1421 if (mTrack == 0) return NO_INIT; 1422 return mTrack->frameSize(); 1423} 1424 1425uint32_t MediaPlayerService::AudioOutput::latency () const 1426{ 1427 return mLatency; 1428} 1429 1430float MediaPlayerService::AudioOutput::msecsPerFrame() const 1431{ 1432 return mMsecsPerFrame; 1433} 1434 1435status_t MediaPlayerService::AudioOutput::open( 1436 uint32_t sampleRate, int channelCount, int format, int bufferCount, 1437 AudioCallback cb, void *cookie) 1438{ 1439 mCallback = cb; 1440 mCallbackCookie = cookie; 1441 1442 // Check argument "bufferCount" against the mininum buffer count 1443 if (bufferCount < mMinBufferCount) { 1444 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount); 1445 bufferCount = mMinBufferCount; 1446 1447 } 1448 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount); 1449 if (mTrack) close(); 1450 int afSampleRate; 1451 int afFrameCount; 1452 int frameCount; 1453 1454 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) { 1455 return NO_INIT; 1456 } 1457 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) { 1458 return NO_INIT; 1459 } 1460 1461 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate; 1462 1463 AudioTrack *t; 1464 if (mCallback != NULL) { 1465 t = new AudioTrack( 1466 mStreamType, 1467 sampleRate, 1468 format, 1469 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO, 1470 frameCount, 1471 0 /* flags */, 1472 CallbackWrapper, 1473 this); 1474 } else { 1475 t = new AudioTrack( 1476 mStreamType, 1477 sampleRate, 1478 format, 1479 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO, 1480 frameCount); 1481 } 1482 1483 if ((t == 0) || (t->initCheck() != NO_ERROR)) { 1484 LOGE("Unable to create audio track"); 1485 delete t; 1486 return NO_INIT; 1487 } 1488 1489 LOGV("setVolume"); 1490 t->setVolume(mLeftVolume, mRightVolume); 1491 mMsecsPerFrame = 1.e3 / (float) sampleRate; 1492 mLatency = t->latency(); 1493 mTrack = t; 1494 return NO_ERROR; 1495} 1496 1497void MediaPlayerService::AudioOutput::start() 1498{ 1499 LOGV("start"); 1500 if (mTrack) { 1501 mTrack->setVolume(mLeftVolume, mRightVolume); 1502 mTrack->start(); 1503 mTrack->getPosition(&mNumFramesWritten); 1504 } 1505} 1506 1507void MediaPlayerService::AudioOutput::snoopWrite(const void* buffer, size_t size) { 1508 // Only make visualization buffers if anyone recently requested visualization data 1509 uint64_t now = uptimeMillis(); 1510 if (lastReadTime + TOTALBUFTIMEMSEC >= now) { 1511 // Based on the current play counter, the number of frames written and 1512 // the current real time we can calculate the approximate real start 1513 // time of the buffer we're about to write. 1514 uint32_t pos; 1515 mTrack->getPosition(&pos); 1516 1517 // we're writing ahead by this many frames: 1518 int ahead = mNumFramesWritten - pos; 1519 //LOGI("@@@ written: %d, playpos: %d, latency: %d", mNumFramesWritten, pos, mTrack->latency()); 1520 // which is this many milliseconds, assuming 44100 Hz: 1521 ahead /= 44; 1522 1523 makeVizBuffers((const char*)buffer, size, now + ahead + mTrack->latency()); 1524 lastWriteTime = now; 1525 } 1526} 1527 1528 1529ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size) 1530{ 1531 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback."); 1532 1533 //LOGV("write(%p, %u)", buffer, size); 1534 if (mTrack) { 1535 snoopWrite(buffer, size); 1536 ssize_t ret = mTrack->write(buffer, size); 1537 mNumFramesWritten += ret / 4; // assume 16 bit stereo 1538 return ret; 1539 } 1540 return NO_INIT; 1541} 1542 1543void MediaPlayerService::AudioOutput::stop() 1544{ 1545 LOGV("stop"); 1546 if (mTrack) mTrack->stop(); 1547 lastWriteTime = 0; 1548} 1549 1550void MediaPlayerService::AudioOutput::flush() 1551{ 1552 LOGV("flush"); 1553 if (mTrack) mTrack->flush(); 1554} 1555 1556void MediaPlayerService::AudioOutput::pause() 1557{ 1558 LOGV("pause"); 1559 if (mTrack) mTrack->pause(); 1560 lastWriteTime = 0; 1561} 1562 1563void MediaPlayerService::AudioOutput::close() 1564{ 1565 LOGV("close"); 1566 delete mTrack; 1567 mTrack = 0; 1568} 1569 1570void MediaPlayerService::AudioOutput::setVolume(float left, float right) 1571{ 1572 LOGV("setVolume(%f, %f)", left, right); 1573 mLeftVolume = left; 1574 mRightVolume = right; 1575 if (mTrack) { 1576 mTrack->setVolume(left, right); 1577 } 1578} 1579 1580// static 1581void MediaPlayerService::AudioOutput::CallbackWrapper( 1582 int event, void *cookie, void *info) { 1583 //LOGV("callbackwrapper"); 1584 if (event != AudioTrack::EVENT_MORE_DATA) { 1585 return; 1586 } 1587 1588 AudioOutput *me = (AudioOutput *)cookie; 1589 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info; 1590 1591 (*me->mCallback)( 1592 me, buffer->raw, buffer->size, me->mCallbackCookie); 1593 me->snoopWrite(buffer->raw, buffer->size); 1594} 1595 1596#undef LOG_TAG 1597#define LOG_TAG "AudioCache" 1598MediaPlayerService::AudioCache::AudioCache(const char* name) : 1599 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0), 1600 mError(NO_ERROR), mCommandComplete(false) 1601{ 1602 // create ashmem heap 1603 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name); 1604} 1605 1606uint32_t MediaPlayerService::AudioCache::latency () const 1607{ 1608 return 0; 1609} 1610 1611float MediaPlayerService::AudioCache::msecsPerFrame() const 1612{ 1613 return mMsecsPerFrame; 1614} 1615 1616status_t MediaPlayerService::AudioCache::open( 1617 uint32_t sampleRate, int channelCount, int format, int bufferCount, 1618 AudioCallback cb, void *cookie) 1619{ 1620 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount); 1621 if (cb != NULL) { 1622 return UNKNOWN_ERROR; // TODO: implement this. 1623 } 1624 if (mHeap->getHeapID() < 0) { 1625 return NO_INIT; 1626 } 1627 1628 mSampleRate = sampleRate; 1629 mChannelCount = (uint16_t)channelCount; 1630 mFormat = (uint16_t)format; 1631 mMsecsPerFrame = 1.e3 / (float) sampleRate; 1632 return NO_ERROR; 1633} 1634 1635ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size) 1636{ 1637 LOGV("write(%p, %u)", buffer, size); 1638 if ((buffer == 0) || (size == 0)) return size; 1639 1640 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase()); 1641 if (p == NULL) return NO_INIT; 1642 p += mSize; 1643 LOGV("memcpy(%p, %p, %u)", p, buffer, size); 1644 if (mSize + size > mHeap->getSize()) { 1645 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize()); 1646 size = mHeap->getSize() - mSize; 1647 } 1648 memcpy(p, buffer, size); 1649 mSize += size; 1650 return size; 1651} 1652 1653// call with lock held 1654status_t MediaPlayerService::AudioCache::wait() 1655{ 1656 Mutex::Autolock lock(mLock); 1657 if (!mCommandComplete) { 1658 mSignal.wait(mLock); 1659 } 1660 mCommandComplete = false; 1661 1662 if (mError == NO_ERROR) { 1663 LOGV("wait - success"); 1664 } else { 1665 LOGV("wait - error"); 1666 } 1667 return mError; 1668} 1669 1670void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2) 1671{ 1672 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2); 1673 AudioCache* p = static_cast<AudioCache*>(cookie); 1674 1675 // ignore buffering messages 1676 switch (msg) 1677 { 1678 case MEDIA_ERROR: 1679 LOGE("Error %d, %d occurred", ext1, ext2); 1680 p->mError = ext1; 1681 break; 1682 case MEDIA_PREPARED: 1683 LOGV("prepared"); 1684 break; 1685 case MEDIA_PLAYBACK_COMPLETE: 1686 LOGV("playback complete"); 1687 break; 1688 default: 1689 LOGV("ignored"); 1690 return; 1691 } 1692 1693 // wake up thread 1694 p->mCommandComplete = true; 1695 p->mSignal.signal(); 1696} 1697 1698} // namespace android 1699