summaryrefslogtreecommitdiffstats
path: root/media/libmediaplayerservice
diff options
context:
space:
mode:
authorThe Android Open Source Project <initial-contribution@android.com>2009-03-03 19:31:44 -0800
committerThe Android Open Source Project <initial-contribution@android.com>2009-03-03 19:31:44 -0800
commit89fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5 (patch)
tree28d26f7b71e943e25c7da6e8043d79b7b8d9cf7b /media/libmediaplayerservice
parent15f767b960b38059a74a42a33e16d8df2aec8bc1 (diff)
downloadframeworks_av-89fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5.zip
frameworks_av-89fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5.tar.gz
frameworks_av-89fa4ad53f2f4d57adbc97ae1149fc00c9b6f3c5.tar.bz2
auto import from //depot/cupcake/@135843
Diffstat (limited to 'media/libmediaplayerservice')
-rw-r--r--media/libmediaplayerservice/Android.mk36
-rw-r--r--media/libmediaplayerservice/MediaPlayerService.cpp1173
-rw-r--r--media/libmediaplayerservice/MediaPlayerService.h238
-rw-r--r--media/libmediaplayerservice/MediaRecorderClient.cpp273
-rw-r--r--media/libmediaplayerservice/MediaRecorderClient.h66
-rw-r--r--media/libmediaplayerservice/MetadataRetrieverClient.cpp250
-rw-r--r--media/libmediaplayerservice/MetadataRetrieverClient.h71
-rw-r--r--media/libmediaplayerservice/MidiFile.cpp558
-rw-r--r--media/libmediaplayerservice/MidiFile.h77
-rw-r--r--media/libmediaplayerservice/VorbisPlayer.cpp529
-rw-r--r--media/libmediaplayerservice/VorbisPlayer.h91
11 files changed, 3362 insertions, 0 deletions
diff --git a/media/libmediaplayerservice/Android.mk b/media/libmediaplayerservice/Android.mk
new file mode 100644
index 0000000..f710921
--- /dev/null
+++ b/media/libmediaplayerservice/Android.mk
@@ -0,0 +1,36 @@
+LOCAL_PATH:= $(call my-dir)
+
+#
+# libmediaplayerservice
+#
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= \
+ MediaRecorderClient.cpp \
+ MediaPlayerService.cpp \
+ MetadataRetrieverClient.cpp \
+ VorbisPlayer.cpp \
+ MidiFile.cpp
+
+ifeq ($(TARGET_OS)-$(TARGET_SIMULATOR),linux-true)
+LOCAL_LDLIBS += -ldl -lpthread
+endif
+
+LOCAL_SHARED_LIBRARIES := \
+ libcutils \
+ libutils \
+ libvorbisidec \
+ libsonivox \
+ libopencoreplayer \
+ libopencoreauthor \
+ libmedia \
+ libandroid_runtime
+
+LOCAL_C_INCLUDES := external/tremor/Tremor \
+ $(call include-path-for, graphics corecg)
+
+LOCAL_MODULE:= libmediaplayerservice
+
+include $(BUILD_SHARED_LIBRARY)
+
diff --git a/media/libmediaplayerservice/MediaPlayerService.cpp b/media/libmediaplayerservice/MediaPlayerService.cpp
new file mode 100644
index 0000000..40705c6
--- /dev/null
+++ b/media/libmediaplayerservice/MediaPlayerService.cpp
@@ -0,0 +1,1173 @@
+/*
+**
+** Copyright 2008, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+** http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+
+// Proxy for media player implementations
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "MediaPlayerService"
+#include <utils/Log.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <dirent.h>
+#include <unistd.h>
+
+#include <string.h>
+#include <cutils/atomic.h>
+
+#include <android_runtime/ActivityManager.h>
+#include <utils/IPCThreadState.h>
+#include <utils/IServiceManager.h>
+#include <utils/MemoryHeapBase.h>
+#include <utils/MemoryBase.h>
+#include <cutils/properties.h>
+
+#include <media/MediaPlayerInterface.h>
+#include <media/mediarecorder.h>
+#include <media/MediaMetadataRetrieverInterface.h>
+#include <media/AudioTrack.h>
+
+#include "MediaRecorderClient.h"
+#include "MediaPlayerService.h"
+#include "MetadataRetrieverClient.h"
+
+#include "MidiFile.h"
+#include "VorbisPlayer.h"
+#include <media/PVPlayer.h>
+
+/* desktop Linux needs a little help with gettid() */
+#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
+#define __KERNEL__
+# include <linux/unistd.h>
+#ifdef _syscall0
+_syscall0(pid_t,gettid)
+#else
+pid_t gettid() { return syscall(__NR_gettid);}
+#endif
+#undef __KERNEL__
+#endif
+
+
+namespace android {
+
+// TODO: Temp hack until we can register players
+typedef struct {
+ const char *extension;
+ const player_type playertype;
+} extmap;
+extmap FILE_EXTS [] = {
+ {".mid", SONIVOX_PLAYER},
+ {".midi", SONIVOX_PLAYER},
+ {".smf", SONIVOX_PLAYER},
+ {".xmf", SONIVOX_PLAYER},
+ {".imy", SONIVOX_PLAYER},
+ {".rtttl", SONIVOX_PLAYER},
+ {".rtx", SONIVOX_PLAYER},
+ {".ota", SONIVOX_PLAYER},
+ {".ogg", VORBIS_PLAYER},
+ {".oga", VORBIS_PLAYER},
+};
+
+// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
+/* static */ const uint32_t MediaPlayerService::AudioOutput::kAudioVideoDelayMs = 96;
+/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
+/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
+
+void MediaPlayerService::instantiate() {
+ defaultServiceManager()->addService(
+ String16("media.player"), new MediaPlayerService());
+}
+
+MediaPlayerService::MediaPlayerService()
+{
+ LOGV("MediaPlayerService created");
+ mNextConnId = 1;
+}
+
+MediaPlayerService::~MediaPlayerService()
+{
+ LOGV("MediaPlayerService destroyed");
+}
+
+sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
+{
+ sp<MediaRecorderClient> recorder = new MediaRecorderClient(pid);
+ LOGV("Create new media recorder client from pid %d", pid);
+ return recorder;
+}
+
+sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
+{
+ sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
+ LOGV("Create new media retriever from pid %d", pid);
+ return retriever;
+}
+
+sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client, const char* url)
+{
+ int32_t connId = android_atomic_inc(&mNextConnId);
+ sp<Client> c = new Client(this, pid, connId, client);
+ LOGV("Create new client(%d) from pid %d, url=%s, connId=%d", connId, pid, url, connId);
+ if (NO_ERROR != c->setDataSource(url))
+ {
+ c.clear();
+ return c;
+ }
+ wp<Client> w = c;
+ Mutex::Autolock lock(mLock);
+ mClients.add(w);
+ return c;
+}
+
+sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
+ int fd, int64_t offset, int64_t length)
+{
+ int32_t connId = android_atomic_inc(&mNextConnId);
+ sp<Client> c = new Client(this, pid, connId, client);
+ LOGV("Create new client(%d) from pid %d, fd=%d, offset=%lld, length=%lld",
+ connId, pid, fd, offset, length);
+ if (NO_ERROR != c->setDataSource(fd, offset, length)) {
+ c.clear();
+ } else {
+ wp<Client> w = c;
+ Mutex::Autolock lock(mLock);
+ mClients.add(w);
+ }
+ ::close(fd);
+ return c;
+}
+
+status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
+{
+ const size_t SIZE = 256;
+ char buffer[SIZE];
+ String8 result;
+
+ result.append(" AudioCache\n");
+ if (mHeap != 0) {
+ snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
+ mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
+ result.append(buffer);
+ }
+ snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
+ mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
+ result.append(buffer);
+ snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
+ mSampleRate, mSize, mError, mCommandComplete?"true":"false");
+ result.append(buffer);
+ ::write(fd, result.string(), result.size());
+ return NO_ERROR;
+}
+
+status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
+{
+ const size_t SIZE = 256;
+ char buffer[SIZE];
+ String8 result;
+
+ result.append(" AudioOutput\n");
+ snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
+ mStreamType, mLeftVolume, mRightVolume);
+ result.append(buffer);
+ snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
+ mMsecsPerFrame, mLatency);
+ result.append(buffer);
+ ::write(fd, result.string(), result.size());
+ if (mTrack != 0) {
+ mTrack->dump(fd, args);
+ }
+ return NO_ERROR;
+}
+
+status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
+{
+ const size_t SIZE = 256;
+ char buffer[SIZE];
+ String8 result;
+ result.append(" Client\n");
+ snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
+ mPid, mConnId, mStatus, mLoop?"true": "false");
+ result.append(buffer);
+ write(fd, result.string(), result.size());
+ if (mAudioOutput != 0) {
+ mAudioOutput->dump(fd, args);
+ }
+ write(fd, "\n", 1);
+ return NO_ERROR;
+}
+
+static int myTid() {
+#ifdef HAVE_GETTID
+ return gettid();
+#else
+ return getpid();
+#endif
+}
+
+#if defined(__arm__)
+extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
+ size_t* infoSize, size_t* totalMemory, size_t* backtraceSize);
+extern "C" void free_malloc_leak_info(uint8_t* info);
+
+void memStatus(int fd, const Vector<String16>& args)
+{
+ const size_t SIZE = 256;
+ char buffer[SIZE];
+ String8 result;
+
+ typedef struct {
+ size_t size;
+ size_t dups;
+ intptr_t * backtrace;
+ } AllocEntry;
+
+ uint8_t *info = NULL;
+ size_t overallSize = 0;
+ size_t infoSize = 0;
+ size_t totalMemory = 0;
+ size_t backtraceSize = 0;
+
+ get_malloc_leak_info(&info, &overallSize, &infoSize, &totalMemory, &backtraceSize);
+ if (info) {
+ uint8_t *ptr = info;
+ size_t count = overallSize / infoSize;
+
+ snprintf(buffer, SIZE, " Allocation count %i\n", count);
+ result.append(buffer);
+
+ AllocEntry * entries = new AllocEntry[count];
+
+ for (size_t i = 0; i < count; i++) {
+ // Each entry should be size_t, size_t, intptr_t[backtraceSize]
+ AllocEntry *e = &entries[i];
+
+ e->size = *reinterpret_cast<size_t *>(ptr);
+ ptr += sizeof(size_t);
+
+ e->dups = *reinterpret_cast<size_t *>(ptr);
+ ptr += sizeof(size_t);
+
+ e->backtrace = reinterpret_cast<intptr_t *>(ptr);
+ ptr += sizeof(intptr_t) * backtraceSize;
+ }
+
+ // Now we need to sort the entries. They come sorted by size but
+ // not by stack trace which causes problems using diff.
+ bool moved;
+ do {
+ moved = false;
+ for (size_t i = 0; i < (count - 1); i++) {
+ AllocEntry *e1 = &entries[i];
+ AllocEntry *e2 = &entries[i+1];
+
+ bool swap = e1->size < e2->size;
+ if (e1->size == e2->size) {
+ for(size_t j = 0; j < backtraceSize; j++) {
+ if (e1->backtrace[j] == e2->backtrace[j]) {
+ continue;
+ }
+ swap = e1->backtrace[j] < e2->backtrace[j];
+ break;
+ }
+ }
+ if (swap) {
+ AllocEntry t = entries[i];
+ entries[i] = entries[i+1];
+ entries[i+1] = t;
+ moved = true;
+ }
+ }
+ } while (moved);
+
+ for (size_t i = 0; i < count; i++) {
+ AllocEntry *e = &entries[i];
+
+ snprintf(buffer, SIZE, "size %8i, dup %4i", e->size, e->dups);
+ result.append(buffer);
+ for (size_t ct = 0; (ct < backtraceSize) && e->backtrace[ct]; ct++) {
+ if (ct) {
+ result.append(", ");
+ }
+ snprintf(buffer, SIZE, "0x%08x", e->backtrace[ct]);
+ result.append(buffer);
+ }
+ result.append("\n");
+ }
+
+ delete[] entries;
+ free_malloc_leak_info(info);
+ }
+
+ write(fd, result.string(), result.size());
+}
+#endif
+
+status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
+{
+ const size_t SIZE = 256;
+ char buffer[SIZE];
+ String8 result;
+ if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
+ snprintf(buffer, SIZE, "Permission Denial: "
+ "can't dump MediaPlayerService from pid=%d, uid=%d\n",
+ IPCThreadState::self()->getCallingPid(),
+ IPCThreadState::self()->getCallingUid());
+ result.append(buffer);
+ } else {
+ Mutex::Autolock lock(mLock);
+ for (int i = 0, n = mClients.size(); i < n; ++i) {
+ sp<Client> c = mClients[i].promote();
+ if (c != 0) c->dump(fd, args);
+ }
+ result.append(" Files opened and/or mapped:\n");
+ snprintf(buffer, SIZE, "/proc/%d/maps", myTid());
+ FILE *f = fopen(buffer, "r");
+ if (f) {
+ while (!feof(f)) {
+ fgets(buffer, SIZE, f);
+ if (strstr(buffer, " /sdcard/") ||
+ strstr(buffer, " /system/sounds/") ||
+ strstr(buffer, " /system/media/")) {
+ result.append(" ");
+ result.append(buffer);
+ }
+ }
+ fclose(f);
+ } else {
+ result.append("couldn't open ");
+ result.append(buffer);
+ result.append("\n");
+ }
+
+ snprintf(buffer, SIZE, "/proc/%d/fd", myTid());
+ DIR *d = opendir(buffer);
+ if (d) {
+ struct dirent *ent;
+ while((ent = readdir(d)) != NULL) {
+ if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
+ snprintf(buffer, SIZE, "/proc/%d/fd/%s", myTid(), ent->d_name);
+ struct stat s;
+ if (lstat(buffer, &s) == 0) {
+ if ((s.st_mode & S_IFMT) == S_IFLNK) {
+ char linkto[256];
+ int len = readlink(buffer, linkto, sizeof(linkto));
+ if(len > 0) {
+ if(len > 255) {
+ linkto[252] = '.';
+ linkto[253] = '.';
+ linkto[254] = '.';
+ linkto[255] = 0;
+ } else {
+ linkto[len] = 0;
+ }
+ if (strstr(linkto, "/sdcard/") == linkto ||
+ strstr(linkto, "/system/sounds/") == linkto ||
+ strstr(linkto, "/system/media/") == linkto) {
+ result.append(" ");
+ result.append(buffer);
+ result.append(" -> ");
+ result.append(linkto);
+ result.append("\n");
+ }
+ }
+ } else {
+ result.append(" unexpected type for ");
+ result.append(buffer);
+ result.append("\n");
+ }
+ }
+ }
+ }
+ closedir(d);
+ } else {
+ result.append("couldn't open ");
+ result.append(buffer);
+ result.append("\n");
+ }
+
+#if defined(__arm__)
+ bool dumpMem = false;
+ for (size_t i = 0; i < args.size(); i++) {
+ if (args[i] == String16("-m")) {
+ dumpMem = true;
+ }
+ }
+ if (dumpMem) {
+ memStatus(fd, args);
+ }
+#endif
+ }
+ write(fd, result.string(), result.size());
+ return NO_ERROR;
+}
+
+void MediaPlayerService::removeClient(wp<Client> client)
+{
+ Mutex::Autolock lock(mLock);
+ mClients.remove(client);
+}
+
+MediaPlayerService::Client::Client(const sp<MediaPlayerService>& service, pid_t pid,
+ int32_t connId, const sp<IMediaPlayerClient>& client)
+{
+ LOGV("Client(%d) constructor", connId);
+ mPid = pid;
+ mConnId = connId;
+ mService = service;
+ mClient = client;
+ mLoop = false;
+ mStatus = NO_INIT;
+#if CALLBACK_ANTAGONIZER
+ LOGD("create Antagonizer");
+ mAntagonizer = new Antagonizer(notify, this);
+#endif
+}
+
+MediaPlayerService::Client::~Client()
+{
+ LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
+ mAudioOutput.clear();
+ wp<Client> client(this);
+ disconnect();
+ mService->removeClient(client);
+}
+
+void MediaPlayerService::Client::disconnect()
+{
+ LOGV("disconnect(%d) from pid %d", mConnId, mPid);
+ // grab local reference and clear main reference to prevent future
+ // access to object
+ sp<MediaPlayerBase> p;
+ {
+ Mutex::Autolock l(mLock);
+ p = mPlayer;
+ }
+ mPlayer.clear();
+
+ // clear the notification to prevent callbacks to dead client
+ // and reset the player. We assume the player will serialize
+ // access to itself if necessary.
+ if (p != 0) {
+ p->setNotifyCallback(0, 0);
+#if CALLBACK_ANTAGONIZER
+ LOGD("kill Antagonizer");
+ mAntagonizer->kill();
+#endif
+ p->reset();
+ }
+
+ IPCThreadState::self()->flushCommands();
+}
+
+static player_type getPlayerType(int fd, int64_t offset, int64_t length)
+{
+ char buf[20];
+ lseek(fd, offset, SEEK_SET);
+ read(fd, buf, sizeof(buf));
+ lseek(fd, offset, SEEK_SET);
+
+ long ident = *((long*)buf);
+
+ // Ogg vorbis?
+ if (ident == 0x5367674f) // 'OggS'
+ return VORBIS_PLAYER;
+
+ // Some kind of MIDI?
+ EAS_DATA_HANDLE easdata;
+ if (EAS_Init(&easdata) == EAS_SUCCESS) {
+ EAS_FILE locator;
+ locator.path = NULL;
+ locator.fd = fd;
+ locator.offset = offset;
+ locator.length = length;
+ EAS_HANDLE eashandle;
+ if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
+ EAS_CloseFile(easdata, eashandle);
+ EAS_Shutdown(easdata);
+ return SONIVOX_PLAYER;
+ }
+ EAS_Shutdown(easdata);
+ }
+
+ // Fall through to PV
+ return PV_PLAYER;
+}
+
+static player_type getPlayerType(const char* url)
+{
+
+ // use MidiFile for MIDI extensions
+ int lenURL = strlen(url);
+ for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
+ int len = strlen(FILE_EXTS[i].extension);
+ int start = lenURL - len;
+ if (start > 0) {
+ if (!strncmp(url + start, FILE_EXTS[i].extension, len)) {
+ return FILE_EXTS[i].playertype;
+ }
+ }
+ }
+
+ // Fall through to PV
+ return PV_PLAYER;
+}
+
+static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
+ notify_callback_f notifyFunc)
+{
+ sp<MediaPlayerBase> p;
+ switch (playerType) {
+ case PV_PLAYER:
+ LOGV(" create PVPlayer");
+ p = new PVPlayer();
+ break;
+ case SONIVOX_PLAYER:
+ LOGV(" create MidiFile");
+ p = new MidiFile();
+ break;
+ case VORBIS_PLAYER:
+ LOGV(" create VorbisPlayer");
+ p = new VorbisPlayer();
+ break;
+ }
+ if (p != NULL) {
+ if (p->initCheck() == NO_ERROR) {
+ p->setNotifyCallback(cookie, notifyFunc);
+ } else {
+ p.clear();
+ }
+ }
+ if (p == NULL) {
+ LOGE("Failed to create player object");
+ }
+ return p;
+}
+
+sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
+{
+ // determine if we have the right player type
+ sp<MediaPlayerBase> p = mPlayer;
+ if ((p != NULL) && (p->playerType() != playerType)) {
+ LOGV("delete player");
+ p.clear();
+ }
+ if (p == NULL) {
+ p = android::createPlayer(playerType, this, notify);
+ }
+ return p;
+}
+
+status_t MediaPlayerService::Client::setDataSource(const char *url)
+{
+ LOGV("setDataSource(%s)", url);
+ if (url == NULL)
+ return UNKNOWN_ERROR;
+
+ if (strncmp(url, "content://", 10) == 0) {
+ // get a filedescriptor for the content Uri and
+ // pass it to the setDataSource(fd) method
+
+ String16 url16(url);
+ int fd = android::openContentProviderFile(url16);
+ if (fd < 0)
+ {
+ LOGE("Couldn't open fd for %s", url);
+ return UNKNOWN_ERROR;
+ }
+ setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
+ close(fd);
+ return mStatus;
+ } else {
+ player_type playerType = getPlayerType(url);
+ LOGV("player type = %d", playerType);
+
+ // create the right type of player
+ sp<MediaPlayerBase> p = createPlayer(playerType);
+ if (p == NULL) return NO_INIT;
+
+ if (!p->hardwareOutput()) {
+ mAudioOutput = new AudioOutput();
+ static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
+ }
+
+ // now set data source
+ LOGV(" setDataSource");
+ mStatus = p->setDataSource(url);
+ if (mStatus == NO_ERROR) mPlayer = p;
+ return mStatus;
+ }
+}
+
+status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
+{
+ LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
+ struct stat sb;
+ int ret = fstat(fd, &sb);
+ if (ret != 0) {
+ LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
+ return UNKNOWN_ERROR;
+ }
+
+ LOGV("st_dev = %llu", sb.st_dev);
+ LOGV("st_mode = %u", sb.st_mode);
+ LOGV("st_uid = %lu", sb.st_uid);
+ LOGV("st_gid = %lu", sb.st_gid);
+ LOGV("st_size = %llu", sb.st_size);
+
+ if (offset >= sb.st_size) {
+ LOGE("offset error");
+ ::close(fd);
+ return UNKNOWN_ERROR;
+ }
+ if (offset + length > sb.st_size) {
+ length = sb.st_size - offset;
+ LOGV("calculated length = %lld", length);
+ }
+
+ player_type playerType = getPlayerType(fd, offset, length);
+ LOGV("player type = %d", playerType);
+
+ // create the right type of player
+ sp<MediaPlayerBase> p = createPlayer(playerType);
+ if (p == NULL) return NO_INIT;
+
+ if (!p->hardwareOutput()) {
+ mAudioOutput = new AudioOutput();
+ static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
+ }
+
+ // now set data source
+ mStatus = p->setDataSource(fd, offset, length);
+ if (mStatus == NO_ERROR) mPlayer = p;
+ return mStatus;
+}
+
+status_t MediaPlayerService::Client::setVideoSurface(const sp<ISurface>& surface)
+{
+ LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
+ sp<MediaPlayerBase> p = getPlayer();
+ if (p == 0) return UNKNOWN_ERROR;
+ return p->setVideoSurface(surface);
+}
+
+status_t MediaPlayerService::Client::prepareAsync()
+{
+ LOGV("[%d] prepareAsync", mConnId);
+ sp<MediaPlayerBase> p = getPlayer();
+ if (p == 0) return UNKNOWN_ERROR;
+ status_t ret = p->prepareAsync();
+#if CALLBACK_ANTAGONIZER
+ LOGD("start Antagonizer");
+ if (ret == NO_ERROR) mAntagonizer->start();
+#endif
+ return ret;
+}
+
+status_t MediaPlayerService::Client::start()
+{
+ LOGV("[%d] start", mConnId);
+ sp<MediaPlayerBase> p = getPlayer();
+ if (p == 0) return UNKNOWN_ERROR;
+ p->setLooping(mLoop);
+ return p->start();
+}
+
+status_t MediaPlayerService::Client::stop()
+{
+ LOGV("[%d] stop", mConnId);
+ sp<MediaPlayerBase> p = getPlayer();
+ if (p == 0) return UNKNOWN_ERROR;
+ return p->stop();
+}
+
+status_t MediaPlayerService::Client::pause()
+{
+ LOGV("[%d] pause", mConnId);
+ sp<MediaPlayerBase> p = getPlayer();
+ if (p == 0) return UNKNOWN_ERROR;
+ return p->pause();
+}
+
+status_t MediaPlayerService::Client::isPlaying(bool* state)
+{
+ *state = false;
+ sp<MediaPlayerBase> p = getPlayer();
+ if (p == 0) return UNKNOWN_ERROR;
+ *state = p->isPlaying();
+ LOGV("[%d] isPlaying: %d", mConnId, *state);
+ return NO_ERROR;
+}
+
+status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
+{
+ LOGV("getCurrentPosition");
+ sp<MediaPlayerBase> p = getPlayer();
+ if (p == 0) return UNKNOWN_ERROR;
+ status_t ret = p->getCurrentPosition(msec);
+ if (ret == NO_ERROR) {
+ LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
+ } else {
+ LOGE("getCurrentPosition returned %d", ret);
+ }
+ return ret;
+}
+
+status_t MediaPlayerService::Client::getDuration(int *msec)
+{
+ LOGV("getDuration");
+ sp<MediaPlayerBase> p = getPlayer();
+ if (p == 0) return UNKNOWN_ERROR;
+ status_t ret = p->getDuration(msec);
+ if (ret == NO_ERROR) {
+ LOGV("[%d] getDuration = %d", mConnId, *msec);
+ } else {
+ LOGE("getDuration returned %d", ret);
+ }
+ return ret;
+}
+
+status_t MediaPlayerService::Client::seekTo(int msec)
+{
+ LOGV("[%d] seekTo(%d)", mConnId, msec);
+ sp<MediaPlayerBase> p = getPlayer();
+ if (p == 0) return UNKNOWN_ERROR;
+ return p->seekTo(msec);
+}
+
+status_t MediaPlayerService::Client::reset()
+{
+ LOGV("[%d] reset", mConnId);
+ sp<MediaPlayerBase> p = getPlayer();
+ if (p == 0) return UNKNOWN_ERROR;
+ return p->reset();
+}
+
+status_t MediaPlayerService::Client::setAudioStreamType(int type)
+{
+ LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
+ // TODO: for hardware output, call player instead
+ Mutex::Autolock l(mLock);
+ if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
+ return NO_ERROR;
+}
+
+status_t MediaPlayerService::Client::setLooping(int loop)
+{
+ LOGV("[%d] setLooping(%d)", mConnId, loop);
+ mLoop = loop;
+ sp<MediaPlayerBase> p = getPlayer();
+ if (p != 0) return p->setLooping(loop);
+ return NO_ERROR;
+}
+
+status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
+{
+ LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
+ // TODO: for hardware output, call player instead
+ Mutex::Autolock l(mLock);
+ if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
+ return NO_ERROR;
+}
+
+void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2)
+{
+ Client* client = static_cast<Client*>(cookie);
+ LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
+ client->mClient->notify(msg, ext1, ext2);
+}
+
+#if CALLBACK_ANTAGONIZER
+const int Antagonizer::interval = 10000; // 10 msecs
+
+Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
+ mExit(false), mActive(false), mClient(client), mCb(cb)
+{
+ createThread(callbackThread, this);
+}
+
+void Antagonizer::kill()
+{
+ Mutex::Autolock _l(mLock);
+ mActive = false;
+ mExit = true;
+ mCondition.wait(mLock);
+}
+
+int Antagonizer::callbackThread(void* user)
+{
+ LOGD("Antagonizer started");
+ Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
+ while (!p->mExit) {
+ if (p->mActive) {
+ LOGV("send event");
+ p->mCb(p->mClient, 0, 0, 0);
+ }
+ usleep(interval);
+ }
+ Mutex::Autolock _l(p->mLock);
+ p->mCondition.signal();
+ LOGD("Antagonizer stopped");
+ return 0;
+}
+#endif
+
+static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
+
+sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
+{
+ LOGV("decode(%s)", url);
+ sp<MemoryBase> mem;
+ sp<MediaPlayerBase> player;
+
+ // Protect our precious, precious DRMd ringtones by only allowing
+ // decoding of http, but not filesystem paths or content Uris.
+ // If the application wants to decode those, it should open a
+ // filedescriptor for them and use that.
+ if (url != NULL && strncmp(url, "http://", 7) != 0) {
+ LOGD("Can't decode %s by path, use filedescriptor instead", url);
+ return mem;
+ }
+
+ player_type playerType = getPlayerType(url);
+ LOGV("player type = %d", playerType);
+
+ // create the right type of player
+ sp<AudioCache> cache = new AudioCache(url);
+ player = android::createPlayer(playerType, cache.get(), cache->notify);
+ if (player == NULL) goto Exit;
+ if (player->hardwareOutput()) goto Exit;
+
+ static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
+
+ // set data source
+ if (player->setDataSource(url) != NO_ERROR) goto Exit;
+
+ LOGV("prepare");
+ player->prepareAsync();
+
+ LOGV("wait for prepare");
+ if (cache->wait() != NO_ERROR) goto Exit;
+
+ LOGV("start");
+ player->start();
+
+ LOGV("wait for playback complete");
+ if (cache->wait() != NO_ERROR) goto Exit;
+
+ mem = new MemoryBase(cache->getHeap(), 0, cache->size());
+ *pSampleRate = cache->sampleRate();
+ *pNumChannels = cache->channelCount();
+ *pFormat = cache->format();
+ LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
+
+Exit:
+ if (player != 0) player->reset();
+ return mem;
+}
+
+sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
+{
+ LOGV("decode(%d, %lld, %lld)", fd, offset, length);
+ sp<MemoryBase> mem;
+ sp<MediaPlayerBase> player;
+
+ player_type playerType = getPlayerType(fd, offset, length);
+ LOGV("player type = %d", playerType);
+
+ // create the right type of player
+ sp<AudioCache> cache = new AudioCache("decode_fd");
+ player = android::createPlayer(playerType, cache.get(), cache->notify);
+ if (player == NULL) goto Exit;
+ if (player->hardwareOutput()) goto Exit;
+
+ static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
+
+ // set data source
+ if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
+
+ LOGV("prepare");
+ player->prepareAsync();
+
+ LOGV("wait for prepare");
+ if (cache->wait() != NO_ERROR) goto Exit;
+
+ LOGV("start");
+ player->start();
+
+ LOGV("wait for playback complete");
+ if (cache->wait() != NO_ERROR) goto Exit;
+
+ mem = new MemoryBase(cache->getHeap(), 0, cache->size());
+ *pSampleRate = cache->sampleRate();
+ *pNumChannels = cache->channelCount();
+ *pFormat = cache->format();
+ LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
+
+Exit:
+ if (player != 0) player->reset();
+ ::close(fd);
+ return mem;
+}
+
+#undef LOG_TAG
+#define LOG_TAG "AudioSink"
+MediaPlayerService::AudioOutput::AudioOutput()
+{
+ mTrack = 0;
+ mStreamType = AudioSystem::MUSIC;
+ mLeftVolume = 1.0;
+ mRightVolume = 1.0;
+ mLatency = 0;
+ mMsecsPerFrame = 0;
+ setMinBufferCount();
+}
+
+MediaPlayerService::AudioOutput::~AudioOutput()
+{
+ close();
+}
+
+void MediaPlayerService::AudioOutput::setMinBufferCount()
+{
+ char value[PROPERTY_VALUE_MAX];
+ if (property_get("ro.kernel.qemu", value, 0)) {
+ mIsOnEmulator = true;
+ mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
+ }
+}
+
+bool MediaPlayerService::AudioOutput::isOnEmulator()
+{
+ setMinBufferCount();
+ return mIsOnEmulator;
+}
+
+int MediaPlayerService::AudioOutput::getMinBufferCount()
+{
+ setMinBufferCount();
+ return mMinBufferCount;
+}
+
+ssize_t MediaPlayerService::AudioOutput::bufferSize() const
+{
+ if (mTrack == 0) return NO_INIT;
+ return mTrack->frameCount() * frameSize();
+}
+
+ssize_t MediaPlayerService::AudioOutput::frameCount() const
+{
+ if (mTrack == 0) return NO_INIT;
+ return mTrack->frameCount();
+}
+
+ssize_t MediaPlayerService::AudioOutput::channelCount() const
+{
+ if (mTrack == 0) return NO_INIT;
+ return mTrack->channelCount();
+}
+
+ssize_t MediaPlayerService::AudioOutput::frameSize() const
+{
+ if (mTrack == 0) return NO_INIT;
+ return mTrack->frameSize();
+}
+
+uint32_t MediaPlayerService::AudioOutput::latency () const
+{
+ return mLatency;
+}
+
+float MediaPlayerService::AudioOutput::msecsPerFrame() const
+{
+ return mMsecsPerFrame;
+}
+
+status_t MediaPlayerService::AudioOutput::open(uint32_t sampleRate, int channelCount, int format, int bufferCount)
+{
+ // Check argument "bufferCount" against the mininum buffer count
+ if (bufferCount < mMinBufferCount) {
+ LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
+ bufferCount = mMinBufferCount;
+
+ }
+ LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
+ if (mTrack) close();
+ int afSampleRate;
+ int afFrameCount;
+ int frameCount;
+
+ if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
+ return NO_INIT;
+ }
+ if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
+ return NO_INIT;
+ }
+
+ frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
+ AudioTrack *t = new AudioTrack(mStreamType, sampleRate, format, channelCount, frameCount);
+ if ((t == 0) || (t->initCheck() != NO_ERROR)) {
+ LOGE("Unable to create audio track");
+ delete t;
+ return NO_INIT;
+ }
+
+ LOGV("setVolume");
+ t->setVolume(mLeftVolume, mRightVolume);
+ mMsecsPerFrame = 1.e3 / (float) sampleRate;
+ mLatency = t->latency() + kAudioVideoDelayMs;
+ mTrack = t;
+ return NO_ERROR;
+}
+
+void MediaPlayerService::AudioOutput::start()
+{
+ LOGV("start");
+ if (mTrack) {
+ mTrack->setVolume(mLeftVolume, mRightVolume);
+ mTrack->start();
+ }
+}
+
+ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
+{
+ //LOGV("write(%p, %u)", buffer, size);
+ if (mTrack) return mTrack->write(buffer, size);
+ return NO_INIT;
+}
+
+void MediaPlayerService::AudioOutput::stop()
+{
+ LOGV("stop");
+ if (mTrack) mTrack->stop();
+}
+
+void MediaPlayerService::AudioOutput::flush()
+{
+ LOGV("flush");
+ if (mTrack) mTrack->flush();
+}
+
+void MediaPlayerService::AudioOutput::pause()
+{
+ LOGV("pause");
+ if (mTrack) mTrack->pause();
+}
+
+void MediaPlayerService::AudioOutput::close()
+{
+ LOGV("close");
+ delete mTrack;
+ mTrack = 0;
+}
+
+void MediaPlayerService::AudioOutput::setVolume(float left, float right)
+{
+ LOGV("setVolume(%f, %f)", left, right);
+ mLeftVolume = left;
+ mRightVolume = right;
+ if (mTrack) {
+ mTrack->setVolume(left, right);
+ }
+}
+
+#undef LOG_TAG
+#define LOG_TAG "AudioCache"
+MediaPlayerService::AudioCache::AudioCache(const char* name) :
+ mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
+ mError(NO_ERROR), mCommandComplete(false)
+{
+ // create ashmem heap
+ mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
+}
+
+uint32_t MediaPlayerService::AudioCache::latency () const
+{
+ return 0;
+}
+
+float MediaPlayerService::AudioCache::msecsPerFrame() const
+{
+ return mMsecsPerFrame;
+}
+
+status_t MediaPlayerService::AudioCache::open(uint32_t sampleRate, int channelCount, int format, int bufferCount)
+{
+ LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
+ if (mHeap->getHeapID() < 0) return NO_INIT;
+ mSampleRate = sampleRate;
+ mChannelCount = (uint16_t)channelCount;
+ mFormat = (uint16_t)format;
+ mMsecsPerFrame = 1.e3 / (float) sampleRate;
+ return NO_ERROR;
+}
+
+ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
+{
+ LOGV("write(%p, %u)", buffer, size);
+ if ((buffer == 0) || (size == 0)) return size;
+
+ uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
+ if (p == NULL) return NO_INIT;
+ p += mSize;
+ LOGV("memcpy(%p, %p, %u)", p, buffer, size);
+ if (mSize + size > mHeap->getSize()) {
+ LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
+ size = mHeap->getSize() - mSize;
+ }
+ memcpy(p, buffer, size);
+ mSize += size;
+ return size;
+}
+
+// call with lock held
+status_t MediaPlayerService::AudioCache::wait()
+{
+ Mutex::Autolock lock(mLock);
+ if (!mCommandComplete) {
+ mSignal.wait(mLock);
+ }
+ mCommandComplete = false;
+
+ if (mError == NO_ERROR) {
+ LOGV("wait - success");
+ } else {
+ LOGV("wait - error");
+ }
+ return mError;
+}
+
+void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2)
+{
+ LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
+ AudioCache* p = static_cast<AudioCache*>(cookie);
+
+ // ignore buffering messages
+ if (msg == MEDIA_BUFFERING_UPDATE) return;
+
+ // set error condition
+ if (msg == MEDIA_ERROR) {
+ LOGE("Error %d, %d occurred", ext1, ext2);
+ p->mError = ext1;
+ }
+
+ // wake up thread
+ LOGV("wakeup thread");
+ p->mCommandComplete = true;
+ p->mSignal.signal();
+}
+
+}; // namespace android
diff --git a/media/libmediaplayerservice/MediaPlayerService.h b/media/libmediaplayerservice/MediaPlayerService.h
new file mode 100644
index 0000000..f138886
--- /dev/null
+++ b/media/libmediaplayerservice/MediaPlayerService.h
@@ -0,0 +1,238 @@
+/*
+**
+** Copyright 2008, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+** http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+
+#ifndef ANDROID_MEDIAPLAYERSERVICE_H
+#define ANDROID_MEDIAPLAYERSERVICE_H
+
+#include <utils.h>
+#include <utils/KeyedVector.h>
+#include <ui/SurfaceComposerClient.h>
+
+#include <media/IMediaPlayerService.h>
+#include <media/MediaPlayerInterface.h>
+
+namespace android {
+
+class IMediaRecorder;
+class IMediaMetadataRetriever;
+
+#define CALLBACK_ANTAGONIZER 0
+#if CALLBACK_ANTAGONIZER
+class Antagonizer {
+public:
+ Antagonizer(notify_callback_f cb, void* client);
+ void start() { mActive = true; }
+ void stop() { mActive = false; }
+ void kill();
+private:
+ static const int interval;
+ Antagonizer();
+ static int callbackThread(void* cookie);
+ Mutex mLock;
+ Condition mCondition;
+ bool mExit;
+ bool mActive;
+ void* mClient;
+ notify_callback_f mCb;
+};
+#endif
+
+class MediaPlayerService : public BnMediaPlayerService
+{
+ class Client;
+
+ class AudioOutput : public MediaPlayerBase::AudioSink
+ {
+ public:
+ AudioOutput();
+ virtual ~AudioOutput();
+
+ virtual bool ready() const { return mTrack != NULL; }
+ virtual bool realtime() const { return true; }
+ virtual ssize_t bufferSize() const;
+ virtual ssize_t frameCount() const;
+ virtual ssize_t channelCount() const;
+ virtual ssize_t frameSize() const;
+ virtual uint32_t latency() const;
+ virtual float msecsPerFrame() const;
+ virtual status_t open(uint32_t sampleRate, int channelCount, int format, int bufferCount=4);
+ virtual void start();
+ virtual ssize_t write(const void* buffer, size_t size);
+ virtual void stop();
+ virtual void flush();
+ virtual void pause();
+ virtual void close();
+ void setAudioStreamType(int streamType) { mStreamType = streamType; }
+ void setVolume(float left, float right);
+ virtual status_t dump(int fd, const Vector<String16>& args) const;
+
+ static bool isOnEmulator();
+ static int getMinBufferCount();
+ private:
+ static void setMinBufferCount();
+
+ AudioTrack* mTrack;
+ int mStreamType;
+ float mLeftVolume;
+ float mRightVolume;
+ float mMsecsPerFrame;
+ uint32_t mLatency;
+
+ // TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
+ static const uint32_t kAudioVideoDelayMs;
+ static bool mIsOnEmulator;
+ static int mMinBufferCount; // 12 for emulator; otherwise 4
+
+ };
+
+ class AudioCache : public MediaPlayerBase::AudioSink
+ {
+ public:
+ AudioCache(const char* name);
+ virtual ~AudioCache() {}
+
+ virtual bool ready() const { return (mChannelCount > 0) && (mHeap->getHeapID() > 0); }
+ virtual bool realtime() const { return false; }
+ virtual ssize_t bufferSize() const { return frameSize() * mFrameCount; }
+ virtual ssize_t frameCount() const { return mFrameCount; }
+ virtual ssize_t channelCount() const { return (ssize_t)mChannelCount; }
+ virtual ssize_t frameSize() const { return ssize_t(mChannelCount * ((mFormat == AudioSystem::PCM_16_BIT)?sizeof(int16_t):sizeof(u_int8_t))); }
+ virtual uint32_t latency() const;
+ virtual float msecsPerFrame() const;
+ virtual status_t open(uint32_t sampleRate, int channelCount, int format, int bufferCount=1);
+ virtual void start() {}
+ virtual ssize_t write(const void* buffer, size_t size);
+ virtual void stop() {}
+ virtual void flush() {}
+ virtual void pause() {}
+ virtual void close() {}
+ void setAudioStreamType(int streamType) {}
+ void setVolume(float left, float right) {}
+ uint32_t sampleRate() const { return mSampleRate; }
+ uint32_t format() const { return (uint32_t)mFormat; }
+ size_t size() const { return mSize; }
+ status_t wait();
+
+ sp<IMemoryHeap> getHeap() const { return mHeap; }
+
+ static void notify(void* cookie, int msg, int ext1, int ext2);
+ virtual status_t dump(int fd, const Vector<String16>& args) const;
+
+ private:
+ AudioCache();
+
+ Mutex mLock;
+ Condition mSignal;
+ sp<MemoryHeapBase> mHeap;
+ float mMsecsPerFrame;
+ uint16_t mChannelCount;
+ uint16_t mFormat;
+ ssize_t mFrameCount;
+ uint32_t mSampleRate;
+ uint32_t mSize;
+ int mError;
+ bool mCommandComplete;
+ };
+
+public:
+ static void instantiate();
+
+ // IMediaPlayerService interface
+ virtual sp<IMediaRecorder> createMediaRecorder(pid_t pid);
+ virtual sp<IMediaMetadataRetriever> createMetadataRetriever(pid_t pid);
+
+ // House keeping for media player clients
+ virtual sp<IMediaPlayer> create(pid_t pid, const sp<IMediaPlayerClient>& client, const char* url);
+ virtual sp<IMediaPlayer> create(pid_t pid, const sp<IMediaPlayerClient>& client, int fd, int64_t offset, int64_t length);
+ virtual sp<IMemory> decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat);
+ virtual sp<IMemory> decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat);
+
+ virtual status_t dump(int fd, const Vector<String16>& args);
+
+ void removeClient(wp<Client> client);
+
+private:
+
+ class Client : public BnMediaPlayer {
+
+ // IMediaPlayer interface
+ virtual void disconnect();
+ virtual status_t setVideoSurface(const sp<ISurface>& surface);
+ virtual status_t prepareAsync();
+ virtual status_t start();
+ virtual status_t stop();
+ virtual status_t pause();
+ virtual status_t isPlaying(bool* state);
+ virtual status_t seekTo(int msec);
+ virtual status_t getCurrentPosition(int* msec);
+ virtual status_t getDuration(int* msec);
+ virtual status_t reset();
+ virtual status_t setAudioStreamType(int type);
+ virtual status_t setLooping(int loop);
+ virtual status_t setVolume(float leftVolume, float rightVolume);
+
+ sp<MediaPlayerBase> createPlayer(player_type playerType);
+ status_t setDataSource(const char *url);
+ status_t setDataSource(int fd, int64_t offset, int64_t length);
+ static void notify(void* cookie, int msg, int ext1, int ext2);
+
+ pid_t pid() const { return mPid; }
+ virtual status_t dump(int fd, const Vector<String16>& args) const;
+
+ private:
+ friend class MediaPlayerService;
+ Client( const sp<MediaPlayerService>& service,
+ pid_t pid,
+ int32_t connId,
+ const sp<IMediaPlayerClient>& client);
+ Client();
+ virtual ~Client();
+
+ void deletePlayer();
+
+ sp<MediaPlayerBase> getPlayer() const { Mutex::Autolock lock(mLock); return mPlayer; }
+
+ mutable Mutex mLock;
+ sp<MediaPlayerBase> mPlayer;
+ sp<MediaPlayerService> mService;
+ sp<IMediaPlayerClient> mClient;
+ sp<AudioOutput> mAudioOutput;
+ pid_t mPid;
+ status_t mStatus;
+ bool mLoop;
+ int32_t mConnId;
+#if CALLBACK_ANTAGONIZER
+ Antagonizer* mAntagonizer;
+#endif
+ };
+
+// ----------------------------------------------------------------------------
+
+ MediaPlayerService();
+ virtual ~MediaPlayerService();
+
+ mutable Mutex mLock;
+ SortedVector< wp<Client> > mClients;
+ int32_t mNextConnId;
+};
+
+// ----------------------------------------------------------------------------
+
+}; // namespace android
+
+#endif // ANDROID_MEDIAPLAYERSERVICE_H
+
diff --git a/media/libmediaplayerservice/MediaRecorderClient.cpp b/media/libmediaplayerservice/MediaRecorderClient.cpp
new file mode 100644
index 0000000..4b45acb
--- /dev/null
+++ b/media/libmediaplayerservice/MediaRecorderClient.cpp
@@ -0,0 +1,273 @@
+/*
+ ** Copyright 2008, HTC Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ ** http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "MediaRecorderService"
+#include <utils/Log.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <dirent.h>
+#include <unistd.h>
+#include <string.h>
+#include <cutils/atomic.h>
+#include <android_runtime/ActivityManager.h>
+#include <utils/IPCThreadState.h>
+#include <utils/IServiceManager.h>
+#include <utils/MemoryHeapBase.h>
+#include <utils/MemoryBase.h>
+#include <media/PVMediaRecorder.h>
+
+#include "MediaRecorderClient.h"
+
+namespace android {
+
+status_t MediaRecorderClient::setCamera(const sp<ICamera>& camera)
+{
+ LOGV("setCamera");
+ Mutex::Autolock lock(mLock);
+ if (mRecorder == NULL) {
+ LOGE("recorder is not initialized");
+ return NO_INIT;
+ }
+ return mRecorder->setCamera(camera);
+}
+
+status_t MediaRecorderClient::setPreviewSurface(const sp<ISurface>& surface)
+{
+ LOGV("setPreviewSurface");
+ Mutex::Autolock lock(mLock);
+ if (mRecorder == NULL) {
+ LOGE("recorder is not initialized");
+ return NO_INIT;
+ }
+ return mRecorder->setPreviewSurface(surface);
+}
+
+status_t MediaRecorderClient::setVideoSource(int vs)
+{
+ LOGV("setVideoSource(%d)", vs);
+ Mutex::Autolock lock(mLock);
+ if (mRecorder == NULL) {
+ LOGE("recorder is not initialized");
+ }
+ return mRecorder->setVideoSource((video_source)vs);
+}
+
+status_t MediaRecorderClient::setAudioSource(int as)
+{
+ LOGV("setAudioSource(%d)", as);
+ Mutex::Autolock lock(mLock);
+ if (mRecorder == NULL) {
+ LOGE("recorder is not initialized");
+ }
+ return mRecorder->setAudioSource((audio_source)as);
+}
+
+status_t MediaRecorderClient::setOutputFormat(int of)
+{
+ LOGV("setOutputFormat(%d)", of);
+ Mutex::Autolock lock(mLock);
+ if (mRecorder == NULL) {
+ LOGE("recorder is not initialized");
+ return NO_INIT;
+ }
+ return mRecorder->setOutputFormat((output_format)of);
+}
+
+status_t MediaRecorderClient::setVideoEncoder(int ve)
+{
+ LOGV("setVideoEncoder(%d)", ve);
+ Mutex::Autolock lock(mLock);
+ if (mRecorder == NULL) {
+ LOGE("recorder is not initialized");
+ return NO_INIT;
+ }
+ return mRecorder->setVideoEncoder((video_encoder)ve);
+}
+
+status_t MediaRecorderClient::setAudioEncoder(int ae)
+{
+ LOGV("setAudioEncoder(%d)", ae);
+ Mutex::Autolock lock(mLock);
+ if (mRecorder == NULL) {
+ LOGE("recorder is not initialized");
+ return NO_INIT;
+ }
+ return mRecorder->setAudioEncoder((audio_encoder)ae);
+}
+
+status_t MediaRecorderClient::setOutputFile(const char* path)
+{
+ LOGV("setOutputFile(%s)", path);
+ Mutex::Autolock lock(mLock);
+ if (mRecorder == NULL) {
+ LOGE("recorder is not initialized");
+ return NO_INIT;
+ }
+ return mRecorder->setOutputFile(path);
+}
+
+status_t MediaRecorderClient::setOutputFile(int fd, int64_t offset, int64_t length)
+{
+ LOGV("setOutputFile(%d, %lld, %lld)", fd, offset, length);
+ Mutex::Autolock lock(mLock);
+ if (mRecorder == NULL) {
+ LOGE("recorder is not initialized");
+ return NO_INIT;
+ }
+ return mRecorder->setOutputFile(fd, offset, length);
+}
+
+status_t MediaRecorderClient::setVideoSize(int width, int height)
+{
+ LOGV("setVideoSize(%dx%d)", width, height);
+ Mutex::Autolock lock(mLock);
+ if (mRecorder == NULL) {
+ LOGE("recorder is not initialized");
+ return NO_INIT;
+ }
+ return mRecorder->setVideoSize(width, height);
+}
+
+status_t MediaRecorderClient::setVideoFrameRate(int frames_per_second)
+{
+ LOGV("setVideoFrameRate(%d)", frames_per_second);
+ Mutex::Autolock lock(mLock);
+ if (mRecorder == NULL) {
+ LOGE("recorder is not initialized");
+ return NO_INIT;
+ }
+ return mRecorder->setVideoFrameRate(frames_per_second);
+}
+
+status_t MediaRecorderClient::prepare()
+{
+ LOGV("prepare");
+ Mutex::Autolock lock(mLock);
+ if (mRecorder == NULL) {
+ LOGE("recorder is not initialized");
+ return NO_INIT;
+ }
+ return mRecorder->prepare();
+}
+
+
+status_t MediaRecorderClient::getMaxAmplitude(int* max)
+{
+ LOGV("getMaxAmplitude");
+ Mutex::Autolock lock(mLock);
+ if (mRecorder == NULL) {
+ LOGE("recorder is not initialized");
+ return NO_INIT;
+ }
+ return mRecorder->getMaxAmplitude(max);
+}
+
+status_t MediaRecorderClient::start()
+{
+ LOGV("start");
+ Mutex::Autolock lock(mLock);
+ if (mRecorder == NULL) {
+ LOGE("recorder is not initialized");
+ return NO_INIT;
+ }
+ return mRecorder->start();
+
+}
+
+status_t MediaRecorderClient::stop()
+{
+ LOGV("stop");
+ Mutex::Autolock lock(mLock);
+ if (mRecorder == NULL) {
+ LOGE("recorder is not initialized");
+ return NO_INIT;
+ }
+ return mRecorder->stop();
+}
+
+status_t MediaRecorderClient::init()
+{
+ LOGV("init");
+ Mutex::Autolock lock(mLock);
+ if (mRecorder == NULL) {
+ LOGE("recorder is not initialized");
+ return NO_INIT;
+ }
+ return mRecorder->init();
+}
+
+status_t MediaRecorderClient::close()
+{
+ LOGV("close");
+ Mutex::Autolock lock(mLock);
+ if (mRecorder == NULL) {
+ LOGE("recorder is not initialized");
+ return NO_INIT;
+ }
+ return mRecorder->close();
+}
+
+
+status_t MediaRecorderClient::reset()
+{
+ LOGV("reset");
+ Mutex::Autolock lock(mLock);
+ if (mRecorder == NULL) {
+ LOGE("recorder is not initialized");
+ return NO_INIT;
+ }
+ return mRecorder->reset();
+}
+
+status_t MediaRecorderClient::release()
+{
+ LOGV("release");
+ Mutex::Autolock lock(mLock);
+ if (mRecorder != NULL) {
+ delete mRecorder;
+ mRecorder = NULL;
+ }
+ return NO_ERROR;
+}
+
+MediaRecorderClient::MediaRecorderClient(pid_t pid)
+{
+ LOGV("Client constructor");
+ mPid = pid;
+ mRecorder = new PVMediaRecorder();
+}
+
+MediaRecorderClient::~MediaRecorderClient()
+{
+ LOGV("Client destructor");
+ release();
+}
+
+status_t MediaRecorderClient::setListener(const sp<IMediaPlayerClient>& listener)
+{
+ LOGV("setListener");
+ Mutex::Autolock lock(mLock);
+ if (mRecorder == NULL) {
+ LOGE("recorder is not initialized");
+ return NO_INIT;
+ }
+ return mRecorder->setListener(listener);
+}
+
+}; // namespace android
+
diff --git a/media/libmediaplayerservice/MediaRecorderClient.h b/media/libmediaplayerservice/MediaRecorderClient.h
new file mode 100644
index 0000000..93fd802
--- /dev/null
+++ b/media/libmediaplayerservice/MediaRecorderClient.h
@@ -0,0 +1,66 @@
+/*
+ **
+ ** Copyright 2008, HTC Inc.
+ **
+ ** Licensed under the Apache License, Version 2.0 (the "License");
+ ** you may not use this file except in compliance with the License.
+ ** You may obtain a copy of the License at
+ **
+ ** http://www.apache.org/licenses/LICENSE-2.0
+ **
+ ** Unless required by applicable law or agreed to in writing, software
+ ** distributed under the License is distributed on an "AS IS" BASIS,
+ ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ** See the License for the specific language governing permissions and
+ ** limitations under the License.
+ */
+
+#ifndef ANDROID_MEDIARECORDERCLIENT_H
+#define ANDROID_MEDIARECORDERCLIENT_H
+
+#include <media/IMediaRecorder.h>
+
+namespace android {
+
+class PVMediaRecorder;
+class ISurface;
+
+class MediaRecorderClient : public BnMediaRecorder
+{
+public:
+ virtual status_t setCamera(const sp<ICamera>& camera);
+ virtual status_t setPreviewSurface(const sp<ISurface>& surface);
+ virtual status_t setVideoSource(int vs);
+ virtual status_t setAudioSource(int as);
+ virtual status_t setOutputFormat(int of);
+ virtual status_t setVideoEncoder(int ve);
+ virtual status_t setAudioEncoder(int ae);
+ virtual status_t setOutputFile(const char* path);
+ virtual status_t setOutputFile(int fd, int64_t offset, int64_t length);
+ virtual status_t setVideoSize(int width, int height);
+ virtual status_t setVideoFrameRate(int frames_per_second);
+ virtual status_t setListener(const sp<IMediaPlayerClient>& listener);
+ virtual status_t prepare();
+ virtual status_t getMaxAmplitude(int* max);
+ virtual status_t start();
+ virtual status_t stop();
+ virtual status_t reset();
+ virtual status_t init();
+ virtual status_t close();
+ virtual status_t release();
+
+private:
+ friend class MediaPlayerService; // for accessing private constructor
+
+ MediaRecorderClient(pid_t pid);
+ virtual ~MediaRecorderClient();
+
+ pid_t mPid;
+ Mutex mLock;
+ PVMediaRecorder *mRecorder;
+};
+
+}; // namespace android
+
+#endif // ANDROID_MEDIARECORDERCLIENT_H
+
diff --git a/media/libmediaplayerservice/MetadataRetrieverClient.cpp b/media/libmediaplayerservice/MetadataRetrieverClient.cpp
new file mode 100644
index 0000000..a320bd5
--- /dev/null
+++ b/media/libmediaplayerservice/MetadataRetrieverClient.cpp
@@ -0,0 +1,250 @@
+/*
+**
+** Copyright (C) 2008 The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+** http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "MetadataRetrieverClient"
+#include <utils/Log.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <dirent.h>
+#include <unistd.h>
+
+#include <string.h>
+#include <cutils/atomic.h>
+#include <utils/MemoryDealer.h>
+#include <android_runtime/ActivityManager.h>
+#include <utils/IPCThreadState.h>
+#include <utils/IServiceManager.h>
+#include <media/MediaMetadataRetrieverInterface.h>
+#include <media/MediaPlayerInterface.h>
+#include <media/PVMetadataRetriever.h>
+#include <private/media/VideoFrame.h>
+
+#include "MetadataRetrieverClient.h"
+
+
+namespace android {
+
+MetadataRetrieverClient::MetadataRetrieverClient(pid_t pid)
+{
+ LOGV("MetadataRetrieverClient constructor pid(%d)", pid);
+ mPid = pid;
+ mThumbnailDealer = NULL;
+ mAlbumArtDealer = NULL;
+ mThumbnail = NULL;
+ mAlbumArt = NULL;
+
+ mRetriever = new PVMetadataRetriever();
+ if (mRetriever == NULL) {
+ LOGE("failed to initialize the retriever");
+ }
+}
+
+MetadataRetrieverClient::~MetadataRetrieverClient()
+{
+ LOGV("MetadataRetrieverClient destructor");
+ disconnect();
+}
+
+status_t MetadataRetrieverClient::dump(int fd, const Vector<String16>& args) const
+{
+ const size_t SIZE = 256;
+ char buffer[SIZE];
+ String8 result;
+ result.append(" MetadataRetrieverClient\n");
+ snprintf(buffer, 255, " pid(%d)\n", mPid);
+ result.append(buffer);
+ write(fd, result.string(), result.size());
+ write(fd, "\n", 1);
+ return NO_ERROR;
+}
+
+void MetadataRetrieverClient::disconnect()
+{
+ LOGV("disconnect from pid %d", mPid);
+ Mutex::Autolock lock(mLock);
+ mRetriever.clear();
+ mThumbnailDealer.clear();
+ mAlbumArtDealer.clear();
+ mThumbnail.clear();
+ mAlbumArt.clear();
+ IPCThreadState::self()->flushCommands();
+}
+
+status_t MetadataRetrieverClient::setDataSource(const char *url)
+{
+ LOGV("setDataSource(%s)", url);
+ Mutex::Autolock lock(mLock);
+ if (url == NULL) {
+ return UNKNOWN_ERROR;
+ }
+ if (mRetriever == NULL) {
+ LOGE("retriever is not initialized");
+ return NO_INIT;
+ }
+ return mRetriever->setDataSource(url);
+}
+
+status_t MetadataRetrieverClient::setDataSource(int fd, int64_t offset, int64_t length)
+{
+ LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
+ Mutex::Autolock lock(mLock);
+ if (mRetriever == NULL) {
+ LOGE("retriever is not initialized");
+ ::close(fd);
+ return NO_INIT;
+ }
+
+ struct stat sb;
+ int ret = fstat(fd, &sb);
+ if (ret != 0) {
+ LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
+ return UNKNOWN_ERROR;
+ }
+ LOGV("st_dev = %llu", sb.st_dev);
+ LOGV("st_mode = %u", sb.st_mode);
+ LOGV("st_uid = %lu", sb.st_uid);
+ LOGV("st_gid = %lu", sb.st_gid);
+ LOGV("st_size = %llu", sb.st_size);
+
+ if (offset >= sb.st_size) {
+ LOGE("offset (%lld) bigger than file size (%llu)", offset, sb.st_size);
+ ::close(fd);
+ return UNKNOWN_ERROR;
+ }
+ if (offset + length > sb.st_size) {
+ length = sb.st_size - offset;
+ LOGE("calculated length = %lld", length);
+ }
+ status_t status = mRetriever->setDataSource(fd, offset, length);
+ ::close(fd);
+ return status;
+}
+
+status_t MetadataRetrieverClient::setMode(int mode)
+{
+ LOGV("setMode");
+ Mutex::Autolock lock(mLock);
+ if (mRetriever == NULL) {
+ LOGE("retriever is not initialized");
+ return NO_INIT;
+ }
+ return mRetriever->setMode(mode);
+}
+
+status_t MetadataRetrieverClient::getMode(int* mode) const
+{
+ LOGV("getMode");
+ Mutex::Autolock lock(mLock);
+ if (mRetriever == NULL) {
+ LOGE("retriever is not initialized");
+ return NO_INIT;
+ }
+ return mRetriever->getMode(mode);
+}
+
+sp<IMemory> MetadataRetrieverClient::captureFrame()
+{
+ LOGV("captureFrame");
+ Mutex::Autolock lock(mLock);
+ mThumbnail.clear();
+ mThumbnailDealer.clear();
+ if (mRetriever == NULL) {
+ LOGE("retriever is not initialized");
+ return NULL;
+ }
+ VideoFrame *frame = mRetriever->captureFrame();
+ if (frame == NULL) {
+ LOGE("failed to capture a video frame");
+ return NULL;
+ }
+ size_t size = sizeof(VideoFrame) + frame->mSize;
+ mThumbnailDealer = new MemoryDealer(size);
+ if (mThumbnailDealer == NULL) {
+ LOGE("failed to create MemoryDealer");
+ delete frame;
+ return NULL;
+ }
+ mThumbnail = mThumbnailDealer->allocate(size);
+ if (mThumbnail == NULL) {
+ LOGE("not enough memory for VideoFrame size=%u", size);
+ mThumbnailDealer.clear();
+ delete frame;
+ return NULL;
+ }
+ VideoFrame *frameCopy = static_cast<VideoFrame *>(mThumbnail->pointer());
+ frameCopy->mWidth = frame->mWidth;
+ frameCopy->mHeight = frame->mHeight;
+ frameCopy->mDisplayWidth = frame->mDisplayWidth;
+ frameCopy->mDisplayHeight = frame->mDisplayHeight;
+ frameCopy->mSize = frame->mSize;
+ frameCopy->mData = (uint8_t *)frameCopy + sizeof(VideoFrame);
+ memcpy(frameCopy->mData, frame->mData, frame->mSize);
+ delete frame; // Fix memory leakage
+ return mThumbnail;
+}
+
+sp<IMemory> MetadataRetrieverClient::extractAlbumArt()
+{
+ LOGV("extractAlbumArt");
+ Mutex::Autolock lock(mLock);
+ mAlbumArt.clear();
+ mAlbumArtDealer.clear();
+ if (mRetriever == NULL) {
+ LOGE("retriever is not initialized");
+ return NULL;
+ }
+ MediaAlbumArt *albumArt = mRetriever->extractAlbumArt();
+ if (albumArt == NULL) {
+ LOGE("failed to extract an album art");
+ return NULL;
+ }
+ size_t size = sizeof(MediaAlbumArt) + albumArt->mSize;
+ mAlbumArtDealer = new MemoryDealer(size);
+ if (mAlbumArtDealer == NULL) {
+ LOGE("failed to create MemoryDealer object");
+ delete albumArt;
+ return NULL;
+ }
+ mAlbumArt = mAlbumArtDealer->allocate(size);
+ if (mAlbumArt == NULL) {
+ LOGE("not enough memory for MediaAlbumArt size=%u", size);
+ mAlbumArtDealer.clear();
+ delete albumArt;
+ return NULL;
+ }
+ MediaAlbumArt *albumArtCopy = static_cast<MediaAlbumArt *>(mAlbumArt->pointer());
+ albumArtCopy->mSize = albumArt->mSize;
+ albumArtCopy->mData = (uint8_t *)albumArtCopy + sizeof(MediaAlbumArt);
+ memcpy(albumArtCopy->mData, albumArt->mData, albumArt->mSize);
+ delete albumArt; // Fix memory leakage
+ return mAlbumArt;
+}
+
+const char* MetadataRetrieverClient::extractMetadata(int keyCode)
+{
+ LOGV("extractMetadata");
+ Mutex::Autolock lock(mLock);
+ if (mRetriever == NULL) {
+ LOGE("retriever is not initialized");
+ return NULL;
+ }
+ return mRetriever->extractMetadata(keyCode);
+}
+
+}; // namespace android
diff --git a/media/libmediaplayerservice/MetadataRetrieverClient.h b/media/libmediaplayerservice/MetadataRetrieverClient.h
new file mode 100644
index 0000000..ce29c98
--- /dev/null
+++ b/media/libmediaplayerservice/MetadataRetrieverClient.h
@@ -0,0 +1,71 @@
+/*
+**
+** Copyright (C) 2008 The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+** http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+
+#ifndef ANDROID_MEDIAMETADATARETRIEVERSERVICE_H
+#define ANDROID_MEDIAMETADATARETRIEVERSERVICE_H
+
+#include <utils.h>
+#include <utils/KeyedVector.h>
+#include <utils/IMemory.h>
+
+#include <media/MediaMetadataRetrieverInterface.h>
+
+
+namespace android {
+
+class IMediaPlayerService;
+class MemoryDealer;
+
+class MetadataRetrieverClient : public BnMediaMetadataRetriever
+{
+public:
+ MetadataRetrieverClient(const sp<IMediaPlayerService>& service, pid_t pid, int32_t connId);
+
+ // Implements IMediaMetadataRetriever interface
+ // These methods are called in IMediaMetadataRetriever.cpp?
+ virtual void disconnect();
+ virtual status_t setDataSource(const char *url);
+ virtual status_t setDataSource(int fd, int64_t offset, int64_t length);
+ virtual status_t setMode(int mode);
+ virtual status_t getMode(int* mode) const;
+ virtual sp<IMemory> captureFrame();
+ virtual sp<IMemory> extractAlbumArt();
+ virtual const char* extractMetadata(int keyCode);
+
+ virtual status_t dump(int fd, const Vector<String16>& args) const;
+
+private:
+ friend class MediaPlayerService;
+
+ explicit MetadataRetrieverClient(pid_t pid);
+ virtual ~MetadataRetrieverClient();
+
+ mutable Mutex mLock;
+ sp<MediaMetadataRetrieverBase> mRetriever;
+ pid_t mPid;
+
+ // Keep the shared memory copy of album art and capture frame (for thumbnail)
+ sp<MemoryDealer> mAlbumArtDealer;
+ sp<MemoryDealer> mThumbnailDealer;
+ sp<IMemory> mAlbumArt;
+ sp<IMemory> mThumbnail;
+};
+
+}; // namespace android
+
+#endif // ANDROID_MEDIAMETADATARETRIEVERSERVICE_H
+
diff --git a/media/libmediaplayerservice/MidiFile.cpp b/media/libmediaplayerservice/MidiFile.cpp
new file mode 100644
index 0000000..d03caa5
--- /dev/null
+++ b/media/libmediaplayerservice/MidiFile.cpp
@@ -0,0 +1,558 @@
+/* MidiFile.cpp
+**
+** Copyright 2007, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+** http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "MidiFile"
+#include "utils/Log.h"
+
+#include <stdio.h>
+#include <assert.h>
+#include <limits.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sched.h>
+#include <utils/threads.h>
+#include <libsonivox/eas_reverb.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include "MidiFile.h"
+
+#ifdef HAVE_GETTID
+static pid_t myTid() { return gettid(); }
+#else
+static pid_t myTid() { return getpid(); }
+#endif
+
+// ----------------------------------------------------------------------------
+
+namespace android {
+
+// ----------------------------------------------------------------------------
+
+// The midi engine buffers are a bit small (128 frames), so we batch them up
+static const int NUM_BUFFERS = 4;
+
+// TODO: Determine appropriate return codes
+static status_t ERROR_NOT_OPEN = -1;
+static status_t ERROR_OPEN_FAILED = -2;
+static status_t ERROR_EAS_FAILURE = -3;
+static status_t ERROR_ALLOCATE_FAILED = -4;
+
+static const S_EAS_LIB_CONFIG* pLibConfig = NULL;
+
+MidiFile::MidiFile() :
+ mEasData(NULL), mEasHandle(NULL), mAudioBuffer(NULL),
+ mPlayTime(-1), mDuration(-1), mState(EAS_STATE_ERROR),
+ mStreamType(AudioSystem::MUSIC), mLoop(false), mExit(false),
+ mPaused(false), mRender(false), mTid(-1)
+{
+ LOGV("constructor");
+
+ mFileLocator.path = NULL;
+ mFileLocator.fd = -1;
+ mFileLocator.offset = 0;
+ mFileLocator.length = 0;
+
+ // get the library configuration and do sanity check
+ if (pLibConfig == NULL)
+ pLibConfig = EAS_Config();
+ if ((pLibConfig == NULL) || (LIB_VERSION != pLibConfig->libVersion)) {
+ LOGE("EAS library/header mismatch");
+ goto Failed;
+ }
+
+ // initialize EAS library
+ if (EAS_Init(&mEasData) != EAS_SUCCESS) {
+ LOGE("EAS_Init failed");
+ goto Failed;
+ }
+
+ // select reverb preset and enable
+ EAS_SetParameter(mEasData, EAS_MODULE_REVERB, EAS_PARAM_REVERB_PRESET, EAS_PARAM_REVERB_CHAMBER);
+ EAS_SetParameter(mEasData, EAS_MODULE_REVERB, EAS_PARAM_REVERB_BYPASS, EAS_FALSE);
+
+ // create playback thread
+ {
+ Mutex::Autolock l(mMutex);
+ createThreadEtc(renderThread, this, "midithread");
+ mCondition.wait(mMutex);
+ LOGV("thread started");
+ }
+
+ // indicate success
+ if (mTid > 0) {
+ LOGV(" render thread(%d) started", mTid);
+ mState = EAS_STATE_READY;
+ }
+
+Failed:
+ return;
+}
+
+status_t MidiFile::initCheck()
+{
+ if (mState == EAS_STATE_ERROR) return ERROR_EAS_FAILURE;
+ return NO_ERROR;
+}
+
+MidiFile::~MidiFile() {
+ LOGV("MidiFile destructor");
+ release();
+}
+
+status_t MidiFile::setDataSource(const char* path)
+{
+ LOGV("MidiFile::setDataSource url=%s", path);
+ Mutex::Autolock lock(mMutex);
+
+ // file still open?
+ if (mEasHandle) {
+ reset_nosync();
+ }
+
+ // open file and set paused state
+ mFileLocator.path = strdup(path);
+ mFileLocator.fd = -1;
+ mFileLocator.offset = 0;
+ mFileLocator.length = 0;
+ EAS_RESULT result = EAS_OpenFile(mEasData, &mFileLocator, &mEasHandle);
+ if (result == EAS_SUCCESS) {
+ updateState();
+ }
+
+ if (result != EAS_SUCCESS) {
+ LOGE("EAS_OpenFile failed: [%d]", (int)result);
+ mState = EAS_STATE_ERROR;
+ return ERROR_OPEN_FAILED;
+ }
+
+ mState = EAS_STATE_OPEN;
+ mPlayTime = 0;
+ return NO_ERROR;
+}
+
+status_t MidiFile::setDataSource(int fd, int64_t offset, int64_t length)
+{
+ LOGV("MidiFile::setDataSource fd=%d", fd);
+ Mutex::Autolock lock(mMutex);
+
+ // file still open?
+ if (mEasHandle) {
+ reset_nosync();
+ }
+
+ // open file and set paused state
+ mFileLocator.fd = dup(fd);
+ mFileLocator.offset = offset;
+ mFileLocator.length = length;
+ EAS_RESULT result = EAS_OpenFile(mEasData, &mFileLocator, &mEasHandle);
+ updateState();
+
+ if (result != EAS_SUCCESS) {
+ LOGE("EAS_OpenFile failed: [%d]", (int)result);
+ mState = EAS_STATE_ERROR;
+ return ERROR_OPEN_FAILED;
+ }
+
+ mState = EAS_STATE_OPEN;
+ mPlayTime = 0;
+ return NO_ERROR;
+}
+
+status_t MidiFile::prepare()
+{
+ LOGV("MidiFile::prepare");
+ Mutex::Autolock lock(mMutex);
+ if (!mEasHandle) {
+ return ERROR_NOT_OPEN;
+ }
+ EAS_RESULT result;
+ if ((result = EAS_Prepare(mEasData, mEasHandle)) != EAS_SUCCESS) {
+ LOGE("EAS_Prepare failed: [%ld]", result);
+ return ERROR_EAS_FAILURE;
+ }
+ updateState();
+ return NO_ERROR;
+}
+
+status_t MidiFile::prepareAsync()
+{
+ LOGV("MidiFile::prepareAsync");
+ status_t ret = prepare();
+
+ // don't hold lock during callback
+ if (ret == NO_ERROR) {
+ sendEvent(MEDIA_PREPARED);
+ } else {
+ sendEvent(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, ret);
+ }
+ return ret;
+}
+
+status_t MidiFile::start()
+{
+ LOGV("MidiFile::start");
+ Mutex::Autolock lock(mMutex);
+ if (!mEasHandle) {
+ return ERROR_NOT_OPEN;
+ }
+
+ // resuming after pause?
+ if (mPaused) {
+ if (EAS_Resume(mEasData, mEasHandle) != EAS_SUCCESS) {
+ return ERROR_EAS_FAILURE;
+ }
+ mPaused = false;
+ updateState();
+ }
+
+ mRender = true;
+
+ // wake up render thread
+ LOGV(" wakeup render thread");
+ mCondition.signal();
+ return NO_ERROR;
+}
+
+status_t MidiFile::stop()
+{
+ LOGV("MidiFile::stop");
+ Mutex::Autolock lock(mMutex);
+ if (!mEasHandle) {
+ return ERROR_NOT_OPEN;
+ }
+ if (!mPaused && (mState != EAS_STATE_STOPPED)) {
+ EAS_RESULT result = EAS_Pause(mEasData, mEasHandle);
+ if (result != EAS_SUCCESS) {
+ LOGE("EAS_Pause returned error %ld", result);
+ return ERROR_EAS_FAILURE;
+ }
+ }
+ mPaused = false;
+ return NO_ERROR;
+}
+
+status_t MidiFile::seekTo(int position)
+{
+ LOGV("MidiFile::seekTo %d", position);
+ // hold lock during EAS calls
+ {
+ Mutex::Autolock lock(mMutex);
+ if (!mEasHandle) {
+ return ERROR_NOT_OPEN;
+ }
+ EAS_RESULT result;
+ if ((result = EAS_Locate(mEasData, mEasHandle, position, false))
+ != EAS_SUCCESS)
+ {
+ LOGE("EAS_Locate returned %ld", result);
+ return ERROR_EAS_FAILURE;
+ }
+ EAS_GetLocation(mEasData, mEasHandle, &mPlayTime);
+ }
+ sendEvent(MEDIA_SEEK_COMPLETE);
+ return NO_ERROR;
+}
+
+status_t MidiFile::pause()
+{
+ LOGV("MidiFile::pause");
+ Mutex::Autolock lock(mMutex);
+ if (!mEasHandle) {
+ return ERROR_NOT_OPEN;
+ }
+ if ((mState == EAS_STATE_PAUSING) || (mState == EAS_STATE_PAUSED)) return NO_ERROR;
+ if (EAS_Pause(mEasData, mEasHandle) != EAS_SUCCESS) {
+ return ERROR_EAS_FAILURE;
+ }
+ mPaused = true;
+ return NO_ERROR;
+}
+
+bool MidiFile::isPlaying()
+{
+ LOGV("MidiFile::isPlaying, mState=%d", int(mState));
+ if (!mEasHandle || mPaused) return false;
+ return (mState == EAS_STATE_PLAY);
+}
+
+status_t MidiFile::getCurrentPosition(int* position)
+{
+ LOGV("MidiFile::getCurrentPosition");
+ if (!mEasHandle) {
+ LOGE("getCurrentPosition(): file not open");
+ return ERROR_NOT_OPEN;
+ }
+ if (mPlayTime < 0) {
+ LOGE("getCurrentPosition(): mPlayTime = %ld", mPlayTime);
+ return ERROR_EAS_FAILURE;
+ }
+ *position = mPlayTime;
+ return NO_ERROR;
+}
+
+status_t MidiFile::getDuration(int* duration)
+{
+
+ LOGV("MidiFile::getDuration");
+ {
+ Mutex::Autolock lock(mMutex);
+ if (!mEasHandle) return ERROR_NOT_OPEN;
+ *duration = mDuration;
+ }
+
+ // if no duration cached, get the duration
+ // don't need a lock here because we spin up a new engine
+ if (*duration < 0) {
+ EAS_I32 temp;
+ EAS_DATA_HANDLE easData = NULL;
+ EAS_HANDLE easHandle = NULL;
+ EAS_RESULT result = EAS_Init(&easData);
+ if (result == EAS_SUCCESS) {
+ result = EAS_OpenFile(easData, &mFileLocator, &easHandle);
+ }
+ if (result == EAS_SUCCESS) {
+ result = EAS_Prepare(easData, easHandle);
+ }
+ if (result == EAS_SUCCESS) {
+ result = EAS_ParseMetaData(easData, easHandle, &temp);
+ }
+ if (easHandle) {
+ EAS_CloseFile(easData, easHandle);
+ }
+ if (easData) {
+ EAS_Shutdown(easData);
+ }
+
+ if (result != EAS_SUCCESS) {
+ return ERROR_EAS_FAILURE;
+ }
+
+ // cache successful result
+ mDuration = *duration = int(temp);
+ }
+
+ return NO_ERROR;
+}
+
+status_t MidiFile::release()
+{
+ LOGV("MidiFile::release");
+ Mutex::Autolock l(mMutex);
+ reset_nosync();
+
+ // wait for render thread to exit
+ mExit = true;
+ mCondition.signal();
+
+ // wait for thread to exit
+ if (mAudioBuffer) {
+ mCondition.wait(mMutex);
+ }
+
+ // release resources
+ if (mEasData) {
+ EAS_Shutdown(mEasData);
+ mEasData = NULL;
+ }
+ return NO_ERROR;
+}
+
+status_t MidiFile::reset()
+{
+ LOGV("MidiFile::reset");
+ Mutex::Autolock lock(mMutex);
+ return reset_nosync();
+}
+
+// call only with mutex held
+status_t MidiFile::reset_nosync()
+{
+ LOGV("MidiFile::reset_nosync");
+ // close file
+ if (mEasHandle) {
+ EAS_CloseFile(mEasData, mEasHandle);
+ mEasHandle = NULL;
+ }
+ if (mFileLocator.path) {
+ free((void*)mFileLocator.path);
+ mFileLocator.path = NULL;
+ }
+ if (mFileLocator.fd >= 0) {
+ close(mFileLocator.fd);
+ }
+ mFileLocator.fd = -1;
+ mFileLocator.offset = 0;
+ mFileLocator.length = 0;
+
+ mPlayTime = -1;
+ mDuration = -1;
+ mLoop = false;
+ mPaused = false;
+ mRender = false;
+ return NO_ERROR;
+}
+
+status_t MidiFile::setLooping(int loop)
+{
+ LOGV("MidiFile::setLooping");
+ Mutex::Autolock lock(mMutex);
+ if (!mEasHandle) {
+ return ERROR_NOT_OPEN;
+ }
+ loop = loop ? -1 : 0;
+ if (EAS_SetRepeat(mEasData, mEasHandle, loop) != EAS_SUCCESS) {
+ return ERROR_EAS_FAILURE;
+ }
+ return NO_ERROR;
+}
+
+status_t MidiFile::createOutputTrack() {
+ if (mAudioSink->open(pLibConfig->sampleRate, pLibConfig->numChannels, AudioSystem::PCM_16_BIT, 2) != NO_ERROR) {
+ LOGE("mAudioSink open failed");
+ return ERROR_OPEN_FAILED;
+ }
+ return NO_ERROR;
+}
+
+int MidiFile::renderThread(void* p) {
+
+ return ((MidiFile*)p)->render();
+}
+
+int MidiFile::render() {
+ EAS_RESULT result = EAS_FAILURE;
+ EAS_I32 count;
+ int temp;
+ bool audioStarted = false;
+
+ LOGV("MidiFile::render");
+
+ // allocate render buffer
+ mAudioBuffer = new EAS_PCM[pLibConfig->mixBufferSize * pLibConfig->numChannels * NUM_BUFFERS];
+ if (!mAudioBuffer) {
+ LOGE("mAudioBuffer allocate failed");
+ goto threadExit;
+ }
+
+ // signal main thread that we started
+ {
+ Mutex::Autolock l(mMutex);
+ mTid = myTid();
+ LOGV("render thread(%d) signal", mTid);
+ mCondition.signal();
+ }
+
+ while (1) {
+ mMutex.lock();
+
+ // nothing to render, wait for client thread to wake us up
+ while (!mRender && !mExit)
+ {
+ LOGV("MidiFile::render - signal wait");
+ mCondition.wait(mMutex);
+ LOGV("MidiFile::render - signal rx'd");
+ }
+ if (mExit) {
+ mMutex.unlock();
+ break;
+ }
+
+ // render midi data into the input buffer
+ //LOGV("MidiFile::render - rendering audio");
+ int num_output = 0;
+ EAS_PCM* p = mAudioBuffer;
+ for (int i = 0; i < NUM_BUFFERS; i++) {
+ result = EAS_Render(mEasData, p, pLibConfig->mixBufferSize, &count);
+ if (result != EAS_SUCCESS) {
+ LOGE("EAS_Render returned %ld", result);
+ }
+ p += count * pLibConfig->numChannels;
+ num_output += count * pLibConfig->numChannels * sizeof(EAS_PCM);
+ }
+
+ // update playback state and position
+ // LOGV("MidiFile::render - updating state");
+ EAS_GetLocation(mEasData, mEasHandle, &mPlayTime);
+ EAS_State(mEasData, mEasHandle, &mState);
+ mMutex.unlock();
+
+ // create audio output track if necessary
+ if (!mAudioSink->ready()) {
+ LOGV("MidiFile::render - create output track");
+ if (createOutputTrack() != NO_ERROR)
+ goto threadExit;
+ }
+
+ // Write data to the audio hardware
+ // LOGV("MidiFile::render - writing to audio output");
+ if ((temp = mAudioSink->write(mAudioBuffer, num_output)) < 0) {
+ LOGE("Error in writing:%d",temp);
+ return temp;
+ }
+
+ // start audio output if necessary
+ if (!audioStarted) {
+ //LOGV("MidiFile::render - starting audio");
+ mAudioSink->start();
+ audioStarted = true;
+ }
+
+ // still playing?
+ if ((mState == EAS_STATE_STOPPED) || (mState == EAS_STATE_ERROR) ||
+ (mState == EAS_STATE_PAUSED))
+ {
+ switch(mState) {
+ case EAS_STATE_STOPPED:
+ {
+ LOGV("MidiFile::render - stopped");
+ sendEvent(MEDIA_PLAYBACK_COMPLETE);
+ break;
+ }
+ case EAS_STATE_ERROR:
+ {
+ LOGE("MidiFile::render - error");
+ sendEvent(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN);
+ break;
+ }
+ case EAS_STATE_PAUSED:
+ LOGV("MidiFile::render - paused");
+ break;
+ default:
+ break;
+ }
+ mAudioSink->stop();
+ audioStarted = false;
+ mRender = false;
+ }
+ }
+
+threadExit:
+ mAudioSink.clear();
+ if (mAudioBuffer) {
+ delete [] mAudioBuffer;
+ mAudioBuffer = NULL;
+ }
+ mMutex.lock();
+ mTid = -1;
+ mCondition.signal();
+ mMutex.unlock();
+ return result;
+}
+
+} // end namespace android
diff --git a/media/libmediaplayerservice/MidiFile.h b/media/libmediaplayerservice/MidiFile.h
new file mode 100644
index 0000000..302f1cf
--- /dev/null
+++ b/media/libmediaplayerservice/MidiFile.h
@@ -0,0 +1,77 @@
+/*
+**
+** Copyright 2008, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+** http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+
+#ifndef ANDROID_MIDIFILE_H
+#define ANDROID_MIDIFILE_H
+
+#include <media/MediaPlayerInterface.h>
+#include <media/AudioTrack.h>
+#include <libsonivox/eas.h>
+
+namespace android {
+
+class MidiFile : public MediaPlayerInterface {
+public:
+ MidiFile();
+ ~MidiFile();
+
+ virtual status_t initCheck();
+ virtual status_t setDataSource(const char* path);
+ virtual status_t setDataSource(int fd, int64_t offset, int64_t length);
+ virtual status_t setVideoSurface(const sp<ISurface>& surface) { return UNKNOWN_ERROR; }
+ virtual status_t prepare();
+ virtual status_t prepareAsync();
+ virtual status_t start();
+ virtual status_t stop();
+ virtual status_t seekTo(int msec);
+ virtual status_t pause();
+ virtual bool isPlaying();
+ virtual status_t getCurrentPosition(int* msec);
+ virtual status_t getDuration(int* msec);
+ virtual status_t release();
+ virtual status_t reset();
+ virtual status_t setLooping(int loop);
+ virtual player_type playerType() { return SONIVOX_PLAYER; }
+
+private:
+ status_t createOutputTrack();
+ status_t reset_nosync();
+ static int renderThread(void*);
+ int render();
+ void updateState(){ EAS_State(mEasData, mEasHandle, &mState); }
+
+ Mutex mMutex;
+ Condition mCondition;
+ EAS_DATA_HANDLE mEasData;
+ EAS_HANDLE mEasHandle;
+ EAS_PCM* mAudioBuffer;
+ EAS_I32 mPlayTime;
+ EAS_I32 mDuration;
+ EAS_STATE mState;
+ EAS_FILE mFileLocator;
+ int mStreamType;
+ bool mLoop;
+ volatile bool mExit;
+ bool mPaused;
+ volatile bool mRender;
+ pid_t mTid;
+};
+
+}; // namespace android
+
+#endif // ANDROID_MIDIFILE_H
+
diff --git a/media/libmediaplayerservice/VorbisPlayer.cpp b/media/libmediaplayerservice/VorbisPlayer.cpp
new file mode 100644
index 0000000..0ad335f
--- /dev/null
+++ b/media/libmediaplayerservice/VorbisPlayer.cpp
@@ -0,0 +1,529 @@
+/*
+** Copyright 2007, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+** http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "VorbisPlayer"
+#include "utils/Log.h"
+
+#include <stdio.h>
+#include <assert.h>
+#include <limits.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sched.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+
+
+#include "VorbisPlayer.h"
+
+#ifdef HAVE_GETTID
+static pid_t myTid() { return gettid(); }
+#else
+static pid_t myTid() { return getpid(); }
+#endif
+
+// ----------------------------------------------------------------------------
+
+namespace android {
+
+// ----------------------------------------------------------------------------
+
+// TODO: Determine appropriate return codes
+static status_t ERROR_NOT_OPEN = -1;
+static status_t ERROR_OPEN_FAILED = -2;
+static status_t ERROR_ALLOCATE_FAILED = -4;
+static status_t ERROR_NOT_SUPPORTED = -8;
+static status_t ERROR_NOT_READY = -16;
+static status_t STATE_INIT = 0;
+static status_t STATE_ERROR = 1;
+static status_t STATE_OPEN = 2;
+
+
+VorbisPlayer::VorbisPlayer() :
+ mAudioBuffer(NULL), mPlayTime(-1), mDuration(-1), mState(STATE_ERROR),
+ mStreamType(AudioSystem::MUSIC), mLoop(false), mAndroidLoop(false),
+ mExit(false), mPaused(false), mRender(false), mRenderTid(-1)
+{
+ LOGV("constructor\n");
+ memset(&mVorbisFile, 0, sizeof mVorbisFile);
+}
+
+void VorbisPlayer::onFirstRef()
+{
+ LOGV("onFirstRef");
+ // create playback thread
+ Mutex::Autolock l(mMutex);
+ createThreadEtc(renderThread, this, "vorbis decoder");
+ mCondition.wait(mMutex);
+ if (mRenderTid > 0) {
+ LOGV("render thread(%d) started", mRenderTid);
+ mState = STATE_INIT;
+ }
+}
+
+status_t VorbisPlayer::initCheck()
+{
+ if (mState != STATE_ERROR) return NO_ERROR;
+ return ERROR_NOT_READY;
+}
+
+VorbisPlayer::~VorbisPlayer() {
+ LOGV("VorbisPlayer destructor\n");
+ release();
+}
+
+status_t VorbisPlayer::setDataSource(const char* path)
+{
+ return setdatasource(path, -1, 0, 0x7ffffffffffffffLL); // intentionally less than LONG_MAX
+}
+
+status_t VorbisPlayer::setDataSource(int fd, int64_t offset, int64_t length)
+{
+ return setdatasource(NULL, fd, offset, length);
+}
+
+size_t VorbisPlayer::vp_fread(void *buf, size_t size, size_t nmemb, void *me) {
+ VorbisPlayer *self = (VorbisPlayer*) me;
+
+ long curpos = vp_ftell(me);
+ while (nmemb != 0 && (curpos + size * nmemb) > self->mLength) {
+ nmemb--;
+ }
+ return fread(buf, size, nmemb, self->mFile);
+}
+
+int VorbisPlayer::vp_fseek(void *me, ogg_int64_t off, int whence) {
+ VorbisPlayer *self = (VorbisPlayer*) me;
+ if (whence == SEEK_SET)
+ return fseek(self->mFile, off + self->mOffset, whence);
+ else if (whence == SEEK_CUR)
+ return fseek(self->mFile, off, whence);
+ else if (whence == SEEK_END)
+ return fseek(self->mFile, self->mOffset + self->mLength + off, SEEK_SET);
+ return -1;
+}
+
+int VorbisPlayer::vp_fclose(void *me) {
+ LOGV("vp_fclose");
+ VorbisPlayer *self = (VorbisPlayer*) me;
+ int ret = fclose (self->mFile);
+ self->mFile = NULL;
+ return ret;
+}
+
+long VorbisPlayer::vp_ftell(void *me) {
+ VorbisPlayer *self = (VorbisPlayer*) me;
+ return ftell(self->mFile) - self->mOffset;
+}
+
+status_t VorbisPlayer::setdatasource(const char *path, int fd, int64_t offset, int64_t length)
+{
+ LOGV("setDataSource url=%s, fd=%d\n", path, fd);
+
+ // file still open?
+ Mutex::Autolock l(mMutex);
+ if (mState == STATE_OPEN) {
+ reset_nosync();
+ }
+
+ // open file and set paused state
+ if (path) {
+ mFile = fopen(path, "r");
+ } else {
+ mFile = fdopen(dup(fd), "r");
+ }
+ if (mFile == NULL) {
+ return ERROR_OPEN_FAILED;
+ }
+
+ struct stat sb;
+ int ret;
+ if (path) {
+ ret = stat(path, &sb);
+ } else {
+ ret = fstat(fd, &sb);
+ }
+ if (ret != 0) {
+ mState = STATE_ERROR;
+ fclose(mFile);
+ return ERROR_OPEN_FAILED;
+ }
+ if (sb.st_size > (length + offset)) {
+ mLength = length;
+ } else {
+ mLength = sb.st_size - offset;
+ }
+
+ ov_callbacks callbacks = {
+ (size_t (*)(void *, size_t, size_t, void *)) vp_fread,
+ (int (*)(void *, ogg_int64_t, int)) vp_fseek,
+ (int (*)(void *)) vp_fclose,
+ (long (*)(void *)) vp_ftell
+ };
+
+ mOffset = offset;
+ fseek(mFile, offset, SEEK_SET);
+
+ int result = ov_open_callbacks(this, &mVorbisFile, NULL, 0, callbacks);
+ if (result < 0) {
+ LOGE("ov_open() failed: [%d]\n", (int)result);
+ mState = STATE_ERROR;
+ fclose(mFile);
+ return ERROR_OPEN_FAILED;
+ }
+
+ // look for the android loop tag (for ringtones)
+ char **ptr = ov_comment(&mVorbisFile,-1)->user_comments;
+ while(*ptr) {
+ // does the comment start with ANDROID_LOOP_TAG
+ if(strncmp(*ptr, ANDROID_LOOP_TAG, strlen(ANDROID_LOOP_TAG)) == 0) {
+ // read the value of the tag
+ char *val = *ptr + strlen(ANDROID_LOOP_TAG) + 1;
+ mAndroidLoop = (strncmp(val, "true", 4) == 0);
+ }
+ // we keep parsing even after finding one occurence of ANDROID_LOOP_TAG,
+ // as we could find another one (the tag might have been appended more than once).
+ ++ptr;
+ }
+ LOGV_IF(mAndroidLoop, "looped sound");
+
+ mState = STATE_OPEN;
+ return NO_ERROR;
+}
+
+status_t VorbisPlayer::prepare()
+{
+ LOGV("prepare\n");
+ if (mState != STATE_OPEN ) {
+ return ERROR_NOT_OPEN;
+ }
+ return NO_ERROR;
+}
+
+status_t VorbisPlayer::prepareAsync() {
+ LOGV("prepareAsync\n");
+ // can't hold the lock here because of the callback
+ // it's safe because we don't change state
+ if (mState != STATE_OPEN ) {
+ sendEvent(MEDIA_ERROR);
+ return NO_ERROR;
+ }
+ sendEvent(MEDIA_PREPARED);
+ return NO_ERROR;
+}
+
+status_t VorbisPlayer::start()
+{
+ LOGV("start\n");
+ Mutex::Autolock l(mMutex);
+ if (mState != STATE_OPEN) {
+ return ERROR_NOT_OPEN;
+ }
+
+ mPaused = false;
+ mRender = true;
+
+ // wake up render thread
+ LOGV(" wakeup render thread\n");
+ mCondition.signal();
+ return NO_ERROR;
+}
+
+status_t VorbisPlayer::stop()
+{
+ LOGV("stop\n");
+ Mutex::Autolock l(mMutex);
+ if (mState != STATE_OPEN) {
+ return ERROR_NOT_OPEN;
+ }
+ mPaused = true;
+ mRender = false;
+ return NO_ERROR;
+}
+
+status_t VorbisPlayer::seekTo(int position)
+{
+ LOGV("seekTo %d\n", position);
+ Mutex::Autolock l(mMutex);
+ if (mState != STATE_OPEN) {
+ return ERROR_NOT_OPEN;
+ }
+
+ int result = ov_time_seek(&mVorbisFile, position);
+ if (result != 0) {
+ LOGE("ov_time_seek() returned %d\n", result);
+ return result;
+ }
+ sendEvent(MEDIA_SEEK_COMPLETE);
+ return NO_ERROR;
+}
+
+status_t VorbisPlayer::pause()
+{
+ LOGV("pause\n");
+ Mutex::Autolock l(mMutex);
+ if (mState != STATE_OPEN) {
+ return ERROR_NOT_OPEN;
+ }
+ mPaused = true;
+ return NO_ERROR;
+}
+
+bool VorbisPlayer::isPlaying()
+{
+ LOGV("isPlaying\n");
+ if (mState == STATE_OPEN) {
+ return mRender;
+ }
+ return false;
+}
+
+status_t VorbisPlayer::getCurrentPosition(int* position)
+{
+ LOGV("getCurrentPosition\n");
+ Mutex::Autolock l(mMutex);
+ if (mState != STATE_OPEN) {
+ LOGE("getCurrentPosition(): file not open");
+ return ERROR_NOT_OPEN;
+ }
+ *position = ov_time_tell(&mVorbisFile);
+ if (*position < 0) {
+ LOGE("getCurrentPosition(): ov_time_tell returned %d", *position);
+ return *position;
+ }
+ return NO_ERROR;
+}
+
+status_t VorbisPlayer::getDuration(int* duration)
+{
+ LOGV("getDuration\n");
+ Mutex::Autolock l(mMutex);
+ if (mState != STATE_OPEN) {
+ return ERROR_NOT_OPEN;
+ }
+
+ int ret = ov_time_total(&mVorbisFile, -1);
+ if (ret == OV_EINVAL) {
+ return -1;
+ }
+
+ *duration = ret;
+ return NO_ERROR;
+}
+
+status_t VorbisPlayer::release()
+{
+ LOGV("release\n");
+ Mutex::Autolock l(mMutex);
+ reset_nosync();
+
+ // TODO: timeout when thread won't exit
+ // wait for render thread to exit
+ if (mRenderTid > 0) {
+ mExit = true;
+ mCondition.signal();
+ mCondition.wait(mMutex);
+ }
+ return NO_ERROR;
+}
+
+status_t VorbisPlayer::reset()
+{
+ LOGV("reset\n");
+ Mutex::Autolock l(mMutex);
+ if (mState != STATE_OPEN) {
+ return NO_ERROR;
+ }
+ return reset_nosync();
+}
+
+// always call with lock held
+status_t VorbisPlayer::reset_nosync()
+{
+ // close file
+ ov_clear(&mVorbisFile); // this also closes the FILE
+ if (mFile != NULL) {
+ LOGV("OOPS! Vorbis didn't close the file");
+ fclose(mFile);
+ }
+ mState = STATE_ERROR;
+
+ mPlayTime = -1;
+ mDuration = -1;
+ mLoop = false;
+ mAndroidLoop = false;
+ mPaused = false;
+ mRender = false;
+ return NO_ERROR;
+}
+
+status_t VorbisPlayer::setLooping(int loop)
+{
+ LOGV("setLooping\n");
+ Mutex::Autolock l(mMutex);
+ mLoop = (loop != 0);
+ return NO_ERROR;
+}
+
+status_t VorbisPlayer::createOutputTrack() {
+ // open audio track
+ vorbis_info *vi = ov_info(&mVorbisFile, -1);
+
+ LOGV("Create AudioTrack object: rate=%ld, channels=%d\n",
+ vi->rate, vi->channels);
+ if (mAudioSink->open(vi->rate, vi->channels, AudioSystem::PCM_16_BIT, DEFAULT_AUDIOSINK_BUFFERCOUNT) != NO_ERROR) {
+ LOGE("mAudioSink open failed");
+ return ERROR_OPEN_FAILED;
+ }
+ return NO_ERROR;
+}
+
+int VorbisPlayer::renderThread(void* p) {
+ return ((VorbisPlayer*)p)->render();
+}
+
+#define AUDIOBUFFER_SIZE 4096
+
+int VorbisPlayer::render() {
+ int result = -1;
+ int temp;
+ int current_section = 0;
+ bool audioStarted = false;
+
+ LOGV("render\n");
+
+ // allocate render buffer
+ mAudioBuffer = new char[AUDIOBUFFER_SIZE];
+ if (!mAudioBuffer) {
+ LOGE("mAudioBuffer allocate failed\n");
+ goto threadExit;
+ }
+
+ // let main thread know we're ready
+ {
+ Mutex::Autolock l(mMutex);
+ mRenderTid = myTid();
+ mCondition.signal();
+ }
+
+ while (1) {
+ long numread = 0;
+ {
+ Mutex::Autolock l(mMutex);
+
+ // pausing?
+ if (mPaused) {
+ if (mAudioSink->ready()) mAudioSink->pause();
+ mRender = false;
+ audioStarted = false;
+ }
+
+ // nothing to render, wait for client thread to wake us up
+ if (!mExit && !mRender) {
+ LOGV("render - signal wait\n");
+ mCondition.wait(mMutex);
+ LOGV("render - signal rx'd\n");
+ }
+ if (mExit) break;
+
+ // We could end up here if start() is called, and before we get a
+ // chance to run, the app calls stop() or reset(). Re-check render
+ // flag so we don't try to render in stop or reset state.
+ if (!mRender) continue;
+
+ // render vorbis data into the input buffer
+ numread = ov_read(&mVorbisFile, mAudioBuffer, AUDIOBUFFER_SIZE, &current_section);
+ if (numread == 0) {
+ // end of file, do we need to loop?
+ // ...
+ if (mLoop || mAndroidLoop) {
+ ov_time_seek(&mVorbisFile, 0);
+ current_section = 0;
+ numread = ov_read(&mVorbisFile, mAudioBuffer, AUDIOBUFFER_SIZE, &current_section);
+ } else {
+ mAudioSink->stop();
+ audioStarted = false;
+ mRender = false;
+ mPaused = true;
+ int endpos = ov_time_tell(&mVorbisFile);
+
+ LOGV("send MEDIA_PLAYBACK_COMPLETE");
+ sendEvent(MEDIA_PLAYBACK_COMPLETE);
+
+ // wait until we're started again
+ LOGV("playback complete - wait for signal");
+ mCondition.wait(mMutex);
+ LOGV("playback complete - signal rx'd");
+ if (mExit) break;
+
+ // if we're still at the end, restart from the beginning
+ if (mState == STATE_OPEN) {
+ int curpos = ov_time_tell(&mVorbisFile);
+ if (curpos == endpos) {
+ ov_time_seek(&mVorbisFile, 0);
+ }
+ current_section = 0;
+ numread = ov_read(&mVorbisFile, mAudioBuffer, AUDIOBUFFER_SIZE, &current_section);
+ }
+ }
+ }
+ }
+
+ // codec returns negative number on error
+ if (numread < 0) {
+ LOGE("Error in Vorbis decoder");
+ sendEvent(MEDIA_ERROR);
+ break;
+ }
+
+ // create audio output track if necessary
+ if (!mAudioSink->ready()) {
+ LOGV("render - create output track\n");
+ if (createOutputTrack() != NO_ERROR)
+ break;
+ }
+
+ // Write data to the audio hardware
+ if ((temp = mAudioSink->write(mAudioBuffer, numread)) < 0) {
+ LOGE("Error in writing:%d",temp);
+ result = temp;
+ break;
+ }
+
+ // start audio output if necessary
+ if (!audioStarted && !mPaused && !mExit) {
+ LOGV("render - starting audio\n");
+ mAudioSink->start();
+ audioStarted = true;
+ }
+ }
+
+threadExit:
+ mAudioSink.clear();
+ if (mAudioBuffer) {
+ delete [] mAudioBuffer;
+ mAudioBuffer = NULL;
+ }
+
+ // tell main thread goodbye
+ Mutex::Autolock l(mMutex);
+ mRenderTid = -1;
+ mCondition.signal();
+ return result;
+}
+
+} // end namespace android
diff --git a/media/libmediaplayerservice/VorbisPlayer.h b/media/libmediaplayerservice/VorbisPlayer.h
new file mode 100644
index 0000000..c30dc1b
--- /dev/null
+++ b/media/libmediaplayerservice/VorbisPlayer.h
@@ -0,0 +1,91 @@
+/*
+**
+** Copyright 2008, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+** http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+
+#ifndef ANDROID_VORBISPLAYER_H
+#define ANDROID_VORBISPLAYER_H
+
+#include <utils/threads.h>
+
+#include <media/MediaPlayerInterface.h>
+#include <media/AudioTrack.h>
+
+#include "ivorbiscodec.h"
+#include "ivorbisfile.h"
+
+#define ANDROID_LOOP_TAG "ANDROID_LOOP"
+
+namespace android {
+
+class VorbisPlayer : public MediaPlayerInterface {
+public:
+ VorbisPlayer();
+ ~VorbisPlayer();
+
+ virtual void onFirstRef();
+ virtual status_t initCheck();
+ virtual status_t setDataSource(const char* path);
+ virtual status_t setDataSource(int fd, int64_t offset, int64_t length);
+ virtual status_t setVideoSurface(const sp<ISurface>& surface) { return UNKNOWN_ERROR; }
+ virtual status_t prepare();
+ virtual status_t prepareAsync();
+ virtual status_t start();
+ virtual status_t stop();
+ virtual status_t seekTo(int msec);
+ virtual status_t pause();
+ virtual bool isPlaying();
+ virtual status_t getCurrentPosition(int* msec);
+ virtual status_t getDuration(int* msec);
+ virtual status_t release();
+ virtual status_t reset();
+ virtual status_t setLooping(int loop);
+ virtual player_type playerType() { return VORBIS_PLAYER; }
+
+private:
+ status_t setdatasource(const char *path, int fd, int64_t offset, int64_t length);
+ status_t reset_nosync();
+ status_t createOutputTrack();
+ static int renderThread(void*);
+ int render();
+
+ static size_t vp_fread(void *, size_t, size_t, void *);
+ static int vp_fseek(void *, ogg_int64_t, int);
+ static int vp_fclose(void *);
+ static long vp_ftell(void *);
+
+ Mutex mMutex;
+ Condition mCondition;
+ FILE* mFile;
+ int64_t mOffset;
+ int64_t mLength;
+ OggVorbis_File mVorbisFile;
+ char* mAudioBuffer;
+ int mPlayTime;
+ int mDuration;
+ status_t mState;
+ int mStreamType;
+ bool mLoop;
+ bool mAndroidLoop;
+ volatile bool mExit;
+ bool mPaused;
+ volatile bool mRender;
+ pid_t mRenderTid;
+};
+
+}; // namespace android
+
+#endif // ANDROID_VORBISPLAYER_H
+