AwesomePlayer.cpp revision c0dfc5b02d4179769bbdd25c10d430576ec09568
1/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#undef DEBUG_HDCP
18
19//#define LOG_NDEBUG 0
20#define LOG_TAG "AwesomePlayer"
21#include <utils/Log.h>
22
23#include <dlfcn.h>
24
25#include "include/ARTSPController.h"
26#include "include/AwesomePlayer.h"
27#include "include/SoftwareRenderer.h"
28#include "include/NuCachedSource2.h"
29#include "include/ThrottledSource.h"
30#include "include/MPEG2TSExtractor.h"
31#include "include/TimedTextPlayer.h"
32
33#include <binder/IPCThreadState.h>
34#include <binder/IServiceManager.h>
35#include <media/IMediaPlayerService.h>
36#include <media/stagefright/foundation/hexdump.h>
37#include <media/stagefright/foundation/ADebug.h>
38#include <media/stagefright/AudioPlayer.h>
39#include <media/stagefright/DataSource.h>
40#include <media/stagefright/FileSource.h>
41#include <media/stagefright/MediaBuffer.h>
42#include <media/stagefright/MediaDefs.h>
43#include <media/stagefright/MediaExtractor.h>
44#include <media/stagefright/MediaSource.h>
45#include <media/stagefright/MetaData.h>
46#include <media/stagefright/OMXCodec.h>
47
48#include <surfaceflinger/Surface.h>
49#include <gui/ISurfaceTexture.h>
50#include <gui/SurfaceTextureClient.h>
51#include <surfaceflinger/ISurfaceComposer.h>
52
53#include <media/stagefright/foundation/ALooper.h>
54#include <media/stagefright/foundation/AMessage.h>
55
56#include <cutils/properties.h>
57
58#define USE_SURFACE_ALLOC 1
59
60namespace android {
61
62static int64_t kLowWaterMarkUs = 2000000ll;  // 2secs
63static int64_t kHighWaterMarkUs = 10000000ll;  // 10secs
64static int64_t kHighWaterMarkRTSPUs = 4000000ll;  // 4secs
65static const size_t kLowWaterMarkBytes = 40000;
66static const size_t kHighWaterMarkBytes = 200000;
67
68struct AwesomeEvent : public TimedEventQueue::Event {
69    AwesomeEvent(
70            AwesomePlayer *player,
71            void (AwesomePlayer::*method)())
72        : mPlayer(player),
73          mMethod(method) {
74    }
75
76protected:
77    virtual ~AwesomeEvent() {}
78
79    virtual void fire(TimedEventQueue *queue, int64_t /* now_us */) {
80        (mPlayer->*mMethod)();
81    }
82
83private:
84    AwesomePlayer *mPlayer;
85    void (AwesomePlayer::*mMethod)();
86
87    AwesomeEvent(const AwesomeEvent &);
88    AwesomeEvent &operator=(const AwesomeEvent &);
89};
90
91struct AwesomeLocalRenderer : public AwesomeRenderer {
92    AwesomeLocalRenderer(
93            const sp<ANativeWindow> &nativeWindow, const sp<MetaData> &meta)
94        : mTarget(new SoftwareRenderer(nativeWindow, meta)) {
95    }
96
97    virtual void render(MediaBuffer *buffer) {
98        render((const uint8_t *)buffer->data() + buffer->range_offset(),
99               buffer->range_length());
100    }
101
102    void render(const void *data, size_t size) {
103        mTarget->render(data, size, NULL);
104    }
105
106protected:
107    virtual ~AwesomeLocalRenderer() {
108        delete mTarget;
109        mTarget = NULL;
110    }
111
112private:
113    SoftwareRenderer *mTarget;
114
115    AwesomeLocalRenderer(const AwesomeLocalRenderer &);
116    AwesomeLocalRenderer &operator=(const AwesomeLocalRenderer &);;
117};
118
119struct AwesomeNativeWindowRenderer : public AwesomeRenderer {
120    AwesomeNativeWindowRenderer(
121            const sp<ANativeWindow> &nativeWindow,
122            int32_t rotationDegrees)
123        : mNativeWindow(nativeWindow) {
124        applyRotation(rotationDegrees);
125    }
126
127    virtual void render(MediaBuffer *buffer) {
128        status_t err = mNativeWindow->queueBuffer(
129                mNativeWindow.get(), buffer->graphicBuffer().get());
130        if (err != 0) {
131            LOGE("queueBuffer failed with error %s (%d)", strerror(-err),
132                    -err);
133            return;
134        }
135
136        sp<MetaData> metaData = buffer->meta_data();
137        metaData->setInt32(kKeyRendered, 1);
138    }
139
140protected:
141    virtual ~AwesomeNativeWindowRenderer() {}
142
143private:
144    sp<ANativeWindow> mNativeWindow;
145
146    void applyRotation(int32_t rotationDegrees) {
147        uint32_t transform;
148        switch (rotationDegrees) {
149            case 0: transform = 0; break;
150            case 90: transform = HAL_TRANSFORM_ROT_90; break;
151            case 180: transform = HAL_TRANSFORM_ROT_180; break;
152            case 270: transform = HAL_TRANSFORM_ROT_270; break;
153            default: transform = 0; break;
154        }
155
156        if (transform) {
157            CHECK_EQ(0, native_window_set_buffers_transform(
158                        mNativeWindow.get(), transform));
159        }
160    }
161
162    AwesomeNativeWindowRenderer(const AwesomeNativeWindowRenderer &);
163    AwesomeNativeWindowRenderer &operator=(
164            const AwesomeNativeWindowRenderer &);
165};
166
167// To collect the decoder usage
168void addBatteryData(uint32_t params) {
169    sp<IBinder> binder =
170        defaultServiceManager()->getService(String16("media.player"));
171    sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
172    CHECK(service.get() != NULL);
173
174    service->addBatteryData(params);
175}
176
177////////////////////////////////////////////////////////////////////////////////
178AwesomePlayer::AwesomePlayer()
179    : mQueueStarted(false),
180      mTimeSource(NULL),
181      mVideoRendererIsPreview(false),
182      mAudioPlayer(NULL),
183      mDisplayWidth(0),
184      mDisplayHeight(0),
185      mFlags(0),
186      mExtractorFlags(0),
187      mVideoBuffer(NULL),
188      mDecryptHandle(NULL),
189      mLastVideoTimeUs(-1),
190      mTextPlayer(NULL) {
191    CHECK_EQ(mClient.connect(), (status_t)OK);
192
193    DataSource::RegisterDefaultSniffers();
194
195    mVideoEvent = new AwesomeEvent(this, &AwesomePlayer::onVideoEvent);
196    mVideoEventPending = false;
197    mStreamDoneEvent = new AwesomeEvent(this, &AwesomePlayer::onStreamDone);
198    mStreamDoneEventPending = false;
199    mBufferingEvent = new AwesomeEvent(this, &AwesomePlayer::onBufferingUpdate);
200    mBufferingEventPending = false;
201    mVideoLagEvent = new AwesomeEvent(this, &AwesomePlayer::onVideoLagUpdate);
202    mVideoEventPending = false;
203
204    mCheckAudioStatusEvent = new AwesomeEvent(
205            this, &AwesomePlayer::onCheckAudioStatus);
206
207    mAudioStatusEventPending = false;
208
209    reset();
210}
211
212AwesomePlayer::~AwesomePlayer() {
213    if (mQueueStarted) {
214        mQueue.stop();
215    }
216
217    reset();
218
219    mClient.disconnect();
220}
221
222void AwesomePlayer::cancelPlayerEvents(bool keepBufferingGoing) {
223    mQueue.cancelEvent(mVideoEvent->eventID());
224    mVideoEventPending = false;
225    mQueue.cancelEvent(mStreamDoneEvent->eventID());
226    mStreamDoneEventPending = false;
227    mQueue.cancelEvent(mCheckAudioStatusEvent->eventID());
228    mAudioStatusEventPending = false;
229    mQueue.cancelEvent(mVideoLagEvent->eventID());
230    mVideoLagEventPending = false;
231
232    if (!keepBufferingGoing) {
233        mQueue.cancelEvent(mBufferingEvent->eventID());
234        mBufferingEventPending = false;
235    }
236}
237
238void AwesomePlayer::setListener(const wp<MediaPlayerBase> &listener) {
239    Mutex::Autolock autoLock(mLock);
240    mListener = listener;
241}
242
243status_t AwesomePlayer::setDataSource(
244        const char *uri, const KeyedVector<String8, String8> *headers) {
245    Mutex::Autolock autoLock(mLock);
246    return setDataSource_l(uri, headers);
247}
248
249status_t AwesomePlayer::setDataSource_l(
250        const char *uri, const KeyedVector<String8, String8> *headers) {
251    reset_l();
252
253    mUri = uri;
254
255    if (headers) {
256        mUriHeaders = *headers;
257
258        ssize_t index = mUriHeaders.indexOfKey(String8("x-hide-urls-from-log"));
259        if (index >= 0) {
260            // Browser is in "incognito" mode, suppress logging URLs.
261
262            // This isn't something that should be passed to the server.
263            mUriHeaders.removeItemsAt(index);
264
265            mFlags |= INCOGNITO;
266        }
267    }
268
269    if (!(mFlags & INCOGNITO)) {
270        LOGI("setDataSource_l('%s')", mUri.string());
271    } else {
272        LOGI("setDataSource_l(URL suppressed)");
273    }
274
275    // The actual work will be done during preparation in the call to
276    // ::finishSetDataSource_l to avoid blocking the calling thread in
277    // setDataSource for any significant time.
278
279    return OK;
280}
281
282status_t AwesomePlayer::setDataSource(
283        int fd, int64_t offset, int64_t length) {
284    Mutex::Autolock autoLock(mLock);
285
286    reset_l();
287
288    sp<DataSource> dataSource = new FileSource(fd, offset, length);
289
290    status_t err = dataSource->initCheck();
291
292    if (err != OK) {
293        return err;
294    }
295
296    mFileSource = dataSource;
297
298    return setDataSource_l(dataSource);
299}
300
301status_t AwesomePlayer::setDataSource(const sp<IStreamSource> &source) {
302    return INVALID_OPERATION;
303}
304
305status_t AwesomePlayer::setDataSource_l(
306        const sp<DataSource> &dataSource) {
307    sp<MediaExtractor> extractor = MediaExtractor::Create(dataSource);
308
309    if (extractor == NULL) {
310        return UNKNOWN_ERROR;
311    }
312
313    dataSource->getDrmInfo(mDecryptHandle, &mDrmManagerClient);
314    if (mDecryptHandle != NULL) {
315        CHECK(mDrmManagerClient);
316        if (RightsStatus::RIGHTS_VALID != mDecryptHandle->status) {
317            notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, ERROR_DRM_NO_LICENSE);
318        }
319    }
320
321    return setDataSource_l(extractor);
322}
323
324status_t AwesomePlayer::setDataSource_l(const sp<MediaExtractor> &extractor) {
325    // Attempt to approximate overall stream bitrate by summing all
326    // tracks' individual bitrates, if not all of them advertise bitrate,
327    // we have to fail.
328
329    int64_t totalBitRate = 0;
330
331    for (size_t i = 0; i < extractor->countTracks(); ++i) {
332        sp<MetaData> meta = extractor->getTrackMetaData(i);
333
334        int32_t bitrate;
335        if (!meta->findInt32(kKeyBitRate, &bitrate)) {
336            totalBitRate = -1;
337            break;
338        }
339
340        totalBitRate += bitrate;
341    }
342
343    mBitrate = totalBitRate;
344
345    LOGV("mBitrate = %lld bits/sec", mBitrate);
346
347    bool haveAudio = false;
348    bool haveVideo = false;
349    for (size_t i = 0; i < extractor->countTracks(); ++i) {
350        sp<MetaData> meta = extractor->getTrackMetaData(i);
351
352        const char *mime;
353        CHECK(meta->findCString(kKeyMIMEType, &mime));
354
355        if (!haveVideo && !strncasecmp(mime, "video/", 6)) {
356            setVideoSource(extractor->getTrack(i));
357            haveVideo = true;
358
359            // Set the presentation/display size
360            int32_t displayWidth, displayHeight;
361            bool success = meta->findInt32(kKeyDisplayWidth, &displayWidth);
362            if (success) {
363                success = meta->findInt32(kKeyDisplayHeight, &displayHeight);
364            }
365            if (success) {
366                mDisplayWidth = displayWidth;
367                mDisplayHeight = displayHeight;
368            }
369
370        } else if (!haveAudio && !strncasecmp(mime, "audio/", 6)) {
371            setAudioSource(extractor->getTrack(i));
372            haveAudio = true;
373
374            if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_VORBIS)) {
375                // Only do this for vorbis audio, none of the other audio
376                // formats even support this ringtone specific hack and
377                // retrieving the metadata on some extractors may turn out
378                // to be very expensive.
379                sp<MetaData> fileMeta = extractor->getMetaData();
380                int32_t loop;
381                if (fileMeta != NULL
382                        && fileMeta->findInt32(kKeyAutoLoop, &loop) && loop != 0) {
383                    mFlags |= AUTO_LOOPING;
384                }
385            }
386        } else if (!strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP)) {
387            addTextSource(extractor->getTrack(i));
388        }
389    }
390
391    if (!haveAudio && !haveVideo) {
392        return UNKNOWN_ERROR;
393    }
394
395    mExtractorFlags = extractor->flags();
396
397    return OK;
398}
399
400void AwesomePlayer::reset() {
401    Mutex::Autolock autoLock(mLock);
402    reset_l();
403}
404
405void AwesomePlayer::reset_l() {
406    mDisplayWidth = 0;
407    mDisplayHeight = 0;
408
409    if (mDecryptHandle != NULL) {
410            mDrmManagerClient->setPlaybackStatus(mDecryptHandle,
411                    Playback::STOP, 0);
412            mDecryptHandle = NULL;
413            mDrmManagerClient = NULL;
414    }
415
416    if (mFlags & PLAYING) {
417        uint32_t params = IMediaPlayerService::kBatteryDataTrackDecoder;
418        if ((mAudioSource != NULL) && (mAudioSource != mAudioTrack)) {
419            params |= IMediaPlayerService::kBatteryDataTrackAudio;
420        }
421        if (mVideoSource != NULL) {
422            params |= IMediaPlayerService::kBatteryDataTrackVideo;
423        }
424        addBatteryData(params);
425    }
426
427    if (mFlags & PREPARING) {
428        mFlags |= PREPARE_CANCELLED;
429        if (mConnectingDataSource != NULL) {
430            LOGI("interrupting the connection process");
431            mConnectingDataSource->disconnect();
432        } else if (mConnectingRTSPController != NULL) {
433            LOGI("interrupting the connection process");
434            mConnectingRTSPController->disconnect();
435        }
436
437        if (mFlags & PREPARING_CONNECTED) {
438            // We are basically done preparing, we're just buffering
439            // enough data to start playback, we can safely interrupt that.
440            finishAsyncPrepare_l();
441        }
442    }
443
444    while (mFlags & PREPARING) {
445        mPreparedCondition.wait(mLock);
446    }
447
448    cancelPlayerEvents();
449
450    mCachedSource.clear();
451    mAudioTrack.clear();
452    mVideoTrack.clear();
453
454    // Shutdown audio first, so that the respone to the reset request
455    // appears to happen instantaneously as far as the user is concerned
456    // If we did this later, audio would continue playing while we
457    // shutdown the video-related resources and the player appear to
458    // not be as responsive to a reset request.
459    if (mAudioPlayer == NULL && mAudioSource != NULL) {
460        // If we had an audio player, it would have effectively
461        // taken possession of the audio source and stopped it when
462        // _it_ is stopped. Otherwise this is still our responsibility.
463        mAudioSource->stop();
464    }
465    mAudioSource.clear();
466
467    mTimeSource = NULL;
468
469    delete mAudioPlayer;
470    mAudioPlayer = NULL;
471
472    if (mTextPlayer != NULL) {
473        delete mTextPlayer;
474        mTextPlayer = NULL;
475    }
476
477    mVideoRenderer.clear();
478
479    if (mRTSPController != NULL) {
480        mRTSPController->disconnect();
481        mRTSPController.clear();
482    }
483
484    if (mVideoSource != NULL) {
485        shutdownVideoDecoder_l();
486    }
487
488    mDurationUs = -1;
489    mFlags = 0;
490    mExtractorFlags = 0;
491    mTimeSourceDeltaUs = 0;
492    mVideoTimeUs = 0;
493
494    mSeeking = NO_SEEK;
495    mSeekNotificationSent = false;
496    mSeekTimeUs = 0;
497
498    mUri.setTo("");
499    mUriHeaders.clear();
500
501    mFileSource.clear();
502
503    mBitrate = -1;
504    mLastVideoTimeUs = -1;
505}
506
507void AwesomePlayer::notifyListener_l(int msg, int ext1, int ext2) {
508    if (mListener != NULL) {
509        sp<MediaPlayerBase> listener = mListener.promote();
510
511        if (listener != NULL) {
512            listener->sendEvent(msg, ext1, ext2);
513        }
514    }
515}
516
517bool AwesomePlayer::getBitrate(int64_t *bitrate) {
518    off64_t size;
519    if (mDurationUs >= 0 && mCachedSource != NULL
520            && mCachedSource->getSize(&size) == OK) {
521        *bitrate = size * 8000000ll / mDurationUs;  // in bits/sec
522        return true;
523    }
524
525    if (mBitrate >= 0) {
526        *bitrate = mBitrate;
527        return true;
528    }
529
530    *bitrate = 0;
531
532    return false;
533}
534
535// Returns true iff cached duration is available/applicable.
536bool AwesomePlayer::getCachedDuration_l(int64_t *durationUs, bool *eos) {
537    int64_t bitrate;
538
539    if (mRTSPController != NULL) {
540        *durationUs = mRTSPController->getQueueDurationUs(eos);
541        return true;
542    } else if (mCachedSource != NULL && getBitrate(&bitrate)) {
543        status_t finalStatus;
544        size_t cachedDataRemaining = mCachedSource->approxDataRemaining(&finalStatus);
545        *durationUs = cachedDataRemaining * 8000000ll / bitrate;
546        *eos = (finalStatus != OK);
547        return true;
548    }
549
550    return false;
551}
552
553void AwesomePlayer::ensureCacheIsFetching_l() {
554    if (mCachedSource != NULL) {
555        mCachedSource->resumeFetchingIfNecessary();
556    }
557}
558
559void AwesomePlayer::onVideoLagUpdate() {
560    Mutex::Autolock autoLock(mLock);
561    if (!mVideoLagEventPending) {
562        return;
563    }
564    mVideoLagEventPending = false;
565
566    int64_t audioTimeUs = mAudioPlayer->getMediaTimeUs();
567    int64_t videoLateByUs = audioTimeUs - mVideoTimeUs;
568
569    if (!(mFlags & VIDEO_AT_EOS) && videoLateByUs > 300000ll) {
570        LOGV("video late by %lld ms.", videoLateByUs / 1000ll);
571
572        notifyListener_l(
573                MEDIA_INFO,
574                MEDIA_INFO_VIDEO_TRACK_LAGGING,
575                videoLateByUs / 1000ll);
576    }
577
578    postVideoLagEvent_l();
579}
580
581void AwesomePlayer::onBufferingUpdate() {
582    Mutex::Autolock autoLock(mLock);
583    if (!mBufferingEventPending) {
584        return;
585    }
586    mBufferingEventPending = false;
587
588    if (mCachedSource != NULL) {
589        status_t finalStatus;
590        size_t cachedDataRemaining = mCachedSource->approxDataRemaining(&finalStatus);
591        bool eos = (finalStatus != OK);
592
593        if (eos) {
594            if (finalStatus == ERROR_END_OF_STREAM) {
595                notifyListener_l(MEDIA_BUFFERING_UPDATE, 100);
596            }
597            if (mFlags & PREPARING) {
598                LOGV("cache has reached EOS, prepare is done.");
599                finishAsyncPrepare_l();
600            }
601        } else {
602            int64_t bitrate;
603            if (getBitrate(&bitrate)) {
604                size_t cachedSize = mCachedSource->cachedSize();
605                int64_t cachedDurationUs = cachedSize * 8000000ll / bitrate;
606
607                int percentage = 100.0 * (double)cachedDurationUs / mDurationUs;
608                if (percentage > 100) {
609                    percentage = 100;
610                }
611
612                notifyListener_l(MEDIA_BUFFERING_UPDATE, percentage);
613            } else {
614                // We don't know the bitrate of the stream, use absolute size
615                // limits to maintain the cache.
616
617                if ((mFlags & PLAYING) && !eos
618                        && (cachedDataRemaining < kLowWaterMarkBytes)) {
619                    LOGI("cache is running low (< %d) , pausing.",
620                         kLowWaterMarkBytes);
621                    mFlags |= CACHE_UNDERRUN;
622                    pause_l();
623                    ensureCacheIsFetching_l();
624                    notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_START);
625                } else if (eos || cachedDataRemaining > kHighWaterMarkBytes) {
626                    if (mFlags & CACHE_UNDERRUN) {
627                        LOGI("cache has filled up (> %d), resuming.",
628                             kHighWaterMarkBytes);
629                        mFlags &= ~CACHE_UNDERRUN;
630                        play_l();
631                        notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_END);
632                    } else if (mFlags & PREPARING) {
633                        LOGV("cache has filled up (> %d), prepare is done",
634                             kHighWaterMarkBytes);
635                        finishAsyncPrepare_l();
636                    }
637                }
638            }
639        }
640    }
641
642    int64_t cachedDurationUs;
643    bool eos;
644    if (getCachedDuration_l(&cachedDurationUs, &eos)) {
645        LOGV("cachedDurationUs = %.2f secs, eos=%d",
646             cachedDurationUs / 1E6, eos);
647
648        int64_t highWaterMarkUs =
649            (mRTSPController != NULL) ? kHighWaterMarkRTSPUs : kHighWaterMarkUs;
650
651        if ((mFlags & PLAYING) && !eos
652                && (cachedDurationUs < kLowWaterMarkUs)) {
653            LOGI("cache is running low (%.2f secs) , pausing.",
654                 cachedDurationUs / 1E6);
655            mFlags |= CACHE_UNDERRUN;
656            pause_l();
657            ensureCacheIsFetching_l();
658            notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_START);
659        } else if (eos || cachedDurationUs > highWaterMarkUs) {
660            if (mFlags & CACHE_UNDERRUN) {
661                LOGI("cache has filled up (%.2f secs), resuming.",
662                     cachedDurationUs / 1E6);
663                mFlags &= ~CACHE_UNDERRUN;
664                play_l();
665                notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_END);
666            } else if (mFlags & PREPARING) {
667                LOGV("cache has filled up (%.2f secs), prepare is done",
668                     cachedDurationUs / 1E6);
669                finishAsyncPrepare_l();
670            }
671        }
672    }
673
674    postBufferingEvent_l();
675}
676
677void AwesomePlayer::onStreamDone() {
678    // Posted whenever any stream finishes playing.
679
680    Mutex::Autolock autoLock(mLock);
681    if (!mStreamDoneEventPending) {
682        return;
683    }
684    mStreamDoneEventPending = false;
685
686    if (mStreamDoneStatus != ERROR_END_OF_STREAM) {
687        LOGV("MEDIA_ERROR %d", mStreamDoneStatus);
688
689        notifyListener_l(
690                MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, mStreamDoneStatus);
691
692        pause_l(true /* at eos */);
693
694        mFlags |= AT_EOS;
695        return;
696    }
697
698    const bool allDone =
699        (mVideoSource == NULL || (mFlags & VIDEO_AT_EOS))
700            && (mAudioSource == NULL || (mFlags & AUDIO_AT_EOS));
701
702    if (!allDone) {
703        return;
704    }
705
706    if (mFlags & (LOOPING | AUTO_LOOPING)) {
707        seekTo_l(0);
708
709        if (mVideoSource != NULL) {
710            postVideoEvent_l();
711        }
712    } else {
713        LOGV("MEDIA_PLAYBACK_COMPLETE");
714        notifyListener_l(MEDIA_PLAYBACK_COMPLETE);
715
716        pause_l(true /* at eos */);
717
718        mFlags |= AT_EOS;
719    }
720}
721
722status_t AwesomePlayer::play() {
723    Mutex::Autolock autoLock(mLock);
724
725    mFlags &= ~CACHE_UNDERRUN;
726
727    return play_l();
728}
729
730status_t AwesomePlayer::play_l() {
731    mFlags &= ~SEEK_PREVIEW;
732
733    if (mFlags & PLAYING) {
734        return OK;
735    }
736
737    if (!(mFlags & PREPARED)) {
738        status_t err = prepare_l();
739
740        if (err != OK) {
741            return err;
742        }
743    }
744
745    mFlags |= PLAYING;
746    mFlags |= FIRST_FRAME;
747
748    if (mDecryptHandle != NULL) {
749        int64_t position;
750        getPosition(&position);
751        mDrmManagerClient->setPlaybackStatus(mDecryptHandle,
752                Playback::START, position / 1000);
753    }
754
755    if (mAudioSource != NULL) {
756        if (mAudioPlayer == NULL) {
757            if (mAudioSink != NULL) {
758                mAudioPlayer = new AudioPlayer(mAudioSink, this);
759                mAudioPlayer->setSource(mAudioSource);
760
761                mTimeSource = mAudioPlayer;
762
763                // If there was a seek request before we ever started,
764                // honor the request now.
765                // Make sure to do this before starting the audio player
766                // to avoid a race condition.
767                seekAudioIfNecessary_l();
768            }
769        }
770
771        CHECK(!(mFlags & AUDIO_RUNNING));
772
773        if (mVideoSource == NULL) {
774            status_t err = startAudioPlayer_l();
775
776            if (err != OK) {
777                delete mAudioPlayer;
778                mAudioPlayer = NULL;
779
780                mFlags &= ~(PLAYING | FIRST_FRAME);
781
782                if (mDecryptHandle != NULL) {
783                    mDrmManagerClient->setPlaybackStatus(
784                            mDecryptHandle, Playback::STOP, 0);
785                }
786
787                return err;
788            }
789        }
790    }
791
792    if (mTimeSource == NULL && mAudioPlayer == NULL) {
793        mTimeSource = &mSystemTimeSource;
794    }
795
796    if (mVideoSource != NULL) {
797        // Kick off video playback
798        postVideoEvent_l();
799
800        if (mAudioSource != NULL && mVideoSource != NULL) {
801            postVideoLagEvent_l();
802        }
803    }
804
805    if (mFlags & AT_EOS) {
806        // Legacy behaviour, if a stream finishes playing and then
807        // is started again, we play from the start...
808        seekTo_l(0);
809    }
810
811    uint32_t params = IMediaPlayerService::kBatteryDataCodecStarted
812        | IMediaPlayerService::kBatteryDataTrackDecoder;
813    if ((mAudioSource != NULL) && (mAudioSource != mAudioTrack)) {
814        params |= IMediaPlayerService::kBatteryDataTrackAudio;
815    }
816    if (mVideoSource != NULL) {
817        params |= IMediaPlayerService::kBatteryDataTrackVideo;
818    }
819    addBatteryData(params);
820
821    return OK;
822}
823
824status_t AwesomePlayer::startAudioPlayer_l() {
825    CHECK(!(mFlags & AUDIO_RUNNING));
826
827    if (mAudioSource == NULL || mAudioPlayer == NULL) {
828        return OK;
829    }
830
831    if (!(mFlags & AUDIOPLAYER_STARTED)) {
832        mFlags |= AUDIOPLAYER_STARTED;
833
834        bool wasSeeking = mAudioPlayer->isSeeking();
835
836        // We've already started the MediaSource in order to enable
837        // the prefetcher to read its data.
838        status_t err = mAudioPlayer->start(
839                true /* sourceAlreadyStarted */);
840
841        if (err != OK) {
842            notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err);
843            return err;
844        }
845
846        if (wasSeeking) {
847            CHECK(!mAudioPlayer->isSeeking());
848
849            // We will have finished the seek while starting the audio player.
850            postAudioSeekComplete_l();
851        }
852    } else {
853        mAudioPlayer->resume();
854    }
855
856    mFlags |= AUDIO_RUNNING;
857
858    mWatchForAudioEOS = true;
859
860    return OK;
861}
862
863void AwesomePlayer::notifyVideoSize_l() {
864    sp<MetaData> meta = mVideoSource->getFormat();
865
866    int32_t cropLeft, cropTop, cropRight, cropBottom;
867    if (!meta->findRect(
868                kKeyCropRect, &cropLeft, &cropTop, &cropRight, &cropBottom)) {
869        int32_t width, height;
870        CHECK(meta->findInt32(kKeyWidth, &width));
871        CHECK(meta->findInt32(kKeyHeight, &height));
872
873        cropLeft = cropTop = 0;
874        cropRight = width - 1;
875        cropBottom = height - 1;
876
877        LOGV("got dimensions only %d x %d", width, height);
878    } else {
879        LOGV("got crop rect %d, %d, %d, %d",
880             cropLeft, cropTop, cropRight, cropBottom);
881    }
882
883    int32_t displayWidth;
884    if (meta->findInt32(kKeyDisplayWidth, &displayWidth)) {
885        LOGV("Display width changed (%d=>%d)", mDisplayWidth, displayWidth);
886        mDisplayWidth = displayWidth;
887    }
888    int32_t displayHeight;
889    if (meta->findInt32(kKeyDisplayHeight, &displayHeight)) {
890        LOGV("Display height changed (%d=>%d)", mDisplayHeight, displayHeight);
891        mDisplayHeight = displayHeight;
892    }
893
894    int32_t usableWidth = cropRight - cropLeft + 1;
895    int32_t usableHeight = cropBottom - cropTop + 1;
896    if (mDisplayWidth != 0) {
897        usableWidth = mDisplayWidth;
898    }
899    if (mDisplayHeight != 0) {
900        usableHeight = mDisplayHeight;
901    }
902
903    int32_t rotationDegrees;
904    if (!mVideoTrack->getFormat()->findInt32(
905                kKeyRotation, &rotationDegrees)) {
906        rotationDegrees = 0;
907    }
908
909    if (rotationDegrees == 90 || rotationDegrees == 270) {
910        notifyListener_l(
911                MEDIA_SET_VIDEO_SIZE, usableHeight, usableWidth);
912    } else {
913        notifyListener_l(
914                MEDIA_SET_VIDEO_SIZE, usableWidth, usableHeight);
915    }
916}
917
918void AwesomePlayer::initRenderer_l() {
919    if (mNativeWindow == NULL) {
920        return;
921    }
922
923    sp<MetaData> meta = mVideoSource->getFormat();
924
925    int32_t format;
926    const char *component;
927    int32_t decodedWidth, decodedHeight;
928    CHECK(meta->findInt32(kKeyColorFormat, &format));
929    CHECK(meta->findCString(kKeyDecoderComponent, &component));
930    CHECK(meta->findInt32(kKeyWidth, &decodedWidth));
931    CHECK(meta->findInt32(kKeyHeight, &decodedHeight));
932
933    int32_t rotationDegrees;
934    if (!mVideoTrack->getFormat()->findInt32(
935                kKeyRotation, &rotationDegrees)) {
936        rotationDegrees = 0;
937    }
938
939    mVideoRenderer.clear();
940
941    // Must ensure that mVideoRenderer's destructor is actually executed
942    // before creating a new one.
943    IPCThreadState::self()->flushCommands();
944
945    if (USE_SURFACE_ALLOC && strncmp(component, "OMX.", 4) == 0) {
946        // Hardware decoders avoid the CPU color conversion by decoding
947        // directly to ANativeBuffers, so we must use a renderer that
948        // just pushes those buffers to the ANativeWindow.
949        mVideoRenderer =
950            new AwesomeNativeWindowRenderer(mNativeWindow, rotationDegrees);
951    } else {
952        // Other decoders are instantiated locally and as a consequence
953        // allocate their buffers in local address space.  This renderer
954        // then performs a color conversion and copy to get the data
955        // into the ANativeBuffer.
956        mVideoRenderer = new AwesomeLocalRenderer(mNativeWindow, meta);
957    }
958}
959
960status_t AwesomePlayer::pause() {
961    Mutex::Autolock autoLock(mLock);
962
963    mFlags &= ~CACHE_UNDERRUN;
964
965    return pause_l();
966}
967
968status_t AwesomePlayer::pause_l(bool at_eos) {
969    if (!(mFlags & PLAYING)) {
970        return OK;
971    }
972
973    cancelPlayerEvents(true /* keepBufferingGoing */);
974
975    if (mAudioPlayer != NULL && (mFlags & AUDIO_RUNNING)) {
976        if (at_eos) {
977            // If we played the audio stream to completion we
978            // want to make sure that all samples remaining in the audio
979            // track's queue are played out.
980            mAudioPlayer->pause(true /* playPendingSamples */);
981        } else {
982            mAudioPlayer->pause();
983        }
984
985        mFlags &= ~AUDIO_RUNNING;
986    }
987
988    if (mFlags & TEXTPLAYER_STARTED) {
989        mTextPlayer->pause();
990        mFlags &= ~TEXT_RUNNING;
991    }
992
993    mFlags &= ~PLAYING;
994
995    if (mDecryptHandle != NULL) {
996        mDrmManagerClient->setPlaybackStatus(mDecryptHandle,
997                Playback::PAUSE, 0);
998    }
999
1000    uint32_t params = IMediaPlayerService::kBatteryDataTrackDecoder;
1001    if ((mAudioSource != NULL) && (mAudioSource != mAudioTrack)) {
1002        params |= IMediaPlayerService::kBatteryDataTrackAudio;
1003    }
1004    if (mVideoSource != NULL) {
1005        params |= IMediaPlayerService::kBatteryDataTrackVideo;
1006    }
1007
1008    addBatteryData(params);
1009
1010    return OK;
1011}
1012
1013bool AwesomePlayer::isPlaying() const {
1014    return (mFlags & PLAYING) || (mFlags & CACHE_UNDERRUN);
1015}
1016
1017void AwesomePlayer::setSurface(const sp<Surface> &surface) {
1018    Mutex::Autolock autoLock(mLock);
1019
1020    mSurface = surface;
1021    setNativeWindow_l(surface);
1022}
1023
1024void AwesomePlayer::setSurfaceTexture(const sp<ISurfaceTexture> &surfaceTexture) {
1025    Mutex::Autolock autoLock(mLock);
1026
1027    mSurface.clear();
1028    if (surfaceTexture != NULL) {
1029        setNativeWindow_l(new SurfaceTextureClient(surfaceTexture));
1030    }
1031}
1032
1033void AwesomePlayer::shutdownVideoDecoder_l() {
1034    if (mVideoBuffer) {
1035        mVideoBuffer->release();
1036        mVideoBuffer = NULL;
1037    }
1038
1039    mVideoSource->stop();
1040
1041    // The following hack is necessary to ensure that the OMX
1042    // component is completely released by the time we may try
1043    // to instantiate it again.
1044    wp<MediaSource> tmp = mVideoSource;
1045    mVideoSource.clear();
1046    while (tmp.promote() != NULL) {
1047        usleep(1000);
1048    }
1049    IPCThreadState::self()->flushCommands();
1050}
1051
1052void AwesomePlayer::setNativeWindow_l(const sp<ANativeWindow> &native) {
1053    mNativeWindow = native;
1054
1055    if (mVideoSource == NULL) {
1056        return;
1057    }
1058
1059    LOGI("attempting to reconfigure to use new surface");
1060
1061    bool wasPlaying = (mFlags & PLAYING) != 0;
1062
1063    pause_l();
1064    mVideoRenderer.clear();
1065
1066    shutdownVideoDecoder_l();
1067
1068    CHECK_EQ(initVideoDecoder(), (status_t)OK);
1069
1070    if (mLastVideoTimeUs >= 0) {
1071        mSeeking = SEEK;
1072        mSeekNotificationSent = true;
1073        mSeekTimeUs = mLastVideoTimeUs;
1074        mFlags &= ~(AT_EOS | AUDIO_AT_EOS | VIDEO_AT_EOS);
1075    }
1076
1077    if (wasPlaying) {
1078        play_l();
1079    }
1080}
1081
1082void AwesomePlayer::setAudioSink(
1083        const sp<MediaPlayerBase::AudioSink> &audioSink) {
1084    Mutex::Autolock autoLock(mLock);
1085
1086    mAudioSink = audioSink;
1087}
1088
1089status_t AwesomePlayer::setLooping(bool shouldLoop) {
1090    Mutex::Autolock autoLock(mLock);
1091
1092    mFlags = mFlags & ~LOOPING;
1093
1094    if (shouldLoop) {
1095        mFlags |= LOOPING;
1096    }
1097
1098    return OK;
1099}
1100
1101status_t AwesomePlayer::getDuration(int64_t *durationUs) {
1102    Mutex::Autolock autoLock(mMiscStateLock);
1103
1104    if (mDurationUs < 0) {
1105        return UNKNOWN_ERROR;
1106    }
1107
1108    *durationUs = mDurationUs;
1109
1110    return OK;
1111}
1112
1113status_t AwesomePlayer::getPosition(int64_t *positionUs) {
1114    if (mRTSPController != NULL) {
1115        *positionUs = mRTSPController->getNormalPlayTimeUs();
1116    }
1117    else if (mSeeking != NO_SEEK) {
1118        *positionUs = mSeekTimeUs;
1119    } else if (mVideoSource != NULL
1120            && (mAudioPlayer == NULL || !(mFlags & VIDEO_AT_EOS))) {
1121        Mutex::Autolock autoLock(mMiscStateLock);
1122        *positionUs = mVideoTimeUs;
1123    } else if (mAudioPlayer != NULL) {
1124        *positionUs = mAudioPlayer->getMediaTimeUs();
1125    } else {
1126        *positionUs = 0;
1127    }
1128
1129    return OK;
1130}
1131
1132status_t AwesomePlayer::seekTo(int64_t timeUs) {
1133    if (mExtractorFlags & MediaExtractor::CAN_SEEK) {
1134        Mutex::Autolock autoLock(mLock);
1135        return seekTo_l(timeUs);
1136    }
1137
1138    return OK;
1139}
1140
1141status_t AwesomePlayer::setTimedTextTrackIndex(int32_t index) {
1142    if (mTextPlayer != NULL) {
1143        if (index >= 0) { // to turn on a text track
1144            status_t err = mTextPlayer->setTimedTextTrackIndex(index);
1145            if (err != OK) {
1146                return err;
1147            }
1148
1149            mFlags |= TEXT_RUNNING;
1150            mFlags |= TEXTPLAYER_STARTED;
1151            return OK;
1152        } else { // to turn off the text track display
1153            if (mFlags  & TEXT_RUNNING) {
1154                mFlags &= ~TEXT_RUNNING;
1155            }
1156            if (mFlags  & TEXTPLAYER_STARTED) {
1157                mFlags &= ~TEXTPLAYER_STARTED;
1158            }
1159
1160            return mTextPlayer->setTimedTextTrackIndex(index);
1161        }
1162    } else {
1163        return INVALID_OPERATION;
1164    }
1165}
1166
1167// static
1168void AwesomePlayer::OnRTSPSeekDoneWrapper(void *cookie) {
1169    static_cast<AwesomePlayer *>(cookie)->onRTSPSeekDone();
1170}
1171
1172void AwesomePlayer::onRTSPSeekDone() {
1173    notifyListener_l(MEDIA_SEEK_COMPLETE);
1174    mSeekNotificationSent = true;
1175}
1176
1177status_t AwesomePlayer::seekTo_l(int64_t timeUs) {
1178    if (mRTSPController != NULL) {
1179        mRTSPController->seekAsync(timeUs, OnRTSPSeekDoneWrapper, this);
1180        return OK;
1181    }
1182
1183    if (mFlags & CACHE_UNDERRUN) {
1184        mFlags &= ~CACHE_UNDERRUN;
1185        play_l();
1186    }
1187
1188    if ((mFlags & PLAYING) && mVideoSource != NULL && (mFlags & VIDEO_AT_EOS)) {
1189        // Video playback completed before, there's no pending
1190        // video event right now. In order for this new seek
1191        // to be honored, we need to post one.
1192
1193        postVideoEvent_l();
1194    }
1195
1196    mSeeking = SEEK;
1197    mSeekNotificationSent = false;
1198    mSeekTimeUs = timeUs;
1199    mFlags &= ~(AT_EOS | AUDIO_AT_EOS | VIDEO_AT_EOS);
1200
1201    seekAudioIfNecessary_l();
1202
1203    if (mFlags & TEXTPLAYER_STARTED) {
1204        mTextPlayer->seekTo(mSeekTimeUs);
1205    }
1206
1207    if (!(mFlags & PLAYING)) {
1208        LOGV("seeking while paused, sending SEEK_COMPLETE notification"
1209             " immediately.");
1210
1211        notifyListener_l(MEDIA_SEEK_COMPLETE);
1212        mSeekNotificationSent = true;
1213
1214        if ((mFlags & PREPARED) && mVideoSource != NULL) {
1215            mFlags |= SEEK_PREVIEW;
1216            postVideoEvent_l();
1217        }
1218    }
1219
1220    return OK;
1221}
1222
1223void AwesomePlayer::seekAudioIfNecessary_l() {
1224    if (mSeeking != NO_SEEK && mVideoSource == NULL && mAudioPlayer != NULL) {
1225        mAudioPlayer->seekTo(mSeekTimeUs);
1226
1227        mWatchForAudioSeekComplete = true;
1228        mWatchForAudioEOS = true;
1229
1230        if (mDecryptHandle != NULL) {
1231            mDrmManagerClient->setPlaybackStatus(mDecryptHandle,
1232                    Playback::PAUSE, 0);
1233            mDrmManagerClient->setPlaybackStatus(mDecryptHandle,
1234                    Playback::START, mSeekTimeUs / 1000);
1235        }
1236    }
1237}
1238
1239void AwesomePlayer::setAudioSource(sp<MediaSource> source) {
1240    CHECK(source != NULL);
1241
1242    mAudioTrack = source;
1243}
1244
1245void AwesomePlayer::addTextSource(sp<MediaSource> source) {
1246    CHECK(source != NULL);
1247
1248    if (mTextPlayer == NULL) {
1249        mTextPlayer = new TimedTextPlayer(this, mListener, &mQueue);
1250    }
1251
1252    mTextPlayer->addTextSource(source);
1253}
1254
1255status_t AwesomePlayer::initAudioDecoder() {
1256    sp<MetaData> meta = mAudioTrack->getFormat();
1257
1258    const char *mime;
1259    CHECK(meta->findCString(kKeyMIMEType, &mime));
1260
1261    if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_RAW)) {
1262        mAudioSource = mAudioTrack;
1263    } else {
1264        mAudioSource = OMXCodec::Create(
1265                mClient.interface(), mAudioTrack->getFormat(),
1266                false, // createEncoder
1267                mAudioTrack);
1268    }
1269
1270    if (mAudioSource != NULL) {
1271        int64_t durationUs;
1272        if (mAudioTrack->getFormat()->findInt64(kKeyDuration, &durationUs)) {
1273            Mutex::Autolock autoLock(mMiscStateLock);
1274            if (mDurationUs < 0 || durationUs > mDurationUs) {
1275                mDurationUs = durationUs;
1276            }
1277        }
1278
1279        status_t err = mAudioSource->start();
1280
1281        if (err != OK) {
1282            mAudioSource.clear();
1283            return err;
1284        }
1285    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_QCELP)) {
1286        // For legacy reasons we're simply going to ignore the absence
1287        // of an audio decoder for QCELP instead of aborting playback
1288        // altogether.
1289        return OK;
1290    }
1291
1292    return mAudioSource != NULL ? OK : UNKNOWN_ERROR;
1293}
1294
1295void AwesomePlayer::setVideoSource(sp<MediaSource> source) {
1296    CHECK(source != NULL);
1297
1298    mVideoTrack = source;
1299}
1300
1301status_t AwesomePlayer::initVideoDecoder(uint32_t flags) {
1302
1303    // Either the application or the DRM system can independently say
1304    // that there must be a hardware-protected path to an external video sink.
1305    // For now we always require a hardware-protected path to external video sink
1306    // if content is DRMed, but eventually this could be optional per DRM agent.
1307    // When the application wants protection, then
1308    //   (USE_SURFACE_ALLOC && (mSurface != 0) &&
1309    //   (mSurface->getFlags() & ISurfaceComposer::eProtectedByApp))
1310    // will be true, but that part is already handled by SurfaceFlinger.
1311
1312#ifdef DEBUG_HDCP
1313    // For debugging, we allow a system property to control the protected usage.
1314    // In case of uninitialized or unexpected property, we default to "DRM only".
1315    bool setProtectionBit = false;
1316    char value[PROPERTY_VALUE_MAX];
1317    if (property_get("persist.sys.hdcp_checking", value, NULL)) {
1318        if (!strcmp(value, "never")) {
1319            // nop
1320        } else if (!strcmp(value, "always")) {
1321            setProtectionBit = true;
1322        } else if (!strcmp(value, "drm-only")) {
1323            if (mDecryptHandle != NULL) {
1324                setProtectionBit = true;
1325            }
1326        // property value is empty, or unexpected value
1327        } else {
1328            if (mDecryptHandle != NULL) {
1329                setProtectionBit = true;
1330            }
1331        }
1332    // can' read property value
1333    } else {
1334        if (mDecryptHandle != NULL) {
1335            setProtectionBit = true;
1336        }
1337    }
1338    // note that usage bit is already cleared, so no need to clear it in the "else" case
1339    if (setProtectionBit) {
1340        flags |= OMXCodec::kEnableGrallocUsageProtected;
1341    }
1342#else
1343    if (mDecryptHandle != NULL) {
1344        flags |= OMXCodec::kEnableGrallocUsageProtected;
1345    }
1346#endif
1347    LOGV("initVideoDecoder flags=0x%x", flags);
1348    mVideoSource = OMXCodec::Create(
1349            mClient.interface(), mVideoTrack->getFormat(),
1350            false, // createEncoder
1351            mVideoTrack,
1352            NULL, flags, USE_SURFACE_ALLOC ? mNativeWindow : NULL);
1353
1354    if (mVideoSource != NULL) {
1355        int64_t durationUs;
1356        if (mVideoTrack->getFormat()->findInt64(kKeyDuration, &durationUs)) {
1357            Mutex::Autolock autoLock(mMiscStateLock);
1358            if (mDurationUs < 0 || durationUs > mDurationUs) {
1359                mDurationUs = durationUs;
1360            }
1361        }
1362
1363        status_t err = mVideoSource->start();
1364
1365        if (err != OK) {
1366            mVideoSource.clear();
1367            return err;
1368        }
1369    }
1370
1371    return mVideoSource != NULL ? OK : UNKNOWN_ERROR;
1372}
1373
1374void AwesomePlayer::finishSeekIfNecessary(int64_t videoTimeUs) {
1375    if (mSeeking == SEEK_VIDEO_ONLY) {
1376        mSeeking = NO_SEEK;
1377        return;
1378    }
1379
1380    if (mSeeking == NO_SEEK || (mFlags & SEEK_PREVIEW)) {
1381        return;
1382    }
1383
1384    if (mAudioPlayer != NULL) {
1385        LOGV("seeking audio to %lld us (%.2f secs).", videoTimeUs, videoTimeUs / 1E6);
1386
1387        // If we don't have a video time, seek audio to the originally
1388        // requested seek time instead.
1389
1390        mAudioPlayer->seekTo(videoTimeUs < 0 ? mSeekTimeUs : videoTimeUs);
1391        mWatchForAudioSeekComplete = true;
1392        mWatchForAudioEOS = true;
1393    } else if (!mSeekNotificationSent) {
1394        // If we're playing video only, report seek complete now,
1395        // otherwise audio player will notify us later.
1396        notifyListener_l(MEDIA_SEEK_COMPLETE);
1397        mSeekNotificationSent = true;
1398    }
1399
1400    mFlags |= FIRST_FRAME;
1401    mSeeking = NO_SEEK;
1402
1403    if (mDecryptHandle != NULL) {
1404        mDrmManagerClient->setPlaybackStatus(mDecryptHandle,
1405                Playback::PAUSE, 0);
1406        mDrmManagerClient->setPlaybackStatus(mDecryptHandle,
1407                Playback::START, videoTimeUs / 1000);
1408    }
1409}
1410
1411void AwesomePlayer::onVideoEvent() {
1412    Mutex::Autolock autoLock(mLock);
1413    if (!mVideoEventPending) {
1414        // The event has been cancelled in reset_l() but had already
1415        // been scheduled for execution at that time.
1416        return;
1417    }
1418    mVideoEventPending = false;
1419
1420    if (mSeeking != NO_SEEK) {
1421        if (mVideoBuffer) {
1422            mVideoBuffer->release();
1423            mVideoBuffer = NULL;
1424        }
1425
1426        if (mSeeking == SEEK && mCachedSource != NULL && mAudioSource != NULL
1427                && !(mFlags & SEEK_PREVIEW)) {
1428            // We're going to seek the video source first, followed by
1429            // the audio source.
1430            // In order to avoid jumps in the DataSource offset caused by
1431            // the audio codec prefetching data from the old locations
1432            // while the video codec is already reading data from the new
1433            // locations, we'll "pause" the audio source, causing it to
1434            // stop reading input data until a subsequent seek.
1435
1436            if (mAudioPlayer != NULL && (mFlags & AUDIO_RUNNING)) {
1437                mAudioPlayer->pause();
1438
1439                mFlags &= ~AUDIO_RUNNING;
1440            }
1441            mAudioSource->pause();
1442        }
1443    }
1444
1445    if (!mVideoBuffer) {
1446        MediaSource::ReadOptions options;
1447        if (mSeeking != NO_SEEK) {
1448            LOGV("seeking to %lld us (%.2f secs)", mSeekTimeUs, mSeekTimeUs / 1E6);
1449
1450            options.setSeekTo(
1451                    mSeekTimeUs,
1452                    mSeeking == SEEK_VIDEO_ONLY
1453                        ? MediaSource::ReadOptions::SEEK_NEXT_SYNC
1454                        : MediaSource::ReadOptions::SEEK_CLOSEST_SYNC);
1455        }
1456        for (;;) {
1457            status_t err = mVideoSource->read(&mVideoBuffer, &options);
1458            options.clearSeekTo();
1459
1460            if (err != OK) {
1461                CHECK(mVideoBuffer == NULL);
1462
1463                if (err == INFO_FORMAT_CHANGED) {
1464                    LOGV("VideoSource signalled format change.");
1465
1466                    notifyVideoSize_l();
1467
1468                    if (mVideoRenderer != NULL) {
1469                        mVideoRendererIsPreview = false;
1470                        initRenderer_l();
1471                    }
1472                    continue;
1473                }
1474
1475                // So video playback is complete, but we may still have
1476                // a seek request pending that needs to be applied
1477                // to the audio track.
1478                if (mSeeking != NO_SEEK) {
1479                    LOGV("video stream ended while seeking!");
1480                }
1481                finishSeekIfNecessary(-1);
1482
1483                if (mAudioPlayer != NULL
1484                        && !(mFlags & (AUDIO_RUNNING | SEEK_PREVIEW))) {
1485                    startAudioPlayer_l();
1486                }
1487
1488                mFlags |= VIDEO_AT_EOS;
1489                postStreamDoneEvent_l(err);
1490                return;
1491            }
1492
1493            if (mVideoBuffer->range_length() == 0) {
1494                // Some decoders, notably the PV AVC software decoder
1495                // return spurious empty buffers that we just want to ignore.
1496
1497                mVideoBuffer->release();
1498                mVideoBuffer = NULL;
1499                continue;
1500            }
1501
1502            break;
1503        }
1504    }
1505
1506    int64_t timeUs;
1507    CHECK(mVideoBuffer->meta_data()->findInt64(kKeyTime, &timeUs));
1508
1509    mLastVideoTimeUs = timeUs;
1510
1511    if (mSeeking == SEEK_VIDEO_ONLY) {
1512        if (mSeekTimeUs > timeUs) {
1513            LOGI("XXX mSeekTimeUs = %lld us, timeUs = %lld us",
1514                 mSeekTimeUs, timeUs);
1515        }
1516    }
1517
1518    {
1519        Mutex::Autolock autoLock(mMiscStateLock);
1520        mVideoTimeUs = timeUs;
1521    }
1522
1523    SeekType wasSeeking = mSeeking;
1524    finishSeekIfNecessary(timeUs);
1525
1526    if (mAudioPlayer != NULL && !(mFlags & (AUDIO_RUNNING | SEEK_PREVIEW))) {
1527        status_t err = startAudioPlayer_l();
1528        if (err != OK) {
1529            LOGE("Startung the audio player failed w/ err %d", err);
1530            return;
1531        }
1532    }
1533
1534    if ((mFlags & TEXTPLAYER_STARTED) && !(mFlags & (TEXT_RUNNING | SEEK_PREVIEW))) {
1535        mTextPlayer->resume();
1536        mFlags |= TEXT_RUNNING;
1537    }
1538
1539    TimeSource *ts = (mFlags & AUDIO_AT_EOS) ? &mSystemTimeSource : mTimeSource;
1540
1541    if (mFlags & FIRST_FRAME) {
1542        mFlags &= ~FIRST_FRAME;
1543        mTimeSourceDeltaUs = ts->getRealTimeUs() - timeUs;
1544    }
1545
1546    int64_t realTimeUs, mediaTimeUs;
1547    if (!(mFlags & AUDIO_AT_EOS) && mAudioPlayer != NULL
1548        && mAudioPlayer->getMediaTimeMapping(&realTimeUs, &mediaTimeUs)) {
1549        mTimeSourceDeltaUs = realTimeUs - mediaTimeUs;
1550    }
1551
1552    if (wasSeeking == SEEK_VIDEO_ONLY) {
1553        int64_t nowUs = ts->getRealTimeUs() - mTimeSourceDeltaUs;
1554
1555        int64_t latenessUs = nowUs - timeUs;
1556
1557        if (latenessUs > 0) {
1558            LOGI("after SEEK_VIDEO_ONLY we're late by %.2f secs", latenessUs / 1E6);
1559        }
1560    }
1561
1562    if (wasSeeking == NO_SEEK) {
1563        // Let's display the first frame after seeking right away.
1564
1565        int64_t nowUs = ts->getRealTimeUs() - mTimeSourceDeltaUs;
1566
1567        int64_t latenessUs = nowUs - timeUs;
1568
1569        if (latenessUs > 500000ll
1570                && mRTSPController == NULL
1571                && mAudioPlayer != NULL
1572                && mAudioPlayer->getMediaTimeMapping(
1573                    &realTimeUs, &mediaTimeUs)) {
1574            LOGI("we're much too late (%.2f secs), video skipping ahead",
1575                 latenessUs / 1E6);
1576
1577            mVideoBuffer->release();
1578            mVideoBuffer = NULL;
1579
1580            mSeeking = SEEK_VIDEO_ONLY;
1581            mSeekTimeUs = mediaTimeUs;
1582
1583            postVideoEvent_l();
1584            return;
1585        }
1586
1587        if (latenessUs > 40000) {
1588            // We're more than 40ms late.
1589            LOGV("we're late by %lld us (%.2f secs), dropping frame",
1590                 latenessUs, latenessUs / 1E6);
1591            mVideoBuffer->release();
1592            mVideoBuffer = NULL;
1593
1594            postVideoEvent_l();
1595            return;
1596        }
1597
1598        if (latenessUs < -10000) {
1599            // We're more than 10ms early.
1600
1601            postVideoEvent_l(10000);
1602            return;
1603        }
1604    }
1605
1606    if (mVideoRendererIsPreview || mVideoRenderer == NULL) {
1607        mVideoRendererIsPreview = false;
1608
1609        initRenderer_l();
1610    }
1611
1612    if (mVideoRenderer != NULL) {
1613        mVideoRenderer->render(mVideoBuffer);
1614    }
1615
1616    mVideoBuffer->release();
1617    mVideoBuffer = NULL;
1618
1619    if (wasSeeking != NO_SEEK && (mFlags & SEEK_PREVIEW)) {
1620        mFlags &= ~SEEK_PREVIEW;
1621        return;
1622    }
1623
1624    postVideoEvent_l();
1625}
1626
1627void AwesomePlayer::postVideoEvent_l(int64_t delayUs) {
1628    if (mVideoEventPending) {
1629        return;
1630    }
1631
1632    mVideoEventPending = true;
1633    mQueue.postEventWithDelay(mVideoEvent, delayUs < 0 ? 10000 : delayUs);
1634}
1635
1636void AwesomePlayer::postStreamDoneEvent_l(status_t status) {
1637    if (mStreamDoneEventPending) {
1638        return;
1639    }
1640    mStreamDoneEventPending = true;
1641
1642    mStreamDoneStatus = status;
1643    mQueue.postEvent(mStreamDoneEvent);
1644}
1645
1646void AwesomePlayer::postBufferingEvent_l() {
1647    if (mBufferingEventPending) {
1648        return;
1649    }
1650    mBufferingEventPending = true;
1651    mQueue.postEventWithDelay(mBufferingEvent, 1000000ll);
1652}
1653
1654void AwesomePlayer::postVideoLagEvent_l() {
1655    if (mVideoLagEventPending) {
1656        return;
1657    }
1658    mVideoLagEventPending = true;
1659    mQueue.postEventWithDelay(mVideoLagEvent, 1000000ll);
1660}
1661
1662void AwesomePlayer::postCheckAudioStatusEvent_l(int64_t delayUs) {
1663    if (mAudioStatusEventPending) {
1664        return;
1665    }
1666    mAudioStatusEventPending = true;
1667    mQueue.postEventWithDelay(mCheckAudioStatusEvent, delayUs);
1668}
1669
1670void AwesomePlayer::onCheckAudioStatus() {
1671    Mutex::Autolock autoLock(mLock);
1672    if (!mAudioStatusEventPending) {
1673        // Event was dispatched and while we were blocking on the mutex,
1674        // has already been cancelled.
1675        return;
1676    }
1677
1678    mAudioStatusEventPending = false;
1679
1680    if (mWatchForAudioSeekComplete && !mAudioPlayer->isSeeking()) {
1681        mWatchForAudioSeekComplete = false;
1682
1683        if (!mSeekNotificationSent) {
1684            notifyListener_l(MEDIA_SEEK_COMPLETE);
1685            mSeekNotificationSent = true;
1686        }
1687
1688        mSeeking = NO_SEEK;
1689    }
1690
1691    status_t finalStatus;
1692    if (mWatchForAudioEOS && mAudioPlayer->reachedEOS(&finalStatus)) {
1693        mWatchForAudioEOS = false;
1694        mFlags |= AUDIO_AT_EOS;
1695        mFlags |= FIRST_FRAME;
1696        postStreamDoneEvent_l(finalStatus);
1697    }
1698}
1699
1700status_t AwesomePlayer::prepare() {
1701    Mutex::Autolock autoLock(mLock);
1702    return prepare_l();
1703}
1704
1705status_t AwesomePlayer::prepare_l() {
1706    if (mFlags & PREPARED) {
1707        return OK;
1708    }
1709
1710    if (mFlags & PREPARING) {
1711        return UNKNOWN_ERROR;
1712    }
1713
1714    mIsAsyncPrepare = false;
1715    status_t err = prepareAsync_l();
1716
1717    if (err != OK) {
1718        return err;
1719    }
1720
1721    while (mFlags & PREPARING) {
1722        mPreparedCondition.wait(mLock);
1723    }
1724
1725    return mPrepareResult;
1726}
1727
1728status_t AwesomePlayer::prepareAsync() {
1729    Mutex::Autolock autoLock(mLock);
1730
1731    if (mFlags & PREPARING) {
1732        return UNKNOWN_ERROR;  // async prepare already pending
1733    }
1734
1735    mIsAsyncPrepare = true;
1736    return prepareAsync_l();
1737}
1738
1739status_t AwesomePlayer::prepareAsync_l() {
1740    if (mFlags & PREPARING) {
1741        return UNKNOWN_ERROR;  // async prepare already pending
1742    }
1743
1744    if (!mQueueStarted) {
1745        mQueue.start();
1746        mQueueStarted = true;
1747    }
1748
1749    mFlags |= PREPARING;
1750    mAsyncPrepareEvent = new AwesomeEvent(
1751            this, &AwesomePlayer::onPrepareAsyncEvent);
1752
1753    mQueue.postEvent(mAsyncPrepareEvent);
1754
1755    return OK;
1756}
1757
1758status_t AwesomePlayer::finishSetDataSource_l() {
1759    sp<DataSource> dataSource;
1760
1761    if (!strncasecmp("http://", mUri.string(), 7)
1762            || !strncasecmp("https://", mUri.string(), 8)) {
1763        mConnectingDataSource = HTTPBase::Create(
1764                (mFlags & INCOGNITO)
1765                    ? HTTPBase::kFlagIncognito
1766                    : 0);
1767
1768        mLock.unlock();
1769        status_t err = mConnectingDataSource->connect(mUri, &mUriHeaders);
1770        mLock.lock();
1771
1772        if (err != OK) {
1773            mConnectingDataSource.clear();
1774
1775            LOGI("mConnectingDataSource->connect() returned %d", err);
1776            return err;
1777        }
1778
1779#if 0
1780        mCachedSource = new NuCachedSource2(
1781                new ThrottledSource(
1782                    mConnectingDataSource, 50 * 1024 /* bytes/sec */));
1783#else
1784        mCachedSource = new NuCachedSource2(mConnectingDataSource);
1785#endif
1786        mConnectingDataSource.clear();
1787
1788        dataSource = mCachedSource;
1789
1790        String8 contentType = dataSource->getMIMEType();
1791
1792        if (strncasecmp(contentType.string(), "audio/", 6)) {
1793            // We're not doing this for streams that appear to be audio-only
1794            // streams to ensure that even low bandwidth streams start
1795            // playing back fairly instantly.
1796
1797            // We're going to prefill the cache before trying to instantiate
1798            // the extractor below, as the latter is an operation that otherwise
1799            // could block on the datasource for a significant amount of time.
1800            // During that time we'd be unable to abort the preparation phase
1801            // without this prefill.
1802
1803            mLock.unlock();
1804
1805            for (;;) {
1806                status_t finalStatus;
1807                size_t cachedDataRemaining =
1808                    mCachedSource->approxDataRemaining(&finalStatus);
1809
1810                if (finalStatus != OK || cachedDataRemaining >= kHighWaterMarkBytes
1811                        || (mFlags & PREPARE_CANCELLED)) {
1812                    break;
1813                }
1814
1815                usleep(200000);
1816            }
1817
1818            mLock.lock();
1819        }
1820
1821        if (mFlags & PREPARE_CANCELLED) {
1822            LOGI("Prepare cancelled while waiting for initial cache fill.");
1823            return UNKNOWN_ERROR;
1824        }
1825    } else if (!strncasecmp("rtsp://", mUri.string(), 7)) {
1826        if (mLooper == NULL) {
1827            mLooper = new ALooper;
1828            mLooper->setName("rtsp");
1829            mLooper->start();
1830        }
1831        mRTSPController = new ARTSPController(mLooper);
1832        mConnectingRTSPController = mRTSPController;
1833
1834        mLock.unlock();
1835        status_t err = mRTSPController->connect(mUri.string());
1836        mLock.lock();
1837
1838        mConnectingRTSPController.clear();
1839
1840        LOGI("ARTSPController::connect returned %d", err);
1841
1842        if (err != OK) {
1843            mRTSPController.clear();
1844            return err;
1845        }
1846
1847        sp<MediaExtractor> extractor = mRTSPController.get();
1848        return setDataSource_l(extractor);
1849    } else {
1850        dataSource = DataSource::CreateFromURI(mUri.string(), &mUriHeaders);
1851    }
1852
1853    if (dataSource == NULL) {
1854        return UNKNOWN_ERROR;
1855    }
1856
1857    sp<MediaExtractor> extractor = MediaExtractor::Create(dataSource);
1858
1859    if (extractor == NULL) {
1860        return UNKNOWN_ERROR;
1861    }
1862
1863    dataSource->getDrmInfo(mDecryptHandle, &mDrmManagerClient);
1864
1865    if (mDecryptHandle != NULL) {
1866        CHECK(mDrmManagerClient);
1867        if (RightsStatus::RIGHTS_VALID != mDecryptHandle->status) {
1868            notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, ERROR_DRM_NO_LICENSE);
1869        }
1870    }
1871
1872    return setDataSource_l(extractor);
1873}
1874
1875void AwesomePlayer::abortPrepare(status_t err) {
1876    CHECK(err != OK);
1877
1878    if (mIsAsyncPrepare) {
1879        notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err);
1880    }
1881
1882    mPrepareResult = err;
1883    mFlags &= ~(PREPARING|PREPARE_CANCELLED|PREPARING_CONNECTED);
1884    mAsyncPrepareEvent = NULL;
1885    mPreparedCondition.broadcast();
1886}
1887
1888// static
1889bool AwesomePlayer::ContinuePreparation(void *cookie) {
1890    AwesomePlayer *me = static_cast<AwesomePlayer *>(cookie);
1891
1892    return (me->mFlags & PREPARE_CANCELLED) == 0;
1893}
1894
1895void AwesomePlayer::onPrepareAsyncEvent() {
1896    Mutex::Autolock autoLock(mLock);
1897
1898    if (mFlags & PREPARE_CANCELLED) {
1899        LOGI("prepare was cancelled before doing anything");
1900        abortPrepare(UNKNOWN_ERROR);
1901        return;
1902    }
1903
1904    if (mUri.size() > 0) {
1905        status_t err = finishSetDataSource_l();
1906
1907        if (err != OK) {
1908            abortPrepare(err);
1909            return;
1910        }
1911    }
1912
1913    if (mVideoTrack != NULL && mVideoSource == NULL) {
1914        status_t err = initVideoDecoder();
1915
1916        if (err != OK) {
1917            abortPrepare(err);
1918            return;
1919        }
1920    }
1921
1922    if (mAudioTrack != NULL && mAudioSource == NULL) {
1923        status_t err = initAudioDecoder();
1924
1925        if (err != OK) {
1926            abortPrepare(err);
1927            return;
1928        }
1929    }
1930
1931    mFlags |= PREPARING_CONNECTED;
1932
1933    if (mCachedSource != NULL || mRTSPController != NULL) {
1934        postBufferingEvent_l();
1935    } else {
1936        finishAsyncPrepare_l();
1937    }
1938}
1939
1940void AwesomePlayer::finishAsyncPrepare_l() {
1941    if (mIsAsyncPrepare) {
1942        if (mVideoSource == NULL) {
1943            notifyListener_l(MEDIA_SET_VIDEO_SIZE, 0, 0);
1944        } else {
1945            notifyVideoSize_l();
1946        }
1947
1948        notifyListener_l(MEDIA_PREPARED);
1949    }
1950
1951    mPrepareResult = OK;
1952    mFlags &= ~(PREPARING|PREPARE_CANCELLED|PREPARING_CONNECTED);
1953    mFlags |= PREPARED;
1954    mAsyncPrepareEvent = NULL;
1955    mPreparedCondition.broadcast();
1956}
1957
1958uint32_t AwesomePlayer::flags() const {
1959    return mExtractorFlags;
1960}
1961
1962void AwesomePlayer::postAudioEOS(int64_t delayUs) {
1963    Mutex::Autolock autoLock(mLock);
1964    postCheckAudioStatusEvent_l(delayUs);
1965}
1966
1967void AwesomePlayer::postAudioSeekComplete() {
1968    Mutex::Autolock autoLock(mLock);
1969    postAudioSeekComplete_l();
1970}
1971
1972void AwesomePlayer::postAudioSeekComplete_l() {
1973    postCheckAudioStatusEvent_l(0 /* delayUs */);
1974}
1975
1976status_t AwesomePlayer::setParameter(int key, const Parcel &request) {
1977    if (key == KEY_PARAMETER_TIMED_TEXT_TRACK_INDEX) {
1978        return setTimedTextTrackIndex(request.readInt32());
1979    }
1980    return ERROR_UNSUPPORTED;
1981}
1982
1983status_t AwesomePlayer::getParameter(int key, Parcel *reply) {
1984    return OK;
1985}
1986}  // namespace android
1987