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