AwesomePlayer.cpp revision 8ae49d87b98d57d6758b0c51b95e28a6581a79f1
1/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "AwesomePlayer"
19#include <utils/Log.h>
20
21#include <dlfcn.h>
22
23#include "include/ARTSPController.h"
24#include "include/AwesomePlayer.h"
25#include "include/LiveSource.h"
26#include "include/SoftwareRenderer.h"
27#include "include/NuCachedSource2.h"
28#include "include/ThrottledSource.h"
29
30#include "ARTPSession.h"
31#include "APacketSource.h"
32#include "ASessionDescription.h"
33#include "UDPPusher.h"
34
35#include <binder/IPCThreadState.h>
36#include <media/stagefright/AudioPlayer.h>
37#include <media/stagefright/DataSource.h>
38#include <media/stagefright/FileSource.h>
39#include <media/stagefright/MediaBuffer.h>
40#include <media/stagefright/MediaDefs.h>
41#include <media/stagefright/MediaExtractor.h>
42#include <media/stagefright/MediaDebug.h>
43#include <media/stagefright/MediaSource.h>
44#include <media/stagefright/MetaData.h>
45#include <media/stagefright/OMXCodec.h>
46
47#include <surfaceflinger/ISurface.h>
48
49#include <media/stagefright/foundation/ALooper.h>
50
51namespace android {
52
53static int64_t kLowWaterMarkUs = 2000000ll;  // 2secs
54static int64_t kHighWaterMarkUs = 10000000ll;  // 10secs
55
56struct AwesomeEvent : public TimedEventQueue::Event {
57    AwesomeEvent(
58            AwesomePlayer *player,
59            void (AwesomePlayer::*method)())
60        : mPlayer(player),
61          mMethod(method) {
62    }
63
64protected:
65    virtual ~AwesomeEvent() {}
66
67    virtual void fire(TimedEventQueue *queue, int64_t /* now_us */) {
68        (mPlayer->*mMethod)();
69    }
70
71private:
72    AwesomePlayer *mPlayer;
73    void (AwesomePlayer::*mMethod)();
74
75    AwesomeEvent(const AwesomeEvent &);
76    AwesomeEvent &operator=(const AwesomeEvent &);
77};
78
79struct AwesomeRemoteRenderer : public AwesomeRenderer {
80    AwesomeRemoteRenderer(const sp<IOMXRenderer> &target)
81        : mTarget(target) {
82    }
83
84    virtual void render(MediaBuffer *buffer) {
85        void *id;
86        if (buffer->meta_data()->findPointer(kKeyBufferID, &id)) {
87            mTarget->render((IOMX::buffer_id)id);
88        }
89    }
90
91private:
92    sp<IOMXRenderer> mTarget;
93
94    AwesomeRemoteRenderer(const AwesomeRemoteRenderer &);
95    AwesomeRemoteRenderer &operator=(const AwesomeRemoteRenderer &);
96};
97
98struct AwesomeLocalRenderer : public AwesomeRenderer {
99    AwesomeLocalRenderer(
100            bool previewOnly,
101            const char *componentName,
102            OMX_COLOR_FORMATTYPE colorFormat,
103            const sp<ISurface> &surface,
104            size_t displayWidth, size_t displayHeight,
105            size_t decodedWidth, size_t decodedHeight)
106        : mTarget(NULL),
107          mLibHandle(NULL) {
108            init(previewOnly, componentName,
109                 colorFormat, surface, displayWidth,
110                 displayHeight, decodedWidth, decodedHeight);
111    }
112
113    virtual void render(MediaBuffer *buffer) {
114        render((const uint8_t *)buffer->data() + buffer->range_offset(),
115               buffer->range_length());
116    }
117
118    void render(const void *data, size_t size) {
119        mTarget->render(data, size, NULL);
120    }
121
122protected:
123    virtual ~AwesomeLocalRenderer() {
124        delete mTarget;
125        mTarget = NULL;
126
127        if (mLibHandle) {
128            dlclose(mLibHandle);
129            mLibHandle = NULL;
130        }
131    }
132
133private:
134    VideoRenderer *mTarget;
135    void *mLibHandle;
136
137    void init(
138            bool previewOnly,
139            const char *componentName,
140            OMX_COLOR_FORMATTYPE colorFormat,
141            const sp<ISurface> &surface,
142            size_t displayWidth, size_t displayHeight,
143            size_t decodedWidth, size_t decodedHeight);
144
145    AwesomeLocalRenderer(const AwesomeLocalRenderer &);
146    AwesomeLocalRenderer &operator=(const AwesomeLocalRenderer &);;
147};
148
149void AwesomeLocalRenderer::init(
150        bool previewOnly,
151        const char *componentName,
152        OMX_COLOR_FORMATTYPE colorFormat,
153        const sp<ISurface> &surface,
154        size_t displayWidth, size_t displayHeight,
155        size_t decodedWidth, size_t decodedHeight) {
156    if (!previewOnly) {
157        // We will stick to the vanilla software-color-converting renderer
158        // for "previewOnly" mode, to avoid unneccessarily switching overlays
159        // more often than necessary.
160
161        mLibHandle = dlopen("libstagefrighthw.so", RTLD_NOW);
162
163        if (mLibHandle) {
164            typedef VideoRenderer *(*CreateRendererFunc)(
165                    const sp<ISurface> &surface,
166                    const char *componentName,
167                    OMX_COLOR_FORMATTYPE colorFormat,
168                    size_t displayWidth, size_t displayHeight,
169                    size_t decodedWidth, size_t decodedHeight);
170
171            CreateRendererFunc func =
172                (CreateRendererFunc)dlsym(
173                        mLibHandle,
174                        "_Z14createRendererRKN7android2spINS_8ISurfaceEEEPKc20"
175                        "OMX_COLOR_FORMATTYPEjjjj");
176
177            if (func) {
178                mTarget =
179                    (*func)(surface, componentName, colorFormat,
180                        displayWidth, displayHeight,
181                        decodedWidth, decodedHeight);
182            }
183        }
184    }
185
186    if (mTarget == NULL) {
187        mTarget = new SoftwareRenderer(
188                colorFormat, surface, displayWidth, displayHeight,
189                decodedWidth, decodedHeight);
190    }
191}
192
193AwesomePlayer::AwesomePlayer()
194    : mQueueStarted(false),
195      mTimeSource(NULL),
196      mVideoRendererIsPreview(false),
197      mAudioPlayer(NULL),
198      mFlags(0),
199      mExtractorFlags(0),
200      mLastVideoBuffer(NULL),
201      mVideoBuffer(NULL),
202      mSuspensionState(NULL) {
203    CHECK_EQ(mClient.connect(), OK);
204
205    DataSource::RegisterDefaultSniffers();
206
207    mVideoEvent = new AwesomeEvent(this, &AwesomePlayer::onVideoEvent);
208    mVideoEventPending = false;
209    mStreamDoneEvent = new AwesomeEvent(this, &AwesomePlayer::onStreamDone);
210    mStreamDoneEventPending = false;
211    mBufferingEvent = new AwesomeEvent(this, &AwesomePlayer::onBufferingUpdate);
212    mBufferingEventPending = false;
213
214    mCheckAudioStatusEvent = new AwesomeEvent(
215            this, &AwesomePlayer::onCheckAudioStatus);
216
217    mAudioStatusEventPending = false;
218
219    reset();
220}
221
222AwesomePlayer::~AwesomePlayer() {
223    if (mQueueStarted) {
224        mQueue.stop();
225    }
226
227    reset();
228
229    mClient.disconnect();
230}
231
232void AwesomePlayer::cancelPlayerEvents(bool keepBufferingGoing) {
233    mQueue.cancelEvent(mVideoEvent->eventID());
234    mVideoEventPending = false;
235    mQueue.cancelEvent(mStreamDoneEvent->eventID());
236    mStreamDoneEventPending = false;
237    mQueue.cancelEvent(mCheckAudioStatusEvent->eventID());
238    mAudioStatusEventPending = 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
251status_t AwesomePlayer::setDataSource(
252        const char *uri, const KeyedVector<String8, String8> *headers) {
253    Mutex::Autolock autoLock(mLock);
254    return setDataSource_l(uri, headers);
255}
256
257status_t AwesomePlayer::setDataSource_l(
258        const char *uri, const KeyedVector<String8, String8> *headers) {
259    reset_l();
260
261    mUri = uri;
262
263    if (headers) {
264        mUriHeaders = *headers;
265    }
266
267    // The actual work will be done during preparation in the call to
268    // ::finishSetDataSource_l to avoid blocking the calling thread in
269    // setDataSource for any significant time.
270
271    return OK;
272}
273
274status_t AwesomePlayer::setDataSource(
275        int fd, int64_t offset, int64_t length) {
276#if 0
277    // return setDataSource("httplive://qthttp.apple.com.edgesuite.net/1009qpeijrfn/sl.m3u8");
278    return setDataSource("httplive://qthttp.apple.com.edgesuite.net/1009qpeijrfn/0440.m3u8");
279    // return setDataSource("httplive://qthttp.apple.com.edgesuite.net/1009qpeijrfn/0640.m3u8");
280    // return setDataSource("httplive://qthttp.apple.com.edgesuite.net/1009qpeijrfn/1240_vod.m3u8");
281    // return setDataSource("httplive://iphoned5.akamai.com.edgesuite.net/mhbarron/nasatv/nasatv_96.m3u8");
282    // return setDataSource("httplive://iphoned5.akamai.com.edgesuite.net/mhbarron/nasatv/nasatv_1500.m3u8");
283    // return setDataSource("httplive://iphone.video.hsn.com/iPhone_high.m3u8");
284    // return setDataSource("httplive://iphoned5.akamai.com.edgesuite.net/mhbarron/iphonewebcast/webcast090209_all/webcast090209_all.m3u8");
285    // return setDataSource("httplive://qthttp.akamai.com.edgesuite.net/iphone_demo/Video_Content/usat/tt_062209_iphone/hi/prog_index.m3u8");
286    // return setDataSource("httplive://qthttp.akamai.com.edgesuite.net/iphone_demo/Video_Content/usat/tt_googmaps/hi/prog_index.m3u8");
287    // return setDataSource("httplive://qthttp.akamai.com.edgesuite.net/iphone_demo/Video_Content/mtv/ni_spo_25a_rt74137_clip_syn/hi/prog_index.m3u8");
288#endif
289
290    Mutex::Autolock autoLock(mLock);
291
292    reset_l();
293
294    sp<DataSource> dataSource = new FileSource(fd, offset, length);
295
296    status_t err = dataSource->initCheck();
297
298    if (err != OK) {
299        return err;
300    }
301
302    mFileSource = dataSource;
303
304    return setDataSource_l(dataSource);
305}
306
307status_t AwesomePlayer::setDataSource_l(
308        const sp<DataSource> &dataSource) {
309    sp<MediaExtractor> extractor = MediaExtractor::Create(dataSource);
310
311    if (extractor == NULL) {
312        return UNKNOWN_ERROR;
313    }
314
315    return setDataSource_l(extractor);
316}
317
318status_t AwesomePlayer::setDataSource_l(const sp<MediaExtractor> &extractor) {
319    bool haveAudio = false;
320    bool haveVideo = false;
321    for (size_t i = 0; i < extractor->countTracks(); ++i) {
322        sp<MetaData> meta = extractor->getTrackMetaData(i);
323
324        const char *mime;
325        CHECK(meta->findCString(kKeyMIMEType, &mime));
326
327        if (!haveVideo && !strncasecmp(mime, "video/", 6)) {
328            setVideoSource(extractor->getTrack(i));
329            haveVideo = true;
330        } else if (!haveAudio && !strncasecmp(mime, "audio/", 6)) {
331            setAudioSource(extractor->getTrack(i));
332            haveAudio = true;
333
334            sp<MetaData> fileMeta = extractor->getMetaData();
335            int32_t loop;
336            if (fileMeta != NULL
337                    && fileMeta->findInt32(kKeyAutoLoop, &loop) && loop != 0) {
338                mFlags |= AUTO_LOOPING;
339            }
340        }
341
342        if (haveAudio && haveVideo) {
343            break;
344        }
345    }
346
347    if (!haveAudio && !haveVideo) {
348        return UNKNOWN_ERROR;
349    }
350
351    mExtractorFlags = extractor->flags();
352
353    return OK;
354}
355
356void AwesomePlayer::reset() {
357    Mutex::Autolock autoLock(mLock);
358    reset_l();
359}
360
361void AwesomePlayer::reset_l() {
362    if (mFlags & PREPARING) {
363        mFlags |= PREPARE_CANCELLED;
364        if (mConnectingDataSource != NULL) {
365            LOGI("interrupting the connection process");
366            mConnectingDataSource->disconnect();
367        }
368    }
369
370    while (mFlags & PREPARING) {
371        mPreparedCondition.wait(mLock);
372    }
373
374    cancelPlayerEvents();
375
376    mCachedSource.clear();
377    mAudioTrack.clear();
378    mVideoTrack.clear();
379
380    // Shutdown audio first, so that the respone to the reset request
381    // appears to happen instantaneously as far as the user is concerned
382    // If we did this later, audio would continue playing while we
383    // shutdown the video-related resources and the player appear to
384    // not be as responsive to a reset request.
385    if (mAudioPlayer == NULL && mAudioSource != NULL) {
386        // If we had an audio player, it would have effectively
387        // taken possession of the audio source and stopped it when
388        // _it_ is stopped. Otherwise this is still our responsibility.
389        mAudioSource->stop();
390    }
391    mAudioSource.clear();
392
393    mTimeSource = NULL;
394
395    delete mAudioPlayer;
396    mAudioPlayer = NULL;
397
398    mVideoRenderer.clear();
399
400    if (mLastVideoBuffer) {
401        mLastVideoBuffer->release();
402        mLastVideoBuffer = NULL;
403    }
404
405    if (mVideoBuffer) {
406        mVideoBuffer->release();
407        mVideoBuffer = NULL;
408    }
409
410    if (mRTSPController != NULL) {
411        mRTSPController->disconnect();
412        mRTSPController.clear();
413    }
414
415    mRTPPusher.clear();
416    mRTCPPusher.clear();
417    mRTPSession.clear();
418
419    if (mVideoSource != NULL) {
420        mVideoSource->stop();
421
422        // The following hack is necessary to ensure that the OMX
423        // component is completely released by the time we may try
424        // to instantiate it again.
425        wp<MediaSource> tmp = mVideoSource;
426        mVideoSource.clear();
427        while (tmp.promote() != NULL) {
428            usleep(1000);
429        }
430        IPCThreadState::self()->flushCommands();
431    }
432
433    mDurationUs = -1;
434    mFlags = 0;
435    mExtractorFlags = 0;
436    mVideoWidth = mVideoHeight = -1;
437    mTimeSourceDeltaUs = 0;
438    mVideoTimeUs = 0;
439
440    mSeeking = false;
441    mSeekNotificationSent = false;
442    mSeekTimeUs = 0;
443
444    mUri.setTo("");
445    mUriHeaders.clear();
446
447    mFileSource.clear();
448
449    delete mSuspensionState;
450    mSuspensionState = NULL;
451}
452
453void AwesomePlayer::notifyListener_l(int msg, int ext1, int ext2) {
454    if (mListener != NULL) {
455        sp<MediaPlayerBase> listener = mListener.promote();
456
457        if (listener != NULL) {
458            listener->sendEvent(msg, ext1, ext2);
459        }
460    }
461}
462
463// Returns true iff cached duration is available/applicable.
464bool AwesomePlayer::getCachedDuration_l(int64_t *durationUs, bool *eos) {
465    off_t totalSize;
466
467    if (mRTSPController != NULL) {
468        *durationUs = mRTSPController->getQueueDurationUs(eos);
469        return true;
470    } else if (mCachedSource != NULL && mDurationUs >= 0
471            && mCachedSource->getSize(&totalSize) == OK) {
472        int64_t bitrate = totalSize * 8000000ll / mDurationUs;  // in bits/sec
473
474        size_t cachedDataRemaining = mCachedSource->approxDataRemaining(eos);
475        *durationUs = cachedDataRemaining * 8000000ll / bitrate;
476        return true;
477    }
478
479    return false;
480}
481
482void AwesomePlayer::onBufferingUpdate() {
483    Mutex::Autolock autoLock(mLock);
484    if (!mBufferingEventPending) {
485        return;
486    }
487    mBufferingEventPending = false;
488
489    if (mCachedSource != NULL) {
490        bool eos;
491        size_t cachedDataRemaining = mCachedSource->approxDataRemaining(&eos);
492
493        if (eos) {
494            notifyListener_l(MEDIA_BUFFERING_UPDATE, 100);
495        } else {
496            off_t size;
497            if (mDurationUs >= 0 && mCachedSource->getSize(&size) == OK) {
498                int64_t bitrate = size * 8000000ll / mDurationUs;  // in bits/sec
499
500                size_t cachedSize = mCachedSource->cachedSize();
501                int64_t cachedDurationUs = cachedSize * 8000000ll / bitrate;
502
503                int percentage = 100.0 * (double)cachedDurationUs / mDurationUs;
504                if (percentage > 100) {
505                    percentage = 100;
506                }
507
508                notifyListener_l(MEDIA_BUFFERING_UPDATE, percentage);
509            } else {
510                // We don't know the bitrate of the stream, use absolute size
511                // limits to maintain the cache.
512
513                const size_t kLowWaterMarkBytes = 400000;
514                const size_t kHighWaterMarkBytes = 1000000;
515
516                if ((mFlags & PLAYING) && !eos
517                        && (cachedDataRemaining < kLowWaterMarkBytes)) {
518                    LOGI("cache is running low (< %d) , pausing.",
519                         kLowWaterMarkBytes);
520                    mFlags |= CACHE_UNDERRUN;
521                    pause_l();
522                    notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_START);
523                } else if (eos || cachedDataRemaining > kHighWaterMarkBytes) {
524                    if (mFlags & CACHE_UNDERRUN) {
525                        LOGI("cache has filled up (> %d), resuming.",
526                             kHighWaterMarkBytes);
527                        mFlags &= ~CACHE_UNDERRUN;
528                        play_l();
529                        notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_END);
530                    } else if (mFlags & PREPARING) {
531                        LOGV("cache has filled up (> %d), prepare is done",
532                             kHighWaterMarkBytes);
533                        finishAsyncPrepare_l();
534                    }
535                }
536            }
537        }
538    }
539
540    int64_t cachedDurationUs;
541    bool eos;
542    if (getCachedDuration_l(&cachedDurationUs, &eos)) {
543        if ((mFlags & PLAYING) && !eos
544                && (cachedDurationUs < kLowWaterMarkUs)) {
545            LOGI("cache is running low (%.2f secs) , pausing.",
546                 cachedDurationUs / 1E6);
547            mFlags |= CACHE_UNDERRUN;
548            pause_l();
549            notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_START);
550        } else if (eos || cachedDurationUs > kHighWaterMarkUs) {
551            if (mFlags & CACHE_UNDERRUN) {
552                LOGI("cache has filled up (%.2f secs), resuming.",
553                     cachedDurationUs / 1E6);
554                mFlags &= ~CACHE_UNDERRUN;
555                play_l();
556                notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_END);
557            } else if (mFlags & PREPARING) {
558                LOGV("cache has filled up (%.2f secs), prepare is done",
559                     cachedDurationUs / 1E6);
560                finishAsyncPrepare_l();
561            }
562        }
563    }
564
565    postBufferingEvent_l();
566}
567
568void AwesomePlayer::onStreamDone() {
569    // Posted whenever any stream finishes playing.
570
571    Mutex::Autolock autoLock(mLock);
572    if (!mStreamDoneEventPending) {
573        return;
574    }
575    mStreamDoneEventPending = false;
576
577    if (mStreamDoneStatus != ERROR_END_OF_STREAM) {
578        LOGV("MEDIA_ERROR %d", mStreamDoneStatus);
579
580        notifyListener_l(
581                MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, mStreamDoneStatus);
582
583        pause_l();
584
585        mFlags |= AT_EOS;
586        return;
587    }
588
589    const bool allDone =
590        (mVideoSource == NULL || (mFlags & VIDEO_AT_EOS))
591            && (mAudioSource == NULL || (mFlags & AUDIO_AT_EOS));
592
593    if (!allDone) {
594        return;
595    }
596
597    if (mFlags & (LOOPING | AUTO_LOOPING)) {
598        seekTo_l(0);
599
600        if (mVideoSource != NULL) {
601            postVideoEvent_l();
602        }
603    } else {
604        LOGV("MEDIA_PLAYBACK_COMPLETE");
605        notifyListener_l(MEDIA_PLAYBACK_COMPLETE);
606
607        pause_l();
608
609        mFlags |= AT_EOS;
610    }
611}
612
613status_t AwesomePlayer::play() {
614    Mutex::Autolock autoLock(mLock);
615
616    mFlags &= ~CACHE_UNDERRUN;
617
618    return play_l();
619}
620
621status_t AwesomePlayer::play_l() {
622    if (mFlags & PLAYING) {
623        return OK;
624    }
625
626    if (!(mFlags & PREPARED)) {
627        status_t err = prepare_l();
628
629        if (err != OK) {
630            return err;
631        }
632    }
633
634    mFlags |= PLAYING;
635    mFlags |= FIRST_FRAME;
636
637    bool deferredAudioSeek = false;
638
639    if (mAudioSource != NULL) {
640        if (mAudioPlayer == NULL) {
641            if (mAudioSink != NULL) {
642                mAudioPlayer = new AudioPlayer(mAudioSink);
643                mAudioPlayer->setSource(mAudioSource);
644
645                // We've already started the MediaSource in order to enable
646                // the prefetcher to read its data.
647                status_t err = mAudioPlayer->start(
648                        true /* sourceAlreadyStarted */);
649
650                if (err != OK) {
651                    delete mAudioPlayer;
652                    mAudioPlayer = NULL;
653
654                    mFlags &= ~(PLAYING | FIRST_FRAME);
655
656                    return err;
657                }
658
659                mTimeSource = mAudioPlayer;
660
661                deferredAudioSeek = true;
662
663                mWatchForAudioSeekComplete = false;
664                mWatchForAudioEOS = true;
665            }
666        } else {
667            mAudioPlayer->resume();
668        }
669
670        postCheckAudioStatusEvent_l();
671    }
672
673    if (mTimeSource == NULL && mAudioPlayer == NULL) {
674        mTimeSource = &mSystemTimeSource;
675    }
676
677    if (mVideoSource != NULL) {
678        // Kick off video playback
679        postVideoEvent_l();
680    }
681
682    if (deferredAudioSeek) {
683        // If there was a seek request while we were paused
684        // and we're just starting up again, honor the request now.
685        seekAudioIfNecessary_l();
686    }
687
688    if (mFlags & AT_EOS) {
689        // Legacy behaviour, if a stream finishes playing and then
690        // is started again, we play from the start...
691        seekTo_l(0);
692    }
693
694    return OK;
695}
696
697void AwesomePlayer::initRenderer_l() {
698    if (mISurface != NULL) {
699        sp<MetaData> meta = mVideoSource->getFormat();
700
701        int32_t format;
702        const char *component;
703        int32_t decodedWidth, decodedHeight;
704        CHECK(meta->findInt32(kKeyColorFormat, &format));
705        CHECK(meta->findCString(kKeyDecoderComponent, &component));
706        CHECK(meta->findInt32(kKeyWidth, &decodedWidth));
707        CHECK(meta->findInt32(kKeyHeight, &decodedHeight));
708
709        mVideoRenderer.clear();
710
711        // Must ensure that mVideoRenderer's destructor is actually executed
712        // before creating a new one.
713        IPCThreadState::self()->flushCommands();
714
715        if (!strncmp("OMX.", component, 4)) {
716            // Our OMX codecs allocate buffers on the media_server side
717            // therefore they require a remote IOMXRenderer that knows how
718            // to display them.
719            mVideoRenderer = new AwesomeRemoteRenderer(
720                mClient.interface()->createRenderer(
721                        mISurface, component,
722                        (OMX_COLOR_FORMATTYPE)format,
723                        decodedWidth, decodedHeight,
724                        mVideoWidth, mVideoHeight));
725        } else {
726            // Other decoders are instantiated locally and as a consequence
727            // allocate their buffers in local address space.
728            mVideoRenderer = new AwesomeLocalRenderer(
729                false,  // previewOnly
730                component,
731                (OMX_COLOR_FORMATTYPE)format,
732                mISurface,
733                mVideoWidth, mVideoHeight,
734                decodedWidth, decodedHeight);
735        }
736    }
737}
738
739status_t AwesomePlayer::pause() {
740    Mutex::Autolock autoLock(mLock);
741
742    mFlags &= ~CACHE_UNDERRUN;
743
744    return pause_l();
745}
746
747status_t AwesomePlayer::pause_l() {
748    if (!(mFlags & PLAYING)) {
749        return OK;
750    }
751
752    cancelPlayerEvents(true /* keepBufferingGoing */);
753
754    if (mAudioPlayer != NULL) {
755        mAudioPlayer->pause();
756    }
757
758    mFlags &= ~PLAYING;
759
760    return OK;
761}
762
763bool AwesomePlayer::isPlaying() const {
764    return (mFlags & PLAYING) || (mFlags & CACHE_UNDERRUN);
765}
766
767void AwesomePlayer::setISurface(const sp<ISurface> &isurface) {
768    Mutex::Autolock autoLock(mLock);
769
770    mISurface = isurface;
771}
772
773void AwesomePlayer::setAudioSink(
774        const sp<MediaPlayerBase::AudioSink> &audioSink) {
775    Mutex::Autolock autoLock(mLock);
776
777    mAudioSink = audioSink;
778}
779
780status_t AwesomePlayer::setLooping(bool shouldLoop) {
781    Mutex::Autolock autoLock(mLock);
782
783    mFlags = mFlags & ~LOOPING;
784
785    if (shouldLoop) {
786        mFlags |= LOOPING;
787    }
788
789    return OK;
790}
791
792status_t AwesomePlayer::getDuration(int64_t *durationUs) {
793    Mutex::Autolock autoLock(mMiscStateLock);
794
795    if (mDurationUs < 0) {
796        return UNKNOWN_ERROR;
797    }
798
799    *durationUs = mDurationUs;
800
801    return OK;
802}
803
804status_t AwesomePlayer::getPosition(int64_t *positionUs) {
805    if (mRTSPController != NULL) {
806        *positionUs = mRTSPController->getNormalPlayTimeUs();
807    }
808    else if (mSeeking) {
809        *positionUs = mSeekTimeUs;
810    } else if (mVideoSource != NULL) {
811        Mutex::Autolock autoLock(mMiscStateLock);
812        *positionUs = mVideoTimeUs;
813    } else if (mAudioPlayer != NULL) {
814        *positionUs = mAudioPlayer->getMediaTimeUs();
815    } else {
816        *positionUs = 0;
817    }
818
819    return OK;
820}
821
822status_t AwesomePlayer::seekTo(int64_t timeUs) {
823    if (mExtractorFlags
824            & (MediaExtractor::CAN_SEEK_FORWARD
825                | MediaExtractor::CAN_SEEK_BACKWARD)) {
826        Mutex::Autolock autoLock(mLock);
827        return seekTo_l(timeUs);
828    }
829
830    return OK;
831}
832
833status_t AwesomePlayer::seekTo_l(int64_t timeUs) {
834    if (mRTSPController != NULL) {
835        mRTSPController->seek(timeUs);
836
837        notifyListener_l(MEDIA_SEEK_COMPLETE);
838        mSeekNotificationSent = true;
839        return OK;
840    }
841
842    if (mFlags & CACHE_UNDERRUN) {
843        mFlags &= ~CACHE_UNDERRUN;
844        play_l();
845    }
846
847    mSeeking = true;
848    mSeekNotificationSent = false;
849    mSeekTimeUs = timeUs;
850    mFlags &= ~(AT_EOS | AUDIO_AT_EOS | VIDEO_AT_EOS);
851
852    seekAudioIfNecessary_l();
853
854    if (!(mFlags & PLAYING)) {
855        LOGV("seeking while paused, sending SEEK_COMPLETE notification"
856             " immediately.");
857
858        notifyListener_l(MEDIA_SEEK_COMPLETE);
859        mSeekNotificationSent = true;
860    }
861
862    return OK;
863}
864
865void AwesomePlayer::seekAudioIfNecessary_l() {
866    if (mSeeking && mVideoSource == NULL && mAudioPlayer != NULL) {
867        mAudioPlayer->seekTo(mSeekTimeUs);
868
869        mWatchForAudioSeekComplete = true;
870        mWatchForAudioEOS = true;
871        mSeekNotificationSent = false;
872    }
873}
874
875status_t AwesomePlayer::getVideoDimensions(
876        int32_t *width, int32_t *height) const {
877    Mutex::Autolock autoLock(mLock);
878
879    if (mVideoWidth < 0 || mVideoHeight < 0) {
880        return UNKNOWN_ERROR;
881    }
882
883    *width = mVideoWidth;
884    *height = mVideoHeight;
885
886    return OK;
887}
888
889void AwesomePlayer::setAudioSource(sp<MediaSource> source) {
890    CHECK(source != NULL);
891
892    mAudioTrack = source;
893}
894
895status_t AwesomePlayer::initAudioDecoder() {
896    sp<MetaData> meta = mAudioTrack->getFormat();
897
898    const char *mime;
899    CHECK(meta->findCString(kKeyMIMEType, &mime));
900
901    if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_RAW)) {
902        mAudioSource = mAudioTrack;
903    } else {
904        mAudioSource = OMXCodec::Create(
905                mClient.interface(), mAudioTrack->getFormat(),
906                false, // createEncoder
907                mAudioTrack);
908    }
909
910    if (mAudioSource != NULL) {
911        int64_t durationUs;
912        if (mAudioTrack->getFormat()->findInt64(kKeyDuration, &durationUs)) {
913            Mutex::Autolock autoLock(mMiscStateLock);
914            if (mDurationUs < 0 || durationUs > mDurationUs) {
915                mDurationUs = durationUs;
916            }
917        }
918
919        status_t err = mAudioSource->start();
920
921        if (err != OK) {
922            mAudioSource.clear();
923            return err;
924        }
925    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_QCELP)) {
926        // For legacy reasons we're simply going to ignore the absence
927        // of an audio decoder for QCELP instead of aborting playback
928        // altogether.
929        return OK;
930    }
931
932    return mAudioSource != NULL ? OK : UNKNOWN_ERROR;
933}
934
935void AwesomePlayer::setVideoSource(sp<MediaSource> source) {
936    CHECK(source != NULL);
937
938    mVideoTrack = source;
939}
940
941status_t AwesomePlayer::initVideoDecoder() {
942    uint32_t flags = 0;
943    mVideoSource = OMXCodec::Create(
944            mClient.interface(), mVideoTrack->getFormat(),
945            false, // createEncoder
946            mVideoTrack,
947            NULL, flags);
948
949    if (mVideoSource != NULL) {
950        int64_t durationUs;
951        if (mVideoTrack->getFormat()->findInt64(kKeyDuration, &durationUs)) {
952            Mutex::Autolock autoLock(mMiscStateLock);
953            if (mDurationUs < 0 || durationUs > mDurationUs) {
954                mDurationUs = durationUs;
955            }
956        }
957
958        CHECK(mVideoTrack->getFormat()->findInt32(kKeyWidth, &mVideoWidth));
959        CHECK(mVideoTrack->getFormat()->findInt32(kKeyHeight, &mVideoHeight));
960
961        status_t err = mVideoSource->start();
962
963        if (err != OK) {
964            mVideoSource.clear();
965            return err;
966        }
967    }
968
969    return mVideoSource != NULL ? OK : UNKNOWN_ERROR;
970}
971
972void AwesomePlayer::onVideoEvent() {
973    Mutex::Autolock autoLock(mLock);
974    if (!mVideoEventPending) {
975        // The event has been cancelled in reset_l() but had already
976        // been scheduled for execution at that time.
977        return;
978    }
979    mVideoEventPending = false;
980
981    if (mSeeking) {
982        if (mLastVideoBuffer) {
983            mLastVideoBuffer->release();
984            mLastVideoBuffer = NULL;
985        }
986
987        if (mVideoBuffer) {
988            mVideoBuffer->release();
989            mVideoBuffer = NULL;
990        }
991
992        if (mCachedSource != NULL && mAudioSource != NULL) {
993            // We're going to seek the video source first, followed by
994            // the audio source.
995            // In order to avoid jumps in the DataSource offset caused by
996            // the audio codec prefetching data from the old locations
997            // while the video codec is already reading data from the new
998            // locations, we'll "pause" the audio source, causing it to
999            // stop reading input data until a subsequent seek.
1000
1001            if (mAudioPlayer != NULL) {
1002                mAudioPlayer->pause();
1003            }
1004            mAudioSource->pause();
1005        }
1006    }
1007
1008    if (!mVideoBuffer) {
1009        MediaSource::ReadOptions options;
1010        if (mSeeking) {
1011            LOGV("seeking to %lld us (%.2f secs)", mSeekTimeUs, mSeekTimeUs / 1E6);
1012
1013            options.setSeekTo(
1014                    mSeekTimeUs, MediaSource::ReadOptions::SEEK_CLOSEST_SYNC);
1015        }
1016        for (;;) {
1017            status_t err = mVideoSource->read(&mVideoBuffer, &options);
1018            options.clearSeekTo();
1019
1020            if (err != OK) {
1021                CHECK_EQ(mVideoBuffer, NULL);
1022
1023                if (err == INFO_FORMAT_CHANGED) {
1024                    LOGV("VideoSource signalled format change.");
1025
1026                    if (mVideoRenderer != NULL) {
1027                        mVideoRendererIsPreview = false;
1028                        initRenderer_l();
1029                    }
1030                    continue;
1031                }
1032
1033                mFlags |= VIDEO_AT_EOS;
1034                postStreamDoneEvent_l(err);
1035                return;
1036            }
1037
1038            if (mVideoBuffer->range_length() == 0) {
1039                // Some decoders, notably the PV AVC software decoder
1040                // return spurious empty buffers that we just want to ignore.
1041
1042                mVideoBuffer->release();
1043                mVideoBuffer = NULL;
1044                continue;
1045            }
1046
1047            break;
1048        }
1049    }
1050
1051    int64_t timeUs;
1052    CHECK(mVideoBuffer->meta_data()->findInt64(kKeyTime, &timeUs));
1053
1054    {
1055        Mutex::Autolock autoLock(mMiscStateLock);
1056        mVideoTimeUs = timeUs;
1057    }
1058
1059    if (mSeeking) {
1060        if (mAudioPlayer != NULL) {
1061            LOGV("seeking audio to %lld us (%.2f secs).", timeUs, timeUs / 1E6);
1062
1063            mAudioPlayer->seekTo(timeUs);
1064            mAudioPlayer->resume();
1065            mWatchForAudioSeekComplete = true;
1066            mWatchForAudioEOS = true;
1067        } else if (!mSeekNotificationSent) {
1068            // If we're playing video only, report seek complete now,
1069            // otherwise audio player will notify us later.
1070            notifyListener_l(MEDIA_SEEK_COMPLETE);
1071        }
1072
1073        mFlags |= FIRST_FRAME;
1074        mSeeking = false;
1075        mSeekNotificationSent = false;
1076    }
1077
1078    TimeSource *ts = (mFlags & AUDIO_AT_EOS) ? &mSystemTimeSource : mTimeSource;
1079
1080    if (mFlags & FIRST_FRAME) {
1081        mFlags &= ~FIRST_FRAME;
1082
1083        mTimeSourceDeltaUs = ts->getRealTimeUs() - timeUs;
1084    }
1085
1086    int64_t realTimeUs, mediaTimeUs;
1087    if (!(mFlags & AUDIO_AT_EOS) && mAudioPlayer != NULL
1088        && mAudioPlayer->getMediaTimeMapping(&realTimeUs, &mediaTimeUs)) {
1089        mTimeSourceDeltaUs = realTimeUs - mediaTimeUs;
1090    }
1091
1092    int64_t nowUs = ts->getRealTimeUs() - mTimeSourceDeltaUs;
1093
1094    int64_t latenessUs = nowUs - timeUs;
1095
1096    if (mRTPSession != NULL) {
1097        // We'll completely ignore timestamps for gtalk videochat
1098        // and we'll play incoming video as fast as we get it.
1099        latenessUs = 0;
1100    }
1101
1102    if (latenessUs > 40000) {
1103        // We're more than 40ms late.
1104        LOGV("we're late by %lld us (%.2f secs)", latenessUs, latenessUs / 1E6);
1105
1106        mVideoBuffer->release();
1107        mVideoBuffer = NULL;
1108
1109        postVideoEvent_l();
1110        return;
1111    }
1112
1113    if (latenessUs < -10000) {
1114        // We're more than 10ms early.
1115
1116        postVideoEvent_l(10000);
1117        return;
1118    }
1119
1120    if (mVideoRendererIsPreview || mVideoRenderer == NULL) {
1121        mVideoRendererIsPreview = false;
1122
1123        initRenderer_l();
1124    }
1125
1126    if (mVideoRenderer != NULL) {
1127        mVideoRenderer->render(mVideoBuffer);
1128    }
1129
1130    if (mLastVideoBuffer) {
1131        mLastVideoBuffer->release();
1132        mLastVideoBuffer = NULL;
1133    }
1134    mLastVideoBuffer = mVideoBuffer;
1135    mVideoBuffer = NULL;
1136
1137    postVideoEvent_l();
1138}
1139
1140void AwesomePlayer::postVideoEvent_l(int64_t delayUs) {
1141    if (mVideoEventPending) {
1142        return;
1143    }
1144
1145    mVideoEventPending = true;
1146    mQueue.postEventWithDelay(mVideoEvent, delayUs < 0 ? 10000 : delayUs);
1147}
1148
1149void AwesomePlayer::postStreamDoneEvent_l(status_t status) {
1150    if (mStreamDoneEventPending) {
1151        return;
1152    }
1153    mStreamDoneEventPending = true;
1154
1155    mStreamDoneStatus = status;
1156    mQueue.postEvent(mStreamDoneEvent);
1157}
1158
1159void AwesomePlayer::postBufferingEvent_l() {
1160    if (mBufferingEventPending) {
1161        return;
1162    }
1163    mBufferingEventPending = true;
1164    mQueue.postEventWithDelay(mBufferingEvent, 1000000ll);
1165}
1166
1167void AwesomePlayer::postCheckAudioStatusEvent_l() {
1168    if (mAudioStatusEventPending) {
1169        return;
1170    }
1171    mAudioStatusEventPending = true;
1172    mQueue.postEventWithDelay(mCheckAudioStatusEvent, 100000ll);
1173}
1174
1175void AwesomePlayer::onCheckAudioStatus() {
1176    Mutex::Autolock autoLock(mLock);
1177    if (!mAudioStatusEventPending) {
1178        // Event was dispatched and while we were blocking on the mutex,
1179        // has already been cancelled.
1180        return;
1181    }
1182
1183    mAudioStatusEventPending = false;
1184
1185    if (mWatchForAudioSeekComplete && !mAudioPlayer->isSeeking()) {
1186        mWatchForAudioSeekComplete = false;
1187
1188        if (!mSeekNotificationSent) {
1189            notifyListener_l(MEDIA_SEEK_COMPLETE);
1190            mSeekNotificationSent = true;
1191        }
1192
1193        mSeeking = false;
1194    }
1195
1196    status_t finalStatus;
1197    if (mWatchForAudioEOS && mAudioPlayer->reachedEOS(&finalStatus)) {
1198        mWatchForAudioEOS = false;
1199        mFlags |= AUDIO_AT_EOS;
1200        mFlags |= FIRST_FRAME;
1201        postStreamDoneEvent_l(finalStatus);
1202    }
1203
1204    postCheckAudioStatusEvent_l();
1205}
1206
1207status_t AwesomePlayer::prepare() {
1208    Mutex::Autolock autoLock(mLock);
1209    return prepare_l();
1210}
1211
1212status_t AwesomePlayer::prepare_l() {
1213    if (mFlags & PREPARED) {
1214        return OK;
1215    }
1216
1217    if (mFlags & PREPARING) {
1218        return UNKNOWN_ERROR;
1219    }
1220
1221    mIsAsyncPrepare = false;
1222    status_t err = prepareAsync_l();
1223
1224    if (err != OK) {
1225        return err;
1226    }
1227
1228    while (mFlags & PREPARING) {
1229        mPreparedCondition.wait(mLock);
1230    }
1231
1232    return mPrepareResult;
1233}
1234
1235status_t AwesomePlayer::prepareAsync() {
1236    Mutex::Autolock autoLock(mLock);
1237
1238    if (mFlags & PREPARING) {
1239        return UNKNOWN_ERROR;  // async prepare already pending
1240    }
1241
1242    mIsAsyncPrepare = true;
1243    return prepareAsync_l();
1244}
1245
1246status_t AwesomePlayer::prepareAsync_l() {
1247    if (mFlags & PREPARING) {
1248        return UNKNOWN_ERROR;  // async prepare already pending
1249    }
1250
1251    if (!mQueueStarted) {
1252        mQueue.start();
1253        mQueueStarted = true;
1254    }
1255
1256    mFlags |= PREPARING;
1257    mAsyncPrepareEvent = new AwesomeEvent(
1258            this, &AwesomePlayer::onPrepareAsyncEvent);
1259
1260    mQueue.postEvent(mAsyncPrepareEvent);
1261
1262    return OK;
1263}
1264
1265status_t AwesomePlayer::finishSetDataSource_l() {
1266    sp<DataSource> dataSource;
1267
1268    if (!strncasecmp("http://", mUri.string(), 7)) {
1269        mConnectingDataSource = new NuHTTPDataSource;
1270
1271        mLock.unlock();
1272        status_t err = mConnectingDataSource->connect(mUri, &mUriHeaders);
1273        mLock.lock();
1274
1275        if (err != OK) {
1276            mConnectingDataSource.clear();
1277
1278            LOGI("mConnectingDataSource->connect() returned %d", err);
1279            return err;
1280        }
1281
1282#if 0
1283        mCachedSource = new NuCachedSource2(
1284                new ThrottledSource(
1285                    mConnectingDataSource, 50 * 1024 /* bytes/sec */));
1286#else
1287        mCachedSource = new NuCachedSource2(mConnectingDataSource);
1288#endif
1289        mConnectingDataSource.clear();
1290
1291        dataSource = mCachedSource;
1292    } else if (!strncasecmp(mUri.string(), "httplive://", 11)) {
1293        String8 uri("http://");
1294        uri.append(mUri.string() + 11);
1295
1296        dataSource = new LiveSource(uri.string());
1297
1298        mCachedSource = new NuCachedSource2(dataSource);
1299        dataSource = mCachedSource;
1300
1301        sp<MediaExtractor> extractor =
1302            MediaExtractor::Create(dataSource, MEDIA_MIMETYPE_CONTAINER_MPEG2TS);
1303
1304        return setDataSource_l(extractor);
1305    } else if (!strncmp("rtsp://gtalk/", mUri.string(), 13)) {
1306        if (mLooper == NULL) {
1307            mLooper = new ALooper;
1308            mLooper->setName("gtalk rtp");
1309            mLooper->start(
1310                    false /* runOnCallingThread */,
1311                    false /* canCallJava */,
1312                    PRIORITY_HIGHEST);
1313        }
1314
1315        const char *startOfCodecString = &mUri.string()[13];
1316        const char *startOfSlash1 = strchr(startOfCodecString, '/');
1317        if (startOfSlash1 == NULL) {
1318            return BAD_VALUE;
1319        }
1320        const char *startOfWidthString = &startOfSlash1[1];
1321        const char *startOfSlash2 = strchr(startOfWidthString, '/');
1322        if (startOfSlash2 == NULL) {
1323            return BAD_VALUE;
1324        }
1325        const char *startOfHeightString = &startOfSlash2[1];
1326
1327        String8 codecString(startOfCodecString, startOfSlash1 - startOfCodecString);
1328        String8 widthString(startOfWidthString, startOfSlash2 - startOfWidthString);
1329        String8 heightString(startOfHeightString);
1330
1331#if 0
1332        mRTPPusher = new UDPPusher("/data/misc/rtpout.bin", 5434);
1333        mLooper->registerHandler(mRTPPusher);
1334
1335        mRTCPPusher = new UDPPusher("/data/misc/rtcpout.bin", 5435);
1336        mLooper->registerHandler(mRTCPPusher);
1337#endif
1338
1339        mRTPSession = new ARTPSession;
1340        mLooper->registerHandler(mRTPSession);
1341
1342#if 0
1343        // My AMR SDP
1344        static const char *raw =
1345            "v=0\r\n"
1346            "o=- 64 233572944 IN IP4 127.0.0.0\r\n"
1347            "s=QuickTime\r\n"
1348            "t=0 0\r\n"
1349            "a=range:npt=0-315\r\n"
1350            "a=isma-compliance:2,2.0,2\r\n"
1351            "m=audio 5434 RTP/AVP 97\r\n"
1352            "c=IN IP4 127.0.0.1\r\n"
1353            "b=AS:30\r\n"
1354            "a=rtpmap:97 AMR/8000/1\r\n"
1355            "a=fmtp:97 octet-align\r\n";
1356#elif 1
1357        String8 sdp;
1358        sdp.appendFormat(
1359            "v=0\r\n"
1360            "o=- 64 233572944 IN IP4 127.0.0.0\r\n"
1361            "s=QuickTime\r\n"
1362            "t=0 0\r\n"
1363            "a=range:npt=0-315\r\n"
1364            "a=isma-compliance:2,2.0,2\r\n"
1365            "m=video 5434 RTP/AVP 97\r\n"
1366            "c=IN IP4 127.0.0.1\r\n"
1367            "b=AS:30\r\n"
1368            "a=rtpmap:97 %s/90000\r\n"
1369            "a=cliprect:0,0,%s,%s\r\n"
1370            "a=framesize:97 %s-%s\r\n",
1371
1372            codecString.string(),
1373            heightString.string(), widthString.string(),
1374            widthString.string(), heightString.string()
1375            );
1376        const char *raw = sdp.string();
1377
1378#endif
1379
1380        sp<ASessionDescription> desc = new ASessionDescription;
1381        CHECK(desc->setTo(raw, strlen(raw)));
1382
1383        CHECK_EQ(mRTPSession->setup(desc), (status_t)OK);
1384
1385        if (mRTPPusher != NULL) {
1386            mRTPPusher->start();
1387        }
1388
1389        if (mRTCPPusher != NULL) {
1390            mRTCPPusher->start();
1391        }
1392
1393        CHECK_EQ(mRTPSession->countTracks(), 1u);
1394        sp<MediaSource> source = mRTPSession->trackAt(0);
1395
1396#if 0
1397        bool eos;
1398        while (((APacketSource *)source.get())
1399                ->getQueuedDuration(&eos) < 5000000ll && !eos) {
1400            usleep(100000ll);
1401        }
1402#endif
1403
1404        const char *mime;
1405        CHECK(source->getFormat()->findCString(kKeyMIMEType, &mime));
1406
1407        if (!strncasecmp("video/", mime, 6)) {
1408            setVideoSource(source);
1409        } else {
1410            CHECK(!strncasecmp("audio/", mime, 6));
1411            setAudioSource(source);
1412        }
1413
1414        mExtractorFlags = MediaExtractor::CAN_PAUSE;
1415
1416        return OK;
1417    } else if (!strncasecmp("rtsp://", mUri.string(), 7)) {
1418        if (mLooper == NULL) {
1419            mLooper = new ALooper;
1420            mLooper->setName("rtsp");
1421            mLooper->start();
1422        }
1423        mRTSPController = new ARTSPController(mLooper);
1424        status_t err = mRTSPController->connect(mUri.string());
1425
1426        LOGI("ARTSPController::connect returned %d", err);
1427
1428        if (err != OK) {
1429            mRTSPController.clear();
1430            return err;
1431        }
1432
1433        sp<MediaExtractor> extractor = mRTSPController.get();
1434        return setDataSource_l(extractor);
1435    } else {
1436        dataSource = DataSource::CreateFromURI(mUri.string(), &mUriHeaders);
1437    }
1438
1439    if (dataSource == NULL) {
1440        return UNKNOWN_ERROR;
1441    }
1442
1443    sp<MediaExtractor> extractor = MediaExtractor::Create(dataSource);
1444
1445    if (extractor == NULL) {
1446        return UNKNOWN_ERROR;
1447    }
1448
1449    return setDataSource_l(extractor);
1450}
1451
1452void AwesomePlayer::abortPrepare(status_t err) {
1453    CHECK(err != OK);
1454
1455    if (mIsAsyncPrepare) {
1456        notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err);
1457    }
1458
1459    mPrepareResult = err;
1460    mFlags &= ~(PREPARING|PREPARE_CANCELLED);
1461    mAsyncPrepareEvent = NULL;
1462    mPreparedCondition.broadcast();
1463}
1464
1465// static
1466bool AwesomePlayer::ContinuePreparation(void *cookie) {
1467    AwesomePlayer *me = static_cast<AwesomePlayer *>(cookie);
1468
1469    return (me->mFlags & PREPARE_CANCELLED) == 0;
1470}
1471
1472void AwesomePlayer::onPrepareAsyncEvent() {
1473    Mutex::Autolock autoLock(mLock);
1474
1475    if (mFlags & PREPARE_CANCELLED) {
1476        LOGI("prepare was cancelled before doing anything");
1477        abortPrepare(UNKNOWN_ERROR);
1478        return;
1479    }
1480
1481    if (mUri.size() > 0) {
1482        status_t err = finishSetDataSource_l();
1483
1484        if (err != OK) {
1485            abortPrepare(err);
1486            return;
1487        }
1488    }
1489
1490    if (mVideoTrack != NULL && mVideoSource == NULL) {
1491        status_t err = initVideoDecoder();
1492
1493        if (err != OK) {
1494            abortPrepare(err);
1495            return;
1496        }
1497    }
1498
1499    if (mAudioTrack != NULL && mAudioSource == NULL) {
1500        status_t err = initAudioDecoder();
1501
1502        if (err != OK) {
1503            abortPrepare(err);
1504            return;
1505        }
1506    }
1507
1508    if (mCachedSource != NULL || mRTSPController != NULL) {
1509        postBufferingEvent_l();
1510    } else {
1511        finishAsyncPrepare_l();
1512    }
1513}
1514
1515void AwesomePlayer::finishAsyncPrepare_l() {
1516    if (mIsAsyncPrepare) {
1517        if (mVideoWidth < 0 || mVideoHeight < 0) {
1518            notifyListener_l(MEDIA_SET_VIDEO_SIZE, 0, 0);
1519        } else {
1520            notifyListener_l(MEDIA_SET_VIDEO_SIZE, mVideoWidth, mVideoHeight);
1521        }
1522
1523        notifyListener_l(MEDIA_PREPARED);
1524    }
1525
1526    mPrepareResult = OK;
1527    mFlags &= ~(PREPARING|PREPARE_CANCELLED);
1528    mFlags |= PREPARED;
1529    mAsyncPrepareEvent = NULL;
1530    mPreparedCondition.broadcast();
1531}
1532
1533status_t AwesomePlayer::suspend() {
1534    LOGV("suspend");
1535    Mutex::Autolock autoLock(mLock);
1536
1537    if (mSuspensionState != NULL) {
1538        if (mLastVideoBuffer == NULL) {
1539            //go into here if video is suspended again
1540            //after resuming without being played between
1541            //them
1542            SuspensionState *state = mSuspensionState;
1543            mSuspensionState = NULL;
1544            reset_l();
1545            mSuspensionState = state;
1546            return OK;
1547        }
1548
1549        delete mSuspensionState;
1550        mSuspensionState = NULL;
1551    }
1552
1553    if (mFlags & PREPARING) {
1554        mFlags |= PREPARE_CANCELLED;
1555        if (mConnectingDataSource != NULL) {
1556            LOGI("interrupting the connection process");
1557            mConnectingDataSource->disconnect();
1558        }
1559    }
1560
1561    while (mFlags & PREPARING) {
1562        mPreparedCondition.wait(mLock);
1563    }
1564
1565    SuspensionState *state = new SuspensionState;
1566    state->mUri = mUri;
1567    state->mUriHeaders = mUriHeaders;
1568    state->mFileSource = mFileSource;
1569
1570    state->mFlags = mFlags & (PLAYING | AUTO_LOOPING | LOOPING | AT_EOS);
1571    getPosition(&state->mPositionUs);
1572
1573    if (mLastVideoBuffer) {
1574        size_t size = mLastVideoBuffer->range_length();
1575        if (size) {
1576            state->mLastVideoFrameSize = size;
1577            state->mLastVideoFrame = malloc(size);
1578            memcpy(state->mLastVideoFrame,
1579                   (const uint8_t *)mLastVideoBuffer->data()
1580                        + mLastVideoBuffer->range_offset(),
1581                   size);
1582
1583            state->mVideoWidth = mVideoWidth;
1584            state->mVideoHeight = mVideoHeight;
1585
1586            sp<MetaData> meta = mVideoSource->getFormat();
1587            CHECK(meta->findInt32(kKeyColorFormat, &state->mColorFormat));
1588            CHECK(meta->findInt32(kKeyWidth, &state->mDecodedWidth));
1589            CHECK(meta->findInt32(kKeyHeight, &state->mDecodedHeight));
1590        }
1591    }
1592
1593    reset_l();
1594
1595    mSuspensionState = state;
1596
1597    return OK;
1598}
1599
1600status_t AwesomePlayer::resume() {
1601    LOGV("resume");
1602    Mutex::Autolock autoLock(mLock);
1603
1604    if (mSuspensionState == NULL) {
1605        return INVALID_OPERATION;
1606    }
1607
1608    SuspensionState *state = mSuspensionState;
1609    mSuspensionState = NULL;
1610
1611    status_t err;
1612    if (state->mFileSource != NULL) {
1613        err = setDataSource_l(state->mFileSource);
1614
1615        if (err == OK) {
1616            mFileSource = state->mFileSource;
1617        }
1618    } else {
1619        err = setDataSource_l(state->mUri, &state->mUriHeaders);
1620    }
1621
1622    if (err != OK) {
1623        delete state;
1624        state = NULL;
1625
1626        return err;
1627    }
1628
1629    seekTo_l(state->mPositionUs);
1630
1631    mFlags = state->mFlags & (AUTO_LOOPING | LOOPING | AT_EOS);
1632
1633    if (state->mLastVideoFrame && mISurface != NULL) {
1634        mVideoRenderer =
1635            new AwesomeLocalRenderer(
1636                    true,  // previewOnly
1637                    "",
1638                    (OMX_COLOR_FORMATTYPE)state->mColorFormat,
1639                    mISurface,
1640                    state->mVideoWidth,
1641                    state->mVideoHeight,
1642                    state->mDecodedWidth,
1643                    state->mDecodedHeight);
1644
1645        mVideoRendererIsPreview = true;
1646
1647        ((AwesomeLocalRenderer *)mVideoRenderer.get())->render(
1648                state->mLastVideoFrame, state->mLastVideoFrameSize);
1649    }
1650
1651    if (state->mFlags & PLAYING) {
1652        play_l();
1653    }
1654
1655    mSuspensionState = state;
1656    state = NULL;
1657
1658    return OK;
1659}
1660
1661uint32_t AwesomePlayer::flags() const {
1662    return mExtractorFlags;
1663}
1664
1665}  // namespace android
1666
1667