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