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