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 #ifndef ANDROID_MEDIAPLAYERSERVICE_H
     19 #define ANDROID_MEDIAPLAYERSERVICE_H
     20 
     21 #include <arpa/inet.h>
     22 
     23 #include <utils/threads.h>
     24 #include <utils/Errors.h>
     25 #include <utils/KeyedVector.h>
     26 #include <utils/String8.h>
     27 #include <utils/Vector.h>
     28 
     29 #include <media/MediaPlayerInterface.h>
     30 #include <media/Metadata.h>
     31 #include <media/stagefright/foundation/ABase.h>
     32 
     33 #include <system/audio.h>
     34 
     35 namespace android {
     36 
     37 class AudioTrack;
     38 class IMediaRecorder;
     39 class IMediaMetadataRetriever;
     40 class IOMX;
     41 class IRemoteDisplay;
     42 class IRemoteDisplayClient;
     43 class MediaRecorderClient;
     44 
     45 #define CALLBACK_ANTAGONIZER 0
     46 #if CALLBACK_ANTAGONIZER
     47 class Antagonizer {
     48 public:
     49     Antagonizer(notify_callback_f cb, void* client);
     50     void start() { mActive = true; }
     51     void stop() { mActive = false; }
     52     void kill();
     53 private:
     54     static const int interval;
     55     Antagonizer();
     56     static int callbackThread(void* cookie);
     57     Mutex               mLock;
     58     Condition           mCondition;
     59     bool                mExit;
     60     bool                mActive;
     61     void*               mClient;
     62     notify_callback_f   mCb;
     63 };
     64 #endif
     65 
     66 class MediaPlayerService : public BnMediaPlayerService
     67 {
     68     class Client;
     69 
     70     class AudioOutput : public MediaPlayerBase::AudioSink
     71     {
     72         class CallbackData;
     73 
     74      public:
     75                                 AudioOutput(int sessionId, int uid);
     76         virtual                 ~AudioOutput();
     77 
     78         virtual bool            ready() const { return mTrack != 0; }
     79         virtual bool            realtime() const { return true; }
     80         virtual ssize_t         bufferSize() const;
     81         virtual ssize_t         frameCount() const;
     82         virtual ssize_t         channelCount() const;
     83         virtual ssize_t         frameSize() const;
     84         virtual uint32_t        latency() const;
     85         virtual float           msecsPerFrame() const;
     86         virtual status_t        getPosition(uint32_t *position) const;
     87         virtual status_t        getFramesWritten(uint32_t *frameswritten) const;
     88         virtual int             getSessionId() const;
     89 
     90         virtual status_t        open(
     91                 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
     92                 audio_format_t format, int bufferCount,
     93                 AudioCallback cb, void *cookie,
     94                 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
     95                 const audio_offload_info_t *offloadInfo = NULL);
     96 
     97         virtual status_t        start();
     98         virtual ssize_t         write(const void* buffer, size_t size);
     99         virtual void            stop();
    100         virtual void            flush();
    101         virtual void            pause();
    102         virtual void            close();
    103                 void            setAudioStreamType(audio_stream_type_t streamType) {
    104                                                                         mStreamType = streamType; }
    105         virtual audio_stream_type_t getAudioStreamType() const { return mStreamType; }
    106 
    107                 void            setVolume(float left, float right);
    108         virtual status_t        setPlaybackRatePermille(int32_t ratePermille);
    109                 status_t        setAuxEffectSendLevel(float level);
    110                 status_t        attachAuxEffect(int effectId);
    111         virtual status_t        dump(int fd, const Vector<String16>& args) const;
    112 
    113         static bool             isOnEmulator();
    114         static int              getMinBufferCount();
    115                 void            setNextOutput(const sp<AudioOutput>& nextOutput);
    116                 void            switchToNextOutput();
    117         virtual bool            needsTrailingPadding() { return mNextOutput == NULL; }
    118         virtual status_t        setParameters(const String8& keyValuePairs);
    119         virtual String8         getParameters(const String8& keys);
    120 
    121     private:
    122         static void             setMinBufferCount();
    123         static void             CallbackWrapper(
    124                 int event, void *me, void *info);
    125                void             deleteRecycledTrack();
    126 
    127         sp<AudioTrack>          mTrack;
    128         sp<AudioTrack>          mRecycledTrack;
    129         sp<AudioOutput>         mNextOutput;
    130         AudioCallback           mCallback;
    131         void *                  mCallbackCookie;
    132         CallbackData *          mCallbackData;
    133         uint64_t                mBytesWritten;
    134         audio_stream_type_t     mStreamType;
    135         float                   mLeftVolume;
    136         float                   mRightVolume;
    137         int32_t                 mPlaybackRatePermille;
    138         uint32_t                mSampleRateHz; // sample rate of the content, as set in open()
    139         float                   mMsecsPerFrame;
    140         int                     mSessionId;
    141         int                     mUid;
    142         float                   mSendLevel;
    143         int                     mAuxEffectId;
    144         static bool             mIsOnEmulator;
    145         static int              mMinBufferCount;  // 12 for emulator; otherwise 4
    146         audio_output_flags_t    mFlags;
    147 
    148         // CallbackData is what is passed to the AudioTrack as the "user" data.
    149         // We need to be able to target this to a different Output on the fly,
    150         // so we can't use the Output itself for this.
    151         class CallbackData {
    152         public:
    153             CallbackData(AudioOutput *cookie) {
    154                 mData = cookie;
    155                 mSwitching = false;
    156             }
    157             AudioOutput *   getOutput() { return mData;}
    158             void            setOutput(AudioOutput* newcookie) { mData = newcookie; }
    159             // lock/unlock are used by the callback before accessing the payload of this object
    160             void            lock() { mLock.lock(); }
    161             void            unlock() { mLock.unlock(); }
    162             // beginTrackSwitch/endTrackSwitch are used when this object is being handed over
    163             // to the next sink.
    164             void            beginTrackSwitch() { mLock.lock(); mSwitching = true; }
    165             void            endTrackSwitch() {
    166                 if (mSwitching) {
    167                     mLock.unlock();
    168                 }
    169                 mSwitching = false;
    170             }
    171         private:
    172             AudioOutput *   mData;
    173             mutable Mutex   mLock;
    174             bool            mSwitching;
    175             DISALLOW_EVIL_CONSTRUCTORS(CallbackData);
    176         };
    177 
    178     }; // AudioOutput
    179 
    180 
    181     class AudioCache : public MediaPlayerBase::AudioSink
    182     {
    183     public:
    184                                 AudioCache(const sp<IMemoryHeap>& heap);
    185         virtual                 ~AudioCache() {}
    186 
    187         virtual bool            ready() const { return (mChannelCount > 0) && (mHeap->getHeapID() > 0); }
    188         virtual bool            realtime() const { return false; }
    189         virtual ssize_t         bufferSize() const { return frameSize() * mFrameCount; }
    190         virtual ssize_t         frameCount() const { return mFrameCount; }
    191         virtual ssize_t         channelCount() const { return (ssize_t)mChannelCount; }
    192         virtual ssize_t         frameSize() const { return ssize_t(mChannelCount * ((mFormat == AUDIO_FORMAT_PCM_16_BIT)?sizeof(int16_t):sizeof(u_int8_t))); }
    193         virtual uint32_t        latency() const;
    194         virtual float           msecsPerFrame() const;
    195         virtual status_t        getPosition(uint32_t *position) const;
    196         virtual status_t        getFramesWritten(uint32_t *frameswritten) const;
    197         virtual int             getSessionId() const;
    198 
    199         virtual status_t        open(
    200                 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
    201                 audio_format_t format, int bufferCount = 1,
    202                 AudioCallback cb = NULL, void *cookie = NULL,
    203                 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
    204                 const audio_offload_info_t *offloadInfo = NULL);
    205 
    206         virtual status_t        start();
    207         virtual ssize_t         write(const void* buffer, size_t size);
    208         virtual void            stop();
    209         virtual void            flush() {}
    210         virtual void            pause() {}
    211         virtual void            close() {}
    212                 void            setAudioStreamType(audio_stream_type_t streamType) {}
    213                 // stream type is not used for AudioCache
    214         virtual audio_stream_type_t getAudioStreamType() const { return AUDIO_STREAM_DEFAULT; }
    215 
    216                 void            setVolume(float left, float right) {}
    217         virtual status_t        setPlaybackRatePermille(int32_t ratePermille) { return INVALID_OPERATION; }
    218                 uint32_t        sampleRate() const { return mSampleRate; }
    219                 audio_format_t  format() const { return mFormat; }
    220                 size_t          size() const { return mSize; }
    221                 status_t        wait();
    222 
    223                 sp<IMemoryHeap> getHeap() const { return mHeap; }
    224 
    225         static  void            notify(void* cookie, int msg,
    226                                        int ext1, int ext2, const Parcel *obj);
    227         virtual status_t        dump(int fd, const Vector<String16>& args) const;
    228 
    229     private:
    230                                 AudioCache();
    231 
    232         Mutex               mLock;
    233         Condition           mSignal;
    234         sp<IMemoryHeap>     mHeap;
    235         float               mMsecsPerFrame;
    236         uint16_t            mChannelCount;
    237         audio_format_t      mFormat;
    238         ssize_t             mFrameCount;
    239         uint32_t            mSampleRate;
    240         uint32_t            mSize;
    241         int                 mError;
    242         bool                mCommandComplete;
    243 
    244         sp<Thread>          mCallbackThread;
    245     }; // AudioCache
    246 
    247 public:
    248     static  void                instantiate();
    249 
    250     // IMediaPlayerService interface
    251     virtual sp<IMediaRecorder>  createMediaRecorder();
    252     void    removeMediaRecorderClient(wp<MediaRecorderClient> client);
    253     virtual sp<IMediaMetadataRetriever> createMetadataRetriever();
    254 
    255     virtual sp<IMediaPlayer>    create(const sp<IMediaPlayerClient>& client, int audioSessionId);
    256 
    257     virtual status_t            decode(const char* url, uint32_t *pSampleRate, int* pNumChannels,
    258                                        audio_format_t* pFormat,
    259                                        const sp<IMemoryHeap>& heap, size_t *pSize);
    260     virtual status_t            decode(int fd, int64_t offset, int64_t length,
    261                                        uint32_t *pSampleRate, int* pNumChannels,
    262                                        audio_format_t* pFormat,
    263                                        const sp<IMemoryHeap>& heap, size_t *pSize);
    264     virtual sp<IOMX>            getOMX();
    265     virtual sp<ICrypto>         makeCrypto();
    266     virtual sp<IDrm>            makeDrm();
    267     virtual sp<IHDCP>           makeHDCP(bool createEncryptionModule);
    268 
    269     virtual sp<IRemoteDisplay> listenForRemoteDisplay(const sp<IRemoteDisplayClient>& client,
    270             const String8& iface);
    271     virtual status_t            dump(int fd, const Vector<String16>& args);
    272 
    273     virtual status_t        updateProxyConfig(
    274             const char *host, int32_t port, const char *exclusionList);
    275 
    276             void                removeClient(wp<Client> client);
    277 
    278     // For battery usage tracking purpose
    279     struct BatteryUsageInfo {
    280         // how many streams are being played by one UID
    281         int     refCount;
    282         // a temp variable to store the duration(ms) of audio codecs
    283         // when we start a audio codec, we minus the system time from audioLastTime
    284         // when we pause it, we add the system time back to the audioLastTime
    285         // so after the pause, audioLastTime = pause time - start time
    286         // if multiple audio streams are played (or recorded), then audioLastTime
    287         // = the total playing time of all the streams
    288         int32_t audioLastTime;
    289         // when all the audio streams are being paused, we assign audioLastTime to
    290         // this variable, so this value could be provided to the battery app
    291         // in the next pullBatteryData call
    292         int32_t audioTotalTime;
    293 
    294         int32_t videoLastTime;
    295         int32_t videoTotalTime;
    296     };
    297     KeyedVector<int, BatteryUsageInfo>    mBatteryData;
    298 
    299     enum {
    300         SPEAKER,
    301         OTHER_AUDIO_DEVICE,
    302         SPEAKER_AND_OTHER,
    303         NUM_AUDIO_DEVICES
    304     };
    305 
    306     struct BatteryAudioFlingerUsageInfo {
    307         int refCount; // how many audio streams are being played
    308         int deviceOn[NUM_AUDIO_DEVICES]; // whether the device is currently used
    309         int32_t lastTime[NUM_AUDIO_DEVICES]; // in ms
    310         // totalTime[]: total time of audio output devices usage
    311         int32_t totalTime[NUM_AUDIO_DEVICES]; // in ms
    312     };
    313 
    314     // This varialble is used to record the usage of audio output device
    315     // for battery app
    316     BatteryAudioFlingerUsageInfo mBatteryAudio;
    317 
    318     // Collect info of the codec usage from media player and media recorder
    319     virtual void                addBatteryData(uint32_t params);
    320     // API for the Battery app to pull the data of codecs usage
    321     virtual status_t            pullBatteryData(Parcel* reply);
    322 private:
    323 
    324     class Client : public BnMediaPlayer {
    325         // IMediaPlayer interface
    326         virtual void            disconnect();
    327         virtual status_t        setVideoSurfaceTexture(
    328                                         const sp<IGraphicBufferProducer>& bufferProducer);
    329         virtual status_t        prepareAsync();
    330         virtual status_t        start();
    331         virtual status_t        stop();
    332         virtual status_t        pause();
    333         virtual status_t        isPlaying(bool* state);
    334         virtual status_t        seekTo(int msec);
    335         virtual status_t        getCurrentPosition(int* msec);
    336         virtual status_t        getDuration(int* msec);
    337         virtual status_t        reset();
    338         virtual status_t        setAudioStreamType(audio_stream_type_t type);
    339         virtual status_t        setLooping(int loop);
    340         virtual status_t        setVolume(float leftVolume, float rightVolume);
    341         virtual status_t        invoke(const Parcel& request, Parcel *reply);
    342         virtual status_t        setMetadataFilter(const Parcel& filter);
    343         virtual status_t        getMetadata(bool update_only,
    344                                             bool apply_filter,
    345                                             Parcel *reply);
    346         virtual status_t        setAuxEffectSendLevel(float level);
    347         virtual status_t        attachAuxEffect(int effectId);
    348         virtual status_t        setParameter(int key, const Parcel &request);
    349         virtual status_t        getParameter(int key, Parcel *reply);
    350         virtual status_t        setRetransmitEndpoint(const struct sockaddr_in* endpoint);
    351         virtual status_t        getRetransmitEndpoint(struct sockaddr_in* endpoint);
    352         virtual status_t        setNextPlayer(const sp<IMediaPlayer>& player);
    353 
    354         sp<MediaPlayerBase>     createPlayer(player_type playerType);
    355 
    356         virtual status_t        setDataSource(
    357                         const char *url,
    358                         const KeyedVector<String8, String8> *headers);
    359 
    360         virtual status_t        setDataSource(int fd, int64_t offset, int64_t length);
    361 
    362         virtual status_t        setDataSource(const sp<IStreamSource> &source);
    363 
    364         sp<MediaPlayerBase>     setDataSource_pre(player_type playerType);
    365         void                    setDataSource_post(const sp<MediaPlayerBase>& p,
    366                                                    status_t status);
    367 
    368         static  void            notify(void* cookie, int msg,
    369                                        int ext1, int ext2, const Parcel *obj);
    370 
    371                 pid_t           pid() const { return mPid; }
    372         virtual status_t        dump(int fd, const Vector<String16>& args) const;
    373 
    374                 int             getAudioSessionId() { return mAudioSessionId; }
    375 
    376     private:
    377         friend class MediaPlayerService;
    378                                 Client( const sp<MediaPlayerService>& service,
    379                                         pid_t pid,
    380                                         int32_t connId,
    381                                         const sp<IMediaPlayerClient>& client,
    382                                         int audioSessionId,
    383                                         uid_t uid);
    384                                 Client();
    385         virtual                 ~Client();
    386 
    387                 void            deletePlayer();
    388 
    389         sp<MediaPlayerBase>     getPlayer() const { Mutex::Autolock lock(mLock); return mPlayer; }
    390 
    391 
    392 
    393         // @param type Of the metadata to be tested.
    394         // @return true if the metadata should be dropped according to
    395         //              the filters.
    396         bool shouldDropMetadata(media::Metadata::Type type) const;
    397 
    398         // Add a new element to the set of metadata updated. Noop if
    399         // the element exists already.
    400         // @param type Of the metadata to be recorded.
    401         void addNewMetadataUpdate(media::Metadata::Type type);
    402 
    403         // Disconnect from the currently connected ANativeWindow.
    404         void disconnectNativeWindow();
    405 
    406         mutable     Mutex                       mLock;
    407                     sp<MediaPlayerBase>         mPlayer;
    408                     sp<MediaPlayerService>      mService;
    409                     sp<IMediaPlayerClient>      mClient;
    410                     sp<AudioOutput>             mAudioOutput;
    411                     pid_t                       mPid;
    412                     status_t                    mStatus;
    413                     bool                        mLoop;
    414                     int32_t                     mConnId;
    415                     int                         mAudioSessionId;
    416                     uid_t                       mUID;
    417                     sp<ANativeWindow>           mConnectedWindow;
    418                     sp<IBinder>                 mConnectedWindowBinder;
    419                     struct sockaddr_in          mRetransmitEndpoint;
    420                     bool                        mRetransmitEndpointValid;
    421                     sp<Client>                  mNextClient;
    422 
    423         // Metadata filters.
    424         media::Metadata::Filter mMetadataAllow;  // protected by mLock
    425         media::Metadata::Filter mMetadataDrop;  // protected by mLock
    426 
    427         // Metadata updated. For each MEDIA_INFO_METADATA_UPDATE
    428         // notification we try to update mMetadataUpdated which is a
    429         // set: no duplicate.
    430         // getMetadata clears this set.
    431         media::Metadata::Filter mMetadataUpdated;  // protected by mLock
    432 
    433 #if CALLBACK_ANTAGONIZER
    434                     Antagonizer*                mAntagonizer;
    435 #endif
    436     }; // Client
    437 
    438 // ----------------------------------------------------------------------------
    439 
    440                             MediaPlayerService();
    441     virtual                 ~MediaPlayerService();
    442 
    443     mutable     Mutex                       mLock;
    444                 SortedVector< wp<Client> >  mClients;
    445                 SortedVector< wp<MediaRecorderClient> > mMediaRecorderClients;
    446                 int32_t                     mNextConnId;
    447                 sp<IOMX>                    mOMX;
    448                 sp<ICrypto>                 mCrypto;
    449 };
    450 
    451 // ----------------------------------------------------------------------------
    452 
    453 }; // namespace android
    454 
    455 #endif // ANDROID_MEDIAPLAYERSERVICE_H
    456