mediaplayer.cpp revision 4710a1f6c9800dae90f9e2702ba2b5b54c095eae
1/* mediaplayer.cpp
2**
3** Copyright 2006, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9**     http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18//#define LOG_NDEBUG 0
19#define LOG_TAG "MediaPlayer"
20#include <utils/Log.h>
21
22#include <sys/types.h>
23#include <sys/stat.h>
24#include <unistd.h>
25#include <fcntl.h>
26
27#include <binder/IServiceManager.h>
28#include <binder/IPCThreadState.h>
29
30#include <media/mediaplayer.h>
31#include <media/AudioTrack.h>
32
33#include <binder/MemoryBase.h>
34
35namespace android {
36
37// client singleton for binder interface to service
38Mutex MediaPlayer::sServiceLock;
39sp<IMediaPlayerService> MediaPlayer::sMediaPlayerService;
40sp<MediaPlayer::DeathNotifier> MediaPlayer::sDeathNotifier;
41SortedVector< wp<MediaPlayer> > MediaPlayer::sObitRecipients;
42
43// establish binder interface to service
44const sp<IMediaPlayerService>& MediaPlayer::getMediaPlayerService()
45{
46    Mutex::Autolock _l(sServiceLock);
47    if (sMediaPlayerService.get() == 0) {
48        sp<IServiceManager> sm = defaultServiceManager();
49        sp<IBinder> binder;
50        do {
51            binder = sm->getService(String16("media.player"));
52            if (binder != 0)
53                break;
54            LOGW("MediaPlayerService not published, waiting...");
55            usleep(500000); // 0.5 s
56        } while(true);
57        if (sDeathNotifier == NULL) {
58            sDeathNotifier = new DeathNotifier();
59        }
60        binder->linkToDeath(sDeathNotifier);
61        sMediaPlayerService = interface_cast<IMediaPlayerService>(binder);
62    }
63    LOGE_IF(sMediaPlayerService==0, "no MediaPlayerService!?");
64    return sMediaPlayerService;
65}
66
67void MediaPlayer::addObitRecipient(const wp<MediaPlayer>& recipient)
68{
69    Mutex::Autolock _l(sServiceLock);
70    sObitRecipients.add(recipient);
71}
72
73void MediaPlayer::removeObitRecipient(const wp<MediaPlayer>& recipient)
74{
75    Mutex::Autolock _l(sServiceLock);
76    sObitRecipients.remove(recipient);
77}
78
79MediaPlayer::MediaPlayer()
80{
81    LOGV("constructor");
82    mListener = NULL;
83    mCookie = NULL;
84    mDuration = -1;
85    mStreamType = AudioSystem::MUSIC;
86    mCurrentPosition = -1;
87    mSeekPosition = -1;
88    mCurrentState = MEDIA_PLAYER_IDLE;
89    mPrepareSync = false;
90    mPrepareStatus = NO_ERROR;
91    mLoop = false;
92    mLeftVolume = mRightVolume = 1.0;
93    mVideoWidth = mVideoHeight = 0;
94    mLockThreadId = 0;
95}
96
97void MediaPlayer::onFirstRef()
98{
99    addObitRecipient(this);
100}
101
102MediaPlayer::~MediaPlayer()
103{
104    LOGV("destructor");
105    removeObitRecipient(this);
106    disconnect();
107    IPCThreadState::self()->flushCommands();
108}
109
110void MediaPlayer::disconnect()
111{
112    LOGV("disconnect");
113    sp<IMediaPlayer> p;
114    {
115        Mutex::Autolock _l(mLock);
116        p = mPlayer;
117        mPlayer.clear();
118    }
119
120    if (p != 0) {
121        p->disconnect();
122    }
123}
124
125// always call with lock held
126void MediaPlayer::clear_l()
127{
128    mDuration = -1;
129    mCurrentPosition = -1;
130    mSeekPosition = -1;
131    mVideoWidth = mVideoHeight = 0;
132}
133
134status_t MediaPlayer::setListener(const sp<MediaPlayerListener>& listener)
135{
136    LOGV("setListener");
137    Mutex::Autolock _l(mLock);
138    mListener = listener;
139    return NO_ERROR;
140}
141
142
143status_t MediaPlayer::setDataSource(const sp<IMediaPlayer>& player)
144{
145    status_t err = UNKNOWN_ERROR;
146    sp<IMediaPlayer> p;
147    { // scope for the lock
148        Mutex::Autolock _l(mLock);
149
150        if ( !( mCurrentState & ( MEDIA_PLAYER_IDLE | MEDIA_PLAYER_STATE_ERROR ) ) ) {
151            LOGE("setDataSource called in state %d", mCurrentState);
152            return INVALID_OPERATION;
153        }
154
155        clear_l();
156        p = mPlayer;
157        mPlayer = player;
158        if (player != 0) {
159            mCurrentState = MEDIA_PLAYER_INITIALIZED;
160            err = NO_ERROR;
161        } else {
162            LOGE("Unable to to create media player");
163        }
164    }
165
166    if (p != 0) {
167        p->disconnect();
168    }
169
170    return err;
171}
172
173status_t MediaPlayer::setDataSource(const char *url)
174{
175    LOGV("setDataSource(%s)", url);
176    status_t err = BAD_VALUE;
177    if (url != NULL) {
178        const sp<IMediaPlayerService>& service(getMediaPlayerService());
179        if (service != 0) {
180            sp<IMediaPlayer> player(service->create(getpid(), this, url));
181            err = setDataSource(player);
182        }
183    }
184    return err;
185}
186
187status_t MediaPlayer::setDataSource(int fd, int64_t offset, int64_t length)
188{
189    LOGV("setDataSource(%d, %lld, %lld)", fd, offset, length);
190    status_t err = UNKNOWN_ERROR;
191    const sp<IMediaPlayerService>& service(getMediaPlayerService());
192    if (service != 0) {
193        sp<IMediaPlayer> player(service->create(getpid(), this, fd, offset, length));
194        err = setDataSource(player);
195    }
196    return err;
197}
198
199status_t MediaPlayer::setVideoSurface(const sp<Surface>& surface)
200{
201    LOGV("setVideoSurface");
202    Mutex::Autolock _l(mLock);
203    if (mPlayer == 0) return NO_INIT;
204    return  mPlayer->setVideoSurface(surface->getISurface());
205}
206
207// must call with lock held
208status_t MediaPlayer::prepareAsync_l()
209{
210    if ( (mPlayer != 0) && ( mCurrentState & ( MEDIA_PLAYER_INITIALIZED | MEDIA_PLAYER_STOPPED) ) ) {
211        mPlayer->setAudioStreamType(mStreamType);
212        mCurrentState = MEDIA_PLAYER_PREPARING;
213        return mPlayer->prepareAsync();
214    }
215    LOGE("prepareAsync called in state %d", mCurrentState);
216    return INVALID_OPERATION;
217}
218
219// TODO: In case of error, prepareAsync provides the caller with 2 error codes,
220// one defined in the Android framework and one provided by the implementation
221// that generated the error. The sync version of prepare returns only 1 error
222// code.
223status_t MediaPlayer::prepare()
224{
225    LOGV("prepare");
226    Mutex::Autolock _l(mLock);
227    mLockThreadId = getThreadId();
228    if (mPrepareSync) {
229        mLockThreadId = 0;
230        return -EALREADY;
231    }
232    mPrepareSync = true;
233    status_t ret = prepareAsync_l();
234    if (ret != NO_ERROR) {
235        mLockThreadId = 0;
236        return ret;
237    }
238
239    if (mPrepareSync) {
240        mSignal.wait(mLock);  // wait for prepare done
241        mPrepareSync = false;
242    }
243    LOGV("prepare complete - status=%d", mPrepareStatus);
244    mLockThreadId = 0;
245    return mPrepareStatus;
246}
247
248status_t MediaPlayer::prepareAsync()
249{
250    LOGV("prepareAsync");
251    Mutex::Autolock _l(mLock);
252    return prepareAsync_l();
253}
254
255status_t MediaPlayer::start()
256{
257    LOGV("start");
258    Mutex::Autolock _l(mLock);
259    if (mCurrentState & MEDIA_PLAYER_STARTED)
260        return NO_ERROR;
261    if ( (mPlayer != 0) && ( mCurrentState & ( MEDIA_PLAYER_PREPARED |
262                    MEDIA_PLAYER_PLAYBACK_COMPLETE | MEDIA_PLAYER_PAUSED ) ) ) {
263        mPlayer->setLooping(mLoop);
264        mPlayer->setVolume(mLeftVolume, mRightVolume);
265        mCurrentState = MEDIA_PLAYER_STARTED;
266        status_t ret = mPlayer->start();
267        if (ret != NO_ERROR) {
268            mCurrentState = MEDIA_PLAYER_STATE_ERROR;
269        } else {
270            if (mCurrentState == MEDIA_PLAYER_PLAYBACK_COMPLETE) {
271                LOGV("playback completed immediately following start()");
272            }
273        }
274        return ret;
275    }
276    LOGE("start called in state %d", mCurrentState);
277    return INVALID_OPERATION;
278}
279
280status_t MediaPlayer::stop()
281{
282    LOGV("stop");
283    Mutex::Autolock _l(mLock);
284    if (mCurrentState & MEDIA_PLAYER_STOPPED) return NO_ERROR;
285    if ( (mPlayer != 0) && ( mCurrentState & ( MEDIA_PLAYER_STARTED | MEDIA_PLAYER_PREPARED |
286                    MEDIA_PLAYER_PAUSED | MEDIA_PLAYER_PLAYBACK_COMPLETE ) ) ) {
287        status_t ret = mPlayer->stop();
288        if (ret != NO_ERROR) {
289            mCurrentState = MEDIA_PLAYER_STATE_ERROR;
290        } else {
291            mCurrentState = MEDIA_PLAYER_STOPPED;
292        }
293        return ret;
294    }
295    LOGE("stop called in state %d", mCurrentState);
296    return INVALID_OPERATION;
297}
298
299status_t MediaPlayer::pause()
300{
301    LOGV("pause");
302    Mutex::Autolock _l(mLock);
303    if (mCurrentState & MEDIA_PLAYER_PAUSED)
304        return NO_ERROR;
305    if ((mPlayer != 0) && (mCurrentState & MEDIA_PLAYER_STARTED)) {
306        status_t ret = mPlayer->pause();
307        if (ret != NO_ERROR) {
308            mCurrentState = MEDIA_PLAYER_STATE_ERROR;
309        } else {
310            mCurrentState = MEDIA_PLAYER_PAUSED;
311        }
312        return ret;
313    }
314    LOGE("pause called in state %d", mCurrentState);
315    return INVALID_OPERATION;
316}
317
318bool MediaPlayer::isPlaying()
319{
320    Mutex::Autolock _l(mLock);
321    if (mPlayer != 0) {
322        bool temp = false;
323        mPlayer->isPlaying(&temp);
324        LOGV("isPlaying: %d", temp);
325        if ((mCurrentState & MEDIA_PLAYER_STARTED) && ! temp) {
326            LOGE("internal/external state mismatch corrected");
327            mCurrentState = MEDIA_PLAYER_PAUSED;
328        }
329        return temp;
330    }
331    LOGV("isPlaying: no active player");
332    return false;
333}
334
335status_t MediaPlayer::getVideoWidth(int *w)
336{
337    LOGV("getVideoWidth");
338    Mutex::Autolock _l(mLock);
339    if (mPlayer == 0) return INVALID_OPERATION;
340    *w = mVideoWidth;
341    return NO_ERROR;
342}
343
344status_t MediaPlayer::getVideoHeight(int *h)
345{
346    LOGV("getVideoHeight");
347    Mutex::Autolock _l(mLock);
348    if (mPlayer == 0) return INVALID_OPERATION;
349    *h = mVideoHeight;
350    return NO_ERROR;
351}
352
353status_t MediaPlayer::getCurrentPosition(int *msec)
354{
355    LOGV("getCurrentPosition");
356    Mutex::Autolock _l(mLock);
357    if (mPlayer != 0) {
358        if (mCurrentPosition >= 0) {
359            LOGV("Using cached seek position: %d", mCurrentPosition);
360            *msec = mCurrentPosition;
361            return NO_ERROR;
362        }
363        return mPlayer->getCurrentPosition(msec);
364    }
365    return INVALID_OPERATION;
366}
367
368status_t MediaPlayer::getDuration_l(int *msec)
369{
370    LOGV("getDuration");
371    bool isValidState = (mCurrentState & (MEDIA_PLAYER_PREPARED | MEDIA_PLAYER_STARTED | MEDIA_PLAYER_PAUSED | MEDIA_PLAYER_STOPPED | MEDIA_PLAYER_PLAYBACK_COMPLETE));
372    if (mPlayer != 0 && isValidState) {
373        status_t ret = NO_ERROR;
374        if (mDuration <= 0)
375            ret = mPlayer->getDuration(&mDuration);
376        if (msec)
377            *msec = mDuration;
378        return ret;
379    }
380    LOGE("Attempt to call getDuration without a valid mediaplayer");
381    return INVALID_OPERATION;
382}
383
384status_t MediaPlayer::getDuration(int *msec)
385{
386    Mutex::Autolock _l(mLock);
387    return getDuration_l(msec);
388}
389
390status_t MediaPlayer::seekTo_l(int msec)
391{
392    LOGV("seekTo %d", msec);
393    if ((mPlayer != 0) && ( mCurrentState & ( MEDIA_PLAYER_STARTED | MEDIA_PLAYER_PREPARED | MEDIA_PLAYER_PAUSED |  MEDIA_PLAYER_PLAYBACK_COMPLETE) ) ) {
394        if ( msec < 0 ) {
395            LOGW("Attempt to seek to invalid position: %d", msec);
396            msec = 0;
397        } else if ((mDuration > 0) && (msec > mDuration)) {
398            LOGW("Attempt to seek to past end of file: request = %d, EOF = %d", msec, mDuration);
399            msec = mDuration;
400        }
401        // cache duration
402        mCurrentPosition = msec;
403        if (mSeekPosition < 0) {
404            getDuration_l(NULL);
405            mSeekPosition = msec;
406            return mPlayer->seekTo(msec);
407        }
408        else {
409            LOGV("Seek in progress - queue up seekTo[%d]", msec);
410            return NO_ERROR;
411        }
412    }
413    LOGE("Attempt to perform seekTo in wrong state: mPlayer=%p, mCurrentState=%u", mPlayer.get(), mCurrentState);
414    return INVALID_OPERATION;
415}
416
417status_t MediaPlayer::seekTo(int msec)
418{
419    mLockThreadId = getThreadId();
420    Mutex::Autolock _l(mLock);
421    status_t result = seekTo_l(msec);
422    mLockThreadId = 0;
423
424    return result;
425}
426
427status_t MediaPlayer::reset()
428{
429    LOGV("reset");
430    Mutex::Autolock _l(mLock);
431    mLoop = false;
432    if (mCurrentState == MEDIA_PLAYER_IDLE) return NO_ERROR;
433    mPrepareSync = false;
434    if (mPlayer != 0) {
435        status_t ret = mPlayer->reset();
436        if (ret != NO_ERROR) {
437            LOGE("reset() failed with return code (%d)", ret);
438            mCurrentState = MEDIA_PLAYER_STATE_ERROR;
439        } else {
440            mCurrentState = MEDIA_PLAYER_IDLE;
441        }
442        return ret;
443    }
444    clear_l();
445    return NO_ERROR;
446}
447
448status_t MediaPlayer::setAudioStreamType(int type)
449{
450    LOGV("MediaPlayer::setAudioStreamType");
451    Mutex::Autolock _l(mLock);
452    if (mStreamType == type) return NO_ERROR;
453    if (mCurrentState & ( MEDIA_PLAYER_PREPARED | MEDIA_PLAYER_STARTED |
454                MEDIA_PLAYER_PAUSED | MEDIA_PLAYER_PLAYBACK_COMPLETE ) ) {
455        // Can't change the stream type after prepare
456        LOGE("setAudioStream called in state %d", mCurrentState);
457        return INVALID_OPERATION;
458    }
459    // cache
460    mStreamType = type;
461    return OK;
462}
463
464status_t MediaPlayer::setLooping(int loop)
465{
466    LOGV("MediaPlayer::setLooping");
467    Mutex::Autolock _l(mLock);
468    mLoop = (loop != 0);
469    if (mPlayer != 0) {
470        return mPlayer->setLooping(loop);
471    }
472    return OK;
473}
474
475bool MediaPlayer::isLooping() {
476    LOGV("isLooping");
477    Mutex::Autolock _l(mLock);
478    if (mPlayer != 0) {
479        return mLoop;
480    }
481    LOGV("isLooping: no active player");
482    return false;
483}
484
485status_t MediaPlayer::setVolume(float leftVolume, float rightVolume)
486{
487    LOGV("MediaPlayer::setVolume(%f, %f)", leftVolume, rightVolume);
488    Mutex::Autolock _l(mLock);
489    mLeftVolume = leftVolume;
490    mRightVolume = rightVolume;
491    if (mPlayer != 0) {
492        return mPlayer->setVolume(leftVolume, rightVolume);
493    }
494    return OK;
495}
496
497void MediaPlayer::notify(int msg, int ext1, int ext2)
498{
499    LOGV("message received msg=%d, ext1=%d, ext2=%d", msg, ext1, ext2);
500    bool send = true;
501    bool locked = false;
502
503    // TODO: In the future, we might be on the same thread if the app is
504    // running in the same process as the media server. In that case,
505    // this will deadlock.
506    //
507    // The threadId hack below works around this for the care of prepare
508    // and seekTo within the same process.
509    // FIXME: Remember, this is a hack, it's not even a hack that is applied
510    // consistently for all use-cases, this needs to be revisited.
511     if (mLockThreadId != getThreadId()) {
512        mLock.lock();
513        locked = true;
514    }
515
516    if (mPlayer == 0) {
517        LOGV("notify(%d, %d, %d) callback on disconnected mediaplayer", msg, ext1, ext2);
518        if (locked) mLock.unlock();   // release the lock when done.
519        return;
520    }
521
522    switch (msg) {
523    case MEDIA_NOP: // interface test message
524        break;
525    case MEDIA_PREPARED:
526        LOGV("prepared");
527        mCurrentState = MEDIA_PLAYER_PREPARED;
528        if (mPrepareSync) {
529            LOGV("signal application thread");
530            mPrepareSync = false;
531            mPrepareStatus = NO_ERROR;
532            mSignal.signal();
533        }
534        break;
535    case MEDIA_PLAYBACK_COMPLETE:
536        LOGV("playback complete");
537        if (!mLoop) {
538            mCurrentState = MEDIA_PLAYER_PLAYBACK_COMPLETE;
539        }
540        break;
541    case MEDIA_ERROR:
542        // Always log errors.
543        // ext1: Media framework error code.
544        // ext2: Implementation dependant error code.
545        LOGE("error (%d, %d)", ext1, ext2);
546        mCurrentState = MEDIA_PLAYER_STATE_ERROR;
547        if (mPrepareSync)
548        {
549            LOGV("signal application thread");
550            mPrepareSync = false;
551            mPrepareStatus = ext1;
552            mSignal.signal();
553            send = false;
554        }
555        break;
556    case MEDIA_INFO:
557        // ext1: Media framework error code.
558        // ext2: Implementation dependant error code.
559        LOGW("info/warning (%d, %d)", ext1, ext2);
560        break;
561    case MEDIA_SEEK_COMPLETE:
562        LOGV("Received seek complete");
563        if (mSeekPosition != mCurrentPosition) {
564            LOGV("Executing queued seekTo(%d)", mSeekPosition);
565            mSeekPosition = -1;
566            seekTo_l(mCurrentPosition);
567        }
568        else {
569            LOGV("All seeks complete - return to regularly scheduled program");
570            mCurrentPosition = mSeekPosition = -1;
571        }
572        break;
573    case MEDIA_BUFFERING_UPDATE:
574        LOGV("buffering %d", ext1);
575        break;
576    case MEDIA_SET_VIDEO_SIZE:
577        LOGV("New video size %d x %d", ext1, ext2);
578        mVideoWidth = ext1;
579        mVideoHeight = ext2;
580        break;
581    default:
582        LOGV("unrecognized message: (%d, %d, %d)", msg, ext1, ext2);
583        break;
584    }
585
586    sp<MediaPlayerListener> listener = mListener;
587    if (locked) mLock.unlock();
588
589    // this prevents re-entrant calls into client code
590    if ((listener != 0) && send) {
591        Mutex::Autolock _l(mNotifyLock);
592        LOGV("callback application");
593        listener->notify(msg, ext1, ext2);
594        LOGV("back from callback");
595    }
596}
597
598void MediaPlayer::DeathNotifier::binderDied(const wp<IBinder>& who) {
599    LOGW("MediaPlayer server died!");
600
601    // Need to do this with the lock held
602    SortedVector< wp<MediaPlayer> > list;
603    {
604        Mutex::Autolock _l(MediaPlayer::sServiceLock);
605        MediaPlayer::sMediaPlayerService.clear();
606        list = sObitRecipients;
607    }
608
609    // Notify application when media server dies.
610    // Don't hold the static lock during callback in case app
611    // makes a call that needs the lock.
612    size_t count = list.size();
613    for (size_t iter = 0; iter < count; ++iter) {
614        sp<MediaPlayer> player = list[iter].promote();
615        if ((player != 0) && (player->mPlayer != 0)) {
616            player->notify(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, 0);
617        }
618    }
619}
620
621MediaPlayer::DeathNotifier::~DeathNotifier()
622{
623    Mutex::Autolock _l(sServiceLock);
624    sObitRecipients.clear();
625    if (sMediaPlayerService != 0) {
626        sMediaPlayerService->asBinder()->unlinkToDeath(this);
627    }
628}
629
630/*static*/ sp<IMemory> MediaPlayer::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
631{
632    LOGV("decode(%s)", url);
633    sp<IMemory> p;
634    const sp<IMediaPlayerService>& service = getMediaPlayerService();
635    if (service != 0) {
636        p = sMediaPlayerService->decode(url, pSampleRate, pNumChannels, pFormat);
637    } else {
638        LOGE("Unable to locate media service");
639    }
640    return p;
641
642}
643
644/*static*/ sp<IMemory> MediaPlayer::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
645{
646    LOGV("decode(%d, %lld, %lld)", fd, offset, length);
647    sp<IMemory> p;
648    const sp<IMediaPlayerService>& service = getMediaPlayerService();
649    if (service != 0) {
650        p = sMediaPlayerService->decode(fd, offset, length, pSampleRate, pNumChannels, pFormat);
651    } else {
652        LOGE("Unable to locate media service");
653    }
654    return p;
655
656}
657
658}; // namespace android
659