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