• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef __ANDROID_GENERICPLAYER_H__
18 #define __ANDROID_GENERICPLAYER_H__
19 
20 #include <media/stagefright/foundation/AHandler.h>
21 #include <media/stagefright/foundation/ALooper.h>
22 #include <media/stagefright/foundation/AMessage.h>
23 
24 //--------------------------------------------------------------------------------------------------
25 /**
26  * Message parameters for AHandler messages, see list in GenericPlayer::kWhatxxx
27  */
28 #define WHATPARAM_SEEK_SEEKTIME_MS                  "seekTimeMs"
29 #define WHATPARAM_LOOP_LOOPING                      "looping"
30 #define WHATPARAM_BUFFERING_UPDATE                  "bufferingUpdate"
31 #define WHATPARAM_BUFFERING_UPDATETHRESHOLD_PERCENT "buffUpdateThreshold"
32 #define WHATPARAM_ATTACHAUXEFFECT                   "attachAuxEffect"
33 #define WHATPARAM_SETAUXEFFECTSENDLEVEL             "setAuxEffectSendLevel"
34 // Parameters for kWhatSetPlayEvents
35 #define WHATPARAM_SETPLAYEVENTS_FLAGS               "setPlayEventsFlags"
36 #define WHATPARAM_SETPLAYEVENTS_MARKER              "setPlayEventsMarker"
37 #define WHATPARAM_SETPLAYEVENTS_UPDATE              "setPlayEventsUpdate"
38 // Parameters for kWhatOneShot (see explanation at definition of kWhatOneShot below)
39 #define WHATPARAM_ONESHOT_GENERATION                "oneShotGeneration"
40 
41 namespace android {
42 
43 // abstract base class
44 class GenericPlayer : public AHandler
45 {
46 public:
47 
48     enum {
49         kEventPrepared                = 'prep',
50         kEventHasVideoSize            = 'vsiz',
51         kEventPrefetchStatusChange    = 'pfsc',
52         kEventPrefetchFillLevelUpdate = 'pflu',
53         kEventEndOfStream             = 'eos',
54         kEventChannelCount            = 'ccnt',
55         kEventPlay                    = 'play', // SL_PLAYEVENT_*
56         kEventErrorAfterPrepare       = 'easp', // error after successful prepare
57     };
58 
59 
60     GenericPlayer(const AudioPlayback_Parameters* params);
61     virtual ~GenericPlayer();
62 
63     void init(const notif_cbf_t cbf, void* notifUser);
64     virtual void preDestroy();
65 
66     void setDataSource(const char *uri);
67     void setDataSource(int fd, int64_t offset, int64_t length, bool closeAfterUse = false);
68 
69     void prepare();
70     virtual void play();
71     void pause();
72     void stop();
73     // timeMsec must be >= 0 or == ANDROID_UNKNOWN_TIME (used by StreamPlayer after discontinuity)
74     void seek(int64_t timeMsec);
75     void loop(bool loop);
76     void setBufferingUpdateThreshold(int16_t thresholdPercent);
77 
78     void getDurationMsec(int* msec); //msec != NULL, ANDROID_UNKNOWN_TIME if unknown
79     virtual void getPositionMsec(int* msec) = 0; //msec != NULL, ANDROID_UNKNOWN_TIME if unknown
80 
setVideoSurfaceTexture(const sp<ISurfaceTexture> & surfaceTexture)81     virtual void setVideoSurfaceTexture(const sp<ISurfaceTexture> &surfaceTexture) {}
82 
83     void setVolume(float leftVol, float rightVol);
84     void attachAuxEffect(int32_t effectId);
85     void setAuxEffectSendLevel(float level);
86 
87     virtual void setPlaybackRate(int32_t ratePermille);
88 
89     // Call after changing any of the IPlay settings related to SL_PLAYEVENT_*
90     void setPlayEvents(int32_t eventFlags, int32_t markerPosition, int32_t positionUpdatePeriod);
91 
92 protected:
93     // mutex used for set vs use of volume, duration, and cache (fill, threshold) settings
94     Mutex mSettingsLock;
95 
96     void resetDataLocator();
97     DataLocator2 mDataLocator;
98     int          mDataLocatorType;
99 
100     // Constants used to identify the messages in this player's AHandler message loop
101     //   in onMessageReceived()
102     enum {
103         kWhatPrepare         = 'prep',  // start preparation
104         kWhatNotif           = 'noti',  // send a notification to client
105         kWhatPlay            = 'play',  // start player
106         kWhatPause           = 'paus',  // pause or stop player
107         kWhatSeek            = 'seek',  // request a seek to specified position
108         kWhatSeekComplete    = 'skcp',  // seek request has completed
109         kWhatLoop            = 'loop',  // set the player's looping status
110         kWhatVolumeUpdate    = 'volu',  // set the channel gains to specified values
111         kWhatBufferingUpdate = 'bufu',
112         kWhatBuffUpdateThres = 'buut',
113         kWhatAttachAuxEffect = 'aaux',
114         kWhatSetAuxEffectSendLevel = 'saux',
115         kWhatSetPlayEvents   = 'spev',  // process new IPlay settings related to SL_PLAYEVENT_*
116         kWhatOneShot         = 'ones',  // deferred (non-0 timeout) handler for SL_PLAYEVENT_*
117         // As used here, "one-shot" is the software equivalent of a "retriggerable monostable
118         // multivibrator" from electronics.  Briefly, a one-shot is a timer that can be triggered
119         // to fire at some point in the future.  It is "retriggerable" because while the timer
120         // is active, it is possible to replace the current timeout value by a new value.
121         // This is done by cancelling the current timer (using a generation count),
122         // and then posting another timer with the new desired value.
123     };
124 
125     // Send a notification to one of the event listeners
126     virtual void notify(const char* event, int data1, bool async);
127     virtual void notify(const char* event, int data1, int data2, bool async);
128 
129     // AHandler implementation
130     virtual void onMessageReceived(const sp<AMessage> &msg);
131 
132     // Async event handlers (called from GenericPlayer's event loop)
133     virtual void onPrepare();
134     virtual void onNotify(const sp<AMessage> &msg);
135     virtual void onPlay();
136     virtual void onPause();
137     virtual void onSeek(const sp<AMessage> &msg);
138     virtual void onLoop(const sp<AMessage> &msg);
139     virtual void onVolumeUpdate();
140     virtual void onSeekComplete();
141     virtual void onBufferingUpdate(const sp<AMessage> &msg);
142     virtual void onSetBufferingUpdateThreshold(const sp<AMessage> &msg);
143     virtual void onAttachAuxEffect(const sp<AMessage> &msg);
144     virtual void onSetAuxEffectSendLevel(const sp<AMessage> &msg);
145     void onSetPlayEvents(const sp<AMessage> &msg);
146     void onOneShot(const sp<AMessage> &msg);
147 
148     // Convenience methods
149     //   for async notifications of prefetch status and cache fill level, needs to be called
150     //     with mSettingsLock locked
151     void notifyStatus();
152     void notifyCacheFill();
153     //   for internal async notification to update state that the player is no longer seeking
154     void seekComplete();
155     void bufferingUpdate(int16_t fillLevelPerMille);
156 
157     // Event notification from GenericPlayer to OpenSL ES / OpenMAX AL framework
158     notif_cbf_t mNotifyClient;
159     void*       mNotifyUser;
160     // lock to protect mNotifyClient and mNotifyUser updates
161     Mutex       mNotifyClientLock;
162 
163     // Bits for mStateFlags
164     enum {
165         kFlagPrepared               = 1 << 0,   // use only for successful preparation
166         kFlagPreparing              = 1 << 1,
167         kFlagPlaying                = 1 << 2,
168         kFlagBuffering              = 1 << 3,
169         kFlagSeeking                = 1 << 4,   // set if we (not Stagefright) initiated a seek
170         kFlagLooping                = 1 << 5,   // set if looping is enabled
171         kFlagPreparedUnsuccessfully = 1 << 6,
172     };
173 
174     // Only accessed from event loop, does not need a mutex
175     uint32_t mStateFlags;
176 
177     sp<ALooper> mLooper;
178 
179     const AudioPlayback_Parameters mPlaybackParams;
180 
181     // protected by mSettingsLock after construction
182     AndroidAudioLevels mAndroidAudioLevels;
183 
184     // protected by mSettingsLock
185     int32_t mDurationMsec;
186     int16_t mPlaybackRatePermille;
187 
188     CacheStatus_t mCacheStatus;
189     int16_t mCacheFill; // cache fill level + played back level in permille
190     int16_t mLastNotifiedCacheFill; // last cache fill level communicated to the listener
191     int16_t mCacheFillNotifThreshold; // threshold in cache fill level for cache fill to be reported
192 
193     // Call any time any of the IPlay copies, current position, or play state changes, and
194     // supply the latest known position or ANDROID_UNKNOWN_TIME if position is unknown to caller.
195     void updateOneShot(int positionMs = ANDROID_UNKNOWN_TIME);
196 
197     // players that "render" data to present it to the user (a music player, a video player),
198     // should return true, while players that only decode (hopefully faster than "real time")
199     // should return false.
advancesPositionInRealTime()200     virtual bool advancesPositionInRealTime() const { return true; }
201 
202 private:
203 
204     // Our copy of some important IPlay member variables, except in Android units
205     int32_t mEventFlags;
206     int32_t mMarkerPositionMs;
207     int32_t mPositionUpdatePeriodMs;
208 
209     // We need to be able to cancel any pending one-shot event(s) prior to posting
210     // a new one-shot.  As AMessage does not currently support cancellation by
211     // "what" category, we simulate this by keeping a generation counter for
212     // one-shots.  When a one-shot event is delivered, it checks to see if it is
213     // still the current one-shot.  If not, it returns immediately, thus
214     // effectively cancelling itself.  Note that counter wrap-around is possible
215     // but unlikely and benign.
216     int32_t mOneShotGeneration;
217 
218     // Play position at time of the most recently delivered SL_PLAYEVENT_HEADATNEWPOS,
219     // or ANDROID_UNKNOWN_TIME if a SL_PLAYEVENT_HEADATNEWPOS has never been delivered.
220     int32_t mDeliveredNewPosMs;
221 
222     // Play position most recently observed by updateOneShot, or ANDROID_UNKNOWN_TIME
223     // if the play position has never been observed.
224     int32_t mObservedPositionMs;
225 
226     DISALLOW_EVIL_CONSTRUCTORS(GenericPlayer);
227 };
228 
229 } // namespace android
230 
231 extern void android_player_volumeUpdate(float *pVolumes /*[2]*/, const IVolume *volumeItf,
232         unsigned channelCount, float amplFromDirectLevel, const bool *audibilityFactors /*[2]*/);
233 
234 #endif /* __ANDROID_GENERICPLAYER_H__ */
235