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