mediaplayer.cpp revision 8e1b6cce24574b9ecd5b0300155776bd0b4ef756
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::invoke(const Parcel& request, Parcel *reply)
200{
201    Mutex::Autolock _l(mLock);
202    if ((mPlayer != NULL) && ( mCurrentState & MEDIA_PLAYER_INITIALIZED ))
203    {
204         LOGV("invoke %d", request.dataSize());
205         return  mPlayer->invoke(request, reply);
206    }
207    LOGE("invoke failed: wrong state %X", mCurrentState);
208    return INVALID_OPERATION;
209}
210
211status_t MediaPlayer::setMetadataFilter(const Parcel& filter)
212{
213    LOGD("setMetadataFilter");
214    Mutex::Autolock lock(mLock);
215    if (mPlayer == NULL) {
216        return NO_INIT;
217    }
218    return mPlayer->setMetadataFilter(filter);
219}
220
221status_t MediaPlayer::getMetadata(bool update_only, bool apply_filter, Parcel *metadata)
222{
223    LOGD("getMetadata");
224    Mutex::Autolock lock(mLock);
225    if (mPlayer == NULL) {
226        return NO_INIT;
227    }
228    return mPlayer->getMetadata(update_only, apply_filter, metadata);
229}
230
231status_t MediaPlayer::setVideoSurface(const sp<Surface>& surface)
232{
233    LOGV("setVideoSurface");
234    Mutex::Autolock _l(mLock);
235    if (mPlayer == 0) return NO_INIT;
236    return  mPlayer->setVideoSurface(surface->getISurface());
237}
238
239// must call with lock held
240status_t MediaPlayer::prepareAsync_l()
241{
242    if ( (mPlayer != 0) && ( mCurrentState & ( MEDIA_PLAYER_INITIALIZED | MEDIA_PLAYER_STOPPED) ) ) {
243        mPlayer->setAudioStreamType(mStreamType);
244        mCurrentState = MEDIA_PLAYER_PREPARING;
245        return mPlayer->prepareAsync();
246    }
247    LOGE("prepareAsync called in state %d", mCurrentState);
248    return INVALID_OPERATION;
249}
250
251// TODO: In case of error, prepareAsync provides the caller with 2 error codes,
252// one defined in the Android framework and one provided by the implementation
253// that generated the error. The sync version of prepare returns only 1 error
254// code.
255status_t MediaPlayer::prepare()
256{
257    LOGV("prepare");
258    Mutex::Autolock _l(mLock);
259    mLockThreadId = getThreadId();
260    if (mPrepareSync) {
261        mLockThreadId = 0;
262        return -EALREADY;
263    }
264    mPrepareSync = true;
265    status_t ret = prepareAsync_l();
266    if (ret != NO_ERROR) {
267        mLockThreadId = 0;
268        return ret;
269    }
270
271    if (mPrepareSync) {
272        mSignal.wait(mLock);  // wait for prepare done
273        mPrepareSync = false;
274    }
275    LOGV("prepare complete - status=%d", mPrepareStatus);
276    mLockThreadId = 0;
277    return mPrepareStatus;
278}
279
280status_t MediaPlayer::prepareAsync()
281{
282    LOGV("prepareAsync");
283    Mutex::Autolock _l(mLock);
284    return prepareAsync_l();
285}
286
287status_t MediaPlayer::start()
288{
289    LOGV("start");
290    Mutex::Autolock _l(mLock);
291    if (mCurrentState & MEDIA_PLAYER_STARTED)
292        return NO_ERROR;
293    if ( (mPlayer != 0) && ( mCurrentState & ( MEDIA_PLAYER_PREPARED |
294                    MEDIA_PLAYER_PLAYBACK_COMPLETE | MEDIA_PLAYER_PAUSED ) ) ) {
295        mPlayer->setLooping(mLoop);
296        mPlayer->setVolume(mLeftVolume, mRightVolume);
297        mCurrentState = MEDIA_PLAYER_STARTED;
298        status_t ret = mPlayer->start();
299        if (ret != NO_ERROR) {
300            mCurrentState = MEDIA_PLAYER_STATE_ERROR;
301        } else {
302            if (mCurrentState == MEDIA_PLAYER_PLAYBACK_COMPLETE) {
303                LOGV("playback completed immediately following start()");
304            }
305        }
306        return ret;
307    }
308    LOGE("start called in state %d", mCurrentState);
309    return INVALID_OPERATION;
310}
311
312status_t MediaPlayer::stop()
313{
314    LOGV("stop");
315    Mutex::Autolock _l(mLock);
316    if (mCurrentState & MEDIA_PLAYER_STOPPED) return NO_ERROR;
317    if ( (mPlayer != 0) && ( mCurrentState & ( MEDIA_PLAYER_STARTED | MEDIA_PLAYER_PREPARED |
318                    MEDIA_PLAYER_PAUSED | MEDIA_PLAYER_PLAYBACK_COMPLETE ) ) ) {
319        status_t ret = mPlayer->stop();
320        if (ret != NO_ERROR) {
321            mCurrentState = MEDIA_PLAYER_STATE_ERROR;
322        } else {
323            mCurrentState = MEDIA_PLAYER_STOPPED;
324        }
325        return ret;
326    }
327    LOGE("stop called in state %d", mCurrentState);
328    return INVALID_OPERATION;
329}
330
331status_t MediaPlayer::pause()
332{
333    LOGV("pause");
334    Mutex::Autolock _l(mLock);
335    if (mCurrentState & MEDIA_PLAYER_PAUSED)
336        return NO_ERROR;
337    if ((mPlayer != 0) && (mCurrentState & MEDIA_PLAYER_STARTED)) {
338        status_t ret = mPlayer->pause();
339        if (ret != NO_ERROR) {
340            mCurrentState = MEDIA_PLAYER_STATE_ERROR;
341        } else {
342            mCurrentState = MEDIA_PLAYER_PAUSED;
343        }
344        return ret;
345    }
346    LOGE("pause called in state %d", mCurrentState);
347    return INVALID_OPERATION;
348}
349
350bool MediaPlayer::isPlaying()
351{
352    Mutex::Autolock _l(mLock);
353    if (mPlayer != 0) {
354        bool temp = false;
355        mPlayer->isPlaying(&temp);
356        LOGV("isPlaying: %d", temp);
357        if ((mCurrentState & MEDIA_PLAYER_STARTED) && ! temp) {
358            LOGE("internal/external state mismatch corrected");
359            mCurrentState = MEDIA_PLAYER_PAUSED;
360        }
361        return temp;
362    }
363    LOGV("isPlaying: no active player");
364    return false;
365}
366
367status_t MediaPlayer::getVideoWidth(int *w)
368{
369    LOGV("getVideoWidth");
370    Mutex::Autolock _l(mLock);
371    if (mPlayer == 0) return INVALID_OPERATION;
372    *w = mVideoWidth;
373    return NO_ERROR;
374}
375
376status_t MediaPlayer::getVideoHeight(int *h)
377{
378    LOGV("getVideoHeight");
379    Mutex::Autolock _l(mLock);
380    if (mPlayer == 0) return INVALID_OPERATION;
381    *h = mVideoHeight;
382    return NO_ERROR;
383}
384
385status_t MediaPlayer::getCurrentPosition(int *msec)
386{
387    LOGV("getCurrentPosition");
388    Mutex::Autolock _l(mLock);
389    if (mPlayer != 0) {
390        if (mCurrentPosition >= 0) {
391            LOGV("Using cached seek position: %d", mCurrentPosition);
392            *msec = mCurrentPosition;
393            return NO_ERROR;
394        }
395        return mPlayer->getCurrentPosition(msec);
396    }
397    return INVALID_OPERATION;
398}
399
400status_t MediaPlayer::getDuration_l(int *msec)
401{
402    LOGV("getDuration");
403    bool isValidState = (mCurrentState & (MEDIA_PLAYER_PREPARED | MEDIA_PLAYER_STARTED | MEDIA_PLAYER_PAUSED | MEDIA_PLAYER_STOPPED | MEDIA_PLAYER_PLAYBACK_COMPLETE));
404    if (mPlayer != 0 && isValidState) {
405        status_t ret = NO_ERROR;
406        if (mDuration <= 0)
407            ret = mPlayer->getDuration(&mDuration);
408        if (msec)
409            *msec = mDuration;
410        return ret;
411    }
412    LOGE("Attempt to call getDuration without a valid mediaplayer");
413    return INVALID_OPERATION;
414}
415
416status_t MediaPlayer::getDuration(int *msec)
417{
418    Mutex::Autolock _l(mLock);
419    return getDuration_l(msec);
420}
421
422status_t MediaPlayer::seekTo_l(int msec)
423{
424    LOGV("seekTo %d", msec);
425    if ((mPlayer != 0) && ( mCurrentState & ( MEDIA_PLAYER_STARTED | MEDIA_PLAYER_PREPARED | MEDIA_PLAYER_PAUSED |  MEDIA_PLAYER_PLAYBACK_COMPLETE) ) ) {
426        if ( msec < 0 ) {
427            LOGW("Attempt to seek to invalid position: %d", msec);
428            msec = 0;
429        } else if ((mDuration > 0) && (msec > mDuration)) {
430            LOGW("Attempt to seek to past end of file: request = %d, EOF = %d", msec, mDuration);
431            msec = mDuration;
432        }
433        // cache duration
434        mCurrentPosition = msec;
435        if (mSeekPosition < 0) {
436            getDuration_l(NULL);
437            mSeekPosition = msec;
438            return mPlayer->seekTo(msec);
439        }
440        else {
441            LOGV("Seek in progress - queue up seekTo[%d]", msec);
442            return NO_ERROR;
443        }
444    }
445    LOGE("Attempt to perform seekTo in wrong state: mPlayer=%p, mCurrentState=%u", mPlayer.get(), mCurrentState);
446    return INVALID_OPERATION;
447}
448
449status_t MediaPlayer::seekTo(int msec)
450{
451    mLockThreadId = getThreadId();
452    Mutex::Autolock _l(mLock);
453    status_t result = seekTo_l(msec);
454    mLockThreadId = 0;
455
456    return result;
457}
458
459status_t MediaPlayer::reset()
460{
461    LOGV("reset");
462    Mutex::Autolock _l(mLock);
463    mLoop = false;
464    if (mCurrentState == MEDIA_PLAYER_IDLE) return NO_ERROR;
465    mPrepareSync = false;
466    if (mPlayer != 0) {
467        status_t ret = mPlayer->reset();
468        if (ret != NO_ERROR) {
469            LOGE("reset() failed with return code (%d)", ret);
470            mCurrentState = MEDIA_PLAYER_STATE_ERROR;
471        } else {
472            mCurrentState = MEDIA_PLAYER_IDLE;
473        }
474        return ret;
475    }
476    clear_l();
477    return NO_ERROR;
478}
479
480status_t MediaPlayer::setAudioStreamType(int type)
481{
482    LOGV("MediaPlayer::setAudioStreamType");
483    Mutex::Autolock _l(mLock);
484    if (mStreamType == type) return NO_ERROR;
485    if (mCurrentState & ( MEDIA_PLAYER_PREPARED | MEDIA_PLAYER_STARTED |
486                MEDIA_PLAYER_PAUSED | MEDIA_PLAYER_PLAYBACK_COMPLETE ) ) {
487        // Can't change the stream type after prepare
488        LOGE("setAudioStream called in state %d", mCurrentState);
489        return INVALID_OPERATION;
490    }
491    // cache
492    mStreamType = type;
493    return OK;
494}
495
496status_t MediaPlayer::setLooping(int loop)
497{
498    LOGV("MediaPlayer::setLooping");
499    Mutex::Autolock _l(mLock);
500    mLoop = (loop != 0);
501    if (mPlayer != 0) {
502        return mPlayer->setLooping(loop);
503    }
504    return OK;
505}
506
507bool MediaPlayer::isLooping() {
508    LOGV("isLooping");
509    Mutex::Autolock _l(mLock);
510    if (mPlayer != 0) {
511        return mLoop;
512    }
513    LOGV("isLooping: no active player");
514    return false;
515}
516
517status_t MediaPlayer::setVolume(float leftVolume, float rightVolume)
518{
519    LOGV("MediaPlayer::setVolume(%f, %f)", leftVolume, rightVolume);
520    Mutex::Autolock _l(mLock);
521    mLeftVolume = leftVolume;
522    mRightVolume = rightVolume;
523    if (mPlayer != 0) {
524        return mPlayer->setVolume(leftVolume, rightVolume);
525    }
526    return OK;
527}
528
529void MediaPlayer::notify(int msg, int ext1, int ext2)
530{
531    LOGV("message received msg=%d, ext1=%d, ext2=%d", msg, ext1, ext2);
532    bool send = true;
533    bool locked = false;
534
535    // TODO: In the future, we might be on the same thread if the app is
536    // running in the same process as the media server. In that case,
537    // this will deadlock.
538    //
539    // The threadId hack below works around this for the care of prepare
540    // and seekTo within the same process.
541    // FIXME: Remember, this is a hack, it's not even a hack that is applied
542    // consistently for all use-cases, this needs to be revisited.
543     if (mLockThreadId != getThreadId()) {
544        mLock.lock();
545        locked = true;
546    }
547
548    if (mPlayer == 0) {
549        LOGV("notify(%d, %d, %d) callback on disconnected mediaplayer", msg, ext1, ext2);
550        if (locked) mLock.unlock();   // release the lock when done.
551        return;
552    }
553
554    switch (msg) {
555    case MEDIA_NOP: // interface test message
556        break;
557    case MEDIA_PREPARED:
558        LOGV("prepared");
559        mCurrentState = MEDIA_PLAYER_PREPARED;
560        if (mPrepareSync) {
561            LOGV("signal application thread");
562            mPrepareSync = false;
563            mPrepareStatus = NO_ERROR;
564            mSignal.signal();
565        }
566        break;
567    case MEDIA_PLAYBACK_COMPLETE:
568        LOGV("playback complete");
569        if (!mLoop) {
570            mCurrentState = MEDIA_PLAYER_PLAYBACK_COMPLETE;
571        }
572        break;
573    case MEDIA_ERROR:
574        // Always log errors.
575        // ext1: Media framework error code.
576        // ext2: Implementation dependant error code.
577        LOGE("error (%d, %d)", ext1, ext2);
578        mCurrentState = MEDIA_PLAYER_STATE_ERROR;
579        if (mPrepareSync)
580        {
581            LOGV("signal application thread");
582            mPrepareSync = false;
583            mPrepareStatus = ext1;
584            mSignal.signal();
585            send = false;
586        }
587        break;
588    case MEDIA_INFO:
589        // ext1: Media framework error code.
590        // ext2: Implementation dependant error code.
591        LOGW("info/warning (%d, %d)", ext1, ext2);
592        break;
593    case MEDIA_SEEK_COMPLETE:
594        LOGV("Received seek complete");
595        if (mSeekPosition != mCurrentPosition) {
596            LOGV("Executing queued seekTo(%d)", mSeekPosition);
597            mSeekPosition = -1;
598            seekTo_l(mCurrentPosition);
599        }
600        else {
601            LOGV("All seeks complete - return to regularly scheduled program");
602            mCurrentPosition = mSeekPosition = -1;
603        }
604        break;
605    case MEDIA_BUFFERING_UPDATE:
606        LOGV("buffering %d", ext1);
607        break;
608    case MEDIA_SET_VIDEO_SIZE:
609        LOGV("New video size %d x %d", ext1, ext2);
610        mVideoWidth = ext1;
611        mVideoHeight = ext2;
612        break;
613    default:
614        LOGV("unrecognized message: (%d, %d, %d)", msg, ext1, ext2);
615        break;
616    }
617
618    sp<MediaPlayerListener> listener = mListener;
619    if (locked) mLock.unlock();
620
621    // this prevents re-entrant calls into client code
622    if ((listener != 0) && send) {
623        Mutex::Autolock _l(mNotifyLock);
624        LOGV("callback application");
625        listener->notify(msg, ext1, ext2);
626        LOGV("back from callback");
627    }
628}
629
630void MediaPlayer::DeathNotifier::binderDied(const wp<IBinder>& who) {
631    LOGW("MediaPlayer server died!");
632
633    // Need to do this with the lock held
634    SortedVector< wp<MediaPlayer> > list;
635    {
636        Mutex::Autolock _l(MediaPlayer::sServiceLock);
637        MediaPlayer::sMediaPlayerService.clear();
638        list = sObitRecipients;
639    }
640
641    // Notify application when media server dies.
642    // Don't hold the static lock during callback in case app
643    // makes a call that needs the lock.
644    size_t count = list.size();
645    for (size_t iter = 0; iter < count; ++iter) {
646        sp<MediaPlayer> player = list[iter].promote();
647        if ((player != 0) && (player->mPlayer != 0)) {
648            player->notify(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, 0);
649        }
650    }
651}
652
653MediaPlayer::DeathNotifier::~DeathNotifier()
654{
655    Mutex::Autolock _l(sServiceLock);
656    sObitRecipients.clear();
657    if (sMediaPlayerService != 0) {
658        sMediaPlayerService->asBinder()->unlinkToDeath(this);
659    }
660}
661
662/*static*/ sp<IMemory> MediaPlayer::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
663{
664    LOGV("decode(%s)", url);
665    sp<IMemory> p;
666    const sp<IMediaPlayerService>& service = getMediaPlayerService();
667    if (service != 0) {
668        p = sMediaPlayerService->decode(url, pSampleRate, pNumChannels, pFormat);
669    } else {
670        LOGE("Unable to locate media service");
671    }
672    return p;
673
674}
675
676/*static*/ sp<IMemory> MediaPlayer::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
677{
678    LOGV("decode(%d, %lld, %lld)", fd, offset, length);
679    sp<IMemory> p;
680    const sp<IMediaPlayerService>& service = getMediaPlayerService();
681    if (service != 0) {
682        p = sMediaPlayerService->decode(fd, offset, length, pSampleRate, pNumChannels, pFormat);
683    } else {
684        LOGE("Unable to locate media service");
685    }
686    return p;
687
688}
689
690}; // namespace android
691