NuPlayerRenderer.cpp revision e17afa888040eb5fbd31249305efd88ee03bb5bc
1/*
2 * Copyright (C) 2010 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 "NuPlayerRenderer"
19#include <utils/Log.h>
20
21#include "NuPlayerRenderer.h"
22
23#include <media/stagefright/foundation/ABuffer.h>
24#include <media/stagefright/foundation/ADebug.h>
25#include <media/stagefright/foundation/AMessage.h>
26#include <media/stagefright/foundation/AUtils.h>
27#include <media/stagefright/MediaErrors.h>
28#include <media/stagefright/MetaData.h>
29#include <media/stagefright/Utils.h>
30
31#include <VideoFrameScheduler.h>
32
33#include <inttypes.h>
34
35namespace android {
36
37// Maximum time in paused state when offloading audio decompression. When elapsed, the AudioSink
38// is closed to allow the audio DSP to power down.
39static const int64_t kOffloadPauseMaxUs = 10000000ll;
40
41// static
42const int64_t NuPlayer::Renderer::kMinPositionUpdateDelayUs = 100000ll;
43
44NuPlayer::Renderer::Renderer(
45        const sp<MediaPlayerBase::AudioSink> &sink,
46        const sp<AMessage> &notify,
47        uint32_t flags)
48    : mAudioSink(sink),
49      mNotify(notify),
50      mFlags(flags),
51      mNumFramesWritten(0),
52      mDrainAudioQueuePending(false),
53      mDrainVideoQueuePending(false),
54      mAudioQueueGeneration(0),
55      mVideoQueueGeneration(0),
56      mAudioFirstAnchorTimeMediaUs(-1),
57      mAnchorTimeMediaUs(-1),
58      mAnchorTimeRealUs(-1),
59      mAnchorNumFramesWritten(-1),
60      mAnchorMaxMediaUs(-1),
61      mVideoLateByUs(0ll),
62      mHasAudio(false),
63      mHasVideo(false),
64      mPauseStartedTimeRealUs(-1),
65      mFlushingAudio(false),
66      mFlushingVideo(false),
67      mSyncQueues(false),
68      mPaused(false),
69      mVideoSampleReceived(false),
70      mVideoRenderingStarted(false),
71      mVideoRenderingStartGeneration(0),
72      mAudioRenderingStartGeneration(0),
73      mAudioOffloadPauseTimeoutGeneration(0),
74      mAudioOffloadTornDown(false),
75      mCurrentOffloadInfo(AUDIO_INFO_INITIALIZER),
76      mTotalBuffersQueued(0),
77      mLastAudioBufferDrained(0) {
78}
79
80NuPlayer::Renderer::~Renderer() {
81    if (offloadingAudio()) {
82        mAudioSink->stop();
83        mAudioSink->flush();
84        mAudioSink->close();
85    }
86}
87
88void NuPlayer::Renderer::queueBuffer(
89        bool audio,
90        const sp<ABuffer> &buffer,
91        const sp<AMessage> &notifyConsumed) {
92    sp<AMessage> msg = new AMessage(kWhatQueueBuffer, id());
93    msg->setInt32("audio", static_cast<int32_t>(audio));
94    msg->setBuffer("buffer", buffer);
95    msg->setMessage("notifyConsumed", notifyConsumed);
96    msg->post();
97}
98
99void NuPlayer::Renderer::queueEOS(bool audio, status_t finalResult) {
100    CHECK_NE(finalResult, (status_t)OK);
101
102    sp<AMessage> msg = new AMessage(kWhatQueueEOS, id());
103    msg->setInt32("audio", static_cast<int32_t>(audio));
104    msg->setInt32("finalResult", finalResult);
105    msg->post();
106}
107
108void NuPlayer::Renderer::flush(bool audio) {
109    {
110        Mutex::Autolock autoLock(mFlushLock);
111        if (audio) {
112            if (mFlushingAudio) {
113                return;
114            }
115            mFlushingAudio = true;
116        } else {
117            if (mFlushingVideo) {
118                return;
119            }
120            mFlushingVideo = true;
121        }
122    }
123
124    sp<AMessage> msg = new AMessage(kWhatFlush, id());
125    msg->setInt32("audio", static_cast<int32_t>(audio));
126    msg->post();
127}
128
129void NuPlayer::Renderer::signalTimeDiscontinuity() {
130    Mutex::Autolock autoLock(mLock);
131    // CHECK(mAudioQueue.empty());
132    // CHECK(mVideoQueue.empty());
133    setAudioFirstAnchorTime(-1);
134    setAnchorTime(-1, -1);
135    setVideoLateByUs(0);
136    mSyncQueues = false;
137}
138
139void NuPlayer::Renderer::signalAudioSinkChanged() {
140    (new AMessage(kWhatAudioSinkChanged, id()))->post();
141}
142
143void NuPlayer::Renderer::signalDisableOffloadAudio() {
144    (new AMessage(kWhatDisableOffloadAudio, id()))->post();
145}
146
147void NuPlayer::Renderer::pause() {
148    (new AMessage(kWhatPause, id()))->post();
149}
150
151void NuPlayer::Renderer::resume() {
152    (new AMessage(kWhatResume, id()))->post();
153}
154
155void NuPlayer::Renderer::setVideoFrameRate(float fps) {
156    sp<AMessage> msg = new AMessage(kWhatSetVideoFrameRate, id());
157    msg->setFloat("frame-rate", fps);
158    msg->post();
159}
160
161status_t NuPlayer::Renderer::getCurrentPosition(int64_t *mediaUs) {
162    return getCurrentPosition(mediaUs, ALooper::GetNowUs());
163}
164
165status_t NuPlayer::Renderer::getCurrentPosition(
166        int64_t *mediaUs, int64_t nowUs, bool allowPastQueuedVideo) {
167    Mutex::Autolock autoLock(mTimeLock);
168    if (!mHasAudio && !mHasVideo) {
169        return NO_INIT;
170    }
171
172    if (mAnchorTimeMediaUs < 0) {
173        return NO_INIT;
174    }
175
176    int64_t positionUs = (nowUs - mAnchorTimeRealUs) + mAnchorTimeMediaUs;
177
178    if (mPauseStartedTimeRealUs != -1) {
179        positionUs -= (nowUs - mPauseStartedTimeRealUs);
180    }
181
182    // limit position to the last queued media time (for video only stream
183    // position will be discrete as we don't know how long each frame lasts)
184    if (mAnchorMaxMediaUs >= 0 && !allowPastQueuedVideo) {
185        if (positionUs > mAnchorMaxMediaUs) {
186            positionUs = mAnchorMaxMediaUs;
187        }
188    }
189
190    if (positionUs < mAudioFirstAnchorTimeMediaUs) {
191        positionUs = mAudioFirstAnchorTimeMediaUs;
192    }
193
194    *mediaUs = (positionUs <= 0) ? 0 : positionUs;
195    return OK;
196}
197
198void NuPlayer::Renderer::setHasMedia(bool audio) {
199    Mutex::Autolock autoLock(mTimeLock);
200    if (audio) {
201        mHasAudio = true;
202    } else {
203        mHasVideo = true;
204    }
205}
206
207void NuPlayer::Renderer::setAudioFirstAnchorTime(int64_t mediaUs) {
208    Mutex::Autolock autoLock(mTimeLock);
209    mAudioFirstAnchorTimeMediaUs = mediaUs;
210}
211
212void NuPlayer::Renderer::setAudioFirstAnchorTimeIfNeeded(int64_t mediaUs) {
213    Mutex::Autolock autoLock(mTimeLock);
214    if (mAudioFirstAnchorTimeMediaUs == -1) {
215        mAudioFirstAnchorTimeMediaUs = mediaUs;
216    }
217}
218
219void NuPlayer::Renderer::setAnchorTime(
220        int64_t mediaUs, int64_t realUs, int64_t numFramesWritten, bool resume) {
221    Mutex::Autolock autoLock(mTimeLock);
222    mAnchorTimeMediaUs = mediaUs;
223    mAnchorTimeRealUs = realUs;
224    mAnchorNumFramesWritten = numFramesWritten;
225    if (resume) {
226        mPauseStartedTimeRealUs = -1;
227    }
228}
229
230void NuPlayer::Renderer::setVideoLateByUs(int64_t lateUs) {
231    Mutex::Autolock autoLock(mTimeLock);
232    mVideoLateByUs = lateUs;
233}
234
235int64_t NuPlayer::Renderer::getVideoLateByUs() {
236    Mutex::Autolock autoLock(mTimeLock);
237    return mVideoLateByUs;
238}
239
240void NuPlayer::Renderer::setPauseStartedTimeRealUs(int64_t realUs) {
241    Mutex::Autolock autoLock(mTimeLock);
242    mPauseStartedTimeRealUs = realUs;
243}
244
245bool NuPlayer::Renderer::openAudioSink(
246        const sp<AMessage> &format,
247        bool offloadOnly,
248        bool hasVideo,
249        uint32_t flags) {
250    sp<AMessage> msg = new AMessage(kWhatOpenAudioSink, id());
251    msg->setMessage("format", format);
252    msg->setInt32("offload-only", offloadOnly);
253    msg->setInt32("has-video", hasVideo);
254    msg->setInt32("flags", flags);
255
256    sp<AMessage> response;
257    msg->postAndAwaitResponse(&response);
258
259    int32_t offload;
260    CHECK(response->findInt32("offload", &offload));
261    return (offload != 0);
262}
263
264void NuPlayer::Renderer::closeAudioSink() {
265    sp<AMessage> msg = new AMessage(kWhatCloseAudioSink, id());
266
267    sp<AMessage> response;
268    msg->postAndAwaitResponse(&response);
269}
270
271void NuPlayer::Renderer::onMessageReceived(const sp<AMessage> &msg) {
272    switch (msg->what()) {
273        case kWhatOpenAudioSink:
274        {
275            sp<AMessage> format;
276            CHECK(msg->findMessage("format", &format));
277
278            int32_t offloadOnly;
279            CHECK(msg->findInt32("offload-only", &offloadOnly));
280
281            int32_t hasVideo;
282            CHECK(msg->findInt32("has-video", &hasVideo));
283
284            uint32_t flags;
285            CHECK(msg->findInt32("flags", (int32_t *)&flags));
286
287            bool offload = onOpenAudioSink(format, offloadOnly, hasVideo, flags);
288
289            sp<AMessage> response = new AMessage;
290            response->setInt32("offload", offload);
291
292            uint32_t replyID;
293            CHECK(msg->senderAwaitsResponse(&replyID));
294            response->postReply(replyID);
295
296            break;
297        }
298
299        case kWhatCloseAudioSink:
300        {
301            uint32_t replyID;
302            CHECK(msg->senderAwaitsResponse(&replyID));
303
304            onCloseAudioSink();
305
306            sp<AMessage> response = new AMessage;
307            response->postReply(replyID);
308            break;
309        }
310
311        case kWhatStopAudioSink:
312        {
313            mAudioSink->stop();
314            break;
315        }
316
317        case kWhatDrainAudioQueue:
318        {
319            int32_t generation;
320            CHECK(msg->findInt32("generation", &generation));
321            if (generation != mAudioQueueGeneration) {
322                break;
323            }
324
325            mDrainAudioQueuePending = false;
326
327            if (onDrainAudioQueue()) {
328                uint32_t numFramesPlayed;
329                CHECK_EQ(mAudioSink->getPosition(&numFramesPlayed),
330                         (status_t)OK);
331
332                uint32_t numFramesPendingPlayout =
333                    mNumFramesWritten - numFramesPlayed;
334
335                // This is how long the audio sink will have data to
336                // play back.
337                int64_t delayUs =
338                    mAudioSink->msecsPerFrame()
339                        * numFramesPendingPlayout * 1000ll;
340
341                // Let's give it more data after about half that time
342                // has elapsed.
343                // kWhatDrainAudioQueue is used for non-offloading mode,
344                // and mLock is used only for offloading mode. Therefore,
345                // no need to acquire mLock here.
346                postDrainAudioQueue_l(delayUs / 2);
347            }
348            break;
349        }
350
351        case kWhatDrainVideoQueue:
352        {
353            int32_t generation;
354            CHECK(msg->findInt32("generation", &generation));
355            if (generation != mVideoQueueGeneration) {
356                break;
357            }
358
359            mDrainVideoQueuePending = false;
360
361            onDrainVideoQueue();
362
363            postDrainVideoQueue();
364            break;
365        }
366
367        case kWhatPostDrainVideoQueue:
368        {
369            int32_t generation;
370            CHECK(msg->findInt32("generation", &generation));
371            if (generation != mVideoQueueGeneration) {
372                break;
373            }
374
375            mDrainVideoQueuePending = false;
376            postDrainVideoQueue();
377            break;
378        }
379
380        case kWhatQueueBuffer:
381        {
382            onQueueBuffer(msg);
383            break;
384        }
385
386        case kWhatQueueEOS:
387        {
388            onQueueEOS(msg);
389            break;
390        }
391
392        case kWhatFlush:
393        {
394            onFlush(msg);
395            break;
396        }
397
398        case kWhatAudioSinkChanged:
399        {
400            onAudioSinkChanged();
401            break;
402        }
403
404        case kWhatDisableOffloadAudio:
405        {
406            onDisableOffloadAudio();
407            break;
408        }
409
410        case kWhatPause:
411        {
412            onPause();
413            break;
414        }
415
416        case kWhatResume:
417        {
418            onResume();
419            break;
420        }
421
422        case kWhatSetVideoFrameRate:
423        {
424            float fps;
425            CHECK(msg->findFloat("frame-rate", &fps));
426            onSetVideoFrameRate(fps);
427            break;
428        }
429
430        case kWhatAudioOffloadTearDown:
431        {
432            onAudioOffloadTearDown(kDueToError);
433            break;
434        }
435
436        case kWhatAudioOffloadPauseTimeout:
437        {
438            int32_t generation;
439            CHECK(msg->findInt32("generation", &generation));
440            if (generation != mAudioOffloadPauseTimeoutGeneration) {
441                break;
442            }
443            ALOGV("Audio Offload tear down due to pause timeout.");
444            onAudioOffloadTearDown(kDueToTimeout);
445            break;
446        }
447
448        default:
449            TRESPASS();
450            break;
451    }
452}
453
454void NuPlayer::Renderer::postDrainAudioQueue_l(int64_t delayUs) {
455    if (mDrainAudioQueuePending || mSyncQueues || mPaused
456            || offloadingAudio()) {
457        return;
458    }
459
460    if (mAudioQueue.empty()) {
461        return;
462    }
463
464    mDrainAudioQueuePending = true;
465    sp<AMessage> msg = new AMessage(kWhatDrainAudioQueue, id());
466    msg->setInt32("generation", mAudioQueueGeneration);
467    msg->post(delayUs);
468}
469
470void NuPlayer::Renderer::prepareForMediaRenderingStart() {
471    mAudioRenderingStartGeneration = mAudioQueueGeneration;
472    mVideoRenderingStartGeneration = mVideoQueueGeneration;
473}
474
475void NuPlayer::Renderer::notifyIfMediaRenderingStarted() {
476    if (mVideoRenderingStartGeneration == mVideoQueueGeneration &&
477        mAudioRenderingStartGeneration == mAudioQueueGeneration) {
478        mVideoRenderingStartGeneration = -1;
479        mAudioRenderingStartGeneration = -1;
480
481        sp<AMessage> notify = mNotify->dup();
482        notify->setInt32("what", kWhatMediaRenderingStart);
483        notify->post();
484    }
485}
486
487// static
488size_t NuPlayer::Renderer::AudioSinkCallback(
489        MediaPlayerBase::AudioSink * /* audioSink */,
490        void *buffer,
491        size_t size,
492        void *cookie,
493        MediaPlayerBase::AudioSink::cb_event_t event) {
494    NuPlayer::Renderer *me = (NuPlayer::Renderer *)cookie;
495
496    switch (event) {
497        case MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER:
498        {
499            return me->fillAudioBuffer(buffer, size);
500            break;
501        }
502
503        case MediaPlayerBase::AudioSink::CB_EVENT_STREAM_END:
504        {
505            me->notifyEOS(true /* audio */, ERROR_END_OF_STREAM);
506            break;
507        }
508
509        case MediaPlayerBase::AudioSink::CB_EVENT_TEAR_DOWN:
510        {
511            me->notifyAudioOffloadTearDown();
512            break;
513        }
514    }
515
516    return 0;
517}
518
519size_t NuPlayer::Renderer::fillAudioBuffer(void *buffer, size_t size) {
520    Mutex::Autolock autoLock(mLock);
521
522    if (!offloadingAudio() || mPaused) {
523        return 0;
524    }
525
526    bool hasEOS = false;
527
528    size_t sizeCopied = 0;
529    bool firstEntry = true;
530    while (sizeCopied < size && !mAudioQueue.empty()) {
531        QueueEntry *entry = &*mAudioQueue.begin();
532
533        if (entry->mBuffer == NULL) { // EOS
534            hasEOS = true;
535            mAudioQueue.erase(mAudioQueue.begin());
536            entry = NULL;
537            break;
538        }
539
540        if (firstEntry && entry->mOffset == 0) {
541            firstEntry = false;
542            int64_t mediaTimeUs;
543            CHECK(entry->mBuffer->meta()->findInt64("timeUs", &mediaTimeUs));
544            ALOGV("rendering audio at media time %.2f secs", mediaTimeUs / 1E6);
545            setAudioFirstAnchorTimeIfNeeded(mediaTimeUs);
546        }
547
548        size_t copy = entry->mBuffer->size() - entry->mOffset;
549        size_t sizeRemaining = size - sizeCopied;
550        if (copy > sizeRemaining) {
551            copy = sizeRemaining;
552        }
553
554        memcpy((char *)buffer + sizeCopied,
555               entry->mBuffer->data() + entry->mOffset,
556               copy);
557
558        entry->mOffset += copy;
559        if (entry->mOffset == entry->mBuffer->size()) {
560            entry->mNotifyConsumed->post();
561            mAudioQueue.erase(mAudioQueue.begin());
562            entry = NULL;
563        }
564        sizeCopied += copy;
565        notifyIfMediaRenderingStarted();
566    }
567
568    if (mAudioFirstAnchorTimeMediaUs >= 0) {
569        int64_t nowUs = ALooper::GetNowUs();
570        setAnchorTime(mAudioFirstAnchorTimeMediaUs, nowUs - getPlayedOutAudioDurationUs(nowUs));
571    }
572
573    // we don't know how much data we are queueing for offloaded tracks
574    mAnchorMaxMediaUs = -1;
575
576    if (hasEOS) {
577        (new AMessage(kWhatStopAudioSink, id()))->post();
578    }
579
580    return sizeCopied;
581}
582
583bool NuPlayer::Renderer::onDrainAudioQueue() {
584    uint32_t numFramesPlayed;
585    if (mAudioSink->getPosition(&numFramesPlayed) != OK) {
586        return false;
587    }
588
589    ssize_t numFramesAvailableToWrite =
590        mAudioSink->frameCount() - (mNumFramesWritten - numFramesPlayed);
591
592#if 0
593    if (numFramesAvailableToWrite == mAudioSink->frameCount()) {
594        ALOGI("audio sink underrun");
595    } else {
596        ALOGV("audio queue has %d frames left to play",
597             mAudioSink->frameCount() - numFramesAvailableToWrite);
598    }
599#endif
600
601    size_t numBytesAvailableToWrite =
602        numFramesAvailableToWrite * mAudioSink->frameSize();
603
604    while (numBytesAvailableToWrite > 0 && !mAudioQueue.empty()) {
605        QueueEntry *entry = &*mAudioQueue.begin();
606
607        mLastAudioBufferDrained = entry->mBufferOrdinal;
608
609        if (entry->mBuffer == NULL) {
610            // EOS
611            int64_t postEOSDelayUs = 0;
612            if (mAudioSink->needsTrailingPadding()) {
613                postEOSDelayUs = getPendingAudioPlayoutDurationUs(ALooper::GetNowUs());
614            }
615            notifyEOS(true /* audio */, entry->mFinalResult, postEOSDelayUs);
616
617            mAudioQueue.erase(mAudioQueue.begin());
618            entry = NULL;
619            return false;
620        }
621
622        if (entry->mOffset == 0) {
623            int64_t mediaTimeUs;
624            CHECK(entry->mBuffer->meta()->findInt64("timeUs", &mediaTimeUs));
625            ALOGV("rendering audio at media time %.2f secs", mediaTimeUs / 1E6);
626            onNewAudioMediaTime(mediaTimeUs);
627        }
628
629        size_t copy = entry->mBuffer->size() - entry->mOffset;
630        if (copy > numBytesAvailableToWrite) {
631            copy = numBytesAvailableToWrite;
632        }
633
634        ssize_t written = mAudioSink->write(entry->mBuffer->data() + entry->mOffset, copy);
635        if (written < 0) {
636            // An error in AudioSink write is fatal here.
637            LOG_ALWAYS_FATAL("AudioSink write error(%zd) when writing %zu bytes", written, copy);
638        }
639
640        entry->mOffset += written;
641        if (entry->mOffset == entry->mBuffer->size()) {
642            entry->mNotifyConsumed->post();
643            mAudioQueue.erase(mAudioQueue.begin());
644
645            entry = NULL;
646        }
647
648        numBytesAvailableToWrite -= written;
649        size_t copiedFrames = written / mAudioSink->frameSize();
650        mNumFramesWritten += copiedFrames;
651
652        notifyIfMediaRenderingStarted();
653
654        if (written != (ssize_t)copy) {
655            // A short count was received from AudioSink::write()
656            //
657            // AudioSink write should block until exactly the number of bytes are delivered.
658            // But it may return with a short count (without an error) when:
659            //
660            // 1) Size to be copied is not a multiple of the frame size. We consider this fatal.
661            // 2) AudioSink is an AudioCache for data retrieval, and the AudioCache is exceeded.
662
663            // (Case 1)
664            // Must be a multiple of the frame size.  If it is not a multiple of a frame size, it
665            // needs to fail, as we should not carry over fractional frames between calls.
666            CHECK_EQ(copy % mAudioSink->frameSize(), 0);
667
668            // (Case 2)
669            // Return early to the caller.
670            // Beware of calling immediately again as this may busy-loop if you are not careful.
671            ALOGW("AudioSink write short frame count %zd < %zu", written, copy);
672            break;
673        }
674    }
675    mAnchorMaxMediaUs =
676        mAnchorTimeMediaUs +
677                (int64_t)(max((long long)mNumFramesWritten - mAnchorNumFramesWritten, 0LL)
678                        * 1000LL * mAudioSink->msecsPerFrame());
679
680    return !mAudioQueue.empty();
681}
682
683int64_t NuPlayer::Renderer::getPendingAudioPlayoutDurationUs(int64_t nowUs) {
684    int64_t writtenAudioDurationUs =
685        mNumFramesWritten * 1000LL * mAudioSink->msecsPerFrame();
686    return writtenAudioDurationUs - getPlayedOutAudioDurationUs(nowUs);
687}
688
689int64_t NuPlayer::Renderer::getRealTimeUs(int64_t mediaTimeUs, int64_t nowUs) {
690    int64_t currentPositionUs;
691    if (getCurrentPosition(&currentPositionUs, nowUs, true /* allowPastQueuedVideo */) != OK) {
692        // If failed to get current position, e.g. due to audio clock is not ready, then just
693        // play out video immediately without delay.
694        return nowUs;
695    }
696    return (mediaTimeUs - currentPositionUs) + nowUs;
697}
698
699void NuPlayer::Renderer::onNewAudioMediaTime(int64_t mediaTimeUs) {
700    // TRICKY: vorbis decoder generates multiple frames with the same
701    // timestamp, so only update on the first frame with a given timestamp
702    if (mediaTimeUs == mAnchorTimeMediaUs) {
703        return;
704    }
705    setAudioFirstAnchorTimeIfNeeded(mediaTimeUs);
706    int64_t nowUs = ALooper::GetNowUs();
707    setAnchorTime(
708            mediaTimeUs, nowUs + getPendingAudioPlayoutDurationUs(nowUs), mNumFramesWritten);
709}
710
711void NuPlayer::Renderer::postDrainVideoQueue() {
712    if (mDrainVideoQueuePending
713            || mSyncQueues
714            || (mPaused && mVideoSampleReceived)) {
715        return;
716    }
717
718    if (mVideoQueue.empty()) {
719        return;
720    }
721
722    QueueEntry &entry = *mVideoQueue.begin();
723
724    sp<AMessage> msg = new AMessage(kWhatDrainVideoQueue, id());
725    msg->setInt32("generation", mVideoQueueGeneration);
726
727    if (entry.mBuffer == NULL) {
728        // EOS doesn't carry a timestamp.
729        msg->post();
730        mDrainVideoQueuePending = true;
731        return;
732    }
733
734    int64_t delayUs;
735    int64_t nowUs = ALooper::GetNowUs();
736    int64_t realTimeUs;
737    if (mFlags & FLAG_REAL_TIME) {
738        int64_t mediaTimeUs;
739        CHECK(entry.mBuffer->meta()->findInt64("timeUs", &mediaTimeUs));
740        realTimeUs = mediaTimeUs;
741    } else {
742        int64_t mediaTimeUs;
743        CHECK(entry.mBuffer->meta()->findInt64("timeUs", &mediaTimeUs));
744
745        if (mAnchorTimeMediaUs < 0) {
746            setAnchorTime(mediaTimeUs, nowUs);
747            realTimeUs = nowUs;
748        } else {
749            realTimeUs = getRealTimeUs(mediaTimeUs, nowUs);
750        }
751        if (!mHasAudio) {
752            mAnchorMaxMediaUs = mediaTimeUs + 100000; // smooth out videos >= 10fps
753        }
754
755        // Heuristics to handle situation when media time changed without a
756        // discontinuity. If we have not drained an audio buffer that was
757        // received after this buffer, repost in 10 msec. Otherwise repost
758        // in 500 msec.
759        delayUs = realTimeUs - nowUs;
760        if (delayUs > 500000) {
761            int64_t postDelayUs = 500000;
762            if (mHasAudio && (mLastAudioBufferDrained - entry.mBufferOrdinal) <= 0) {
763                postDelayUs = 10000;
764            }
765            msg->setWhat(kWhatPostDrainVideoQueue);
766            msg->post(postDelayUs);
767            mVideoScheduler->restart();
768            ALOGI("possible video time jump of %dms, retrying in %dms",
769                    (int)(delayUs / 1000), (int)(postDelayUs / 1000));
770            mDrainVideoQueuePending = true;
771            return;
772        }
773    }
774
775    realTimeUs = mVideoScheduler->schedule(realTimeUs * 1000) / 1000;
776    int64_t twoVsyncsUs = 2 * (mVideoScheduler->getVsyncPeriod() / 1000);
777
778    delayUs = realTimeUs - nowUs;
779
780    ALOGW_IF(delayUs > 500000, "unusually high delayUs: %" PRId64, delayUs);
781    // post 2 display refreshes before rendering is due
782    msg->post(delayUs > twoVsyncsUs ? delayUs - twoVsyncsUs : 0);
783
784    mDrainVideoQueuePending = true;
785}
786
787void NuPlayer::Renderer::onDrainVideoQueue() {
788    if (mVideoQueue.empty()) {
789        return;
790    }
791
792    QueueEntry *entry = &*mVideoQueue.begin();
793
794    if (entry->mBuffer == NULL) {
795        // EOS
796
797        notifyEOS(false /* audio */, entry->mFinalResult);
798
799        mVideoQueue.erase(mVideoQueue.begin());
800        entry = NULL;
801
802        setVideoLateByUs(0);
803        return;
804    }
805
806    int64_t nowUs = -1;
807    int64_t realTimeUs;
808    if (mFlags & FLAG_REAL_TIME) {
809        CHECK(entry->mBuffer->meta()->findInt64("timeUs", &realTimeUs));
810    } else {
811        int64_t mediaTimeUs;
812        CHECK(entry->mBuffer->meta()->findInt64("timeUs", &mediaTimeUs));
813
814        nowUs = ALooper::GetNowUs();
815        realTimeUs = getRealTimeUs(mediaTimeUs, nowUs);
816    }
817
818    bool tooLate = false;
819
820    if (!mPaused) {
821        if (nowUs == -1) {
822            nowUs = ALooper::GetNowUs();
823        }
824        setVideoLateByUs(nowUs - realTimeUs);
825        tooLate = (mVideoLateByUs > 40000);
826
827        if (tooLate) {
828            ALOGV("video late by %lld us (%.2f secs)",
829                 mVideoLateByUs, mVideoLateByUs / 1E6);
830        } else {
831            ALOGV("rendering video at media time %.2f secs",
832                    (mFlags & FLAG_REAL_TIME ? realTimeUs :
833                    (realTimeUs + mAnchorTimeMediaUs - mAnchorTimeRealUs)) / 1E6);
834        }
835    } else {
836        setVideoLateByUs(0);
837        if (!mVideoSampleReceived && !mHasAudio) {
838            // This will ensure that the first frame after a flush won't be used as anchor
839            // when renderer is in paused state, because resume can happen any time after seek.
840            setAnchorTime(-1, -1);
841        }
842    }
843
844    entry->mNotifyConsumed->setInt64("timestampNs", realTimeUs * 1000ll);
845    entry->mNotifyConsumed->setInt32("render", !tooLate);
846    entry->mNotifyConsumed->post();
847    mVideoQueue.erase(mVideoQueue.begin());
848    entry = NULL;
849
850    mVideoSampleReceived = true;
851
852    if (!mPaused) {
853        if (!mVideoRenderingStarted) {
854            mVideoRenderingStarted = true;
855            notifyVideoRenderingStart();
856        }
857        notifyIfMediaRenderingStarted();
858    }
859}
860
861void NuPlayer::Renderer::notifyVideoRenderingStart() {
862    sp<AMessage> notify = mNotify->dup();
863    notify->setInt32("what", kWhatVideoRenderingStart);
864    notify->post();
865}
866
867void NuPlayer::Renderer::notifyEOS(bool audio, status_t finalResult, int64_t delayUs) {
868    sp<AMessage> notify = mNotify->dup();
869    notify->setInt32("what", kWhatEOS);
870    notify->setInt32("audio", static_cast<int32_t>(audio));
871    notify->setInt32("finalResult", finalResult);
872    notify->post(delayUs);
873}
874
875void NuPlayer::Renderer::notifyAudioOffloadTearDown() {
876    (new AMessage(kWhatAudioOffloadTearDown, id()))->post();
877}
878
879void NuPlayer::Renderer::onQueueBuffer(const sp<AMessage> &msg) {
880    int32_t audio;
881    CHECK(msg->findInt32("audio", &audio));
882
883    setHasMedia(audio);
884
885    if (mHasVideo) {
886        if (mVideoScheduler == NULL) {
887            mVideoScheduler = new VideoFrameScheduler();
888            mVideoScheduler->init();
889        }
890    }
891
892    if (dropBufferWhileFlushing(audio, msg)) {
893        return;
894    }
895
896    sp<ABuffer> buffer;
897    CHECK(msg->findBuffer("buffer", &buffer));
898
899    sp<AMessage> notifyConsumed;
900    CHECK(msg->findMessage("notifyConsumed", &notifyConsumed));
901
902    QueueEntry entry;
903    entry.mBuffer = buffer;
904    entry.mNotifyConsumed = notifyConsumed;
905    entry.mOffset = 0;
906    entry.mFinalResult = OK;
907    entry.mBufferOrdinal = ++mTotalBuffersQueued;
908
909    if (audio) {
910        Mutex::Autolock autoLock(mLock);
911        mAudioQueue.push_back(entry);
912        postDrainAudioQueue_l();
913    } else {
914        mVideoQueue.push_back(entry);
915        postDrainVideoQueue();
916    }
917
918    Mutex::Autolock autoLock(mLock);
919    if (!mSyncQueues || mAudioQueue.empty() || mVideoQueue.empty()) {
920        return;
921    }
922
923    sp<ABuffer> firstAudioBuffer = (*mAudioQueue.begin()).mBuffer;
924    sp<ABuffer> firstVideoBuffer = (*mVideoQueue.begin()).mBuffer;
925
926    if (firstAudioBuffer == NULL || firstVideoBuffer == NULL) {
927        // EOS signalled on either queue.
928        syncQueuesDone_l();
929        return;
930    }
931
932    int64_t firstAudioTimeUs;
933    int64_t firstVideoTimeUs;
934    CHECK(firstAudioBuffer->meta()
935            ->findInt64("timeUs", &firstAudioTimeUs));
936    CHECK(firstVideoBuffer->meta()
937            ->findInt64("timeUs", &firstVideoTimeUs));
938
939    int64_t diff = firstVideoTimeUs - firstAudioTimeUs;
940
941    ALOGV("queueDiff = %.2f secs", diff / 1E6);
942
943    if (diff > 100000ll) {
944        // Audio data starts More than 0.1 secs before video.
945        // Drop some audio.
946
947        (*mAudioQueue.begin()).mNotifyConsumed->post();
948        mAudioQueue.erase(mAudioQueue.begin());
949        return;
950    }
951
952    syncQueuesDone_l();
953}
954
955void NuPlayer::Renderer::syncQueuesDone_l() {
956    if (!mSyncQueues) {
957        return;
958    }
959
960    mSyncQueues = false;
961
962    if (!mAudioQueue.empty()) {
963        postDrainAudioQueue_l();
964    }
965
966    if (!mVideoQueue.empty()) {
967        postDrainVideoQueue();
968    }
969}
970
971void NuPlayer::Renderer::onQueueEOS(const sp<AMessage> &msg) {
972    int32_t audio;
973    CHECK(msg->findInt32("audio", &audio));
974
975    if (dropBufferWhileFlushing(audio, msg)) {
976        return;
977    }
978
979    int32_t finalResult;
980    CHECK(msg->findInt32("finalResult", &finalResult));
981
982    QueueEntry entry;
983    entry.mOffset = 0;
984    entry.mFinalResult = finalResult;
985
986    if (audio) {
987        Mutex::Autolock autoLock(mLock);
988        if (mAudioQueue.empty() && mSyncQueues) {
989            syncQueuesDone_l();
990        }
991        mAudioQueue.push_back(entry);
992        postDrainAudioQueue_l();
993    } else {
994        if (mVideoQueue.empty() && mSyncQueues) {
995            Mutex::Autolock autoLock(mLock);
996            syncQueuesDone_l();
997        }
998        mVideoQueue.push_back(entry);
999        postDrainVideoQueue();
1000    }
1001}
1002
1003void NuPlayer::Renderer::onFlush(const sp<AMessage> &msg) {
1004    int32_t audio;
1005    CHECK(msg->findInt32("audio", &audio));
1006
1007    {
1008        Mutex::Autolock autoLock(mFlushLock);
1009        if (audio) {
1010            mFlushingAudio = false;
1011        } else {
1012            mFlushingVideo = false;
1013        }
1014    }
1015
1016    // If we're currently syncing the queues, i.e. dropping audio while
1017    // aligning the first audio/video buffer times and only one of the
1018    // two queues has data, we may starve that queue by not requesting
1019    // more buffers from the decoder. If the other source then encounters
1020    // a discontinuity that leads to flushing, we'll never find the
1021    // corresponding discontinuity on the other queue.
1022    // Therefore we'll stop syncing the queues if at least one of them
1023    // is flushed.
1024    {
1025         Mutex::Autolock autoLock(mLock);
1026         syncQueuesDone_l();
1027         setPauseStartedTimeRealUs(-1);
1028    }
1029
1030    ALOGV("flushing %s", audio ? "audio" : "video");
1031    if (audio) {
1032        {
1033            Mutex::Autolock autoLock(mLock);
1034            flushQueue(&mAudioQueue);
1035
1036            ++mAudioQueueGeneration;
1037            prepareForMediaRenderingStart();
1038
1039            if (offloadingAudio()) {
1040                setAudioFirstAnchorTime(-1);
1041            }
1042        }
1043
1044        mDrainAudioQueuePending = false;
1045
1046        if (offloadingAudio()) {
1047            mAudioSink->pause();
1048            mAudioSink->flush();
1049            mAudioSink->start();
1050        }
1051    } else {
1052        flushQueue(&mVideoQueue);
1053
1054        mDrainVideoQueuePending = false;
1055        ++mVideoQueueGeneration;
1056
1057        if (mVideoScheduler != NULL) {
1058            mVideoScheduler->restart();
1059        }
1060
1061        prepareForMediaRenderingStart();
1062    }
1063
1064    mVideoSampleReceived = false;
1065    notifyFlushComplete(audio);
1066}
1067
1068void NuPlayer::Renderer::flushQueue(List<QueueEntry> *queue) {
1069    while (!queue->empty()) {
1070        QueueEntry *entry = &*queue->begin();
1071
1072        if (entry->mBuffer != NULL) {
1073            entry->mNotifyConsumed->post();
1074        }
1075
1076        queue->erase(queue->begin());
1077        entry = NULL;
1078    }
1079}
1080
1081void NuPlayer::Renderer::notifyFlushComplete(bool audio) {
1082    sp<AMessage> notify = mNotify->dup();
1083    notify->setInt32("what", kWhatFlushComplete);
1084    notify->setInt32("audio", static_cast<int32_t>(audio));
1085    notify->post();
1086}
1087
1088bool NuPlayer::Renderer::dropBufferWhileFlushing(
1089        bool audio, const sp<AMessage> &msg) {
1090    bool flushing = false;
1091
1092    {
1093        Mutex::Autolock autoLock(mFlushLock);
1094        if (audio) {
1095            flushing = mFlushingAudio;
1096        } else {
1097            flushing = mFlushingVideo;
1098        }
1099    }
1100
1101    if (!flushing) {
1102        return false;
1103    }
1104
1105    sp<AMessage> notifyConsumed;
1106    if (msg->findMessage("notifyConsumed", &notifyConsumed)) {
1107        notifyConsumed->post();
1108    }
1109
1110    return true;
1111}
1112
1113void NuPlayer::Renderer::onAudioSinkChanged() {
1114    if (offloadingAudio()) {
1115        return;
1116    }
1117    CHECK(!mDrainAudioQueuePending);
1118    mNumFramesWritten = 0;
1119    mAnchorNumFramesWritten = -1;
1120    uint32_t written;
1121    if (mAudioSink->getFramesWritten(&written) == OK) {
1122        mNumFramesWritten = written;
1123    }
1124}
1125
1126void NuPlayer::Renderer::onDisableOffloadAudio() {
1127    Mutex::Autolock autoLock(mLock);
1128    mFlags &= ~FLAG_OFFLOAD_AUDIO;
1129    ++mAudioQueueGeneration;
1130}
1131
1132void NuPlayer::Renderer::onPause() {
1133    if (mPaused) {
1134        ALOGW("Renderer::onPause() called while already paused!");
1135        return;
1136    }
1137    {
1138        Mutex::Autolock autoLock(mLock);
1139        ++mAudioQueueGeneration;
1140        ++mVideoQueueGeneration;
1141        prepareForMediaRenderingStart();
1142        mPaused = true;
1143        setPauseStartedTimeRealUs(ALooper::GetNowUs());
1144    }
1145
1146    mDrainAudioQueuePending = false;
1147    mDrainVideoQueuePending = false;
1148
1149    if (mHasAudio) {
1150        mAudioSink->pause();
1151        startAudioOffloadPauseTimeout();
1152    }
1153
1154    ALOGV("now paused audio queue has %d entries, video has %d entries",
1155          mAudioQueue.size(), mVideoQueue.size());
1156}
1157
1158void NuPlayer::Renderer::onResume() {
1159    if (!mPaused) {
1160        return;
1161    }
1162
1163    if (mHasAudio) {
1164        cancelAudioOffloadPauseTimeout();
1165        mAudioSink->start();
1166    }
1167
1168    Mutex::Autolock autoLock(mLock);
1169    mPaused = false;
1170    if (mPauseStartedTimeRealUs != -1) {
1171        int64_t newAnchorRealUs =
1172            mAnchorTimeRealUs + ALooper::GetNowUs() - mPauseStartedTimeRealUs;
1173        setAnchorTime(
1174                mAnchorTimeMediaUs, newAnchorRealUs, mAnchorNumFramesWritten, true /* resume */);
1175    }
1176
1177    if (!mAudioQueue.empty()) {
1178        postDrainAudioQueue_l();
1179    }
1180
1181    if (!mVideoQueue.empty()) {
1182        postDrainVideoQueue();
1183    }
1184}
1185
1186void NuPlayer::Renderer::onSetVideoFrameRate(float fps) {
1187    if (mVideoScheduler == NULL) {
1188        mVideoScheduler = new VideoFrameScheduler();
1189    }
1190    mVideoScheduler->init(fps);
1191}
1192
1193// TODO: Remove unnecessary calls to getPlayedOutAudioDurationUs()
1194// as it acquires locks and may query the audio driver.
1195//
1196// Some calls could conceivably retrieve extrapolated data instead of
1197// accessing getTimestamp() or getPosition() every time a data buffer with
1198// a media time is received.
1199//
1200int64_t NuPlayer::Renderer::getPlayedOutAudioDurationUs(int64_t nowUs) {
1201    uint32_t numFramesPlayed;
1202    int64_t numFramesPlayedAt;
1203    AudioTimestamp ts;
1204    static const int64_t kStaleTimestamp100ms = 100000;
1205
1206    status_t res = mAudioSink->getTimestamp(ts);
1207    if (res == OK) {                 // case 1: mixing audio tracks and offloaded tracks.
1208        numFramesPlayed = ts.mPosition;
1209        numFramesPlayedAt =
1210            ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1211        const int64_t timestampAge = nowUs - numFramesPlayedAt;
1212        if (timestampAge > kStaleTimestamp100ms) {
1213            // This is an audio FIXME.
1214            // getTimestamp returns a timestamp which may come from audio mixing threads.
1215            // After pausing, the MixerThread may go idle, thus the mTime estimate may
1216            // become stale. Assuming that the MixerThread runs 20ms, with FastMixer at 5ms,
1217            // the max latency should be about 25ms with an average around 12ms (to be verified).
1218            // For safety we use 100ms.
1219            ALOGV("getTimestamp: returned stale timestamp nowUs(%lld) numFramesPlayedAt(%lld)",
1220                    (long long)nowUs, (long long)numFramesPlayedAt);
1221            numFramesPlayedAt = nowUs - kStaleTimestamp100ms;
1222        }
1223        //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1224    } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1225        numFramesPlayed = 0;
1226        numFramesPlayedAt = nowUs;
1227        //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
1228        //        numFramesPlayed, (long long)numFramesPlayedAt);
1229    } else {                         // case 3: transitory at new track or audio fast tracks.
1230        res = mAudioSink->getPosition(&numFramesPlayed);
1231        CHECK_EQ(res, (status_t)OK);
1232        numFramesPlayedAt = nowUs;
1233        numFramesPlayedAt += 1000LL * mAudioSink->latency() / 2; /* XXX */
1234        //ALOGD("getPosition: %d %lld", numFramesPlayed, numFramesPlayedAt);
1235    }
1236
1237    // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1238    //CHECK_EQ(numFramesPlayed & (1 << 31), 0);  // can't be negative until 12.4 hrs, test
1239    int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000LL * mAudioSink->msecsPerFrame())
1240            + nowUs - numFramesPlayedAt;
1241    if (durationUs < 0) {
1242        // Occurs when numFramesPlayed position is very small and the following:
1243        // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
1244        //     numFramesPlayedAt is greater than nowUs by time more than numFramesPlayed.
1245        // (2) In case 3, using getPosition and adding mAudioSink->latency() to
1246        //     numFramesPlayedAt, by a time amount greater than numFramesPlayed.
1247        //
1248        // Both of these are transitory conditions.
1249        ALOGV("getPlayedOutAudioDurationUs: negative duration %lld set to zero", (long long)durationUs);
1250        durationUs = 0;
1251    }
1252    ALOGV("getPlayedOutAudioDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
1253            (long long)durationUs, (long long)nowUs, numFramesPlayed, (long long)numFramesPlayedAt);
1254    return durationUs;
1255}
1256
1257void NuPlayer::Renderer::onAudioOffloadTearDown(AudioOffloadTearDownReason reason) {
1258    if (mAudioOffloadTornDown) {
1259        return;
1260    }
1261    mAudioOffloadTornDown = true;
1262
1263    int64_t currentPositionUs;
1264    if (getCurrentPosition(&currentPositionUs) != OK) {
1265        currentPositionUs = 0;
1266    }
1267
1268    mAudioSink->stop();
1269    mAudioSink->flush();
1270
1271    sp<AMessage> notify = mNotify->dup();
1272    notify->setInt32("what", kWhatAudioOffloadTearDown);
1273    notify->setInt64("positionUs", currentPositionUs);
1274    notify->setInt32("reason", reason);
1275    notify->post();
1276}
1277
1278void NuPlayer::Renderer::startAudioOffloadPauseTimeout() {
1279    if (offloadingAudio()) {
1280        sp<AMessage> msg = new AMessage(kWhatAudioOffloadPauseTimeout, id());
1281        msg->setInt32("generation", mAudioOffloadPauseTimeoutGeneration);
1282        msg->post(kOffloadPauseMaxUs);
1283    }
1284}
1285
1286void NuPlayer::Renderer::cancelAudioOffloadPauseTimeout() {
1287    if (offloadingAudio()) {
1288        ++mAudioOffloadPauseTimeoutGeneration;
1289    }
1290}
1291
1292bool NuPlayer::Renderer::onOpenAudioSink(
1293        const sp<AMessage> &format,
1294        bool offloadOnly,
1295        bool hasVideo,
1296        uint32_t flags) {
1297    ALOGV("openAudioSink: offloadOnly(%d) offloadingAudio(%d)",
1298            offloadOnly, offloadingAudio());
1299    bool audioSinkChanged = false;
1300
1301    int32_t numChannels;
1302    CHECK(format->findInt32("channel-count", &numChannels));
1303
1304    int32_t channelMask;
1305    if (!format->findInt32("channel-mask", &channelMask)) {
1306        // signal to the AudioSink to derive the mask from count.
1307        channelMask = CHANNEL_MASK_USE_CHANNEL_ORDER;
1308    }
1309
1310    int32_t sampleRate;
1311    CHECK(format->findInt32("sample-rate", &sampleRate));
1312
1313    if (offloadingAudio()) {
1314        audio_format_t audioFormat = AUDIO_FORMAT_PCM_16_BIT;
1315        AString mime;
1316        CHECK(format->findString("mime", &mime));
1317        status_t err = mapMimeToAudioFormat(audioFormat, mime.c_str());
1318
1319        if (err != OK) {
1320            ALOGE("Couldn't map mime \"%s\" to a valid "
1321                    "audio_format", mime.c_str());
1322            onDisableOffloadAudio();
1323        } else {
1324            ALOGV("Mime \"%s\" mapped to audio_format 0x%x",
1325                    mime.c_str(), audioFormat);
1326
1327            int avgBitRate = -1;
1328            format->findInt32("bit-rate", &avgBitRate);
1329
1330            int32_t aacProfile = -1;
1331            if (audioFormat == AUDIO_FORMAT_AAC
1332                    && format->findInt32("aac-profile", &aacProfile)) {
1333                // Redefine AAC format as per aac profile
1334                mapAACProfileToAudioFormat(
1335                        audioFormat,
1336                        aacProfile);
1337            }
1338
1339            audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
1340            offloadInfo.duration_us = -1;
1341            format->findInt64(
1342                    "durationUs", &offloadInfo.duration_us);
1343            offloadInfo.sample_rate = sampleRate;
1344            offloadInfo.channel_mask = channelMask;
1345            offloadInfo.format = audioFormat;
1346            offloadInfo.stream_type = AUDIO_STREAM_MUSIC;
1347            offloadInfo.bit_rate = avgBitRate;
1348            offloadInfo.has_video = hasVideo;
1349            offloadInfo.is_streaming = true;
1350
1351            if (memcmp(&mCurrentOffloadInfo, &offloadInfo, sizeof(offloadInfo)) == 0) {
1352                ALOGV("openAudioSink: no change in offload mode");
1353                // no change from previous configuration, everything ok.
1354                return offloadingAudio();
1355            }
1356            ALOGV("openAudioSink: try to open AudioSink in offload mode");
1357            uint32_t offloadFlags = flags;
1358            offloadFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
1359            offloadFlags &= ~AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1360            audioSinkChanged = true;
1361            mAudioSink->close();
1362            err = mAudioSink->open(
1363                    sampleRate,
1364                    numChannels,
1365                    (audio_channel_mask_t)channelMask,
1366                    audioFormat,
1367                    8 /* bufferCount */,
1368                    &NuPlayer::Renderer::AudioSinkCallback,
1369                    this,
1370                    (audio_output_flags_t)offloadFlags,
1371                    &offloadInfo);
1372
1373            if (err == OK) {
1374                // If the playback is offloaded to h/w, we pass
1375                // the HAL some metadata information.
1376                // We don't want to do this for PCM because it
1377                // will be going through the AudioFlinger mixer
1378                // before reaching the hardware.
1379                // TODO
1380                mCurrentOffloadInfo = offloadInfo;
1381                err = mAudioSink->start();
1382                ALOGV_IF(err == OK, "openAudioSink: offload succeeded");
1383            }
1384            if (err != OK) {
1385                // Clean up, fall back to non offload mode.
1386                mAudioSink->close();
1387                onDisableOffloadAudio();
1388                mCurrentOffloadInfo = AUDIO_INFO_INITIALIZER;
1389                ALOGV("openAudioSink: offload failed");
1390            }
1391        }
1392    }
1393    if (!offloadOnly && !offloadingAudio()) {
1394        ALOGV("openAudioSink: open AudioSink in NON-offload mode");
1395        uint32_t pcmFlags = flags;
1396        pcmFlags &= ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
1397        audioSinkChanged = true;
1398        mAudioSink->close();
1399        mCurrentOffloadInfo = AUDIO_INFO_INITIALIZER;
1400        CHECK_EQ(mAudioSink->open(
1401                    sampleRate,
1402                    numChannels,
1403                    (audio_channel_mask_t)channelMask,
1404                    AUDIO_FORMAT_PCM_16_BIT,
1405                    8 /* bufferCount */,
1406                    NULL,
1407                    NULL,
1408                    (audio_output_flags_t)pcmFlags),
1409                 (status_t)OK);
1410        mAudioSink->start();
1411    }
1412    if (audioSinkChanged) {
1413        onAudioSinkChanged();
1414    }
1415
1416    return offloadingAudio();
1417}
1418
1419void NuPlayer::Renderer::onCloseAudioSink() {
1420    mAudioSink->close();
1421    mCurrentOffloadInfo = AUDIO_INFO_INITIALIZER;
1422}
1423
1424}  // namespace android
1425
1426