android_GenericPlayer.h revision c4374bd42cd7eadda841a6b089234becb4f6c508
120e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown/*
220e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown * Copyright (C) 2011 The Android Open Source Project
320e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown *
420e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown * Licensed under the Apache License, Version 2.0 (the "License");
520e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown * you may not use this file except in compliance with the License.
620e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown * You may obtain a copy of the License at
720e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown *
820e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown *      http://www.apache.org/licenses/LICENSE-2.0
920e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown *
1020e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown * Unless required by applicable law or agreed to in writing, software
1120e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown * distributed under the License is distributed on an "AS IS" BASIS,
1220e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1320e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown * See the License for the specific language governing permissions and
1420e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown * limitations under the License.
1520e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown */
1620e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown
1720e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown#ifndef __ANDROID_GENERICPLAYER_H__
1820e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown#define __ANDROID_GENERICPLAYER_H__
1920e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown
2020e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown#include <media/stagefright/foundation/AHandler.h>
2120e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown#include <media/stagefright/foundation/ALooper.h>
2220e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown#include <media/stagefright/foundation/AMessage.h>
2320e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown
2420e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown//--------------------------------------------------------------------------------------------------
2520e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown/**
2620e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown * Message parameters for AHandler messages, see list in GenericPlayer::kWhatxxx
2720e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown */
2820e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown#define WHATPARAM_SEEK_SEEKTIME_MS                  "seekTimeMs"
2920e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown#define WHATPARAM_LOOP_LOOPING                      "looping"
3020e987bfc35d0ae6cb6344ead65ed44ee7cf8750Jeff Brown#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
43// abstract base class
44class GenericPlayer : public AHandler
45{
46public:
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
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',  // start preparation
102        kWhatNotif           = 'noti',  // send a notification to client
103        kWhatPlay            = 'play',  // start player
104        kWhatPause           = 'paus',  // pause or stop player
105        kWhatSeek            = 'seek',  // request a seek to specified position
106        kWhatSeekComplete    = 'skcp',  // seek request has completed
107        kWhatLoop            = 'loop',  // set the player's looping status
108        kWhatVolumeUpdate    = 'volu',  // set the channel gains to specified values
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    // Only accessed from event loop, does not need a mutex
173    uint32_t mStateFlags;
174
175    sp<ALooper> mLooper;
176
177    const AudioPlayback_Parameters mPlaybackParams;
178
179    // protected by mSettingsLock after construction
180    AndroidAudioLevels mAndroidAudioLevels;
181
182    // protected by mSettingsLock
183    int32_t mDurationMsec;
184
185    CacheStatus_t mCacheStatus;
186    int16_t mCacheFill; // cache fill level + played back level in permille
187    int16_t mLastNotifiedCacheFill; // last cache fill level communicated to the listener
188    int16_t mCacheFillNotifThreshold; // threshold in cache fill level for cache fill to be reported
189
190    // Call any time any of the IPlay copies, current position, or play state changes, and
191    // supply the latest known position or ANDROID_UNKNOWN_TIME if position is unknown to caller.
192    void updateOneShot(int positionMs = ANDROID_UNKNOWN_TIME);
193
194    virtual bool advancesPositionInRealTime() const { return true; }
195
196private:
197
198    // Our copy of some important IPlay member variables, except in Android units
199    int32_t mEventFlags;
200    int32_t mMarkerPositionMs;
201    int32_t mPositionUpdatePeriodMs;
202
203    // We need to be able to cancel any pending one-shot event(s) prior to posting
204    // a new one-shot.  As AMessage does not currently support cancellation by
205    // "what" category, we simulate this by keeping a generation counter for
206    // one-shots.  When a one-shot event is delivered, it checks to see if it is
207    // still the current one-shot.  If not, it returns immediately, thus
208    // effectively cancelling itself.  Note that counter wrap-around is possible
209    // but unlikely and benign.
210    int32_t mOneShotGeneration;
211
212    // Play position at time of the most recently delivered SL_PLAYEVENT_HEADATNEWPOS,
213    // or ANDROID_UNKNOWN_TIME if a SL_PLAYEVENT_HEADATNEWPOS has never been delivered.
214    int32_t mDeliveredNewPosMs;
215
216    // Play position most recently observed by updateOneShot, or ANDROID_UNKNOWN_TIME
217    // if the play position has never been observed.
218    int32_t mObservedPositionMs;
219
220    DISALLOW_EVIL_CONSTRUCTORS(GenericPlayer);
221};
222
223} // namespace android
224
225extern void android_player_volumeUpdate(float *pVolumes /*[2]*/, const IVolume *volumeItf,
226        unsigned channelCount, float amplFromDirectLevel, const bool *audibilityFactors /*[2]*/);
227
228#endif /* __ANDROID_GENERICPLAYER_H__ */
229