MediaPlayerService.cpp revision da7581b7b61b84f15e8d671c86fd117c322b009e
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 <dirent.h> 27#include <unistd.h> 28 29#include <string.h> 30 31#include <cutils/atomic.h> 32#include <cutils/properties.h> // for property_get 33 34#include <utils/misc.h> 35 36#include <android_runtime/ActivityManager.h> 37 38#include <binder/IPCThreadState.h> 39#include <binder/IServiceManager.h> 40#include <binder/MemoryHeapBase.h> 41#include <binder/MemoryBase.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#include <cutils/properties.h> 47 48#include <media/MediaPlayerInterface.h> 49#include <media/mediarecorder.h> 50#include <media/MediaMetadataRetrieverInterface.h> 51#include <media/Metadata.h> 52#include <media/AudioTrack.h> 53 54#include "MediaRecorderClient.h" 55#include "MediaPlayerService.h" 56#include "MetadataRetrieverClient.h" 57 58#include "MidiFile.h" 59#include <media/PVPlayer.h> 60#include "TestPlayerStub.h" 61#include "StagefrightPlayer.h" 62 63#include <OMX.h> 64 65/* desktop Linux needs a little help with gettid() */ 66#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS) 67#define __KERNEL__ 68# include <linux/unistd.h> 69#ifdef _syscall0 70_syscall0(pid_t,gettid) 71#else 72pid_t gettid() { return syscall(__NR_gettid);} 73#endif 74#undef __KERNEL__ 75#endif 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 LOGE("Failed to read filter's length"); 120 *status = NOT_ENOUGH_DATA; 121 return false; 122 } 123 124 if( val > kMaxFilterSize || val < 0) 125 { 126 LOGE("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 LOGE("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 LOGE("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 185// TODO: Temp hack until we can register players 186typedef struct { 187 const char *extension; 188 const player_type playertype; 189} extmap; 190extmap FILE_EXTS [] = { 191 {".mid", SONIVOX_PLAYER}, 192 {".midi", SONIVOX_PLAYER}, 193 {".smf", SONIVOX_PLAYER}, 194 {".xmf", SONIVOX_PLAYER}, 195 {".imy", SONIVOX_PLAYER}, 196 {".rtttl", SONIVOX_PLAYER}, 197 {".rtx", SONIVOX_PLAYER}, 198 {".ota", SONIVOX_PLAYER}, 199#ifndef NO_OPENCORE 200 {".wma", PV_PLAYER}, 201 {".wmv", PV_PLAYER}, 202 {".asf", PV_PLAYER}, 203#endif 204}; 205 206// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround 207/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4; 208/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false; 209 210void MediaPlayerService::instantiate() { 211 defaultServiceManager()->addService( 212 String16("media.player"), new MediaPlayerService()); 213} 214 215MediaPlayerService::MediaPlayerService() 216{ 217 LOGV("MediaPlayerService created"); 218 mNextConnId = 1; 219} 220 221MediaPlayerService::~MediaPlayerService() 222{ 223 LOGV("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 LOGV("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 LOGV("Delete media recorder client"); 241} 242 243sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid) 244{ 245 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid); 246 LOGV("Create new media retriever from pid %d", pid); 247 return retriever; 248} 249 250sp<IMediaPlayer> MediaPlayerService::create( 251 pid_t pid, const sp<IMediaPlayerClient>& client, const char* url, 252 const KeyedVector<String8, String8> *headers, int audioSessionId) 253{ 254 int32_t connId = android_atomic_inc(&mNextConnId); 255 sp<Client> c = new Client(this, pid, connId, client, audioSessionId); 256 LOGV("Create new client(%d) from pid %d, url=%s, connId=%d, audioSessionId=%d", 257 connId, pid, url, connId, audioSessionId); 258 if (NO_ERROR != c->setDataSource(url, headers)) 259 { 260 c.clear(); 261 return c; 262 } 263 wp<Client> w = c; 264 Mutex::Autolock lock(mLock); 265 mClients.add(w); 266 return c; 267} 268 269sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client, 270 int fd, int64_t offset, int64_t length, int audioSessionId) 271{ 272 int32_t connId = android_atomic_inc(&mNextConnId); 273 sp<Client> c = new Client(this, pid, connId, client, audioSessionId); 274 LOGV("Create new client(%d) from pid %d, fd=%d, offset=%lld, length=%lld, audioSessionId=%d", 275 connId, pid, fd, offset, length, audioSessionId); 276 if (NO_ERROR != c->setDataSource(fd, offset, length)) { 277 c.clear(); 278 } else { 279 wp<Client> w = c; 280 Mutex::Autolock lock(mLock); 281 mClients.add(w); 282 } 283 ::close(fd); 284 return c; 285} 286 287sp<IOMX> MediaPlayerService::getOMX() { 288 Mutex::Autolock autoLock(mLock); 289 290 if (mOMX.get() == NULL) { 291 mOMX = new OMX; 292 } 293 294 return mOMX; 295} 296 297status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const 298{ 299 const size_t SIZE = 256; 300 char buffer[SIZE]; 301 String8 result; 302 303 result.append(" AudioCache\n"); 304 if (mHeap != 0) { 305 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n", 306 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice()); 307 result.append(buffer); 308 } 309 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n", 310 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount); 311 result.append(buffer); 312 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n", 313 mSampleRate, mSize, mError, mCommandComplete?"true":"false"); 314 result.append(buffer); 315 ::write(fd, result.string(), result.size()); 316 return NO_ERROR; 317} 318 319status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const 320{ 321 const size_t SIZE = 256; 322 char buffer[SIZE]; 323 String8 result; 324 325 result.append(" AudioOutput\n"); 326 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", 327 mStreamType, mLeftVolume, mRightVolume); 328 result.append(buffer); 329 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n", 330 mMsecsPerFrame, mLatency); 331 result.append(buffer); 332 ::write(fd, result.string(), result.size()); 333 if (mTrack != 0) { 334 mTrack->dump(fd, args); 335 } 336 return NO_ERROR; 337} 338 339status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const 340{ 341 const size_t SIZE = 256; 342 char buffer[SIZE]; 343 String8 result; 344 result.append(" Client\n"); 345 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n", 346 mPid, mConnId, mStatus, mLoop?"true": "false"); 347 result.append(buffer); 348 write(fd, result.string(), result.size()); 349 if (mAudioOutput != 0) { 350 mAudioOutput->dump(fd, args); 351 } 352 write(fd, "\n", 1); 353 return NO_ERROR; 354} 355 356static int myTid() { 357#ifdef HAVE_GETTID 358 return gettid(); 359#else 360 return getpid(); 361#endif 362} 363 364#if defined(__arm__) 365extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize, 366 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize); 367extern "C" void free_malloc_leak_info(uint8_t* info); 368 369// Use the String-class below instead of String8 to allocate all memory 370// beforehand and not reenter the heap while we are examining it... 371struct MyString8 { 372 static const size_t MAX_SIZE = 256 * 1024; 373 374 MyString8() 375 : mPtr((char *)malloc(MAX_SIZE)) { 376 *mPtr = '\0'; 377 } 378 379 ~MyString8() { 380 free(mPtr); 381 } 382 383 void append(const char *s) { 384 strcat(mPtr, s); 385 } 386 387 const char *string() const { 388 return mPtr; 389 } 390 391 size_t size() const { 392 return strlen(mPtr); 393 } 394 395private: 396 char *mPtr; 397 398 MyString8(const MyString8 &); 399 MyString8 &operator=(const MyString8 &); 400}; 401 402void memStatus(int fd, const Vector<String16>& args) 403{ 404 const size_t SIZE = 256; 405 char buffer[SIZE]; 406 MyString8 result; 407 408 typedef struct { 409 size_t size; 410 size_t dups; 411 intptr_t * backtrace; 412 } AllocEntry; 413 414 uint8_t *info = NULL; 415 size_t overallSize = 0; 416 size_t infoSize = 0; 417 size_t totalMemory = 0; 418 size_t backtraceSize = 0; 419 420 get_malloc_leak_info(&info, &overallSize, &infoSize, &totalMemory, &backtraceSize); 421 if (info) { 422 uint8_t *ptr = info; 423 size_t count = overallSize / infoSize; 424 425 snprintf(buffer, SIZE, " Allocation count %i\n", count); 426 result.append(buffer); 427 snprintf(buffer, SIZE, " Total memory %i\n", totalMemory); 428 result.append(buffer); 429 430 AllocEntry * entries = new AllocEntry[count]; 431 432 for (size_t i = 0; i < count; i++) { 433 // Each entry should be size_t, size_t, intptr_t[backtraceSize] 434 AllocEntry *e = &entries[i]; 435 436 e->size = *reinterpret_cast<size_t *>(ptr); 437 ptr += sizeof(size_t); 438 439 e->dups = *reinterpret_cast<size_t *>(ptr); 440 ptr += sizeof(size_t); 441 442 e->backtrace = reinterpret_cast<intptr_t *>(ptr); 443 ptr += sizeof(intptr_t) * backtraceSize; 444 } 445 446 // Now we need to sort the entries. They come sorted by size but 447 // not by stack trace which causes problems using diff. 448 bool moved; 449 do { 450 moved = false; 451 for (size_t i = 0; i < (count - 1); i++) { 452 AllocEntry *e1 = &entries[i]; 453 AllocEntry *e2 = &entries[i+1]; 454 455 bool swap = e1->size < e2->size; 456 if (e1->size == e2->size) { 457 for(size_t j = 0; j < backtraceSize; j++) { 458 if (e1->backtrace[j] == e2->backtrace[j]) { 459 continue; 460 } 461 swap = e1->backtrace[j] < e2->backtrace[j]; 462 break; 463 } 464 } 465 if (swap) { 466 AllocEntry t = entries[i]; 467 entries[i] = entries[i+1]; 468 entries[i+1] = t; 469 moved = true; 470 } 471 } 472 } while (moved); 473 474 for (size_t i = 0; i < count; i++) { 475 AllocEntry *e = &entries[i]; 476 477 snprintf(buffer, SIZE, "size %8i, dup %4i, ", e->size, e->dups); 478 result.append(buffer); 479 for (size_t ct = 0; (ct < backtraceSize) && e->backtrace[ct]; ct++) { 480 if (ct) { 481 result.append(", "); 482 } 483 snprintf(buffer, SIZE, "0x%08x", e->backtrace[ct]); 484 result.append(buffer); 485 } 486 result.append("\n"); 487 } 488 489 delete[] entries; 490 free_malloc_leak_info(info); 491 } 492 493 write(fd, result.string(), result.size()); 494} 495#endif 496 497status_t MediaPlayerService::dump(int fd, const Vector<String16>& args) 498{ 499 const size_t SIZE = 256; 500 char buffer[SIZE]; 501 String8 result; 502 if (checkCallingPermission(String16("android.permission.DUMP")) == false) { 503 snprintf(buffer, SIZE, "Permission Denial: " 504 "can't dump MediaPlayerService from pid=%d, uid=%d\n", 505 IPCThreadState::self()->getCallingPid(), 506 IPCThreadState::self()->getCallingUid()); 507 result.append(buffer); 508 } else { 509 Mutex::Autolock lock(mLock); 510 for (int i = 0, n = mClients.size(); i < n; ++i) { 511 sp<Client> c = mClients[i].promote(); 512 if (c != 0) c->dump(fd, args); 513 } 514 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) { 515 result.append(" MediaRecorderClient\n"); 516 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote(); 517 snprintf(buffer, 255, " pid(%d)\n\n", c->mPid); 518 result.append(buffer); 519 } 520 521 result.append(" Files opened and/or mapped:\n"); 522 snprintf(buffer, SIZE, "/proc/%d/maps", myTid()); 523 FILE *f = fopen(buffer, "r"); 524 if (f) { 525 while (!feof(f)) { 526 fgets(buffer, SIZE, f); 527 if (strstr(buffer, " /sdcard/") || 528 strstr(buffer, " /system/sounds/") || 529 strstr(buffer, " /system/media/")) { 530 result.append(" "); 531 result.append(buffer); 532 } 533 } 534 fclose(f); 535 } else { 536 result.append("couldn't open "); 537 result.append(buffer); 538 result.append("\n"); 539 } 540 541 snprintf(buffer, SIZE, "/proc/%d/fd", myTid()); 542 DIR *d = opendir(buffer); 543 if (d) { 544 struct dirent *ent; 545 while((ent = readdir(d)) != NULL) { 546 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) { 547 snprintf(buffer, SIZE, "/proc/%d/fd/%s", myTid(), ent->d_name); 548 struct stat s; 549 if (lstat(buffer, &s) == 0) { 550 if ((s.st_mode & S_IFMT) == S_IFLNK) { 551 char linkto[256]; 552 int len = readlink(buffer, linkto, sizeof(linkto)); 553 if(len > 0) { 554 if(len > 255) { 555 linkto[252] = '.'; 556 linkto[253] = '.'; 557 linkto[254] = '.'; 558 linkto[255] = 0; 559 } else { 560 linkto[len] = 0; 561 } 562 if (strstr(linkto, "/sdcard/") == linkto || 563 strstr(linkto, "/system/sounds/") == linkto || 564 strstr(linkto, "/system/media/") == linkto) { 565 result.append(" "); 566 result.append(buffer); 567 result.append(" -> "); 568 result.append(linkto); 569 result.append("\n"); 570 } 571 } 572 } else { 573 result.append(" unexpected type for "); 574 result.append(buffer); 575 result.append("\n"); 576 } 577 } 578 } 579 } 580 closedir(d); 581 } else { 582 result.append("couldn't open "); 583 result.append(buffer); 584 result.append("\n"); 585 } 586 587#if defined(__arm__) 588 bool dumpMem = false; 589 for (size_t i = 0; i < args.size(); i++) { 590 if (args[i] == String16("-m")) { 591 dumpMem = true; 592 } 593 } 594 if (dumpMem) { 595 memStatus(fd, args); 596 } 597#endif 598 } 599 write(fd, result.string(), result.size()); 600 return NO_ERROR; 601} 602 603void MediaPlayerService::removeClient(wp<Client> client) 604{ 605 Mutex::Autolock lock(mLock); 606 mClients.remove(client); 607} 608 609MediaPlayerService::Client::Client(const sp<MediaPlayerService>& service, pid_t pid, 610 int32_t connId, const sp<IMediaPlayerClient>& client, int audioSessionId) 611{ 612 LOGV("Client(%d) constructor", connId); 613 mPid = pid; 614 mConnId = connId; 615 mService = service; 616 mClient = client; 617 mLoop = false; 618 mStatus = NO_INIT; 619 mAudioSessionId = audioSessionId; 620 621#if CALLBACK_ANTAGONIZER 622 LOGD("create Antagonizer"); 623 mAntagonizer = new Antagonizer(notify, this); 624#endif 625} 626 627MediaPlayerService::Client::~Client() 628{ 629 LOGV("Client(%d) destructor pid = %d", mConnId, mPid); 630 mAudioOutput.clear(); 631 wp<Client> client(this); 632 disconnect(); 633 mService->removeClient(client); 634} 635 636void MediaPlayerService::Client::disconnect() 637{ 638 LOGV("disconnect(%d) from pid %d", mConnId, mPid); 639 // grab local reference and clear main reference to prevent future 640 // access to object 641 sp<MediaPlayerBase> p; 642 { 643 Mutex::Autolock l(mLock); 644 p = mPlayer; 645 } 646 mClient.clear(); 647 648 mPlayer.clear(); 649 650 // clear the notification to prevent callbacks to dead client 651 // and reset the player. We assume the player will serialize 652 // access to itself if necessary. 653 if (p != 0) { 654 p->setNotifyCallback(0, 0); 655#if CALLBACK_ANTAGONIZER 656 LOGD("kill Antagonizer"); 657 mAntagonizer->kill(); 658#endif 659 p->reset(); 660 } 661 662 IPCThreadState::self()->flushCommands(); 663} 664 665static player_type getDefaultPlayerType() { 666 return STAGEFRIGHT_PLAYER; 667} 668 669player_type getPlayerType(int fd, int64_t offset, int64_t length) 670{ 671 char buf[20]; 672 lseek(fd, offset, SEEK_SET); 673 read(fd, buf, sizeof(buf)); 674 lseek(fd, offset, SEEK_SET); 675 676 long ident = *((long*)buf); 677 678 // Ogg vorbis? 679 if (ident == 0x5367674f) // 'OggS' 680 return STAGEFRIGHT_PLAYER; 681 682#ifndef NO_OPENCORE 683 if (ident == 0x75b22630) { 684 // The magic number for .asf files, i.e. wmv and wma content. 685 // These are not currently supported through stagefright. 686 return PV_PLAYER; 687 } 688#endif 689 690 // Some kind of MIDI? 691 EAS_DATA_HANDLE easdata; 692 if (EAS_Init(&easdata) == EAS_SUCCESS) { 693 EAS_FILE locator; 694 locator.path = NULL; 695 locator.fd = fd; 696 locator.offset = offset; 697 locator.length = length; 698 EAS_HANDLE eashandle; 699 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) { 700 EAS_CloseFile(easdata, eashandle); 701 EAS_Shutdown(easdata); 702 return SONIVOX_PLAYER; 703 } 704 EAS_Shutdown(easdata); 705 } 706 707 return getDefaultPlayerType(); 708} 709 710player_type getPlayerType(const char* url) 711{ 712 if (TestPlayerStub::canBeUsed(url)) { 713 return TEST_PLAYER; 714 } 715 716 // use MidiFile for MIDI extensions 717 int lenURL = strlen(url); 718 for (int i = 0; i < NELEM(FILE_EXTS); ++i) { 719 int len = strlen(FILE_EXTS[i].extension); 720 int start = lenURL - len; 721 if (start > 0) { 722 if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) { 723 return FILE_EXTS[i].playertype; 724 } 725 } 726 } 727 728 if (!strncasecmp(url, "rtsp://", 7)) { 729 char value[PROPERTY_VALUE_MAX]; 730 if (!property_get("media.stagefright.enable-rtsp", value, NULL) 731 || (strcmp(value, "1") && strcasecmp(value, "true"))) { 732 // For now, we're going to use PV for rtsp-based playback 733 // by default until we can clear up a few more issues. 734 return PV_PLAYER; 735 } 736 } 737 738 return getDefaultPlayerType(); 739} 740 741static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie, 742 notify_callback_f notifyFunc) 743{ 744 sp<MediaPlayerBase> p; 745 switch (playerType) { 746#ifndef NO_OPENCORE 747 case PV_PLAYER: 748 LOGV(" create PVPlayer"); 749 p = new PVPlayer(); 750 break; 751#endif 752 case SONIVOX_PLAYER: 753 LOGV(" create MidiFile"); 754 p = new MidiFile(); 755 break; 756 case STAGEFRIGHT_PLAYER: 757 LOGV(" create StagefrightPlayer"); 758 p = new StagefrightPlayer; 759 break; 760 case TEST_PLAYER: 761 LOGV("Create Test Player stub"); 762 p = new TestPlayerStub(); 763 break; 764 } 765 if (p != NULL) { 766 if (p->initCheck() == NO_ERROR) { 767 p->setNotifyCallback(cookie, notifyFunc); 768 } else { 769 p.clear(); 770 } 771 } 772 if (p == NULL) { 773 LOGE("Failed to create player object"); 774 } 775 return p; 776} 777 778sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType) 779{ 780 // determine if we have the right player type 781 sp<MediaPlayerBase> p = mPlayer; 782 if ((p != NULL) && (p->playerType() != playerType)) { 783 LOGV("delete player"); 784 p.clear(); 785 } 786 if (p == NULL) { 787 p = android::createPlayer(playerType, this, notify); 788 } 789 return p; 790} 791 792status_t MediaPlayerService::Client::setDataSource( 793 const char *url, const KeyedVector<String8, String8> *headers) 794{ 795 LOGV("setDataSource(%s)", url); 796 if (url == NULL) 797 return UNKNOWN_ERROR; 798 799 if (strncmp(url, "content://", 10) == 0) { 800 // get a filedescriptor for the content Uri and 801 // pass it to the setDataSource(fd) method 802 803 String16 url16(url); 804 int fd = android::openContentProviderFile(url16); 805 if (fd < 0) 806 { 807 LOGE("Couldn't open fd for %s", url); 808 return UNKNOWN_ERROR; 809 } 810 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus 811 close(fd); 812 return mStatus; 813 } else { 814 player_type playerType = getPlayerType(url); 815 LOGV("player type = %d", playerType); 816 817 // create the right type of player 818 sp<MediaPlayerBase> p = createPlayer(playerType); 819 if (p == NULL) return NO_INIT; 820 821 if (!p->hardwareOutput()) { 822 mAudioOutput = new AudioOutput(mAudioSessionId); 823 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput); 824 } 825 826 // now set data source 827 LOGV(" setDataSource"); 828 mStatus = p->setDataSource(url, headers); 829 if (mStatus == NO_ERROR) { 830 mPlayer = p; 831 } else { 832 LOGE(" error: %d", mStatus); 833 } 834 return mStatus; 835 } 836} 837 838status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length) 839{ 840 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length); 841 struct stat sb; 842 int ret = fstat(fd, &sb); 843 if (ret != 0) { 844 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno)); 845 return UNKNOWN_ERROR; 846 } 847 848 LOGV("st_dev = %llu", sb.st_dev); 849 LOGV("st_mode = %u", sb.st_mode); 850 LOGV("st_uid = %lu", sb.st_uid); 851 LOGV("st_gid = %lu", sb.st_gid); 852 LOGV("st_size = %llu", sb.st_size); 853 854 if (offset >= sb.st_size) { 855 LOGE("offset error"); 856 ::close(fd); 857 return UNKNOWN_ERROR; 858 } 859 if (offset + length > sb.st_size) { 860 length = sb.st_size - offset; 861 LOGV("calculated length = %lld", length); 862 } 863 864 player_type playerType = getPlayerType(fd, offset, length); 865 LOGV("player type = %d", playerType); 866 867 // create the right type of player 868 sp<MediaPlayerBase> p = createPlayer(playerType); 869 if (p == NULL) return NO_INIT; 870 871 if (!p->hardwareOutput()) { 872 mAudioOutput = new AudioOutput(mAudioSessionId); 873 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput); 874 } 875 876 // now set data source 877 mStatus = p->setDataSource(fd, offset, length); 878 if (mStatus == NO_ERROR) mPlayer = p; 879 return mStatus; 880} 881 882status_t MediaPlayerService::Client::setVideoSurface(const sp<ISurface>& surface) 883{ 884 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get()); 885 sp<MediaPlayerBase> p = getPlayer(); 886 if (p == 0) return UNKNOWN_ERROR; 887 return p->setVideoSurface(surface); 888} 889 890status_t MediaPlayerService::Client::invoke(const Parcel& request, 891 Parcel *reply) 892{ 893 sp<MediaPlayerBase> p = getPlayer(); 894 if (p == NULL) return UNKNOWN_ERROR; 895 return p->invoke(request, reply); 896} 897 898// This call doesn't need to access the native player. 899status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter) 900{ 901 status_t status; 902 media::Metadata::Filter allow, drop; 903 904 if (unmarshallFilter(filter, &allow, &status) && 905 unmarshallFilter(filter, &drop, &status)) { 906 Mutex::Autolock lock(mLock); 907 908 mMetadataAllow = allow; 909 mMetadataDrop = drop; 910 } 911 return status; 912} 913 914status_t MediaPlayerService::Client::getMetadata( 915 bool update_only, bool apply_filter, Parcel *reply) 916{ 917 sp<MediaPlayerBase> player = getPlayer(); 918 if (player == 0) return UNKNOWN_ERROR; 919 920 status_t status; 921 // Placeholder for the return code, updated by the caller. 922 reply->writeInt32(-1); 923 924 media::Metadata::Filter ids; 925 926 // We don't block notifications while we fetch the data. We clear 927 // mMetadataUpdated first so we don't lose notifications happening 928 // during the rest of this call. 929 { 930 Mutex::Autolock lock(mLock); 931 if (update_only) { 932 ids = mMetadataUpdated; 933 } 934 mMetadataUpdated.clear(); 935 } 936 937 media::Metadata metadata(reply); 938 939 metadata.appendHeader(); 940 status = player->getMetadata(ids, reply); 941 942 if (status != OK) { 943 metadata.resetParcel(); 944 LOGE("getMetadata failed %d", status); 945 return status; 946 } 947 948 // FIXME: Implement filtering on the result. Not critical since 949 // filtering takes place on the update notifications already. This 950 // would be when all the metadata are fetch and a filter is set. 951 952 // Everything is fine, update the metadata length. 953 metadata.updateLength(); 954 return OK; 955} 956 957status_t MediaPlayerService::Client::suspend() { 958 sp<MediaPlayerBase> p = getPlayer(); 959 if (p == 0) return UNKNOWN_ERROR; 960 961 return p->suspend(); 962} 963 964status_t MediaPlayerService::Client::resume() { 965 sp<MediaPlayerBase> p = getPlayer(); 966 if (p == 0) return UNKNOWN_ERROR; 967 968 return p->resume(); 969} 970 971status_t MediaPlayerService::Client::prepareAsync() 972{ 973 LOGV("[%d] prepareAsync", mConnId); 974 sp<MediaPlayerBase> p = getPlayer(); 975 if (p == 0) return UNKNOWN_ERROR; 976 status_t ret = p->prepareAsync(); 977#if CALLBACK_ANTAGONIZER 978 LOGD("start Antagonizer"); 979 if (ret == NO_ERROR) mAntagonizer->start(); 980#endif 981 return ret; 982} 983 984status_t MediaPlayerService::Client::start() 985{ 986 LOGV("[%d] start", mConnId); 987 sp<MediaPlayerBase> p = getPlayer(); 988 if (p == 0) return UNKNOWN_ERROR; 989 p->setLooping(mLoop); 990 return p->start(); 991} 992 993status_t MediaPlayerService::Client::stop() 994{ 995 LOGV("[%d] stop", mConnId); 996 sp<MediaPlayerBase> p = getPlayer(); 997 if (p == 0) return UNKNOWN_ERROR; 998 return p->stop(); 999} 1000 1001status_t MediaPlayerService::Client::pause() 1002{ 1003 LOGV("[%d] pause", mConnId); 1004 sp<MediaPlayerBase> p = getPlayer(); 1005 if (p == 0) return UNKNOWN_ERROR; 1006 return p->pause(); 1007} 1008 1009status_t MediaPlayerService::Client::isPlaying(bool* state) 1010{ 1011 *state = false; 1012 sp<MediaPlayerBase> p = getPlayer(); 1013 if (p == 0) return UNKNOWN_ERROR; 1014 *state = p->isPlaying(); 1015 LOGV("[%d] isPlaying: %d", mConnId, *state); 1016 return NO_ERROR; 1017} 1018 1019status_t MediaPlayerService::Client::getCurrentPosition(int *msec) 1020{ 1021 LOGV("getCurrentPosition"); 1022 sp<MediaPlayerBase> p = getPlayer(); 1023 if (p == 0) return UNKNOWN_ERROR; 1024 status_t ret = p->getCurrentPosition(msec); 1025 if (ret == NO_ERROR) { 1026 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec); 1027 } else { 1028 LOGE("getCurrentPosition returned %d", ret); 1029 } 1030 return ret; 1031} 1032 1033status_t MediaPlayerService::Client::getDuration(int *msec) 1034{ 1035 LOGV("getDuration"); 1036 sp<MediaPlayerBase> p = getPlayer(); 1037 if (p == 0) return UNKNOWN_ERROR; 1038 status_t ret = p->getDuration(msec); 1039 if (ret == NO_ERROR) { 1040 LOGV("[%d] getDuration = %d", mConnId, *msec); 1041 } else { 1042 LOGE("getDuration returned %d", ret); 1043 } 1044 return ret; 1045} 1046 1047status_t MediaPlayerService::Client::seekTo(int msec) 1048{ 1049 LOGV("[%d] seekTo(%d)", mConnId, msec); 1050 sp<MediaPlayerBase> p = getPlayer(); 1051 if (p == 0) return UNKNOWN_ERROR; 1052 return p->seekTo(msec); 1053} 1054 1055status_t MediaPlayerService::Client::reset() 1056{ 1057 LOGV("[%d] reset", mConnId); 1058 sp<MediaPlayerBase> p = getPlayer(); 1059 if (p == 0) return UNKNOWN_ERROR; 1060 return p->reset(); 1061} 1062 1063status_t MediaPlayerService::Client::setAudioStreamType(int type) 1064{ 1065 LOGV("[%d] setAudioStreamType(%d)", mConnId, type); 1066 // TODO: for hardware output, call player instead 1067 Mutex::Autolock l(mLock); 1068 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type); 1069 return NO_ERROR; 1070} 1071 1072status_t MediaPlayerService::Client::setLooping(int loop) 1073{ 1074 LOGV("[%d] setLooping(%d)", mConnId, loop); 1075 mLoop = loop; 1076 sp<MediaPlayerBase> p = getPlayer(); 1077 if (p != 0) return p->setLooping(loop); 1078 return NO_ERROR; 1079} 1080 1081status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume) 1082{ 1083 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume); 1084 // TODO: for hardware output, call player instead 1085 Mutex::Autolock l(mLock); 1086 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume); 1087 return NO_ERROR; 1088} 1089 1090 1091void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2) 1092{ 1093 Client* client = static_cast<Client*>(cookie); 1094 1095 if (MEDIA_INFO == msg && 1096 MEDIA_INFO_METADATA_UPDATE == ext1) { 1097 const media::Metadata::Type metadata_type = ext2; 1098 1099 if(client->shouldDropMetadata(metadata_type)) { 1100 return; 1101 } 1102 1103 // Update the list of metadata that have changed. getMetadata 1104 // also access mMetadataUpdated and clears it. 1105 client->addNewMetadataUpdate(metadata_type); 1106 } 1107 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2); 1108 client->mClient->notify(msg, ext1, ext2); 1109} 1110 1111 1112bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const 1113{ 1114 Mutex::Autolock lock(mLock); 1115 1116 if (findMetadata(mMetadataDrop, code)) { 1117 return true; 1118 } 1119 1120 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) { 1121 return false; 1122 } else { 1123 return true; 1124 } 1125} 1126 1127 1128void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) { 1129 Mutex::Autolock lock(mLock); 1130 if (mMetadataUpdated.indexOf(metadata_type) < 0) { 1131 mMetadataUpdated.add(metadata_type); 1132 } 1133} 1134 1135#if CALLBACK_ANTAGONIZER 1136const int Antagonizer::interval = 10000; // 10 msecs 1137 1138Antagonizer::Antagonizer(notify_callback_f cb, void* client) : 1139 mExit(false), mActive(false), mClient(client), mCb(cb) 1140{ 1141 createThread(callbackThread, this); 1142} 1143 1144void Antagonizer::kill() 1145{ 1146 Mutex::Autolock _l(mLock); 1147 mActive = false; 1148 mExit = true; 1149 mCondition.wait(mLock); 1150} 1151 1152int Antagonizer::callbackThread(void* user) 1153{ 1154 LOGD("Antagonizer started"); 1155 Antagonizer* p = reinterpret_cast<Antagonizer*>(user); 1156 while (!p->mExit) { 1157 if (p->mActive) { 1158 LOGV("send event"); 1159 p->mCb(p->mClient, 0, 0, 0); 1160 } 1161 usleep(interval); 1162 } 1163 Mutex::Autolock _l(p->mLock); 1164 p->mCondition.signal(); 1165 LOGD("Antagonizer stopped"); 1166 return 0; 1167} 1168#endif 1169 1170static size_t kDefaultHeapSize = 1024 * 1024; // 1MB 1171 1172sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat) 1173{ 1174 LOGV("decode(%s)", url); 1175 sp<MemoryBase> mem; 1176 sp<MediaPlayerBase> player; 1177 1178 // Protect our precious, precious DRMd ringtones by only allowing 1179 // decoding of http, but not filesystem paths or content Uris. 1180 // If the application wants to decode those, it should open a 1181 // filedescriptor for them and use that. 1182 if (url != NULL && strncmp(url, "http://", 7) != 0) { 1183 LOGD("Can't decode %s by path, use filedescriptor instead", url); 1184 return mem; 1185 } 1186 1187 player_type playerType = getPlayerType(url); 1188 LOGV("player type = %d", playerType); 1189 1190 // create the right type of player 1191 sp<AudioCache> cache = new AudioCache(url); 1192 player = android::createPlayer(playerType, cache.get(), cache->notify); 1193 if (player == NULL) goto Exit; 1194 if (player->hardwareOutput()) goto Exit; 1195 1196 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache); 1197 1198 // set data source 1199 if (player->setDataSource(url) != NO_ERROR) goto Exit; 1200 1201 LOGV("prepare"); 1202 player->prepareAsync(); 1203 1204 LOGV("wait for prepare"); 1205 if (cache->wait() != NO_ERROR) goto Exit; 1206 1207 LOGV("start"); 1208 player->start(); 1209 1210 LOGV("wait for playback complete"); 1211 if (cache->wait() != NO_ERROR) goto Exit; 1212 1213 mem = new MemoryBase(cache->getHeap(), 0, cache->size()); 1214 *pSampleRate = cache->sampleRate(); 1215 *pNumChannels = cache->channelCount(); 1216 *pFormat = cache->format(); 1217 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat); 1218 1219Exit: 1220 if (player != 0) player->reset(); 1221 return mem; 1222} 1223 1224sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat) 1225{ 1226 LOGV("decode(%d, %lld, %lld)", fd, offset, length); 1227 sp<MemoryBase> mem; 1228 sp<MediaPlayerBase> player; 1229 1230 player_type playerType = getPlayerType(fd, offset, length); 1231 LOGV("player type = %d", playerType); 1232 1233 // create the right type of player 1234 sp<AudioCache> cache = new AudioCache("decode_fd"); 1235 player = android::createPlayer(playerType, cache.get(), cache->notify); 1236 if (player == NULL) goto Exit; 1237 if (player->hardwareOutput()) goto Exit; 1238 1239 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache); 1240 1241 // set data source 1242 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit; 1243 1244 LOGV("prepare"); 1245 player->prepareAsync(); 1246 1247 LOGV("wait for prepare"); 1248 if (cache->wait() != NO_ERROR) goto Exit; 1249 1250 LOGV("start"); 1251 player->start(); 1252 1253 LOGV("wait for playback complete"); 1254 if (cache->wait() != NO_ERROR) goto Exit; 1255 1256 mem = new MemoryBase(cache->getHeap(), 0, cache->size()); 1257 *pSampleRate = cache->sampleRate(); 1258 *pNumChannels = cache->channelCount(); 1259 *pFormat = cache->format(); 1260 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat); 1261 1262Exit: 1263 if (player != 0) player->reset(); 1264 ::close(fd); 1265 return mem; 1266} 1267 1268 1269#undef LOG_TAG 1270#define LOG_TAG "AudioSink" 1271MediaPlayerService::AudioOutput::AudioOutput(int sessionId) 1272 : mCallback(NULL), 1273 mCallbackCookie(NULL), 1274 mSessionId(sessionId) { 1275 LOGV("AudioOutput(%d)", sessionId); 1276 mTrack = 0; 1277 mStreamType = AudioSystem::MUSIC; 1278 mLeftVolume = 1.0; 1279 mRightVolume = 1.0; 1280 mLatency = 0; 1281 mMsecsPerFrame = 0; 1282 setMinBufferCount(); 1283} 1284 1285MediaPlayerService::AudioOutput::~AudioOutput() 1286{ 1287 close(); 1288} 1289 1290void MediaPlayerService::AudioOutput::setMinBufferCount() 1291{ 1292 char value[PROPERTY_VALUE_MAX]; 1293 if (property_get("ro.kernel.qemu", value, 0)) { 1294 mIsOnEmulator = true; 1295 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator 1296 } 1297} 1298 1299bool MediaPlayerService::AudioOutput::isOnEmulator() 1300{ 1301 setMinBufferCount(); 1302 return mIsOnEmulator; 1303} 1304 1305int MediaPlayerService::AudioOutput::getMinBufferCount() 1306{ 1307 setMinBufferCount(); 1308 return mMinBufferCount; 1309} 1310 1311ssize_t MediaPlayerService::AudioOutput::bufferSize() const 1312{ 1313 if (mTrack == 0) return NO_INIT; 1314 return mTrack->frameCount() * frameSize(); 1315} 1316 1317ssize_t MediaPlayerService::AudioOutput::frameCount() const 1318{ 1319 if (mTrack == 0) return NO_INIT; 1320 return mTrack->frameCount(); 1321} 1322 1323ssize_t MediaPlayerService::AudioOutput::channelCount() const 1324{ 1325 if (mTrack == 0) return NO_INIT; 1326 return mTrack->channelCount(); 1327} 1328 1329ssize_t MediaPlayerService::AudioOutput::frameSize() const 1330{ 1331 if (mTrack == 0) return NO_INIT; 1332 return mTrack->frameSize(); 1333} 1334 1335uint32_t MediaPlayerService::AudioOutput::latency () const 1336{ 1337 return mLatency; 1338} 1339 1340float MediaPlayerService::AudioOutput::msecsPerFrame() const 1341{ 1342 return mMsecsPerFrame; 1343} 1344 1345status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) 1346{ 1347 if (mTrack == 0) return NO_INIT; 1348 return mTrack->getPosition(position); 1349} 1350 1351status_t MediaPlayerService::AudioOutput::open( 1352 uint32_t sampleRate, int channelCount, int format, int bufferCount, 1353 AudioCallback cb, void *cookie) 1354{ 1355 mCallback = cb; 1356 mCallbackCookie = cookie; 1357 1358 // Check argument "bufferCount" against the mininum buffer count 1359 if (bufferCount < mMinBufferCount) { 1360 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount); 1361 bufferCount = mMinBufferCount; 1362 1363 } 1364 LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId); 1365 if (mTrack) close(); 1366 int afSampleRate; 1367 int afFrameCount; 1368 int frameCount; 1369 1370 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) { 1371 return NO_INIT; 1372 } 1373 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) { 1374 return NO_INIT; 1375 } 1376 1377 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate; 1378 1379 AudioTrack *t; 1380 if (mCallback != NULL) { 1381 t = new AudioTrack( 1382 mStreamType, 1383 sampleRate, 1384 format, 1385 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO, 1386 frameCount, 1387 0 /* flags */, 1388 CallbackWrapper, 1389 this, 1390 0, 1391 mSessionId); 1392 } else { 1393 t = new AudioTrack( 1394 mStreamType, 1395 sampleRate, 1396 format, 1397 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO, 1398 frameCount, 1399 0, 1400 NULL, 1401 NULL, 1402 0, 1403 mSessionId); 1404 } 1405 1406 if ((t == 0) || (t->initCheck() != NO_ERROR)) { 1407 LOGE("Unable to create audio track"); 1408 delete t; 1409 return NO_INIT; 1410 } 1411 1412 LOGV("setVolume"); 1413 t->setVolume(mLeftVolume, mRightVolume); 1414 mMsecsPerFrame = 1.e3 / (float) sampleRate; 1415 mLatency = t->latency(); 1416 mTrack = t; 1417 return NO_ERROR; 1418} 1419 1420void MediaPlayerService::AudioOutput::start() 1421{ 1422 LOGV("start"); 1423 if (mTrack) { 1424 mTrack->setVolume(mLeftVolume, mRightVolume); 1425 mTrack->start(); 1426 } 1427} 1428 1429 1430 1431ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size) 1432{ 1433 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback."); 1434 1435 //LOGV("write(%p, %u)", buffer, size); 1436 if (mTrack) { 1437 ssize_t ret = mTrack->write(buffer, size); 1438 return ret; 1439 } 1440 return NO_INIT; 1441} 1442 1443void MediaPlayerService::AudioOutput::stop() 1444{ 1445 LOGV("stop"); 1446 if (mTrack) mTrack->stop(); 1447} 1448 1449void MediaPlayerService::AudioOutput::flush() 1450{ 1451 LOGV("flush"); 1452 if (mTrack) mTrack->flush(); 1453} 1454 1455void MediaPlayerService::AudioOutput::pause() 1456{ 1457 LOGV("pause"); 1458 if (mTrack) mTrack->pause(); 1459} 1460 1461void MediaPlayerService::AudioOutput::close() 1462{ 1463 LOGV("close"); 1464 delete mTrack; 1465 mTrack = 0; 1466} 1467 1468void MediaPlayerService::AudioOutput::setVolume(float left, float right) 1469{ 1470 LOGV("setVolume(%f, %f)", left, right); 1471 mLeftVolume = left; 1472 mRightVolume = right; 1473 if (mTrack) { 1474 mTrack->setVolume(left, right); 1475 } 1476} 1477 1478// static 1479void MediaPlayerService::AudioOutput::CallbackWrapper( 1480 int event, void *cookie, void *info) { 1481 //LOGV("callbackwrapper"); 1482 if (event != AudioTrack::EVENT_MORE_DATA) { 1483 return; 1484 } 1485 1486 AudioOutput *me = (AudioOutput *)cookie; 1487 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info; 1488 1489 size_t actualSize = (*me->mCallback)( 1490 me, buffer->raw, buffer->size, me->mCallbackCookie); 1491 1492 buffer->size = actualSize; 1493 1494} 1495 1496#undef LOG_TAG 1497#define LOG_TAG "AudioCache" 1498MediaPlayerService::AudioCache::AudioCache(const char* name) : 1499 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0), 1500 mError(NO_ERROR), mCommandComplete(false) 1501{ 1502 // create ashmem heap 1503 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name); 1504} 1505 1506uint32_t MediaPlayerService::AudioCache::latency () const 1507{ 1508 return 0; 1509} 1510 1511float MediaPlayerService::AudioCache::msecsPerFrame() const 1512{ 1513 return mMsecsPerFrame; 1514} 1515 1516status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position) 1517{ 1518 if (position == 0) return BAD_VALUE; 1519 *position = mSize; 1520 return NO_ERROR; 1521} 1522 1523//////////////////////////////////////////////////////////////////////////////// 1524 1525struct CallbackThread : public Thread { 1526 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink, 1527 MediaPlayerBase::AudioSink::AudioCallback cb, 1528 void *cookie); 1529 1530protected: 1531 virtual ~CallbackThread(); 1532 1533 virtual bool threadLoop(); 1534 1535private: 1536 wp<MediaPlayerBase::AudioSink> mSink; 1537 MediaPlayerBase::AudioSink::AudioCallback mCallback; 1538 void *mCookie; 1539 void *mBuffer; 1540 size_t mBufferSize; 1541 1542 CallbackThread(const CallbackThread &); 1543 CallbackThread &operator=(const CallbackThread &); 1544}; 1545 1546CallbackThread::CallbackThread( 1547 const wp<MediaPlayerBase::AudioSink> &sink, 1548 MediaPlayerBase::AudioSink::AudioCallback cb, 1549 void *cookie) 1550 : mSink(sink), 1551 mCallback(cb), 1552 mCookie(cookie), 1553 mBuffer(NULL), 1554 mBufferSize(0) { 1555} 1556 1557CallbackThread::~CallbackThread() { 1558 if (mBuffer) { 1559 free(mBuffer); 1560 mBuffer = NULL; 1561 } 1562} 1563 1564bool CallbackThread::threadLoop() { 1565 sp<MediaPlayerBase::AudioSink> sink = mSink.promote(); 1566 if (sink == NULL) { 1567 return false; 1568 } 1569 1570 if (mBuffer == NULL) { 1571 mBufferSize = sink->bufferSize(); 1572 mBuffer = malloc(mBufferSize); 1573 } 1574 1575 size_t actualSize = 1576 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie); 1577 1578 if (actualSize > 0) { 1579 sink->write(mBuffer, actualSize); 1580 } 1581 1582 return true; 1583} 1584 1585//////////////////////////////////////////////////////////////////////////////// 1586 1587status_t MediaPlayerService::AudioCache::open( 1588 uint32_t sampleRate, int channelCount, int format, int bufferCount, 1589 AudioCallback cb, void *cookie) 1590{ 1591 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount); 1592 if (mHeap->getHeapID() < 0) { 1593 return NO_INIT; 1594 } 1595 1596 mSampleRate = sampleRate; 1597 mChannelCount = (uint16_t)channelCount; 1598 mFormat = (uint16_t)format; 1599 mMsecsPerFrame = 1.e3 / (float) sampleRate; 1600 1601 if (cb != NULL) { 1602 mCallbackThread = new CallbackThread(this, cb, cookie); 1603 } 1604 return NO_ERROR; 1605} 1606 1607void MediaPlayerService::AudioCache::start() { 1608 if (mCallbackThread != NULL) { 1609 mCallbackThread->run("AudioCache callback"); 1610 } 1611} 1612 1613void MediaPlayerService::AudioCache::stop() { 1614 if (mCallbackThread != NULL) { 1615 mCallbackThread->requestExitAndWait(); 1616 } 1617} 1618 1619ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size) 1620{ 1621 LOGV("write(%p, %u)", buffer, size); 1622 if ((buffer == 0) || (size == 0)) return size; 1623 1624 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase()); 1625 if (p == NULL) return NO_INIT; 1626 p += mSize; 1627 LOGV("memcpy(%p, %p, %u)", p, buffer, size); 1628 if (mSize + size > mHeap->getSize()) { 1629 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize()); 1630 size = mHeap->getSize() - mSize; 1631 } 1632 memcpy(p, buffer, size); 1633 mSize += size; 1634 return size; 1635} 1636 1637// call with lock held 1638status_t MediaPlayerService::AudioCache::wait() 1639{ 1640 Mutex::Autolock lock(mLock); 1641 while (!mCommandComplete) { 1642 mSignal.wait(mLock); 1643 } 1644 mCommandComplete = false; 1645 1646 if (mError == NO_ERROR) { 1647 LOGV("wait - success"); 1648 } else { 1649 LOGV("wait - error"); 1650 } 1651 return mError; 1652} 1653 1654void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2) 1655{ 1656 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2); 1657 AudioCache* p = static_cast<AudioCache*>(cookie); 1658 1659 // ignore buffering messages 1660 switch (msg) 1661 { 1662 case MEDIA_ERROR: 1663 LOGE("Error %d, %d occurred", ext1, ext2); 1664 p->mError = ext1; 1665 break; 1666 case MEDIA_PREPARED: 1667 LOGV("prepared"); 1668 break; 1669 case MEDIA_PLAYBACK_COMPLETE: 1670 LOGV("playback complete"); 1671 break; 1672 default: 1673 LOGV("ignored"); 1674 return; 1675 } 1676 1677 // wake up thread 1678 Mutex::Autolock lock(p->mLock); 1679 p->mCommandComplete = true; 1680 p->mSignal.signal(); 1681} 1682 1683} // namespace android 1684