android_GenericMediaPlayer.cpp revision 4ee246c55533bdab8ab5fa0f0581744fe58e7c91
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//#define USE_LOG SLAndroidLogLevel_Verbose
18
19#include "sles_allinclusive.h"
20#include "android_GenericMediaPlayer.h"
21
22#include <media/IMediaPlayerService.h>
23#include <surfaceflinger/ISurfaceComposer.h>
24#include <surfaceflinger/SurfaceComposerClient.h>
25#include <media/stagefright/foundation/ADebug.h>
26
27namespace android {
28
29// default delay in Us used when reposting an event when the player is not ready to accept
30// the command yet. This is for instance used when seeking on a MediaPlayer that's still preparing
31#define DEFAULT_COMMAND_DELAY_FOR_REPOST_US (100*1000) // 100ms
32
33static const char* const kDistantProtocolPrefix[] = { "http:", "https:", "ftp:", "rtp:", "rtsp:"};
34#define NB_DISTANT_PROTOCOLS (sizeof(kDistantProtocolPrefix)/sizeof(kDistantProtocolPrefix[0]))
35
36//--------------------------------------------------------------------------------------------------
37MediaPlayerNotificationClient::MediaPlayerNotificationClient(GenericMediaPlayer* gmp) :
38    mGenericMediaPlayer(gmp),
39    mPlayerPrepared(false)
40{
41
42}
43
44MediaPlayerNotificationClient::~MediaPlayerNotificationClient() {
45
46}
47
48//--------------------------------------------------
49// IMediaPlayerClient implementation
50void MediaPlayerNotificationClient::notify(int msg, int ext1, int ext2) {
51    SL_LOGI("MediaPlayerNotificationClient::notify(msg=%d, ext1=%d, ext2=%d)", msg, ext1, ext2);
52
53    switch (msg) {
54      case MEDIA_PREPARED:
55        mPlayerPrepared = true;
56        mPlayerPreparedCondition.signal();
57        break;
58
59      case MEDIA_SET_VIDEO_SIZE:
60        // only send video size updates if the player was flagged as having video, to avoid
61        // sending video size updates of (0,0)
62        if (mGenericMediaPlayer->mHasVideo) {
63            mGenericMediaPlayer->notify(PLAYEREVENT_VIDEO_SIZE_UPDATE,
64                    (int32_t)ext1, (int32_t)ext2, true /*async*/);
65        }
66        break;
67
68      case MEDIA_SEEK_COMPLETE:
69          mGenericMediaPlayer->seekComplete();
70        break;
71
72      case MEDIA_PLAYBACK_COMPLETE:
73        mGenericMediaPlayer->notify(PLAYEREVENT_ENDOFSTREAM, 1, true /*async*/);
74        break;
75
76      case MEDIA_BUFFERING_UPDATE:
77        // values received from Android framework for buffer fill level use percent,
78        //   while SL/XA use permille, so does GenericPlayer
79        mGenericMediaPlayer->bufferingUpdate(ext1 * 10 /*fillLevelPerMille*/);
80        break;
81
82      default: { }
83    }
84}
85
86//--------------------------------------------------
87void MediaPlayerNotificationClient::blockUntilPlayerPrepared() {
88    Mutex::Autolock _l(mLock);
89    while (!mPlayerPrepared) {
90        mPlayerPreparedCondition.wait(mLock);
91    }
92}
93
94//--------------------------------------------------------------------------------------------------
95GenericMediaPlayer::GenericMediaPlayer(const AudioPlayback_Parameters* params, bool hasVideo) :
96    GenericPlayer(params),
97    mHasVideo(hasVideo),
98    mVideoSurface(0),
99    mVideoSurfaceTexture(0),
100    mPlayer(0),
101    mPlayerClient(0)
102{
103    SL_LOGD("GenericMediaPlayer::GenericMediaPlayer()");
104
105    mServiceManager = defaultServiceManager();
106    mBinder = mServiceManager->getService(String16("media.player"));
107    mMediaPlayerService = interface_cast<IMediaPlayerService>(mBinder);
108
109    CHECK(mMediaPlayerService.get() != NULL);
110
111    mPlayerClient = new MediaPlayerNotificationClient(this);
112}
113
114GenericMediaPlayer::~GenericMediaPlayer() {
115    SL_LOGD("GenericMediaPlayer::~GenericMediaPlayer()");
116
117}
118
119//--------------------------------------------------
120void GenericMediaPlayer::setVideoSurface(const sp<Surface> &surface) {
121    mVideoSurface = surface;
122}
123
124void GenericMediaPlayer::setVideoSurfaceTexture(const sp<ISurfaceTexture> &surfaceTexture) {
125    mVideoSurfaceTexture = surfaceTexture;
126}
127
128
129//--------------------------------------------------
130// Event handlers
131
132void GenericMediaPlayer::onPrepare() {
133    SL_LOGD("GenericMediaPlayer::onPrepare()");
134    if (!(mStateFlags & kFlagPrepared) && (mPlayer != 0)) {
135        if (mHasVideo) {
136            if (mVideoSurface != 0) {
137                mPlayer->setVideoSurface(mVideoSurface);
138            } else if (mVideoSurfaceTexture != 0) {
139                mPlayer->setVideoSurfaceTexture(mVideoSurfaceTexture);
140            }
141        }
142        mPlayer->setAudioStreamType(mPlaybackParams.streamType);
143        mPlayer->prepareAsync();
144        mPlayerClient->blockUntilPlayerPrepared();
145        onAfterMediaPlayerPrepared();
146        GenericPlayer::onPrepare();
147    }
148    SL_LOGD("GenericMediaPlayer::onPrepare() done, mStateFlags=0x%x", mStateFlags);
149}
150
151
152void GenericMediaPlayer::onPlay() {
153    SL_LOGD("GenericMediaPlayer::onPlay()");
154    if ((mStateFlags & kFlagPrepared) && (mPlayer != 0)) {
155        SL_LOGD("starting player");
156        mPlayer->start();
157        mStateFlags |= kFlagPlaying;
158    } else {
159        SL_LOGV("NOT starting player mStateFlags=0x%x", mStateFlags);
160    }
161}
162
163
164void GenericMediaPlayer::onPause() {
165    SL_LOGD("GenericMediaPlayer::onPause()");
166    if ((mStateFlags & kFlagPrepared) && (mPlayer != 0)) {
167        mPlayer->pause();
168        mStateFlags &= ~kFlagPlaying;
169    }
170}
171
172
173void GenericMediaPlayer::onSeek(const sp<AMessage> &msg) {
174    SL_LOGV("GenericMediaPlayer::onSeek");
175    if ((mStateFlags & kFlagSeeking) || !(mStateFlags & kFlagPrepared)) {
176        // we are not ready to accept a seek command at this time, retry later
177        msg->post(DEFAULT_COMMAND_DELAY_FOR_REPOST_US);
178    } else {
179        int64_t timeMsec;
180        if (msg->findInt64(WHATPARAM_SEEK_SEEKTIME_MS, &timeMsec) && (mPlayer != 0)) {
181            if (OK == mPlayer->seekTo(timeMsec)) {
182                mStateFlags |= kFlagSeeking;
183            }
184        }
185    }
186}
187
188
189void GenericMediaPlayer::onLoop(const sp<AMessage> &msg) {
190    SL_LOGV("GenericMediaPlayer::onLoop");
191    int32_t loop = 0;
192    if (msg->findInt32(WHATPARAM_LOOP_LOOPING, &loop)) {
193        if (OK == mPlayer->setLooping(loop)) {
194            if (loop) {
195                mStateFlags |= kFlagLooping;
196            } else {
197                mStateFlags &= ~kFlagLooping;
198            }
199        }
200    }
201}
202
203
204void GenericMediaPlayer::onVolumeUpdate() {
205    SL_LOGD("GenericMediaPlayer::onVolumeUpdate()");
206    // use settings lock to read the volume settings
207    Mutex::Autolock _l(mSettingsLock);
208    if (mPlayer != 0) {
209        if (mAndroidAudioLevels.mMute) {
210            mPlayer->setVolume(0.0f, 0.0f);
211        } else {
212            mPlayer->setVolume(mAndroidAudioLevels.mFinalVolume[0],
213                    mAndroidAudioLevels.mFinalVolume[1]);
214        }
215    }
216}
217
218
219void GenericMediaPlayer::onBufferingUpdate(const sp<AMessage> &msg) {
220    int32_t fillLevel = 0;
221    if (msg->findInt32(WHATPARAM_BUFFERING_UPDATE, &fillLevel)) {
222        SL_LOGD("GenericMediaPlayer::onBufferingUpdate(fillLevel=%d)", fillLevel);
223
224        Mutex::Autolock _l(mSettingsLock);
225        mCacheFill = fillLevel;
226        // handle cache fill update
227        if (mCacheFill - mLastNotifiedCacheFill >= mCacheFillNotifThreshold) {
228            notifyCacheFill();
229        }
230        // handle prefetch status update
231        //   compute how much time ahead of position is buffered
232        int durationMsec, positionMsec = -1;
233        if ((mStateFlags & kFlagPrepared) && (mPlayer != 0)
234                && (OK == mPlayer->getDuration(&durationMsec))
235                        && (OK == mPlayer->getCurrentPosition(&positionMsec))) {
236            if ((-1 != durationMsec) && (-1 != positionMsec)) {
237                // evaluate prefetch status based on buffer time thresholds
238                int64_t bufferedDurationMsec = (durationMsec * fillLevel / 100) - positionMsec;
239                CacheStatus_t newCacheStatus = mCacheStatus;
240                if (bufferedDurationMsec > DURATION_CACHED_HIGH_MS) {
241                    newCacheStatus = kStatusHigh;
242                } else if (bufferedDurationMsec > DURATION_CACHED_MED_MS) {
243                    newCacheStatus = kStatusEnough;
244                } else if (bufferedDurationMsec > DURATION_CACHED_LOW_MS) {
245                    newCacheStatus = kStatusIntermediate;
246                } else if (bufferedDurationMsec == 0) {
247                    newCacheStatus = kStatusEmpty;
248                } else {
249                    newCacheStatus = kStatusLow;
250                }
251
252                if (newCacheStatus != mCacheStatus) {
253                    mCacheStatus = newCacheStatus;
254                    notifyStatus();
255                }
256            }
257        }
258    }
259}
260
261
262//--------------------------------------------------
263/**
264 * called from the event handling loop
265 * pre-condition: mPlayer is prepared
266 */
267void GenericMediaPlayer::onAfterMediaPlayerPrepared() {
268    // the MediaPlayer mPlayer is prepared, retrieve its duration
269    {
270        Mutex::Autolock _l(mSettingsLock);
271        int msec = 0;
272        if (OK == mPlayer->getDuration(&msec)) {
273            mDurationMsec = msec;
274        }
275    }
276    // when the MediaPlayer mPlayer is prepared, there is "sufficient data" in the playback buffers
277    // if the data source was local, and the buffers are considered full so we need to notify that
278    bool isLocalSource = true;
279    if (kDataLocatorUri == mDataLocatorType) {
280        for (unsigned int i = 0 ; i < NB_DISTANT_PROTOCOLS ; i++) {
281            if (!strncasecmp(mDataLocator.uriRef,
282                    kDistantProtocolPrefix[i], strlen(kDistantProtocolPrefix[i]))) {
283                isLocalSource = false;
284                break;
285            }
286        }
287    }
288    if (isLocalSource) {
289        SL_LOGD("media player prepared on local source");
290        {
291            Mutex::Autolock _l(mSettingsLock);
292            mCacheStatus = kStatusHigh;
293            mCacheFill = 1000;
294            notifyStatus();
295            notifyCacheFill();
296        }
297    } else {
298        SL_LOGD("media player prepared on non-local source");
299    }
300}
301
302} // namespace android
303