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