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