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