AwesomePlayer.cpp revision 3318523222e31fb4a7fcc345ddb4ec845d30ef96
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#define 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_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 (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        Mutex::Autolock autoLock(mMiscStateLock);
1057        *positionUs = mVideoTimeUs;
1058    } else if (mAudioPlayer != NULL) {
1059        *positionUs = mAudioPlayer->getMediaTimeUs();
1060    } else {
1061        *positionUs = 0;
1062    }
1063
1064    return OK;
1065}
1066
1067status_t AwesomePlayer::seekTo(int64_t timeUs) {
1068    if (mExtractorFlags & MediaExtractor::CAN_SEEK) {
1069        Mutex::Autolock autoLock(mLock);
1070        return seekTo_l(timeUs);
1071    }
1072
1073    return OK;
1074}
1075
1076// static
1077void AwesomePlayer::OnRTSPSeekDoneWrapper(void *cookie) {
1078    static_cast<AwesomePlayer *>(cookie)->onRTSPSeekDone();
1079}
1080
1081void AwesomePlayer::onRTSPSeekDone() {
1082    notifyListener_l(MEDIA_SEEK_COMPLETE);
1083    mSeekNotificationSent = true;
1084}
1085
1086status_t AwesomePlayer::seekTo_l(int64_t timeUs) {
1087    if (mRTSPController != NULL) {
1088        mRTSPController->seekAsync(timeUs, OnRTSPSeekDoneWrapper, this);
1089        return OK;
1090    }
1091
1092    if (mFlags & CACHE_UNDERRUN) {
1093        mFlags &= ~CACHE_UNDERRUN;
1094        play_l();
1095    }
1096
1097    mSeeking = SEEK;
1098    mSeekNotificationSent = false;
1099    mSeekTimeUs = timeUs;
1100    mFlags &= ~(AT_EOS | AUDIO_AT_EOS | VIDEO_AT_EOS);
1101
1102    seekAudioIfNecessary_l();
1103
1104    if (!(mFlags & PLAYING)) {
1105        LOGV("seeking while paused, sending SEEK_COMPLETE notification"
1106             " immediately.");
1107
1108        notifyListener_l(MEDIA_SEEK_COMPLETE);
1109        mSeekNotificationSent = true;
1110
1111        if ((mFlags & PREPARED) && mVideoSource != NULL) {
1112            mFlags |= SEEK_PREVIEW;
1113            postVideoEvent_l();
1114        }
1115    }
1116
1117    return OK;
1118}
1119
1120void AwesomePlayer::seekAudioIfNecessary_l() {
1121    if (mSeeking != NO_SEEK && mVideoSource == NULL && mAudioPlayer != NULL) {
1122        mAudioPlayer->seekTo(mSeekTimeUs);
1123
1124        mWatchForAudioSeekComplete = true;
1125        mWatchForAudioEOS = true;
1126        mSeekNotificationSent = false;
1127
1128        if (mDecryptHandle != NULL) {
1129            mDrmManagerClient->setPlaybackStatus(mDecryptHandle,
1130                    Playback::PAUSE, 0);
1131            mDrmManagerClient->setPlaybackStatus(mDecryptHandle,
1132                    Playback::START, mSeekTimeUs / 1000);
1133        }
1134    }
1135}
1136
1137void AwesomePlayer::setAudioSource(sp<MediaSource> source) {
1138    CHECK(source != NULL);
1139
1140    mAudioTrack = source;
1141}
1142
1143status_t AwesomePlayer::initAudioDecoder() {
1144    sp<MetaData> meta = mAudioTrack->getFormat();
1145
1146    const char *mime;
1147    CHECK(meta->findCString(kKeyMIMEType, &mime));
1148
1149    if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_RAW)) {
1150        mAudioSource = mAudioTrack;
1151    } else {
1152        mAudioSource = OMXCodec::Create(
1153                mClient.interface(), mAudioTrack->getFormat(),
1154                false, // createEncoder
1155                mAudioTrack);
1156    }
1157
1158    if (mAudioSource != NULL) {
1159        int64_t durationUs;
1160        if (mAudioTrack->getFormat()->findInt64(kKeyDuration, &durationUs)) {
1161            Mutex::Autolock autoLock(mMiscStateLock);
1162            if (mDurationUs < 0 || durationUs > mDurationUs) {
1163                mDurationUs = durationUs;
1164            }
1165        }
1166
1167        status_t err = mAudioSource->start();
1168
1169        if (err != OK) {
1170            mAudioSource.clear();
1171            return err;
1172        }
1173    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_QCELP)) {
1174        // For legacy reasons we're simply going to ignore the absence
1175        // of an audio decoder for QCELP instead of aborting playback
1176        // altogether.
1177        return OK;
1178    }
1179
1180    return mAudioSource != NULL ? OK : UNKNOWN_ERROR;
1181}
1182
1183void AwesomePlayer::setVideoSource(sp<MediaSource> source) {
1184    CHECK(source != NULL);
1185
1186    mVideoTrack = source;
1187}
1188
1189status_t AwesomePlayer::initVideoDecoder(uint32_t flags) {
1190
1191    // Either the application or the DRM system can independently say
1192    // that there must be a hardware-protected path to an external video sink.
1193    // For now we always require a hardware-protected path to external video sink
1194    // if content is DRMed, but eventually this could be optional per DRM agent.
1195    // When the application wants protection, then
1196    //   (USE_SURFACE_ALLOC && (mSurface != 0) &&
1197    //   (mSurface->getFlags() & ISurfaceComposer::eProtectedByApp))
1198    // will be true, but that part is already handled by SurfaceFlinger.
1199
1200#ifdef DEBUG_HDCP
1201    // For debugging, we allow a system property to control the protected usage.
1202    // In case of uninitialized or unexpected property, we default to "DRM only".
1203    bool setProtectionBit = false;
1204    char value[PROPERTY_VALUE_MAX];
1205    if (property_get("persist.sys.hdcp_checking", value, NULL)) {
1206        if (!strcmp(value, "never")) {
1207            // nop
1208        } else if (!strcmp(value, "always")) {
1209            setProtectionBit = true;
1210        } else if (!strcmp(value, "drm-only")) {
1211            if (mDecryptHandle != NULL) {
1212                setProtectionBit = true;
1213            }
1214        // property value is empty, or unexpected value
1215        } else {
1216            if (mDecryptHandle != NULL) {
1217                setProtectionBit = true;
1218            }
1219        }
1220    // can' read property value
1221    } else {
1222        if (mDecryptHandle != NULL) {
1223            setProtectionBit = true;
1224        }
1225    }
1226    // note that usage bit is already cleared, so no need to clear it in the "else" case
1227    if (setProtectionBit) {
1228        flags |= OMXCodec::kEnableGrallocUsageProtected;
1229    }
1230#else
1231    if (mDecryptHandle != NULL) {
1232        flags |= OMXCodec::kEnableGrallocUsageProtected;
1233    }
1234#endif
1235    LOGV("initVideoDecoder flags=0x%x", flags);
1236    mVideoSource = OMXCodec::Create(
1237            mClient.interface(), mVideoTrack->getFormat(),
1238            false, // createEncoder
1239            mVideoTrack,
1240            NULL, flags, USE_SURFACE_ALLOC ? mNativeWindow : NULL);
1241
1242    if (mVideoSource != NULL) {
1243        int64_t durationUs;
1244        if (mVideoTrack->getFormat()->findInt64(kKeyDuration, &durationUs)) {
1245            Mutex::Autolock autoLock(mMiscStateLock);
1246            if (mDurationUs < 0 || durationUs > mDurationUs) {
1247                mDurationUs = durationUs;
1248            }
1249        }
1250
1251        status_t err = mVideoSource->start();
1252
1253        if (err != OK) {
1254            mVideoSource.clear();
1255            return err;
1256        }
1257    }
1258
1259    return mVideoSource != NULL ? OK : UNKNOWN_ERROR;
1260}
1261
1262void AwesomePlayer::finishSeekIfNecessary(int64_t videoTimeUs) {
1263    if (mSeeking == SEEK_VIDEO_ONLY) {
1264        mSeeking = NO_SEEK;
1265        return;
1266    }
1267
1268    if (mSeeking == NO_SEEK || (mFlags & SEEK_PREVIEW)) {
1269        return;
1270    }
1271
1272    if (mAudioPlayer != NULL) {
1273        LOGV("seeking audio to %lld us (%.2f secs).", videoTimeUs, videoTimeUs / 1E6);
1274
1275        // If we don't have a video time, seek audio to the originally
1276        // requested seek time instead.
1277
1278        mAudioPlayer->seekTo(videoTimeUs < 0 ? mSeekTimeUs : videoTimeUs);
1279        mWatchForAudioSeekComplete = true;
1280    } else if (!mSeekNotificationSent) {
1281        // If we're playing video only, report seek complete now,
1282        // otherwise audio player will notify us later.
1283        notifyListener_l(MEDIA_SEEK_COMPLETE);
1284    }
1285
1286    mFlags |= FIRST_FRAME;
1287    mSeeking = NO_SEEK;
1288    mSeekNotificationSent = false;
1289
1290    if (mDecryptHandle != NULL) {
1291        mDrmManagerClient->setPlaybackStatus(mDecryptHandle,
1292                Playback::PAUSE, 0);
1293        mDrmManagerClient->setPlaybackStatus(mDecryptHandle,
1294                Playback::START, videoTimeUs / 1000);
1295    }
1296}
1297
1298void AwesomePlayer::onVideoEvent() {
1299    Mutex::Autolock autoLock(mLock);
1300    if (!mVideoEventPending) {
1301        // The event has been cancelled in reset_l() but had already
1302        // been scheduled for execution at that time.
1303        return;
1304    }
1305    mVideoEventPending = false;
1306
1307    if (mSeeking != NO_SEEK) {
1308        if (mVideoBuffer) {
1309            mVideoBuffer->release();
1310            mVideoBuffer = NULL;
1311        }
1312
1313        if (mSeeking == SEEK && mCachedSource != NULL && mAudioSource != NULL
1314                && !(mFlags & SEEK_PREVIEW)) {
1315            // We're going to seek the video source first, followed by
1316            // the audio source.
1317            // In order to avoid jumps in the DataSource offset caused by
1318            // the audio codec prefetching data from the old locations
1319            // while the video codec is already reading data from the new
1320            // locations, we'll "pause" the audio source, causing it to
1321            // stop reading input data until a subsequent seek.
1322
1323            if (mAudioPlayer != NULL && (mFlags & AUDIO_RUNNING)) {
1324                mAudioPlayer->pause();
1325
1326                mFlags &= ~AUDIO_RUNNING;
1327            }
1328            mAudioSource->pause();
1329        }
1330    }
1331
1332    if (!mVideoBuffer) {
1333        MediaSource::ReadOptions options;
1334        if (mSeeking != NO_SEEK) {
1335            LOGV("seeking to %lld us (%.2f secs)", mSeekTimeUs, mSeekTimeUs / 1E6);
1336
1337            options.setSeekTo(
1338                    mSeekTimeUs,
1339                    mSeeking == SEEK_VIDEO_ONLY
1340                        ? MediaSource::ReadOptions::SEEK_NEXT_SYNC
1341                        : MediaSource::ReadOptions::SEEK_CLOSEST_SYNC);
1342        }
1343        for (;;) {
1344            status_t err = mVideoSource->read(&mVideoBuffer, &options);
1345            options.clearSeekTo();
1346
1347            if (err != OK) {
1348                CHECK(mVideoBuffer == NULL);
1349
1350                if (err == INFO_FORMAT_CHANGED) {
1351                    LOGV("VideoSource signalled format change.");
1352
1353                    notifyVideoSize_l();
1354
1355                    if (mVideoRenderer != NULL) {
1356                        mVideoRendererIsPreview = false;
1357                        initRenderer_l();
1358                    }
1359                    continue;
1360                }
1361
1362                // So video playback is complete, but we may still have
1363                // a seek request pending that needs to be applied
1364                // to the audio track.
1365                if (mSeeking != NO_SEEK) {
1366                    LOGV("video stream ended while seeking!");
1367                }
1368                finishSeekIfNecessary(-1);
1369
1370                mFlags |= VIDEO_AT_EOS;
1371                postStreamDoneEvent_l(err);
1372                return;
1373            }
1374
1375            if (mVideoBuffer->range_length() == 0) {
1376                // Some decoders, notably the PV AVC software decoder
1377                // return spurious empty buffers that we just want to ignore.
1378
1379                mVideoBuffer->release();
1380                mVideoBuffer = NULL;
1381                continue;
1382            }
1383
1384            break;
1385        }
1386    }
1387
1388    int64_t timeUs;
1389    CHECK(mVideoBuffer->meta_data()->findInt64(kKeyTime, &timeUs));
1390
1391    if (mSeeking == SEEK_VIDEO_ONLY) {
1392        if (mSeekTimeUs > timeUs) {
1393            LOGI("XXX mSeekTimeUs = %lld us, timeUs = %lld us",
1394                 mSeekTimeUs, timeUs);
1395        }
1396    }
1397
1398    {
1399        Mutex::Autolock autoLock(mMiscStateLock);
1400        mVideoTimeUs = timeUs;
1401    }
1402
1403    SeekType wasSeeking = mSeeking;
1404    finishSeekIfNecessary(timeUs);
1405
1406    if (mAudioPlayer != NULL && !(mFlags & (AUDIO_RUNNING | SEEK_PREVIEW))) {
1407        status_t err = startAudioPlayer_l();
1408        if (err != OK) {
1409            LOGE("Startung the audio player failed w/ err %d", err);
1410            return;
1411        }
1412    }
1413
1414    TimeSource *ts = (mFlags & AUDIO_AT_EOS) ? &mSystemTimeSource : mTimeSource;
1415
1416    if (mFlags & FIRST_FRAME) {
1417        mFlags &= ~FIRST_FRAME;
1418        mSinceLastDropped = 0;
1419        mTimeSourceDeltaUs = ts->getRealTimeUs() - timeUs;
1420    }
1421
1422    int64_t realTimeUs, mediaTimeUs;
1423    if (!(mFlags & AUDIO_AT_EOS) && mAudioPlayer != NULL
1424        && mAudioPlayer->getMediaTimeMapping(&realTimeUs, &mediaTimeUs)) {
1425        mTimeSourceDeltaUs = realTimeUs - mediaTimeUs;
1426    }
1427
1428    if (wasSeeking == SEEK_VIDEO_ONLY) {
1429        int64_t nowUs = ts->getRealTimeUs() - mTimeSourceDeltaUs;
1430
1431        int64_t latenessUs = nowUs - timeUs;
1432
1433        if (latenessUs > 0) {
1434            LOGI("after SEEK_VIDEO_ONLY we're late by %.2f secs", latenessUs / 1E6);
1435        }
1436    }
1437
1438    if (wasSeeking == NO_SEEK) {
1439        // Let's display the first frame after seeking right away.
1440
1441        int64_t nowUs = ts->getRealTimeUs() - mTimeSourceDeltaUs;
1442
1443        int64_t latenessUs = nowUs - timeUs;
1444
1445        if (latenessUs > 500000ll
1446                && mRTSPController == NULL
1447                && mAudioPlayer != NULL
1448                && mAudioPlayer->getMediaTimeMapping(
1449                    &realTimeUs, &mediaTimeUs)) {
1450            LOGI("we're much too late (%.2f secs), video skipping ahead",
1451                 latenessUs / 1E6);
1452
1453            mVideoBuffer->release();
1454            mVideoBuffer = NULL;
1455
1456            mSeeking = SEEK_VIDEO_ONLY;
1457            mSeekTimeUs = mediaTimeUs;
1458
1459            postVideoEvent_l();
1460            return;
1461        }
1462
1463        if (latenessUs > 40000) {
1464            // We're more than 40ms late.
1465            LOGV("we're late by %lld us (%.2f secs)", latenessUs, latenessUs / 1E6);
1466            if ( mSinceLastDropped > FRAME_DROP_FREQ)
1467            {
1468                LOGV("we're late by %lld us (%.2f secs) dropping one after %d frames", latenessUs, latenessUs / 1E6, mSinceLastDropped);
1469                mSinceLastDropped = 0;
1470                mVideoBuffer->release();
1471                mVideoBuffer = NULL;
1472
1473                postVideoEvent_l();
1474                return;
1475            }
1476        }
1477
1478        if (latenessUs < -10000) {
1479            // We're more than 10ms early.
1480
1481            postVideoEvent_l(10000);
1482            return;
1483        }
1484    }
1485
1486    if (mVideoRendererIsPreview || mVideoRenderer == NULL) {
1487        mVideoRendererIsPreview = false;
1488
1489        initRenderer_l();
1490    }
1491
1492    if (mVideoRenderer != NULL) {
1493        mSinceLastDropped++;
1494        mVideoRenderer->render(mVideoBuffer);
1495    }
1496
1497    mVideoBuffer->release();
1498    mVideoBuffer = NULL;
1499
1500    if (wasSeeking != NO_SEEK && (mFlags & SEEK_PREVIEW)) {
1501        mFlags &= ~SEEK_PREVIEW;
1502        return;
1503    }
1504
1505    postVideoEvent_l();
1506}
1507
1508void AwesomePlayer::postVideoEvent_l(int64_t delayUs) {
1509    if (mVideoEventPending) {
1510        return;
1511    }
1512
1513    mVideoEventPending = true;
1514    mQueue.postEventWithDelay(mVideoEvent, delayUs < 0 ? 10000 : delayUs);
1515}
1516
1517void AwesomePlayer::postStreamDoneEvent_l(status_t status) {
1518    if (mStreamDoneEventPending) {
1519        return;
1520    }
1521    mStreamDoneEventPending = true;
1522
1523    mStreamDoneStatus = status;
1524    mQueue.postEvent(mStreamDoneEvent);
1525}
1526
1527void AwesomePlayer::postBufferingEvent_l() {
1528    if (mBufferingEventPending) {
1529        return;
1530    }
1531    mBufferingEventPending = true;
1532    mQueue.postEventWithDelay(mBufferingEvent, 1000000ll);
1533}
1534
1535void AwesomePlayer::postVideoLagEvent_l() {
1536    if (mVideoLagEventPending) {
1537        return;
1538    }
1539    mVideoLagEventPending = true;
1540    mQueue.postEventWithDelay(mVideoLagEvent, 1000000ll);
1541}
1542
1543void AwesomePlayer::postCheckAudioStatusEvent_l() {
1544    if (mAudioStatusEventPending) {
1545        return;
1546    }
1547    mAudioStatusEventPending = true;
1548    mQueue.postEvent(mCheckAudioStatusEvent);
1549}
1550
1551void AwesomePlayer::onCheckAudioStatus() {
1552    Mutex::Autolock autoLock(mLock);
1553    if (!mAudioStatusEventPending) {
1554        // Event was dispatched and while we were blocking on the mutex,
1555        // has already been cancelled.
1556        return;
1557    }
1558
1559    mAudioStatusEventPending = false;
1560
1561    if (mWatchForAudioSeekComplete && !mAudioPlayer->isSeeking()) {
1562        mWatchForAudioSeekComplete = false;
1563
1564        if (!mSeekNotificationSent) {
1565            notifyListener_l(MEDIA_SEEK_COMPLETE);
1566            mSeekNotificationSent = true;
1567        }
1568
1569        mSeeking = NO_SEEK;
1570    }
1571
1572    status_t finalStatus;
1573    if (mWatchForAudioEOS && mAudioPlayer->reachedEOS(&finalStatus)) {
1574        mWatchForAudioEOS = false;
1575        mFlags |= AUDIO_AT_EOS;
1576        mFlags |= FIRST_FRAME;
1577        postStreamDoneEvent_l(finalStatus);
1578    }
1579}
1580
1581status_t AwesomePlayer::prepare() {
1582    Mutex::Autolock autoLock(mLock);
1583    return prepare_l();
1584}
1585
1586status_t AwesomePlayer::prepare_l() {
1587    if (mFlags & PREPARED) {
1588        return OK;
1589    }
1590
1591    if (mFlags & PREPARING) {
1592        return UNKNOWN_ERROR;
1593    }
1594
1595    mIsAsyncPrepare = false;
1596    status_t err = prepareAsync_l();
1597
1598    if (err != OK) {
1599        return err;
1600    }
1601
1602    while (mFlags & PREPARING) {
1603        mPreparedCondition.wait(mLock);
1604    }
1605
1606    return mPrepareResult;
1607}
1608
1609status_t AwesomePlayer::prepareAsync() {
1610    Mutex::Autolock autoLock(mLock);
1611
1612    if (mFlags & PREPARING) {
1613        return UNKNOWN_ERROR;  // async prepare already pending
1614    }
1615
1616    mIsAsyncPrepare = true;
1617    return prepareAsync_l();
1618}
1619
1620status_t AwesomePlayer::prepareAsync_l() {
1621    if (mFlags & PREPARING) {
1622        return UNKNOWN_ERROR;  // async prepare already pending
1623    }
1624
1625    if (!mQueueStarted) {
1626        mQueue.start();
1627        mQueueStarted = true;
1628    }
1629
1630    mFlags |= PREPARING;
1631    mAsyncPrepareEvent = new AwesomeEvent(
1632            this, &AwesomePlayer::onPrepareAsyncEvent);
1633
1634    mQueue.postEvent(mAsyncPrepareEvent);
1635
1636    return OK;
1637}
1638
1639status_t AwesomePlayer::finishSetDataSource_l() {
1640    sp<DataSource> dataSource;
1641
1642    if (!strncasecmp("http://", mUri.string(), 7)
1643            || !strncasecmp("https://", mUri.string(), 8)) {
1644        mConnectingDataSource = new NuHTTPDataSource(
1645                (mFlags & INCOGNITO) ? NuHTTPDataSource::kFlagIncognito : 0);
1646
1647        mLock.unlock();
1648        status_t err = mConnectingDataSource->connect(mUri, &mUriHeaders);
1649        mLock.lock();
1650
1651        if (err != OK) {
1652            mConnectingDataSource.clear();
1653
1654            LOGI("mConnectingDataSource->connect() returned %d", err);
1655            return err;
1656        }
1657
1658#if 0
1659        mCachedSource = new NuCachedSource2(
1660                new ThrottledSource(
1661                    mConnectingDataSource, 50 * 1024 /* bytes/sec */));
1662#else
1663        mCachedSource = new NuCachedSource2(mConnectingDataSource);
1664#endif
1665        mConnectingDataSource.clear();
1666
1667        dataSource = mCachedSource;
1668
1669        // We're going to prefill the cache before trying to instantiate
1670        // the extractor below, as the latter is an operation that otherwise
1671        // could block on the datasource for a significant amount of time.
1672        // During that time we'd be unable to abort the preparation phase
1673        // without this prefill.
1674
1675        mLock.unlock();
1676
1677        for (;;) {
1678            status_t finalStatus;
1679            size_t cachedDataRemaining =
1680                mCachedSource->approxDataRemaining(&finalStatus);
1681
1682            if (finalStatus != OK || cachedDataRemaining >= kHighWaterMarkBytes
1683                    || (mFlags & PREPARE_CANCELLED)) {
1684                break;
1685            }
1686
1687            usleep(200000);
1688        }
1689
1690        mLock.lock();
1691
1692        if (mFlags & PREPARE_CANCELLED) {
1693            LOGI("Prepare cancelled while waiting for initial cache fill.");
1694            return UNKNOWN_ERROR;
1695        }
1696    } else if (!strncasecmp("rtsp://", mUri.string(), 7)) {
1697        if (mLooper == NULL) {
1698            mLooper = new ALooper;
1699            mLooper->setName("rtsp");
1700            mLooper->start();
1701        }
1702        mRTSPController = new ARTSPController(mLooper);
1703        mConnectingRTSPController = mRTSPController;
1704
1705        mLock.unlock();
1706        status_t err = mRTSPController->connect(mUri.string());
1707        mLock.lock();
1708
1709        mConnectingRTSPController.clear();
1710
1711        LOGI("ARTSPController::connect returned %d", err);
1712
1713        if (err != OK) {
1714            mRTSPController.clear();
1715            return err;
1716        }
1717
1718        sp<MediaExtractor> extractor = mRTSPController.get();
1719        return setDataSource_l(extractor);
1720    } else {
1721        dataSource = DataSource::CreateFromURI(mUri.string(), &mUriHeaders);
1722    }
1723
1724    if (dataSource == NULL) {
1725        return UNKNOWN_ERROR;
1726    }
1727
1728    sp<MediaExtractor> extractor = MediaExtractor::Create(dataSource);
1729
1730    if (extractor == NULL) {
1731        return UNKNOWN_ERROR;
1732    }
1733
1734    dataSource->getDrmInfo(&mDecryptHandle, &mDrmManagerClient);
1735    if (mDecryptHandle != NULL) {
1736        CHECK(mDrmManagerClient);
1737        if (RightsStatus::RIGHTS_VALID != mDecryptHandle->status) {
1738            notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, ERROR_NO_LICENSE);
1739        }
1740    }
1741
1742    return setDataSource_l(extractor);
1743}
1744
1745void AwesomePlayer::abortPrepare(status_t err) {
1746    CHECK(err != OK);
1747
1748    if (mIsAsyncPrepare) {
1749        notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err);
1750    }
1751
1752    mPrepareResult = err;
1753    mFlags &= ~(PREPARING|PREPARE_CANCELLED|PREPARING_CONNECTED);
1754    mAsyncPrepareEvent = NULL;
1755    mPreparedCondition.broadcast();
1756}
1757
1758// static
1759bool AwesomePlayer::ContinuePreparation(void *cookie) {
1760    AwesomePlayer *me = static_cast<AwesomePlayer *>(cookie);
1761
1762    return (me->mFlags & PREPARE_CANCELLED) == 0;
1763}
1764
1765void AwesomePlayer::onPrepareAsyncEvent() {
1766    Mutex::Autolock autoLock(mLock);
1767
1768    if (mFlags & PREPARE_CANCELLED) {
1769        LOGI("prepare was cancelled before doing anything");
1770        abortPrepare(UNKNOWN_ERROR);
1771        return;
1772    }
1773
1774    if (mUri.size() > 0) {
1775        status_t err = finishSetDataSource_l();
1776
1777        if (err != OK) {
1778            abortPrepare(err);
1779            return;
1780        }
1781    }
1782
1783    if (mVideoTrack != NULL && mVideoSource == NULL) {
1784        status_t err = initVideoDecoder();
1785
1786        if (err != OK) {
1787            abortPrepare(err);
1788            return;
1789        }
1790    }
1791
1792    if (mAudioTrack != NULL && mAudioSource == NULL) {
1793        status_t err = initAudioDecoder();
1794
1795        if (err != OK) {
1796            abortPrepare(err);
1797            return;
1798        }
1799    }
1800
1801    mFlags |= PREPARING_CONNECTED;
1802
1803    if (mCachedSource != NULL || mRTSPController != NULL) {
1804        postBufferingEvent_l();
1805    } else {
1806        finishAsyncPrepare_l();
1807    }
1808}
1809
1810void AwesomePlayer::finishAsyncPrepare_l() {
1811    if (mIsAsyncPrepare) {
1812        if (mVideoSource == NULL) {
1813            notifyListener_l(MEDIA_SET_VIDEO_SIZE, 0, 0);
1814        } else {
1815            notifyVideoSize_l();
1816        }
1817
1818        notifyListener_l(MEDIA_PREPARED);
1819    }
1820
1821    mPrepareResult = OK;
1822    mFlags &= ~(PREPARING|PREPARE_CANCELLED|PREPARING_CONNECTED);
1823    mFlags |= PREPARED;
1824    mAsyncPrepareEvent = NULL;
1825    mPreparedCondition.broadcast();
1826}
1827
1828uint32_t AwesomePlayer::flags() const {
1829    return mExtractorFlags;
1830}
1831
1832void AwesomePlayer::postAudioEOS() {
1833    postCheckAudioStatusEvent_l();
1834}
1835
1836void AwesomePlayer::postAudioSeekComplete() {
1837    postCheckAudioStatusEvent_l();
1838}
1839
1840}  // namespace android
1841