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