MediaPlayerService.cpp revision 4612b1f4df00f1985d28131fbf52afc2146ded54
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        return UNKNOWN_ERROR;
759    }
760    if (offset + length > sb.st_size) {
761        length = sb.st_size - offset;
762        ALOGV("calculated length = %lld", length);
763    }
764
765    player_type playerType = MediaPlayerFactory::getPlayerType(this,
766                                                               fd,
767                                                               offset,
768                                                               length);
769    sp<MediaPlayerBase> p = setDataSource_pre(playerType);
770    if (p == NULL) {
771        return NO_INIT;
772    }
773
774    // now set data source
775    setDataSource_post(p, p->setDataSource(fd, offset, length));
776    return mStatus;
777}
778
779status_t MediaPlayerService::Client::setDataSource(
780        const sp<IStreamSource> &source) {
781    // create the right type of player
782    player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
783    sp<MediaPlayerBase> p = setDataSource_pre(playerType);
784    if (p == NULL) {
785        return NO_INIT;
786    }
787
788    // now set data source
789    setDataSource_post(p, p->setDataSource(source));
790    return mStatus;
791}
792
793status_t MediaPlayerService::Client::setDataSource(
794        const sp<IDataSource> &source) {
795    sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
796    player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
797    sp<MediaPlayerBase> p = setDataSource_pre(playerType);
798    if (p == NULL) {
799        return NO_INIT;
800    }
801    // now set data source
802    setDataSource_post(p, p->setDataSource(dataSource));
803    return mStatus;
804}
805
806void MediaPlayerService::Client::disconnectNativeWindow() {
807    if (mConnectedWindow != NULL) {
808        status_t err = native_window_api_disconnect(mConnectedWindow.get(),
809                NATIVE_WINDOW_API_MEDIA);
810
811        if (err != OK) {
812            ALOGW("native_window_api_disconnect returned an error: %s (%d)",
813                    strerror(-err), err);
814        }
815    }
816    mConnectedWindow.clear();
817}
818
819status_t MediaPlayerService::Client::setVideoSurfaceTexture(
820        const sp<IGraphicBufferProducer>& bufferProducer)
821{
822    ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
823    sp<MediaPlayerBase> p = getPlayer();
824    if (p == 0) return UNKNOWN_ERROR;
825
826    sp<IBinder> binder(IInterface::asBinder(bufferProducer));
827    if (mConnectedWindowBinder == binder) {
828        return OK;
829    }
830
831    sp<ANativeWindow> anw;
832    if (bufferProducer != NULL) {
833        anw = new Surface(bufferProducer, true /* controlledByApp */);
834        status_t err = native_window_api_connect(anw.get(),
835                NATIVE_WINDOW_API_MEDIA);
836
837        if (err != OK) {
838            ALOGE("setVideoSurfaceTexture failed: %d", err);
839            // Note that we must do the reset before disconnecting from the ANW.
840            // Otherwise queue/dequeue calls could be made on the disconnected
841            // ANW, which may result in errors.
842            reset();
843
844            disconnectNativeWindow();
845
846            return err;
847        }
848    }
849
850    // Note that we must set the player's new GraphicBufferProducer before
851    // disconnecting the old one.  Otherwise queue/dequeue calls could be made
852    // on the disconnected ANW, which may result in errors.
853    status_t err = p->setVideoSurfaceTexture(bufferProducer);
854
855    disconnectNativeWindow();
856
857    mConnectedWindow = anw;
858
859    if (err == OK) {
860        mConnectedWindowBinder = binder;
861    } else {
862        disconnectNativeWindow();
863    }
864
865    return err;
866}
867
868status_t MediaPlayerService::Client::invoke(const Parcel& request,
869                                            Parcel *reply)
870{
871    sp<MediaPlayerBase> p = getPlayer();
872    if (p == NULL) return UNKNOWN_ERROR;
873    return p->invoke(request, reply);
874}
875
876// This call doesn't need to access the native player.
877status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
878{
879    status_t status;
880    media::Metadata::Filter allow, drop;
881
882    if (unmarshallFilter(filter, &allow, &status) &&
883        unmarshallFilter(filter, &drop, &status)) {
884        Mutex::Autolock lock(mLock);
885
886        mMetadataAllow = allow;
887        mMetadataDrop = drop;
888    }
889    return status;
890}
891
892status_t MediaPlayerService::Client::getMetadata(
893        bool update_only, bool /*apply_filter*/, Parcel *reply)
894{
895    sp<MediaPlayerBase> player = getPlayer();
896    if (player == 0) return UNKNOWN_ERROR;
897
898    status_t status;
899    // Placeholder for the return code, updated by the caller.
900    reply->writeInt32(-1);
901
902    media::Metadata::Filter ids;
903
904    // We don't block notifications while we fetch the data. We clear
905    // mMetadataUpdated first so we don't lose notifications happening
906    // during the rest of this call.
907    {
908        Mutex::Autolock lock(mLock);
909        if (update_only) {
910            ids = mMetadataUpdated;
911        }
912        mMetadataUpdated.clear();
913    }
914
915    media::Metadata metadata(reply);
916
917    metadata.appendHeader();
918    status = player->getMetadata(ids, reply);
919
920    if (status != OK) {
921        metadata.resetParcel();
922        ALOGE("getMetadata failed %d", status);
923        return status;
924    }
925
926    // FIXME: Implement filtering on the result. Not critical since
927    // filtering takes place on the update notifications already. This
928    // would be when all the metadata are fetch and a filter is set.
929
930    // Everything is fine, update the metadata length.
931    metadata.updateLength();
932    return OK;
933}
934
935status_t MediaPlayerService::Client::prepareAsync()
936{
937    ALOGV("[%d] prepareAsync", mConnId);
938    sp<MediaPlayerBase> p = getPlayer();
939    if (p == 0) return UNKNOWN_ERROR;
940    status_t ret = p->prepareAsync();
941#if CALLBACK_ANTAGONIZER
942    ALOGD("start Antagonizer");
943    if (ret == NO_ERROR) mAntagonizer->start();
944#endif
945    return ret;
946}
947
948status_t MediaPlayerService::Client::start()
949{
950    ALOGV("[%d] start", mConnId);
951    sp<MediaPlayerBase> p = getPlayer();
952    if (p == 0) return UNKNOWN_ERROR;
953    p->setLooping(mLoop);
954    return p->start();
955}
956
957status_t MediaPlayerService::Client::stop()
958{
959    ALOGV("[%d] stop", mConnId);
960    sp<MediaPlayerBase> p = getPlayer();
961    if (p == 0) return UNKNOWN_ERROR;
962    return p->stop();
963}
964
965status_t MediaPlayerService::Client::pause()
966{
967    ALOGV("[%d] pause", mConnId);
968    sp<MediaPlayerBase> p = getPlayer();
969    if (p == 0) return UNKNOWN_ERROR;
970    return p->pause();
971}
972
973status_t MediaPlayerService::Client::isPlaying(bool* state)
974{
975    *state = false;
976    sp<MediaPlayerBase> p = getPlayer();
977    if (p == 0) return UNKNOWN_ERROR;
978    *state = p->isPlaying();
979    ALOGV("[%d] isPlaying: %d", mConnId, *state);
980    return NO_ERROR;
981}
982
983status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
984{
985    ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
986            mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
987    sp<MediaPlayerBase> p = getPlayer();
988    if (p == 0) return UNKNOWN_ERROR;
989    return p->setPlaybackSettings(rate);
990}
991
992status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
993{
994    sp<MediaPlayerBase> p = getPlayer();
995    if (p == 0) return UNKNOWN_ERROR;
996    status_t ret = p->getPlaybackSettings(rate);
997    if (ret == NO_ERROR) {
998        ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
999                mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1000    } else {
1001        ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1002    }
1003    return ret;
1004}
1005
1006status_t MediaPlayerService::Client::setSyncSettings(
1007        const AVSyncSettings& sync, float videoFpsHint)
1008{
1009    ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1010            mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1011    sp<MediaPlayerBase> p = getPlayer();
1012    if (p == 0) return UNKNOWN_ERROR;
1013    return p->setSyncSettings(sync, videoFpsHint);
1014}
1015
1016status_t MediaPlayerService::Client::getSyncSettings(
1017        AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1018{
1019    sp<MediaPlayerBase> p = getPlayer();
1020    if (p == 0) return UNKNOWN_ERROR;
1021    status_t ret = p->getSyncSettings(sync, videoFps);
1022    if (ret == NO_ERROR) {
1023        ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1024                mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1025    } else {
1026        ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1027    }
1028    return ret;
1029}
1030
1031status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1032{
1033    ALOGV("getCurrentPosition");
1034    sp<MediaPlayerBase> p = getPlayer();
1035    if (p == 0) return UNKNOWN_ERROR;
1036    status_t ret = p->getCurrentPosition(msec);
1037    if (ret == NO_ERROR) {
1038        ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
1039    } else {
1040        ALOGE("getCurrentPosition returned %d", ret);
1041    }
1042    return ret;
1043}
1044
1045status_t MediaPlayerService::Client::getDuration(int *msec)
1046{
1047    ALOGV("getDuration");
1048    sp<MediaPlayerBase> p = getPlayer();
1049    if (p == 0) return UNKNOWN_ERROR;
1050    status_t ret = p->getDuration(msec);
1051    if (ret == NO_ERROR) {
1052        ALOGV("[%d] getDuration = %d", mConnId, *msec);
1053    } else {
1054        ALOGE("getDuration returned %d", ret);
1055    }
1056    return ret;
1057}
1058
1059status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1060    ALOGV("setNextPlayer");
1061    Mutex::Autolock l(mLock);
1062    sp<Client> c = static_cast<Client*>(player.get());
1063    mNextClient = c;
1064
1065    if (c != NULL) {
1066        if (mAudioOutput != NULL) {
1067            mAudioOutput->setNextOutput(c->mAudioOutput);
1068        } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1069            ALOGE("no current audio output");
1070        }
1071
1072        if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1073            mPlayer->setNextPlayer(mNextClient->getPlayer());
1074        }
1075    }
1076
1077    return OK;
1078}
1079
1080status_t MediaPlayerService::Client::seekTo(int msec)
1081{
1082    ALOGV("[%d] seekTo(%d)", mConnId, msec);
1083    sp<MediaPlayerBase> p = getPlayer();
1084    if (p == 0) return UNKNOWN_ERROR;
1085    return p->seekTo(msec);
1086}
1087
1088status_t MediaPlayerService::Client::reset()
1089{
1090    ALOGV("[%d] reset", mConnId);
1091    mRetransmitEndpointValid = false;
1092    sp<MediaPlayerBase> p = getPlayer();
1093    if (p == 0) return UNKNOWN_ERROR;
1094    return p->reset();
1095}
1096
1097status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
1098{
1099    ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1100    // TODO: for hardware output, call player instead
1101    Mutex::Autolock l(mLock);
1102    if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1103    return NO_ERROR;
1104}
1105
1106status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1107{
1108    if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1109    mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1110    unmarshallAudioAttributes(parcel, mAudioAttributes);
1111
1112    ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1113            mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1114            mAudioAttributes->tags);
1115
1116    if (mAudioOutput != 0) {
1117        mAudioOutput->setAudioAttributes(mAudioAttributes);
1118    }
1119    return NO_ERROR;
1120}
1121
1122status_t MediaPlayerService::Client::setLooping(int loop)
1123{
1124    ALOGV("[%d] setLooping(%d)", mConnId, loop);
1125    mLoop = loop;
1126    sp<MediaPlayerBase> p = getPlayer();
1127    if (p != 0) return p->setLooping(loop);
1128    return NO_ERROR;
1129}
1130
1131status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1132{
1133    ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1134
1135    // for hardware output, call player instead
1136    sp<MediaPlayerBase> p = getPlayer();
1137    {
1138      Mutex::Autolock l(mLock);
1139      if (p != 0 && p->hardwareOutput()) {
1140          MediaPlayerHWInterface* hwp =
1141                  reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1142          return hwp->setVolume(leftVolume, rightVolume);
1143      } else {
1144          if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1145          return NO_ERROR;
1146      }
1147    }
1148
1149    return NO_ERROR;
1150}
1151
1152status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1153{
1154    ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1155    Mutex::Autolock l(mLock);
1156    if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1157    return NO_ERROR;
1158}
1159
1160status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1161{
1162    ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1163    Mutex::Autolock l(mLock);
1164    if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1165    return NO_ERROR;
1166}
1167
1168status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
1169    ALOGV("[%d] setParameter(%d)", mConnId, key);
1170    switch (key) {
1171    case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1172    {
1173        Mutex::Autolock l(mLock);
1174        return setAudioAttributes_l(request);
1175    }
1176    default:
1177        sp<MediaPlayerBase> p = getPlayer();
1178        if (p == 0) { return UNKNOWN_ERROR; }
1179        return p->setParameter(key, request);
1180    }
1181}
1182
1183status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
1184    ALOGV("[%d] getParameter(%d)", mConnId, key);
1185    sp<MediaPlayerBase> p = getPlayer();
1186    if (p == 0) return UNKNOWN_ERROR;
1187    return p->getParameter(key, reply);
1188}
1189
1190status_t MediaPlayerService::Client::setRetransmitEndpoint(
1191        const struct sockaddr_in* endpoint) {
1192
1193    if (NULL != endpoint) {
1194        uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1195        uint16_t p = ntohs(endpoint->sin_port);
1196        ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1197                (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1198    } else {
1199        ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1200    }
1201
1202    sp<MediaPlayerBase> p = getPlayer();
1203
1204    // Right now, the only valid time to set a retransmit endpoint is before
1205    // player selection has been made (since the presence or absence of a
1206    // retransmit endpoint is going to determine which player is selected during
1207    // setDataSource).
1208    if (p != 0) return INVALID_OPERATION;
1209
1210    if (NULL != endpoint) {
1211        mRetransmitEndpoint = *endpoint;
1212        mRetransmitEndpointValid = true;
1213    } else {
1214        mRetransmitEndpointValid = false;
1215    }
1216
1217    return NO_ERROR;
1218}
1219
1220status_t MediaPlayerService::Client::getRetransmitEndpoint(
1221        struct sockaddr_in* endpoint)
1222{
1223    if (NULL == endpoint)
1224        return BAD_VALUE;
1225
1226    sp<MediaPlayerBase> p = getPlayer();
1227
1228    if (p != NULL)
1229        return p->getRetransmitEndpoint(endpoint);
1230
1231    if (!mRetransmitEndpointValid)
1232        return NO_INIT;
1233
1234    *endpoint = mRetransmitEndpoint;
1235
1236    return NO_ERROR;
1237}
1238
1239void MediaPlayerService::Client::notify(
1240        void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
1241{
1242    Client* client = static_cast<Client*>(cookie);
1243    if (client == NULL) {
1244        return;
1245    }
1246
1247    sp<IMediaPlayerClient> c;
1248    {
1249        Mutex::Autolock l(client->mLock);
1250        c = client->mClient;
1251        if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
1252            if (client->mAudioOutput != NULL)
1253                client->mAudioOutput->switchToNextOutput();
1254            client->mNextClient->start();
1255            client->mNextClient->mClient->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1256        }
1257    }
1258
1259    if (MEDIA_INFO == msg &&
1260        MEDIA_INFO_METADATA_UPDATE == ext1) {
1261        const media::Metadata::Type metadata_type = ext2;
1262
1263        if(client->shouldDropMetadata(metadata_type)) {
1264            return;
1265        }
1266
1267        // Update the list of metadata that have changed. getMetadata
1268        // also access mMetadataUpdated and clears it.
1269        client->addNewMetadataUpdate(metadata_type);
1270    }
1271
1272    if (c != NULL) {
1273        ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1274        c->notify(msg, ext1, ext2, obj);
1275    }
1276}
1277
1278
1279bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
1280{
1281    Mutex::Autolock lock(mLock);
1282
1283    if (findMetadata(mMetadataDrop, code)) {
1284        return true;
1285    }
1286
1287    if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
1288        return false;
1289    } else {
1290        return true;
1291    }
1292}
1293
1294
1295void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
1296    Mutex::Autolock lock(mLock);
1297    if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1298        mMetadataUpdated.add(metadata_type);
1299    }
1300}
1301
1302#if CALLBACK_ANTAGONIZER
1303const int Antagonizer::interval = 10000; // 10 msecs
1304
1305Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1306    mExit(false), mActive(false), mClient(client), mCb(cb)
1307{
1308    createThread(callbackThread, this);
1309}
1310
1311void Antagonizer::kill()
1312{
1313    Mutex::Autolock _l(mLock);
1314    mActive = false;
1315    mExit = true;
1316    mCondition.wait(mLock);
1317}
1318
1319int Antagonizer::callbackThread(void* user)
1320{
1321    ALOGD("Antagonizer started");
1322    Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1323    while (!p->mExit) {
1324        if (p->mActive) {
1325            ALOGV("send event");
1326            p->mCb(p->mClient, 0, 0, 0);
1327        }
1328        usleep(interval);
1329    }
1330    Mutex::Autolock _l(p->mLock);
1331    p->mCondition.signal();
1332    ALOGD("Antagonizer stopped");
1333    return 0;
1334}
1335#endif
1336
1337#undef LOG_TAG
1338#define LOG_TAG "AudioSink"
1339MediaPlayerService::AudioOutput::AudioOutput(int sessionId, int uid, int pid,
1340        const audio_attributes_t* attr)
1341    : mCallback(NULL),
1342      mCallbackCookie(NULL),
1343      mCallbackData(NULL),
1344      mBytesWritten(0),
1345      mSessionId(sessionId),
1346      mUid(uid),
1347      mPid(pid),
1348      mFlags(AUDIO_OUTPUT_FLAG_NONE) {
1349    ALOGV("AudioOutput(%d)", sessionId);
1350    mStreamType = AUDIO_STREAM_MUSIC;
1351    mLeftVolume = 1.0;
1352    mRightVolume = 1.0;
1353    mPlaybackRate = AUDIO_PLAYBACK_RATE_DEFAULT;
1354    mSampleRateHz = 0;
1355    mMsecsPerFrame = 0;
1356    mAuxEffectId = 0;
1357    mSendLevel = 0.0;
1358    setMinBufferCount();
1359    mAttributes = attr;
1360}
1361
1362MediaPlayerService::AudioOutput::~AudioOutput()
1363{
1364    close();
1365    delete mCallbackData;
1366}
1367
1368void MediaPlayerService::AudioOutput::setMinBufferCount()
1369{
1370    char value[PROPERTY_VALUE_MAX];
1371    if (property_get("ro.kernel.qemu", value, 0)) {
1372        mIsOnEmulator = true;
1373        mMinBufferCount = 12;  // to prevent systematic buffer underrun for emulator
1374    }
1375}
1376
1377bool MediaPlayerService::AudioOutput::isOnEmulator()
1378{
1379    setMinBufferCount();
1380    return mIsOnEmulator;
1381}
1382
1383int MediaPlayerService::AudioOutput::getMinBufferCount()
1384{
1385    setMinBufferCount();
1386    return mMinBufferCount;
1387}
1388
1389ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1390{
1391    if (mTrack == 0) return NO_INIT;
1392    return mTrack->frameCount() * frameSize();
1393}
1394
1395ssize_t MediaPlayerService::AudioOutput::frameCount() const
1396{
1397    if (mTrack == 0) return NO_INIT;
1398    return mTrack->frameCount();
1399}
1400
1401ssize_t MediaPlayerService::AudioOutput::channelCount() const
1402{
1403    if (mTrack == 0) return NO_INIT;
1404    return mTrack->channelCount();
1405}
1406
1407ssize_t MediaPlayerService::AudioOutput::frameSize() const
1408{
1409    if (mTrack == 0) return NO_INIT;
1410    return mTrack->frameSize();
1411}
1412
1413uint32_t MediaPlayerService::AudioOutput::latency () const
1414{
1415    if (mTrack == 0) return 0;
1416    return mTrack->latency();
1417}
1418
1419float MediaPlayerService::AudioOutput::msecsPerFrame() const
1420{
1421    return mMsecsPerFrame;
1422}
1423
1424status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
1425{
1426    if (mTrack == 0) return NO_INIT;
1427    return mTrack->getPosition(position);
1428}
1429
1430status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1431{
1432    if (mTrack == 0) return NO_INIT;
1433    return mTrack->getTimestamp(ts);
1434}
1435
1436status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1437{
1438    if (mTrack == 0) return NO_INIT;
1439    *frameswritten = mBytesWritten / frameSize();
1440    return OK;
1441}
1442
1443status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1444{
1445    if (mTrack == 0) return NO_INIT;
1446    return mTrack->setParameters(keyValuePairs);
1447}
1448
1449String8  MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1450{
1451    if (mTrack == 0) return String8::empty();
1452    return mTrack->getParameters(keys);
1453}
1454
1455void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
1456    mAttributes = attributes;
1457}
1458
1459void MediaPlayerService::AudioOutput::deleteRecycledTrack()
1460{
1461    ALOGV("deleteRecycledTrack");
1462
1463    if (mRecycledTrack != 0) {
1464
1465        if (mCallbackData != NULL) {
1466            mCallbackData->setOutput(NULL);
1467            mCallbackData->endTrackSwitch();
1468        }
1469
1470        if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
1471            mRecycledTrack->flush();
1472        }
1473        // An offloaded track isn't flushed because the STREAM_END is reported
1474        // slightly prematurely to allow time for the gapless track switch
1475        // but this means that if we decide not to recycle the track there
1476        // could be a small amount of residual data still playing. We leave
1477        // AudioFlinger to drain the track.
1478
1479        mRecycledTrack.clear();
1480        delete mCallbackData;
1481        mCallbackData = NULL;
1482        close();
1483    }
1484}
1485
1486status_t MediaPlayerService::AudioOutput::open(
1487        uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1488        audio_format_t format, int bufferCount,
1489        AudioCallback cb, void *cookie,
1490        audio_output_flags_t flags,
1491        const audio_offload_info_t *offloadInfo,
1492        bool doNotReconnect)
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                    doNotReconnect);
1610        } else {
1611            t = new AudioTrack(
1612                    mStreamType,
1613                    sampleRate,
1614                    format,
1615                    channelMask,
1616                    frameCount,
1617                    flags,
1618                    NULL, // callback
1619                    NULL, // user data
1620                    0, // notification frames
1621                    mSessionId,
1622                    AudioTrack::TRANSFER_DEFAULT,
1623                    NULL, // offload info
1624                    mUid,
1625                    mPid,
1626                    mAttributes,
1627                    doNotReconnect);
1628        }
1629
1630        if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1631            ALOGE("Unable to create audio track");
1632            delete newcbd;
1633            // t goes out of scope, so reference count drops to zero
1634            return NO_INIT;
1635        } else {
1636            // successful AudioTrack initialization implies a legacy stream type was generated
1637            // from the audio attributes
1638            mStreamType = t->streamType();
1639        }
1640    }
1641
1642    if (reuse) {
1643        CHECK(mRecycledTrack != NULL);
1644
1645        if (!bothOffloaded) {
1646            if (mRecycledTrack->frameCount() != t->frameCount()) {
1647                ALOGV("framecount differs: %u/%u frames",
1648                      mRecycledTrack->frameCount(), t->frameCount());
1649                reuse = false;
1650            }
1651        }
1652
1653        if (reuse) {
1654            ALOGV("chaining to next output and recycling track");
1655            close();
1656            mTrack = mRecycledTrack;
1657            mRecycledTrack.clear();
1658            if (mCallbackData != NULL) {
1659                mCallbackData->setOutput(this);
1660            }
1661            delete newcbd;
1662            return OK;
1663        }
1664    }
1665
1666    // we're not going to reuse the track, unblock and flush it
1667    // this was done earlier if both tracks are offloaded
1668    if (!bothOffloaded) {
1669        deleteRecycledTrack();
1670    }
1671
1672    CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
1673
1674    mCallbackData = newcbd;
1675    ALOGV("setVolume");
1676    t->setVolume(mLeftVolume, mRightVolume);
1677
1678    mSampleRateHz = sampleRate;
1679    mFlags = flags;
1680    mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
1681    uint32_t pos;
1682    if (t->getPosition(&pos) == OK) {
1683        mBytesWritten = uint64_t(pos) * t->frameSize();
1684    }
1685    mTrack = t;
1686
1687    status_t res = NO_ERROR;
1688    if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
1689        res = t->setPlaybackRate(mPlaybackRate);
1690        if (res == NO_ERROR) {
1691            t->setAuxEffectSendLevel(mSendLevel);
1692            res = t->attachAuxEffect(mAuxEffectId);
1693        }
1694    }
1695    ALOGV("open() DONE status %d", res);
1696    return res;
1697}
1698
1699status_t MediaPlayerService::AudioOutput::start()
1700{
1701    ALOGV("start");
1702    if (mCallbackData != NULL) {
1703        mCallbackData->endTrackSwitch();
1704    }
1705    if (mTrack != 0) {
1706        mTrack->setVolume(mLeftVolume, mRightVolume);
1707        mTrack->setAuxEffectSendLevel(mSendLevel);
1708        return mTrack->start();
1709    }
1710    return NO_INIT;
1711}
1712
1713void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
1714    mNextOutput = nextOutput;
1715}
1716
1717
1718void MediaPlayerService::AudioOutput::switchToNextOutput() {
1719    ALOGV("switchToNextOutput");
1720    if (mNextOutput != NULL) {
1721        if (mCallbackData != NULL) {
1722            mCallbackData->beginTrackSwitch();
1723        }
1724        delete mNextOutput->mCallbackData;
1725        mNextOutput->mCallbackData = mCallbackData;
1726        mCallbackData = NULL;
1727        mNextOutput->mRecycledTrack = mTrack;
1728        mTrack.clear();
1729        mNextOutput->mSampleRateHz = mSampleRateHz;
1730        mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
1731        mNextOutput->mBytesWritten = mBytesWritten;
1732        mNextOutput->mFlags = mFlags;
1733    }
1734}
1735
1736ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
1737{
1738    LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1739
1740    //ALOGV("write(%p, %u)", buffer, size);
1741    if (mTrack != 0) {
1742        ssize_t ret = mTrack->write(buffer, size, blocking);
1743        if (ret >= 0) {
1744            mBytesWritten += ret;
1745        }
1746        return ret;
1747    }
1748    return NO_INIT;
1749}
1750
1751void MediaPlayerService::AudioOutput::stop()
1752{
1753    ALOGV("stop");
1754    if (mTrack != 0) mTrack->stop();
1755}
1756
1757void MediaPlayerService::AudioOutput::flush()
1758{
1759    ALOGV("flush");
1760    if (mTrack != 0) mTrack->flush();
1761}
1762
1763void MediaPlayerService::AudioOutput::pause()
1764{
1765    ALOGV("pause");
1766    if (mTrack != 0) mTrack->pause();
1767}
1768
1769void MediaPlayerService::AudioOutput::close()
1770{
1771    ALOGV("close");
1772    mTrack.clear();
1773}
1774
1775void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1776{
1777    ALOGV("setVolume(%f, %f)", left, right);
1778    mLeftVolume = left;
1779    mRightVolume = right;
1780    if (mTrack != 0) {
1781        mTrack->setVolume(left, right);
1782    }
1783}
1784
1785status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
1786{
1787    ALOGV("setPlaybackRate(%f %f %d %d)",
1788                rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
1789    if (mTrack == 0) {
1790        // remember rate so that we can set it when the track is opened
1791        mPlaybackRate = rate;
1792        return OK;
1793    }
1794    status_t res = mTrack->setPlaybackRate(rate);
1795    if (res != NO_ERROR) {
1796        return res;
1797    }
1798    // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
1799    CHECK_GT(rate.mSpeed, 0.f);
1800    mPlaybackRate = rate;
1801    if (mSampleRateHz != 0) {
1802        mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
1803    }
1804    return res;
1805}
1806
1807status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
1808{
1809    ALOGV("setPlaybackRate");
1810    if (mTrack == 0) {
1811        return NO_INIT;
1812    }
1813    *rate = mTrack->getPlaybackRate();
1814    return NO_ERROR;
1815}
1816
1817status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1818{
1819    ALOGV("setAuxEffectSendLevel(%f)", level);
1820    mSendLevel = level;
1821    if (mTrack != 0) {
1822        return mTrack->setAuxEffectSendLevel(level);
1823    }
1824    return NO_ERROR;
1825}
1826
1827status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1828{
1829    ALOGV("attachAuxEffect(%d)", effectId);
1830    mAuxEffectId = effectId;
1831    if (mTrack != 0) {
1832        return mTrack->attachAuxEffect(effectId);
1833    }
1834    return NO_ERROR;
1835}
1836
1837// static
1838void MediaPlayerService::AudioOutput::CallbackWrapper(
1839        int event, void *cookie, void *info) {
1840    //ALOGV("callbackwrapper");
1841    CallbackData *data = (CallbackData*)cookie;
1842    data->lock();
1843    AudioOutput *me = data->getOutput();
1844    AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1845    if (me == NULL) {
1846        // no output set, likely because the track was scheduled to be reused
1847        // by another player, but the format turned out to be incompatible.
1848        data->unlock();
1849        if (buffer != NULL) {
1850            buffer->size = 0;
1851        }
1852        return;
1853    }
1854
1855    switch(event) {
1856    case AudioTrack::EVENT_MORE_DATA: {
1857        size_t actualSize = (*me->mCallback)(
1858                me, buffer->raw, buffer->size, me->mCallbackCookie,
1859                CB_EVENT_FILL_BUFFER);
1860
1861        if ((me->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0 &&
1862            actualSize == 0 && buffer->size > 0 && me->mNextOutput == NULL) {
1863            // We've reached EOS but the audio track is not stopped yet,
1864            // keep playing silence.
1865
1866            memset(buffer->raw, 0, buffer->size);
1867            actualSize = buffer->size;
1868        }
1869
1870        buffer->size = actualSize;
1871        } break;
1872
1873
1874    case AudioTrack::EVENT_STREAM_END:
1875        ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
1876        (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
1877                me->mCallbackCookie, CB_EVENT_STREAM_END);
1878        break;
1879
1880    case AudioTrack::EVENT_NEW_IAUDIOTRACK :
1881        ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
1882        (*me->mCallback)(me,  NULL /* buffer */, 0 /* size */,
1883                me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
1884        break;
1885
1886    case AudioTrack::EVENT_UNDERRUN:
1887        // This occurs when there is no data available, typically occurring
1888        // when there is a failure to supply data to the AudioTrack.  It can also
1889        // occur in non-offloaded mode when the audio device comes out of standby.
1890        //
1891        // If you see this at the start of playback, there probably was a glitch.
1892        ALOGI("callbackwrapper: EVENT_UNDERRUN (discarded)");
1893        break;
1894
1895    default:
1896        ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
1897    }
1898
1899    data->unlock();
1900}
1901
1902int MediaPlayerService::AudioOutput::getSessionId() const
1903{
1904    return mSessionId;
1905}
1906
1907uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
1908{
1909    if (mTrack == 0) return 0;
1910    return mTrack->getSampleRate();
1911}
1912
1913////////////////////////////////////////////////////////////////////////////////
1914
1915struct CallbackThread : public Thread {
1916    CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1917                   MediaPlayerBase::AudioSink::AudioCallback cb,
1918                   void *cookie);
1919
1920protected:
1921    virtual ~CallbackThread();
1922
1923    virtual bool threadLoop();
1924
1925private:
1926    wp<MediaPlayerBase::AudioSink> mSink;
1927    MediaPlayerBase::AudioSink::AudioCallback mCallback;
1928    void *mCookie;
1929    void *mBuffer;
1930    size_t mBufferSize;
1931
1932    CallbackThread(const CallbackThread &);
1933    CallbackThread &operator=(const CallbackThread &);
1934};
1935
1936CallbackThread::CallbackThread(
1937        const wp<MediaPlayerBase::AudioSink> &sink,
1938        MediaPlayerBase::AudioSink::AudioCallback cb,
1939        void *cookie)
1940    : mSink(sink),
1941      mCallback(cb),
1942      mCookie(cookie),
1943      mBuffer(NULL),
1944      mBufferSize(0) {
1945}
1946
1947CallbackThread::~CallbackThread() {
1948    if (mBuffer) {
1949        free(mBuffer);
1950        mBuffer = NULL;
1951    }
1952}
1953
1954bool CallbackThread::threadLoop() {
1955    sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1956    if (sink == NULL) {
1957        return false;
1958    }
1959
1960    if (mBuffer == NULL) {
1961        mBufferSize = sink->bufferSize();
1962        mBuffer = malloc(mBufferSize);
1963    }
1964
1965    size_t actualSize =
1966        (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
1967                MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
1968
1969    if (actualSize > 0) {
1970        sink->write(mBuffer, actualSize);
1971        // Could return false on sink->write() error or short count.
1972        // Not necessarily appropriate but would work for AudioCache behavior.
1973    }
1974
1975    return true;
1976}
1977
1978////////////////////////////////////////////////////////////////////////////////
1979
1980void MediaPlayerService::addBatteryData(uint32_t params)
1981{
1982    Mutex::Autolock lock(mLock);
1983
1984    int32_t time = systemTime() / 1000000L;
1985
1986    // change audio output devices. This notification comes from AudioFlinger
1987    if ((params & kBatteryDataSpeakerOn)
1988            || (params & kBatteryDataOtherAudioDeviceOn)) {
1989
1990        int deviceOn[NUM_AUDIO_DEVICES];
1991        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1992            deviceOn[i] = 0;
1993        }
1994
1995        if ((params & kBatteryDataSpeakerOn)
1996                && (params & kBatteryDataOtherAudioDeviceOn)) {
1997            deviceOn[SPEAKER_AND_OTHER] = 1;
1998        } else if (params & kBatteryDataSpeakerOn) {
1999            deviceOn[SPEAKER] = 1;
2000        } else {
2001            deviceOn[OTHER_AUDIO_DEVICE] = 1;
2002        }
2003
2004        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2005            if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2006
2007                if (mBatteryAudio.refCount > 0) { // if playing audio
2008                    if (!deviceOn[i]) {
2009                        mBatteryAudio.lastTime[i] += time;
2010                        mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2011                        mBatteryAudio.lastTime[i] = 0;
2012                    } else {
2013                        mBatteryAudio.lastTime[i] = 0 - time;
2014                    }
2015                }
2016
2017                mBatteryAudio.deviceOn[i] = deviceOn[i];
2018            }
2019        }
2020        return;
2021    }
2022
2023    // an audio stream is started
2024    if (params & kBatteryDataAudioFlingerStart) {
2025        // record the start time only if currently no other audio
2026        // is being played
2027        if (mBatteryAudio.refCount == 0) {
2028            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2029                if (mBatteryAudio.deviceOn[i]) {
2030                    mBatteryAudio.lastTime[i] -= time;
2031                }
2032            }
2033        }
2034
2035        mBatteryAudio.refCount ++;
2036        return;
2037
2038    } else if (params & kBatteryDataAudioFlingerStop) {
2039        if (mBatteryAudio.refCount <= 0) {
2040            ALOGW("Battery track warning: refCount is <= 0");
2041            return;
2042        }
2043
2044        // record the stop time only if currently this is the only
2045        // audio being played
2046        if (mBatteryAudio.refCount == 1) {
2047            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2048                if (mBatteryAudio.deviceOn[i]) {
2049                    mBatteryAudio.lastTime[i] += time;
2050                    mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2051                    mBatteryAudio.lastTime[i] = 0;
2052                }
2053            }
2054        }
2055
2056        mBatteryAudio.refCount --;
2057        return;
2058    }
2059
2060    int uid = IPCThreadState::self()->getCallingUid();
2061    if (uid == AID_MEDIA) {
2062        return;
2063    }
2064    int index = mBatteryData.indexOfKey(uid);
2065
2066    if (index < 0) { // create a new entry for this UID
2067        BatteryUsageInfo info;
2068        info.audioTotalTime = 0;
2069        info.videoTotalTime = 0;
2070        info.audioLastTime = 0;
2071        info.videoLastTime = 0;
2072        info.refCount = 0;
2073
2074        if (mBatteryData.add(uid, info) == NO_MEMORY) {
2075            ALOGE("Battery track error: no memory for new app");
2076            return;
2077        }
2078    }
2079
2080    BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2081
2082    if (params & kBatteryDataCodecStarted) {
2083        if (params & kBatteryDataTrackAudio) {
2084            info.audioLastTime -= time;
2085            info.refCount ++;
2086        }
2087        if (params & kBatteryDataTrackVideo) {
2088            info.videoLastTime -= time;
2089            info.refCount ++;
2090        }
2091    } else {
2092        if (info.refCount == 0) {
2093            ALOGW("Battery track warning: refCount is already 0");
2094            return;
2095        } else if (info.refCount < 0) {
2096            ALOGE("Battery track error: refCount < 0");
2097            mBatteryData.removeItem(uid);
2098            return;
2099        }
2100
2101        if (params & kBatteryDataTrackAudio) {
2102            info.audioLastTime += time;
2103            info.refCount --;
2104        }
2105        if (params & kBatteryDataTrackVideo) {
2106            info.videoLastTime += time;
2107            info.refCount --;
2108        }
2109
2110        // no stream is being played by this UID
2111        if (info.refCount == 0) {
2112            info.audioTotalTime += info.audioLastTime;
2113            info.audioLastTime = 0;
2114            info.videoTotalTime += info.videoLastTime;
2115            info.videoLastTime = 0;
2116        }
2117    }
2118}
2119
2120status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2121    Mutex::Autolock lock(mLock);
2122
2123    // audio output devices usage
2124    int32_t time = systemTime() / 1000000L; //in ms
2125    int32_t totalTime;
2126
2127    for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2128        totalTime = mBatteryAudio.totalTime[i];
2129
2130        if (mBatteryAudio.deviceOn[i]
2131            && (mBatteryAudio.lastTime[i] != 0)) {
2132                int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2133                totalTime += tmpTime;
2134        }
2135
2136        reply->writeInt32(totalTime);
2137        // reset the total time
2138        mBatteryAudio.totalTime[i] = 0;
2139   }
2140
2141    // codec usage
2142    BatteryUsageInfo info;
2143    int size = mBatteryData.size();
2144
2145    reply->writeInt32(size);
2146    int i = 0;
2147
2148    while (i < size) {
2149        info = mBatteryData.valueAt(i);
2150
2151        reply->writeInt32(mBatteryData.keyAt(i)); //UID
2152        reply->writeInt32(info.audioTotalTime);
2153        reply->writeInt32(info.videoTotalTime);
2154
2155        info.audioTotalTime = 0;
2156        info.videoTotalTime = 0;
2157
2158        // remove the UID entry where no stream is being played
2159        if (info.refCount <= 0) {
2160            mBatteryData.removeItemsAt(i);
2161            size --;
2162            i --;
2163        }
2164        i++;
2165    }
2166    return NO_ERROR;
2167}
2168} // namespace android
2169