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