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