AwesomePlayer.cpp revision a61e0f254f586d59c575e3087992889c0cf026cb
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 displayWidth;
884    if (meta->findInt32(kKeyDisplayWidth, &displayWidth)) {
885        LOGV("Display width changed (%d=>%d)", mDisplayWidth, displayWidth);
886        mDisplayWidth = displayWidth;
887    }
888    int32_t displayHeight;
889    if (meta->findInt32(kKeyDisplayHeight, &displayHeight)) {
890        LOGV("Display height changed (%d=>%d)", mDisplayHeight, displayHeight);
891        mDisplayHeight = displayHeight;
892    }
893
894    int32_t usableWidth = cropRight - cropLeft + 1;
895    int32_t usableHeight = cropBottom - cropTop + 1;
896    if (mDisplayWidth != 0) {
897        usableWidth = mDisplayWidth;
898    }
899    if (mDisplayHeight != 0) {
900        usableHeight = mDisplayHeight;
901    }
902
903    int32_t rotationDegrees;
904    if (!mVideoTrack->getFormat()->findInt32(
905                kKeyRotation, &rotationDegrees)) {
906        rotationDegrees = 0;
907    }
908
909    if (rotationDegrees == 90 || rotationDegrees == 270) {
910        notifyListener_l(
911                MEDIA_SET_VIDEO_SIZE, usableHeight, usableWidth);
912    } else {
913        notifyListener_l(
914                MEDIA_SET_VIDEO_SIZE, usableWidth, usableHeight);
915    }
916}
917
918void AwesomePlayer::initRenderer_l() {
919    if (mNativeWindow == NULL) {
920        return;
921    }
922
923    sp<MetaData> meta = mVideoSource->getFormat();
924
925    int32_t format;
926    const char *component;
927    int32_t decodedWidth, decodedHeight;
928    CHECK(meta->findInt32(kKeyColorFormat, &format));
929    CHECK(meta->findCString(kKeyDecoderComponent, &component));
930    CHECK(meta->findInt32(kKeyWidth, &decodedWidth));
931    CHECK(meta->findInt32(kKeyHeight, &decodedHeight));
932
933    int32_t rotationDegrees;
934    if (!mVideoTrack->getFormat()->findInt32(
935                kKeyRotation, &rotationDegrees)) {
936        rotationDegrees = 0;
937    }
938
939    mVideoRenderer.clear();
940
941    // Must ensure that mVideoRenderer's destructor is actually executed
942    // before creating a new one.
943    IPCThreadState::self()->flushCommands();
944
945    if (USE_SURFACE_ALLOC && strncmp(component, "OMX.", 4) == 0) {
946        // Hardware decoders avoid the CPU color conversion by decoding
947        // directly to ANativeBuffers, so we must use a renderer that
948        // just pushes those buffers to the ANativeWindow.
949        mVideoRenderer =
950            new AwesomeNativeWindowRenderer(mNativeWindow, rotationDegrees);
951    } else {
952        // Other decoders are instantiated locally and as a consequence
953        // allocate their buffers in local address space.  This renderer
954        // then performs a color conversion and copy to get the data
955        // into the ANativeBuffer.
956        mVideoRenderer = new AwesomeLocalRenderer(mNativeWindow, meta);
957    }
958}
959
960status_t AwesomePlayer::pause() {
961    Mutex::Autolock autoLock(mLock);
962
963    mFlags &= ~CACHE_UNDERRUN;
964
965    return pause_l();
966}
967
968status_t AwesomePlayer::pause_l(bool at_eos) {
969    if (!(mFlags & PLAYING)) {
970        return OK;
971    }
972
973    cancelPlayerEvents(true /* keepBufferingGoing */);
974
975    if (mAudioPlayer != NULL && (mFlags & AUDIO_RUNNING)) {
976        if (at_eos) {
977            // If we played the audio stream to completion we
978            // want to make sure that all samples remaining in the audio
979            // track's queue are played out.
980            mAudioPlayer->pause(true /* playPendingSamples */);
981        } else {
982            mAudioPlayer->pause();
983        }
984
985        mFlags &= ~AUDIO_RUNNING;
986    }
987
988    mFlags &= ~PLAYING;
989
990    if (mDecryptHandle != NULL) {
991        mDrmManagerClient->setPlaybackStatus(mDecryptHandle,
992                Playback::PAUSE, 0);
993    }
994
995    uint32_t params = IMediaPlayerService::kBatteryDataTrackDecoder;
996    if ((mAudioSource != NULL) && (mAudioSource != mAudioTrack)) {
997        params |= IMediaPlayerService::kBatteryDataTrackAudio;
998    }
999    if (mVideoSource != NULL) {
1000        params |= IMediaPlayerService::kBatteryDataTrackVideo;
1001    }
1002
1003    addBatteryData(params);
1004
1005    return OK;
1006}
1007
1008bool AwesomePlayer::isPlaying() const {
1009    return (mFlags & PLAYING) || (mFlags & CACHE_UNDERRUN);
1010}
1011
1012void AwesomePlayer::setSurface(const sp<Surface> &surface) {
1013    Mutex::Autolock autoLock(mLock);
1014
1015    mSurface = surface;
1016    mNativeWindow = surface;
1017}
1018
1019void AwesomePlayer::setSurfaceTexture(const sp<ISurfaceTexture> &surfaceTexture) {
1020    Mutex::Autolock autoLock(mLock);
1021
1022    mSurface.clear();
1023    if (surfaceTexture != NULL) {
1024        mNativeWindow = new SurfaceTextureClient(surfaceTexture);
1025    }
1026
1027}
1028
1029void AwesomePlayer::setAudioSink(
1030        const sp<MediaPlayerBase::AudioSink> &audioSink) {
1031    Mutex::Autolock autoLock(mLock);
1032
1033    mAudioSink = audioSink;
1034}
1035
1036status_t AwesomePlayer::setLooping(bool shouldLoop) {
1037    Mutex::Autolock autoLock(mLock);
1038
1039    mFlags = mFlags & ~LOOPING;
1040
1041    if (shouldLoop) {
1042        mFlags |= LOOPING;
1043    }
1044
1045    return OK;
1046}
1047
1048status_t AwesomePlayer::getDuration(int64_t *durationUs) {
1049    Mutex::Autolock autoLock(mMiscStateLock);
1050
1051    if (mDurationUs < 0) {
1052        return UNKNOWN_ERROR;
1053    }
1054
1055    *durationUs = mDurationUs;
1056
1057    return OK;
1058}
1059
1060status_t AwesomePlayer::getPosition(int64_t *positionUs) {
1061    if (mRTSPController != NULL) {
1062        *positionUs = mRTSPController->getNormalPlayTimeUs();
1063    }
1064    else if (mSeeking != NO_SEEK) {
1065        *positionUs = mSeekTimeUs;
1066    } else if (mVideoSource != NULL) {
1067        Mutex::Autolock autoLock(mMiscStateLock);
1068        *positionUs = mVideoTimeUs;
1069    } else if (mAudioPlayer != NULL) {
1070        *positionUs = mAudioPlayer->getMediaTimeUs();
1071    } else {
1072        *positionUs = 0;
1073    }
1074
1075    return OK;
1076}
1077
1078status_t AwesomePlayer::seekTo(int64_t timeUs) {
1079    if (mExtractorFlags & MediaExtractor::CAN_SEEK) {
1080        Mutex::Autolock autoLock(mLock);
1081        return seekTo_l(timeUs);
1082    }
1083
1084    return OK;
1085}
1086
1087// static
1088void AwesomePlayer::OnRTSPSeekDoneWrapper(void *cookie) {
1089    static_cast<AwesomePlayer *>(cookie)->onRTSPSeekDone();
1090}
1091
1092void AwesomePlayer::onRTSPSeekDone() {
1093    notifyListener_l(MEDIA_SEEK_COMPLETE);
1094    mSeekNotificationSent = true;
1095}
1096
1097status_t AwesomePlayer::seekTo_l(int64_t timeUs) {
1098    if (mRTSPController != NULL) {
1099        mRTSPController->seekAsync(timeUs, OnRTSPSeekDoneWrapper, this);
1100        return OK;
1101    }
1102
1103    if (mFlags & CACHE_UNDERRUN) {
1104        mFlags &= ~CACHE_UNDERRUN;
1105        play_l();
1106    }
1107
1108    mSeeking = SEEK;
1109    mSeekNotificationSent = false;
1110    mSeekTimeUs = timeUs;
1111    mFlags &= ~(AT_EOS | AUDIO_AT_EOS | VIDEO_AT_EOS);
1112
1113    seekAudioIfNecessary_l();
1114
1115    if (!(mFlags & PLAYING)) {
1116        LOGV("seeking while paused, sending SEEK_COMPLETE notification"
1117             " immediately.");
1118
1119        notifyListener_l(MEDIA_SEEK_COMPLETE);
1120        mSeekNotificationSent = true;
1121
1122        if ((mFlags & PREPARED) && mVideoSource != NULL) {
1123            mFlags |= SEEK_PREVIEW;
1124            postVideoEvent_l();
1125        }
1126    }
1127
1128    return OK;
1129}
1130
1131void AwesomePlayer::seekAudioIfNecessary_l() {
1132    if (mSeeking != NO_SEEK && mVideoSource == NULL && mAudioPlayer != NULL) {
1133        mAudioPlayer->seekTo(mSeekTimeUs);
1134
1135        mWatchForAudioSeekComplete = true;
1136        mWatchForAudioEOS = true;
1137
1138        if (mDecryptHandle != NULL) {
1139            mDrmManagerClient->setPlaybackStatus(mDecryptHandle,
1140                    Playback::PAUSE, 0);
1141            mDrmManagerClient->setPlaybackStatus(mDecryptHandle,
1142                    Playback::START, mSeekTimeUs / 1000);
1143        }
1144    }
1145}
1146
1147void AwesomePlayer::setAudioSource(sp<MediaSource> source) {
1148    CHECK(source != NULL);
1149
1150    mAudioTrack = source;
1151}
1152
1153status_t AwesomePlayer::initAudioDecoder() {
1154    sp<MetaData> meta = mAudioTrack->getFormat();
1155
1156    const char *mime;
1157    CHECK(meta->findCString(kKeyMIMEType, &mime));
1158
1159    if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_RAW)) {
1160        mAudioSource = mAudioTrack;
1161    } else {
1162        mAudioSource = OMXCodec::Create(
1163                mClient.interface(), mAudioTrack->getFormat(),
1164                false, // createEncoder
1165                mAudioTrack);
1166    }
1167
1168    if (mAudioSource != NULL) {
1169        int64_t durationUs;
1170        if (mAudioTrack->getFormat()->findInt64(kKeyDuration, &durationUs)) {
1171            Mutex::Autolock autoLock(mMiscStateLock);
1172            if (mDurationUs < 0 || durationUs > mDurationUs) {
1173                mDurationUs = durationUs;
1174            }
1175        }
1176
1177        status_t err = mAudioSource->start();
1178
1179        if (err != OK) {
1180            mAudioSource.clear();
1181            return err;
1182        }
1183    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_QCELP)) {
1184        // For legacy reasons we're simply going to ignore the absence
1185        // of an audio decoder for QCELP instead of aborting playback
1186        // altogether.
1187        return OK;
1188    }
1189
1190    return mAudioSource != NULL ? OK : UNKNOWN_ERROR;
1191}
1192
1193void AwesomePlayer::setVideoSource(sp<MediaSource> source) {
1194    CHECK(source != NULL);
1195
1196    mVideoTrack = source;
1197}
1198
1199status_t AwesomePlayer::initVideoDecoder(uint32_t flags) {
1200
1201    // Either the application or the DRM system can independently say
1202    // that there must be a hardware-protected path to an external video sink.
1203    // For now we always require a hardware-protected path to external video sink
1204    // if content is DRMed, but eventually this could be optional per DRM agent.
1205    // When the application wants protection, then
1206    //   (USE_SURFACE_ALLOC && (mSurface != 0) &&
1207    //   (mSurface->getFlags() & ISurfaceComposer::eProtectedByApp))
1208    // will be true, but that part is already handled by SurfaceFlinger.
1209
1210#ifdef DEBUG_HDCP
1211    // For debugging, we allow a system property to control the protected usage.
1212    // In case of uninitialized or unexpected property, we default to "DRM only".
1213    bool setProtectionBit = false;
1214    char value[PROPERTY_VALUE_MAX];
1215    if (property_get("persist.sys.hdcp_checking", value, NULL)) {
1216        if (!strcmp(value, "never")) {
1217            // nop
1218        } else if (!strcmp(value, "always")) {
1219            setProtectionBit = true;
1220        } else if (!strcmp(value, "drm-only")) {
1221            if (mDecryptHandle != NULL) {
1222                setProtectionBit = true;
1223            }
1224        // property value is empty, or unexpected value
1225        } else {
1226            if (mDecryptHandle != NULL) {
1227                setProtectionBit = true;
1228            }
1229        }
1230    // can' read property value
1231    } else {
1232        if (mDecryptHandle != NULL) {
1233            setProtectionBit = true;
1234        }
1235    }
1236    // note that usage bit is already cleared, so no need to clear it in the "else" case
1237    if (setProtectionBit) {
1238        flags |= OMXCodec::kEnableGrallocUsageProtected;
1239    }
1240#else
1241    if (mDecryptHandle != NULL) {
1242        flags |= OMXCodec::kEnableGrallocUsageProtected;
1243    }
1244#endif
1245    LOGV("initVideoDecoder flags=0x%x", flags);
1246    mVideoSource = OMXCodec::Create(
1247            mClient.interface(), mVideoTrack->getFormat(),
1248            false, // createEncoder
1249            mVideoTrack,
1250            NULL, flags, USE_SURFACE_ALLOC ? mNativeWindow : NULL);
1251
1252    if (mVideoSource != NULL) {
1253        int64_t durationUs;
1254        if (mVideoTrack->getFormat()->findInt64(kKeyDuration, &durationUs)) {
1255            Mutex::Autolock autoLock(mMiscStateLock);
1256            if (mDurationUs < 0 || durationUs > mDurationUs) {
1257                mDurationUs = durationUs;
1258            }
1259        }
1260
1261        status_t err = mVideoSource->start();
1262
1263        if (err != OK) {
1264            mVideoSource.clear();
1265            return err;
1266        }
1267    }
1268
1269    return mVideoSource != NULL ? OK : UNKNOWN_ERROR;
1270}
1271
1272void AwesomePlayer::finishSeekIfNecessary(int64_t videoTimeUs) {
1273    if (mSeeking == SEEK_VIDEO_ONLY) {
1274        mSeeking = NO_SEEK;
1275        return;
1276    }
1277
1278    if (mSeeking == NO_SEEK || (mFlags & SEEK_PREVIEW)) {
1279        return;
1280    }
1281
1282    if (mAudioPlayer != NULL) {
1283        LOGV("seeking audio to %lld us (%.2f secs).", videoTimeUs, videoTimeUs / 1E6);
1284
1285        // If we don't have a video time, seek audio to the originally
1286        // requested seek time instead.
1287
1288        mAudioPlayer->seekTo(videoTimeUs < 0 ? mSeekTimeUs : videoTimeUs);
1289        mWatchForAudioSeekComplete = 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        mSeekNotificationSent = true;
1295    }
1296
1297    mFlags |= FIRST_FRAME;
1298    mSeeking = NO_SEEK;
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                mFlags |= VIDEO_AT_EOS;
1381                postStreamDoneEvent_l(err);
1382                return;
1383            }
1384
1385            if (mVideoBuffer->range_length() == 0) {
1386                // Some decoders, notably the PV AVC software decoder
1387                // return spurious empty buffers that we just want to ignore.
1388
1389                mVideoBuffer->release();
1390                mVideoBuffer = NULL;
1391                continue;
1392            }
1393
1394            break;
1395        }
1396    }
1397
1398    int64_t timeUs;
1399    CHECK(mVideoBuffer->meta_data()->findInt64(kKeyTime, &timeUs));
1400
1401    if (mSeeking == SEEK_VIDEO_ONLY) {
1402        if (mSeekTimeUs > timeUs) {
1403            LOGI("XXX mSeekTimeUs = %lld us, timeUs = %lld us",
1404                 mSeekTimeUs, timeUs);
1405        }
1406    }
1407
1408    {
1409        Mutex::Autolock autoLock(mMiscStateLock);
1410        mVideoTimeUs = timeUs;
1411    }
1412
1413    SeekType wasSeeking = mSeeking;
1414    finishSeekIfNecessary(timeUs);
1415
1416    if (mAudioPlayer != NULL && !(mFlags & (AUDIO_RUNNING | SEEK_PREVIEW))) {
1417        status_t err = startAudioPlayer_l();
1418        if (err != OK) {
1419            LOGE("Startung the audio player failed w/ err %d", err);
1420            return;
1421        }
1422    }
1423
1424    TimeSource *ts = (mFlags & AUDIO_AT_EOS) ? &mSystemTimeSource : mTimeSource;
1425
1426    if (mFlags & FIRST_FRAME) {
1427        mFlags &= ~FIRST_FRAME;
1428        mSinceLastDropped = 0;
1429        mTimeSourceDeltaUs = ts->getRealTimeUs() - timeUs;
1430    }
1431
1432    int64_t realTimeUs, mediaTimeUs;
1433    if (!(mFlags & AUDIO_AT_EOS) && mAudioPlayer != NULL
1434        && mAudioPlayer->getMediaTimeMapping(&realTimeUs, &mediaTimeUs)) {
1435        mTimeSourceDeltaUs = realTimeUs - mediaTimeUs;
1436    }
1437
1438    if (wasSeeking == SEEK_VIDEO_ONLY) {
1439        int64_t nowUs = ts->getRealTimeUs() - mTimeSourceDeltaUs;
1440
1441        int64_t latenessUs = nowUs - timeUs;
1442
1443        if (latenessUs > 0) {
1444            LOGI("after SEEK_VIDEO_ONLY we're late by %.2f secs", latenessUs / 1E6);
1445        }
1446    }
1447
1448    if (wasSeeking == NO_SEEK) {
1449        // Let's display the first frame after seeking right away.
1450
1451        int64_t nowUs = ts->getRealTimeUs() - mTimeSourceDeltaUs;
1452
1453        int64_t latenessUs = nowUs - timeUs;
1454
1455        if (latenessUs > 500000ll
1456                && mRTSPController == NULL
1457                && mAudioPlayer != NULL
1458                && mAudioPlayer->getMediaTimeMapping(
1459                    &realTimeUs, &mediaTimeUs)) {
1460            LOGI("we're much too late (%.2f secs), video skipping ahead",
1461                 latenessUs / 1E6);
1462
1463            mVideoBuffer->release();
1464            mVideoBuffer = NULL;
1465
1466            mSeeking = SEEK_VIDEO_ONLY;
1467            mSeekTimeUs = mediaTimeUs;
1468
1469            postVideoEvent_l();
1470            return;
1471        }
1472
1473        if (latenessUs > 40000) {
1474            // We're more than 40ms late.
1475            LOGV("we're late by %lld us (%.2f secs)", latenessUs, latenessUs / 1E6);
1476            if ( mSinceLastDropped > FRAME_DROP_FREQ)
1477            {
1478                LOGV("we're late by %lld us (%.2f secs) dropping one after %d frames", latenessUs, latenessUs / 1E6, mSinceLastDropped);
1479                mSinceLastDropped = 0;
1480                mVideoBuffer->release();
1481                mVideoBuffer = NULL;
1482
1483                postVideoEvent_l();
1484                return;
1485            }
1486        }
1487
1488        if (latenessUs < -10000) {
1489            // We're more than 10ms early.
1490
1491            postVideoEvent_l(10000);
1492            return;
1493        }
1494    }
1495
1496    if (mVideoRendererIsPreview || mVideoRenderer == NULL) {
1497        mVideoRendererIsPreview = false;
1498
1499        initRenderer_l();
1500    }
1501
1502    if (mVideoRenderer != NULL) {
1503        mSinceLastDropped++;
1504        mVideoRenderer->render(mVideoBuffer);
1505    }
1506
1507    mVideoBuffer->release();
1508    mVideoBuffer = NULL;
1509
1510    if (wasSeeking != NO_SEEK && (mFlags & SEEK_PREVIEW)) {
1511        mFlags &= ~SEEK_PREVIEW;
1512        return;
1513    }
1514
1515    postVideoEvent_l();
1516}
1517
1518void AwesomePlayer::postVideoEvent_l(int64_t delayUs) {
1519    if (mVideoEventPending) {
1520        return;
1521    }
1522
1523    mVideoEventPending = true;
1524    mQueue.postEventWithDelay(mVideoEvent, delayUs < 0 ? 10000 : delayUs);
1525}
1526
1527void AwesomePlayer::postStreamDoneEvent_l(status_t status) {
1528    if (mStreamDoneEventPending) {
1529        return;
1530    }
1531    mStreamDoneEventPending = true;
1532
1533    mStreamDoneStatus = status;
1534    mQueue.postEvent(mStreamDoneEvent);
1535}
1536
1537void AwesomePlayer::postBufferingEvent_l() {
1538    if (mBufferingEventPending) {
1539        return;
1540    }
1541    mBufferingEventPending = true;
1542    mQueue.postEventWithDelay(mBufferingEvent, 1000000ll);
1543}
1544
1545void AwesomePlayer::postVideoLagEvent_l() {
1546    if (mVideoLagEventPending) {
1547        return;
1548    }
1549    mVideoLagEventPending = true;
1550    mQueue.postEventWithDelay(mVideoLagEvent, 1000000ll);
1551}
1552
1553void AwesomePlayer::postCheckAudioStatusEvent_l(int64_t delayUs) {
1554    if (mAudioStatusEventPending) {
1555        return;
1556    }
1557    mAudioStatusEventPending = true;
1558    mQueue.postEventWithDelay(mCheckAudioStatusEvent, delayUs);
1559}
1560
1561void AwesomePlayer::onCheckAudioStatus() {
1562    Mutex::Autolock autoLock(mLock);
1563    if (!mAudioStatusEventPending) {
1564        // Event was dispatched and while we were blocking on the mutex,
1565        // has already been cancelled.
1566        return;
1567    }
1568
1569    mAudioStatusEventPending = false;
1570
1571    if (mWatchForAudioSeekComplete && !mAudioPlayer->isSeeking()) {
1572        mWatchForAudioSeekComplete = false;
1573
1574        if (!mSeekNotificationSent) {
1575            notifyListener_l(MEDIA_SEEK_COMPLETE);
1576            mSeekNotificationSent = true;
1577        }
1578
1579        mSeeking = NO_SEEK;
1580    }
1581
1582    status_t finalStatus;
1583    if (mWatchForAudioEOS && mAudioPlayer->reachedEOS(&finalStatus)) {
1584        mWatchForAudioEOS = false;
1585        mFlags |= AUDIO_AT_EOS;
1586        mFlags |= FIRST_FRAME;
1587        postStreamDoneEvent_l(finalStatus);
1588    }
1589}
1590
1591status_t AwesomePlayer::prepare() {
1592    Mutex::Autolock autoLock(mLock);
1593    return prepare_l();
1594}
1595
1596status_t AwesomePlayer::prepare_l() {
1597    if (mFlags & PREPARED) {
1598        return OK;
1599    }
1600
1601    if (mFlags & PREPARING) {
1602        return UNKNOWN_ERROR;
1603    }
1604
1605    mIsAsyncPrepare = false;
1606    status_t err = prepareAsync_l();
1607
1608    if (err != OK) {
1609        return err;
1610    }
1611
1612    while (mFlags & PREPARING) {
1613        mPreparedCondition.wait(mLock);
1614    }
1615
1616    return mPrepareResult;
1617}
1618
1619status_t AwesomePlayer::prepareAsync() {
1620    Mutex::Autolock autoLock(mLock);
1621
1622    if (mFlags & PREPARING) {
1623        return UNKNOWN_ERROR;  // async prepare already pending
1624    }
1625
1626    mIsAsyncPrepare = true;
1627    return prepareAsync_l();
1628}
1629
1630status_t AwesomePlayer::prepareAsync_l() {
1631    if (mFlags & PREPARING) {
1632        return UNKNOWN_ERROR;  // async prepare already pending
1633    }
1634
1635    if (!mQueueStarted) {
1636        mQueue.start();
1637        mQueueStarted = true;
1638    }
1639
1640    mFlags |= PREPARING;
1641    mAsyncPrepareEvent = new AwesomeEvent(
1642            this, &AwesomePlayer::onPrepareAsyncEvent);
1643
1644    mQueue.postEvent(mAsyncPrepareEvent);
1645
1646    return OK;
1647}
1648
1649status_t AwesomePlayer::finishSetDataSource_l() {
1650    sp<DataSource> dataSource;
1651
1652    if (!strncasecmp("http://", mUri.string(), 7)
1653            || !strncasecmp("https://", mUri.string(), 8)) {
1654        mConnectingDataSource = HTTPBase::Create(
1655                (mFlags & INCOGNITO)
1656                    ? HTTPBase::kFlagIncognito
1657                    : 0);
1658
1659        mLock.unlock();
1660        status_t err = mConnectingDataSource->connect(mUri, &mUriHeaders);
1661        mLock.lock();
1662
1663        if (err != OK) {
1664            mConnectingDataSource.clear();
1665
1666            LOGI("mConnectingDataSource->connect() returned %d", err);
1667            return err;
1668        }
1669
1670#if 0
1671        mCachedSource = new NuCachedSource2(
1672                new ThrottledSource(
1673                    mConnectingDataSource, 50 * 1024 /* bytes/sec */));
1674#else
1675        mCachedSource = new NuCachedSource2(mConnectingDataSource);
1676#endif
1677        mConnectingDataSource.clear();
1678
1679        dataSource = mCachedSource;
1680
1681        // We're going to prefill the cache before trying to instantiate
1682        // the extractor below, as the latter is an operation that otherwise
1683        // could block on the datasource for a significant amount of time.
1684        // During that time we'd be unable to abort the preparation phase
1685        // without this prefill.
1686
1687        mLock.unlock();
1688
1689        for (;;) {
1690            status_t finalStatus;
1691            size_t cachedDataRemaining =
1692                mCachedSource->approxDataRemaining(&finalStatus);
1693
1694            if (finalStatus != OK || cachedDataRemaining >= kHighWaterMarkBytes
1695                    || (mFlags & PREPARE_CANCELLED)) {
1696                break;
1697            }
1698
1699            usleep(200000);
1700        }
1701
1702        mLock.lock();
1703
1704        if (mFlags & PREPARE_CANCELLED) {
1705            LOGI("Prepare cancelled while waiting for initial cache fill.");
1706            return UNKNOWN_ERROR;
1707        }
1708    } else if (!strncasecmp("rtsp://", mUri.string(), 7)) {
1709        if (mLooper == NULL) {
1710            mLooper = new ALooper;
1711            mLooper->setName("rtsp");
1712            mLooper->start();
1713        }
1714        mRTSPController = new ARTSPController(mLooper);
1715        mConnectingRTSPController = mRTSPController;
1716
1717        mLock.unlock();
1718        status_t err = mRTSPController->connect(mUri.string());
1719        mLock.lock();
1720
1721        mConnectingRTSPController.clear();
1722
1723        LOGI("ARTSPController::connect returned %d", err);
1724
1725        if (err != OK) {
1726            mRTSPController.clear();
1727            return err;
1728        }
1729
1730        sp<MediaExtractor> extractor = mRTSPController.get();
1731        return setDataSource_l(extractor);
1732    } else {
1733        dataSource = DataSource::CreateFromURI(mUri.string(), &mUriHeaders);
1734    }
1735
1736    if (dataSource == NULL) {
1737        return UNKNOWN_ERROR;
1738    }
1739
1740    sp<MediaExtractor> extractor = MediaExtractor::Create(dataSource);
1741
1742    if (extractor == NULL) {
1743        return UNKNOWN_ERROR;
1744    }
1745
1746    dataSource->getDrmInfo(mDecryptHandle, &mDrmManagerClient);
1747
1748    if (mDecryptHandle != NULL) {
1749        CHECK(mDrmManagerClient);
1750        if (RightsStatus::RIGHTS_VALID == mDecryptHandle->status) {
1751            if (DecryptApiType::WV_BASED == mDecryptHandle->decryptApiType) {
1752                LOGD("Setting mCachedSource to NULL for WVM\n");
1753                mCachedSource.clear();
1754            }
1755        } else {
1756            notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, ERROR_NO_LICENSE);
1757        }
1758    }
1759
1760    return setDataSource_l(extractor);
1761}
1762
1763void AwesomePlayer::abortPrepare(status_t err) {
1764    CHECK(err != OK);
1765
1766    if (mIsAsyncPrepare) {
1767        notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err);
1768    }
1769
1770    mPrepareResult = err;
1771    mFlags &= ~(PREPARING|PREPARE_CANCELLED|PREPARING_CONNECTED);
1772    mAsyncPrepareEvent = NULL;
1773    mPreparedCondition.broadcast();
1774}
1775
1776// static
1777bool AwesomePlayer::ContinuePreparation(void *cookie) {
1778    AwesomePlayer *me = static_cast<AwesomePlayer *>(cookie);
1779
1780    return (me->mFlags & PREPARE_CANCELLED) == 0;
1781}
1782
1783void AwesomePlayer::onPrepareAsyncEvent() {
1784    Mutex::Autolock autoLock(mLock);
1785
1786    if (mFlags & PREPARE_CANCELLED) {
1787        LOGI("prepare was cancelled before doing anything");
1788        abortPrepare(UNKNOWN_ERROR);
1789        return;
1790    }
1791
1792    if (mUri.size() > 0) {
1793        status_t err = finishSetDataSource_l();
1794
1795        if (err != OK) {
1796            abortPrepare(err);
1797            return;
1798        }
1799    }
1800
1801    if (mVideoTrack != NULL && mVideoSource == NULL) {
1802        status_t err = initVideoDecoder();
1803
1804        if (err != OK) {
1805            abortPrepare(err);
1806            return;
1807        }
1808    }
1809
1810    if (mAudioTrack != NULL && mAudioSource == NULL) {
1811        status_t err = initAudioDecoder();
1812
1813        if (err != OK) {
1814            abortPrepare(err);
1815            return;
1816        }
1817    }
1818
1819    mFlags |= PREPARING_CONNECTED;
1820
1821    if (mCachedSource != NULL || mRTSPController != NULL) {
1822        postBufferingEvent_l();
1823    } else {
1824        finishAsyncPrepare_l();
1825    }
1826}
1827
1828void AwesomePlayer::finishAsyncPrepare_l() {
1829    if (mIsAsyncPrepare) {
1830        if (mVideoSource == NULL) {
1831            notifyListener_l(MEDIA_SET_VIDEO_SIZE, 0, 0);
1832        } else {
1833            notifyVideoSize_l();
1834        }
1835
1836        notifyListener_l(MEDIA_PREPARED);
1837    }
1838
1839    mPrepareResult = OK;
1840    mFlags &= ~(PREPARING|PREPARE_CANCELLED|PREPARING_CONNECTED);
1841    mFlags |= PREPARED;
1842    mAsyncPrepareEvent = NULL;
1843    mPreparedCondition.broadcast();
1844}
1845
1846uint32_t AwesomePlayer::flags() const {
1847    return mExtractorFlags;
1848}
1849
1850void AwesomePlayer::postAudioEOS(int64_t delayUs) {
1851    postCheckAudioStatusEvent_l(delayUs);
1852}
1853
1854void AwesomePlayer::postAudioSeekComplete() {
1855    postCheckAudioStatusEvent_l(0 /* delayUs */);
1856}
1857
1858}  // namespace android
1859