• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 "MediaPlayerNative"
20 #include <utils/Log.h>
21 
22 #include <fcntl.h>
23 #include <inttypes.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 #include <unistd.h>
27 
28 
29 #include <android/IDataSource.h>
30 #include <binder/IPCThreadState.h>
31 #include <media/mediaplayer.h>
32 #include <media/AudioResamplerPublic.h>
33 #include <media/AudioSystem.h>
34 #include <media/AVSyncSettings.h>
35 #include <utils/KeyedVector.h>
36 #include <utils/String8.h>
37 #include <system/audio.h>
38 #include <system/window.h>
39 
40 namespace android {
41 
42 using media::VolumeShaper;
43 using content::AttributionSourceState;
44 
MediaPlayer(const AttributionSourceState & attributionSource,const audio_session_t sessionId)45 MediaPlayer::MediaPlayer(const AttributionSourceState& attributionSource,
46     const audio_session_t sessionId) : mAttributionSource(attributionSource)
47 {
48     ALOGV("constructor");
49     mListener = NULL;
50     mCookie = NULL;
51     mStreamType = AUDIO_STREAM_MUSIC;
52     mAudioAttributesParcel = NULL;
53     mCurrentPosition = -1;
54     mCurrentSeekMode = MediaPlayerSeekMode::SEEK_PREVIOUS_SYNC;
55     mSeekPosition = -1;
56     mSeekMode = MediaPlayerSeekMode::SEEK_PREVIOUS_SYNC;
57     mCurrentState = MEDIA_PLAYER_IDLE;
58     mPrepareSync = false;
59     mPrepareStatus = NO_ERROR;
60     mLoop = false;
61     mLeftVolume = mRightVolume = 1.0;
62     mVideoWidth = mVideoHeight = 0;
63     mLockThreadId = 0;
64     if (sessionId == AUDIO_SESSION_ALLOCATE) {
65         mAudioSessionId = static_cast<audio_session_t>(
66             AudioSystem::newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION));
67     } else {
68         mAudioSessionId = sessionId;
69     }
70     AudioSystem::acquireAudioSessionId(mAudioSessionId, (pid_t)-1, (uid_t)-1); // always in client.
71     mSendLevel = 0;
72     mRetransmitEndpointValid = false;
73 }
74 
~MediaPlayer()75 MediaPlayer::~MediaPlayer()
76 {
77     ALOGV("destructor");
78     if (mAudioAttributesParcel != NULL) {
79         delete mAudioAttributesParcel;
80         mAudioAttributesParcel = NULL;
81     }
82     AudioSystem::releaseAudioSessionId(mAudioSessionId, (pid_t)-1);
83     disconnect();
84     IPCThreadState::self()->flushCommands();
85 }
86 
disconnect()87 void MediaPlayer::disconnect()
88 {
89     ALOGV("disconnect");
90     sp<IMediaPlayer> p;
91     {
92         Mutex::Autolock _l(mLock);
93         p = mPlayer;
94         mPlayer.clear();
95     }
96 
97     if (p != 0) {
98         p->disconnect();
99     }
100 }
101 
102 // always call with lock held
clear_l()103 void MediaPlayer::clear_l()
104 {
105     mCurrentPosition = -1;
106     mCurrentSeekMode = MediaPlayerSeekMode::SEEK_PREVIOUS_SYNC;
107     mSeekPosition = -1;
108     mSeekMode = MediaPlayerSeekMode::SEEK_PREVIOUS_SYNC;
109     mVideoWidth = mVideoHeight = 0;
110     mRetransmitEndpointValid = false;
111 }
112 
setListener(const sp<MediaPlayerListener> & listener)113 status_t MediaPlayer::setListener(const sp<MediaPlayerListener>& listener)
114 {
115     ALOGV("setListener");
116     Mutex::Autolock _l(mLock);
117     mListener = listener;
118     return NO_ERROR;
119 }
120 
121 
attachNewPlayer(const sp<IMediaPlayer> & player)122 status_t MediaPlayer::attachNewPlayer(const sp<IMediaPlayer>& player)
123 {
124     status_t err = UNKNOWN_ERROR;
125     sp<IMediaPlayer> p;
126     { // scope for the lock
127         Mutex::Autolock _l(mLock);
128 
129         if ( !( (mCurrentState & MEDIA_PLAYER_IDLE) ||
130                 (mCurrentState == MEDIA_PLAYER_STATE_ERROR ) ) ) {
131             ALOGE("attachNewPlayer called in state %d", mCurrentState);
132             return INVALID_OPERATION;
133         }
134 
135         clear_l();
136         p = mPlayer;
137         mPlayer = player;
138         if (player != 0) {
139             mCurrentState = MEDIA_PLAYER_INITIALIZED;
140             err = NO_ERROR;
141         } else {
142             ALOGE("Unable to create media player");
143         }
144     }
145 
146     if (p != 0) {
147         p->disconnect();
148     }
149 
150     return err;
151 }
152 
setDataSource(const sp<IMediaHTTPService> & httpService,const char * url,const KeyedVector<String8,String8> * headers)153 status_t MediaPlayer::setDataSource(
154         const sp<IMediaHTTPService> &httpService,
155         const char *url, const KeyedVector<String8, String8> *headers)
156 {
157     ALOGV("setDataSource(%s)", url);
158     status_t err = BAD_VALUE;
159     if (url != NULL) {
160         const sp<IMediaPlayerService> service(getMediaPlayerService());
161         if (service != 0) {
162             sp<IMediaPlayer> player(service->create(this, mAudioSessionId, mAttributionSource));
163             if ((NO_ERROR != doSetRetransmitEndpoint(player)) ||
164                 (NO_ERROR != player->setDataSource(httpService, url, headers))) {
165                 player.clear();
166             }
167             err = attachNewPlayer(player);
168         }
169     }
170     return err;
171 }
172 
setDataSource(int fd,int64_t offset,int64_t length)173 status_t MediaPlayer::setDataSource(int fd, int64_t offset, int64_t length)
174 {
175     ALOGV("setDataSource(%d, %" PRId64 ", %" PRId64 ")", fd, offset, length);
176     status_t err = UNKNOWN_ERROR;
177     const sp<IMediaPlayerService> service(getMediaPlayerService());
178     if (service != 0) {
179         sp<IMediaPlayer> player(service->create(this, mAudioSessionId, mAttributionSource));
180         if ((NO_ERROR != doSetRetransmitEndpoint(player)) ||
181             (NO_ERROR != player->setDataSource(fd, offset, length))) {
182             player.clear();
183         }
184         err = attachNewPlayer(player);
185     }
186     return err;
187 }
188 
setDataSource(const sp<IDataSource> & source)189 status_t MediaPlayer::setDataSource(const sp<IDataSource> &source)
190 {
191     ALOGV("setDataSource(IDataSource)");
192     status_t err = UNKNOWN_ERROR;
193     const sp<IMediaPlayerService> service(getMediaPlayerService());
194     if (service != 0) {
195         sp<IMediaPlayer> player(service->create(this, mAudioSessionId, mAttributionSource));
196         if ((NO_ERROR != doSetRetransmitEndpoint(player)) ||
197             (NO_ERROR != player->setDataSource(source))) {
198             player.clear();
199         }
200         err = attachNewPlayer(player);
201     }
202     return err;
203 }
204 
setDataSource(const String8 & rtpParams)205 status_t MediaPlayer::setDataSource(const String8& rtpParams)
206 {
207     ALOGV("setDataSource(rtpParams)");
208     status_t err = UNKNOWN_ERROR;
209     const sp<IMediaPlayerService> service(getMediaPlayerService());
210     if (service != 0) {
211         sp<IMediaPlayer> player(service->create(this, mAudioSessionId, mAttributionSource));
212         if ((NO_ERROR != doSetRetransmitEndpoint(player)) ||
213             (NO_ERROR != player->setDataSource(rtpParams))) {
214             player.clear();
215         }
216         err = attachNewPlayer(player);
217     }
218     return err;
219 }
220 
invoke(const Parcel & request,Parcel * reply)221 status_t MediaPlayer::invoke(const Parcel& request, Parcel *reply)
222 {
223     Mutex::Autolock _l(mLock);
224     const bool hasBeenInitialized =
225             (mCurrentState != MEDIA_PLAYER_STATE_ERROR) &&
226             ((mCurrentState & MEDIA_PLAYER_IDLE) != MEDIA_PLAYER_IDLE);
227     if ((mPlayer != NULL) && hasBeenInitialized) {
228         ALOGV("invoke %zu", request.dataSize());
229         return  mPlayer->invoke(request, reply);
230     }
231     ALOGE("invoke failed: wrong state %X, mPlayer(%p)", mCurrentState, mPlayer.get());
232     return INVALID_OPERATION;
233 }
234 
setMetadataFilter(const Parcel & filter)235 status_t MediaPlayer::setMetadataFilter(const Parcel& filter)
236 {
237     ALOGD("setMetadataFilter");
238     Mutex::Autolock lock(mLock);
239     if (mPlayer == NULL) {
240         return NO_INIT;
241     }
242     return mPlayer->setMetadataFilter(filter);
243 }
244 
getMetadata(bool update_only,bool apply_filter,Parcel * metadata)245 status_t MediaPlayer::getMetadata(bool update_only, bool apply_filter, Parcel *metadata)
246 {
247     ALOGD("getMetadata");
248     Mutex::Autolock lock(mLock);
249     if (mPlayer == NULL) {
250         return NO_INIT;
251     }
252     return mPlayer->getMetadata(update_only, apply_filter, metadata);
253 }
254 
setVideoSurfaceTexture(const sp<IGraphicBufferProducer> & bufferProducer)255 status_t MediaPlayer::setVideoSurfaceTexture(
256         const sp<IGraphicBufferProducer>& bufferProducer)
257 {
258     ALOGV("setVideoSurfaceTexture");
259     Mutex::Autolock _l(mLock);
260     if (mPlayer == 0) return NO_INIT;
261     return mPlayer->setVideoSurfaceTexture(bufferProducer);
262 }
263 
getBufferingSettings(BufferingSettings * buffering)264 status_t MediaPlayer::getBufferingSettings(BufferingSettings* buffering /* nonnull */)
265 {
266     ALOGV("getBufferingSettings");
267 
268     Mutex::Autolock _l(mLock);
269     if (mPlayer == 0) {
270         return NO_INIT;
271     }
272     return mPlayer->getBufferingSettings(buffering);
273 }
274 
setBufferingSettings(const BufferingSettings & buffering)275 status_t MediaPlayer::setBufferingSettings(const BufferingSettings& buffering)
276 {
277     ALOGV("setBufferingSettings");
278 
279     Mutex::Autolock _l(mLock);
280     if (mPlayer == 0) {
281         return NO_INIT;
282     }
283     return mPlayer->setBufferingSettings(buffering);
284 }
285 
286 // must call with lock held
prepareAsync_l()287 status_t MediaPlayer::prepareAsync_l()
288 {
289     if ( (mPlayer != 0) && ( mCurrentState & (MEDIA_PLAYER_INITIALIZED | MEDIA_PLAYER_STOPPED) ) ) {
290         if (mAudioAttributesParcel != NULL) {
291             mPlayer->setParameter(KEY_PARAMETER_AUDIO_ATTRIBUTES, *mAudioAttributesParcel);
292         } else {
293             mPlayer->setAudioStreamType(mStreamType);
294         }
295         mCurrentState = MEDIA_PLAYER_PREPARING;
296         return mPlayer->prepareAsync();
297     }
298     ALOGE("prepareAsync called in state %d, mPlayer(%p)", mCurrentState, mPlayer.get());
299     return INVALID_OPERATION;
300 }
301 
302 // TODO: In case of error, prepareAsync provides the caller with 2 error codes,
303 // one defined in the Android framework and one provided by the implementation
304 // that generated the error. The sync version of prepare returns only 1 error
305 // code.
prepare()306 status_t MediaPlayer::prepare()
307 {
308     ALOGV("prepare");
309     Mutex::Autolock _l(mLock);
310     mLockThreadId = getThreadId();
311     if (mPrepareSync) {
312         mLockThreadId = 0;
313         return -EALREADY;
314     }
315     mPrepareSync = true;
316     status_t ret = prepareAsync_l();
317     if (ret != NO_ERROR) {
318         mLockThreadId = 0;
319         return ret;
320     }
321 
322     if (mPrepareSync) {
323         mSignal.wait(mLock);  // wait for prepare done
324         mPrepareSync = false;
325     }
326     ALOGV("prepare complete - status=%d", mPrepareStatus);
327     mLockThreadId = 0;
328     return mPrepareStatus;
329 }
330 
prepareAsync()331 status_t MediaPlayer::prepareAsync()
332 {
333     ALOGV("prepareAsync");
334     Mutex::Autolock _l(mLock);
335     return prepareAsync_l();
336 }
337 
start()338 status_t MediaPlayer::start()
339 {
340     ALOGV("start");
341 
342     status_t ret = NO_ERROR;
343     Mutex::Autolock _l(mLock);
344 
345     mLockThreadId = getThreadId();
346 
347     if (mCurrentState & MEDIA_PLAYER_STARTED) {
348         ret = NO_ERROR;
349     } else if ( (mPlayer != 0) && ( mCurrentState & ( MEDIA_PLAYER_PREPARED |
350                     MEDIA_PLAYER_PLAYBACK_COMPLETE | MEDIA_PLAYER_PAUSED ) ) ) {
351         mPlayer->setLooping(mLoop);
352         mPlayer->setVolume(mLeftVolume, mRightVolume);
353         mPlayer->setAuxEffectSendLevel(mSendLevel);
354         mCurrentState = MEDIA_PLAYER_STARTED;
355         ret = mPlayer->start();
356         if (ret != NO_ERROR) {
357             mCurrentState = MEDIA_PLAYER_STATE_ERROR;
358         } else {
359             if (mCurrentState == MEDIA_PLAYER_PLAYBACK_COMPLETE) {
360                 ALOGV("playback completed immediately following start()");
361             }
362         }
363     } else {
364         ALOGE("start called in state %d, mPlayer(%p)", mCurrentState, mPlayer.get());
365         ret = INVALID_OPERATION;
366     }
367 
368     mLockThreadId = 0;
369 
370     return ret;
371 }
372 
stop()373 status_t MediaPlayer::stop()
374 {
375     ALOGV("stop");
376     Mutex::Autolock _l(mLock);
377     if (mCurrentState & MEDIA_PLAYER_STOPPED) return NO_ERROR;
378     if ( (mPlayer != 0) && ( mCurrentState & ( MEDIA_PLAYER_STARTED | MEDIA_PLAYER_PREPARED |
379                     MEDIA_PLAYER_PAUSED | MEDIA_PLAYER_PLAYBACK_COMPLETE ) ) ) {
380         status_t ret = mPlayer->stop();
381         if (ret != NO_ERROR) {
382             mCurrentState = MEDIA_PLAYER_STATE_ERROR;
383         } else {
384             mCurrentState = MEDIA_PLAYER_STOPPED;
385         }
386         return ret;
387     }
388     ALOGE("stop called in state %d, mPlayer(%p)", mCurrentState, mPlayer.get());
389     return INVALID_OPERATION;
390 }
391 
pause()392 status_t MediaPlayer::pause()
393 {
394     ALOGV("pause");
395     Mutex::Autolock _l(mLock);
396     if (mCurrentState & (MEDIA_PLAYER_PAUSED|MEDIA_PLAYER_PLAYBACK_COMPLETE))
397         return NO_ERROR;
398     if ((mPlayer != 0) && (mCurrentState & MEDIA_PLAYER_STARTED)) {
399         status_t ret = mPlayer->pause();
400         if (ret != NO_ERROR) {
401             mCurrentState = MEDIA_PLAYER_STATE_ERROR;
402         } else {
403             mCurrentState = MEDIA_PLAYER_PAUSED;
404         }
405         return ret;
406     }
407     ALOGE("pause called in state %d, mPlayer(%p)", mCurrentState, mPlayer.get());
408     return INVALID_OPERATION;
409 }
410 
isPlaying()411 bool MediaPlayer::isPlaying()
412 {
413     Mutex::Autolock _l(mLock);
414     if (mPlayer != 0) {
415         bool temp = false;
416         mPlayer->isPlaying(&temp);
417         ALOGV("isPlaying: %d", temp);
418         if ((mCurrentState & MEDIA_PLAYER_STARTED) && ! temp) {
419             ALOGE("internal/external state mismatch corrected");
420             mCurrentState = MEDIA_PLAYER_PAUSED;
421         } else if ((mCurrentState & MEDIA_PLAYER_PAUSED) && temp) {
422             ALOGE("internal/external state mismatch corrected");
423             mCurrentState = MEDIA_PLAYER_STARTED;
424         }
425         return temp;
426     }
427     ALOGV("isPlaying: no active player");
428     return false;
429 }
430 
setPlaybackSettings(const AudioPlaybackRate & rate)431 status_t MediaPlayer::setPlaybackSettings(const AudioPlaybackRate& rate)
432 {
433     ALOGV("setPlaybackSettings: %f %f %d %d",
434             rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
435     // Negative speed and pitch does not make sense. Further validation will
436     // be done by the respective mediaplayers.
437     if (rate.mSpeed < 0.f || rate.mPitch < 0.f) {
438         return BAD_VALUE;
439     }
440     Mutex::Autolock _l(mLock);
441     if (mPlayer == 0 || (mCurrentState & MEDIA_PLAYER_STOPPED)) {
442         return INVALID_OPERATION;
443     }
444 
445     if (rate.mSpeed != 0.f && !(mCurrentState & MEDIA_PLAYER_STARTED)
446             && (mCurrentState & (MEDIA_PLAYER_PREPARED | MEDIA_PLAYER_PAUSED
447                     | MEDIA_PLAYER_PLAYBACK_COMPLETE))) {
448         mPlayer->setLooping(mLoop);
449         mPlayer->setVolume(mLeftVolume, mRightVolume);
450         mPlayer->setAuxEffectSendLevel(mSendLevel);
451     }
452 
453     status_t err = mPlayer->setPlaybackSettings(rate);
454     if (err == OK) {
455         if (rate.mSpeed == 0.f && mCurrentState == MEDIA_PLAYER_STARTED) {
456             mCurrentState = MEDIA_PLAYER_PAUSED;
457         } else if (rate.mSpeed != 0.f
458                 && (mCurrentState & (MEDIA_PLAYER_PREPARED | MEDIA_PLAYER_PAUSED
459                     | MEDIA_PLAYER_PLAYBACK_COMPLETE))) {
460             mCurrentState = MEDIA_PLAYER_STARTED;
461         }
462     }
463     return err;
464 }
465 
getPlaybackSettings(AudioPlaybackRate * rate)466 status_t MediaPlayer::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
467 {
468     Mutex::Autolock _l(mLock);
469     if (mPlayer == 0) return INVALID_OPERATION;
470     return mPlayer->getPlaybackSettings(rate);
471 }
472 
setSyncSettings(const AVSyncSettings & sync,float videoFpsHint)473 status_t MediaPlayer::setSyncSettings(const AVSyncSettings& sync, float videoFpsHint)
474 {
475     ALOGV("setSyncSettings: %u %u %f %f",
476             sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
477     Mutex::Autolock _l(mLock);
478     if (mPlayer == 0) return INVALID_OPERATION;
479     return mPlayer->setSyncSettings(sync, videoFpsHint);
480 }
481 
getSyncSettings(AVSyncSettings * sync,float * videoFps)482 status_t MediaPlayer::getSyncSettings(
483         AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
484 {
485     Mutex::Autolock _l(mLock);
486     if (mPlayer == 0) return INVALID_OPERATION;
487     return mPlayer->getSyncSettings(sync, videoFps);
488 }
489 
getVideoWidth(int * w)490 status_t MediaPlayer::getVideoWidth(int *w)
491 {
492     ALOGV("getVideoWidth");
493     Mutex::Autolock _l(mLock);
494     if (mPlayer == 0) return INVALID_OPERATION;
495     *w = mVideoWidth;
496     return NO_ERROR;
497 }
498 
getVideoHeight(int * h)499 status_t MediaPlayer::getVideoHeight(int *h)
500 {
501     ALOGV("getVideoHeight");
502     Mutex::Autolock _l(mLock);
503     if (mPlayer == 0) return INVALID_OPERATION;
504     *h = mVideoHeight;
505     return NO_ERROR;
506 }
507 
getCurrentPosition(int * msec)508 status_t MediaPlayer::getCurrentPosition(int *msec)
509 {
510     ALOGV("getCurrentPosition");
511     Mutex::Autolock _l(mLock);
512     if (mPlayer != 0) {
513         if (mCurrentPosition >= 0) {
514             ALOGV("Using cached seek position: %d", mCurrentPosition);
515             *msec = mCurrentPosition;
516             return NO_ERROR;
517         }
518         return mPlayer->getCurrentPosition(msec);
519     }
520     return INVALID_OPERATION;
521 }
522 
getDuration_l(int * msec)523 status_t MediaPlayer::getDuration_l(int *msec)
524 {
525     ALOGV("getDuration_l");
526     bool isValidState = (mCurrentState & (MEDIA_PLAYER_PREPARED | MEDIA_PLAYER_STARTED |
527             MEDIA_PLAYER_PAUSED | MEDIA_PLAYER_STOPPED | MEDIA_PLAYER_PLAYBACK_COMPLETE));
528     if (mPlayer != 0 && isValidState) {
529         int durationMs;
530         status_t ret = mPlayer->getDuration(&durationMs);
531 
532         if (ret != OK) {
533             // Do not enter error state just because no duration was available.
534             durationMs = -1;
535             ret = OK;
536         }
537 
538         if (msec) {
539             *msec = durationMs;
540         }
541         return ret;
542     }
543     ALOGE("Attempt to call getDuration in wrong state: mPlayer=%p, mCurrentState=%u",
544             mPlayer.get(), mCurrentState);
545     return INVALID_OPERATION;
546 }
547 
getDuration(int * msec)548 status_t MediaPlayer::getDuration(int *msec)
549 {
550     Mutex::Autolock _l(mLock);
551     return getDuration_l(msec);
552 }
553 
seekTo_l(int msec,MediaPlayerSeekMode mode)554 status_t MediaPlayer::seekTo_l(int msec, MediaPlayerSeekMode mode)
555 {
556     ALOGV("seekTo (%d, %d)", msec, mode);
557     if ((mPlayer != 0) && ( mCurrentState & ( MEDIA_PLAYER_STARTED | MEDIA_PLAYER_PREPARED |
558             MEDIA_PLAYER_PAUSED |  MEDIA_PLAYER_PLAYBACK_COMPLETE) ) ) {
559         if ( msec < 0 ) {
560             ALOGW("Attempt to seek to invalid position: %d", msec);
561             msec = 0;
562         }
563 
564         int durationMs;
565         status_t err = mPlayer->getDuration(&durationMs);
566 
567         if (err != OK) {
568             ALOGW("Stream has no duration and is therefore not seekable.");
569             return err;
570         }
571 
572         if (msec > durationMs) {
573             ALOGW("Attempt to seek to past end of file: request = %d, "
574                   "durationMs = %d",
575                   msec,
576                   durationMs);
577 
578             msec = durationMs;
579         }
580 
581         // cache duration
582         mCurrentPosition = msec;
583         mCurrentSeekMode = mode;
584         if (mSeekPosition < 0) {
585             mSeekPosition = msec;
586             mSeekMode = mode;
587             return mPlayer->seekTo(msec, mode);
588         }
589         else {
590             ALOGV("Seek in progress - queue up seekTo[%d, %d]", msec, mode);
591             return NO_ERROR;
592         }
593     }
594     ALOGE("Attempt to perform seekTo in wrong state: mPlayer=%p, mCurrentState=%u", mPlayer.get(),
595             mCurrentState);
596     return INVALID_OPERATION;
597 }
598 
seekTo(int msec,MediaPlayerSeekMode mode)599 status_t MediaPlayer::seekTo(int msec, MediaPlayerSeekMode mode)
600 {
601     mLockThreadId = getThreadId();
602     Mutex::Autolock _l(mLock);
603     status_t result = seekTo_l(msec, mode);
604     mLockThreadId = 0;
605 
606     return result;
607 }
608 
notifyAt(int64_t mediaTimeUs)609 status_t MediaPlayer::notifyAt(int64_t mediaTimeUs)
610 {
611     Mutex::Autolock _l(mLock);
612     if (mPlayer != 0) {
613         return mPlayer->notifyAt(mediaTimeUs);
614     }
615     return INVALID_OPERATION;
616 }
617 
reset_l()618 status_t MediaPlayer::reset_l()
619 {
620     mLoop = false;
621     if (mCurrentState == MEDIA_PLAYER_IDLE) return NO_ERROR;
622     mPrepareSync = false;
623     if (mPlayer != 0) {
624         status_t ret = mPlayer->reset();
625         if (ret != NO_ERROR) {
626             ALOGE("reset() failed with return code (%d)", ret);
627             mCurrentState = MEDIA_PLAYER_STATE_ERROR;
628         } else {
629             mPlayer->disconnect();
630             mCurrentState = MEDIA_PLAYER_IDLE;
631         }
632         // setDataSource has to be called again to create a
633         // new mediaplayer.
634         mPlayer = 0;
635         return ret;
636     }
637     clear_l();
638     return NO_ERROR;
639 }
640 
doSetRetransmitEndpoint(const sp<IMediaPlayer> & player)641 status_t MediaPlayer::doSetRetransmitEndpoint(const sp<IMediaPlayer>& player) {
642     Mutex::Autolock _l(mLock);
643 
644     if (player == NULL) {
645         return UNKNOWN_ERROR;
646     }
647 
648     if (mRetransmitEndpointValid) {
649         return player->setRetransmitEndpoint(&mRetransmitEndpoint);
650     }
651 
652     return OK;
653 }
654 
reset()655 status_t MediaPlayer::reset()
656 {
657     ALOGV("reset");
658     mLockThreadId = getThreadId();
659     Mutex::Autolock _l(mLock);
660     status_t result = reset_l();
661     mLockThreadId = 0;
662 
663     return result;
664 }
665 
setAudioStreamType(audio_stream_type_t type)666 status_t MediaPlayer::setAudioStreamType(audio_stream_type_t type)
667 {
668     ALOGV("MediaPlayer::setAudioStreamType");
669     Mutex::Autolock _l(mLock);
670     if (mStreamType == type) return NO_ERROR;
671     if (mCurrentState & ( MEDIA_PLAYER_PREPARED | MEDIA_PLAYER_STARTED |
672                 MEDIA_PLAYER_PAUSED | MEDIA_PLAYER_PLAYBACK_COMPLETE ) ) {
673         // Can't change the stream type after prepare
674         ALOGE("setAudioStream called in state %d", mCurrentState);
675         return INVALID_OPERATION;
676     }
677     // cache
678     mStreamType = type;
679     return OK;
680 }
681 
getAudioStreamType(audio_stream_type_t * type)682 status_t MediaPlayer::getAudioStreamType(audio_stream_type_t *type)
683 {
684     ALOGV("getAudioStreamType");
685     Mutex::Autolock _l(mLock);
686     *type = mStreamType;
687     return OK;
688 }
689 
setLooping(int loop)690 status_t MediaPlayer::setLooping(int loop)
691 {
692     ALOGV("MediaPlayer::setLooping");
693     Mutex::Autolock _l(mLock);
694     mLoop = (loop != 0);
695     if (mPlayer != 0) {
696         return mPlayer->setLooping(loop);
697     }
698     return OK;
699 }
700 
isLooping()701 bool MediaPlayer::isLooping() {
702     ALOGV("isLooping");
703     Mutex::Autolock _l(mLock);
704     if (mPlayer != 0) {
705         return mLoop;
706     }
707     ALOGV("isLooping: no active player");
708     return false;
709 }
710 
setVolume(float leftVolume,float rightVolume)711 status_t MediaPlayer::setVolume(float leftVolume, float rightVolume)
712 {
713     ALOGV("MediaPlayer::setVolume(%f, %f)", leftVolume, rightVolume);
714     Mutex::Autolock _l(mLock);
715     mLeftVolume = leftVolume;
716     mRightVolume = rightVolume;
717     if (mPlayer != 0) {
718         return mPlayer->setVolume(leftVolume, rightVolume);
719     }
720     return OK;
721 }
722 
setAudioSessionId(audio_session_t sessionId)723 status_t MediaPlayer::setAudioSessionId(audio_session_t sessionId)
724 {
725     ALOGV("MediaPlayer::setAudioSessionId(%d)", sessionId);
726     Mutex::Autolock _l(mLock);
727     if (!(mCurrentState & MEDIA_PLAYER_IDLE)) {
728         ALOGE("setAudioSessionId called in state %d", mCurrentState);
729         return INVALID_OPERATION;
730     }
731     if (sessionId < 0) {
732         return BAD_VALUE;
733     }
734     if (sessionId != mAudioSessionId) {
735         AudioSystem::acquireAudioSessionId(sessionId, (pid_t)-1, (uid_t)-1);
736         AudioSystem::releaseAudioSessionId(mAudioSessionId, (pid_t)-1);
737         mAudioSessionId = sessionId;
738     }
739     return NO_ERROR;
740 }
741 
getAudioSessionId()742 audio_session_t MediaPlayer::getAudioSessionId()
743 {
744     Mutex::Autolock _l(mLock);
745     return mAudioSessionId;
746 }
747 
setAuxEffectSendLevel(float level)748 status_t MediaPlayer::setAuxEffectSendLevel(float level)
749 {
750     ALOGV("MediaPlayer::setAuxEffectSendLevel(%f)", level);
751     Mutex::Autolock _l(mLock);
752     mSendLevel = level;
753     if (mPlayer != 0) {
754         return mPlayer->setAuxEffectSendLevel(level);
755     }
756     return OK;
757 }
758 
attachAuxEffect(int effectId)759 status_t MediaPlayer::attachAuxEffect(int effectId)
760 {
761     ALOGV("MediaPlayer::attachAuxEffect(%d)", effectId);
762     Mutex::Autolock _l(mLock);
763     if (mPlayer == 0 ||
764         (mCurrentState & MEDIA_PLAYER_IDLE) ||
765         (mCurrentState == MEDIA_PLAYER_STATE_ERROR )) {
766         ALOGE("attachAuxEffect called in state %d, mPlayer(%p)", mCurrentState, mPlayer.get());
767         return INVALID_OPERATION;
768     }
769 
770     return mPlayer->attachAuxEffect(effectId);
771 }
772 
773 // always call with lock held
checkStateForKeySet_l(int key)774 status_t MediaPlayer::checkStateForKeySet_l(int key)
775 {
776     switch(key) {
777     case KEY_PARAMETER_AUDIO_ATTRIBUTES:
778         if (mCurrentState & ( MEDIA_PLAYER_PREPARED | MEDIA_PLAYER_STARTED |
779                 MEDIA_PLAYER_PAUSED | MEDIA_PLAYER_PLAYBACK_COMPLETE) ) {
780             // Can't change the audio attributes after prepare
781             ALOGE("trying to set audio attributes called in state %d", mCurrentState);
782             return INVALID_OPERATION;
783         }
784         break;
785     default:
786         // parameter doesn't require player state check
787         break;
788     }
789     return OK;
790 }
791 
setParameter(int key,const Parcel & request)792 status_t MediaPlayer::setParameter(int key, const Parcel& request)
793 {
794     ALOGV("MediaPlayer::setParameter(%d)", key);
795     status_t status = INVALID_OPERATION;
796     Mutex::Autolock _l(mLock);
797     if (checkStateForKeySet_l(key) != OK) {
798         return status;
799     }
800     switch (key) {
801     case KEY_PARAMETER_AUDIO_ATTRIBUTES:
802         // save the marshalled audio attributes
803         if (mAudioAttributesParcel != NULL) { delete mAudioAttributesParcel; };
804         mAudioAttributesParcel = new Parcel();
805         mAudioAttributesParcel->appendFrom(&request, 0, request.dataSize());
806         status = OK;
807         break;
808     default:
809         ALOGV_IF(mPlayer == NULL, "setParameter: no active player");
810         break;
811     }
812 
813     if (mPlayer != NULL) {
814         status = mPlayer->setParameter(key, request);
815     }
816     return status;
817 }
818 
getParameter(int key,Parcel * reply)819 status_t MediaPlayer::getParameter(int key, Parcel *reply)
820 {
821     ALOGV("MediaPlayer::getParameter(%d)", key);
822     Mutex::Autolock _l(mLock);
823     if (mPlayer != NULL) {
824         status_t status =  mPlayer->getParameter(key, reply);
825         if (status != OK) {
826             ALOGD("getParameter returns %d", status);
827         }
828         return status;
829     }
830     ALOGV("getParameter: no active player");
831     return INVALID_OPERATION;
832 }
833 
setRetransmitEndpoint(const char * addrString,uint16_t port)834 status_t MediaPlayer::setRetransmitEndpoint(const char* addrString,
835                                             uint16_t port) {
836     ALOGV("MediaPlayer::setRetransmitEndpoint(%s:%hu)",
837             addrString ? addrString : "(null)", port);
838 
839     Mutex::Autolock _l(mLock);
840     if ((mPlayer != NULL) || (mCurrentState != MEDIA_PLAYER_IDLE))
841         return INVALID_OPERATION;
842 
843     if (NULL == addrString) {
844         mRetransmitEndpointValid = false;
845         return OK;
846     }
847 
848     struct in_addr saddr;
849     if(!inet_aton(addrString, &saddr)) {
850         return BAD_VALUE;
851     }
852 
853     memset(&mRetransmitEndpoint, 0, sizeof(mRetransmitEndpoint));
854     mRetransmitEndpoint.sin_family = AF_INET;
855     mRetransmitEndpoint.sin_addr   = saddr;
856     mRetransmitEndpoint.sin_port   = htons(port);
857     mRetransmitEndpointValid       = true;
858 
859     return OK;
860 }
861 
notify(int msg,int ext1,int ext2,const Parcel * obj)862 void MediaPlayer::notify(int msg, int ext1, int ext2, const Parcel *obj)
863 {
864     ALOGV("message received msg=%d, ext1=%d, ext2=%d", msg, ext1, ext2);
865     bool send = true;
866     bool locked = false;
867 
868     // TODO: In the future, we might be on the same thread if the app is
869     // running in the same process as the media server. In that case,
870     // this will deadlock.
871     //
872     // The threadId hack below works around this for the care of prepare,
873     // seekTo, start, and reset within the same process.
874     // FIXME: Remember, this is a hack, it's not even a hack that is applied
875     // consistently for all use-cases, this needs to be revisited.
876     if (mLockThreadId != getThreadId()) {
877         mLock.lock();
878         locked = true;
879     }
880 
881     // Allows calls from JNI in idle state to notify errors
882     if (!(msg == MEDIA_ERROR && mCurrentState == MEDIA_PLAYER_IDLE) && mPlayer == 0) {
883         ALOGV("notify(%d, %d, %d) callback on disconnected mediaplayer", msg, ext1, ext2);
884         if (locked) mLock.unlock();   // release the lock when done.
885         return;
886     }
887 
888     switch (msg) {
889     case MEDIA_NOP: // interface test message
890         break;
891     case MEDIA_PREPARED:
892         ALOGV("MediaPlayer::notify() prepared");
893         mCurrentState = MEDIA_PLAYER_PREPARED;
894         if (mPrepareSync) {
895             ALOGV("signal application thread");
896             mPrepareSync = false;
897             mPrepareStatus = NO_ERROR;
898             mSignal.signal();
899         }
900         break;
901     case MEDIA_DRM_INFO:
902         ALOGV("MediaPlayer::notify() MEDIA_DRM_INFO(%d, %d, %d, %p)", msg, ext1, ext2, obj);
903         break;
904     case MEDIA_PLAYBACK_COMPLETE:
905         ALOGV("playback complete");
906         if (mCurrentState == MEDIA_PLAYER_IDLE) {
907             ALOGE("playback complete in idle state");
908         }
909         if (!mLoop) {
910             mCurrentState = MEDIA_PLAYER_PLAYBACK_COMPLETE;
911         }
912         break;
913     case MEDIA_ERROR:
914         // Always log errors.
915         // ext1: Media framework error code.
916         // ext2: Implementation dependant error code.
917         ALOGE("error (%d, %d)", ext1, ext2);
918         mCurrentState = MEDIA_PLAYER_STATE_ERROR;
919         if (mPrepareSync)
920         {
921             ALOGV("signal application thread");
922             mPrepareSync = false;
923             mPrepareStatus = ext1;
924             mSignal.signal();
925             send = false;
926         }
927         break;
928     case MEDIA_INFO:
929         // ext1: Media framework error code.
930         // ext2: Implementation dependant error code.
931         if (ext1 != MEDIA_INFO_VIDEO_TRACK_LAGGING) {
932             ALOGW("info/warning (%d, %d)", ext1, ext2);
933         }
934         break;
935     case MEDIA_SEEK_COMPLETE:
936         ALOGV("Received seek complete");
937         if (mSeekPosition != mCurrentPosition || (mSeekMode != mCurrentSeekMode)) {
938             ALOGV("Executing queued seekTo(%d, %d)", mCurrentPosition, mCurrentSeekMode);
939             mSeekPosition = -1;
940             mSeekMode = MediaPlayerSeekMode::SEEK_PREVIOUS_SYNC;
941             seekTo_l(mCurrentPosition, mCurrentSeekMode);
942         }
943         else {
944             ALOGV("All seeks complete - return to regularly scheduled program");
945             mCurrentPosition = mSeekPosition = -1;
946             mCurrentSeekMode = mSeekMode = MediaPlayerSeekMode::SEEK_PREVIOUS_SYNC;
947         }
948         break;
949     case MEDIA_BUFFERING_UPDATE:
950         ALOGV("buffering %d", ext1);
951         break;
952     case MEDIA_SET_VIDEO_SIZE:
953         ALOGV("New video size %d x %d", ext1, ext2);
954         mVideoWidth = ext1;
955         mVideoHeight = ext2;
956         break;
957     case MEDIA_STARTED:
958         ALOGV("Received media started message");
959         break;
960     case MEDIA_NOTIFY_TIME:
961         ALOGV("Received notify time message");
962         break;
963     case MEDIA_TIMED_TEXT:
964         ALOGV("Received timed text message");
965         break;
966     case MEDIA_SUBTITLE_DATA:
967         ALOGV("Received subtitle data message");
968         break;
969     case MEDIA_META_DATA:
970         ALOGV("Received timed metadata message");
971         break;
972     case MEDIA_IMS_RX_NOTICE:
973         ALOGV("Received IMS Rx notice message");
974         break;
975     default:
976         ALOGV("unrecognized message: (%d, %d, %d)", msg, ext1, ext2);
977         break;
978     }
979 
980     sp<MediaPlayerListener> listener = mListener;
981     if (locked) mLock.unlock();
982 
983     // this prevents re-entrant calls into client code
984     if ((listener != 0) && send) {
985         Mutex::Autolock _l(mNotifyLock);
986         ALOGV("callback application");
987         listener->notify(msg, ext1, ext2, obj);
988         ALOGV("back from callback");
989     }
990 }
991 
died()992 void MediaPlayer::died()
993 {
994     ALOGV("died");
995     notify(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, 0);
996 }
997 
setNextMediaPlayer(const sp<MediaPlayer> & next)998 status_t MediaPlayer::setNextMediaPlayer(const sp<MediaPlayer>& next) {
999     Mutex::Autolock _l(mLock);
1000     if (mPlayer == NULL) {
1001         return NO_INIT;
1002     }
1003 
1004     if (next != NULL && !(next->mCurrentState &
1005             (MEDIA_PLAYER_PREPARED | MEDIA_PLAYER_PAUSED | MEDIA_PLAYER_PLAYBACK_COMPLETE))) {
1006         ALOGE("next player is not prepared");
1007         return INVALID_OPERATION;
1008     }
1009 
1010     return mPlayer->setNextPlayer(next == NULL ? NULL : next->mPlayer);
1011 }
1012 
applyVolumeShaper(const sp<VolumeShaper::Configuration> & configuration,const sp<VolumeShaper::Operation> & operation)1013 VolumeShaper::Status MediaPlayer::applyVolumeShaper(
1014         const sp<VolumeShaper::Configuration>& configuration,
1015         const sp<VolumeShaper::Operation>& operation)
1016 {
1017     Mutex::Autolock _l(mLock);
1018     if (mPlayer == nullptr) {
1019         return VolumeShaper::Status(NO_INIT);
1020     }
1021     VolumeShaper::Status status = mPlayer->applyVolumeShaper(configuration, operation);
1022     return status;
1023 }
1024 
getVolumeShaperState(int id)1025 sp<VolumeShaper::State> MediaPlayer::getVolumeShaperState(int id)
1026 {
1027     Mutex::Autolock _l(mLock);
1028     if (mPlayer == nullptr) {
1029         return nullptr;
1030     }
1031     return mPlayer->getVolumeShaperState(id);
1032 }
1033 
1034 // Modular DRM
prepareDrm(const uint8_t uuid[16],const Vector<uint8_t> & drmSessionId)1035 status_t MediaPlayer::prepareDrm(const uint8_t uuid[16], const Vector<uint8_t>& drmSessionId)
1036 {
1037     // TODO change to ALOGV
1038     ALOGD("prepareDrm: uuid: %p  drmSessionId: %p(%zu)", uuid,
1039             drmSessionId.array(), drmSessionId.size());
1040     Mutex::Autolock _l(mLock);
1041     if (mPlayer == NULL) {
1042         return NO_INIT;
1043     }
1044 
1045     // Only allowed it in player's preparing/prepared state.
1046     // We get here only if MEDIA_DRM_INFO has already arrived (e.g., prepare is half-way through or
1047     // completed) so the state change to "prepared" might not have happened yet (e.g., buffering).
1048     // Still, we can allow prepareDrm for the use case of being called in OnDrmInfoListener.
1049     if (!(mCurrentState & (MEDIA_PLAYER_PREPARING | MEDIA_PLAYER_PREPARED))) {
1050         ALOGE("prepareDrm is called in the wrong state (%d).", mCurrentState);
1051         return INVALID_OPERATION;
1052     }
1053 
1054     if (drmSessionId.isEmpty()) {
1055         ALOGE("prepareDrm: Unexpected. Can't proceed with crypto. Empty drmSessionId.");
1056         return INVALID_OPERATION;
1057     }
1058 
1059     // Passing down to mediaserver mainly for creating the crypto
1060     status_t status = mPlayer->prepareDrm(uuid, drmSessionId);
1061     ALOGE_IF(status != OK, "prepareDrm: Failed at mediaserver with ret: %d", status);
1062 
1063     // TODO change to ALOGV
1064     ALOGD("prepareDrm: mediaserver::prepareDrm ret=%d", status);
1065 
1066     return status;
1067 }
1068 
releaseDrm()1069 status_t MediaPlayer::releaseDrm()
1070 {
1071     Mutex::Autolock _l(mLock);
1072     if (mPlayer == NULL) {
1073         return NO_INIT;
1074     }
1075 
1076     // Not allowing releaseDrm in an active/resumable state
1077     if (mCurrentState & (MEDIA_PLAYER_STARTED |
1078                          MEDIA_PLAYER_PAUSED |
1079                          MEDIA_PLAYER_PLAYBACK_COMPLETE |
1080                          MEDIA_PLAYER_STATE_ERROR)) {
1081         ALOGE("releaseDrm Unexpected state %d. Can only be called in stopped/idle.", mCurrentState);
1082         return INVALID_OPERATION;
1083     }
1084 
1085     status_t status = mPlayer->releaseDrm();
1086     // TODO change to ALOGV
1087     ALOGD("releaseDrm: mediaserver::releaseDrm ret: %d", status);
1088     if (status != OK) {
1089         ALOGE("releaseDrm: Failed at mediaserver with ret: %d", status);
1090         // Overriding to OK so the client proceed with its own cleanup
1091         // Client can't do more cleanup. mediaserver release its crypto at end of session anyway.
1092         status = OK;
1093     }
1094 
1095     return status;
1096 }
1097 
setOutputDevice(audio_port_handle_t deviceId)1098 status_t MediaPlayer::setOutputDevice(audio_port_handle_t deviceId)
1099 {
1100     Mutex::Autolock _l(mLock);
1101     if (mPlayer == NULL) {
1102         ALOGV("setOutputDevice: player not init");
1103         return NO_INIT;
1104     }
1105     return mPlayer->setOutputDevice(deviceId);
1106 }
1107 
getRoutedDeviceId()1108 audio_port_handle_t MediaPlayer::getRoutedDeviceId()
1109 {
1110     Mutex::Autolock _l(mLock);
1111     if (mPlayer == NULL) {
1112         ALOGV("getRoutedDeviceId: player not init");
1113         return AUDIO_PORT_HANDLE_NONE;
1114     }
1115     audio_port_handle_t deviceId;
1116     status_t status = mPlayer->getRoutedDeviceId(&deviceId);
1117     if (status != NO_ERROR) {
1118         return AUDIO_PORT_HANDLE_NONE;
1119     }
1120     return deviceId;
1121 }
1122 
enableAudioDeviceCallback(bool enabled)1123 status_t MediaPlayer::enableAudioDeviceCallback(bool enabled)
1124 {
1125     Mutex::Autolock _l(mLock);
1126     if (mPlayer == NULL) {
1127         ALOGV("addAudioDeviceCallback: player not init");
1128         return NO_INIT;
1129     }
1130     return mPlayer->enableAudioDeviceCallback(enabled);
1131 }
1132 
1133 } // namespace android
1134