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