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