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