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