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