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