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