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