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