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