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