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