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