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