MediaPlayerService.cpp revision d4e9ca49a3863beeb0027f51e2331e4c5ec2402b
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 <binder/IPCThreadState.h> 38#include <binder/IServiceManager.h> 39#include <binder/MemoryHeapBase.h> 40#include <binder/MemoryBase.h> 41#include <gui/Surface.h> 42#include <utils/Errors.h> // for status_t 43#include <utils/String8.h> 44#include <utils/SystemClock.h> 45#include <utils/Timers.h> 46#include <utils/Vector.h> 47 48#include <media/AudioPolicyHelper.h> 49#include <media/IMediaHTTPService.h> 50#include <media/IRemoteDisplay.h> 51#include <media/IRemoteDisplayClient.h> 52#include <media/MediaPlayerInterface.h> 53#include <media/mediarecorder.h> 54#include <media/MediaMetadataRetrieverInterface.h> 55#include <media/Metadata.h> 56#include <media/AudioTrack.h> 57#include <media/MemoryLeakTrackUtil.h> 58#include <media/stagefright/MediaCodecList.h> 59#include <media/stagefright/MediaErrors.h> 60#include <media/stagefright/Utils.h> 61#include <media/stagefright/foundation/ADebug.h> 62#include <media/stagefright/foundation/ALooperRoster.h> 63#include <media/stagefright/SurfaceUtils.h> 64#include <mediautils/BatteryNotifier.h> 65 66#include <memunreachable/memunreachable.h> 67#include <system/audio.h> 68 69#include <private/android_filesystem_config.h> 70 71#include "ActivityManager.h" 72#include "MediaRecorderClient.h" 73#include "MediaPlayerService.h" 74#include "MetadataRetrieverClient.h" 75#include "MediaPlayerFactory.h" 76 77#include "TestPlayerStub.h" 78#include "nuplayer/NuPlayerDriver.h" 79 80#include <OMX.h> 81 82#include "HDCP.h" 83#include "HTTPBase.h" 84#include "RemoteDisplay.h" 85 86namespace { 87using android::media::Metadata; 88using android::status_t; 89using android::OK; 90using android::BAD_VALUE; 91using android::NOT_ENOUGH_DATA; 92using android::Parcel; 93 94// Max number of entries in the filter. 95const int kMaxFilterSize = 64; // I pulled that out of thin air. 96 97const float kMaxRequiredSpeed = 8.0f; // for PCM tracks allow up to 8x speedup. 98 99// FIXME: Move all the metadata related function in the Metadata.cpp 100 101 102// Unmarshall a filter from a Parcel. 103// Filter format in a parcel: 104// 105// 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 106// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 107// | number of entries (n) | 108// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 109// | metadata type 1 | 110// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 111// | metadata type 2 | 112// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 113// .... 114// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 115// | metadata type n | 116// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 117// 118// @param p Parcel that should start with a filter. 119// @param[out] filter On exit contains the list of metadata type to be 120// filtered. 121// @param[out] status On exit contains the status code to be returned. 122// @return true if the parcel starts with a valid filter. 123bool unmarshallFilter(const Parcel& p, 124 Metadata::Filter *filter, 125 status_t *status) 126{ 127 int32_t val; 128 if (p.readInt32(&val) != OK) 129 { 130 ALOGE("Failed to read filter's length"); 131 *status = NOT_ENOUGH_DATA; 132 return false; 133 } 134 135 if( val > kMaxFilterSize || val < 0) 136 { 137 ALOGE("Invalid filter len %d", val); 138 *status = BAD_VALUE; 139 return false; 140 } 141 142 const size_t num = val; 143 144 filter->clear(); 145 filter->setCapacity(num); 146 147 size_t size = num * sizeof(Metadata::Type); 148 149 150 if (p.dataAvail() < size) 151 { 152 ALOGE("Filter too short expected %zu but got %zu", size, p.dataAvail()); 153 *status = NOT_ENOUGH_DATA; 154 return false; 155 } 156 157 const Metadata::Type *data = 158 static_cast<const Metadata::Type*>(p.readInplace(size)); 159 160 if (NULL == data) 161 { 162 ALOGE("Filter had no data"); 163 *status = BAD_VALUE; 164 return false; 165 } 166 167 // TODO: The stl impl of vector would be more efficient here 168 // because it degenerates into a memcpy on pod types. Try to 169 // replace later or use stl::set. 170 for (size_t i = 0; i < num; ++i) 171 { 172 filter->add(*data); 173 ++data; 174 } 175 *status = OK; 176 return true; 177} 178 179// @param filter Of metadata type. 180// @param val To be searched. 181// @return true if a match was found. 182bool findMetadata(const Metadata::Filter& filter, const int32_t val) 183{ 184 // Deal with empty and ANY right away 185 if (filter.isEmpty()) return false; 186 if (filter[0] == Metadata::kAny) return true; 187 188 return filter.indexOf(val) >= 0; 189} 190 191} // anonymous namespace 192 193 194namespace { 195using android::Parcel; 196using android::String16; 197 198// marshalling tag indicating flattened utf16 tags 199// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java 200const int32_t kAudioAttributesMarshallTagFlattenTags = 1; 201 202// Audio attributes format in a parcel: 203// 204// 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 205// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 206// | usage | 207// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 208// | content_type | 209// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 210// | source | 211// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 212// | flags | 213// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 214// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found 215// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 216// | flattened tags in UTF16 | 217// | ... | 218// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 219// 220// @param p Parcel that contains audio attributes. 221// @param[out] attributes On exit points to an initialized audio_attributes_t structure 222// @param[out] status On exit contains the status code to be returned. 223void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes) 224{ 225 attributes->usage = (audio_usage_t) parcel.readInt32(); 226 attributes->content_type = (audio_content_type_t) parcel.readInt32(); 227 attributes->source = (audio_source_t) parcel.readInt32(); 228 attributes->flags = (audio_flags_mask_t) parcel.readInt32(); 229 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags); 230 if (hasFlattenedTag) { 231 // the tags are UTF16, convert to UTF8 232 String16 tags = parcel.readString16(); 233 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size()); 234 if (realTagSize <= 0) { 235 strcpy(attributes->tags, ""); 236 } else { 237 // copy the flattened string into the attributes as the destination for the conversion: 238 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it 239 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ? 240 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize; 241 utf16_to_utf8(tags.string(), tagSize, attributes->tags, 242 sizeof(attributes->tags) / sizeof(attributes->tags[0])); 243 } 244 } else { 245 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values"); 246 strcpy(attributes->tags, ""); 247 } 248} 249} // anonymous namespace 250 251 252namespace android { 253 254extern ALooperRoster gLooperRoster; 255 256 257static bool checkPermission(const char* permissionString) { 258 if (getpid() == IPCThreadState::self()->getCallingPid()) return true; 259 bool ok = checkCallingPermission(String16(permissionString)); 260 if (!ok) ALOGE("Request requires %s", permissionString); 261 return ok; 262} 263 264// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround 265/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4; 266/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false; 267 268void MediaPlayerService::instantiate() { 269 defaultServiceManager()->addService( 270 String16("media.player"), new MediaPlayerService()); 271} 272 273MediaPlayerService::MediaPlayerService() 274{ 275 ALOGV("MediaPlayerService created"); 276 mNextConnId = 1; 277 278 mBatteryAudio.refCount = 0; 279 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) { 280 mBatteryAudio.deviceOn[i] = 0; 281 mBatteryAudio.lastTime[i] = 0; 282 mBatteryAudio.totalTime[i] = 0; 283 } 284 // speaker is on by default 285 mBatteryAudio.deviceOn[SPEAKER] = 1; 286 287 // reset battery stats 288 // if the mediaserver has crashed, battery stats could be left 289 // in bad state, reset the state upon service start. 290 BatteryNotifier::getInstance().noteResetVideo(); 291 292 MediaPlayerFactory::registerBuiltinFactories(); 293} 294 295MediaPlayerService::~MediaPlayerService() 296{ 297 ALOGV("MediaPlayerService destroyed"); 298} 299 300sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName) 301{ 302 pid_t pid = IPCThreadState::self()->getCallingPid(); 303 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName); 304 wp<MediaRecorderClient> w = recorder; 305 Mutex::Autolock lock(mLock); 306 mMediaRecorderClients.add(w); 307 ALOGV("Create new media recorder client from pid %d", pid); 308 return recorder; 309} 310 311void MediaPlayerService::removeMediaRecorderClient(const wp<MediaRecorderClient>& client) 312{ 313 Mutex::Autolock lock(mLock); 314 mMediaRecorderClients.remove(client); 315 ALOGV("Delete media recorder client"); 316} 317 318sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever() 319{ 320 pid_t pid = IPCThreadState::self()->getCallingPid(); 321 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid); 322 ALOGV("Create new media retriever from pid %d", pid); 323 return retriever; 324} 325 326sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client, 327 audio_session_t audioSessionId) 328{ 329 pid_t pid = IPCThreadState::self()->getCallingPid(); 330 int32_t connId = android_atomic_inc(&mNextConnId); 331 332 sp<Client> c = new Client( 333 this, pid, connId, client, audioSessionId, 334 IPCThreadState::self()->getCallingUid()); 335 336 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid, 337 IPCThreadState::self()->getCallingUid()); 338 339 wp<Client> w = c; 340 { 341 Mutex::Autolock lock(mLock); 342 mClients.add(w); 343 } 344 return c; 345} 346 347sp<IMediaCodecList> MediaPlayerService::getCodecList() const { 348 return MediaCodecList::getLocalInstance(); 349} 350 351sp<IOMX> MediaPlayerService::getOMX() { 352 ALOGI("MediaPlayerService::getOMX"); 353 Mutex::Autolock autoLock(mLock); 354 355 if (mOMX.get() == NULL) { 356 mOMX = new OMX; 357 } 358 359 return mOMX; 360} 361 362sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) { 363 return new HDCP(createEncryptionModule); 364} 365 366sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay( 367 const String16 &opPackageName, 368 const sp<IRemoteDisplayClient>& client, const String8& iface) { 369 if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) { 370 return NULL; 371 } 372 373 return new RemoteDisplay(opPackageName, client, iface.string()); 374} 375 376status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const 377{ 378 const size_t SIZE = 256; 379 char buffer[SIZE]; 380 String8 result; 381 382 result.append(" AudioOutput\n"); 383 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", 384 mStreamType, mLeftVolume, mRightVolume); 385 result.append(buffer); 386 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n", 387 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1); 388 result.append(buffer); 389 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n", 390 mAuxEffectId, mSendLevel); 391 result.append(buffer); 392 393 ::write(fd, result.string(), result.size()); 394 if (mTrack != 0) { 395 mTrack->dump(fd, args); 396 } 397 return NO_ERROR; 398} 399 400status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) 401{ 402 const size_t SIZE = 256; 403 char buffer[SIZE]; 404 String8 result; 405 result.append(" Client\n"); 406 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n", 407 mPid, mConnId, mStatus, mLoop?"true": "false"); 408 result.append(buffer); 409 write(fd, result.string(), result.size()); 410 if (mPlayer != NULL) { 411 mPlayer->dump(fd, args); 412 } 413 if (mAudioOutput != 0) { 414 mAudioOutput->dump(fd, args); 415 } 416 write(fd, "\n", 1); 417 return NO_ERROR; 418} 419 420/** 421 * The only arguments this understands right now are -c, -von and -voff, 422 * which are parsed by ALooperRoster::dump() 423 */ 424status_t MediaPlayerService::dump(int fd, const Vector<String16>& args) 425{ 426 const size_t SIZE = 256; 427 char buffer[SIZE]; 428 String8 result; 429 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction. 430 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients; 431 432 if (checkCallingPermission(String16("android.permission.DUMP")) == false) { 433 snprintf(buffer, SIZE, "Permission Denial: " 434 "can't dump MediaPlayerService from pid=%d, uid=%d\n", 435 IPCThreadState::self()->getCallingPid(), 436 IPCThreadState::self()->getCallingUid()); 437 result.append(buffer); 438 } else { 439 Mutex::Autolock lock(mLock); 440 for (int i = 0, n = mClients.size(); i < n; ++i) { 441 sp<Client> c = mClients[i].promote(); 442 if (c != 0) c->dump(fd, args); 443 clients.add(c); 444 } 445 if (mMediaRecorderClients.size() == 0) { 446 result.append(" No media recorder client\n\n"); 447 } else { 448 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) { 449 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote(); 450 if (c != 0) { 451 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid); 452 result.append(buffer); 453 write(fd, result.string(), result.size()); 454 result = "\n"; 455 c->dump(fd, args); 456 mediaRecorderClients.add(c); 457 } 458 } 459 } 460 461 result.append(" Files opened and/or mapped:\n"); 462 snprintf(buffer, SIZE, "/proc/%d/maps", getpid()); 463 FILE *f = fopen(buffer, "r"); 464 if (f) { 465 while (!feof(f)) { 466 fgets(buffer, SIZE, f); 467 if (strstr(buffer, " /storage/") || 468 strstr(buffer, " /system/sounds/") || 469 strstr(buffer, " /data/") || 470 strstr(buffer, " /system/media/")) { 471 result.append(" "); 472 result.append(buffer); 473 } 474 } 475 fclose(f); 476 } else { 477 result.append("couldn't open "); 478 result.append(buffer); 479 result.append("\n"); 480 } 481 482 snprintf(buffer, SIZE, "/proc/%d/fd", getpid()); 483 DIR *d = opendir(buffer); 484 if (d) { 485 struct dirent *ent; 486 while((ent = readdir(d)) != NULL) { 487 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) { 488 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name); 489 struct stat s; 490 if (lstat(buffer, &s) == 0) { 491 if ((s.st_mode & S_IFMT) == S_IFLNK) { 492 char linkto[256]; 493 int len = readlink(buffer, linkto, sizeof(linkto)); 494 if(len > 0) { 495 if(len > 255) { 496 linkto[252] = '.'; 497 linkto[253] = '.'; 498 linkto[254] = '.'; 499 linkto[255] = 0; 500 } else { 501 linkto[len] = 0; 502 } 503 if (strstr(linkto, "/storage/") == linkto || 504 strstr(linkto, "/system/sounds/") == linkto || 505 strstr(linkto, "/data/") == linkto || 506 strstr(linkto, "/system/media/") == linkto) { 507 result.append(" "); 508 result.append(buffer); 509 result.append(" -> "); 510 result.append(linkto); 511 result.append("\n"); 512 } 513 } 514 } else { 515 result.append(" unexpected type for "); 516 result.append(buffer); 517 result.append("\n"); 518 } 519 } 520 } 521 } 522 closedir(d); 523 } else { 524 result.append("couldn't open "); 525 result.append(buffer); 526 result.append("\n"); 527 } 528 529 gLooperRoster.dump(fd, args); 530 531 bool dumpMem = false; 532 bool unreachableMemory = false; 533 for (size_t i = 0; i < args.size(); i++) { 534 if (args[i] == String16("-m")) { 535 dumpMem = true; 536 } else if (args[i] == String16("--unreachable")) { 537 unreachableMemory = true; 538 } 539 } 540 if (dumpMem) { 541 result.append("\nDumping memory:\n"); 542 std::string s = dumpMemoryAddresses(100 /* limit */); 543 result.append(s.c_str(), s.size()); 544 } 545 if (unreachableMemory) { 546 result.append("\nDumping unreachable memory:\n"); 547 // TODO - should limit be an argument parameter? 548 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */); 549 result.append(s.c_str(), s.size()); 550 } 551 } 552 write(fd, result.string(), result.size()); 553 return NO_ERROR; 554} 555 556void MediaPlayerService::removeClient(const wp<Client>& client) 557{ 558 Mutex::Autolock lock(mLock); 559 mClients.remove(client); 560} 561 562bool MediaPlayerService::hasClient(wp<Client> client) 563{ 564 Mutex::Autolock lock(mLock); 565 return mClients.indexOf(client) != NAME_NOT_FOUND; 566} 567 568MediaPlayerService::Client::Client( 569 const sp<MediaPlayerService>& service, pid_t pid, 570 int32_t connId, const sp<IMediaPlayerClient>& client, 571 audio_session_t audioSessionId, uid_t uid) 572{ 573 ALOGV("Client(%d) constructor", connId); 574 mPid = pid; 575 mConnId = connId; 576 mService = service; 577 mClient = client; 578 mLoop = false; 579 mStatus = NO_INIT; 580 mAudioSessionId = audioSessionId; 581 mUid = uid; 582 mRetransmitEndpointValid = false; 583 mAudioAttributes = NULL; 584 585#if CALLBACK_ANTAGONIZER 586 ALOGD("create Antagonizer"); 587 mAntagonizer = new Antagonizer(notify, this); 588#endif 589} 590 591MediaPlayerService::Client::~Client() 592{ 593 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid); 594 mAudioOutput.clear(); 595 wp<Client> client(this); 596 disconnect(); 597 mService->removeClient(client); 598 if (mAudioAttributes != NULL) { 599 free(mAudioAttributes); 600 } 601 clearDeathNotifiers(); 602} 603 604void MediaPlayerService::Client::disconnect() 605{ 606 ALOGV("disconnect(%d) from pid %d", mConnId, mPid); 607 // grab local reference and clear main reference to prevent future 608 // access to object 609 sp<MediaPlayerBase> p; 610 { 611 Mutex::Autolock l(mLock); 612 p = mPlayer; 613 mClient.clear(); 614 } 615 616 mPlayer.clear(); 617 618 // clear the notification to prevent callbacks to dead client 619 // and reset the player. We assume the player will serialize 620 // access to itself if necessary. 621 if (p != 0) { 622 p->setNotifyCallback(0, 0); 623#if CALLBACK_ANTAGONIZER 624 ALOGD("kill Antagonizer"); 625 mAntagonizer->kill(); 626#endif 627 p->reset(); 628 } 629 630 disconnectNativeWindow(); 631 632 IPCThreadState::self()->flushCommands(); 633} 634 635sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType) 636{ 637 // determine if we have the right player type 638 sp<MediaPlayerBase> p = mPlayer; 639 if ((p != NULL) && (p->playerType() != playerType)) { 640 ALOGV("delete player"); 641 p.clear(); 642 } 643 if (p == NULL) { 644 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid); 645 } 646 647 if (p != NULL) { 648 p->setUID(mUid); 649 } 650 651 return p; 652} 653 654MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier( 655 const sp<IBinder>& service, 656 const sp<MediaPlayerBase>& listener, 657 int which) { 658 mService = service; 659 mOmx = nullptr; 660 mListener = listener; 661 mWhich = which; 662} 663 664MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier( 665 const sp<IOmx>& omx, 666 const sp<MediaPlayerBase>& listener, 667 int which) { 668 mService = nullptr; 669 mOmx = omx; 670 mListener = listener; 671 mWhich = which; 672} 673 674MediaPlayerService::Client::ServiceDeathNotifier::~ServiceDeathNotifier() { 675} 676 677void MediaPlayerService::Client::ServiceDeathNotifier::binderDied(const wp<IBinder>& /*who*/) { 678 sp<MediaPlayerBase> listener = mListener.promote(); 679 if (listener != NULL) { 680 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich); 681 } else { 682 ALOGW("listener for process %d death is gone", mWhich); 683 } 684} 685 686void MediaPlayerService::Client::ServiceDeathNotifier::serviceDied( 687 uint64_t /* cookie */, 688 const wp<::android::hidl::base::V1_0::IBase>& /* who */) { 689 sp<MediaPlayerBase> listener = mListener.promote(); 690 if (listener != NULL) { 691 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich); 692 } else { 693 ALOGW("listener for process %d death is gone", mWhich); 694 } 695} 696 697void MediaPlayerService::Client::ServiceDeathNotifier::unlinkToDeath() { 698 if (mService != nullptr) { 699 mService->unlinkToDeath(this); 700 mService = nullptr; 701 } else if (mOmx != nullptr) { 702 mOmx->unlinkToDeath(this); 703 mOmx = nullptr; 704 } 705} 706 707void MediaPlayerService::Client::clearDeathNotifiers() { 708 if (mExtractorDeathListener != nullptr) { 709 mExtractorDeathListener->unlinkToDeath(); 710 mExtractorDeathListener = nullptr; 711 } 712 if (mCodecDeathListener != nullptr) { 713 mCodecDeathListener->unlinkToDeath(); 714 mCodecDeathListener = nullptr; 715 } 716} 717 718sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre( 719 player_type playerType) 720{ 721 ALOGV("player type = %d", playerType); 722 clearDeathNotifiers(); 723 724 // create the right type of player 725 sp<MediaPlayerBase> p = createPlayer(playerType); 726 if (p == NULL) { 727 return p; 728 } 729 730 sp<IServiceManager> sm = defaultServiceManager(); 731 sp<IBinder> binder = sm->getService(String16("media.extractor")); 732 if (binder == NULL) { 733 ALOGE("extractor service not available"); 734 return NULL; 735 } 736 mExtractorDeathListener = new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH); 737 binder->linkToDeath(mExtractorDeathListener); 738 739 if (property_get_bool("persist.media.treble_omx", true)) { 740 // Treble IOmx 741 sp<IOmx> omx = IOmx::getService(); 742 if (omx == nullptr) { 743 ALOGE("Treble IOmx not available"); 744 return NULL; 745 } 746 mCodecDeathListener = new ServiceDeathNotifier(omx, p, MEDIACODEC_PROCESS_DEATH); 747 omx->linkToDeath(mCodecDeathListener, 0); 748 } else { 749 // Legacy IOMX 750 binder = sm->getService(String16("media.codec")); 751 if (binder == NULL) { 752 ALOGE("codec service not available"); 753 return NULL; 754 } 755 mCodecDeathListener = new ServiceDeathNotifier(binder, p, MEDIACODEC_PROCESS_DEATH); 756 binder->linkToDeath(mCodecDeathListener); 757 } 758 759 if (!p->hardwareOutput()) { 760 Mutex::Autolock l(mLock); 761 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(), 762 mPid, mAudioAttributes); 763 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput); 764 } 765 766 return p; 767} 768 769void MediaPlayerService::Client::setDataSource_post( 770 const sp<MediaPlayerBase>& p, 771 status_t status) 772{ 773 ALOGV(" setDataSource"); 774 mStatus = status; 775 if (mStatus != OK) { 776 ALOGE(" error: %d", mStatus); 777 return; 778 } 779 780 // Set the re-transmission endpoint if one was chosen. 781 if (mRetransmitEndpointValid) { 782 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint); 783 if (mStatus != NO_ERROR) { 784 ALOGE("setRetransmitEndpoint error: %d", mStatus); 785 } 786 } 787 788 if (mStatus == OK) { 789 mPlayer = p; 790 } 791} 792 793status_t MediaPlayerService::Client::setDataSource( 794 const sp<IMediaHTTPService> &httpService, 795 const char *url, 796 const KeyedVector<String8, String8> *headers) 797{ 798 ALOGV("setDataSource(%s)", url); 799 if (url == NULL) 800 return UNKNOWN_ERROR; 801 802 if ((strncmp(url, "http://", 7) == 0) || 803 (strncmp(url, "https://", 8) == 0) || 804 (strncmp(url, "rtsp://", 7) == 0)) { 805 if (!checkPermission("android.permission.INTERNET")) { 806 return PERMISSION_DENIED; 807 } 808 } 809 810 if (strncmp(url, "content://", 10) == 0) { 811 // get a filedescriptor for the content Uri and 812 // pass it to the setDataSource(fd) method 813 814 String16 url16(url); 815 int fd = android::openContentProviderFile(url16); 816 if (fd < 0) 817 { 818 ALOGE("Couldn't open fd for %s", url); 819 return UNKNOWN_ERROR; 820 } 821 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus 822 close(fd); 823 return mStatus; 824 } else { 825 player_type playerType = MediaPlayerFactory::getPlayerType(this, url); 826 sp<MediaPlayerBase> p = setDataSource_pre(playerType); 827 if (p == NULL) { 828 return NO_INIT; 829 } 830 831 setDataSource_post(p, p->setDataSource(httpService, url, headers)); 832 return mStatus; 833 } 834} 835 836status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length) 837{ 838 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld", 839 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length); 840 struct stat sb; 841 int ret = fstat(fd, &sb); 842 if (ret != 0) { 843 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno)); 844 return UNKNOWN_ERROR; 845 } 846 847 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev)); 848 ALOGV("st_mode = %u", sb.st_mode); 849 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid)); 850 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid)); 851 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size)); 852 853 if (offset >= sb.st_size) { 854 ALOGE("offset error"); 855 return UNKNOWN_ERROR; 856 } 857 if (offset + length > sb.st_size) { 858 length = sb.st_size - offset; 859 ALOGV("calculated length = %lld", (long long)length); 860 } 861 862 player_type playerType = MediaPlayerFactory::getPlayerType(this, 863 fd, 864 offset, 865 length); 866 sp<MediaPlayerBase> p = setDataSource_pre(playerType); 867 if (p == NULL) { 868 return NO_INIT; 869 } 870 871 // now set data source 872 setDataSource_post(p, p->setDataSource(fd, offset, length)); 873 return mStatus; 874} 875 876status_t MediaPlayerService::Client::setDataSource( 877 const sp<IStreamSource> &source) { 878 // create the right type of player 879 player_type playerType = MediaPlayerFactory::getPlayerType(this, source); 880 sp<MediaPlayerBase> p = setDataSource_pre(playerType); 881 if (p == NULL) { 882 return NO_INIT; 883 } 884 885 // now set data source 886 setDataSource_post(p, p->setDataSource(source)); 887 return mStatus; 888} 889 890status_t MediaPlayerService::Client::setDataSource( 891 const sp<IDataSource> &source) { 892 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source); 893 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource); 894 sp<MediaPlayerBase> p = setDataSource_pre(playerType); 895 if (p == NULL) { 896 return NO_INIT; 897 } 898 // now set data source 899 setDataSource_post(p, p->setDataSource(dataSource)); 900 return mStatus; 901} 902 903void MediaPlayerService::Client::disconnectNativeWindow() { 904 if (mConnectedWindow != NULL) { 905 status_t err = nativeWindowDisconnect( 906 mConnectedWindow.get(), "disconnectNativeWindow"); 907 908 if (err != OK) { 909 ALOGW("nativeWindowDisconnect returned an error: %s (%d)", 910 strerror(-err), err); 911 } 912 } 913 mConnectedWindow.clear(); 914} 915 916status_t MediaPlayerService::Client::setVideoSurfaceTexture( 917 const sp<IGraphicBufferProducer>& bufferProducer) 918{ 919 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get()); 920 sp<MediaPlayerBase> p = getPlayer(); 921 if (p == 0) return UNKNOWN_ERROR; 922 923 sp<IBinder> binder(IInterface::asBinder(bufferProducer)); 924 if (mConnectedWindowBinder == binder) { 925 return OK; 926 } 927 928 sp<ANativeWindow> anw; 929 if (bufferProducer != NULL) { 930 anw = new Surface(bufferProducer, true /* controlledByApp */); 931 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture"); 932 933 if (err != OK) { 934 ALOGE("setVideoSurfaceTexture failed: %d", err); 935 // Note that we must do the reset before disconnecting from the ANW. 936 // Otherwise queue/dequeue calls could be made on the disconnected 937 // ANW, which may result in errors. 938 reset(); 939 940 disconnectNativeWindow(); 941 942 return err; 943 } 944 } 945 946 // Note that we must set the player's new GraphicBufferProducer before 947 // disconnecting the old one. Otherwise queue/dequeue calls could be made 948 // on the disconnected ANW, which may result in errors. 949 status_t err = p->setVideoSurfaceTexture(bufferProducer); 950 951 disconnectNativeWindow(); 952 953 mConnectedWindow = anw; 954 955 if (err == OK) { 956 mConnectedWindowBinder = binder; 957 } else { 958 disconnectNativeWindow(); 959 } 960 961 return err; 962} 963 964status_t MediaPlayerService::Client::invoke(const Parcel& request, 965 Parcel *reply) 966{ 967 sp<MediaPlayerBase> p = getPlayer(); 968 if (p == NULL) return UNKNOWN_ERROR; 969 return p->invoke(request, reply); 970} 971 972// This call doesn't need to access the native player. 973status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter) 974{ 975 status_t status; 976 media::Metadata::Filter allow, drop; 977 978 if (unmarshallFilter(filter, &allow, &status) && 979 unmarshallFilter(filter, &drop, &status)) { 980 Mutex::Autolock lock(mLock); 981 982 mMetadataAllow = allow; 983 mMetadataDrop = drop; 984 } 985 return status; 986} 987 988status_t MediaPlayerService::Client::getMetadata( 989 bool update_only, bool /*apply_filter*/, Parcel *reply) 990{ 991 sp<MediaPlayerBase> player = getPlayer(); 992 if (player == 0) return UNKNOWN_ERROR; 993 994 status_t status; 995 // Placeholder for the return code, updated by the caller. 996 reply->writeInt32(-1); 997 998 media::Metadata::Filter ids; 999 1000 // We don't block notifications while we fetch the data. We clear 1001 // mMetadataUpdated first so we don't lose notifications happening 1002 // during the rest of this call. 1003 { 1004 Mutex::Autolock lock(mLock); 1005 if (update_only) { 1006 ids = mMetadataUpdated; 1007 } 1008 mMetadataUpdated.clear(); 1009 } 1010 1011 media::Metadata metadata(reply); 1012 1013 metadata.appendHeader(); 1014 status = player->getMetadata(ids, reply); 1015 1016 if (status != OK) { 1017 metadata.resetParcel(); 1018 ALOGE("getMetadata failed %d", status); 1019 return status; 1020 } 1021 1022 // FIXME: Implement filtering on the result. Not critical since 1023 // filtering takes place on the update notifications already. This 1024 // would be when all the metadata are fetch and a filter is set. 1025 1026 // Everything is fine, update the metadata length. 1027 metadata.updateLength(); 1028 return OK; 1029} 1030 1031status_t MediaPlayerService::Client::setBufferingSettings( 1032 const BufferingSettings& buffering) 1033{ 1034 ALOGV("[%d] setBufferingSettings{%s}", 1035 mConnId, buffering.toString().string()); 1036 sp<MediaPlayerBase> p = getPlayer(); 1037 if (p == 0) return UNKNOWN_ERROR; 1038 return p->setBufferingSettings(buffering); 1039} 1040 1041status_t MediaPlayerService::Client::getDefaultBufferingSettings( 1042 BufferingSettings* buffering /* nonnull */) 1043{ 1044 sp<MediaPlayerBase> p = getPlayer(); 1045 // TODO: create mPlayer on demand. 1046 if (p == 0) return UNKNOWN_ERROR; 1047 status_t ret = p->getDefaultBufferingSettings(buffering); 1048 if (ret == NO_ERROR) { 1049 ALOGV("[%d] getDefaultBufferingSettings{%s}", 1050 mConnId, buffering->toString().string()); 1051 } else { 1052 ALOGV("[%d] getDefaultBufferingSettings returned %d", mConnId, ret); 1053 } 1054 return ret; 1055} 1056 1057status_t MediaPlayerService::Client::prepareAsync() 1058{ 1059 ALOGV("[%d] prepareAsync", mConnId); 1060 sp<MediaPlayerBase> p = getPlayer(); 1061 if (p == 0) return UNKNOWN_ERROR; 1062 status_t ret = p->prepareAsync(); 1063#if CALLBACK_ANTAGONIZER 1064 ALOGD("start Antagonizer"); 1065 if (ret == NO_ERROR) mAntagonizer->start(); 1066#endif 1067 return ret; 1068} 1069 1070status_t MediaPlayerService::Client::start() 1071{ 1072 ALOGV("[%d] start", mConnId); 1073 sp<MediaPlayerBase> p = getPlayer(); 1074 if (p == 0) return UNKNOWN_ERROR; 1075 p->setLooping(mLoop); 1076 return p->start(); 1077} 1078 1079status_t MediaPlayerService::Client::stop() 1080{ 1081 ALOGV("[%d] stop", mConnId); 1082 sp<MediaPlayerBase> p = getPlayer(); 1083 if (p == 0) return UNKNOWN_ERROR; 1084 return p->stop(); 1085} 1086 1087status_t MediaPlayerService::Client::pause() 1088{ 1089 ALOGV("[%d] pause", mConnId); 1090 sp<MediaPlayerBase> p = getPlayer(); 1091 if (p == 0) return UNKNOWN_ERROR; 1092 return p->pause(); 1093} 1094 1095status_t MediaPlayerService::Client::isPlaying(bool* state) 1096{ 1097 *state = false; 1098 sp<MediaPlayerBase> p = getPlayer(); 1099 if (p == 0) return UNKNOWN_ERROR; 1100 *state = p->isPlaying(); 1101 ALOGV("[%d] isPlaying: %d", mConnId, *state); 1102 return NO_ERROR; 1103} 1104 1105status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate) 1106{ 1107 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)", 1108 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode); 1109 sp<MediaPlayerBase> p = getPlayer(); 1110 if (p == 0) return UNKNOWN_ERROR; 1111 return p->setPlaybackSettings(rate); 1112} 1113 1114status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */) 1115{ 1116 sp<MediaPlayerBase> p = getPlayer(); 1117 if (p == 0) return UNKNOWN_ERROR; 1118 status_t ret = p->getPlaybackSettings(rate); 1119 if (ret == NO_ERROR) { 1120 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)", 1121 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode); 1122 } else { 1123 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret); 1124 } 1125 return ret; 1126} 1127 1128status_t MediaPlayerService::Client::setSyncSettings( 1129 const AVSyncSettings& sync, float videoFpsHint) 1130{ 1131 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)", 1132 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint); 1133 sp<MediaPlayerBase> p = getPlayer(); 1134 if (p == 0) return UNKNOWN_ERROR; 1135 return p->setSyncSettings(sync, videoFpsHint); 1136} 1137 1138status_t MediaPlayerService::Client::getSyncSettings( 1139 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */) 1140{ 1141 sp<MediaPlayerBase> p = getPlayer(); 1142 if (p == 0) return UNKNOWN_ERROR; 1143 status_t ret = p->getSyncSettings(sync, videoFps); 1144 if (ret == NO_ERROR) { 1145 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)", 1146 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps); 1147 } else { 1148 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret); 1149 } 1150 return ret; 1151} 1152 1153status_t MediaPlayerService::Client::getCurrentPosition(int *msec) 1154{ 1155 ALOGV("getCurrentPosition"); 1156 sp<MediaPlayerBase> p = getPlayer(); 1157 if (p == 0) return UNKNOWN_ERROR; 1158 status_t ret = p->getCurrentPosition(msec); 1159 if (ret == NO_ERROR) { 1160 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec); 1161 } else { 1162 ALOGE("getCurrentPosition returned %d", ret); 1163 } 1164 return ret; 1165} 1166 1167status_t MediaPlayerService::Client::getDuration(int *msec) 1168{ 1169 ALOGV("getDuration"); 1170 sp<MediaPlayerBase> p = getPlayer(); 1171 if (p == 0) return UNKNOWN_ERROR; 1172 status_t ret = p->getDuration(msec); 1173 if (ret == NO_ERROR) { 1174 ALOGV("[%d] getDuration = %d", mConnId, *msec); 1175 } else { 1176 ALOGE("getDuration returned %d", ret); 1177 } 1178 return ret; 1179} 1180 1181status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) { 1182 ALOGV("setNextPlayer"); 1183 Mutex::Autolock l(mLock); 1184 sp<Client> c = static_cast<Client*>(player.get()); 1185 if (c != NULL && !mService->hasClient(c)) { 1186 return BAD_VALUE; 1187 } 1188 1189 mNextClient = c; 1190 1191 if (c != NULL) { 1192 if (mAudioOutput != NULL) { 1193 mAudioOutput->setNextOutput(c->mAudioOutput); 1194 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) { 1195 ALOGE("no current audio output"); 1196 } 1197 1198 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) { 1199 mPlayer->setNextPlayer(mNextClient->getPlayer()); 1200 } 1201 } 1202 1203 return OK; 1204} 1205 1206VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper( 1207 const sp<VolumeShaper::Configuration>& configuration, 1208 const sp<VolumeShaper::Operation>& operation) { 1209 // for hardware output, call player instead 1210 ALOGV("Client::applyVolumeShaper(%p)", this); 1211 sp<MediaPlayerBase> p = getPlayer(); 1212 { 1213 Mutex::Autolock l(mLock); 1214 if (p != 0 && p->hardwareOutput()) { 1215 // TODO: investigate internal implementation 1216 return VolumeShaper::Status(INVALID_OPERATION); 1217 } 1218 if (mAudioOutput.get() != nullptr) { 1219 return mAudioOutput->applyVolumeShaper(configuration, operation); 1220 } 1221 } 1222 return VolumeShaper::Status(INVALID_OPERATION); 1223} 1224 1225sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) { 1226 // for hardware output, call player instead 1227 ALOGV("Client::getVolumeShaperState(%p)", this); 1228 sp<MediaPlayerBase> p = getPlayer(); 1229 { 1230 Mutex::Autolock l(mLock); 1231 if (p != 0 && p->hardwareOutput()) { 1232 // TODO: investigate internal implementation. 1233 return nullptr; 1234 } 1235 if (mAudioOutput.get() != nullptr) { 1236 return mAudioOutput->getVolumeShaperState(id); 1237 } 1238 } 1239 return nullptr; 1240} 1241 1242status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode) 1243{ 1244 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode); 1245 sp<MediaPlayerBase> p = getPlayer(); 1246 if (p == 0) return UNKNOWN_ERROR; 1247 return p->seekTo(msec, mode); 1248} 1249 1250status_t MediaPlayerService::Client::reset() 1251{ 1252 ALOGV("[%d] reset", mConnId); 1253 mRetransmitEndpointValid = false; 1254 sp<MediaPlayerBase> p = getPlayer(); 1255 if (p == 0) return UNKNOWN_ERROR; 1256 return p->reset(); 1257} 1258 1259status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type) 1260{ 1261 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type); 1262 // TODO: for hardware output, call player instead 1263 Mutex::Autolock l(mLock); 1264 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type); 1265 return NO_ERROR; 1266} 1267 1268status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel) 1269{ 1270 if (mAudioAttributes != NULL) { free(mAudioAttributes); } 1271 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t)); 1272 if (mAudioAttributes == NULL) { 1273 return NO_MEMORY; 1274 } 1275 unmarshallAudioAttributes(parcel, mAudioAttributes); 1276 1277 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s", 1278 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags, 1279 mAudioAttributes->tags); 1280 1281 if (mAudioOutput != 0) { 1282 mAudioOutput->setAudioAttributes(mAudioAttributes); 1283 } 1284 return NO_ERROR; 1285} 1286 1287status_t MediaPlayerService::Client::setLooping(int loop) 1288{ 1289 ALOGV("[%d] setLooping(%d)", mConnId, loop); 1290 mLoop = loop; 1291 sp<MediaPlayerBase> p = getPlayer(); 1292 if (p != 0) return p->setLooping(loop); 1293 return NO_ERROR; 1294} 1295 1296status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume) 1297{ 1298 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume); 1299 1300 // for hardware output, call player instead 1301 sp<MediaPlayerBase> p = getPlayer(); 1302 { 1303 Mutex::Autolock l(mLock); 1304 if (p != 0 && p->hardwareOutput()) { 1305 MediaPlayerHWInterface* hwp = 1306 reinterpret_cast<MediaPlayerHWInterface*>(p.get()); 1307 return hwp->setVolume(leftVolume, rightVolume); 1308 } else { 1309 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume); 1310 return NO_ERROR; 1311 } 1312 } 1313 1314 return NO_ERROR; 1315} 1316 1317status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level) 1318{ 1319 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level); 1320 Mutex::Autolock l(mLock); 1321 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level); 1322 return NO_ERROR; 1323} 1324 1325status_t MediaPlayerService::Client::attachAuxEffect(int effectId) 1326{ 1327 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId); 1328 Mutex::Autolock l(mLock); 1329 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId); 1330 return NO_ERROR; 1331} 1332 1333status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) { 1334 ALOGV("[%d] setParameter(%d)", mConnId, key); 1335 switch (key) { 1336 case KEY_PARAMETER_AUDIO_ATTRIBUTES: 1337 { 1338 Mutex::Autolock l(mLock); 1339 return setAudioAttributes_l(request); 1340 } 1341 default: 1342 sp<MediaPlayerBase> p = getPlayer(); 1343 if (p == 0) { return UNKNOWN_ERROR; } 1344 return p->setParameter(key, request); 1345 } 1346} 1347 1348status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) { 1349 ALOGV("[%d] getParameter(%d)", mConnId, key); 1350 sp<MediaPlayerBase> p = getPlayer(); 1351 if (p == 0) return UNKNOWN_ERROR; 1352 return p->getParameter(key, reply); 1353} 1354 1355status_t MediaPlayerService::Client::setRetransmitEndpoint( 1356 const struct sockaddr_in* endpoint) { 1357 1358 if (NULL != endpoint) { 1359 uint32_t a = ntohl(endpoint->sin_addr.s_addr); 1360 uint16_t p = ntohs(endpoint->sin_port); 1361 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId, 1362 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p); 1363 } else { 1364 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId); 1365 } 1366 1367 sp<MediaPlayerBase> p = getPlayer(); 1368 1369 // Right now, the only valid time to set a retransmit endpoint is before 1370 // player selection has been made (since the presence or absence of a 1371 // retransmit endpoint is going to determine which player is selected during 1372 // setDataSource). 1373 if (p != 0) return INVALID_OPERATION; 1374 1375 if (NULL != endpoint) { 1376 mRetransmitEndpoint = *endpoint; 1377 mRetransmitEndpointValid = true; 1378 } else { 1379 mRetransmitEndpointValid = false; 1380 } 1381 1382 return NO_ERROR; 1383} 1384 1385status_t MediaPlayerService::Client::getRetransmitEndpoint( 1386 struct sockaddr_in* endpoint) 1387{ 1388 if (NULL == endpoint) 1389 return BAD_VALUE; 1390 1391 sp<MediaPlayerBase> p = getPlayer(); 1392 1393 if (p != NULL) 1394 return p->getRetransmitEndpoint(endpoint); 1395 1396 if (!mRetransmitEndpointValid) 1397 return NO_INIT; 1398 1399 *endpoint = mRetransmitEndpoint; 1400 1401 return NO_ERROR; 1402} 1403 1404void MediaPlayerService::Client::notify( 1405 void* cookie, int msg, int ext1, int ext2, const Parcel *obj) 1406{ 1407 Client* client = static_cast<Client*>(cookie); 1408 if (client == NULL) { 1409 return; 1410 } 1411 1412 sp<IMediaPlayerClient> c; 1413 sp<Client> nextClient; 1414 status_t errStartNext = NO_ERROR; 1415 { 1416 Mutex::Autolock l(client->mLock); 1417 c = client->mClient; 1418 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) { 1419 nextClient = client->mNextClient; 1420 1421 if (client->mAudioOutput != NULL) 1422 client->mAudioOutput->switchToNextOutput(); 1423 1424 errStartNext = nextClient->start(); 1425 } 1426 } 1427 1428 if (nextClient != NULL) { 1429 sp<IMediaPlayerClient> nc; 1430 { 1431 Mutex::Autolock l(nextClient->mLock); 1432 nc = nextClient->mClient; 1433 } 1434 if (nc != NULL) { 1435 if (errStartNext == NO_ERROR) { 1436 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj); 1437 } else { 1438 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj); 1439 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext); 1440 } 1441 } 1442 } 1443 1444 if (MEDIA_INFO == msg && 1445 MEDIA_INFO_METADATA_UPDATE == ext1) { 1446 const media::Metadata::Type metadata_type = ext2; 1447 1448 if(client->shouldDropMetadata(metadata_type)) { 1449 return; 1450 } 1451 1452 // Update the list of metadata that have changed. getMetadata 1453 // also access mMetadataUpdated and clears it. 1454 client->addNewMetadataUpdate(metadata_type); 1455 } 1456 1457 if (c != NULL) { 1458 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2); 1459 c->notify(msg, ext1, ext2, obj); 1460 } 1461} 1462 1463 1464bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const 1465{ 1466 Mutex::Autolock lock(mLock); 1467 1468 if (findMetadata(mMetadataDrop, code)) { 1469 return true; 1470 } 1471 1472 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) { 1473 return false; 1474 } else { 1475 return true; 1476 } 1477} 1478 1479 1480void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) { 1481 Mutex::Autolock lock(mLock); 1482 if (mMetadataUpdated.indexOf(metadata_type) < 0) { 1483 mMetadataUpdated.add(metadata_type); 1484 } 1485} 1486 1487// Modular DRM 1488status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16], 1489 const Vector<uint8_t>& drmSessionId) 1490{ 1491 ALOGV("[%d] prepareDrm", mConnId); 1492 sp<MediaPlayerBase> p = getPlayer(); 1493 if (p == 0) return UNKNOWN_ERROR; 1494 1495 status_t ret = p->prepareDrm(uuid, drmSessionId); 1496 ALOGV("prepareDrm ret: %d", ret); 1497 1498 return ret; 1499} 1500 1501status_t MediaPlayerService::Client::releaseDrm() 1502{ 1503 ALOGV("[%d] releaseDrm", mConnId); 1504 sp<MediaPlayerBase> p = getPlayer(); 1505 if (p == 0) return UNKNOWN_ERROR; 1506 1507 status_t ret = p->releaseDrm(); 1508 ALOGV("releaseDrm ret: %d", ret); 1509 1510 return ret; 1511} 1512 1513#if CALLBACK_ANTAGONIZER 1514const int Antagonizer::interval = 10000; // 10 msecs 1515 1516Antagonizer::Antagonizer(notify_callback_f cb, void* client) : 1517 mExit(false), mActive(false), mClient(client), mCb(cb) 1518{ 1519 createThread(callbackThread, this); 1520} 1521 1522void Antagonizer::kill() 1523{ 1524 Mutex::Autolock _l(mLock); 1525 mActive = false; 1526 mExit = true; 1527 mCondition.wait(mLock); 1528} 1529 1530int Antagonizer::callbackThread(void* user) 1531{ 1532 ALOGD("Antagonizer started"); 1533 Antagonizer* p = reinterpret_cast<Antagonizer*>(user); 1534 while (!p->mExit) { 1535 if (p->mActive) { 1536 ALOGV("send event"); 1537 p->mCb(p->mClient, 0, 0, 0); 1538 } 1539 usleep(interval); 1540 } 1541 Mutex::Autolock _l(p->mLock); 1542 p->mCondition.signal(); 1543 ALOGD("Antagonizer stopped"); 1544 return 0; 1545} 1546#endif 1547 1548#undef LOG_TAG 1549#define LOG_TAG "AudioSink" 1550MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid, 1551 const audio_attributes_t* attr) 1552 : mCallback(NULL), 1553 mCallbackCookie(NULL), 1554 mCallbackData(NULL), 1555 mStreamType(AUDIO_STREAM_MUSIC), 1556 mLeftVolume(1.0), 1557 mRightVolume(1.0), 1558 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT), 1559 mSampleRateHz(0), 1560 mMsecsPerFrame(0), 1561 mFrameSize(0), 1562 mSessionId(sessionId), 1563 mUid(uid), 1564 mPid(pid), 1565 mSendLevel(0.0), 1566 mAuxEffectId(0), 1567 mFlags(AUDIO_OUTPUT_FLAG_NONE), 1568 mVolumeHandler(new VolumeHandler()) 1569{ 1570 ALOGV("AudioOutput(%d)", sessionId); 1571 if (attr != NULL) { 1572 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t)); 1573 if (mAttributes != NULL) { 1574 memcpy(mAttributes, attr, sizeof(audio_attributes_t)); 1575 mStreamType = audio_attributes_to_stream_type(attr); 1576 } 1577 } else { 1578 mAttributes = NULL; 1579 } 1580 1581 setMinBufferCount(); 1582} 1583 1584MediaPlayerService::AudioOutput::~AudioOutput() 1585{ 1586 close(); 1587 free(mAttributes); 1588 delete mCallbackData; 1589} 1590 1591//static 1592void MediaPlayerService::AudioOutput::setMinBufferCount() 1593{ 1594 char value[PROPERTY_VALUE_MAX]; 1595 if (property_get("ro.kernel.qemu", value, 0)) { 1596 mIsOnEmulator = true; 1597 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator 1598 } 1599} 1600 1601// static 1602bool MediaPlayerService::AudioOutput::isOnEmulator() 1603{ 1604 setMinBufferCount(); // benign race wrt other threads 1605 return mIsOnEmulator; 1606} 1607 1608// static 1609int MediaPlayerService::AudioOutput::getMinBufferCount() 1610{ 1611 setMinBufferCount(); // benign race wrt other threads 1612 return mMinBufferCount; 1613} 1614 1615ssize_t MediaPlayerService::AudioOutput::bufferSize() const 1616{ 1617 Mutex::Autolock lock(mLock); 1618 if (mTrack == 0) return NO_INIT; 1619 return mTrack->frameCount() * mFrameSize; 1620} 1621 1622ssize_t MediaPlayerService::AudioOutput::frameCount() const 1623{ 1624 Mutex::Autolock lock(mLock); 1625 if (mTrack == 0) return NO_INIT; 1626 return mTrack->frameCount(); 1627} 1628 1629ssize_t MediaPlayerService::AudioOutput::channelCount() const 1630{ 1631 Mutex::Autolock lock(mLock); 1632 if (mTrack == 0) return NO_INIT; 1633 return mTrack->channelCount(); 1634} 1635 1636ssize_t MediaPlayerService::AudioOutput::frameSize() const 1637{ 1638 Mutex::Autolock lock(mLock); 1639 if (mTrack == 0) return NO_INIT; 1640 return mFrameSize; 1641} 1642 1643uint32_t MediaPlayerService::AudioOutput::latency () const 1644{ 1645 Mutex::Autolock lock(mLock); 1646 if (mTrack == 0) return 0; 1647 return mTrack->latency(); 1648} 1649 1650float MediaPlayerService::AudioOutput::msecsPerFrame() const 1651{ 1652 Mutex::Autolock lock(mLock); 1653 return mMsecsPerFrame; 1654} 1655 1656status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const 1657{ 1658 Mutex::Autolock lock(mLock); 1659 if (mTrack == 0) return NO_INIT; 1660 return mTrack->getPosition(position); 1661} 1662 1663status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const 1664{ 1665 Mutex::Autolock lock(mLock); 1666 if (mTrack == 0) return NO_INIT; 1667 return mTrack->getTimestamp(ts); 1668} 1669 1670// TODO: Remove unnecessary calls to getPlayedOutDurationUs() 1671// as it acquires locks and may query the audio driver. 1672// 1673// Some calls could conceivably retrieve extrapolated data instead of 1674// accessing getTimestamp() or getPosition() every time a data buffer with 1675// a media time is received. 1676// 1677// Calculate duration of played samples if played at normal rate (i.e., 1.0). 1678int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const 1679{ 1680 Mutex::Autolock lock(mLock); 1681 if (mTrack == 0 || mSampleRateHz == 0) { 1682 return 0; 1683 } 1684 1685 uint32_t numFramesPlayed; 1686 int64_t numFramesPlayedAtUs; 1687 AudioTimestamp ts; 1688 1689 status_t res = mTrack->getTimestamp(ts); 1690 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks. 1691 numFramesPlayed = ts.mPosition; 1692 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000; 1693 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs); 1694 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track 1695 numFramesPlayed = 0; 1696 numFramesPlayedAtUs = nowUs; 1697 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld", 1698 // numFramesPlayed, (long long)numFramesPlayedAtUs); 1699 } else { // case 3: transitory at new track or audio fast tracks. 1700 res = mTrack->getPosition(&numFramesPlayed); 1701 CHECK_EQ(res, (status_t)OK); 1702 numFramesPlayedAtUs = nowUs; 1703 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */ 1704 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs); 1705 } 1706 1707 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test 1708 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours. 1709 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz) 1710 + nowUs - numFramesPlayedAtUs; 1711 if (durationUs < 0) { 1712 // Occurs when numFramesPlayed position is very small and the following: 1713 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and 1714 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed. 1715 // (2) In case 3, using getPosition and adding mAudioSink->latency() to 1716 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed. 1717 // 1718 // Both of these are transitory conditions. 1719 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs); 1720 durationUs = 0; 1721 } 1722 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)", 1723 (long long)durationUs, (long long)nowUs, 1724 numFramesPlayed, (long long)numFramesPlayedAtUs); 1725 return durationUs; 1726} 1727 1728status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const 1729{ 1730 Mutex::Autolock lock(mLock); 1731 if (mTrack == 0) return NO_INIT; 1732 ExtendedTimestamp ets; 1733 status_t status = mTrack->getTimestamp(&ets); 1734 if (status == OK || status == WOULD_BLOCK) { 1735 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT]; 1736 } 1737 return status; 1738} 1739 1740status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs) 1741{ 1742 Mutex::Autolock lock(mLock); 1743 if (mTrack == 0) return NO_INIT; 1744 return mTrack->setParameters(keyValuePairs); 1745} 1746 1747String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys) 1748{ 1749 Mutex::Autolock lock(mLock); 1750 if (mTrack == 0) return String8::empty(); 1751 return mTrack->getParameters(keys); 1752} 1753 1754void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) { 1755 Mutex::Autolock lock(mLock); 1756 if (attributes == NULL) { 1757 free(mAttributes); 1758 mAttributes = NULL; 1759 } else { 1760 if (mAttributes == NULL) { 1761 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t)); 1762 } 1763 memcpy(mAttributes, attributes, sizeof(audio_attributes_t)); 1764 mStreamType = audio_attributes_to_stream_type(attributes); 1765 } 1766} 1767 1768void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType) 1769{ 1770 Mutex::Autolock lock(mLock); 1771 // do not allow direct stream type modification if attributes have been set 1772 if (mAttributes == NULL) { 1773 mStreamType = streamType; 1774 } 1775} 1776 1777void MediaPlayerService::AudioOutput::deleteRecycledTrack_l() 1778{ 1779 ALOGV("deleteRecycledTrack_l"); 1780 if (mRecycledTrack != 0) { 1781 1782 if (mCallbackData != NULL) { 1783 mCallbackData->setOutput(NULL); 1784 mCallbackData->endTrackSwitch(); 1785 } 1786 1787 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) { 1788 int32_t msec = 0; 1789 if (!mRecycledTrack->stopped()) { // check if active 1790 (void)mRecycledTrack->pendingDuration(&msec); 1791 } 1792 mRecycledTrack->stop(); // ensure full data drain 1793 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec); 1794 if (msec > 0) { 1795 static const int32_t WAIT_LIMIT_MS = 3000; 1796 if (msec > WAIT_LIMIT_MS) { 1797 msec = WAIT_LIMIT_MS; 1798 } 1799 usleep(msec * 1000LL); 1800 } 1801 } 1802 // An offloaded track isn't flushed because the STREAM_END is reported 1803 // slightly prematurely to allow time for the gapless track switch 1804 // but this means that if we decide not to recycle the track there 1805 // could be a small amount of residual data still playing. We leave 1806 // AudioFlinger to drain the track. 1807 1808 mRecycledTrack.clear(); 1809 close_l(); 1810 delete mCallbackData; 1811 mCallbackData = NULL; 1812 } 1813} 1814 1815void MediaPlayerService::AudioOutput::close_l() 1816{ 1817 mTrack.clear(); 1818} 1819 1820status_t MediaPlayerService::AudioOutput::open( 1821 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask, 1822 audio_format_t format, int bufferCount, 1823 AudioCallback cb, void *cookie, 1824 audio_output_flags_t flags, 1825 const audio_offload_info_t *offloadInfo, 1826 bool doNotReconnect, 1827 uint32_t suggestedFrameCount) 1828{ 1829 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask, 1830 format, bufferCount, mSessionId, flags); 1831 1832 // offloading is only supported in callback mode for now. 1833 // offloadInfo must be present if offload flag is set 1834 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) && 1835 ((cb == NULL) || (offloadInfo == NULL))) { 1836 return BAD_VALUE; 1837 } 1838 1839 // compute frame count for the AudioTrack internal buffer 1840 size_t frameCount; 1841 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) { 1842 frameCount = 0; // AudioTrack will get frame count from AudioFlinger 1843 } else { 1844 // try to estimate the buffer processing fetch size from AudioFlinger. 1845 // framesPerBuffer is approximate and generally correct, except when it's not :-). 1846 uint32_t afSampleRate; 1847 size_t afFrameCount; 1848 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) { 1849 return NO_INIT; 1850 } 1851 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) { 1852 return NO_INIT; 1853 } 1854 const size_t framesPerBuffer = 1855 (unsigned long long)sampleRate * afFrameCount / afSampleRate; 1856 1857 if (bufferCount == 0) { 1858 // use suggestedFrameCount 1859 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer; 1860 } 1861 // Check argument bufferCount against the mininum buffer count 1862 if (bufferCount != 0 && bufferCount < mMinBufferCount) { 1863 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount); 1864 bufferCount = mMinBufferCount; 1865 } 1866 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger 1867 // which will be the minimum size permitted. 1868 frameCount = bufferCount * framesPerBuffer; 1869 } 1870 1871 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) { 1872 channelMask = audio_channel_out_mask_from_count(channelCount); 1873 if (0 == channelMask) { 1874 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount); 1875 return NO_INIT; 1876 } 1877 } 1878 1879 Mutex::Autolock lock(mLock); 1880 mCallback = cb; 1881 mCallbackCookie = cookie; 1882 1883 // Check whether we can recycle the track 1884 bool reuse = false; 1885 bool bothOffloaded = false; 1886 1887 if (mRecycledTrack != 0) { 1888 // check whether we are switching between two offloaded tracks 1889 bothOffloaded = (flags & mRecycledTrack->getFlags() 1890 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0; 1891 1892 // check if the existing track can be reused as-is, or if a new track needs to be created. 1893 reuse = true; 1894 1895 if ((mCallbackData == NULL && mCallback != NULL) || 1896 (mCallbackData != NULL && mCallback == NULL)) { 1897 // recycled track uses callbacks but the caller wants to use writes, or vice versa 1898 ALOGV("can't chain callback and write"); 1899 reuse = false; 1900 } else if ((mRecycledTrack->getSampleRate() != sampleRate) || 1901 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) { 1902 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch", 1903 mRecycledTrack->getSampleRate(), sampleRate, 1904 mRecycledTrack->channelCount(), channelCount); 1905 reuse = false; 1906 } else if (flags != mFlags) { 1907 ALOGV("output flags differ %08x/%08x", flags, mFlags); 1908 reuse = false; 1909 } else if (mRecycledTrack->format() != format) { 1910 reuse = false; 1911 } 1912 } else { 1913 ALOGV("no track available to recycle"); 1914 } 1915 1916 ALOGV_IF(bothOffloaded, "both tracks offloaded"); 1917 1918 // If we can't recycle and both tracks are offloaded 1919 // we must close the previous output before opening a new one 1920 if (bothOffloaded && !reuse) { 1921 ALOGV("both offloaded and not recycling"); 1922 deleteRecycledTrack_l(); 1923 } 1924 1925 sp<AudioTrack> t; 1926 CallbackData *newcbd = NULL; 1927 1928 // We don't attempt to create a new track if we are recycling an 1929 // offloaded track. But, if we are recycling a non-offloaded or we 1930 // are switching where one is offloaded and one isn't then we create 1931 // the new track in advance so that we can read additional stream info 1932 1933 if (!(reuse && bothOffloaded)) { 1934 ALOGV("creating new AudioTrack"); 1935 1936 if (mCallback != NULL) { 1937 newcbd = new CallbackData(this); 1938 t = new AudioTrack( 1939 mStreamType, 1940 sampleRate, 1941 format, 1942 channelMask, 1943 frameCount, 1944 flags, 1945 CallbackWrapper, 1946 newcbd, 1947 0, // notification frames 1948 mSessionId, 1949 AudioTrack::TRANSFER_CALLBACK, 1950 offloadInfo, 1951 mUid, 1952 mPid, 1953 mAttributes, 1954 doNotReconnect); 1955 } else { 1956 // TODO: Due to buffer memory concerns, we use a max target playback speed 1957 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed), 1958 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed. 1959 const float targetSpeed = 1960 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed); 1961 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed, 1962 "track target speed:%f clamped from playback speed:%f", 1963 targetSpeed, mPlaybackRate.mSpeed); 1964 t = new AudioTrack( 1965 mStreamType, 1966 sampleRate, 1967 format, 1968 channelMask, 1969 frameCount, 1970 flags, 1971 NULL, // callback 1972 NULL, // user data 1973 0, // notification frames 1974 mSessionId, 1975 AudioTrack::TRANSFER_DEFAULT, 1976 NULL, // offload info 1977 mUid, 1978 mPid, 1979 mAttributes, 1980 doNotReconnect, 1981 targetSpeed); 1982 } 1983 1984 if ((t == 0) || (t->initCheck() != NO_ERROR)) { 1985 ALOGE("Unable to create audio track"); 1986 delete newcbd; 1987 // t goes out of scope, so reference count drops to zero 1988 return NO_INIT; 1989 } else { 1990 // successful AudioTrack initialization implies a legacy stream type was generated 1991 // from the audio attributes 1992 mStreamType = t->streamType(); 1993 } 1994 } 1995 1996 if (reuse) { 1997 CHECK(mRecycledTrack != NULL); 1998 1999 if (!bothOffloaded) { 2000 if (mRecycledTrack->frameCount() != t->frameCount()) { 2001 ALOGV("framecount differs: %zu/%zu frames", 2002 mRecycledTrack->frameCount(), t->frameCount()); 2003 reuse = false; 2004 } 2005 } 2006 2007 if (reuse) { 2008 ALOGV("chaining to next output and recycling track"); 2009 close_l(); 2010 mTrack = mRecycledTrack; 2011 mRecycledTrack.clear(); 2012 if (mCallbackData != NULL) { 2013 mCallbackData->setOutput(this); 2014 } 2015 delete newcbd; 2016 return updateTrack(); 2017 } 2018 } 2019 2020 // we're not going to reuse the track, unblock and flush it 2021 // this was done earlier if both tracks are offloaded 2022 if (!bothOffloaded) { 2023 deleteRecycledTrack_l(); 2024 } 2025 2026 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL))); 2027 2028 mCallbackData = newcbd; 2029 ALOGV("setVolume"); 2030 t->setVolume(mLeftVolume, mRightVolume); 2031 2032 // Dispatch any queued VolumeShapers when the track was not open. 2033 mVolumeHandler->forall([&t](const sp<VolumeShaper::Configuration> &configuration, 2034 const sp<VolumeShaper::Operation> &operation) -> VolumeShaper::Status { 2035 return t->applyVolumeShaper(configuration, operation); 2036 }); 2037 mVolumeHandler->reset(); // After dispatching, clear VolumeShaper queue. 2038 2039 mSampleRateHz = sampleRate; 2040 mFlags = flags; 2041 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate); 2042 mFrameSize = t->frameSize(); 2043 mTrack = t; 2044 2045 return updateTrack(); 2046} 2047 2048status_t MediaPlayerService::AudioOutput::updateTrack() { 2049 if (mTrack == NULL) { 2050 return NO_ERROR; 2051 } 2052 2053 status_t res = NO_ERROR; 2054 // Note some output devices may give us a direct track even though we don't specify it. 2055 // Example: Line application b/17459982. 2056 if ((mTrack->getFlags() 2057 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) { 2058 res = mTrack->setPlaybackRate(mPlaybackRate); 2059 if (res == NO_ERROR) { 2060 mTrack->setAuxEffectSendLevel(mSendLevel); 2061 res = mTrack->attachAuxEffect(mAuxEffectId); 2062 } 2063 } 2064 ALOGV("updateTrack() DONE status %d", res); 2065 return res; 2066} 2067 2068status_t MediaPlayerService::AudioOutput::start() 2069{ 2070 ALOGV("start"); 2071 Mutex::Autolock lock(mLock); 2072 if (mCallbackData != NULL) { 2073 mCallbackData->endTrackSwitch(); 2074 } 2075 if (mTrack != 0) { 2076 mTrack->setVolume(mLeftVolume, mRightVolume); 2077 mTrack->setAuxEffectSendLevel(mSendLevel); 2078 return mTrack->start(); 2079 } 2080 return NO_INIT; 2081} 2082 2083void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) { 2084 Mutex::Autolock lock(mLock); 2085 mNextOutput = nextOutput; 2086} 2087 2088void MediaPlayerService::AudioOutput::switchToNextOutput() { 2089 ALOGV("switchToNextOutput"); 2090 2091 // Try to acquire the callback lock before moving track (without incurring deadlock). 2092 const unsigned kMaxSwitchTries = 100; 2093 Mutex::Autolock lock(mLock); 2094 for (unsigned tries = 0;;) { 2095 if (mTrack == 0) { 2096 return; 2097 } 2098 if (mNextOutput != NULL && mNextOutput != this) { 2099 if (mCallbackData != NULL) { 2100 // two alternative approaches 2101#if 1 2102 CallbackData *callbackData = mCallbackData; 2103 mLock.unlock(); 2104 // proper acquisition sequence 2105 callbackData->lock(); 2106 mLock.lock(); 2107 // Caution: it is unlikely that someone deleted our callback or changed our target 2108 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) { 2109 // fatal if we are starved out. 2110 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries, 2111 "switchToNextOutput() cannot obtain correct lock sequence"); 2112 callbackData->unlock(); 2113 continue; 2114 } 2115 callbackData->mSwitching = true; // begin track switch 2116 callbackData->setOutput(NULL); 2117#else 2118 // tryBeginTrackSwitch() returns false if the callback has the lock. 2119 if (!mCallbackData->tryBeginTrackSwitch()) { 2120 // fatal if we are starved out. 2121 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries, 2122 "switchToNextOutput() cannot obtain callback lock"); 2123 mLock.unlock(); 2124 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput 2125 mLock.lock(); 2126 continue; 2127 } 2128#endif 2129 } 2130 2131 Mutex::Autolock nextLock(mNextOutput->mLock); 2132 2133 // If the next output track is not NULL, then it has been 2134 // opened already for playback. 2135 // This is possible even without the next player being started, 2136 // for example, the next player could be prepared and seeked. 2137 // 2138 // Presuming it isn't advisable to force the track over. 2139 if (mNextOutput->mTrack == NULL) { 2140 ALOGD("Recycling track for gapless playback"); 2141 delete mNextOutput->mCallbackData; 2142 mNextOutput->mCallbackData = mCallbackData; 2143 mNextOutput->mRecycledTrack = mTrack; 2144 mNextOutput->mSampleRateHz = mSampleRateHz; 2145 mNextOutput->mMsecsPerFrame = mMsecsPerFrame; 2146 mNextOutput->mFlags = mFlags; 2147 mNextOutput->mFrameSize = mFrameSize; 2148 close_l(); 2149 mCallbackData = NULL; // destruction handled by mNextOutput 2150 } else { 2151 ALOGW("Ignoring gapless playback because next player has already started"); 2152 // remove track in case resource needed for future players. 2153 if (mCallbackData != NULL) { 2154 mCallbackData->endTrackSwitch(); // release lock for callbacks before close. 2155 } 2156 close_l(); 2157 } 2158 } 2159 break; 2160 } 2161} 2162 2163ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking) 2164{ 2165 Mutex::Autolock lock(mLock); 2166 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback."); 2167 2168 //ALOGV("write(%p, %u)", buffer, size); 2169 if (mTrack != 0) { 2170 return mTrack->write(buffer, size, blocking); 2171 } 2172 return NO_INIT; 2173} 2174 2175void MediaPlayerService::AudioOutput::stop() 2176{ 2177 ALOGV("stop"); 2178 Mutex::Autolock lock(mLock); 2179 if (mTrack != 0) mTrack->stop(); 2180} 2181 2182void MediaPlayerService::AudioOutput::flush() 2183{ 2184 ALOGV("flush"); 2185 Mutex::Autolock lock(mLock); 2186 if (mTrack != 0) mTrack->flush(); 2187} 2188 2189void MediaPlayerService::AudioOutput::pause() 2190{ 2191 ALOGV("pause"); 2192 Mutex::Autolock lock(mLock); 2193 if (mTrack != 0) mTrack->pause(); 2194} 2195 2196void MediaPlayerService::AudioOutput::close() 2197{ 2198 ALOGV("close"); 2199 sp<AudioTrack> track; 2200 { 2201 Mutex::Autolock lock(mLock); 2202 track = mTrack; 2203 close_l(); // clears mTrack 2204 } 2205 // destruction of the track occurs outside of mutex. 2206} 2207 2208void MediaPlayerService::AudioOutput::setVolume(float left, float right) 2209{ 2210 ALOGV("setVolume(%f, %f)", left, right); 2211 Mutex::Autolock lock(mLock); 2212 mLeftVolume = left; 2213 mRightVolume = right; 2214 if (mTrack != 0) { 2215 mTrack->setVolume(left, right); 2216 } 2217} 2218 2219status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate) 2220{ 2221 ALOGV("setPlaybackRate(%f %f %d %d)", 2222 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode); 2223 Mutex::Autolock lock(mLock); 2224 if (mTrack == 0) { 2225 // remember rate so that we can set it when the track is opened 2226 mPlaybackRate = rate; 2227 return OK; 2228 } 2229 status_t res = mTrack->setPlaybackRate(rate); 2230 if (res != NO_ERROR) { 2231 return res; 2232 } 2233 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded 2234 CHECK_GT(rate.mSpeed, 0.f); 2235 mPlaybackRate = rate; 2236 if (mSampleRateHz != 0) { 2237 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz); 2238 } 2239 return res; 2240} 2241 2242status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate) 2243{ 2244 ALOGV("setPlaybackRate"); 2245 Mutex::Autolock lock(mLock); 2246 if (mTrack == 0) { 2247 return NO_INIT; 2248 } 2249 *rate = mTrack->getPlaybackRate(); 2250 return NO_ERROR; 2251} 2252 2253status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level) 2254{ 2255 ALOGV("setAuxEffectSendLevel(%f)", level); 2256 Mutex::Autolock lock(mLock); 2257 mSendLevel = level; 2258 if (mTrack != 0) { 2259 return mTrack->setAuxEffectSendLevel(level); 2260 } 2261 return NO_ERROR; 2262} 2263 2264status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId) 2265{ 2266 ALOGV("attachAuxEffect(%d)", effectId); 2267 Mutex::Autolock lock(mLock); 2268 mAuxEffectId = effectId; 2269 if (mTrack != 0) { 2270 return mTrack->attachAuxEffect(effectId); 2271 } 2272 return NO_ERROR; 2273} 2274 2275VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper( 2276 const sp<VolumeShaper::Configuration>& configuration, 2277 const sp<VolumeShaper::Operation>& operation) 2278{ 2279 Mutex::Autolock lock(mLock); 2280 ALOGV("AudioOutput::applyVolumeShaper"); 2281 2282 // We take ownership of the VolumeShaper if set before the track is created. 2283 mVolumeHandler->setIdIfNecessary(configuration); 2284 if (mTrack != 0) { 2285 return mTrack->applyVolumeShaper(configuration, operation); 2286 } else { 2287 return mVolumeHandler->applyVolumeShaper(configuration, operation); 2288 } 2289} 2290 2291sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id) 2292{ 2293 Mutex::Autolock lock(mLock); 2294 if (mTrack != 0) { 2295 return mTrack->getVolumeShaperState(id); 2296 } else { 2297 return mVolumeHandler->getVolumeShaperState(id); 2298 } 2299} 2300 2301// static 2302void MediaPlayerService::AudioOutput::CallbackWrapper( 2303 int event, void *cookie, void *info) { 2304 //ALOGV("callbackwrapper"); 2305 CallbackData *data = (CallbackData*)cookie; 2306 // lock to ensure we aren't caught in the middle of a track switch. 2307 data->lock(); 2308 AudioOutput *me = data->getOutput(); 2309 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info; 2310 if (me == NULL) { 2311 // no output set, likely because the track was scheduled to be reused 2312 // by another player, but the format turned out to be incompatible. 2313 data->unlock(); 2314 if (buffer != NULL) { 2315 buffer->size = 0; 2316 } 2317 return; 2318 } 2319 2320 switch(event) { 2321 case AudioTrack::EVENT_MORE_DATA: { 2322 size_t actualSize = (*me->mCallback)( 2323 me, buffer->raw, buffer->size, me->mCallbackCookie, 2324 CB_EVENT_FILL_BUFFER); 2325 2326 // Log when no data is returned from the callback. 2327 // (1) We may have no data (especially with network streaming sources). 2328 // (2) We may have reached the EOS and the audio track is not stopped yet. 2329 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS. 2330 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill). 2331 // 2332 // This is a benign busy-wait, with the next data request generated 10 ms or more later; 2333 // nevertheless for power reasons, we don't want to see too many of these. 2334 2335 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned"); 2336 2337 buffer->size = actualSize; 2338 } break; 2339 2340 case AudioTrack::EVENT_STREAM_END: 2341 // currently only occurs for offloaded callbacks 2342 ALOGV("callbackwrapper: deliver EVENT_STREAM_END"); 2343 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */, 2344 me->mCallbackCookie, CB_EVENT_STREAM_END); 2345 break; 2346 2347 case AudioTrack::EVENT_NEW_IAUDIOTRACK : 2348 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN"); 2349 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */, 2350 me->mCallbackCookie, CB_EVENT_TEAR_DOWN); 2351 break; 2352 2353 case AudioTrack::EVENT_UNDERRUN: 2354 // This occurs when there is no data available, typically 2355 // when there is a failure to supply data to the AudioTrack. It can also 2356 // occur in non-offloaded mode when the audio device comes out of standby. 2357 // 2358 // If an AudioTrack underruns it outputs silence. Since this happens suddenly 2359 // it may sound like an audible pop or glitch. 2360 // 2361 // The underrun event is sent once per track underrun; the condition is reset 2362 // when more data is sent to the AudioTrack. 2363 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)"); 2364 break; 2365 2366 default: 2367 ALOGE("received unknown event type: %d inside CallbackWrapper !", event); 2368 } 2369 2370 data->unlock(); 2371} 2372 2373audio_session_t MediaPlayerService::AudioOutput::getSessionId() const 2374{ 2375 Mutex::Autolock lock(mLock); 2376 return mSessionId; 2377} 2378 2379uint32_t MediaPlayerService::AudioOutput::getSampleRate() const 2380{ 2381 Mutex::Autolock lock(mLock); 2382 if (mTrack == 0) return 0; 2383 return mTrack->getSampleRate(); 2384} 2385 2386int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const 2387{ 2388 Mutex::Autolock lock(mLock); 2389 if (mTrack == 0) { 2390 return 0; 2391 } 2392 int64_t duration; 2393 if (mTrack->getBufferDurationInUs(&duration) != OK) { 2394 return 0; 2395 } 2396 return duration; 2397} 2398 2399//////////////////////////////////////////////////////////////////////////////// 2400 2401struct CallbackThread : public Thread { 2402 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink, 2403 MediaPlayerBase::AudioSink::AudioCallback cb, 2404 void *cookie); 2405 2406protected: 2407 virtual ~CallbackThread(); 2408 2409 virtual bool threadLoop(); 2410 2411private: 2412 wp<MediaPlayerBase::AudioSink> mSink; 2413 MediaPlayerBase::AudioSink::AudioCallback mCallback; 2414 void *mCookie; 2415 void *mBuffer; 2416 size_t mBufferSize; 2417 2418 CallbackThread(const CallbackThread &); 2419 CallbackThread &operator=(const CallbackThread &); 2420}; 2421 2422CallbackThread::CallbackThread( 2423 const wp<MediaPlayerBase::AudioSink> &sink, 2424 MediaPlayerBase::AudioSink::AudioCallback cb, 2425 void *cookie) 2426 : mSink(sink), 2427 mCallback(cb), 2428 mCookie(cookie), 2429 mBuffer(NULL), 2430 mBufferSize(0) { 2431} 2432 2433CallbackThread::~CallbackThread() { 2434 if (mBuffer) { 2435 free(mBuffer); 2436 mBuffer = NULL; 2437 } 2438} 2439 2440bool CallbackThread::threadLoop() { 2441 sp<MediaPlayerBase::AudioSink> sink = mSink.promote(); 2442 if (sink == NULL) { 2443 return false; 2444 } 2445 2446 if (mBuffer == NULL) { 2447 mBufferSize = sink->bufferSize(); 2448 mBuffer = malloc(mBufferSize); 2449 } 2450 2451 size_t actualSize = 2452 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie, 2453 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER); 2454 2455 if (actualSize > 0) { 2456 sink->write(mBuffer, actualSize); 2457 // Could return false on sink->write() error or short count. 2458 // Not necessarily appropriate but would work for AudioCache behavior. 2459 } 2460 2461 return true; 2462} 2463 2464//////////////////////////////////////////////////////////////////////////////// 2465 2466void MediaPlayerService::addBatteryData(uint32_t params) 2467{ 2468 Mutex::Autolock lock(mLock); 2469 2470 int32_t time = systemTime() / 1000000L; 2471 2472 // change audio output devices. This notification comes from AudioFlinger 2473 if ((params & kBatteryDataSpeakerOn) 2474 || (params & kBatteryDataOtherAudioDeviceOn)) { 2475 2476 int deviceOn[NUM_AUDIO_DEVICES]; 2477 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) { 2478 deviceOn[i] = 0; 2479 } 2480 2481 if ((params & kBatteryDataSpeakerOn) 2482 && (params & kBatteryDataOtherAudioDeviceOn)) { 2483 deviceOn[SPEAKER_AND_OTHER] = 1; 2484 } else if (params & kBatteryDataSpeakerOn) { 2485 deviceOn[SPEAKER] = 1; 2486 } else { 2487 deviceOn[OTHER_AUDIO_DEVICE] = 1; 2488 } 2489 2490 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) { 2491 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){ 2492 2493 if (mBatteryAudio.refCount > 0) { // if playing audio 2494 if (!deviceOn[i]) { 2495 mBatteryAudio.lastTime[i] += time; 2496 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i]; 2497 mBatteryAudio.lastTime[i] = 0; 2498 } else { 2499 mBatteryAudio.lastTime[i] = 0 - time; 2500 } 2501 } 2502 2503 mBatteryAudio.deviceOn[i] = deviceOn[i]; 2504 } 2505 } 2506 return; 2507 } 2508 2509 // an audio stream is started 2510 if (params & kBatteryDataAudioFlingerStart) { 2511 // record the start time only if currently no other audio 2512 // is being played 2513 if (mBatteryAudio.refCount == 0) { 2514 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) { 2515 if (mBatteryAudio.deviceOn[i]) { 2516 mBatteryAudio.lastTime[i] -= time; 2517 } 2518 } 2519 } 2520 2521 mBatteryAudio.refCount ++; 2522 return; 2523 2524 } else if (params & kBatteryDataAudioFlingerStop) { 2525 if (mBatteryAudio.refCount <= 0) { 2526 ALOGW("Battery track warning: refCount is <= 0"); 2527 return; 2528 } 2529 2530 // record the stop time only if currently this is the only 2531 // audio being played 2532 if (mBatteryAudio.refCount == 1) { 2533 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) { 2534 if (mBatteryAudio.deviceOn[i]) { 2535 mBatteryAudio.lastTime[i] += time; 2536 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i]; 2537 mBatteryAudio.lastTime[i] = 0; 2538 } 2539 } 2540 } 2541 2542 mBatteryAudio.refCount --; 2543 return; 2544 } 2545 2546 uid_t uid = IPCThreadState::self()->getCallingUid(); 2547 if (uid == AID_MEDIA) { 2548 return; 2549 } 2550 int index = mBatteryData.indexOfKey(uid); 2551 2552 if (index < 0) { // create a new entry for this UID 2553 BatteryUsageInfo info; 2554 info.audioTotalTime = 0; 2555 info.videoTotalTime = 0; 2556 info.audioLastTime = 0; 2557 info.videoLastTime = 0; 2558 info.refCount = 0; 2559 2560 if (mBatteryData.add(uid, info) == NO_MEMORY) { 2561 ALOGE("Battery track error: no memory for new app"); 2562 return; 2563 } 2564 } 2565 2566 BatteryUsageInfo &info = mBatteryData.editValueFor(uid); 2567 2568 if (params & kBatteryDataCodecStarted) { 2569 if (params & kBatteryDataTrackAudio) { 2570 info.audioLastTime -= time; 2571 info.refCount ++; 2572 } 2573 if (params & kBatteryDataTrackVideo) { 2574 info.videoLastTime -= time; 2575 info.refCount ++; 2576 } 2577 } else { 2578 if (info.refCount == 0) { 2579 ALOGW("Battery track warning: refCount is already 0"); 2580 return; 2581 } else if (info.refCount < 0) { 2582 ALOGE("Battery track error: refCount < 0"); 2583 mBatteryData.removeItem(uid); 2584 return; 2585 } 2586 2587 if (params & kBatteryDataTrackAudio) { 2588 info.audioLastTime += time; 2589 info.refCount --; 2590 } 2591 if (params & kBatteryDataTrackVideo) { 2592 info.videoLastTime += time; 2593 info.refCount --; 2594 } 2595 2596 // no stream is being played by this UID 2597 if (info.refCount == 0) { 2598 info.audioTotalTime += info.audioLastTime; 2599 info.audioLastTime = 0; 2600 info.videoTotalTime += info.videoLastTime; 2601 info.videoLastTime = 0; 2602 } 2603 } 2604} 2605 2606status_t MediaPlayerService::pullBatteryData(Parcel* reply) { 2607 Mutex::Autolock lock(mLock); 2608 2609 // audio output devices usage 2610 int32_t time = systemTime() / 1000000L; //in ms 2611 int32_t totalTime; 2612 2613 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) { 2614 totalTime = mBatteryAudio.totalTime[i]; 2615 2616 if (mBatteryAudio.deviceOn[i] 2617 && (mBatteryAudio.lastTime[i] != 0)) { 2618 int32_t tmpTime = mBatteryAudio.lastTime[i] + time; 2619 totalTime += tmpTime; 2620 } 2621 2622 reply->writeInt32(totalTime); 2623 // reset the total time 2624 mBatteryAudio.totalTime[i] = 0; 2625 } 2626 2627 // codec usage 2628 BatteryUsageInfo info; 2629 int size = mBatteryData.size(); 2630 2631 reply->writeInt32(size); 2632 int i = 0; 2633 2634 while (i < size) { 2635 info = mBatteryData.valueAt(i); 2636 2637 reply->writeInt32(mBatteryData.keyAt(i)); //UID 2638 reply->writeInt32(info.audioTotalTime); 2639 reply->writeInt32(info.videoTotalTime); 2640 2641 info.audioTotalTime = 0; 2642 info.videoTotalTime = 0; 2643 2644 // remove the UID entry where no stream is being played 2645 if (info.refCount <= 0) { 2646 mBatteryData.removeItemsAt(i); 2647 size --; 2648 i --; 2649 } 2650 i++; 2651 } 2652 return NO_ERROR; 2653} 2654} // namespace android 2655