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