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