VirtualDisplaySurface.cpp revision e5b755a045f4203fdd989047441259893c6fbe2d
1/*
2 * Copyright 2013 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#include "VirtualDisplaySurface.h"
19#include "HWComposer.h"
20
21#include <gui/BufferItem.h>
22
23// ---------------------------------------------------------------------------
24namespace android {
25// ---------------------------------------------------------------------------
26
27#if defined(FORCE_HWC_COPY_FOR_VIRTUAL_DISPLAYS)
28static const bool sForceHwcCopy = true;
29#else
30static const bool sForceHwcCopy = false;
31#endif
32
33#define VDS_LOGE(msg, ...) ALOGE("[%s] " msg, \
34        mDisplayName.string(), ##__VA_ARGS__)
35#define VDS_LOGW_IF(cond, msg, ...) ALOGW_IF(cond, "[%s] " msg, \
36        mDisplayName.string(), ##__VA_ARGS__)
37#define VDS_LOGV(msg, ...) ALOGV("[%s] " msg, \
38        mDisplayName.string(), ##__VA_ARGS__)
39
40static const char* dbgCompositionTypeStr(DisplaySurface::CompositionType type) {
41    switch (type) {
42        case DisplaySurface::COMPOSITION_UNKNOWN: return "UNKNOWN";
43        case DisplaySurface::COMPOSITION_GLES:    return "GLES";
44        case DisplaySurface::COMPOSITION_HWC:     return "HWC";
45        case DisplaySurface::COMPOSITION_MIXED:   return "MIXED";
46        default:                                  return "<INVALID>";
47    }
48}
49
50VirtualDisplaySurface::VirtualDisplaySurface(HWComposer& hwc, int32_t dispId,
51        const sp<IGraphicBufferProducer>& sink,
52        const sp<IGraphicBufferProducer>& bqProducer,
53        const sp<IGraphicBufferConsumer>& bqConsumer,
54        const String8& name)
55:   ConsumerBase(bqConsumer),
56    mHwc(hwc),
57    mDisplayId(dispId),
58    mDisplayName(name),
59    mOutputUsage(GRALLOC_USAGE_HW_COMPOSER),
60    mProducerSlotSource(0),
61    mDbgState(DBG_STATE_IDLE),
62    mDbgLastCompositionType(COMPOSITION_UNKNOWN),
63    mMustRecompose(false)
64{
65    mSource[SOURCE_SINK] = sink;
66    mSource[SOURCE_SCRATCH] = bqProducer;
67
68    resetPerFrameState();
69
70    int sinkWidth, sinkHeight;
71    sink->query(NATIVE_WINDOW_WIDTH, &sinkWidth);
72    sink->query(NATIVE_WINDOW_HEIGHT, &sinkHeight);
73    mSinkBufferWidth = sinkWidth;
74    mSinkBufferHeight = sinkHeight;
75
76    // Pick the buffer format to request from the sink when not rendering to it
77    // with GLES. If the consumer needs CPU access, use the default format
78    // set by the consumer. Otherwise allow gralloc to decide the format based
79    // on usage bits.
80    int sinkUsage;
81    sink->query(NATIVE_WINDOW_CONSUMER_USAGE_BITS, &sinkUsage);
82    if (sinkUsage & (GRALLOC_USAGE_SW_READ_MASK | GRALLOC_USAGE_SW_WRITE_MASK)) {
83        int sinkFormat;
84        sink->query(NATIVE_WINDOW_FORMAT, &sinkFormat);
85        mDefaultOutputFormat = sinkFormat;
86    } else {
87        mDefaultOutputFormat = HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
88    }
89    mOutputFormat = mDefaultOutputFormat;
90
91    ConsumerBase::mName = String8::format("VDS: %s", mDisplayName.string());
92    mConsumer->setConsumerName(ConsumerBase::mName);
93    mConsumer->setConsumerUsageBits(GRALLOC_USAGE_HW_COMPOSER);
94    mConsumer->setDefaultBufferSize(sinkWidth, sinkHeight);
95    mConsumer->setDefaultMaxBufferCount(2);
96}
97
98VirtualDisplaySurface::~VirtualDisplaySurface() {
99}
100
101status_t VirtualDisplaySurface::beginFrame(bool mustRecompose) {
102    if (mDisplayId < 0)
103        return NO_ERROR;
104
105    mMustRecompose = mustRecompose;
106
107    VDS_LOGW_IF(mDbgState != DBG_STATE_IDLE,
108            "Unexpected beginFrame() in %s state", dbgStateStr());
109    mDbgState = DBG_STATE_BEGUN;
110
111    return refreshOutputBuffer();
112}
113
114status_t VirtualDisplaySurface::prepareFrame(CompositionType compositionType) {
115    if (mDisplayId < 0)
116        return NO_ERROR;
117
118    VDS_LOGW_IF(mDbgState != DBG_STATE_BEGUN,
119            "Unexpected prepareFrame() in %s state", dbgStateStr());
120    mDbgState = DBG_STATE_PREPARED;
121
122    mCompositionType = compositionType;
123    if (sForceHwcCopy && mCompositionType == COMPOSITION_GLES) {
124        // Some hardware can do RGB->YUV conversion more efficiently in hardware
125        // controlled by HWC than in hardware controlled by the video encoder.
126        // Forcing GLES-composed frames to go through an extra copy by the HWC
127        // allows the format conversion to happen there, rather than passing RGB
128        // directly to the consumer.
129        //
130        // On the other hand, when the consumer prefers RGB or can consume RGB
131        // inexpensively, this forces an unnecessary copy.
132        mCompositionType = COMPOSITION_MIXED;
133    }
134
135    if (mCompositionType != mDbgLastCompositionType) {
136        VDS_LOGV("prepareFrame: composition type changed to %s",
137                dbgCompositionTypeStr(mCompositionType));
138        mDbgLastCompositionType = mCompositionType;
139    }
140
141    if (mCompositionType != COMPOSITION_GLES &&
142            (mOutputFormat != mDefaultOutputFormat ||
143             mOutputUsage != GRALLOC_USAGE_HW_COMPOSER)) {
144        // We must have just switched from GLES-only to MIXED or HWC
145        // composition. Stop using the format and usage requested by the GLES
146        // driver; they may be suboptimal when HWC is writing to the output
147        // buffer. For example, if the output is going to a video encoder, and
148        // HWC can write directly to YUV, some hardware can skip a
149        // memory-to-memory RGB-to-YUV conversion step.
150        //
151        // If we just switched *to* GLES-only mode, we'll change the
152        // format/usage and get a new buffer when the GLES driver calls
153        // dequeueBuffer().
154        mOutputFormat = mDefaultOutputFormat;
155        mOutputUsage = GRALLOC_USAGE_HW_COMPOSER;
156        refreshOutputBuffer();
157    }
158
159    return NO_ERROR;
160}
161
162status_t VirtualDisplaySurface::compositionComplete() {
163    return NO_ERROR;
164}
165
166status_t VirtualDisplaySurface::advanceFrame() {
167    if (mDisplayId < 0)
168        return NO_ERROR;
169
170    if (mCompositionType == COMPOSITION_HWC) {
171        VDS_LOGW_IF(mDbgState != DBG_STATE_PREPARED,
172                "Unexpected advanceFrame() in %s state on HWC frame",
173                dbgStateStr());
174    } else {
175        VDS_LOGW_IF(mDbgState != DBG_STATE_GLES_DONE,
176                "Unexpected advanceFrame() in %s state on GLES/MIXED frame",
177                dbgStateStr());
178    }
179    mDbgState = DBG_STATE_HWC;
180
181    if (mOutputProducerSlot < 0 ||
182            (mCompositionType != COMPOSITION_HWC && mFbProducerSlot < 0)) {
183        // Last chance bailout if something bad happened earlier. For example,
184        // in a GLES configuration, if the sink disappears then dequeueBuffer
185        // will fail, the GLES driver won't queue a buffer, but SurfaceFlinger
186        // will soldier on. So we end up here without a buffer. There should
187        // be lots of scary messages in the log just before this.
188        VDS_LOGE("advanceFrame: no buffer, bailing out");
189        return NO_MEMORY;
190    }
191
192    sp<GraphicBuffer> fbBuffer = mFbProducerSlot >= 0 ?
193            mProducerBuffers[mFbProducerSlot] : sp<GraphicBuffer>(NULL);
194    sp<GraphicBuffer> outBuffer = mProducerBuffers[mOutputProducerSlot];
195    VDS_LOGV("advanceFrame: fb=%d(%p) out=%d(%p)",
196            mFbProducerSlot, fbBuffer.get(),
197            mOutputProducerSlot, outBuffer.get());
198
199    // At this point we know the output buffer acquire fence,
200    // so update HWC state with it.
201    mHwc.setOutputBuffer(mDisplayId, mOutputFence, outBuffer);
202
203    status_t result = NO_ERROR;
204    if (fbBuffer != NULL) {
205        result = mHwc.fbPost(mDisplayId, mFbFence, fbBuffer);
206    }
207
208    return result;
209}
210
211void VirtualDisplaySurface::onFrameCommitted() {
212    if (mDisplayId < 0)
213        return;
214
215    VDS_LOGW_IF(mDbgState != DBG_STATE_HWC,
216            "Unexpected onFrameCommitted() in %s state", dbgStateStr());
217    mDbgState = DBG_STATE_IDLE;
218
219    sp<Fence> fbFence = mHwc.getAndResetReleaseFence(mDisplayId);
220    if (mCompositionType == COMPOSITION_MIXED && mFbProducerSlot >= 0) {
221        // release the scratch buffer back to the pool
222        Mutex::Autolock lock(mMutex);
223        int sslot = mapProducer2SourceSlot(SOURCE_SCRATCH, mFbProducerSlot);
224        VDS_LOGV("onFrameCommitted: release scratch sslot=%d", sslot);
225        addReleaseFenceLocked(sslot, mProducerBuffers[mFbProducerSlot], fbFence);
226        releaseBufferLocked(sslot, mProducerBuffers[mFbProducerSlot],
227                EGL_NO_DISPLAY, EGL_NO_SYNC_KHR);
228    }
229
230    if (mOutputProducerSlot >= 0) {
231        int sslot = mapProducer2SourceSlot(SOURCE_SINK, mOutputProducerSlot);
232        QueueBufferOutput qbo;
233        sp<Fence> outFence = mHwc.getLastRetireFence(mDisplayId);
234        VDS_LOGV("onFrameCommitted: queue sink sslot=%d", sslot);
235        if (mMustRecompose) {
236            status_t result = mSource[SOURCE_SINK]->queueBuffer(sslot,
237                    QueueBufferInput(
238                        systemTime(), false /* isAutoTimestamp */,
239                        HAL_DATASPACE_UNKNOWN,
240                        Rect(mSinkBufferWidth, mSinkBufferHeight),
241                        NATIVE_WINDOW_SCALING_MODE_FREEZE, 0 /* transform */,
242                        true /* async*/,
243                        outFence),
244                    &qbo);
245            if (result == NO_ERROR) {
246                updateQueueBufferOutput(qbo);
247            }
248        } else {
249            // If the surface hadn't actually been updated, then we only went
250            // through the motions of updating the display to keep our state
251            // machine happy. We cancel the buffer to avoid triggering another
252            // re-composition and causing an infinite loop.
253            mSource[SOURCE_SINK]->cancelBuffer(sslot, outFence);
254        }
255    }
256
257    resetPerFrameState();
258}
259
260void VirtualDisplaySurface::dumpAsString(String8& /* result */) const {
261}
262
263void VirtualDisplaySurface::resizeBuffers(const uint32_t w, const uint32_t h) {
264    uint32_t tmpW, tmpH, transformHint, numPendingBuffers;
265    mQueueBufferOutput.deflate(&tmpW, &tmpH, &transformHint, &numPendingBuffers);
266    mQueueBufferOutput.inflate(w, h, transformHint, numPendingBuffers);
267
268    mSinkBufferWidth = w;
269    mSinkBufferHeight = h;
270}
271
272status_t VirtualDisplaySurface::requestBuffer(int pslot,
273        sp<GraphicBuffer>* outBuf) {
274    if (mDisplayId < 0)
275        return mSource[SOURCE_SINK]->requestBuffer(pslot, outBuf);
276
277    VDS_LOGW_IF(mDbgState != DBG_STATE_GLES,
278            "Unexpected requestBuffer pslot=%d in %s state",
279            pslot, dbgStateStr());
280
281    *outBuf = mProducerBuffers[pslot];
282    return NO_ERROR;
283}
284
285status_t VirtualDisplaySurface::setMaxDequeuedBufferCount(
286        int maxDequeuedBuffers) {
287    return mSource[SOURCE_SINK]->setMaxDequeuedBufferCount(maxDequeuedBuffers);
288}
289
290status_t VirtualDisplaySurface::setAsyncMode(bool async) {
291    return mSource[SOURCE_SINK]->setAsyncMode(async);
292}
293
294status_t VirtualDisplaySurface::dequeueBuffer(Source source,
295        PixelFormat format, uint32_t usage, int* sslot, sp<Fence>* fence) {
296    LOG_FATAL_IF(mDisplayId < 0, "mDisplayId=%d but should not be < 0.", mDisplayId);
297    // Don't let a slow consumer block us
298    bool async = (source == SOURCE_SINK);
299
300    status_t result = mSource[source]->dequeueBuffer(sslot, fence, async,
301            mSinkBufferWidth, mSinkBufferHeight, format, usage);
302    if (result < 0)
303        return result;
304    int pslot = mapSource2ProducerSlot(source, *sslot);
305    VDS_LOGV("dequeueBuffer(%s): sslot=%d pslot=%d result=%d",
306            dbgSourceStr(source), *sslot, pslot, result);
307    uint64_t sourceBit = static_cast<uint64_t>(source) << pslot;
308
309    if ((mProducerSlotSource & (1ULL << pslot)) != sourceBit) {
310        // This slot was previously dequeued from the other source; must
311        // re-request the buffer.
312        result |= BUFFER_NEEDS_REALLOCATION;
313        mProducerSlotSource &= ~(1ULL << pslot);
314        mProducerSlotSource |= sourceBit;
315    }
316
317    if (result & RELEASE_ALL_BUFFERS) {
318        for (uint32_t i = 0; i < BufferQueue::NUM_BUFFER_SLOTS; i++) {
319            if ((mProducerSlotSource & (1ULL << i)) == sourceBit)
320                mProducerBuffers[i].clear();
321        }
322    }
323    if (result & BUFFER_NEEDS_REALLOCATION) {
324        result = mSource[source]->requestBuffer(*sslot, &mProducerBuffers[pslot]);
325        if (result < 0) {
326            mProducerBuffers[pslot].clear();
327            mSource[source]->cancelBuffer(*sslot, *fence);
328            return result;
329        }
330        VDS_LOGV("dequeueBuffer(%s): buffers[%d]=%p fmt=%d usage=%#x",
331                dbgSourceStr(source), pslot, mProducerBuffers[pslot].get(),
332                mProducerBuffers[pslot]->getPixelFormat(),
333                mProducerBuffers[pslot]->getUsage());
334    }
335
336    return result;
337}
338
339status_t VirtualDisplaySurface::dequeueBuffer(int* pslot, sp<Fence>* fence, bool async,
340        uint32_t w, uint32_t h, PixelFormat format, uint32_t usage) {
341    if (mDisplayId < 0)
342        return mSource[SOURCE_SINK]->dequeueBuffer(pslot, fence, async, w, h, format, usage);
343
344    VDS_LOGW_IF(mDbgState != DBG_STATE_PREPARED,
345            "Unexpected dequeueBuffer() in %s state", dbgStateStr());
346    mDbgState = DBG_STATE_GLES;
347
348    VDS_LOGW_IF(!async, "EGL called dequeueBuffer with !async despite eglSwapInterval(0)");
349    VDS_LOGV("dequeueBuffer %dx%d fmt=%d usage=%#x", w, h, format, usage);
350
351    status_t result = NO_ERROR;
352    Source source = fbSourceForCompositionType(mCompositionType);
353
354    if (source == SOURCE_SINK) {
355
356        if (mOutputProducerSlot < 0) {
357            // Last chance bailout if something bad happened earlier. For example,
358            // in a GLES configuration, if the sink disappears then dequeueBuffer
359            // will fail, the GLES driver won't queue a buffer, but SurfaceFlinger
360            // will soldier on. So we end up here without a buffer. There should
361            // be lots of scary messages in the log just before this.
362            VDS_LOGE("dequeueBuffer: no buffer, bailing out");
363            return NO_MEMORY;
364        }
365
366        // We already dequeued the output buffer. If the GLES driver wants
367        // something incompatible, we have to cancel and get a new one. This
368        // will mean that HWC will see a different output buffer between
369        // prepare and set, but since we're in GLES-only mode already it
370        // shouldn't matter.
371
372        usage |= GRALLOC_USAGE_HW_COMPOSER;
373        const sp<GraphicBuffer>& buf = mProducerBuffers[mOutputProducerSlot];
374        if ((usage & ~buf->getUsage()) != 0 ||
375                (format != 0 && format != buf->getPixelFormat()) ||
376                (w != 0 && w != mSinkBufferWidth) ||
377                (h != 0 && h != mSinkBufferHeight)) {
378            VDS_LOGV("dequeueBuffer: dequeueing new output buffer: "
379                    "want %dx%d fmt=%d use=%#x, "
380                    "have %dx%d fmt=%d use=%#x",
381                    w, h, format, usage,
382                    mSinkBufferWidth, mSinkBufferHeight,
383                    buf->getPixelFormat(), buf->getUsage());
384            mOutputFormat = format;
385            mOutputUsage = usage;
386            result = refreshOutputBuffer();
387            if (result < 0)
388                return result;
389        }
390    }
391
392    if (source == SOURCE_SINK) {
393        *pslot = mOutputProducerSlot;
394        *fence = mOutputFence;
395    } else {
396        int sslot;
397        result = dequeueBuffer(source, format, usage, &sslot, fence);
398        if (result >= 0) {
399            *pslot = mapSource2ProducerSlot(source, sslot);
400        }
401    }
402    return result;
403}
404
405status_t VirtualDisplaySurface::detachBuffer(int /* slot */) {
406    VDS_LOGE("detachBuffer is not available for VirtualDisplaySurface");
407    return INVALID_OPERATION;
408}
409
410status_t VirtualDisplaySurface::detachNextBuffer(
411        sp<GraphicBuffer>* /* outBuffer */, sp<Fence>* /* outFence */) {
412    VDS_LOGE("detachNextBuffer is not available for VirtualDisplaySurface");
413    return INVALID_OPERATION;
414}
415
416status_t VirtualDisplaySurface::attachBuffer(int* /* outSlot */,
417        const sp<GraphicBuffer>& /* buffer */) {
418    VDS_LOGE("attachBuffer is not available for VirtualDisplaySurface");
419    return INVALID_OPERATION;
420}
421
422status_t VirtualDisplaySurface::queueBuffer(int pslot,
423        const QueueBufferInput& input, QueueBufferOutput* output) {
424    if (mDisplayId < 0)
425        return mSource[SOURCE_SINK]->queueBuffer(pslot, input, output);
426
427    VDS_LOGW_IF(mDbgState != DBG_STATE_GLES,
428            "Unexpected queueBuffer(pslot=%d) in %s state", pslot,
429            dbgStateStr());
430    mDbgState = DBG_STATE_GLES_DONE;
431
432    VDS_LOGV("queueBuffer pslot=%d", pslot);
433
434    status_t result;
435    if (mCompositionType == COMPOSITION_MIXED) {
436        // Queue the buffer back into the scratch pool
437        QueueBufferOutput scratchQBO;
438        int sslot = mapProducer2SourceSlot(SOURCE_SCRATCH, pslot);
439        result = mSource[SOURCE_SCRATCH]->queueBuffer(sslot, input, &scratchQBO);
440        if (result != NO_ERROR)
441            return result;
442
443        // Now acquire the buffer from the scratch pool -- should be the same
444        // slot and fence as we just queued.
445        Mutex::Autolock lock(mMutex);
446        BufferItem item;
447        result = acquireBufferLocked(&item, 0);
448        if (result != NO_ERROR)
449            return result;
450        VDS_LOGW_IF(item.mBuf != sslot,
451                "queueBuffer: acquired sslot %d from SCRATCH after queueing sslot %d",
452                item.mBuf, sslot);
453        mFbProducerSlot = mapSource2ProducerSlot(SOURCE_SCRATCH, item.mBuf);
454        mFbFence = mSlots[item.mBuf].mFence;
455
456    } else {
457        LOG_FATAL_IF(mCompositionType != COMPOSITION_GLES,
458                "Unexpected queueBuffer in state %s for compositionType %s",
459                dbgStateStr(), dbgCompositionTypeStr(mCompositionType));
460
461        // Extract the GLES release fence for HWC to acquire
462        int64_t timestamp;
463        bool isAutoTimestamp;
464        android_dataspace dataSpace;
465        Rect crop;
466        int scalingMode;
467        uint32_t transform;
468        bool async;
469        input.deflate(&timestamp, &isAutoTimestamp, &dataSpace, &crop,
470                &scalingMode, &transform, &async, &mFbFence);
471
472        mFbProducerSlot = pslot;
473        mOutputFence = mFbFence;
474    }
475
476    *output = mQueueBufferOutput;
477    return NO_ERROR;
478}
479
480void VirtualDisplaySurface::cancelBuffer(int pslot, const sp<Fence>& fence) {
481    if (mDisplayId < 0)
482        return mSource[SOURCE_SINK]->cancelBuffer(mapProducer2SourceSlot(SOURCE_SINK, pslot), fence);
483
484    VDS_LOGW_IF(mDbgState != DBG_STATE_GLES,
485            "Unexpected cancelBuffer(pslot=%d) in %s state", pslot,
486            dbgStateStr());
487    VDS_LOGV("cancelBuffer pslot=%d", pslot);
488    Source source = fbSourceForCompositionType(mCompositionType);
489    return mSource[source]->cancelBuffer(
490            mapProducer2SourceSlot(source, pslot), fence);
491}
492
493int VirtualDisplaySurface::query(int what, int* value) {
494    switch (what) {
495        case NATIVE_WINDOW_WIDTH:
496            *value = mSinkBufferWidth;
497            break;
498        case NATIVE_WINDOW_HEIGHT:
499            *value = mSinkBufferHeight;
500            break;
501        default:
502            return mSource[SOURCE_SINK]->query(what, value);
503    }
504    return NO_ERROR;
505}
506
507status_t VirtualDisplaySurface::connect(const sp<IProducerListener>& listener,
508        int api, bool producerControlledByApp,
509        QueueBufferOutput* output) {
510    QueueBufferOutput qbo;
511    status_t result = mSource[SOURCE_SINK]->connect(listener, api,
512            producerControlledByApp, &qbo);
513    if (result == NO_ERROR) {
514        updateQueueBufferOutput(qbo);
515        *output = mQueueBufferOutput;
516    }
517    return result;
518}
519
520status_t VirtualDisplaySurface::disconnect(int api) {
521    return mSource[SOURCE_SINK]->disconnect(api);
522}
523
524status_t VirtualDisplaySurface::setSidebandStream(const sp<NativeHandle>& /*stream*/) {
525    return INVALID_OPERATION;
526}
527
528void VirtualDisplaySurface::allocateBuffers(bool /* async */,
529        uint32_t /* width */, uint32_t /* height */, PixelFormat /* format */,
530        uint32_t /* usage */) {
531    // TODO: Should we actually allocate buffers for a virtual display?
532}
533
534status_t VirtualDisplaySurface::allowAllocation(bool /* allow */) {
535    return INVALID_OPERATION;
536}
537
538status_t VirtualDisplaySurface::setGenerationNumber(uint32_t /* generation */) {
539    ALOGE("setGenerationNumber not supported on VirtualDisplaySurface");
540    return INVALID_OPERATION;
541}
542
543String8 VirtualDisplaySurface::getConsumerName() const {
544    return String8("VirtualDisplaySurface");
545}
546
547void VirtualDisplaySurface::updateQueueBufferOutput(
548        const QueueBufferOutput& qbo) {
549    uint32_t w, h, transformHint, numPendingBuffers;
550    qbo.deflate(&w, &h, &transformHint, &numPendingBuffers);
551    mQueueBufferOutput.inflate(w, h, 0, numPendingBuffers);
552}
553
554void VirtualDisplaySurface::resetPerFrameState() {
555    mCompositionType = COMPOSITION_UNKNOWN;
556    mFbFence = Fence::NO_FENCE;
557    mOutputFence = Fence::NO_FENCE;
558    mOutputProducerSlot = -1;
559    mFbProducerSlot = -1;
560}
561
562status_t VirtualDisplaySurface::refreshOutputBuffer() {
563    if (mOutputProducerSlot >= 0) {
564        mSource[SOURCE_SINK]->cancelBuffer(
565                mapProducer2SourceSlot(SOURCE_SINK, mOutputProducerSlot),
566                mOutputFence);
567    }
568
569    int sslot;
570    status_t result = dequeueBuffer(SOURCE_SINK, mOutputFormat, mOutputUsage,
571            &sslot, &mOutputFence);
572    if (result < 0)
573        return result;
574    mOutputProducerSlot = mapSource2ProducerSlot(SOURCE_SINK, sslot);
575
576    // On GLES-only frames, we don't have the right output buffer acquire fence
577    // until after GLES calls queueBuffer(). So here we just set the buffer
578    // (for use in HWC prepare) but not the fence; we'll call this again with
579    // the proper fence once we have it.
580    result = mHwc.setOutputBuffer(mDisplayId, Fence::NO_FENCE,
581            mProducerBuffers[mOutputProducerSlot]);
582
583    return result;
584}
585
586// This slot mapping function is its own inverse, so two copies are unnecessary.
587// Both are kept to make the intent clear where the function is called, and for
588// the (unlikely) chance that we switch to a different mapping function.
589int VirtualDisplaySurface::mapSource2ProducerSlot(Source source, int sslot) {
590    if (source == SOURCE_SCRATCH) {
591        return BufferQueue::NUM_BUFFER_SLOTS - sslot - 1;
592    } else {
593        return sslot;
594    }
595}
596int VirtualDisplaySurface::mapProducer2SourceSlot(Source source, int pslot) {
597    return mapSource2ProducerSlot(source, pslot);
598}
599
600VirtualDisplaySurface::Source
601VirtualDisplaySurface::fbSourceForCompositionType(CompositionType type) {
602    return type == COMPOSITION_MIXED ? SOURCE_SCRATCH : SOURCE_SINK;
603}
604
605const char* VirtualDisplaySurface::dbgStateStr() const {
606    switch (mDbgState) {
607        case DBG_STATE_IDLE:      return "IDLE";
608        case DBG_STATE_PREPARED:  return "PREPARED";
609        case DBG_STATE_GLES:      return "GLES";
610        case DBG_STATE_GLES_DONE: return "GLES_DONE";
611        case DBG_STATE_HWC:       return "HWC";
612        default:                  return "INVALID";
613    }
614}
615
616const char* VirtualDisplaySurface::dbgSourceStr(Source s) {
617    switch (s) {
618        case SOURCE_SINK:    return "SINK";
619        case SOURCE_SCRATCH: return "SCRATCH";
620        default:             return "INVALID";
621    }
622}
623
624// ---------------------------------------------------------------------------
625} // namespace android
626// ---------------------------------------------------------------------------
627