Commit message: None
CVE: CVE-2016-3913
CWE: CWE-264
Vulnerability description: media/libmediaplayerservice/MediaPlayerService.cpp in mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, 6.x before 2016-10-01, and 7.0 before 2016-10-01 does not validate a certain static_cast operation, which allows attackers to gain privileges via a crafted application, aka internal bug 30204103.

Project: Android

Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
    mExit(false), mActive(false), mClient(client), mCb(cb)
{
    createThread(callbackThread, this);
}

Project: Android

MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, int uid, int pid,
 const audio_attributes_t* attr)
 : mCallback(NULL),
      mCallbackCookie(NULL),
      mCallbackData(NULL),
      mStreamType(AUDIO_STREAM_MUSIC),
      mLeftVolume(1.0),
      mRightVolume(1.0),
      mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
      mSampleRateHz(0),
      mMsecsPerFrame(0),
      mFrameSize(0),
      mSessionId(sessionId),
      mUid(uid),
      mPid(pid),
      mSendLevel(0.0),
      mAuxEffectId(0),
      mFlags(AUDIO_OUTPUT_FLAG_NONE)
{
    ALOGV("AudioOutput(%d)", sessionId);
 if (attr != NULL) {
        mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
 if (mAttributes != NULL) {
            memcpy(mAttributes, attr, sizeof(audio_attributes_t));
            mStreamType = audio_attributes_to_stream_type(attr);
 }
 } else {
        mAttributes = NULL;
 }

    setMinBufferCount();
}

Project: Android

CallbackThread::CallbackThread(
 const wp<MediaPlayerBase::AudioSink> &sink,
 MediaPlayerBase::AudioSink::AudioCallback cb,
 void *cookie)
 : mSink(sink),
      mCallback(cb),
      mCookie(cookie),
      mBuffer(NULL),
      mBufferSize(0) {
}

Project: Android

void MediaPlayerService::AudioOutput::CallbackWrapper(
 int event, void *cookie, void *info) {
 CallbackData *data = (CallbackData*)cookie;
    data->lock();
 AudioOutput *me = data->getOutput();
 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
 if (me == NULL) {
        data->unlock();
 if (buffer != NULL) {
            buffer->size = 0;
 }
 return;
 }

 switch(event) {
 case AudioTrack::EVENT_MORE_DATA: {
 size_t actualSize = (*me->mCallback)(
                me, buffer->raw, buffer->size, me->mCallbackCookie,
                CB_EVENT_FILL_BUFFER);


        ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");

        buffer->size = actualSize;
 } break;

 case AudioTrack::EVENT_STREAM_END:
        ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
                me->mCallbackCookie, CB_EVENT_STREAM_END);
 break;

 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
        ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
 (*me->mCallback)(me,  NULL /* buffer */, 0 /* size */,
                me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
 break;

 case AudioTrack::EVENT_UNDERRUN:
        ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
 break;

 default:
        ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
 }

    data->unlock();
}

Project: Android

 MediaPlayerService::Client::Client(
         const sp<MediaPlayerService>& service, pid_t pid,
         int32_t connId, const sp<IMediaPlayerClient>& client,
 audio_session_t audioSessionId, uid_t uid)
{
    ALOGV("Client(%d) constructor", connId);
    mPid = pid;
    mConnId = connId;
    mService = service;
    mClient = client;
    mLoop = false;
    mStatus = NO_INIT;
    mAudioSessionId = audioSessionId;
    mUID = uid;
    mRetransmitEndpointValid = false;
    mAudioAttributes = NULL;

#if CALLBACK_ANTAGONIZER
    ALOGD("create Antagonizer");
    mAntagonizer = new Antagonizer(notify, this);
#endif
}

Project: Android

MediaPlayerService::MediaPlayerService()
{
    ALOGV("MediaPlayerService created");
    mNextConnId = 1;

    mBatteryAudio.refCount = 0;
 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
        mBatteryAudio.deviceOn[i] = 0;
        mBatteryAudio.lastTime[i] = 0;
        mBatteryAudio.totalTime[i] = 0;
 }
    mBatteryAudio.deviceOn[SPEAKER] = 1;

 BatteryNotifier::getInstance().noteResetVideo();

 MediaPlayerFactory::registerBuiltinFactories();
}

Project: Android

MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
 const sp<IBinder>& service,
 const sp<MediaPlayerBase>& listener,
 int which) {
    mService = service;
    mListener = listener;
    mWhich = which;
}

Project: Android

void MediaPlayerService::addBatteryData(uint32_t params)
{
 Mutex::Autolock lock(mLock);

 int32_t time = systemTime() / 1000000L;

 if ((params & kBatteryDataSpeakerOn)
 || (params & kBatteryDataOtherAudioDeviceOn)) {

 int deviceOn[NUM_AUDIO_DEVICES];
 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
            deviceOn[i] = 0;
 }

 if ((params & kBatteryDataSpeakerOn)
 && (params & kBatteryDataOtherAudioDeviceOn)) {
            deviceOn[SPEAKER_AND_OTHER] = 1;
 } else if (params & kBatteryDataSpeakerOn) {
            deviceOn[SPEAKER] = 1;
 } else {
            deviceOn[OTHER_AUDIO_DEVICE] = 1;
 }

 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){

 if (mBatteryAudio.refCount > 0) { // if playing audio
 if (!deviceOn[i]) {
                        mBatteryAudio.lastTime[i] += time;
                        mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
                        mBatteryAudio.lastTime[i] = 0;
 } else {
                        mBatteryAudio.lastTime[i] = 0 - time;
 }
 }

                mBatteryAudio.deviceOn[i] = deviceOn[i];
 }
 }
 return;
 }

 if (params & kBatteryDataAudioFlingerStart) {
 if (mBatteryAudio.refCount == 0) {
 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
 if (mBatteryAudio.deviceOn[i]) {
                    mBatteryAudio.lastTime[i] -= time;
 }
 }
 }

        mBatteryAudio.refCount ++;
 return;

 } else if (params & kBatteryDataAudioFlingerStop) {
 if (mBatteryAudio.refCount <= 0) {
            ALOGW("Battery track warning: refCount is <= 0");
 return;
 }

 if (mBatteryAudio.refCount == 1) {
 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
 if (mBatteryAudio.deviceOn[i]) {
                    mBatteryAudio.lastTime[i] += time;
                    mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
                    mBatteryAudio.lastTime[i] = 0;
 }
 }
 }

        mBatteryAudio.refCount --;
 return;
 }

 int uid = IPCThreadState::self()->getCallingUid();
 if (uid == AID_MEDIA) {
 return;
 }
 int index = mBatteryData.indexOfKey(uid);

 if (index < 0) { // create a new entry for this UID
 BatteryUsageInfo info;
        info.audioTotalTime = 0;
        info.videoTotalTime = 0;
        info.audioLastTime = 0;
        info.videoLastTime = 0;
        info.refCount = 0;

 if (mBatteryData.add(uid, info) == NO_MEMORY) {
            ALOGE("Battery track error: no memory for new app");
 return;
 }
 }

 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);

 if (params & kBatteryDataCodecStarted) {
 if (params & kBatteryDataTrackAudio) {
            info.audioLastTime -= time;
            info.refCount ++;
 }
 if (params & kBatteryDataTrackVideo) {
            info.videoLastTime -= time;
            info.refCount ++;
 }
 } else {
 if (info.refCount == 0) {
            ALOGW("Battery track warning: refCount is already 0");
 return;
 } else if (info.refCount < 0) {
            ALOGE("Battery track error: refCount < 0");
            mBatteryData.removeItem(uid);
 return;
 }

 if (params & kBatteryDataTrackAudio) {
            info.audioLastTime += time;
            info.refCount --;
 }
 if (params & kBatteryDataTrackVideo) {
            info.videoLastTime += time;
            info.refCount --;
 }

 if (info.refCount == 0) {
            info.audioTotalTime += info.audioLastTime;
            info.audioLastTime = 0;
            info.videoTotalTime += info.videoLastTime;
            info.videoLastTime = 0;
 }
 }
}

Project: Android

void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
 Mutex::Autolock lock(mLock);
 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
        mMetadataUpdated.add(metadata_type);
 }
}

Project: Android

status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
{
    ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
 Mutex::Autolock l(mLock);
 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
 return NO_ERROR;
}

Project: Android

status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
{
    ALOGV("attachAuxEffect(%d)", effectId);
 Mutex::Autolock lock(mLock);
    mAuxEffectId = effectId;
 if (mTrack != 0) {
 return mTrack->attachAuxEffect(effectId);
 }
 return NO_ERROR;
}

Project: Android

void MediaPlayerService::Client::ServiceDeathNotifier::binderDied(const wp<IBinder>& /*who*/) {
    sp<MediaPlayerBase> listener = mListener.promote();
 if (listener != NULL) {
        listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
 } else {
        ALOGW("listener for process %d death is gone", mWhich);
 }
}

Project: Android

ssize_t MediaPlayerService::AudioOutput::bufferSize() const
{
 Mutex::Autolock lock(mLock);
 if (mTrack == 0) return NO_INIT;
 return mTrack->frameCount() * mFrameSize;
}

Project: Android

int Antagonizer::callbackThread(void* user)
{
    ALOGD("Antagonizer started");
 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
 while (!p->mExit) {
 if (p->mActive) {
            ALOGV("send event");
            p->mCb(p->mClient, 0, 0, 0);
 }
        usleep(interval);
 }
 Mutex::Autolock _l(p->mLock);
    p->mCondition.signal();
    ALOGD("Antagonizer stopped");
 return 0;
}

Project: Android

static bool checkPermission(const char* permissionString) {
 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
 bool ok = checkCallingPermission(String16(permissionString));
 if (!ok) ALOGE("Request requires %s", permissionString);
 return ok;
}

Project: Android

void MediaPlayerService::AudioOutput::close()
{
    ALOGV("close");
    sp<AudioTrack> track;
 {
 Mutex::Autolock lock(mLock);
        track = mTrack;
        close_l(); // clears mTrack
 }
}

Project: Android

void MediaPlayerService::AudioOutput::close_l()
{
    mTrack.clear();
}

Project: Android

sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
 audio_session_t audioSessionId)
{
 pid_t pid = IPCThreadState::self()->getCallingPid();
 int32_t connId = android_atomic_inc(&mNextConnId);

    sp<Client> c = new Client(
 this, pid, connId, client, audioSessionId,
 IPCThreadState::self()->getCallingUid());

    ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
 IPCThreadState::self()->getCallingUid());

    wp<Client> w = c;
 {
 Mutex::Autolock lock(mLock);
        mClients.add(w);
 }
 return c;
}

Project: Android

sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
{
 pid_t pid = IPCThreadState::self()->getCallingPid();
    sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
    wp<MediaRecorderClient> w = recorder;
 Mutex::Autolock lock(mLock);
    mMediaRecorderClients.add(w);
    ALOGV("Create new media recorder client from pid %d", pid);
 return recorder;
}

Project: Android

sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
{
 pid_t pid = IPCThreadState::self()->getCallingPid();
    sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
    ALOGV("Create new media retriever from pid %d", pid);
 return retriever;
}

Project: Android

sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
{
    sp<MediaPlayerBase> p = mPlayer;
 if ((p != NULL) && (p->playerType() != playerType)) {
        ALOGV("delete player");
        p.clear();
 }
 if (p == NULL) {
        p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
 }

 if (p != NULL) {
        p->setUID(mUID);
 }

 return p;
}

Project: Android

void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
{
    ALOGV("deleteRecycledTrack_l");
 if (mRecycledTrack != 0) {

 if (mCallbackData != NULL) {
            mCallbackData->setOutput(NULL);
            mCallbackData->endTrackSwitch();
 }

 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
 int32_t msec = 0;
 if (!mRecycledTrack->stopped()) { // check if active
 (void)mRecycledTrack->pendingDuration(&msec);
 }
            mRecycledTrack->stop(); // ensure full data drain
            ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
 if (msec > 0) {
 static const int32_t WAIT_LIMIT_MS = 3000;
 if (msec > WAIT_LIMIT_MS) {
                    msec = WAIT_LIMIT_MS;
 }
                usleep(msec * 1000LL);
 }
 }

        mRecycledTrack.clear();
        close_l();
 delete mCallbackData;
        mCallbackData = NULL;
 }
}

Project: Android

void MediaPlayerService::Client::disconnect()
{
    ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
    sp<MediaPlayerBase> p;
 {
 Mutex::Autolock l(mLock);
        p = mPlayer;
        mClient.clear();
 }

    mPlayer.clear();

 if (p != 0) {
        p->setNotifyCallback(0, 0);
#if CALLBACK_ANTAGONIZER
        ALOGD("kill Antagonizer");
        mAntagonizer->kill();
#endif
        p->reset();
 }

    disconnectNativeWindow();

 IPCThreadState::self()->flushCommands();
}

Project: Android

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, (mTrack != 0) ? mTrack->latency() : -1);
    result.append(buffer);
    snprintf(buffer, 255, "  aux effect id(%d), send level (%f)\n",
            mAuxEffectId, mSendLevel);
    result.append(buffer);

 ::write(fd, result.string(), result.size());
 if (mTrack != 0) {
        mTrack->dump(fd, args);
 }
 return NO_ERROR;
}

Project: Android

status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
{
 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 (mPlayer != NULL) {
        mPlayer->dump(fd, args);
 }
 if (mAudioOutput != 0) {
        mAudioOutput->dump(fd, args);
 }
    write(fd, "\n", 1);
 return NO_ERROR;
}

Project: Android

status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
{
 const size_t SIZE = 256;
 char buffer[SIZE];
 String8 result;
 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;

 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);
            clients.add(c);
 }
 if (mMediaRecorderClients.size() == 0) {
                result.append(" No media recorder client\n\n");
 } else {
 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
                sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
 if (c != 0) {
                    snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
                    result.append(buffer);
                    write(fd, result.string(), result.size());
                    result = "\n";
                    c->dump(fd, args);
                    mediaRecorderClients.add(c);
 }
 }
 }

        result.append(" Files opened and/or mapped:\n");
        snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
 FILE *f = fopen(buffer, "r");
 if (f) {
 while (!feof(f)) {
                fgets(buffer, SIZE, f);
 if (strstr(buffer, " /storage/") ||
                    strstr(buffer, " /system/sounds/") ||
                    strstr(buffer, " /data/") ||
                    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", getpid());
 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", getpid(), 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, "/storage/") == linkto ||
                                    strstr(linkto, "/system/sounds/") == linkto ||
                                    strstr(linkto, "/data/") == 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");
 }

        gLooperRoster.dump(fd, args);

 bool dumpMem = false;
 bool unreachableMemory = false;
 for (size_t i = 0; i < args.size(); i++) {
 if (args[i] == String16("-m")) {
                dumpMem = true;
 } else if (args[i] == String16("--unreachable")) {
                unreachableMemory = true;
 }
 }
 if (dumpMem) {
            result.append("\nDumping memory:\n");
            std::string s = dumpMemoryAddresses(100 /* limit */);
            result.append(s.c_str(), s.size());
 }
 if (unreachableMemory) {
            result.append("\nDumping unreachable memory:\n");
            std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
            result.append(s.c_str(), s.size());
 }
 }
    write(fd, result.string(), result.size());
 return NO_ERROR;
}

Project: Android

bool findMetadata(const Metadata::Filter& filter, const int32_t val)
{
 if (filter.isEmpty()) return false;
 if (filter[0] == Metadata::kAny) return true;

 return filter.indexOf(val) >= 0;
}

Project: Android

ssize_t MediaPlayerService::AudioOutput::frameCount() const
{
 Mutex::Autolock lock(mLock);
 if (mTrack == 0) return NO_INIT;
 return mTrack->frameCount();
}

Project: Android

int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
{
 Mutex::Autolock lock(mLock);
 if (mTrack == 0) {
 return 0;
 }
 int64_t duration;
 if (mTrack->getBufferDurationInUs(&duration) != OK) {
 return 0;
 }
 return duration;
}

Project: Android

sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
 return MediaCodecList::getLocalInstance();
}

Project: Android

status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
{
    ALOGV("getCurrentPosition");
    sp<MediaPlayerBase> p = getPlayer();
 if (p == 0) return UNKNOWN_ERROR;
 status_t ret = p->getCurrentPosition(msec);
 if (ret == NO_ERROR) {
        ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
 } else {
        ALOGE("getCurrentPosition returned %d", ret);
 }
 return ret;
}

Project: Android

status_t MediaPlayerService::Client::getDuration(int *msec)
{
    ALOGV("getDuration");
    sp<MediaPlayerBase> p = getPlayer();
 if (p == 0) return UNKNOWN_ERROR;
 status_t ret = p->getDuration(msec);
 if (ret == NO_ERROR) {
        ALOGV("[%d] getDuration = %d", mConnId, *msec);
 } else {
        ALOGE("getDuration returned %d", ret);
 }
 return ret;
}

Project: Android

status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
{
 Mutex::Autolock lock(mLock);
 if (mTrack == 0) return NO_INIT;
 ExtendedTimestamp ets;
 status_t status = mTrack->getTimestamp(&ets);
 if (status == OK || status == WOULD_BLOCK) {
 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
 }
 return status;
}

Project: Android

status_t MediaPlayerService::Client::getMetadata(
 bool update_only, bool /*apply_filter*/, Parcel *reply)
{
    sp<MediaPlayerBase> player = getPlayer();
 if (player == 0) return UNKNOWN_ERROR;

 status_t status;
    reply->writeInt32(-1);

    media::Metadata::Filter ids;

 {
 Mutex::Autolock lock(mLock);
 if (update_only) {
            ids = mMetadataUpdated;
 }
        mMetadataUpdated.clear();
 }

    media::Metadata metadata(reply);

    metadata.appendHeader();
    status = player->getMetadata(ids, reply);

 if (status != OK) {
        metadata.resetParcel();
        ALOGE("getMetadata failed %d", status);
 return status;
 }


    metadata.updateLength();
 return OK;
}

Project: Android

int MediaPlayerService::AudioOutput::getMinBufferCount()
{
    setMinBufferCount(); // benign race wrt other threads
 return mMinBufferCount;
}

Project: Android

sp<IOMX> MediaPlayerService::getOMX() {
    ALOGI("MediaPlayerService::getOMX");
 Mutex::Autolock autoLock(mLock);

 if (mOMX.get() == NULL) {
        mOMX = new OMX;
 }

 return mOMX;
}

Project: Android

status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
    ALOGV("[%d] getParameter(%d)", mConnId, key);
    sp<MediaPlayerBase> p = getPlayer();
 if (p == 0) return UNKNOWN_ERROR;
 return p->getParameter(key, reply);
}

Project: Android

String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
{
 Mutex::Autolock lock(mLock);
 if (mTrack == 0) return String8::empty();
 return mTrack->getParameters(keys);
}

Project: Android

status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
{
    ALOGV("setPlaybackRate");
 Mutex::Autolock lock(mLock);
 if (mTrack == 0) {
 return NO_INIT;
 }
 *rate = mTrack->getPlaybackRate();
 return NO_ERROR;
}

Project: Android

status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
{
    sp<MediaPlayerBase> p = getPlayer();
 if (p == 0) return UNKNOWN_ERROR;
 status_t ret = p->getPlaybackSettings(rate);
 if (ret == NO_ERROR) {
        ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
                mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
 } else {
        ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
 }
 return ret;
}

Project: Android

int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
{
 Mutex::Autolock lock(mLock);
 if (mTrack == 0 || mSampleRateHz == 0) {
 return 0;
 }

 uint32_t numFramesPlayed;
 int64_t numFramesPlayedAt;
 AudioTimestamp ts;
 static const int64_t kStaleTimestamp100ms = 100000;

 status_t res = mTrack->getTimestamp(ts);
 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
        numFramesPlayed = ts.mPosition;
        numFramesPlayedAt = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
 const int64_t timestampAge = nowUs - numFramesPlayedAt;
 if (timestampAge > kStaleTimestamp100ms) {
            ALOGV("getTimestamp: returned stale timestamp nowUs(%lld) numFramesPlayedAt(%lld)",
 (long long)nowUs, (long long)numFramesPlayedAt);
            numFramesPlayedAt = nowUs - kStaleTimestamp100ms;
 }
 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
        numFramesPlayed = 0;
        numFramesPlayedAt = nowUs;
 } else { // case 3: transitory at new track or audio fast tracks.
        res = mTrack->getPosition(&numFramesPlayed);
        CHECK_EQ(res, (status_t)OK);
        numFramesPlayedAt = nowUs;
        numFramesPlayedAt += 1000LL * mTrack->latency() / 2; /* XXX */
 }

 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
 + nowUs - numFramesPlayedAt;
 if (durationUs < 0) {
        ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
        durationUs = 0;
 }
    ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
 (long long)durationUs, (long long)nowUs, numFramesPlayed, (long long)numFramesPlayedAt);
 return durationUs;
}

Project: Android

status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
{
 Mutex::Autolock lock(mLock);
 if (mTrack == 0) return NO_INIT;
 return mTrack->getPosition(position);
}

Project: Android

uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
{
 Mutex::Autolock lock(mLock);
 if (mTrack == 0) return 0;
 return mTrack->getSampleRate();
}

Project: Android

status_t MediaPlayerService::Client::getSyncSettings(
 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
{
    sp<MediaPlayerBase> p = getPlayer();
 if (p == 0) return UNKNOWN_ERROR;
 status_t ret = p->getSyncSettings(sync, videoFps);
 if (ret == NO_ERROR) {
        ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
                mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
 } else {
        ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
 }
 return ret;
}

Project: Android

status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
{
 Mutex::Autolock lock(mLock);
 if (mTrack == 0) return NO_INIT;
 return mTrack->getTimestamp(ts);
}

Project: Android

void MediaPlayerService::instantiate() {
    defaultServiceManager()->addService(
 String16("media.player"), new MediaPlayerService());
}

Project: Android

status_t MediaPlayerService::Client::invoke(const Parcel& request,
 Parcel *reply)
{
    sp<MediaPlayerBase> p = getPlayer();
 if (p == NULL) return UNKNOWN_ERROR;
 return p->invoke(request, reply);
}

Project: Android

bool MediaPlayerService::AudioOutput::isOnEmulator()
{
    setMinBufferCount(); // benign race wrt other threads
 return mIsOnEmulator;
}

Project: Android

void Antagonizer::kill()
{
 Mutex::Autolock _l(mLock);
    mActive = false;
    mExit = true;
    mCondition.wait(mLock);
}

Project: Android

uint32_t MediaPlayerService::AudioOutput::latency () const
{
 Mutex::Autolock lock(mLock);
 if (mTrack == 0) return 0;
 return mTrack->latency();
}

Project: Android

sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
 const String16 &opPackageName,
 const sp<IRemoteDisplayClient>& client, const String8& iface) {
 if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
 return NULL;
 }

 return new RemoteDisplay(opPackageName, client, iface.string());
}

Project: Android

sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
 return new HDCP(createEncryptionModule);
}

Project: Android

float MediaPlayerService::AudioOutput::msecsPerFrame() const
{
 Mutex::Autolock lock(mLock);
 return mMsecsPerFrame;
}

Project: Android

status_t MediaPlayerService::Client::pause()
{
    ALOGV("[%d] pause", mConnId);
    sp<MediaPlayerBase> p = getPlayer();
 if (p == 0) return UNKNOWN_ERROR;
 return p->pause();
}

Project: Android

void MediaPlayerService::AudioOutput::pause()
{
    ALOGV("pause");
 Mutex::Autolock lock(mLock);
 if (mTrack != 0) mTrack->pause();
}

Project: Android

status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
 Mutex::Autolock lock(mLock);

 int32_t time = systemTime() / 1000000L; //in ms
 int32_t totalTime;

 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
        totalTime = mBatteryAudio.totalTime[i];

 if (mBatteryAudio.deviceOn[i]
 && (mBatteryAudio.lastTime[i] != 0)) {
 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
                totalTime += tmpTime;
 }

        reply->writeInt32(totalTime);
        mBatteryAudio.totalTime[i] = 0;
 }

 BatteryUsageInfo info;
 int size = mBatteryData.size();

    reply->writeInt32(size);
 int i = 0;

 while (i < size) {
        info = mBatteryData.valueAt(i);

        reply->writeInt32(mBatteryData.keyAt(i)); //UID
        reply->writeInt32(info.audioTotalTime);
        reply->writeInt32(info.videoTotalTime);

        info.audioTotalTime = 0;
        info.videoTotalTime = 0;

 if (info.refCount <= 0) {
            mBatteryData.removeItemsAt(i);
            size --;
            i --;
 }
        i++;
 }
 return NO_ERROR;
}

Project: Android

void MediaPlayerService::removeClient(wp<Client> client)
{
 Mutex::Autolock lock(mLock);

     mClients.remove(client);
 }

Project: Android

void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
{
 Mutex::Autolock lock(mLock);
    mMediaRecorderClients.remove(client);
    ALOGV("Delete media recorder client");
}

Project: Android

status_t MediaPlayerService::Client::reset()
{
    ALOGV("[%d] reset", mConnId);
    mRetransmitEndpointValid = false;
    sp<MediaPlayerBase> p = getPlayer();
 if (p == 0) return UNKNOWN_ERROR;
 return p->reset();
}

Project: Android

status_t MediaPlayerService::Client::seekTo(int msec)
{
    ALOGV("[%d] seekTo(%d)", mConnId, msec);
    sp<MediaPlayerBase> p = getPlayer();
 if (p == 0) return UNKNOWN_ERROR;
 return p->seekTo(msec);
}

Project: Android

void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
 Mutex::Autolock lock(mLock);
 if (attributes == NULL) {
        free(mAttributes);
        mAttributes = NULL;
 } else {
 if (mAttributes == NULL) {
            mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
 }
        memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
        mStreamType = audio_attributes_to_stream_type(attributes);
 }
}

Project: Android

status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
{
 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
    mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
 if (mAudioAttributes == NULL) {
 return NO_MEMORY;
 }
    unmarshallAudioAttributes(parcel, mAudioAttributes);

    ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
            mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
            mAudioAttributes->tags);

 if (mAudioOutput != 0) {
        mAudioOutput->setAudioAttributes(mAudioAttributes);
 }
 return NO_ERROR;
}

Project: Android

status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
{
    ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
 Mutex::Autolock l(mLock);
 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
 return NO_ERROR;
}

Project: Android

void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
{
 Mutex::Autolock lock(mLock);
 if (mAttributes == NULL) {
        mStreamType = streamType;
 }
}

Project: Android

status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
{
    ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
 Mutex::Autolock l(mLock);
 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
 return NO_ERROR;
}

Project: Android

status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
{
    ALOGV("setAuxEffectSendLevel(%f)", level);
 Mutex::Autolock lock(mLock);
    mSendLevel = level;
 if (mTrack != 0) {
 return mTrack->setAuxEffectSendLevel(level);
 }
 return NO_ERROR;
}

Project: Android

status_t MediaPlayerService::Client::setDataSource(
 const sp<IMediaHTTPService> &httpService,
 const char *url,
 const KeyedVector<String8, String8> *headers)
{
    ALOGV("setDataSource(%s)", url);
 if (url == NULL)
 return UNKNOWN_ERROR;

 if ((strncmp(url, "http://", 7) == 0) ||
 (strncmp(url, "https://", 8) == 0) ||
 (strncmp(url, "rtsp://", 7) == 0)) {
 if (!checkPermission("android.permission.INTERNET")) {
 return PERMISSION_DENIED;
 }
 }

 if (strncmp(url, "content://", 10) == 0) {

 String16 url16(url);
 int fd = android::openContentProviderFile(url16);
 if (fd < 0)
 {
            ALOGE("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 = MediaPlayerFactory::getPlayerType(this, url);
        sp<MediaPlayerBase> p = setDataSource_pre(playerType);
 if (p == NULL) {
 return NO_INIT;
 }

        setDataSource_post(p, p->setDataSource(httpService, url, headers));
 return mStatus;
 }
}

Project: Android

status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
{
    ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
            fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
 struct stat sb;
 int ret = fstat(fd, &sb);
 if (ret != 0) {
        ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
 return UNKNOWN_ERROR;
 }

    ALOGV("st_dev  = %llu", static_cast<unsigned long long>(sb.st_dev));
    ALOGV("st_mode = %u", sb.st_mode);
    ALOGV("st_uid  = %lu", static_cast<unsigned long>(sb.st_uid));
    ALOGV("st_gid  = %lu", static_cast<unsigned long>(sb.st_gid));
    ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));

 if (offset >= sb.st_size) {
        ALOGE("offset error");
 return UNKNOWN_ERROR;
 }
 if (offset + length > sb.st_size) {
        length = sb.st_size - offset;
        ALOGV("calculated length = %lld", (long long)length);
 }

    player_type playerType = MediaPlayerFactory::getPlayerType(this,
                                                               fd,
                                                               offset,
                                                               length);
    sp<MediaPlayerBase> p = setDataSource_pre(playerType);
 if (p == NULL) {
 return NO_INIT;
 }

    setDataSource_post(p, p->setDataSource(fd, offset, length));
 return mStatus;
}

Project: Android

status_t MediaPlayerService::Client::setDataSource(
 const sp<IStreamSource> &source) {
    player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
    sp<MediaPlayerBase> p = setDataSource_pre(playerType);
 if (p == NULL) {
 return NO_INIT;
 }

    setDataSource_post(p, p->setDataSource(source));
 return mStatus;
}

Project: Android

status_t MediaPlayerService::Client::setDataSource(
 const sp<IDataSource> &source) {
    sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
    player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
    sp<MediaPlayerBase> p = setDataSource_pre(playerType);
 if (p == NULL) {
 return NO_INIT;
 }
    setDataSource_post(p, p->setDataSource(dataSource));
 return mStatus;
}

Project: Android

sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
        player_type playerType)
{
    ALOGV("player type = %d", playerType);

    sp<MediaPlayerBase> p = createPlayer(playerType);
 if (p == NULL) {
 return p;
 }

    sp<IServiceManager> sm = defaultServiceManager();
    sp<IBinder> binder = sm->getService(String16("media.extractor"));
    mExtractorDeathListener = new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH);
    binder->linkToDeath(mExtractorDeathListener);

    binder = sm->getService(String16("media.codec"));
    mCodecDeathListener = new ServiceDeathNotifier(binder, p, MEDIACODEC_PROCESS_DEATH);
    binder->linkToDeath(mCodecDeathListener);

 if (!p->hardwareOutput()) {
 Mutex::Autolock l(mLock);
        mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
                mPid, mAudioAttributes);
 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
 }

 return p;
}

Project: Android

status_t MediaPlayerService::Client::setLooping(int loop)
{
    ALOGV("[%d] setLooping(%d)", mConnId, loop);
    mLoop = loop;
    sp<MediaPlayerBase> p = getPlayer();
 if (p != 0) return p->setLooping(loop);
 return NO_ERROR;
}

Project: Android

status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
{
 status_t status;
    media::Metadata::Filter allow, drop;

 if (unmarshallFilter(filter, &allow, &status) &&
        unmarshallFilter(filter, &drop, &status)) {
 Mutex::Autolock lock(mLock);

        mMetadataAllow = allow;
        mMetadataDrop = drop;
 }
 return status;
}

Project: Android

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
 }
}

Project: Android

void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
 Mutex::Autolock lock(mLock);
    mNextOutput = nextOutput;
}

Project: Android

status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
    ALOGV("[%d] setParameter(%d)", mConnId, key);
 switch (key) {
 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
 {
 Mutex::Autolock l(mLock);
 return setAudioAttributes_l(request);
 }
 default:
        sp<MediaPlayerBase> p = getPlayer();
 if (p == 0) { return UNKNOWN_ERROR; }
 return p->setParameter(key, request);
 }
}

Project: Android

status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
{
 Mutex::Autolock lock(mLock);
 if (mTrack == 0) return NO_INIT;
 return mTrack->setParameters(keyValuePairs);
}

Project: Android

status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
{
    ALOGV("setPlaybackRate(%f %f %d %d)",
                rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
 Mutex::Autolock lock(mLock);
 if (mTrack == 0) {
        mPlaybackRate = rate;
 return OK;
 }
 status_t res = mTrack->setPlaybackRate(rate);
 if (res != NO_ERROR) {
 return res;
 }
    CHECK_GT(rate.mSpeed, 0.f);
    mPlaybackRate = rate;
 if (mSampleRateHz != 0) {
        mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
 }
 return res;
}

Project: Android

status_t MediaPlayerService::Client::setRetransmitEndpoint(
 const struct sockaddr_in* endpoint) {

 if (NULL != endpoint) {
 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
 uint16_t p = ntohs(endpoint->sin_port);
        ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
 } else {
        ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
 }

    sp<MediaPlayerBase> p = getPlayer();

 if (p != 0) return INVALID_OPERATION;

 if (NULL != endpoint) {
        mRetransmitEndpoint = *endpoint;
        mRetransmitEndpointValid = true;
 } else {
        mRetransmitEndpointValid = false;
 }

 return NO_ERROR;
}

Project: Android

status_t MediaPlayerService::Client::setSyncSettings(
 const AVSyncSettings& sync, float videoFpsHint)
{
    ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
            mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
    sp<MediaPlayerBase> p = getPlayer();
 if (p == 0) return UNKNOWN_ERROR;
 return p->setSyncSettings(sync, videoFpsHint);
}

Project: Android

status_t MediaPlayerService::Client::setVideoSurfaceTexture(
 const sp<IGraphicBufferProducer>& bufferProducer)
{
    ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
    sp<MediaPlayerBase> p = getPlayer();
 if (p == 0) return UNKNOWN_ERROR;

    sp<IBinder> binder(IInterface::asBinder(bufferProducer));
 if (mConnectedWindowBinder == binder) {
 return OK;
 }

    sp<ANativeWindow> anw;
 if (bufferProducer != NULL) {
        anw = new Surface(bufferProducer, true /* controlledByApp */);
 status_t err = native_window_api_connect(anw.get(),
                NATIVE_WINDOW_API_MEDIA);

 if (err != OK) {
            ALOGE("setVideoSurfaceTexture failed: %d", err);
            reset();

            disconnectNativeWindow();

 return err;
 }
 }

 status_t err = p->setVideoSurfaceTexture(bufferProducer);

    disconnectNativeWindow();

    mConnectedWindow = anw;

 if (err == OK) {
        mConnectedWindowBinder = binder;
 } else {
        disconnectNativeWindow();
 }

 return err;
}

Project: Android

status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
{
    ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);

    sp<MediaPlayerBase> p = getPlayer();
 {
 Mutex::Autolock l(mLock);
 if (p != 0 && p->hardwareOutput()) {
 MediaPlayerHWInterface* hwp =
 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
 return hwp->setVolume(leftVolume, rightVolume);
 } else {
 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
 return NO_ERROR;
 }
 }

 return NO_ERROR;
}

Project: Android

void MediaPlayerService::AudioOutput::setVolume(float left, float right)
{
    ALOGV("setVolume(%f, %f)", left, right);
 Mutex::Autolock lock(mLock);
    mLeftVolume = left;
    mRightVolume = right;
 if (mTrack != 0) {
        mTrack->setVolume(left, right);
 }
}

Project: Android

bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
{
 Mutex::Autolock lock(mLock);

 if (findMetadata(mMetadataDrop, code)) {
 return true;
 }

 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
 return false;
 } else {
 return true;
 }
}

Project: Android

status_t MediaPlayerService::Client::start()
{
    ALOGV("[%d] start", mConnId);
    sp<MediaPlayerBase> p = getPlayer();
 if (p == 0) return UNKNOWN_ERROR;
    p->setLooping(mLoop);
 return p->start();
}

Project: Android

status_t MediaPlayerService::AudioOutput::start()
{
    ALOGV("start");
 Mutex::Autolock lock(mLock);
 if (mCallbackData != NULL) {
        mCallbackData->endTrackSwitch();
 }
 if (mTrack != 0) {
        mTrack->setVolume(mLeftVolume, mRightVolume);
        mTrack->setAuxEffectSendLevel(mSendLevel);
 return mTrack->start();
 }
 return NO_INIT;
}

Project: Android

status_t MediaPlayerService::Client::stop()
{
    ALOGV("[%d] stop", mConnId);
    sp<MediaPlayerBase> p = getPlayer();
 if (p == 0) return UNKNOWN_ERROR;
 return p->stop();
}

Project: Android

void MediaPlayerService::AudioOutput::switchToNextOutput() {
    ALOGV("switchToNextOutput");

 const unsigned kMaxSwitchTries = 100;
 Mutex::Autolock lock(mLock);
 for (unsigned tries = 0;;) {
 if (mTrack == 0) {
 return;
 }
 if (mNextOutput != NULL && mNextOutput != this) {
 if (mCallbackData != NULL) {
#if 1
 CallbackData *callbackData = mCallbackData;
                mLock.unlock();
                callbackData->lock();
                mLock.lock();
 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
                    LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
 "switchToNextOutput() cannot obtain correct lock sequence");
                    callbackData->unlock();
 continue;
 }
                callbackData->mSwitching = true; // begin track switch
#else
 if (!mCallbackData->tryBeginTrackSwitch()) {
                    LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
 "switchToNextOutput() cannot obtain callback lock");
                    mLock.unlock();
                    usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
                    mLock.lock();
 continue;
 }
#endif
 }

 Mutex::Autolock nextLock(mNextOutput->mLock);

 if (mNextOutput->mTrack == NULL) {
                ALOGD("Recycling track for gapless playback");
 delete mNextOutput->mCallbackData;
                mNextOutput->mCallbackData = mCallbackData;
                mNextOutput->mRecycledTrack = mTrack;
                mNextOutput->mSampleRateHz = mSampleRateHz;
                mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
                mNextOutput->mFlags = mFlags;
                mNextOutput->mFrameSize = mFrameSize;
                close_l();
                mCallbackData = NULL; // destruction handled by mNextOutput
 } else {
                ALOGW("Ignoring gapless playback because next player has already started");
 if (mCallbackData != NULL) {
                    mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
 }
                close_l();
 }
 }
 break;
 }
}

Project: Android

void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
{
    attributes->usage = (audio_usage_t) parcel.readInt32();
    attributes->content_type = (audio_content_type_t) parcel.readInt32();
    attributes->source = (audio_source_t) parcel.readInt32();
    attributes->flags = (audio_flags_mask_t) parcel.readInt32();
 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
 if (hasFlattenedTag) {
 String16 tags = parcel.readString16();
 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
 if (realTagSize <= 0) {
            strcpy(attributes->tags, "");
 } else {
 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
                    AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
            utf16_to_utf8(tags.string(), tagSize, attributes->tags,
 sizeof(attributes->tags) / sizeof(attributes->tags[0]));
 }
 } else {
        ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
        strcpy(attributes->tags, "");
 }
}

Project: Android

bool unmarshallFilter(const Parcel& p,
 Metadata::Filter *filter,
 status_t *status)
{
 int32_t val;
 if (p.readInt32(&val) != OK)
 {
        ALOGE("Failed to read filter's length");
 *status = NOT_ENOUGH_DATA;
 return false;
 }

 if( val > kMaxFilterSize || val < 0)
 {
        ALOGE("Invalid filter len %d", val);
 *status = BAD_VALUE;
 return false;
 }

 const size_t num = val;

    filter->clear();
    filter->setCapacity(num);

 size_t size = num * sizeof(Metadata::Type);


 if (p.dataAvail() < size)
 {
        ALOGE("Filter too short expected %zu but got %zu", size, p.dataAvail());
 *status = NOT_ENOUGH_DATA;
 return false;
 }

 const Metadata::Type *data =
 static_cast<const Metadata::Type*>(p.readInplace(size));

 if (NULL == data)
 {
        ALOGE("Filter had no data");
 *status = BAD_VALUE;
 return false;
 }

 for (size_t i = 0; i < num; ++i)
 {
        filter->add(*data);
 ++data;
 }
 *status = OK;
 return true;
}

Project: Android

ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
{
 Mutex::Autolock lock(mLock);
    LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");

 if (mTrack != 0) {
 return mTrack->write(buffer, size, blocking);
 }
 return NO_INIT;
}

Project: Android

MediaPlayerService::AudioOutput::~AudioOutput()
{
    close();
    free(mAttributes);
 delete mCallbackData;
}

Project: Android

CallbackThread::~CallbackThread() {
 if (mBuffer) {
        free(mBuffer);
        mBuffer = NULL;
 }
}

Project: Android

MediaPlayerService::Client::~Client()
{
    ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
    mAudioOutput.clear();
    wp<Client> client(this);
    disconnect();
    mService->removeClient(client);
 if (mAudioAttributes != NULL) {
        free(mAudioAttributes);
 }
}

Project: Android

MediaPlayerService::~MediaPlayerService()
{
    ALOGV("MediaPlayerService destroyed");
}

Project: Android

MediaPlayerService::Client::ServiceDeathNotifier::~ServiceDeathNotifier() {
    mService->unlinkToDeath(this);
}