android_GenericPlayer.h revision 167a2af67dcc0d20e6e3e995a23a0567715e0ee1
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
41namespace android {
42
43class GenericPlayer : public AHandler
44{
45public:
46
47    enum {
48        kEventPrepared                = 'prep',
49        kEventHasVideoSize            = 'vsiz',
50        kEventPrefetchStatusChange    = 'pfsc',
51        kEventPrefetchFillLevelUpdate = 'pflu',
52        kEventEndOfStream             = 'eos',
53        kEventChannelCount            = 'ccnt',
54        kEventPlay                    = 'play', // SL_PLAYEVENT_*
55        kEventErrorAfterPrepare       = 'easp', // error after successful prepare
56    };
57
58
59    GenericPlayer(const AudioPlayback_Parameters* params);
60    virtual ~GenericPlayer();
61
62    virtual void init(const notif_cbf_t cbf, void* notifUser);
63    virtual void preDestroy();
64
65    void setDataSource(const char *uri);
66    void setDataSource(int fd, int64_t offset, int64_t length, bool closeAfterUse = false);
67
68            void prepare();
69    virtual void play();
70    virtual void pause();
71    virtual void stop();
72    // timeMsec must be >= 0 or == ANDROID_UNKNOWN_TIME (used by StreamPlayer after discontinuity)
73    virtual void seek(int64_t timeMsec);
74    virtual void loop(bool loop);
75    virtual void setBufferingUpdateThreshold(int16_t thresholdPercent);
76
77    virtual void getDurationMsec(int* msec); //msec != NULL, ANDROID_UNKNOWN_TIME if unknown
78    virtual void getPositionMsec(int* msec) = 0; //msec != NULL, ANDROID_UNKNOWN_TIME if unknown
79
80    virtual void setVideoSurface(const sp<Surface> &surface) {}
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    // Call after changing any of the IPlay settings related to SL_PLAYEVENT_*
88    void setPlayEvents(int32_t eventFlags, int32_t markerPosition, int32_t positionUpdatePeriod);
89
90protected:
91    // mutex used for set vs use of volume, duration, and cache (fill, threshold) settings
92    Mutex mSettingsLock;
93
94    void resetDataLocator();
95    DataLocator2 mDataLocator;
96    int          mDataLocatorType;
97
98    // Constants used to identify the messages in this player's AHandler message loop
99    //   in onMessageReceived()
100    enum {
101        kWhatPrepare         = 'prep',
102        kWhatNotif           = 'noti',
103        kWhatPlay            = 'play',
104        kWhatPause           = 'paus',
105        kWhatSeek            = 'seek',
106        kWhatSeekComplete    = 'skcp',
107        kWhatLoop            = 'loop',
108        kWhatVolumeUpdate    = 'volu',
109        kWhatBufferingUpdate = 'bufu',
110        kWhatBuffUpdateThres = 'buut',
111        kWhatAttachAuxEffect = 'aaux',
112        kWhatSetAuxEffectSendLevel = 'saux',
113        kWhatSetPlayEvents   = 'spev',  // process new IPlay settings related to SL_PLAYEVENT_*
114        kWhatOneShot         = 'ones',  // deferred (non-0 timeout) handler for SL_PLAYEVENT_*
115        // As used here, "one-shot" is the software equivalent of a "retriggerable monostable
116        // multivibrator" from electronics.  Briefly, a one-shot is a timer that can be triggered
117        // to fire at some point in the future.  It is "retriggerable" because while the timer
118        // is active, it is possible to replace the current timeout value by a new value.
119        // This is done by cancelling the current timer (using a generation count),
120        // and then posting another timer with the new desired value.
121    };
122
123    // Send a notification to one of the event listeners
124    virtual void notify(const char* event, int data1, bool async);
125    virtual void notify(const char* event, int data1, int data2, bool async);
126
127    // AHandler implementation
128    virtual void onMessageReceived(const sp<AMessage> &msg);
129
130    // Async event handlers (called from GenericPlayer's event loop)
131    virtual void onPrepare();
132    virtual void onNotify(const sp<AMessage> &msg);
133    virtual void onPlay();
134    virtual void onPause();
135    virtual void onSeek(const sp<AMessage> &msg);
136    virtual void onLoop(const sp<AMessage> &msg);
137    virtual void onVolumeUpdate();
138    virtual void onSeekComplete();
139    virtual void onBufferingUpdate(const sp<AMessage> &msg);
140    virtual void onSetBufferingUpdateThreshold(const sp<AMessage> &msg);
141    virtual void onAttachAuxEffect(const sp<AMessage> &msg);
142    virtual void onSetAuxEffectSendLevel(const sp<AMessage> &msg);
143    void onSetPlayEvents(const sp<AMessage> &msg);
144    void onOneShot(const sp<AMessage> &msg);
145
146    // Convenience methods
147    //   for async notifications of prefetch status and cache fill level, needs to be called
148    //     with mSettingsLock locked
149    void notifyStatus();
150    void notifyCacheFill();
151    //   for internal async notification to update state that the player is no longer seeking
152    void seekComplete();
153    void bufferingUpdate(int16_t fillLevelPerMille);
154
155    // Event notification from GenericPlayer to OpenSL ES / OpenMAX AL framework
156    notif_cbf_t mNotifyClient;
157    void*       mNotifyUser;
158    // lock to protect mNotifyClient and mNotifyUser updates
159    Mutex       mNotifyClientLock;
160
161    // Bits for mStateFlags
162    enum {
163        kFlagPrepared               = 1 << 0,   // use only for successful preparation
164        kFlagPreparing              = 1 << 1,
165        kFlagPlaying                = 1 << 2,
166        kFlagBuffering              = 1 << 3,
167        kFlagSeeking                = 1 << 4,   // set if we (not Stagefright) initiated a seek
168        kFlagLooping                = 1 << 5,   // set if looping is enabled
169        kFlagPreparedUnsuccessfully = 1 << 6,
170    };
171
172    uint32_t mStateFlags;
173
174    sp<ALooper> mLooper;
175
176    const AudioPlayback_Parameters mPlaybackParams;
177
178    AndroidAudioLevels mAndroidAudioLevels;
179
180    // protected by mSettingsLock
181    int32_t mDurationMsec;
182
183    CacheStatus_t mCacheStatus;
184    int16_t mCacheFill; // cache fill level + played back level in permille
185    int16_t mLastNotifiedCacheFill; // last cache fill level communicated to the listener
186    int16_t mCacheFillNotifThreshold; // threshold in cache fill level for cache fill to be reported
187
188    // Call any time any of the IPlay copies, current position, or play state changes, and
189    // supply the latest known position or ANDROID_UNKNOWN_TIME if position is unknown to caller.
190    void updateOneShot(int positionMs = ANDROID_UNKNOWN_TIME);
191
192    virtual bool advancesPositionInRealTime() const { return true; }
193
194private:
195
196    // Our copy of some important IPlay member variables, except in Android units
197    int32_t mEventFlags;
198    int32_t mMarkerPositionMs;
199    int32_t mPositionUpdatePeriodMs;
200
201    // We need to be able to cancel any pending one-shot event(s) prior to posting
202    // a new one-shot.  As AMessage does not currently support cancellation by
203    // "what" category, we simulate this by keeping a generation counter for
204    // one-shots.  When a one-shot event is delivered, it checks to see if it is
205    // still the current one-shot.  If not, it returns immediately, thus
206    // effectively cancelling itself.  Note that counter wrap-around is possible
207    // but unlikely and benign.
208    int32_t mOneShotGeneration;
209
210    // Play position at time of the most recently delivered SL_PLAYEVENT_HEADATNEWPOS,
211    // or ANDROID_UNKNOWN_TIME if a SL_PLAYEVENT_HEADATNEWPOS has never been delivered.
212    int32_t mDeliveredNewPosMs;
213
214    // Play position most recently observed by updateOneShot, or ANDROID_UNKNOWN_TIME
215    // if the play position has never been observed.
216    int32_t mObservedPositionMs;
217
218    DISALLOW_EVIL_CONSTRUCTORS(GenericPlayer);
219};
220
221} // namespace android
222
223extern void android_player_volumeUpdate(float *pVolumes /*[2]*/, const IVolume *volumeItf,
224        unsigned channelCount, float amplFromDirectLevel, const bool *audibilityFactors /*[2]*/);
225
226#endif /* __ANDROID_GENERICPLAYER_H__ */
227