MediaPlayerService.cpp revision a7e0e8b4c429fc68eb1bd5b5a30f5b91352288f9
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> 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/Vector.h> 45#include <cutils/properties.h> 46 47#include <media/MediaPlayerInterface.h> 48#include <media/mediarecorder.h> 49#include <media/MediaMetadataRetrieverInterface.h> 50#include <media/AudioTrack.h> 51 52#include "MediaRecorderClient.h" 53#include "MediaPlayerService.h" 54#include "MetadataRetrieverClient.h" 55 56#include "MidiFile.h" 57#include "VorbisPlayer.h" 58#include <media/PVPlayer.h> 59 60/* desktop Linux needs a little help with gettid() */ 61#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS) 62#define __KERNEL__ 63# include <linux/unistd.h> 64#ifdef _syscall0 65_syscall0(pid_t,gettid) 66#else 67pid_t gettid() { return syscall(__NR_gettid);} 68#endif 69#undef __KERNEL__ 70#endif 71 72namespace { 73using android::status_t; 74using android::OK; 75using android::BAD_VALUE; 76using android::NOT_ENOUGH_DATA; 77using android::Parcel; 78using android::Vector; 79 80// Max number of entries in the filter. 81const int kMaxFilterSize = 64; // I pulled that out of thin air. 82 83// Keep in sync with ANY in Metadata.java 84const int32_t kAny = 0; 85 86// To order the metadata types in the vector-filter. 87int lessThan(const int32_t *lhs, const int32_t *rhs) 88{ 89 return *lhs < *rhs ? 0 : 1; 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 Vector<int32_t> *filter, 115 status_t *status) 116{ 117 int32_t s; 118 if (p.readInt32(&s) != OK) 119 { 120 LOGE("Failed to read filter's length"); 121 *status = NOT_ENOUGH_DATA; 122 return false; 123 } 124 125 if( s > kMaxFilterSize || s < 0) 126 { 127 LOGE("Invalid filter len %d", s); 128 *status = BAD_VALUE; 129 return false; 130 } 131 132 size_t size = s; 133 134 filter->clear(); 135 filter->setCapacity(size); 136 137 s *= sizeof(int32_t); 138 139 if (p.dataAvail() < static_cast<size_t>(s)) 140 { 141 LOGE("Filter too short expected %d but got %d", s, p.dataAvail()); 142 *status = NOT_ENOUGH_DATA; 143 return false; 144 } 145 146 const int32_t *data = static_cast<const int32_t*>(p.readInplace(s)); 147 148 if (NULL == data ) 149 { 150 LOGE("Filter had no data"); 151 *status = BAD_VALUE; 152 return false; 153 } 154 155 // TODO: The stl impl of vector would be more efficient here 156 // because it degenerates into a memcpy on pod types. Try to 157 // replace later or use stl::set. 158 for (size_t i = 0; i < size; ++i) 159 { 160 filter->push(*data); 161 ++data; 162 } 163 *status = OK; 164 return true; 165} 166 167bool unmarshallBothFilters(const Parcel& p, 168 Vector<int32_t> *allow, 169 Vector<int32_t> *block, 170 status_t *status) 171{ 172 if (!(unmarshallFilter(p, allow, status) && unmarshallFilter(p, block, status))) 173 { 174 return false; 175 } 176 allow->sort(lessThan); 177 block->sort(lessThan); 178 return true; 179} 180 181// @param filter Should be sorted in ascending order. 182// @param val To be searched. 183// @return true if a match was found. 184bool findMetadata(const Vector<int32_t> filter, const int32_t val) 185{ 186 // Deal with empty and ANY right away 187 if (filter.isEmpty()) return false; 188 if (filter[0] == kAny) return true; 189 190 ssize_t min = 0; 191 ssize_t max = filter.size() - 1; 192 ssize_t mid; 193 do 194 { 195 mid = (min + max) / 2; 196 if (val > filter[mid]) 197 { 198 min = mid + 1; 199 } 200 else 201 { 202 max = mid - 1; 203 } 204 if (filter[mid] == val) 205 { 206 return true; 207 } 208 } 209 while(min <= max); 210 return false; 211} 212 213} // anonymous namespace 214 215 216namespace android { 217 218// TODO: Temp hack until we can register players 219typedef struct { 220 const char *extension; 221 const player_type playertype; 222} extmap; 223extmap FILE_EXTS [] = { 224 {".mid", SONIVOX_PLAYER}, 225 {".midi", SONIVOX_PLAYER}, 226 {".smf", SONIVOX_PLAYER}, 227 {".xmf", SONIVOX_PLAYER}, 228 {".imy", SONIVOX_PLAYER}, 229 {".rtttl", SONIVOX_PLAYER}, 230 {".rtx", SONIVOX_PLAYER}, 231 {".ota", SONIVOX_PLAYER}, 232 {".ogg", VORBIS_PLAYER}, 233 {".oga", VORBIS_PLAYER}, 234}; 235 236// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround 237/* static */ const uint32_t MediaPlayerService::AudioOutput::kAudioVideoDelayMs = 96; 238/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4; 239/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false; 240 241void MediaPlayerService::instantiate() { 242 defaultServiceManager()->addService( 243 String16("media.player"), new MediaPlayerService()); 244} 245 246MediaPlayerService::MediaPlayerService() 247{ 248 LOGV("MediaPlayerService created"); 249 mNextConnId = 1; 250} 251 252MediaPlayerService::~MediaPlayerService() 253{ 254 LOGV("MediaPlayerService destroyed"); 255} 256 257sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid) 258{ 259#ifndef NO_OPENCORE 260 sp<MediaRecorderClient> recorder = new MediaRecorderClient(pid); 261#else 262 sp<MediaRecorderClient> recorder = NULL; 263#endif 264 LOGV("Create new media recorder client from pid %d", pid); 265 return recorder; 266} 267 268sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid) 269{ 270 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid); 271 LOGV("Create new media retriever from pid %d", pid); 272 return retriever; 273} 274 275sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client, const char* url) 276{ 277 int32_t connId = android_atomic_inc(&mNextConnId); 278 sp<Client> c = new Client(this, pid, connId, client); 279 LOGV("Create new client(%d) from pid %d, url=%s, connId=%d", connId, pid, url, connId); 280 if (NO_ERROR != c->setDataSource(url)) 281 { 282 c.clear(); 283 return c; 284 } 285 wp<Client> w = c; 286 Mutex::Autolock lock(mLock); 287 mClients.add(w); 288 return c; 289} 290 291sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client, 292 int fd, int64_t offset, int64_t length) 293{ 294 int32_t connId = android_atomic_inc(&mNextConnId); 295 sp<Client> c = new Client(this, pid, connId, client); 296 LOGV("Create new client(%d) from pid %d, fd=%d, offset=%lld, length=%lld", 297 connId, pid, fd, offset, length); 298 if (NO_ERROR != c->setDataSource(fd, offset, length)) { 299 c.clear(); 300 } else { 301 wp<Client> w = c; 302 Mutex::Autolock lock(mLock); 303 mClients.add(w); 304 } 305 ::close(fd); 306 return c; 307} 308 309status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const 310{ 311 const size_t SIZE = 256; 312 char buffer[SIZE]; 313 String8 result; 314 315 result.append(" AudioCache\n"); 316 if (mHeap != 0) { 317 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n", 318 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice()); 319 result.append(buffer); 320 } 321 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n", 322 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount); 323 result.append(buffer); 324 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n", 325 mSampleRate, mSize, mError, mCommandComplete?"true":"false"); 326 result.append(buffer); 327 ::write(fd, result.string(), result.size()); 328 return NO_ERROR; 329} 330 331status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const 332{ 333 const size_t SIZE = 256; 334 char buffer[SIZE]; 335 String8 result; 336 337 result.append(" AudioOutput\n"); 338 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", 339 mStreamType, mLeftVolume, mRightVolume); 340 result.append(buffer); 341 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n", 342 mMsecsPerFrame, mLatency); 343 result.append(buffer); 344 ::write(fd, result.string(), result.size()); 345 if (mTrack != 0) { 346 mTrack->dump(fd, args); 347 } 348 return NO_ERROR; 349} 350 351status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const 352{ 353 const size_t SIZE = 256; 354 char buffer[SIZE]; 355 String8 result; 356 result.append(" Client\n"); 357 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n", 358 mPid, mConnId, mStatus, mLoop?"true": "false"); 359 result.append(buffer); 360 write(fd, result.string(), result.size()); 361 if (mAudioOutput != 0) { 362 mAudioOutput->dump(fd, args); 363 } 364 write(fd, "\n", 1); 365 return NO_ERROR; 366} 367 368static int myTid() { 369#ifdef HAVE_GETTID 370 return gettid(); 371#else 372 return getpid(); 373#endif 374} 375 376#if defined(__arm__) 377extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize, 378 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize); 379extern "C" void free_malloc_leak_info(uint8_t* info); 380 381void memStatus(int fd, const Vector<String16>& args) 382{ 383 const size_t SIZE = 256; 384 char buffer[SIZE]; 385 String8 result; 386 387 typedef struct { 388 size_t size; 389 size_t dups; 390 intptr_t * backtrace; 391 } AllocEntry; 392 393 uint8_t *info = NULL; 394 size_t overallSize = 0; 395 size_t infoSize = 0; 396 size_t totalMemory = 0; 397 size_t backtraceSize = 0; 398 399 get_malloc_leak_info(&info, &overallSize, &infoSize, &totalMemory, &backtraceSize); 400 if (info) { 401 uint8_t *ptr = info; 402 size_t count = overallSize / infoSize; 403 404 snprintf(buffer, SIZE, " Allocation count %i\n", count); 405 result.append(buffer); 406 407 AllocEntry * entries = new AllocEntry[count]; 408 409 for (size_t i = 0; i < count; i++) { 410 // Each entry should be size_t, size_t, intptr_t[backtraceSize] 411 AllocEntry *e = &entries[i]; 412 413 e->size = *reinterpret_cast<size_t *>(ptr); 414 ptr += sizeof(size_t); 415 416 e->dups = *reinterpret_cast<size_t *>(ptr); 417 ptr += sizeof(size_t); 418 419 e->backtrace = reinterpret_cast<intptr_t *>(ptr); 420 ptr += sizeof(intptr_t) * backtraceSize; 421 } 422 423 // Now we need to sort the entries. They come sorted by size but 424 // not by stack trace which causes problems using diff. 425 bool moved; 426 do { 427 moved = false; 428 for (size_t i = 0; i < (count - 1); i++) { 429 AllocEntry *e1 = &entries[i]; 430 AllocEntry *e2 = &entries[i+1]; 431 432 bool swap = e1->size < e2->size; 433 if (e1->size == e2->size) { 434 for(size_t j = 0; j < backtraceSize; j++) { 435 if (e1->backtrace[j] == e2->backtrace[j]) { 436 continue; 437 } 438 swap = e1->backtrace[j] < e2->backtrace[j]; 439 break; 440 } 441 } 442 if (swap) { 443 AllocEntry t = entries[i]; 444 entries[i] = entries[i+1]; 445 entries[i+1] = t; 446 moved = true; 447 } 448 } 449 } while (moved); 450 451 for (size_t i = 0; i < count; i++) { 452 AllocEntry *e = &entries[i]; 453 454 snprintf(buffer, SIZE, "size %8i, dup %4i", e->size, e->dups); 455 result.append(buffer); 456 for (size_t ct = 0; (ct < backtraceSize) && e->backtrace[ct]; ct++) { 457 if (ct) { 458 result.append(", "); 459 } 460 snprintf(buffer, SIZE, "0x%08x", e->backtrace[ct]); 461 result.append(buffer); 462 } 463 result.append("\n"); 464 } 465 466 delete[] entries; 467 free_malloc_leak_info(info); 468 } 469 470 write(fd, result.string(), result.size()); 471} 472#endif 473 474status_t MediaPlayerService::dump(int fd, const Vector<String16>& args) 475{ 476 const size_t SIZE = 256; 477 char buffer[SIZE]; 478 String8 result; 479 if (checkCallingPermission(String16("android.permission.DUMP")) == false) { 480 snprintf(buffer, SIZE, "Permission Denial: " 481 "can't dump MediaPlayerService from pid=%d, uid=%d\n", 482 IPCThreadState::self()->getCallingPid(), 483 IPCThreadState::self()->getCallingUid()); 484 result.append(buffer); 485 } else { 486 Mutex::Autolock lock(mLock); 487 for (int i = 0, n = mClients.size(); i < n; ++i) { 488 sp<Client> c = mClients[i].promote(); 489 if (c != 0) c->dump(fd, args); 490 } 491 result.append(" Files opened and/or mapped:\n"); 492 snprintf(buffer, SIZE, "/proc/%d/maps", myTid()); 493 FILE *f = fopen(buffer, "r"); 494 if (f) { 495 while (!feof(f)) { 496 fgets(buffer, SIZE, f); 497 if (strstr(buffer, " /sdcard/") || 498 strstr(buffer, " /system/sounds/") || 499 strstr(buffer, " /system/media/")) { 500 result.append(" "); 501 result.append(buffer); 502 } 503 } 504 fclose(f); 505 } else { 506 result.append("couldn't open "); 507 result.append(buffer); 508 result.append("\n"); 509 } 510 511 snprintf(buffer, SIZE, "/proc/%d/fd", myTid()); 512 DIR *d = opendir(buffer); 513 if (d) { 514 struct dirent *ent; 515 while((ent = readdir(d)) != NULL) { 516 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) { 517 snprintf(buffer, SIZE, "/proc/%d/fd/%s", myTid(), ent->d_name); 518 struct stat s; 519 if (lstat(buffer, &s) == 0) { 520 if ((s.st_mode & S_IFMT) == S_IFLNK) { 521 char linkto[256]; 522 int len = readlink(buffer, linkto, sizeof(linkto)); 523 if(len > 0) { 524 if(len > 255) { 525 linkto[252] = '.'; 526 linkto[253] = '.'; 527 linkto[254] = '.'; 528 linkto[255] = 0; 529 } else { 530 linkto[len] = 0; 531 } 532 if (strstr(linkto, "/sdcard/") == linkto || 533 strstr(linkto, "/system/sounds/") == linkto || 534 strstr(linkto, "/system/media/") == linkto) { 535 result.append(" "); 536 result.append(buffer); 537 result.append(" -> "); 538 result.append(linkto); 539 result.append("\n"); 540 } 541 } 542 } else { 543 result.append(" unexpected type for "); 544 result.append(buffer); 545 result.append("\n"); 546 } 547 } 548 } 549 } 550 closedir(d); 551 } else { 552 result.append("couldn't open "); 553 result.append(buffer); 554 result.append("\n"); 555 } 556 557#if defined(__arm__) 558 bool dumpMem = false; 559 for (size_t i = 0; i < args.size(); i++) { 560 if (args[i] == String16("-m")) { 561 dumpMem = true; 562 } 563 } 564 if (dumpMem) { 565 memStatus(fd, args); 566 } 567#endif 568 } 569 write(fd, result.string(), result.size()); 570 return NO_ERROR; 571} 572 573void MediaPlayerService::removeClient(wp<Client> client) 574{ 575 Mutex::Autolock lock(mLock); 576 mClients.remove(client); 577} 578 579MediaPlayerService::Client::Client(const sp<MediaPlayerService>& service, pid_t pid, 580 int32_t connId, const sp<IMediaPlayerClient>& client) 581{ 582 LOGV("Client(%d) constructor", connId); 583 mPid = pid; 584 mConnId = connId; 585 mService = service; 586 mClient = client; 587 mLoop = false; 588 mStatus = NO_INIT; 589#if CALLBACK_ANTAGONIZER 590 LOGD("create Antagonizer"); 591 mAntagonizer = new Antagonizer(notify, this); 592#endif 593} 594 595MediaPlayerService::Client::~Client() 596{ 597 LOGV("Client(%d) destructor pid = %d", mConnId, mPid); 598 mAudioOutput.clear(); 599 wp<Client> client(this); 600 disconnect(); 601 mService->removeClient(client); 602} 603 604void MediaPlayerService::Client::disconnect() 605{ 606 LOGV("disconnect(%d) from pid %d", mConnId, mPid); 607 // grab local reference and clear main reference to prevent future 608 // access to object 609 sp<MediaPlayerBase> p; 610 { 611 Mutex::Autolock l(mLock); 612 p = mPlayer; 613 } 614 mClient.clear(); 615 mPlayer.clear(); 616 617 // clear the notification to prevent callbacks to dead client 618 // and reset the player. We assume the player will serialize 619 // access to itself if necessary. 620 if (p != 0) { 621 p->setNotifyCallback(0, 0); 622#if CALLBACK_ANTAGONIZER 623 LOGD("kill Antagonizer"); 624 mAntagonizer->kill(); 625#endif 626 p->reset(); 627 } 628 629 IPCThreadState::self()->flushCommands(); 630} 631 632static player_type getPlayerType(int fd, int64_t offset, int64_t length) 633{ 634 char buf[20]; 635 lseek(fd, offset, SEEK_SET); 636 read(fd, buf, sizeof(buf)); 637 lseek(fd, offset, SEEK_SET); 638 639 long ident = *((long*)buf); 640 641 // Ogg vorbis? 642 if (ident == 0x5367674f) // 'OggS' 643 return VORBIS_PLAYER; 644 645 // Some kind of MIDI? 646 EAS_DATA_HANDLE easdata; 647 if (EAS_Init(&easdata) == EAS_SUCCESS) { 648 EAS_FILE locator; 649 locator.path = NULL; 650 locator.fd = fd; 651 locator.offset = offset; 652 locator.length = length; 653 EAS_HANDLE eashandle; 654 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) { 655 EAS_CloseFile(easdata, eashandle); 656 EAS_Shutdown(easdata); 657 return SONIVOX_PLAYER; 658 } 659 EAS_Shutdown(easdata); 660 } 661 662 // Fall through to PV 663 return PV_PLAYER; 664} 665 666static player_type getPlayerType(const char* url) 667{ 668 669 // use MidiFile for MIDI extensions 670 int lenURL = strlen(url); 671 for (int i = 0; i < NELEM(FILE_EXTS); ++i) { 672 int len = strlen(FILE_EXTS[i].extension); 673 int start = lenURL - len; 674 if (start > 0) { 675 if (!strncmp(url + start, FILE_EXTS[i].extension, len)) { 676 return FILE_EXTS[i].playertype; 677 } 678 } 679 } 680 681 // Fall through to PV 682 return PV_PLAYER; 683} 684 685static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie, 686 notify_callback_f notifyFunc) 687{ 688 sp<MediaPlayerBase> p; 689 switch (playerType) { 690#ifndef NO_OPENCORE 691 case PV_PLAYER: 692 LOGV(" create PVPlayer"); 693 p = new PVPlayer(); 694 break; 695#endif 696 case SONIVOX_PLAYER: 697 LOGV(" create MidiFile"); 698 p = new MidiFile(); 699 break; 700 case VORBIS_PLAYER: 701 LOGV(" create VorbisPlayer"); 702 p = new VorbisPlayer(); 703 break; 704 } 705 if (p != NULL) { 706 if (p->initCheck() == NO_ERROR) { 707 p->setNotifyCallback(cookie, notifyFunc); 708 } else { 709 p.clear(); 710 } 711 } 712 if (p == NULL) { 713 LOGE("Failed to create player object"); 714 } 715 return p; 716} 717 718sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType) 719{ 720 // determine if we have the right player type 721 sp<MediaPlayerBase> p = mPlayer; 722 if ((p != NULL) && (p->playerType() != playerType)) { 723 LOGV("delete player"); 724 p.clear(); 725 } 726 if (p == NULL) { 727 p = android::createPlayer(playerType, this, notify); 728 } 729 return p; 730} 731 732status_t MediaPlayerService::Client::setDataSource(const char *url) 733{ 734 LOGV("setDataSource(%s)", url); 735 if (url == NULL) 736 return UNKNOWN_ERROR; 737 738 if (strncmp(url, "content://", 10) == 0) { 739 // get a filedescriptor for the content Uri and 740 // pass it to the setDataSource(fd) method 741 742 String16 url16(url); 743 int fd = android::openContentProviderFile(url16); 744 if (fd < 0) 745 { 746 LOGE("Couldn't open fd for %s", url); 747 return UNKNOWN_ERROR; 748 } 749 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus 750 close(fd); 751 return mStatus; 752 } else { 753 player_type playerType = getPlayerType(url); 754 LOGV("player type = %d", playerType); 755 756 // create the right type of player 757 sp<MediaPlayerBase> p = createPlayer(playerType); 758 if (p == NULL) return NO_INIT; 759 760 if (!p->hardwareOutput()) { 761 mAudioOutput = new AudioOutput(); 762 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput); 763 } 764 765 // now set data source 766 LOGV(" setDataSource"); 767 mStatus = p->setDataSource(url); 768 if (mStatus == NO_ERROR) mPlayer = p; 769 return mStatus; 770 } 771} 772 773status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length) 774{ 775 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length); 776 struct stat sb; 777 int ret = fstat(fd, &sb); 778 if (ret != 0) { 779 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno)); 780 return UNKNOWN_ERROR; 781 } 782 783 LOGV("st_dev = %llu", sb.st_dev); 784 LOGV("st_mode = %u", sb.st_mode); 785 LOGV("st_uid = %lu", sb.st_uid); 786 LOGV("st_gid = %lu", sb.st_gid); 787 LOGV("st_size = %llu", sb.st_size); 788 789 if (offset >= sb.st_size) { 790 LOGE("offset error"); 791 ::close(fd); 792 return UNKNOWN_ERROR; 793 } 794 if (offset + length > sb.st_size) { 795 length = sb.st_size - offset; 796 LOGV("calculated length = %lld", length); 797 } 798 799 player_type playerType = getPlayerType(fd, offset, length); 800 LOGV("player type = %d", playerType); 801 802 // create the right type of player 803 sp<MediaPlayerBase> p = createPlayer(playerType); 804 if (p == NULL) return NO_INIT; 805 806 if (!p->hardwareOutput()) { 807 mAudioOutput = new AudioOutput(); 808 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput); 809 } 810 811 // now set data source 812 mStatus = p->setDataSource(fd, offset, length); 813 if (mStatus == NO_ERROR) mPlayer = p; 814 return mStatus; 815} 816 817status_t MediaPlayerService::Client::setVideoSurface(const sp<ISurface>& surface) 818{ 819 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get()); 820 sp<MediaPlayerBase> p = getPlayer(); 821 if (p == 0) return UNKNOWN_ERROR; 822 return p->setVideoSurface(surface); 823} 824 825status_t MediaPlayerService::Client::invoke(const Parcel& request, 826 Parcel *reply) 827{ 828 sp<MediaPlayerBase> p = getPlayer(); 829 if (p == NULL) return UNKNOWN_ERROR; 830 return p->invoke(request, reply); 831} 832 833// This call doesn't need to access the native player. 834status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter) 835{ 836 status_t status; 837 Vector<int32_t> allow, drop; 838 839 if (unmarshallBothFilters(filter, &allow, &drop, &status)) 840 { 841 Mutex::Autolock l(mLock); 842 843 mMetadataAllow = allow; 844 mMetadataDrop = drop; 845 } 846 return status; 847} 848 849status_t MediaPlayerService::Client::prepareAsync() 850{ 851 LOGV("[%d] prepareAsync", mConnId); 852 sp<MediaPlayerBase> p = getPlayer(); 853 if (p == 0) return UNKNOWN_ERROR; 854 status_t ret = p->prepareAsync(); 855#if CALLBACK_ANTAGONIZER 856 LOGD("start Antagonizer"); 857 if (ret == NO_ERROR) mAntagonizer->start(); 858#endif 859 return ret; 860} 861 862status_t MediaPlayerService::Client::start() 863{ 864 LOGV("[%d] start", mConnId); 865 sp<MediaPlayerBase> p = getPlayer(); 866 if (p == 0) return UNKNOWN_ERROR; 867 p->setLooping(mLoop); 868 return p->start(); 869} 870 871status_t MediaPlayerService::Client::stop() 872{ 873 LOGV("[%d] stop", mConnId); 874 sp<MediaPlayerBase> p = getPlayer(); 875 if (p == 0) return UNKNOWN_ERROR; 876 return p->stop(); 877} 878 879status_t MediaPlayerService::Client::pause() 880{ 881 LOGV("[%d] pause", mConnId); 882 sp<MediaPlayerBase> p = getPlayer(); 883 if (p == 0) return UNKNOWN_ERROR; 884 return p->pause(); 885} 886 887status_t MediaPlayerService::Client::isPlaying(bool* state) 888{ 889 *state = false; 890 sp<MediaPlayerBase> p = getPlayer(); 891 if (p == 0) return UNKNOWN_ERROR; 892 *state = p->isPlaying(); 893 LOGV("[%d] isPlaying: %d", mConnId, *state); 894 return NO_ERROR; 895} 896 897status_t MediaPlayerService::Client::getCurrentPosition(int *msec) 898{ 899 LOGV("getCurrentPosition"); 900 sp<MediaPlayerBase> p = getPlayer(); 901 if (p == 0) return UNKNOWN_ERROR; 902 status_t ret = p->getCurrentPosition(msec); 903 if (ret == NO_ERROR) { 904 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec); 905 } else { 906 LOGE("getCurrentPosition returned %d", ret); 907 } 908 return ret; 909} 910 911status_t MediaPlayerService::Client::getDuration(int *msec) 912{ 913 LOGV("getDuration"); 914 sp<MediaPlayerBase> p = getPlayer(); 915 if (p == 0) return UNKNOWN_ERROR; 916 status_t ret = p->getDuration(msec); 917 if (ret == NO_ERROR) { 918 LOGV("[%d] getDuration = %d", mConnId, *msec); 919 } else { 920 LOGE("getDuration returned %d", ret); 921 } 922 return ret; 923} 924 925status_t MediaPlayerService::Client::seekTo(int msec) 926{ 927 LOGV("[%d] seekTo(%d)", mConnId, msec); 928 sp<MediaPlayerBase> p = getPlayer(); 929 if (p == 0) return UNKNOWN_ERROR; 930 return p->seekTo(msec); 931} 932 933status_t MediaPlayerService::Client::reset() 934{ 935 LOGV("[%d] reset", mConnId); 936 sp<MediaPlayerBase> p = getPlayer(); 937 if (p == 0) return UNKNOWN_ERROR; 938 return p->reset(); 939} 940 941status_t MediaPlayerService::Client::setAudioStreamType(int type) 942{ 943 LOGV("[%d] setAudioStreamType(%d)", mConnId, type); 944 // TODO: for hardware output, call player instead 945 Mutex::Autolock l(mLock); 946 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type); 947 return NO_ERROR; 948} 949 950status_t MediaPlayerService::Client::setLooping(int loop) 951{ 952 LOGV("[%d] setLooping(%d)", mConnId, loop); 953 mLoop = loop; 954 sp<MediaPlayerBase> p = getPlayer(); 955 if (p != 0) return p->setLooping(loop); 956 return NO_ERROR; 957} 958 959status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume) 960{ 961 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume); 962 // TODO: for hardware output, call player instead 963 Mutex::Autolock l(mLock); 964 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume); 965 return NO_ERROR; 966} 967 968void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2) 969{ 970 Client* client = static_cast<Client*>(cookie); 971 972 if (MEDIA_INFO == msg && 973 MEDIA_INFO_METADATA_UPDATE == ext1 && 974 client->shouldDropMetadata(ext2 /* metadata type */)) { 975 return; 976 } 977 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2); 978 client->mClient->notify(msg, ext1, ext2); 979} 980 981bool MediaPlayerService::Client::shouldDropMetadata(int code) const 982{ 983 Mutex::Autolock l(mLock); 984 985 if (findMetadata(mMetadataDrop, code)) 986 { 987 return true; 988 } 989 990 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) 991 { 992 return false; 993 } 994 else 995 { 996 return true; 997 } 998} 999 1000#if CALLBACK_ANTAGONIZER 1001const int Antagonizer::interval = 10000; // 10 msecs 1002 1003Antagonizer::Antagonizer(notify_callback_f cb, void* client) : 1004 mExit(false), mActive(false), mClient(client), mCb(cb) 1005{ 1006 createThread(callbackThread, this); 1007} 1008 1009void Antagonizer::kill() 1010{ 1011 Mutex::Autolock _l(mLock); 1012 mActive = false; 1013 mExit = true; 1014 mCondition.wait(mLock); 1015} 1016 1017int Antagonizer::callbackThread(void* user) 1018{ 1019 LOGD("Antagonizer started"); 1020 Antagonizer* p = reinterpret_cast<Antagonizer*>(user); 1021 while (!p->mExit) { 1022 if (p->mActive) { 1023 LOGV("send event"); 1024 p->mCb(p->mClient, 0, 0, 0); 1025 } 1026 usleep(interval); 1027 } 1028 Mutex::Autolock _l(p->mLock); 1029 p->mCondition.signal(); 1030 LOGD("Antagonizer stopped"); 1031 return 0; 1032} 1033#endif 1034 1035static size_t kDefaultHeapSize = 1024 * 1024; // 1MB 1036 1037sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat) 1038{ 1039 LOGV("decode(%s)", url); 1040 sp<MemoryBase> mem; 1041 sp<MediaPlayerBase> player; 1042 1043 // Protect our precious, precious DRMd ringtones by only allowing 1044 // decoding of http, but not filesystem paths or content Uris. 1045 // If the application wants to decode those, it should open a 1046 // filedescriptor for them and use that. 1047 if (url != NULL && strncmp(url, "http://", 7) != 0) { 1048 LOGD("Can't decode %s by path, use filedescriptor instead", url); 1049 return mem; 1050 } 1051 1052 player_type playerType = getPlayerType(url); 1053 LOGV("player type = %d", playerType); 1054 1055 // create the right type of player 1056 sp<AudioCache> cache = new AudioCache(url); 1057 player = android::createPlayer(playerType, cache.get(), cache->notify); 1058 if (player == NULL) goto Exit; 1059 if (player->hardwareOutput()) goto Exit; 1060 1061 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache); 1062 1063 // set data source 1064 if (player->setDataSource(url) != NO_ERROR) goto Exit; 1065 1066 LOGV("prepare"); 1067 player->prepareAsync(); 1068 1069 LOGV("wait for prepare"); 1070 if (cache->wait() != NO_ERROR) goto Exit; 1071 1072 LOGV("start"); 1073 player->start(); 1074 1075 LOGV("wait for playback complete"); 1076 if (cache->wait() != NO_ERROR) goto Exit; 1077 1078 mem = new MemoryBase(cache->getHeap(), 0, cache->size()); 1079 *pSampleRate = cache->sampleRate(); 1080 *pNumChannels = cache->channelCount(); 1081 *pFormat = cache->format(); 1082 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat); 1083 1084Exit: 1085 if (player != 0) player->reset(); 1086 return mem; 1087} 1088 1089sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat) 1090{ 1091 LOGV("decode(%d, %lld, %lld)", fd, offset, length); 1092 sp<MemoryBase> mem; 1093 sp<MediaPlayerBase> player; 1094 1095 player_type playerType = getPlayerType(fd, offset, length); 1096 LOGV("player type = %d", playerType); 1097 1098 // create the right type of player 1099 sp<AudioCache> cache = new AudioCache("decode_fd"); 1100 player = android::createPlayer(playerType, cache.get(), cache->notify); 1101 if (player == NULL) goto Exit; 1102 if (player->hardwareOutput()) goto Exit; 1103 1104 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache); 1105 1106 // set data source 1107 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit; 1108 1109 LOGV("prepare"); 1110 player->prepareAsync(); 1111 1112 LOGV("wait for prepare"); 1113 if (cache->wait() != NO_ERROR) goto Exit; 1114 1115 LOGV("start"); 1116 player->start(); 1117 1118 LOGV("wait for playback complete"); 1119 if (cache->wait() != NO_ERROR) goto Exit; 1120 1121 mem = new MemoryBase(cache->getHeap(), 0, cache->size()); 1122 *pSampleRate = cache->sampleRate(); 1123 *pNumChannels = cache->channelCount(); 1124 *pFormat = cache->format(); 1125 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat); 1126 1127Exit: 1128 if (player != 0) player->reset(); 1129 ::close(fd); 1130 return mem; 1131} 1132 1133#undef LOG_TAG 1134#define LOG_TAG "AudioSink" 1135MediaPlayerService::AudioOutput::AudioOutput() 1136{ 1137 mTrack = 0; 1138 mStreamType = AudioSystem::MUSIC; 1139 mLeftVolume = 1.0; 1140 mRightVolume = 1.0; 1141 mLatency = 0; 1142 mMsecsPerFrame = 0; 1143 setMinBufferCount(); 1144} 1145 1146MediaPlayerService::AudioOutput::~AudioOutput() 1147{ 1148 close(); 1149} 1150 1151void MediaPlayerService::AudioOutput::setMinBufferCount() 1152{ 1153 char value[PROPERTY_VALUE_MAX]; 1154 if (property_get("ro.kernel.qemu", value, 0)) { 1155 mIsOnEmulator = true; 1156 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator 1157 } 1158} 1159 1160bool MediaPlayerService::AudioOutput::isOnEmulator() 1161{ 1162 setMinBufferCount(); 1163 return mIsOnEmulator; 1164} 1165 1166int MediaPlayerService::AudioOutput::getMinBufferCount() 1167{ 1168 setMinBufferCount(); 1169 return mMinBufferCount; 1170} 1171 1172ssize_t MediaPlayerService::AudioOutput::bufferSize() const 1173{ 1174 if (mTrack == 0) return NO_INIT; 1175 return mTrack->frameCount() * frameSize(); 1176} 1177 1178ssize_t MediaPlayerService::AudioOutput::frameCount() const 1179{ 1180 if (mTrack == 0) return NO_INIT; 1181 return mTrack->frameCount(); 1182} 1183 1184ssize_t MediaPlayerService::AudioOutput::channelCount() const 1185{ 1186 if (mTrack == 0) return NO_INIT; 1187 return mTrack->channelCount(); 1188} 1189 1190ssize_t MediaPlayerService::AudioOutput::frameSize() const 1191{ 1192 if (mTrack == 0) return NO_INIT; 1193 return mTrack->frameSize(); 1194} 1195 1196uint32_t MediaPlayerService::AudioOutput::latency () const 1197{ 1198 return mLatency; 1199} 1200 1201float MediaPlayerService::AudioOutput::msecsPerFrame() const 1202{ 1203 return mMsecsPerFrame; 1204} 1205 1206status_t MediaPlayerService::AudioOutput::open(uint32_t sampleRate, int channelCount, int format, int bufferCount) 1207{ 1208 // Check argument "bufferCount" against the mininum buffer count 1209 if (bufferCount < mMinBufferCount) { 1210 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount); 1211 bufferCount = mMinBufferCount; 1212 1213 } 1214 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount); 1215 if (mTrack) close(); 1216 int afSampleRate; 1217 int afFrameCount; 1218 int frameCount; 1219 1220 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) { 1221 return NO_INIT; 1222 } 1223 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) { 1224 return NO_INIT; 1225 } 1226 1227 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate; 1228 AudioTrack *t = new AudioTrack(mStreamType, sampleRate, format, channelCount, frameCount); 1229 if ((t == 0) || (t->initCheck() != NO_ERROR)) { 1230 LOGE("Unable to create audio track"); 1231 delete t; 1232 return NO_INIT; 1233 } 1234 1235 LOGV("setVolume"); 1236 t->setVolume(mLeftVolume, mRightVolume); 1237 mMsecsPerFrame = 1.e3 / (float) sampleRate; 1238 mLatency = t->latency() + kAudioVideoDelayMs; 1239 mTrack = t; 1240 return NO_ERROR; 1241} 1242 1243void MediaPlayerService::AudioOutput::start() 1244{ 1245 LOGV("start"); 1246 if (mTrack) { 1247 mTrack->setVolume(mLeftVolume, mRightVolume); 1248 mTrack->start(); 1249 } 1250} 1251 1252ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size) 1253{ 1254 //LOGV("write(%p, %u)", buffer, size); 1255 if (mTrack) return mTrack->write(buffer, size); 1256 return NO_INIT; 1257} 1258 1259void MediaPlayerService::AudioOutput::stop() 1260{ 1261 LOGV("stop"); 1262 if (mTrack) mTrack->stop(); 1263} 1264 1265void MediaPlayerService::AudioOutput::flush() 1266{ 1267 LOGV("flush"); 1268 if (mTrack) mTrack->flush(); 1269} 1270 1271void MediaPlayerService::AudioOutput::pause() 1272{ 1273 LOGV("pause"); 1274 if (mTrack) mTrack->pause(); 1275} 1276 1277void MediaPlayerService::AudioOutput::close() 1278{ 1279 LOGV("close"); 1280 delete mTrack; 1281 mTrack = 0; 1282} 1283 1284void MediaPlayerService::AudioOutput::setVolume(float left, float right) 1285{ 1286 LOGV("setVolume(%f, %f)", left, right); 1287 mLeftVolume = left; 1288 mRightVolume = right; 1289 if (mTrack) { 1290 mTrack->setVolume(left, right); 1291 } 1292} 1293 1294#undef LOG_TAG 1295#define LOG_TAG "AudioCache" 1296MediaPlayerService::AudioCache::AudioCache(const char* name) : 1297 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0), 1298 mError(NO_ERROR), mCommandComplete(false) 1299{ 1300 // create ashmem heap 1301 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name); 1302} 1303 1304uint32_t MediaPlayerService::AudioCache::latency () const 1305{ 1306 return 0; 1307} 1308 1309float MediaPlayerService::AudioCache::msecsPerFrame() const 1310{ 1311 return mMsecsPerFrame; 1312} 1313 1314status_t MediaPlayerService::AudioCache::open(uint32_t sampleRate, int channelCount, int format, int bufferCount) 1315{ 1316 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount); 1317 if (mHeap->getHeapID() < 0) return NO_INIT; 1318 mSampleRate = sampleRate; 1319 mChannelCount = (uint16_t)channelCount; 1320 mFormat = (uint16_t)format; 1321 mMsecsPerFrame = 1.e3 / (float) sampleRate; 1322 return NO_ERROR; 1323} 1324 1325ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size) 1326{ 1327 LOGV("write(%p, %u)", buffer, size); 1328 if ((buffer == 0) || (size == 0)) return size; 1329 1330 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase()); 1331 if (p == NULL) return NO_INIT; 1332 p += mSize; 1333 LOGV("memcpy(%p, %p, %u)", p, buffer, size); 1334 if (mSize + size > mHeap->getSize()) { 1335 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize()); 1336 size = mHeap->getSize() - mSize; 1337 } 1338 memcpy(p, buffer, size); 1339 mSize += size; 1340 return size; 1341} 1342 1343// call with lock held 1344status_t MediaPlayerService::AudioCache::wait() 1345{ 1346 Mutex::Autolock lock(mLock); 1347 if (!mCommandComplete) { 1348 mSignal.wait(mLock); 1349 } 1350 mCommandComplete = false; 1351 1352 if (mError == NO_ERROR) { 1353 LOGV("wait - success"); 1354 } else { 1355 LOGV("wait - error"); 1356 } 1357 return mError; 1358} 1359 1360void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2) 1361{ 1362 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2); 1363 AudioCache* p = static_cast<AudioCache*>(cookie); 1364 1365 // ignore buffering messages 1366 if (msg == MEDIA_BUFFERING_UPDATE) return; 1367 1368 // set error condition 1369 if (msg == MEDIA_ERROR) { 1370 LOGE("Error %d, %d occurred", ext1, ext2); 1371 p->mError = ext1; 1372 } 1373 1374 // wake up thread 1375 LOGV("wakeup thread"); 1376 p->mCommandComplete = true; 1377 p->mSignal.signal(); 1378} 1379 1380}; // namespace android 1381