NuPlayerRenderer.cpp revision d005c5ddb4842369979df7b76f1d0f5f1380fcd9
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#include <cutils/properties.h>
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/foundation/AWakeLock.h>
28#include <media/stagefright/MediaClock.h>
29#include <media/stagefright/MediaErrors.h>
30#include <media/stagefright/MetaData.h>
31#include <media/stagefright/Utils.h>
32#include <media/stagefright/VideoFrameScheduler.h>
33
34#include <inttypes.h>
35
36namespace android {
37
38/*
39 * Example of common configuration settings in shell script form
40
41   #Turn offload audio off (use PCM for Play Music) -- AudioPolicyManager
42   adb shell setprop audio.offload.disable 1
43
44   #Allow offload audio with video (requires offloading to be enabled) -- AudioPolicyManager
45   adb shell setprop audio.offload.video 1
46
47   #Use audio callbacks for PCM data
48   adb shell setprop media.stagefright.audio.cbk 1
49
50   #Use deep buffer for PCM data with video (it is generally enabled for audio-only)
51   adb shell setprop media.stagefright.audio.deep 1
52
53   #Set size of buffers for pcm audio sink in msec (example: 1000 msec)
54   adb shell setprop media.stagefright.audio.sink 1000
55
56 * These configurations take effect for the next track played (not the current track).
57 */
58
59static inline bool getUseAudioCallbackSetting() {
60    return property_get_bool("media.stagefright.audio.cbk", false /* default_value */);
61}
62
63static inline int32_t getAudioSinkPcmMsSetting() {
64    return property_get_int32(
65            "media.stagefright.audio.sink", 500 /* default_value */);
66}
67
68// Maximum time in paused state when offloading audio decompression. When elapsed, the AudioSink
69// is closed to allow the audio DSP to power down.
70static const int64_t kOffloadPauseMaxUs = 10000000ll;
71
72// static
73const NuPlayer::Renderer::PcmInfo NuPlayer::Renderer::AUDIO_PCMINFO_INITIALIZER = {
74        AUDIO_CHANNEL_NONE,
75        AUDIO_OUTPUT_FLAG_NONE,
76        AUDIO_FORMAT_INVALID,
77        0, // mNumChannels
78        0 // mSampleRate
79};
80
81// static
82const int64_t NuPlayer::Renderer::kMinPositionUpdateDelayUs = 100000ll;
83
84NuPlayer::Renderer::Renderer(
85        const sp<MediaPlayerBase::AudioSink> &sink,
86        const sp<AMessage> &notify,
87        uint32_t flags)
88    : mAudioSink(sink),
89      mNotify(notify),
90      mFlags(flags),
91      mNumFramesWritten(0),
92      mDrainAudioQueuePending(false),
93      mDrainVideoQueuePending(false),
94      mAudioQueueGeneration(0),
95      mVideoQueueGeneration(0),
96      mAudioDrainGeneration(0),
97      mVideoDrainGeneration(0),
98      mPlaybackSettings(AUDIO_PLAYBACK_RATE_DEFAULT),
99      mAudioFirstAnchorTimeMediaUs(-1),
100      mAnchorTimeMediaUs(-1),
101      mAnchorNumFramesWritten(-1),
102      mVideoLateByUs(0ll),
103      mHasAudio(false),
104      mHasVideo(false),
105      mNotifyCompleteAudio(false),
106      mNotifyCompleteVideo(false),
107      mSyncQueues(false),
108      mPaused(false),
109      mPauseDrainAudioAllowedUs(0),
110      mVideoSampleReceived(false),
111      mVideoRenderingStarted(false),
112      mVideoRenderingStartGeneration(0),
113      mAudioRenderingStartGeneration(0),
114      mAudioOffloadPauseTimeoutGeneration(0),
115      mAudioTornDown(false),
116      mCurrentOffloadInfo(AUDIO_INFO_INITIALIZER),
117      mCurrentPcmInfo(AUDIO_PCMINFO_INITIALIZER),
118      mTotalBuffersQueued(0),
119      mLastAudioBufferDrained(0),
120      mUseAudioCallback(false),
121      mWakeLock(new AWakeLock()) {
122    mMediaClock = new MediaClock;
123    mPlaybackRate = mPlaybackSettings.mSpeed;
124    mMediaClock->setPlaybackRate(mPlaybackRate);
125}
126
127NuPlayer::Renderer::~Renderer() {
128    if (offloadingAudio()) {
129        mAudioSink->stop();
130        mAudioSink->flush();
131        mAudioSink->close();
132    }
133}
134
135void NuPlayer::Renderer::queueBuffer(
136        bool audio,
137        const sp<ABuffer> &buffer,
138        const sp<AMessage> &notifyConsumed) {
139    sp<AMessage> msg = new AMessage(kWhatQueueBuffer, this);
140    msg->setInt32("queueGeneration", getQueueGeneration(audio));
141    msg->setInt32("audio", static_cast<int32_t>(audio));
142    msg->setBuffer("buffer", buffer);
143    msg->setMessage("notifyConsumed", notifyConsumed);
144    msg->post();
145}
146
147void NuPlayer::Renderer::queueEOS(bool audio, status_t finalResult) {
148    CHECK_NE(finalResult, (status_t)OK);
149
150    sp<AMessage> msg = new AMessage(kWhatQueueEOS, this);
151    msg->setInt32("queueGeneration", getQueueGeneration(audio));
152    msg->setInt32("audio", static_cast<int32_t>(audio));
153    msg->setInt32("finalResult", finalResult);
154    msg->post();
155}
156
157status_t NuPlayer::Renderer::setPlaybackSettings(const AudioPlaybackRate &rate) {
158    sp<AMessage> msg = new AMessage(kWhatConfigPlayback, this);
159    writeToAMessage(msg, rate);
160    sp<AMessage> response;
161    status_t err = msg->postAndAwaitResponse(&response);
162    if (err == OK && response != NULL) {
163        CHECK(response->findInt32("err", &err));
164    }
165    return err;
166}
167
168status_t NuPlayer::Renderer::onConfigPlayback(const AudioPlaybackRate &rate /* sanitized */) {
169    if (rate.mSpeed == 0.f) {
170        onPause();
171        // don't call audiosink's setPlaybackRate if pausing, as pitch does not
172        // have to correspond to the any non-0 speed (e.g old speed). Keep
173        // settings nonetheless, using the old speed, in case audiosink changes.
174        AudioPlaybackRate newRate = rate;
175        newRate.mSpeed = mPlaybackSettings.mSpeed;
176        mPlaybackSettings = newRate;
177        return OK;
178    }
179
180    if (mAudioSink != NULL && mAudioSink->ready()) {
181        status_t err = mAudioSink->setPlaybackRate(rate);
182        if (err != OK) {
183            return err;
184        }
185    }
186    mPlaybackSettings = rate;
187    mPlaybackRate = rate.mSpeed;
188    mMediaClock->setPlaybackRate(mPlaybackRate);
189    return OK;
190}
191
192status_t NuPlayer::Renderer::getPlaybackSettings(AudioPlaybackRate *rate /* nonnull */) {
193    sp<AMessage> msg = new AMessage(kWhatGetPlaybackSettings, this);
194    sp<AMessage> response;
195    status_t err = msg->postAndAwaitResponse(&response);
196    if (err == OK && response != NULL) {
197        CHECK(response->findInt32("err", &err));
198        if (err == OK) {
199            readFromAMessage(response, rate);
200        }
201    }
202    return err;
203}
204
205status_t NuPlayer::Renderer::onGetPlaybackSettings(AudioPlaybackRate *rate /* nonnull */) {
206    if (mAudioSink != NULL && mAudioSink->ready()) {
207        status_t err = mAudioSink->getPlaybackRate(rate);
208        if (err == OK) {
209            if (!isAudioPlaybackRateEqual(*rate, mPlaybackSettings)) {
210                ALOGW("correcting mismatch in internal/external playback rate");
211            }
212            // get playback settings used by audiosink, as it may be
213            // slightly off due to audiosink not taking small changes.
214            mPlaybackSettings = *rate;
215            if (mPaused) {
216                rate->mSpeed = 0.f;
217            }
218        }
219        return err;
220    }
221    *rate = mPlaybackSettings;
222    return OK;
223}
224
225status_t NuPlayer::Renderer::setSyncSettings(const AVSyncSettings &sync, float videoFpsHint) {
226    sp<AMessage> msg = new AMessage(kWhatConfigSync, this);
227    writeToAMessage(msg, sync, videoFpsHint);
228    sp<AMessage> response;
229    status_t err = msg->postAndAwaitResponse(&response);
230    if (err == OK && response != NULL) {
231        CHECK(response->findInt32("err", &err));
232    }
233    return err;
234}
235
236status_t NuPlayer::Renderer::onConfigSync(const AVSyncSettings &sync, float videoFpsHint __unused) {
237    if (sync.mSource != AVSYNC_SOURCE_DEFAULT) {
238        return BAD_VALUE;
239    }
240    // TODO: support sync sources
241    return INVALID_OPERATION;
242}
243
244status_t NuPlayer::Renderer::getSyncSettings(AVSyncSettings *sync, float *videoFps) {
245    sp<AMessage> msg = new AMessage(kWhatGetSyncSettings, this);
246    sp<AMessage> response;
247    status_t err = msg->postAndAwaitResponse(&response);
248    if (err == OK && response != NULL) {
249        CHECK(response->findInt32("err", &err));
250        if (err == OK) {
251            readFromAMessage(response, sync, videoFps);
252        }
253    }
254    return err;
255}
256
257status_t NuPlayer::Renderer::onGetSyncSettings(
258        AVSyncSettings *sync /* nonnull */, float *videoFps /* nonnull */) {
259    *sync = mSyncSettings;
260    *videoFps = -1.f;
261    return OK;
262}
263
264void NuPlayer::Renderer::flush(bool audio, bool notifyComplete) {
265    {
266        Mutex::Autolock autoLock(mLock);
267        if (audio) {
268            mNotifyCompleteAudio |= notifyComplete;
269            clearAudioFirstAnchorTime_l();
270            ++mAudioQueueGeneration;
271            ++mAudioDrainGeneration;
272        } else {
273            mNotifyCompleteVideo |= notifyComplete;
274            ++mVideoQueueGeneration;
275            ++mVideoDrainGeneration;
276        }
277
278        clearAnchorTime_l();
279        mVideoLateByUs = 0;
280        mSyncQueues = false;
281    }
282
283    sp<AMessage> msg = new AMessage(kWhatFlush, this);
284    msg->setInt32("audio", static_cast<int32_t>(audio));
285    msg->post();
286}
287
288void NuPlayer::Renderer::signalTimeDiscontinuity() {
289}
290
291void NuPlayer::Renderer::signalDisableOffloadAudio() {
292    (new AMessage(kWhatDisableOffloadAudio, this))->post();
293}
294
295void NuPlayer::Renderer::signalEnableOffloadAudio() {
296    (new AMessage(kWhatEnableOffloadAudio, this))->post();
297}
298
299void NuPlayer::Renderer::pause() {
300    (new AMessage(kWhatPause, this))->post();
301}
302
303void NuPlayer::Renderer::resume() {
304    (new AMessage(kWhatResume, this))->post();
305}
306
307void NuPlayer::Renderer::setVideoFrameRate(float fps) {
308    sp<AMessage> msg = new AMessage(kWhatSetVideoFrameRate, this);
309    msg->setFloat("frame-rate", fps);
310    msg->post();
311}
312
313// Called on any threads.
314status_t NuPlayer::Renderer::getCurrentPosition(int64_t *mediaUs) {
315    return mMediaClock->getMediaTime(ALooper::GetNowUs(), mediaUs);
316}
317
318void NuPlayer::Renderer::clearAudioFirstAnchorTime_l() {
319    mAudioFirstAnchorTimeMediaUs = -1;
320    mMediaClock->setStartingTimeMedia(-1);
321}
322
323void NuPlayer::Renderer::setAudioFirstAnchorTimeIfNeeded_l(int64_t mediaUs) {
324    if (mAudioFirstAnchorTimeMediaUs == -1) {
325        mAudioFirstAnchorTimeMediaUs = mediaUs;
326        mMediaClock->setStartingTimeMedia(mediaUs);
327    }
328}
329
330void NuPlayer::Renderer::clearAnchorTime_l() {
331    mMediaClock->clearAnchor();
332    mAnchorTimeMediaUs = -1;
333    mAnchorNumFramesWritten = -1;
334}
335
336void NuPlayer::Renderer::setVideoLateByUs(int64_t lateUs) {
337    Mutex::Autolock autoLock(mLock);
338    mVideoLateByUs = lateUs;
339}
340
341int64_t NuPlayer::Renderer::getVideoLateByUs() {
342    Mutex::Autolock autoLock(mLock);
343    return mVideoLateByUs;
344}
345
346status_t NuPlayer::Renderer::openAudioSink(
347        const sp<AMessage> &format,
348        bool offloadOnly,
349        bool hasVideo,
350        uint32_t flags,
351        bool *isOffloaded) {
352    sp<AMessage> msg = new AMessage(kWhatOpenAudioSink, this);
353    msg->setMessage("format", format);
354    msg->setInt32("offload-only", offloadOnly);
355    msg->setInt32("has-video", hasVideo);
356    msg->setInt32("flags", flags);
357
358    sp<AMessage> response;
359    msg->postAndAwaitResponse(&response);
360
361    int32_t err;
362    if (!response->findInt32("err", &err)) {
363        err = INVALID_OPERATION;
364    } else if (err == OK && isOffloaded != NULL) {
365        int32_t offload;
366        CHECK(response->findInt32("offload", &offload));
367        *isOffloaded = (offload != 0);
368    }
369    return err;
370}
371
372void NuPlayer::Renderer::closeAudioSink() {
373    sp<AMessage> msg = new AMessage(kWhatCloseAudioSink, this);
374
375    sp<AMessage> response;
376    msg->postAndAwaitResponse(&response);
377}
378
379void NuPlayer::Renderer::onMessageReceived(const sp<AMessage> &msg) {
380    switch (msg->what()) {
381        case kWhatOpenAudioSink:
382        {
383            sp<AMessage> format;
384            CHECK(msg->findMessage("format", &format));
385
386            int32_t offloadOnly;
387            CHECK(msg->findInt32("offload-only", &offloadOnly));
388
389            int32_t hasVideo;
390            CHECK(msg->findInt32("has-video", &hasVideo));
391
392            uint32_t flags;
393            CHECK(msg->findInt32("flags", (int32_t *)&flags));
394
395            status_t err = onOpenAudioSink(format, offloadOnly, hasVideo, flags);
396
397            sp<AMessage> response = new AMessage;
398            response->setInt32("err", err);
399            response->setInt32("offload", offloadingAudio());
400
401            sp<AReplyToken> replyID;
402            CHECK(msg->senderAwaitsResponse(&replyID));
403            response->postReply(replyID);
404
405            break;
406        }
407
408        case kWhatCloseAudioSink:
409        {
410            sp<AReplyToken> replyID;
411            CHECK(msg->senderAwaitsResponse(&replyID));
412
413            onCloseAudioSink();
414
415            sp<AMessage> response = new AMessage;
416            response->postReply(replyID);
417            break;
418        }
419
420        case kWhatStopAudioSink:
421        {
422            mAudioSink->stop();
423            break;
424        }
425
426        case kWhatDrainAudioQueue:
427        {
428            mDrainAudioQueuePending = false;
429
430            int32_t generation;
431            CHECK(msg->findInt32("drainGeneration", &generation));
432            if (generation != getDrainGeneration(true /* audio */)) {
433                break;
434            }
435
436            if (onDrainAudioQueue()) {
437                uint32_t numFramesPlayed;
438                CHECK_EQ(mAudioSink->getPosition(&numFramesPlayed),
439                         (status_t)OK);
440
441                uint32_t numFramesPendingPlayout =
442                    mNumFramesWritten - numFramesPlayed;
443
444                // This is how long the audio sink will have data to
445                // play back.
446                int64_t delayUs =
447                    mAudioSink->msecsPerFrame()
448                        * numFramesPendingPlayout * 1000ll;
449                if (mPlaybackRate > 1.0f) {
450                    delayUs /= mPlaybackRate;
451                }
452
453                // Let's give it more data after about half that time
454                // has elapsed.
455                Mutex::Autolock autoLock(mLock);
456                postDrainAudioQueue_l(delayUs / 2);
457            }
458            break;
459        }
460
461        case kWhatDrainVideoQueue:
462        {
463            int32_t generation;
464            CHECK(msg->findInt32("drainGeneration", &generation));
465            if (generation != getDrainGeneration(false /* audio */)) {
466                break;
467            }
468
469            mDrainVideoQueuePending = false;
470
471            onDrainVideoQueue();
472
473            postDrainVideoQueue();
474            break;
475        }
476
477        case kWhatPostDrainVideoQueue:
478        {
479            int32_t generation;
480            CHECK(msg->findInt32("drainGeneration", &generation));
481            if (generation != getDrainGeneration(false /* audio */)) {
482                break;
483            }
484
485            mDrainVideoQueuePending = false;
486            postDrainVideoQueue();
487            break;
488        }
489
490        case kWhatQueueBuffer:
491        {
492            onQueueBuffer(msg);
493            break;
494        }
495
496        case kWhatQueueEOS:
497        {
498            onQueueEOS(msg);
499            break;
500        }
501
502        case kWhatConfigPlayback:
503        {
504            sp<AReplyToken> replyID;
505            CHECK(msg->senderAwaitsResponse(&replyID));
506            AudioPlaybackRate rate;
507            readFromAMessage(msg, &rate);
508            status_t err = onConfigPlayback(rate);
509            sp<AMessage> response = new AMessage;
510            response->setInt32("err", err);
511            response->postReply(replyID);
512            break;
513        }
514
515        case kWhatGetPlaybackSettings:
516        {
517            sp<AReplyToken> replyID;
518            CHECK(msg->senderAwaitsResponse(&replyID));
519            AudioPlaybackRate rate = AUDIO_PLAYBACK_RATE_DEFAULT;
520            status_t err = onGetPlaybackSettings(&rate);
521            sp<AMessage> response = new AMessage;
522            if (err == OK) {
523                writeToAMessage(response, rate);
524            }
525            response->setInt32("err", err);
526            response->postReply(replyID);
527            break;
528        }
529
530        case kWhatConfigSync:
531        {
532            sp<AReplyToken> replyID;
533            CHECK(msg->senderAwaitsResponse(&replyID));
534            AVSyncSettings sync;
535            float videoFpsHint;
536            readFromAMessage(msg, &sync, &videoFpsHint);
537            status_t err = onConfigSync(sync, videoFpsHint);
538            sp<AMessage> response = new AMessage;
539            response->setInt32("err", err);
540            response->postReply(replyID);
541            break;
542        }
543
544        case kWhatGetSyncSettings:
545        {
546            sp<AReplyToken> replyID;
547            CHECK(msg->senderAwaitsResponse(&replyID));
548
549            ALOGV("kWhatGetSyncSettings");
550            AVSyncSettings sync;
551            float videoFps = -1.f;
552            status_t err = onGetSyncSettings(&sync, &videoFps);
553            sp<AMessage> response = new AMessage;
554            if (err == OK) {
555                writeToAMessage(response, sync, videoFps);
556            }
557            response->setInt32("err", err);
558            response->postReply(replyID);
559            break;
560        }
561
562        case kWhatFlush:
563        {
564            onFlush(msg);
565            break;
566        }
567
568        case kWhatDisableOffloadAudio:
569        {
570            onDisableOffloadAudio();
571            break;
572        }
573
574        case kWhatEnableOffloadAudio:
575        {
576            onEnableOffloadAudio();
577            break;
578        }
579
580        case kWhatPause:
581        {
582            onPause();
583            break;
584        }
585
586        case kWhatResume:
587        {
588            onResume();
589            break;
590        }
591
592        case kWhatSetVideoFrameRate:
593        {
594            float fps;
595            CHECK(msg->findFloat("frame-rate", &fps));
596            onSetVideoFrameRate(fps);
597            break;
598        }
599
600        case kWhatAudioTearDown:
601        {
602            onAudioTearDown(kDueToError);
603            break;
604        }
605
606        case kWhatAudioOffloadPauseTimeout:
607        {
608            int32_t generation;
609            CHECK(msg->findInt32("drainGeneration", &generation));
610            if (generation != mAudioOffloadPauseTimeoutGeneration) {
611                break;
612            }
613            ALOGV("Audio Offload tear down due to pause timeout.");
614            onAudioTearDown(kDueToTimeout);
615            mWakeLock->release();
616            break;
617        }
618
619        default:
620            TRESPASS();
621            break;
622    }
623}
624
625void NuPlayer::Renderer::postDrainAudioQueue_l(int64_t delayUs) {
626    if (mDrainAudioQueuePending || mSyncQueues || mUseAudioCallback) {
627        return;
628    }
629
630    if (mAudioQueue.empty()) {
631        return;
632    }
633
634    // FIXME: if paused, wait until AudioTrack stop() is complete before delivering data.
635    if (mPaused) {
636        const int64_t diffUs = mPauseDrainAudioAllowedUs - ALooper::GetNowUs();
637        if (diffUs > delayUs) {
638            delayUs = diffUs;
639        }
640    }
641
642    mDrainAudioQueuePending = true;
643    sp<AMessage> msg = new AMessage(kWhatDrainAudioQueue, this);
644    msg->setInt32("drainGeneration", mAudioDrainGeneration);
645    msg->post(delayUs);
646}
647
648void NuPlayer::Renderer::prepareForMediaRenderingStart_l() {
649    mAudioRenderingStartGeneration = mAudioDrainGeneration;
650    mVideoRenderingStartGeneration = mVideoDrainGeneration;
651}
652
653void NuPlayer::Renderer::notifyIfMediaRenderingStarted_l() {
654    if (mVideoRenderingStartGeneration == mVideoDrainGeneration &&
655        mAudioRenderingStartGeneration == mAudioDrainGeneration) {
656        mVideoRenderingStartGeneration = -1;
657        mAudioRenderingStartGeneration = -1;
658
659        sp<AMessage> notify = mNotify->dup();
660        notify->setInt32("what", kWhatMediaRenderingStart);
661        notify->post();
662    }
663}
664
665// static
666size_t NuPlayer::Renderer::AudioSinkCallback(
667        MediaPlayerBase::AudioSink * /* audioSink */,
668        void *buffer,
669        size_t size,
670        void *cookie,
671        MediaPlayerBase::AudioSink::cb_event_t event) {
672    NuPlayer::Renderer *me = (NuPlayer::Renderer *)cookie;
673
674    switch (event) {
675        case MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER:
676        {
677            return me->fillAudioBuffer(buffer, size);
678            break;
679        }
680
681        case MediaPlayerBase::AudioSink::CB_EVENT_STREAM_END:
682        {
683            ALOGV("AudioSink::CB_EVENT_STREAM_END");
684            me->notifyEOS(true /* audio */, ERROR_END_OF_STREAM);
685            break;
686        }
687
688        case MediaPlayerBase::AudioSink::CB_EVENT_TEAR_DOWN:
689        {
690            ALOGV("AudioSink::CB_EVENT_TEAR_DOWN");
691            me->notifyAudioTearDown();
692            break;
693        }
694    }
695
696    return 0;
697}
698
699size_t NuPlayer::Renderer::fillAudioBuffer(void *buffer, size_t size) {
700    Mutex::Autolock autoLock(mLock);
701
702    if (!mUseAudioCallback) {
703        return 0;
704    }
705
706    bool hasEOS = false;
707
708    size_t sizeCopied = 0;
709    bool firstEntry = true;
710    QueueEntry *entry;  // will be valid after while loop if hasEOS is set.
711    while (sizeCopied < size && !mAudioQueue.empty()) {
712        entry = &*mAudioQueue.begin();
713
714        if (entry->mBuffer == NULL) { // EOS
715            hasEOS = true;
716            mAudioQueue.erase(mAudioQueue.begin());
717            break;
718        }
719
720        if (firstEntry && entry->mOffset == 0) {
721            firstEntry = false;
722            int64_t mediaTimeUs;
723            CHECK(entry->mBuffer->meta()->findInt64("timeUs", &mediaTimeUs));
724            ALOGV("fillAudioBuffer: rendering audio at media time %.2f secs", mediaTimeUs / 1E6);
725            setAudioFirstAnchorTimeIfNeeded_l(mediaTimeUs);
726        }
727
728        size_t copy = entry->mBuffer->size() - entry->mOffset;
729        size_t sizeRemaining = size - sizeCopied;
730        if (copy > sizeRemaining) {
731            copy = sizeRemaining;
732        }
733
734        memcpy((char *)buffer + sizeCopied,
735               entry->mBuffer->data() + entry->mOffset,
736               copy);
737
738        entry->mOffset += copy;
739        if (entry->mOffset == entry->mBuffer->size()) {
740            entry->mNotifyConsumed->post();
741            mAudioQueue.erase(mAudioQueue.begin());
742            entry = NULL;
743        }
744        sizeCopied += copy;
745
746        notifyIfMediaRenderingStarted_l();
747    }
748
749    if (mAudioFirstAnchorTimeMediaUs >= 0) {
750        int64_t nowUs = ALooper::GetNowUs();
751        int64_t nowMediaUs =
752            mAudioFirstAnchorTimeMediaUs + getPlayedOutAudioDurationUs(nowUs);
753        // we don't know how much data we are queueing for offloaded tracks.
754        mMediaClock->updateAnchor(nowMediaUs, nowUs, INT64_MAX);
755    }
756
757    // for non-offloaded audio, we need to compute the frames written because
758    // there is no EVENT_STREAM_END notification. The frames written gives
759    // an estimate on the pending played out duration.
760    if (!offloadingAudio()) {
761        mNumFramesWritten += sizeCopied / mAudioSink->frameSize();
762    }
763
764    if (hasEOS) {
765        (new AMessage(kWhatStopAudioSink, this))->post();
766        // As there is currently no EVENT_STREAM_END callback notification for
767        // non-offloaded audio tracks, we need to post the EOS ourselves.
768        if (!offloadingAudio()) {
769            int64_t postEOSDelayUs = 0;
770            if (mAudioSink->needsTrailingPadding()) {
771                postEOSDelayUs = getPendingAudioPlayoutDurationUs(ALooper::GetNowUs());
772            }
773            ALOGV("fillAudioBuffer: notifyEOS "
774                    "mNumFramesWritten:%u  finalResult:%d  postEOSDelay:%lld",
775                    mNumFramesWritten, entry->mFinalResult, (long long)postEOSDelayUs);
776            notifyEOS(true /* audio */, entry->mFinalResult, postEOSDelayUs);
777        }
778    }
779    return sizeCopied;
780}
781
782void NuPlayer::Renderer::drainAudioQueueUntilLastEOS() {
783    List<QueueEntry>::iterator it = mAudioQueue.begin(), itEOS = it;
784    bool foundEOS = false;
785    while (it != mAudioQueue.end()) {
786        int32_t eos;
787        QueueEntry *entry = &*it++;
788        if (entry->mBuffer == NULL
789                || (entry->mNotifyConsumed->findInt32("eos", &eos) && eos != 0)) {
790            itEOS = it;
791            foundEOS = true;
792        }
793    }
794
795    if (foundEOS) {
796        // post all replies before EOS and drop the samples
797        for (it = mAudioQueue.begin(); it != itEOS; it++) {
798            if (it->mBuffer == NULL) {
799                // delay doesn't matter as we don't even have an AudioTrack
800                notifyEOS(true /* audio */, it->mFinalResult);
801            } else {
802                it->mNotifyConsumed->post();
803            }
804        }
805        mAudioQueue.erase(mAudioQueue.begin(), itEOS);
806    }
807}
808
809bool NuPlayer::Renderer::onDrainAudioQueue() {
810    // do not drain audio during teardown as queued buffers may be invalid.
811    if (mAudioTornDown) {
812        return false;
813    }
814    // TODO: This call to getPosition checks if AudioTrack has been created
815    // in AudioSink before draining audio. If AudioTrack doesn't exist, then
816    // CHECKs on getPosition will fail.
817    // We still need to figure out why AudioTrack is not created when
818    // this function is called. One possible reason could be leftover
819    // audio. Another possible place is to check whether decoder
820    // has received INFO_FORMAT_CHANGED as the first buffer since
821    // AudioSink is opened there, and possible interactions with flush
822    // immediately after start. Investigate error message
823    // "vorbis_dsp_synthesis returned -135", along with RTSP.
824    uint32_t numFramesPlayed;
825    if (mAudioSink->getPosition(&numFramesPlayed) != OK) {
826        // When getPosition fails, renderer will not reschedule the draining
827        // unless new samples are queued.
828        // If we have pending EOS (or "eos" marker for discontinuities), we need
829        // to post these now as NuPlayerDecoder might be waiting for it.
830        drainAudioQueueUntilLastEOS();
831
832        ALOGW("onDrainAudioQueue(): audio sink is not ready");
833        return false;
834    }
835
836#if 0
837    ssize_t numFramesAvailableToWrite =
838        mAudioSink->frameCount() - (mNumFramesWritten - numFramesPlayed);
839
840    if (numFramesAvailableToWrite == mAudioSink->frameCount()) {
841        ALOGI("audio sink underrun");
842    } else {
843        ALOGV("audio queue has %d frames left to play",
844             mAudioSink->frameCount() - numFramesAvailableToWrite);
845    }
846#endif
847
848    uint32_t prevFramesWritten = mNumFramesWritten;
849    while (!mAudioQueue.empty()) {
850        QueueEntry *entry = &*mAudioQueue.begin();
851
852        mLastAudioBufferDrained = entry->mBufferOrdinal;
853
854        if (entry->mBuffer == NULL) {
855            // EOS
856            int64_t postEOSDelayUs = 0;
857            if (mAudioSink->needsTrailingPadding()) {
858                postEOSDelayUs = getPendingAudioPlayoutDurationUs(ALooper::GetNowUs());
859            }
860            notifyEOS(true /* audio */, entry->mFinalResult, postEOSDelayUs);
861
862            mAudioQueue.erase(mAudioQueue.begin());
863            entry = NULL;
864            if (mAudioSink->needsTrailingPadding()) {
865                // If we're not in gapless playback (i.e. through setNextPlayer), we
866                // need to stop the track here, because that will play out the last
867                // little bit at the end of the file. Otherwise short files won't play.
868                mAudioSink->stop();
869                mNumFramesWritten = 0;
870            }
871            return false;
872        }
873
874        // ignore 0-sized buffer which could be EOS marker with no data
875        if (entry->mOffset == 0 && entry->mBuffer->size() > 0) {
876            int64_t mediaTimeUs;
877            CHECK(entry->mBuffer->meta()->findInt64("timeUs", &mediaTimeUs));
878            ALOGV("onDrainAudioQueue: rendering audio at media time %.2f secs",
879                    mediaTimeUs / 1E6);
880            onNewAudioMediaTime(mediaTimeUs);
881        }
882
883        size_t copy = entry->mBuffer->size() - entry->mOffset;
884
885        ssize_t written = mAudioSink->write(entry->mBuffer->data() + entry->mOffset,
886                                            copy, false /* blocking */);
887        if (written < 0) {
888            // An error in AudioSink write. Perhaps the AudioSink was not properly opened.
889            if (written == WOULD_BLOCK) {
890                ALOGV("AudioSink write would block when writing %zu bytes", copy);
891            } else {
892                ALOGE("AudioSink write error(%zd) when writing %zu bytes", written, copy);
893                // This can only happen when AudioSink was opened with doNotReconnect flag set to
894                // true, in which case the NuPlayer will handle the reconnect.
895                notifyAudioTearDown();
896            }
897            break;
898        }
899
900        entry->mOffset += written;
901        if (entry->mOffset == entry->mBuffer->size()) {
902            entry->mNotifyConsumed->post();
903            mAudioQueue.erase(mAudioQueue.begin());
904
905            entry = NULL;
906        }
907
908        size_t copiedFrames = written / mAudioSink->frameSize();
909        mNumFramesWritten += copiedFrames;
910
911        {
912            Mutex::Autolock autoLock(mLock);
913            int64_t maxTimeMedia;
914            maxTimeMedia =
915                mAnchorTimeMediaUs +
916                        (int64_t)(max((long long)mNumFramesWritten - mAnchorNumFramesWritten, 0LL)
917                                * 1000LL * mAudioSink->msecsPerFrame());
918            mMediaClock->updateMaxTimeMedia(maxTimeMedia);
919
920            notifyIfMediaRenderingStarted_l();
921        }
922
923        if (written != (ssize_t)copy) {
924            // A short count was received from AudioSink::write()
925            //
926            // AudioSink write is called in non-blocking mode.
927            // It may return with a short count when:
928            //
929            // 1) Size to be copied is not a multiple of the frame size. We consider this fatal.
930            // 2) The data to be copied exceeds the available buffer in AudioSink.
931            // 3) An error occurs and data has been partially copied to the buffer in AudioSink.
932            // 4) AudioSink is an AudioCache for data retrieval, and the AudioCache is exceeded.
933
934            // (Case 1)
935            // Must be a multiple of the frame size.  If it is not a multiple of a frame size, it
936            // needs to fail, as we should not carry over fractional frames between calls.
937            CHECK_EQ(copy % mAudioSink->frameSize(), 0);
938
939            // (Case 2, 3, 4)
940            // Return early to the caller.
941            // Beware of calling immediately again as this may busy-loop if you are not careful.
942            ALOGV("AudioSink write short frame count %zd < %zu", written, copy);
943            break;
944        }
945    }
946
947    // calculate whether we need to reschedule another write.
948    bool reschedule = !mAudioQueue.empty()
949            && (!mPaused
950                || prevFramesWritten != mNumFramesWritten); // permit pause to fill buffers
951    //ALOGD("reschedule:%d  empty:%d  mPaused:%d  prevFramesWritten:%u  mNumFramesWritten:%u",
952    //        reschedule, mAudioQueue.empty(), mPaused, prevFramesWritten, mNumFramesWritten);
953    return reschedule;
954}
955
956int64_t NuPlayer::Renderer::getDurationUsIfPlayedAtSampleRate(uint32_t numFrames) {
957    int32_t sampleRate = offloadingAudio() ?
958            mCurrentOffloadInfo.sample_rate : mCurrentPcmInfo.mSampleRate;
959    if (sampleRate == 0) {
960        ALOGE("sampleRate is 0 in %s mode", offloadingAudio() ? "offload" : "non-offload");
961        return 0;
962    }
963    // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
964    return (int64_t)((int32_t)numFrames * 1000000LL / sampleRate);
965}
966
967// Calculate duration of pending samples if played at normal rate (i.e., 1.0).
968int64_t NuPlayer::Renderer::getPendingAudioPlayoutDurationUs(int64_t nowUs) {
969    int64_t writtenAudioDurationUs = getDurationUsIfPlayedAtSampleRate(mNumFramesWritten);
970    return writtenAudioDurationUs - getPlayedOutAudioDurationUs(nowUs);
971}
972
973int64_t NuPlayer::Renderer::getRealTimeUs(int64_t mediaTimeUs, int64_t nowUs) {
974    int64_t realUs;
975    if (mMediaClock->getRealTimeFor(mediaTimeUs, &realUs) != OK) {
976        // If failed to get current position, e.g. due to audio clock is
977        // not ready, then just play out video immediately without delay.
978        return nowUs;
979    }
980    return realUs;
981}
982
983void NuPlayer::Renderer::onNewAudioMediaTime(int64_t mediaTimeUs) {
984    Mutex::Autolock autoLock(mLock);
985    // TRICKY: vorbis decoder generates multiple frames with the same
986    // timestamp, so only update on the first frame with a given timestamp
987    if (mediaTimeUs == mAnchorTimeMediaUs) {
988        return;
989    }
990    setAudioFirstAnchorTimeIfNeeded_l(mediaTimeUs);
991    int64_t nowUs = ALooper::GetNowUs();
992    int64_t nowMediaUs = mediaTimeUs - getPendingAudioPlayoutDurationUs(nowUs);
993    mMediaClock->updateAnchor(nowMediaUs, nowUs, mediaTimeUs);
994    mAnchorNumFramesWritten = mNumFramesWritten;
995    mAnchorTimeMediaUs = mediaTimeUs;
996}
997
998// Called without mLock acquired.
999void NuPlayer::Renderer::postDrainVideoQueue() {
1000    if (mDrainVideoQueuePending
1001            || getSyncQueues()
1002            || (mPaused && mVideoSampleReceived)) {
1003        return;
1004    }
1005
1006    if (mVideoQueue.empty()) {
1007        return;
1008    }
1009
1010    QueueEntry &entry = *mVideoQueue.begin();
1011
1012    sp<AMessage> msg = new AMessage(kWhatDrainVideoQueue, this);
1013    msg->setInt32("drainGeneration", getDrainGeneration(false /* audio */));
1014
1015    if (entry.mBuffer == NULL) {
1016        // EOS doesn't carry a timestamp.
1017        msg->post();
1018        mDrainVideoQueuePending = true;
1019        return;
1020    }
1021
1022    int64_t delayUs;
1023    int64_t nowUs = ALooper::GetNowUs();
1024    int64_t realTimeUs;
1025    if (mFlags & FLAG_REAL_TIME) {
1026        int64_t mediaTimeUs;
1027        CHECK(entry.mBuffer->meta()->findInt64("timeUs", &mediaTimeUs));
1028        realTimeUs = mediaTimeUs;
1029    } else {
1030        int64_t mediaTimeUs;
1031        CHECK(entry.mBuffer->meta()->findInt64("timeUs", &mediaTimeUs));
1032
1033        {
1034            Mutex::Autolock autoLock(mLock);
1035            if (mAnchorTimeMediaUs < 0) {
1036                mMediaClock->updateAnchor(mediaTimeUs, nowUs, mediaTimeUs);
1037                mAnchorTimeMediaUs = mediaTimeUs;
1038                realTimeUs = nowUs;
1039            } else {
1040                realTimeUs = getRealTimeUs(mediaTimeUs, nowUs);
1041            }
1042        }
1043        if (!mHasAudio) {
1044            // smooth out videos >= 10fps
1045            mMediaClock->updateMaxTimeMedia(mediaTimeUs + 100000);
1046        }
1047
1048        // Heuristics to handle situation when media time changed without a
1049        // discontinuity. If we have not drained an audio buffer that was
1050        // received after this buffer, repost in 10 msec. Otherwise repost
1051        // in 500 msec.
1052        delayUs = realTimeUs - nowUs;
1053        if (delayUs > 500000) {
1054            int64_t postDelayUs = 500000;
1055            if (mHasAudio && (mLastAudioBufferDrained - entry.mBufferOrdinal) <= 0) {
1056                postDelayUs = 10000;
1057            }
1058            msg->setWhat(kWhatPostDrainVideoQueue);
1059            msg->post(postDelayUs);
1060            mVideoScheduler->restart();
1061            ALOGI("possible video time jump of %dms, retrying in %dms",
1062                    (int)(delayUs / 1000), (int)(postDelayUs / 1000));
1063            mDrainVideoQueuePending = true;
1064            return;
1065        }
1066    }
1067
1068    realTimeUs = mVideoScheduler->schedule(realTimeUs * 1000) / 1000;
1069    int64_t twoVsyncsUs = 2 * (mVideoScheduler->getVsyncPeriod() / 1000);
1070
1071    delayUs = realTimeUs - nowUs;
1072
1073    ALOGW_IF(delayUs > 500000, "unusually high delayUs: %" PRId64, delayUs);
1074    // post 2 display refreshes before rendering is due
1075    msg->post(delayUs > twoVsyncsUs ? delayUs - twoVsyncsUs : 0);
1076
1077    mDrainVideoQueuePending = true;
1078}
1079
1080void NuPlayer::Renderer::onDrainVideoQueue() {
1081    if (mVideoQueue.empty()) {
1082        return;
1083    }
1084
1085    QueueEntry *entry = &*mVideoQueue.begin();
1086
1087    if (entry->mBuffer == NULL) {
1088        // EOS
1089
1090        notifyEOS(false /* audio */, entry->mFinalResult);
1091
1092        mVideoQueue.erase(mVideoQueue.begin());
1093        entry = NULL;
1094
1095        setVideoLateByUs(0);
1096        return;
1097    }
1098
1099    int64_t nowUs = -1;
1100    int64_t realTimeUs;
1101    if (mFlags & FLAG_REAL_TIME) {
1102        CHECK(entry->mBuffer->meta()->findInt64("timeUs", &realTimeUs));
1103    } else {
1104        int64_t mediaTimeUs;
1105        CHECK(entry->mBuffer->meta()->findInt64("timeUs", &mediaTimeUs));
1106
1107        nowUs = ALooper::GetNowUs();
1108        realTimeUs = getRealTimeUs(mediaTimeUs, nowUs);
1109    }
1110
1111    bool tooLate = false;
1112
1113    if (!mPaused) {
1114        if (nowUs == -1) {
1115            nowUs = ALooper::GetNowUs();
1116        }
1117        setVideoLateByUs(nowUs - realTimeUs);
1118        tooLate = (mVideoLateByUs > 40000);
1119
1120        if (tooLate) {
1121            ALOGV("video late by %lld us (%.2f secs)",
1122                 (long long)mVideoLateByUs, mVideoLateByUs / 1E6);
1123        } else {
1124            int64_t mediaUs = 0;
1125            mMediaClock->getMediaTime(realTimeUs, &mediaUs);
1126            ALOGV("rendering video at media time %.2f secs",
1127                    (mFlags & FLAG_REAL_TIME ? realTimeUs :
1128                    mediaUs) / 1E6);
1129        }
1130    } else {
1131        setVideoLateByUs(0);
1132        if (!mVideoSampleReceived && !mHasAudio) {
1133            // This will ensure that the first frame after a flush won't be used as anchor
1134            // when renderer is in paused state, because resume can happen any time after seek.
1135            Mutex::Autolock autoLock(mLock);
1136            clearAnchorTime_l();
1137        }
1138    }
1139
1140    entry->mNotifyConsumed->setInt64("timestampNs", realTimeUs * 1000ll);
1141    entry->mNotifyConsumed->setInt32("render", !tooLate);
1142    entry->mNotifyConsumed->post();
1143    mVideoQueue.erase(mVideoQueue.begin());
1144    entry = NULL;
1145
1146    mVideoSampleReceived = true;
1147
1148    if (!mPaused) {
1149        if (!mVideoRenderingStarted) {
1150            mVideoRenderingStarted = true;
1151            notifyVideoRenderingStart();
1152        }
1153        Mutex::Autolock autoLock(mLock);
1154        notifyIfMediaRenderingStarted_l();
1155    }
1156}
1157
1158void NuPlayer::Renderer::notifyVideoRenderingStart() {
1159    sp<AMessage> notify = mNotify->dup();
1160    notify->setInt32("what", kWhatVideoRenderingStart);
1161    notify->post();
1162}
1163
1164void NuPlayer::Renderer::notifyEOS(bool audio, status_t finalResult, int64_t delayUs) {
1165    sp<AMessage> notify = mNotify->dup();
1166    notify->setInt32("what", kWhatEOS);
1167    notify->setInt32("audio", static_cast<int32_t>(audio));
1168    notify->setInt32("finalResult", finalResult);
1169    notify->post(delayUs);
1170}
1171
1172void NuPlayer::Renderer::notifyAudioTearDown() {
1173    (new AMessage(kWhatAudioTearDown, this))->post();
1174}
1175
1176void NuPlayer::Renderer::onQueueBuffer(const sp<AMessage> &msg) {
1177    int32_t audio;
1178    CHECK(msg->findInt32("audio", &audio));
1179
1180    if (dropBufferIfStale(audio, msg)) {
1181        return;
1182    }
1183
1184    if (audio) {
1185        mHasAudio = true;
1186    } else {
1187        mHasVideo = true;
1188    }
1189
1190    if (mHasVideo) {
1191        if (mVideoScheduler == NULL) {
1192            mVideoScheduler = new VideoFrameScheduler();
1193            mVideoScheduler->init();
1194        }
1195    }
1196
1197    sp<ABuffer> buffer;
1198    CHECK(msg->findBuffer("buffer", &buffer));
1199
1200    sp<AMessage> notifyConsumed;
1201    CHECK(msg->findMessage("notifyConsumed", &notifyConsumed));
1202
1203    QueueEntry entry;
1204    entry.mBuffer = buffer;
1205    entry.mNotifyConsumed = notifyConsumed;
1206    entry.mOffset = 0;
1207    entry.mFinalResult = OK;
1208    entry.mBufferOrdinal = ++mTotalBuffersQueued;
1209
1210    if (audio) {
1211        Mutex::Autolock autoLock(mLock);
1212        mAudioQueue.push_back(entry);
1213        postDrainAudioQueue_l();
1214    } else {
1215        mVideoQueue.push_back(entry);
1216        postDrainVideoQueue();
1217    }
1218
1219    Mutex::Autolock autoLock(mLock);
1220    if (!mSyncQueues || mAudioQueue.empty() || mVideoQueue.empty()) {
1221        return;
1222    }
1223
1224    sp<ABuffer> firstAudioBuffer = (*mAudioQueue.begin()).mBuffer;
1225    sp<ABuffer> firstVideoBuffer = (*mVideoQueue.begin()).mBuffer;
1226
1227    if (firstAudioBuffer == NULL || firstVideoBuffer == NULL) {
1228        // EOS signalled on either queue.
1229        syncQueuesDone_l();
1230        return;
1231    }
1232
1233    int64_t firstAudioTimeUs;
1234    int64_t firstVideoTimeUs;
1235    CHECK(firstAudioBuffer->meta()
1236            ->findInt64("timeUs", &firstAudioTimeUs));
1237    CHECK(firstVideoBuffer->meta()
1238            ->findInt64("timeUs", &firstVideoTimeUs));
1239
1240    int64_t diff = firstVideoTimeUs - firstAudioTimeUs;
1241
1242    ALOGV("queueDiff = %.2f secs", diff / 1E6);
1243
1244    if (diff > 100000ll) {
1245        // Audio data starts More than 0.1 secs before video.
1246        // Drop some audio.
1247
1248        (*mAudioQueue.begin()).mNotifyConsumed->post();
1249        mAudioQueue.erase(mAudioQueue.begin());
1250        return;
1251    }
1252
1253    syncQueuesDone_l();
1254}
1255
1256void NuPlayer::Renderer::syncQueuesDone_l() {
1257    if (!mSyncQueues) {
1258        return;
1259    }
1260
1261    mSyncQueues = false;
1262
1263    if (!mAudioQueue.empty()) {
1264        postDrainAudioQueue_l();
1265    }
1266
1267    if (!mVideoQueue.empty()) {
1268        mLock.unlock();
1269        postDrainVideoQueue();
1270        mLock.lock();
1271    }
1272}
1273
1274void NuPlayer::Renderer::onQueueEOS(const sp<AMessage> &msg) {
1275    int32_t audio;
1276    CHECK(msg->findInt32("audio", &audio));
1277
1278    if (dropBufferIfStale(audio, msg)) {
1279        return;
1280    }
1281
1282    int32_t finalResult;
1283    CHECK(msg->findInt32("finalResult", &finalResult));
1284
1285    QueueEntry entry;
1286    entry.mOffset = 0;
1287    entry.mFinalResult = finalResult;
1288
1289    if (audio) {
1290        Mutex::Autolock autoLock(mLock);
1291        if (mAudioQueue.empty() && mSyncQueues) {
1292            syncQueuesDone_l();
1293        }
1294        mAudioQueue.push_back(entry);
1295        postDrainAudioQueue_l();
1296    } else {
1297        if (mVideoQueue.empty() && getSyncQueues()) {
1298            Mutex::Autolock autoLock(mLock);
1299            syncQueuesDone_l();
1300        }
1301        mVideoQueue.push_back(entry);
1302        postDrainVideoQueue();
1303    }
1304}
1305
1306void NuPlayer::Renderer::onFlush(const sp<AMessage> &msg) {
1307    int32_t audio, notifyComplete;
1308    CHECK(msg->findInt32("audio", &audio));
1309
1310    {
1311        Mutex::Autolock autoLock(mLock);
1312        if (audio) {
1313            notifyComplete = mNotifyCompleteAudio;
1314            mNotifyCompleteAudio = false;
1315        } else {
1316            notifyComplete = mNotifyCompleteVideo;
1317            mNotifyCompleteVideo = false;
1318        }
1319
1320        // If we're currently syncing the queues, i.e. dropping audio while
1321        // aligning the first audio/video buffer times and only one of the
1322        // two queues has data, we may starve that queue by not requesting
1323        // more buffers from the decoder. If the other source then encounters
1324        // a discontinuity that leads to flushing, we'll never find the
1325        // corresponding discontinuity on the other queue.
1326        // Therefore we'll stop syncing the queues if at least one of them
1327        // is flushed.
1328        syncQueuesDone_l();
1329        clearAnchorTime_l();
1330    }
1331
1332    ALOGV("flushing %s", audio ? "audio" : "video");
1333    if (audio) {
1334        {
1335            Mutex::Autolock autoLock(mLock);
1336            flushQueue(&mAudioQueue);
1337
1338            ++mAudioDrainGeneration;
1339            prepareForMediaRenderingStart_l();
1340
1341            // the frame count will be reset after flush.
1342            clearAudioFirstAnchorTime_l();
1343        }
1344
1345        mDrainAudioQueuePending = false;
1346
1347        if (offloadingAudio()) {
1348            mAudioSink->pause();
1349            mAudioSink->flush();
1350            if (!mPaused) {
1351                mAudioSink->start();
1352            }
1353        } else {
1354            mAudioSink->pause();
1355            mAudioSink->flush();
1356            // Call stop() to signal to the AudioSink to completely fill the
1357            // internal buffer before resuming playback.
1358            // FIXME: this is ignored after flush().
1359            mAudioSink->stop();
1360            if (mPaused) {
1361                // Race condition: if renderer is paused and audio sink is stopped,
1362                // we need to make sure that the audio track buffer fully drains
1363                // before delivering data.
1364                // FIXME: remove this if we can detect if stop() is complete.
1365                const int delayUs = 2 * 50 * 1000; // (2 full mixer thread cycles at 50ms)
1366                mPauseDrainAudioAllowedUs = ALooper::GetNowUs() + delayUs;
1367            } else {
1368                mAudioSink->start();
1369            }
1370            mNumFramesWritten = 0;
1371        }
1372    } else {
1373        flushQueue(&mVideoQueue);
1374
1375        mDrainVideoQueuePending = false;
1376
1377        if (mVideoScheduler != NULL) {
1378            mVideoScheduler->restart();
1379        }
1380
1381        Mutex::Autolock autoLock(mLock);
1382        ++mVideoDrainGeneration;
1383        prepareForMediaRenderingStart_l();
1384    }
1385
1386    mVideoSampleReceived = false;
1387
1388    if (notifyComplete) {
1389        notifyFlushComplete(audio);
1390    }
1391}
1392
1393void NuPlayer::Renderer::flushQueue(List<QueueEntry> *queue) {
1394    while (!queue->empty()) {
1395        QueueEntry *entry = &*queue->begin();
1396
1397        if (entry->mBuffer != NULL) {
1398            entry->mNotifyConsumed->post();
1399        }
1400
1401        queue->erase(queue->begin());
1402        entry = NULL;
1403    }
1404}
1405
1406void NuPlayer::Renderer::notifyFlushComplete(bool audio) {
1407    sp<AMessage> notify = mNotify->dup();
1408    notify->setInt32("what", kWhatFlushComplete);
1409    notify->setInt32("audio", static_cast<int32_t>(audio));
1410    notify->post();
1411}
1412
1413bool NuPlayer::Renderer::dropBufferIfStale(
1414        bool audio, const sp<AMessage> &msg) {
1415    int32_t queueGeneration;
1416    CHECK(msg->findInt32("queueGeneration", &queueGeneration));
1417
1418    if (queueGeneration == getQueueGeneration(audio)) {
1419        return false;
1420    }
1421
1422    sp<AMessage> notifyConsumed;
1423    if (msg->findMessage("notifyConsumed", &notifyConsumed)) {
1424        notifyConsumed->post();
1425    }
1426
1427    return true;
1428}
1429
1430void NuPlayer::Renderer::onAudioSinkChanged() {
1431    if (offloadingAudio()) {
1432        return;
1433    }
1434    CHECK(!mDrainAudioQueuePending);
1435    mNumFramesWritten = 0;
1436    {
1437        Mutex::Autolock autoLock(mLock);
1438        mAnchorNumFramesWritten = -1;
1439    }
1440    uint32_t written;
1441    if (mAudioSink->getFramesWritten(&written) == OK) {
1442        mNumFramesWritten = written;
1443    }
1444}
1445
1446void NuPlayer::Renderer::onDisableOffloadAudio() {
1447    Mutex::Autolock autoLock(mLock);
1448    mFlags &= ~FLAG_OFFLOAD_AUDIO;
1449    ++mAudioDrainGeneration;
1450    if (mAudioRenderingStartGeneration != -1) {
1451        prepareForMediaRenderingStart_l();
1452    }
1453}
1454
1455void NuPlayer::Renderer::onEnableOffloadAudio() {
1456    Mutex::Autolock autoLock(mLock);
1457    mFlags |= FLAG_OFFLOAD_AUDIO;
1458    ++mAudioDrainGeneration;
1459    if (mAudioRenderingStartGeneration != -1) {
1460        prepareForMediaRenderingStart_l();
1461    }
1462}
1463
1464void NuPlayer::Renderer::onPause() {
1465    if (mPaused) {
1466        return;
1467    }
1468
1469    {
1470        Mutex::Autolock autoLock(mLock);
1471        // we do not increment audio drain generation so that we fill audio buffer during pause.
1472        ++mVideoDrainGeneration;
1473        prepareForMediaRenderingStart_l();
1474        mPaused = true;
1475        mMediaClock->setPlaybackRate(0.0);
1476    }
1477
1478    mDrainAudioQueuePending = false;
1479    mDrainVideoQueuePending = false;
1480
1481    if (mHasAudio) {
1482        mAudioSink->pause();
1483        startAudioOffloadPauseTimeout();
1484    }
1485
1486    ALOGV("now paused audio queue has %zu entries, video has %zu entries",
1487          mAudioQueue.size(), mVideoQueue.size());
1488}
1489
1490void NuPlayer::Renderer::onResume() {
1491    if (!mPaused) {
1492        return;
1493    }
1494
1495    if (mHasAudio) {
1496        cancelAudioOffloadPauseTimeout();
1497        status_t err = mAudioSink->start();
1498        if (err != OK) {
1499            ALOGE("cannot start AudioSink err %d", err);
1500            notifyAudioTearDown();
1501        }
1502    }
1503
1504    {
1505        Mutex::Autolock autoLock(mLock);
1506        mPaused = false;
1507
1508        // configure audiosink as we did not do it when pausing
1509        if (mAudioSink != NULL && mAudioSink->ready()) {
1510            mAudioSink->setPlaybackRate(mPlaybackSettings);
1511        }
1512
1513        mMediaClock->setPlaybackRate(mPlaybackRate);
1514
1515        if (!mAudioQueue.empty()) {
1516            postDrainAudioQueue_l();
1517        }
1518    }
1519
1520    if (!mVideoQueue.empty()) {
1521        postDrainVideoQueue();
1522    }
1523}
1524
1525void NuPlayer::Renderer::onSetVideoFrameRate(float fps) {
1526    if (mVideoScheduler == NULL) {
1527        mVideoScheduler = new VideoFrameScheduler();
1528    }
1529    mVideoScheduler->init(fps);
1530}
1531
1532int32_t NuPlayer::Renderer::getQueueGeneration(bool audio) {
1533    Mutex::Autolock autoLock(mLock);
1534    return (audio ? mAudioQueueGeneration : mVideoQueueGeneration);
1535}
1536
1537int32_t NuPlayer::Renderer::getDrainGeneration(bool audio) {
1538    Mutex::Autolock autoLock(mLock);
1539    return (audio ? mAudioDrainGeneration : mVideoDrainGeneration);
1540}
1541
1542bool NuPlayer::Renderer::getSyncQueues() {
1543    Mutex::Autolock autoLock(mLock);
1544    return mSyncQueues;
1545}
1546
1547// TODO: Remove unnecessary calls to getPlayedOutAudioDurationUs()
1548// as it acquires locks and may query the audio driver.
1549//
1550// Some calls could conceivably retrieve extrapolated data instead of
1551// accessing getTimestamp() or getPosition() every time a data buffer with
1552// a media time is received.
1553//
1554// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1555int64_t NuPlayer::Renderer::getPlayedOutAudioDurationUs(int64_t nowUs) {
1556    uint32_t numFramesPlayed;
1557    int64_t numFramesPlayedAt;
1558    AudioTimestamp ts;
1559    static const int64_t kStaleTimestamp100ms = 100000;
1560
1561    status_t res = mAudioSink->getTimestamp(ts);
1562    if (res == OK) {                 // case 1: mixing audio tracks and offloaded tracks.
1563        numFramesPlayed = ts.mPosition;
1564        numFramesPlayedAt =
1565            ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1566        const int64_t timestampAge = nowUs - numFramesPlayedAt;
1567        if (timestampAge > kStaleTimestamp100ms) {
1568            // This is an audio FIXME.
1569            // getTimestamp returns a timestamp which may come from audio mixing threads.
1570            // After pausing, the MixerThread may go idle, thus the mTime estimate may
1571            // become stale. Assuming that the MixerThread runs 20ms, with FastMixer at 5ms,
1572            // the max latency should be about 25ms with an average around 12ms (to be verified).
1573            // For safety we use 100ms.
1574            ALOGV("getTimestamp: returned stale timestamp nowUs(%lld) numFramesPlayedAt(%lld)",
1575                    (long long)nowUs, (long long)numFramesPlayedAt);
1576            numFramesPlayedAt = nowUs - kStaleTimestamp100ms;
1577        }
1578        //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1579    } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1580        numFramesPlayed = 0;
1581        numFramesPlayedAt = nowUs;
1582        //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
1583        //        numFramesPlayed, (long long)numFramesPlayedAt);
1584    } else {                         // case 3: transitory at new track or audio fast tracks.
1585        res = mAudioSink->getPosition(&numFramesPlayed);
1586        CHECK_EQ(res, (status_t)OK);
1587        numFramesPlayedAt = nowUs;
1588        numFramesPlayedAt += 1000LL * mAudioSink->latency() / 2; /* XXX */
1589        //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1590    }
1591
1592    //CHECK_EQ(numFramesPlayed & (1 << 31), 0);  // can't be negative until 12.4 hrs, test
1593    int64_t durationUs = getDurationUsIfPlayedAtSampleRate(numFramesPlayed)
1594            + nowUs - numFramesPlayedAt;
1595    if (durationUs < 0) {
1596        // Occurs when numFramesPlayed position is very small and the following:
1597        // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
1598        //     numFramesPlayedAt is greater than nowUs by time more than numFramesPlayed.
1599        // (2) In case 3, using getPosition and adding mAudioSink->latency() to
1600        //     numFramesPlayedAt, by a time amount greater than numFramesPlayed.
1601        //
1602        // Both of these are transitory conditions.
1603        ALOGV("getPlayedOutAudioDurationUs: negative duration %lld set to zero", (long long)durationUs);
1604        durationUs = 0;
1605    }
1606    ALOGV("getPlayedOutAudioDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
1607            (long long)durationUs, (long long)nowUs, numFramesPlayed, (long long)numFramesPlayedAt);
1608    return durationUs;
1609}
1610
1611void NuPlayer::Renderer::onAudioTearDown(AudioTearDownReason reason) {
1612    if (mAudioTornDown) {
1613        return;
1614    }
1615    mAudioTornDown = true;
1616
1617    int64_t currentPositionUs;
1618    sp<AMessage> notify = mNotify->dup();
1619    if (getCurrentPosition(&currentPositionUs) == OK) {
1620        notify->setInt64("positionUs", currentPositionUs);
1621    }
1622
1623    mAudioSink->stop();
1624    mAudioSink->flush();
1625
1626    notify->setInt32("what", kWhatAudioTearDown);
1627    notify->setInt32("reason", reason);
1628    notify->post();
1629}
1630
1631void NuPlayer::Renderer::startAudioOffloadPauseTimeout() {
1632    if (offloadingAudio()) {
1633        mWakeLock->acquire();
1634        sp<AMessage> msg = new AMessage(kWhatAudioOffloadPauseTimeout, this);
1635        msg->setInt32("drainGeneration", mAudioOffloadPauseTimeoutGeneration);
1636        msg->post(kOffloadPauseMaxUs);
1637    }
1638}
1639
1640void NuPlayer::Renderer::cancelAudioOffloadPauseTimeout() {
1641    if (offloadingAudio()) {
1642        mWakeLock->release(true);
1643        ++mAudioOffloadPauseTimeoutGeneration;
1644    }
1645}
1646
1647status_t NuPlayer::Renderer::onOpenAudioSink(
1648        const sp<AMessage> &format,
1649        bool offloadOnly,
1650        bool hasVideo,
1651        uint32_t flags) {
1652    ALOGV("openAudioSink: offloadOnly(%d) offloadingAudio(%d)",
1653            offloadOnly, offloadingAudio());
1654    bool audioSinkChanged = false;
1655
1656    int32_t numChannels;
1657    CHECK(format->findInt32("channel-count", &numChannels));
1658
1659    int32_t channelMask;
1660    if (!format->findInt32("channel-mask", &channelMask)) {
1661        // signal to the AudioSink to derive the mask from count.
1662        channelMask = CHANNEL_MASK_USE_CHANNEL_ORDER;
1663    }
1664
1665    int32_t sampleRate;
1666    CHECK(format->findInt32("sample-rate", &sampleRate));
1667
1668    if (offloadingAudio()) {
1669        audio_format_t audioFormat = AUDIO_FORMAT_PCM_16_BIT;
1670        AString mime;
1671        CHECK(format->findString("mime", &mime));
1672        status_t err = mapMimeToAudioFormat(audioFormat, mime.c_str());
1673
1674        if (err != OK) {
1675            ALOGE("Couldn't map mime \"%s\" to a valid "
1676                    "audio_format", mime.c_str());
1677            onDisableOffloadAudio();
1678        } else {
1679            ALOGV("Mime \"%s\" mapped to audio_format 0x%x",
1680                    mime.c_str(), audioFormat);
1681
1682            int avgBitRate = -1;
1683            format->findInt32("bit-rate", &avgBitRate);
1684
1685            int32_t aacProfile = -1;
1686            if (audioFormat == AUDIO_FORMAT_AAC
1687                    && format->findInt32("aac-profile", &aacProfile)) {
1688                // Redefine AAC format as per aac profile
1689                mapAACProfileToAudioFormat(
1690                        audioFormat,
1691                        aacProfile);
1692            }
1693
1694            audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
1695            offloadInfo.duration_us = -1;
1696            format->findInt64(
1697                    "durationUs", &offloadInfo.duration_us);
1698            offloadInfo.sample_rate = sampleRate;
1699            offloadInfo.channel_mask = channelMask;
1700            offloadInfo.format = audioFormat;
1701            offloadInfo.stream_type = AUDIO_STREAM_MUSIC;
1702            offloadInfo.bit_rate = avgBitRate;
1703            offloadInfo.has_video = hasVideo;
1704            offloadInfo.is_streaming = true;
1705
1706            if (memcmp(&mCurrentOffloadInfo, &offloadInfo, sizeof(offloadInfo)) == 0) {
1707                ALOGV("openAudioSink: no change in offload mode");
1708                // no change from previous configuration, everything ok.
1709                return OK;
1710            }
1711            mCurrentPcmInfo = AUDIO_PCMINFO_INITIALIZER;
1712
1713            ALOGV("openAudioSink: try to open AudioSink in offload mode");
1714            uint32_t offloadFlags = flags;
1715            offloadFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
1716            offloadFlags &= ~AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1717            audioSinkChanged = true;
1718            mAudioSink->close();
1719
1720            err = mAudioSink->open(
1721                    sampleRate,
1722                    numChannels,
1723                    (audio_channel_mask_t)channelMask,
1724                    audioFormat,
1725                    0 /* bufferCount - unused */,
1726                    &NuPlayer::Renderer::AudioSinkCallback,
1727                    this,
1728                    (audio_output_flags_t)offloadFlags,
1729                    &offloadInfo);
1730
1731            if (err == OK) {
1732                err = mAudioSink->setPlaybackRate(mPlaybackSettings);
1733            }
1734
1735            if (err == OK) {
1736                // If the playback is offloaded to h/w, we pass
1737                // the HAL some metadata information.
1738                // We don't want to do this for PCM because it
1739                // will be going through the AudioFlinger mixer
1740                // before reaching the hardware.
1741                // TODO
1742                mCurrentOffloadInfo = offloadInfo;
1743                if (!mPaused) { // for preview mode, don't start if paused
1744                    err = mAudioSink->start();
1745                }
1746                ALOGV_IF(err == OK, "openAudioSink: offload succeeded");
1747            }
1748            if (err != OK) {
1749                // Clean up, fall back to non offload mode.
1750                mAudioSink->close();
1751                onDisableOffloadAudio();
1752                mCurrentOffloadInfo = AUDIO_INFO_INITIALIZER;
1753                ALOGV("openAudioSink: offload failed");
1754            } else {
1755                mUseAudioCallback = true;  // offload mode transfers data through callback
1756                ++mAudioDrainGeneration;  // discard pending kWhatDrainAudioQueue message.
1757            }
1758        }
1759    }
1760    if (!offloadOnly && !offloadingAudio()) {
1761        ALOGV("openAudioSink: open AudioSink in NON-offload mode");
1762        uint32_t pcmFlags = flags;
1763        pcmFlags &= ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
1764
1765        const PcmInfo info = {
1766                (audio_channel_mask_t)channelMask,
1767                (audio_output_flags_t)pcmFlags,
1768                AUDIO_FORMAT_PCM_16_BIT, // TODO: change to audioFormat
1769                numChannels,
1770                sampleRate
1771        };
1772        if (memcmp(&mCurrentPcmInfo, &info, sizeof(info)) == 0) {
1773            ALOGV("openAudioSink: no change in pcm mode");
1774            // no change from previous configuration, everything ok.
1775            return OK;
1776        }
1777
1778        audioSinkChanged = true;
1779        mAudioSink->close();
1780        mCurrentOffloadInfo = AUDIO_INFO_INITIALIZER;
1781        // Note: It is possible to set up the callback, but not use it to send audio data.
1782        // This requires a fix in AudioSink to explicitly specify the transfer mode.
1783        mUseAudioCallback = getUseAudioCallbackSetting();
1784        if (mUseAudioCallback) {
1785            ++mAudioDrainGeneration;  // discard pending kWhatDrainAudioQueue message.
1786        }
1787
1788        // Compute the desired buffer size.
1789        // For callback mode, the amount of time before wakeup is about half the buffer size.
1790        const uint32_t frameCount =
1791                (unsigned long long)sampleRate * getAudioSinkPcmMsSetting() / 1000;
1792
1793        // The doNotReconnect means AudioSink will signal back and let NuPlayer to re-construct
1794        // AudioSink. We don't want this when there's video because it will cause a video seek to
1795        // the previous I frame. But we do want this when there's only audio because it will give
1796        // NuPlayer a chance to switch from non-offload mode to offload mode.
1797        // So we only set doNotReconnect when there's no video.
1798        const bool doNotReconnect = !hasVideo;
1799        status_t err = mAudioSink->open(
1800                    sampleRate,
1801                    numChannels,
1802                    (audio_channel_mask_t)channelMask,
1803                    AUDIO_FORMAT_PCM_16_BIT,
1804                    0 /* bufferCount - unused */,
1805                    mUseAudioCallback ? &NuPlayer::Renderer::AudioSinkCallback : NULL,
1806                    mUseAudioCallback ? this : NULL,
1807                    (audio_output_flags_t)pcmFlags,
1808                    NULL,
1809                    doNotReconnect,
1810                    frameCount);
1811        if (err == OK) {
1812            err = mAudioSink->setPlaybackRate(mPlaybackSettings);
1813        }
1814        if (err != OK) {
1815            ALOGW("openAudioSink: non offloaded open failed status: %d", err);
1816            mAudioSink->close();
1817            mCurrentPcmInfo = AUDIO_PCMINFO_INITIALIZER;
1818            return err;
1819        }
1820        mCurrentPcmInfo = info;
1821        if (!mPaused) { // for preview mode, don't start if paused
1822            mAudioSink->start();
1823        }
1824    }
1825    if (audioSinkChanged) {
1826        onAudioSinkChanged();
1827    }
1828    mAudioTornDown = false;
1829    return OK;
1830}
1831
1832void NuPlayer::Renderer::onCloseAudioSink() {
1833    mAudioSink->close();
1834    mCurrentOffloadInfo = AUDIO_INFO_INITIALIZER;
1835    mCurrentPcmInfo = AUDIO_PCMINFO_INITIALIZER;
1836}
1837
1838}  // namespace android
1839
1840