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