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