• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include <string>
23 
24 #include <utils/threads.h>
25 #include <utils/Errors.h>
26 #include <utils/KeyedVector.h>
27 #include <utils/String8.h>
28 #include <utils/Vector.h>
29 
30 #include <media/AidlConversion.h>
31 #include <media/AudioResamplerPublic.h>
32 #include <media/AudioSystem.h>
33 #include <media/AudioTrack.h>
34 #include <media/MediaPlayerInterface.h>
35 #include <media/Metadata.h>
36 #include <media/stagefright/foundation/ABase.h>
37 #include <mediautils/Synchronization.h>
38 #include <android/content/AttributionSourceState.h>
39 
40 #include <system/audio.h>
41 
42 namespace android {
43 
44 using content::AttributionSourceState;
45 
46 struct AVSyncSettings;
47 class DeathNotifier;
48 class IDataSource;
49 class IMediaRecorder;
50 class IMediaMetadataRetriever;
51 class IRemoteDisplay;
52 class IRemoteDisplayClient;
53 class MediaRecorderClient;
54 
55 #define CALLBACK_ANTAGONIZER 0
56 #if CALLBACK_ANTAGONIZER
57 class Antagonizer {
58 public:
59     Antagonizer(const sp<MediaPlayerBase::Listener> &listener);
start()60     void start() { mActive = true; }
stop()61     void stop() { mActive = false; }
62     void kill();
63 private:
64     static const int interval;
65     Antagonizer();
66     static int callbackThread(void* cookie);
67     Mutex                         mLock;
68     Condition                     mCondition;
69     bool                          mExit;
70     bool                          mActive;
71     sp<MediaPlayerBase::Listener> mListener;
72 };
73 #endif
74 
75 class MediaPlayerService : public BnMediaPlayerService
76 {
77     class Client;
78 
79     class AudioOutput : public MediaPlayerBase::AudioSink
80     {
81         class CallbackData;
82 
83      public:
84                                 AudioOutput(
85                                         audio_session_t sessionId,
86                                         const AttributionSourceState& attributionSource,
87                                         const audio_attributes_t * attr,
88                                         const sp<AudioSystem::AudioDeviceCallback>& deviceCallback);
89         virtual                 ~AudioOutput();
90 
ready()91         virtual bool            ready() const { return mTrack != 0; }
92         virtual ssize_t         bufferSize() const;
93         virtual ssize_t         frameCount() const;
94         virtual ssize_t         channelCount() const;
95         virtual ssize_t         frameSize() const;
96         virtual uint32_t        latency() const;
97         virtual float           msecsPerFrame() const;
98         virtual status_t        getPosition(uint32_t *position) const;
99         virtual status_t        getTimestamp(AudioTimestamp &ts) const;
100         virtual int64_t         getPlayedOutDurationUs(int64_t nowUs) const;
101         virtual status_t        getFramesWritten(uint32_t *frameswritten) const;
102         virtual audio_session_t getSessionId() const;
103         virtual uint32_t        getSampleRate() const;
104         virtual int64_t         getBufferDurationInUs() const;
getFlags()105         virtual audio_output_flags_t getFlags() const { return mFlags; }
106 
107         virtual status_t        open(
108                 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
109                 audio_format_t format, int bufferCount,
110                 AudioCallback cb, void *cookie,
111                 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
112                 const audio_offload_info_t *offloadInfo = NULL,
113                 bool doNotReconnect = false,
114                 uint32_t suggestedFrameCount = 0);
115 
116         virtual status_t        start();
117         virtual ssize_t         write(const void* buffer, size_t size, bool blocking = true);
118         virtual void            stop();
119         virtual void            flush();
120         virtual void            pause();
121         virtual void            close();
122                 void            setAudioStreamType(audio_stream_type_t streamType);
getAudioStreamType()123         virtual audio_stream_type_t getAudioStreamType() const { return mStreamType; }
124                 void            setAudioAttributes(const audio_attributes_t * attributes);
125 
126                 void            setVolume(float left, float right);
127         virtual status_t        setPlaybackRate(const AudioPlaybackRate& rate);
128         virtual status_t        getPlaybackRate(AudioPlaybackRate* rate /* nonnull */);
129 
130                 status_t        setAuxEffectSendLevel(float level);
131                 status_t        attachAuxEffect(int effectId);
132         virtual status_t        dump(int fd, const Vector<String16>& args) const;
133 
134         static bool             isOnEmulator();
135         static int              getMinBufferCount();
136                 void            setNextOutput(const sp<AudioOutput>& nextOutput);
137                 void            switchToNextOutput();
needsTrailingPadding()138         virtual bool            needsTrailingPadding() { return mNextOutput == NULL; }
139         virtual status_t        setParameters(const String8& keyValuePairs);
140         virtual String8         getParameters(const String8& keys);
141 
142         virtual media::VolumeShaper::Status applyVolumeShaper(
143                                         const sp<media::VolumeShaper::Configuration>& configuration,
144                                         const sp<media::VolumeShaper::Operation>& operation) override;
145         virtual sp<media::VolumeShaper::State> getVolumeShaperState(int id) override;
146 
147         // AudioRouting
148         virtual status_t        setOutputDevice(audio_port_handle_t deviceId);
149         virtual status_t        getRoutedDeviceId(audio_port_handle_t* deviceId);
150         virtual status_t        enableAudioDeviceCallback(bool enabled);
151 
152     private:
153         static void             setMinBufferCount();
154         static void             CallbackWrapper(
155                 int event, void *me, void *info);
156                void             deleteRecycledTrack_l();
157                void             close_l();
158            status_t             updateTrack();
159 
160         sp<AudioTrack>          mTrack;
161         sp<AudioTrack>          mRecycledTrack;
162         sp<AudioOutput>         mNextOutput;
163         AudioCallback           mCallback;
164         void *                  mCallbackCookie;
165         sp<CallbackData>        mCallbackData;
166         audio_stream_type_t     mStreamType;
167         audio_attributes_t *    mAttributes;
168         float                   mLeftVolume;
169         float                   mRightVolume;
170         AudioPlaybackRate       mPlaybackRate;
171         uint32_t                mSampleRateHz; // sample rate of the content, as set in open()
172         float                   mMsecsPerFrame;
173         size_t                  mFrameSize;
174         audio_session_t         mSessionId;
175         AttributionSourceState  mAttributionSource;
176         float                   mSendLevel;
177         int                     mAuxEffectId;
178         audio_output_flags_t    mFlags;
179         sp<media::VolumeHandler>       mVolumeHandler;
180         audio_port_handle_t     mSelectedDeviceId;
181         audio_port_handle_t     mRoutedDeviceId;
182         bool                    mDeviceCallbackEnabled;
183         wp<AudioSystem::AudioDeviceCallback>        mDeviceCallback;
184         mutable Mutex           mLock;
185 
186         // static variables below not protected by mutex
187         static bool             mIsOnEmulator;
188         static int              mMinBufferCount;  // 12 for emulator; otherwise 4
189 
190         // CallbackData is what is passed to the AudioTrack as the "user" data.
191         // We need to be able to target this to a different Output on the fly,
192         // so we can't use the Output itself for this.
193         class CallbackData : public AudioTrack::IAudioTrackCallback {
194             friend AudioOutput;
195         public:
CallbackData(const wp<AudioOutput> & cookie)196             explicit CallbackData(const wp<AudioOutput>& cookie) {
197                 mData = cookie;
198                 mSwitching = false;
199             }
getOutput()200             sp<AudioOutput> getOutput() const { return mData.load().promote(); }
setOutput(const wp<AudioOutput> & newcookie)201             void            setOutput(const wp<AudioOutput>& newcookie) { mData.store(newcookie); }
202             // lock/unlock are used by the callback before accessing the payload of this object
lock()203             void            lock() const { mLock.lock(); }
unlock()204             void            unlock() const { mLock.unlock(); }
205 
206             // tryBeginTrackSwitch/endTrackSwitch are used when the CallbackData is handed over
207             // to the next sink.
208 
209             // tryBeginTrackSwitch() returns true only if it obtains the lock.
tryBeginTrackSwitch()210             bool            tryBeginTrackSwitch() {
211                 LOG_ALWAYS_FATAL_IF(mSwitching, "tryBeginTrackSwitch() already called");
212                 if (mLock.tryLock() != OK) {
213                     return false;
214                 }
215                 mSwitching = true;
216                 return true;
217             }
endTrackSwitch()218             void            endTrackSwitch() {
219                 if (mSwitching) {
220                     mLock.unlock();
221                 }
222                 mSwitching = false;
223             }
224         protected:
225             size_t onMoreData(const AudioTrack::Buffer& buffer) override;
226             void onUnderrun() override;
227             void onStreamEnd() override;
228             void onNewIAudioTrack() override;
229         private:
230             mediautils::atomic_wp<AudioOutput> mData;
231             mutable Mutex   mLock; // a recursive mutex might make this unnecessary.
232             bool            mSwitching;
233             DISALLOW_EVIL_CONSTRUCTORS(CallbackData);
234         };
235 
236     }; // AudioOutput
237 
238 public:
239     static  void                instantiate();
240 
241     // IMediaPlayerService interface
242     virtual sp<IMediaRecorder> createMediaRecorder(const AttributionSourceState &attributionSource);
243     void    removeMediaRecorderClient(const wp<MediaRecorderClient>& client);
244     virtual sp<IMediaMetadataRetriever> createMetadataRetriever();
245 
246     virtual sp<IMediaPlayer>    create(const sp<IMediaPlayerClient>& client,
247                                        audio_session_t audioSessionId,
248                                        const AttributionSourceState& attributionSource);
249 
250     virtual sp<IMediaCodecList> getCodecList() const;
251 
252     virtual sp<IRemoteDisplay> listenForRemoteDisplay(const String16 &opPackageName,
253             const sp<IRemoteDisplayClient>& client, const String8& iface);
254     virtual status_t            dump(int fd, const Vector<String16>& args);
255 
256             void                removeClient(const wp<Client>& client);
257             bool                hasClient(wp<Client> client);
258 
259     enum {
260         MEDIASERVER_PROCESS_DEATH = 0,
261         MEDIAEXTRACTOR_PROCESS_DEATH = 1,
262         MEDIACODEC_PROCESS_DEATH = 2,
263         AUDIO_PROCESS_DEATH = 3,   // currently no need to track this
264         CAMERA_PROCESS_DEATH = 4
265     };
266 
267     // Collect info of the codec usage from media player and media recorder
268     virtual void                addBatteryData(uint32_t params);
269     // API for the Battery app to pull the data of codecs usage
270     virtual status_t            pullBatteryData(Parcel* reply);
271 private:
272     struct BatteryTracker {
273         BatteryTracker();
274         // Collect info of the codec usage from media player and media recorder
275         void addBatteryData(uint32_t params);
276         // API for the Battery app to pull the data of codecs usage
277         status_t pullBatteryData(Parcel* reply);
278 
279     private:
280         // For battery usage tracking purpose
281         struct BatteryUsageInfo {
282             // how many streams are being played by one UID
283             int     refCount;
284             // a temp variable to store the duration(ms) of audio codecs
285             // when we start a audio codec, we minus the system time from audioLastTime
286             // when we pause it, we add the system time back to the audioLastTime
287             // so after the pause, audioLastTime = pause time - start time
288             // if multiple audio streams are played (or recorded), then audioLastTime
289             // = the total playing time of all the streams
290             int32_t audioLastTime;
291             // when all the audio streams are being paused, we assign audioLastTime to
292             // this variable, so this value could be provided to the battery app
293             // in the next pullBatteryData call
294             int32_t audioTotalTime;
295 
296             int32_t videoLastTime;
297             int32_t videoTotalTime;
298         };
299         KeyedVector<int, BatteryUsageInfo>    mBatteryData;
300 
301         enum {
302             SPEAKER,
303             OTHER_AUDIO_DEVICE,
304             SPEAKER_AND_OTHER,
305             NUM_AUDIO_DEVICES
306         };
307 
308         struct BatteryAudioFlingerUsageInfo {
309             int refCount; // how many audio streams are being played
310             int deviceOn[NUM_AUDIO_DEVICES]; // whether the device is currently used
311             int32_t lastTime[NUM_AUDIO_DEVICES]; // in ms
312             // totalTime[]: total time of audio output devices usage
313             int32_t totalTime[NUM_AUDIO_DEVICES]; // in ms
314         };
315 
316         // This varialble is used to record the usage of audio output device
317         // for battery app
318         BatteryAudioFlingerUsageInfo mBatteryAudio;
319 
320         mutable Mutex mLock;
321     };
322     BatteryTracker mBatteryTracker;
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        setBufferingSettings(const BufferingSettings& buffering) override;
330         virtual status_t        getBufferingSettings(
331                                         BufferingSettings* buffering /* nonnull */) override;
332         virtual status_t        prepareAsync();
333         virtual status_t        start();
334         virtual status_t        stop();
335         virtual status_t        pause();
336         virtual status_t        isPlaying(bool* state);
337         virtual status_t        setPlaybackSettings(const AudioPlaybackRate& rate);
338         virtual status_t        getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */);
339         virtual status_t        setSyncSettings(const AVSyncSettings& rate, float videoFpsHint);
340         virtual status_t        getSyncSettings(AVSyncSettings* rate /* nonnull */,
341                                                 float* videoFps /* nonnull */);
342         virtual status_t        seekTo(
343                 int msec,
344                 MediaPlayerSeekMode mode = MediaPlayerSeekMode::SEEK_PREVIOUS_SYNC);
345         virtual status_t        getCurrentPosition(int* msec);
346         virtual status_t        getDuration(int* msec);
347         virtual status_t        reset();
348         virtual status_t        notifyAt(int64_t mediaTimeUs);
349         virtual status_t        setAudioStreamType(audio_stream_type_t type);
350         virtual status_t        setLooping(int loop);
351         virtual status_t        setVolume(float leftVolume, float rightVolume);
352         virtual status_t        invoke(const Parcel& request, Parcel *reply);
353         virtual status_t        setMetadataFilter(const Parcel& filter);
354         virtual status_t        getMetadata(bool update_only,
355                                             bool apply_filter,
356                                             Parcel *reply);
357         virtual status_t        setAuxEffectSendLevel(float level);
358         virtual status_t        attachAuxEffect(int effectId);
359         virtual status_t        setParameter(int key, const Parcel &request);
360         virtual status_t        getParameter(int key, Parcel *reply);
361         virtual status_t        setRetransmitEndpoint(const struct sockaddr_in* endpoint);
362         virtual status_t        getRetransmitEndpoint(struct sockaddr_in* endpoint);
363         virtual status_t        setNextPlayer(const sp<IMediaPlayer>& player);
364 
365         virtual media::VolumeShaper::Status applyVolumeShaper(
366                                         const sp<media::VolumeShaper::Configuration>& configuration,
367                                         const sp<media::VolumeShaper::Operation>& operation) override;
368         virtual sp<media::VolumeShaper::State> getVolumeShaperState(int id) override;
369 
370         sp<MediaPlayerBase>     createPlayer(player_type playerType);
371 
372         virtual status_t        setDataSource(
373                         const sp<IMediaHTTPService> &httpService,
374                         const char *url,
375                         const KeyedVector<String8, String8> *headers);
376 
377         virtual status_t        setDataSource(int fd, int64_t offset, int64_t length);
378 
379         virtual status_t        setDataSource(const sp<IStreamSource> &source);
380         virtual status_t        setDataSource(const sp<IDataSource> &source);
381         virtual status_t        setDataSource(const String8& rtpParams);
382 
383 
384         sp<MediaPlayerBase>     setDataSource_pre(player_type playerType);
385         status_t                setDataSource_post(const sp<MediaPlayerBase>& p,
386                                                    status_t status);
387 
388                 void            notify(int msg, int ext1, int ext2, const Parcel *obj);
389 
pid()390                 pid_t           pid() const {
391                     return VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(mAttributionSource.pid));
392                 }
393         virtual status_t        dump(int fd, const Vector<String16>& args);
394 
getAudioSessionId()395                 audio_session_t getAudioSessionId() { return mAudioSessionId; }
396         // Modular DRM
397         virtual status_t prepareDrm(const uint8_t uuid[16], const Vector<uint8_t>& drmSessionId);
398         virtual status_t releaseDrm();
399         // AudioRouting
400         virtual status_t setOutputDevice(audio_port_handle_t deviceId);
401         virtual status_t getRoutedDeviceId(audio_port_handle_t* deviceId);
402         virtual status_t enableAudioDeviceCallback(bool enabled);
403 
404     private:
405         class AudioDeviceUpdatedNotifier: public AudioSystem::AudioDeviceCallback
406         {
407         public:
AudioDeviceUpdatedNotifier(const sp<MediaPlayerBase> & listener)408             AudioDeviceUpdatedNotifier(const sp<MediaPlayerBase>& listener) {
409                 mListener = listener;
410             }
~AudioDeviceUpdatedNotifier()411             ~AudioDeviceUpdatedNotifier() {}
412 
413             virtual void onAudioDeviceUpdate(audio_io_handle_t audioIo,
414                                              audio_port_handle_t deviceId);
415 
416         private:
417             wp<MediaPlayerBase> mListener;
418         };
419 
420         friend class MediaPlayerService;
421                                 Client( const sp<MediaPlayerService>& service,
422                                         const AttributionSourceState& attributionSource,
423                                         int32_t connId,
424                                         const sp<IMediaPlayerClient>& client,
425                                         audio_session_t audioSessionId);
426                                 Client();
427         virtual                 ~Client();
428 
429                 void            deletePlayer();
430 
getPlayer()431         sp<MediaPlayerBase>     getPlayer() const { Mutex::Autolock lock(mLock); return mPlayer; }
432 
433 
434 
435         // @param type Of the metadata to be tested.
436         // @return true if the metadata should be dropped according to
437         //              the filters.
438         bool shouldDropMetadata(media::Metadata::Type type) const;
439 
440         // Add a new element to the set of metadata updated. Noop if
441         // the element exists already.
442         // @param type Of the metadata to be recorded.
443         void addNewMetadataUpdate(media::Metadata::Type type);
444 
445         // Disconnect from the currently connected ANativeWindow.
446         void disconnectNativeWindow_l();
447 
448         status_t setAudioAttributes_l(const Parcel &request);
449 
450         class Listener : public MediaPlayerBase::Listener {
451         public:
Listener(const wp<Client> & client)452             Listener(const wp<Client> &client) : mClient(client) {}
~Listener()453             virtual ~Listener() {}
notify(int msg,int ext1,int ext2,const Parcel * obj)454             virtual void notify(int msg, int ext1, int ext2, const Parcel *obj) {
455                 sp<Client> client = mClient.promote();
456                 if (client != NULL) {
457                     client->notify(msg, ext1, ext2, obj);
458                 }
459             }
460         private:
461             wp<Client> mClient;
462         };
463 
464         mutable     Mutex                         mLock;
465                     sp<MediaPlayerBase>           mPlayer;
466                     sp<MediaPlayerService>        mService;
467                     sp<IMediaPlayerClient>        mClient;
468                     sp<AudioOutput>               mAudioOutput;
469                     const AttributionSourceState  mAttributionSource;
470                     status_t                      mStatus;
471                     bool                          mLoop;
472                     int32_t                       mConnId;
473                     audio_session_t               mAudioSessionId;
474                     audio_attributes_t *          mAudioAttributes;
475                     sp<ANativeWindow>             mConnectedWindow;
476                     sp<IBinder>                   mConnectedWindowBinder;
477                     struct sockaddr_in            mRetransmitEndpoint;
478                     bool                          mRetransmitEndpointValid;
479                     sp<Client>                    mNextClient;
480                     sp<MediaPlayerBase::Listener> mListener;
481 
482         // Metadata filters.
483         media::Metadata::Filter mMetadataAllow;  // protected by mLock
484         media::Metadata::Filter mMetadataDrop;  // protected by mLock
485 
486         // Metadata updated. For each MEDIA_INFO_METADATA_UPDATE
487         // notification we try to update mMetadataUpdated which is a
488         // set: no duplicate.
489         // getMetadata clears this set.
490         media::Metadata::Filter mMetadataUpdated;  // protected by mLock
491 
492         std::vector<DeathNotifier> mDeathNotifiers;
493         sp<AudioDeviceUpdatedNotifier> mAudioDeviceUpdatedListener;
494 #if CALLBACK_ANTAGONIZER
495                     Antagonizer*                  mAntagonizer;
496 #endif
497     }; // Client
498 
499 // ----------------------------------------------------------------------------
500 
501                             MediaPlayerService();
502     virtual                 ~MediaPlayerService();
503 
504     mutable     Mutex                       mLock;
505                 SortedVector< wp<Client> >  mClients;
506                 SortedVector< wp<MediaRecorderClient> > mMediaRecorderClients;
507                 int32_t                     mNextConnId;
508 };
509 
510 // ----------------------------------------------------------------------------
511 
512 }; // namespace android
513 
514 #endif // ANDROID_MEDIAPLAYERSERVICE_H
515