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