VirtualDisplaySurface.cpp revision 7dde599bf1a0dbef7390d91c2689d506371cdbd7
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    sink->setAsyncMode(true);
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                        outFence),
243                    &qbo);
244            if (result == NO_ERROR) {
245                updateQueueBufferOutput(qbo);
246            }
247        } else {
248            // If the surface hadn't actually been updated, then we only went
249            // through the motions of updating the display to keep our state
250            // machine happy. We cancel the buffer to avoid triggering another
251            // re-composition and causing an infinite loop.
252            mSource[SOURCE_SINK]->cancelBuffer(sslot, outFence);
253        }
254    }
255
256    resetPerFrameState();
257}
258
259void VirtualDisplaySurface::dumpAsString(String8& /* result */) const {
260}
261
262void VirtualDisplaySurface::resizeBuffers(const uint32_t w, const uint32_t h) {
263    uint32_t tmpW, tmpH, transformHint, numPendingBuffers;
264    mQueueBufferOutput.deflate(&tmpW, &tmpH, &transformHint, &numPendingBuffers);
265    mQueueBufferOutput.inflate(w, h, transformHint, numPendingBuffers);
266
267    mSinkBufferWidth = w;
268    mSinkBufferHeight = h;
269}
270
271status_t VirtualDisplaySurface::requestBuffer(int pslot,
272        sp<GraphicBuffer>* outBuf) {
273    if (mDisplayId < 0)
274        return mSource[SOURCE_SINK]->requestBuffer(pslot, outBuf);
275
276    VDS_LOGW_IF(mDbgState != DBG_STATE_GLES,
277            "Unexpected requestBuffer pslot=%d in %s state",
278            pslot, dbgStateStr());
279
280    *outBuf = mProducerBuffers[pslot];
281    return NO_ERROR;
282}
283
284status_t VirtualDisplaySurface::setMaxDequeuedBufferCount(
285        int maxDequeuedBuffers) {
286    return mSource[SOURCE_SINK]->setMaxDequeuedBufferCount(maxDequeuedBuffers);
287}
288
289status_t VirtualDisplaySurface::setAsyncMode(bool async) {
290    return mSource[SOURCE_SINK]->setAsyncMode(async);
291}
292
293status_t VirtualDisplaySurface::dequeueBuffer(Source source,
294        PixelFormat format, uint32_t usage, int* sslot, sp<Fence>* fence) {
295    LOG_FATAL_IF(mDisplayId < 0, "mDisplayId=%d but should not be < 0.", mDisplayId);
296
297    status_t result = mSource[source]->dequeueBuffer(sslot, fence,
298            mSinkBufferWidth, mSinkBufferHeight, format, usage);
299    if (result < 0)
300        return result;
301    int pslot = mapSource2ProducerSlot(source, *sslot);
302    VDS_LOGV("dequeueBuffer(%s): sslot=%d pslot=%d result=%d",
303            dbgSourceStr(source), *sslot, pslot, result);
304    uint64_t sourceBit = static_cast<uint64_t>(source) << pslot;
305
306    if ((mProducerSlotSource & (1ULL << pslot)) != sourceBit) {
307        // This slot was previously dequeued from the other source; must
308        // re-request the buffer.
309        result |= BUFFER_NEEDS_REALLOCATION;
310        mProducerSlotSource &= ~(1ULL << pslot);
311        mProducerSlotSource |= sourceBit;
312    }
313
314    if (result & RELEASE_ALL_BUFFERS) {
315        for (uint32_t i = 0; i < BufferQueue::NUM_BUFFER_SLOTS; i++) {
316            if ((mProducerSlotSource & (1ULL << i)) == sourceBit)
317                mProducerBuffers[i].clear();
318        }
319    }
320    if (result & BUFFER_NEEDS_REALLOCATION) {
321        result = mSource[source]->requestBuffer(*sslot, &mProducerBuffers[pslot]);
322        if (result < 0) {
323            mProducerBuffers[pslot].clear();
324            mSource[source]->cancelBuffer(*sslot, *fence);
325            return result;
326        }
327        VDS_LOGV("dequeueBuffer(%s): buffers[%d]=%p fmt=%d usage=%#x",
328                dbgSourceStr(source), pslot, mProducerBuffers[pslot].get(),
329                mProducerBuffers[pslot]->getPixelFormat(),
330                mProducerBuffers[pslot]->getUsage());
331    }
332
333    return result;
334}
335
336status_t VirtualDisplaySurface::dequeueBuffer(int* pslot, sp<Fence>* fence,
337        uint32_t w, uint32_t h, PixelFormat format, uint32_t usage) {
338    if (mDisplayId < 0)
339        return mSource[SOURCE_SINK]->dequeueBuffer(pslot, fence, w, h, format, usage);
340
341    VDS_LOGW_IF(mDbgState != DBG_STATE_PREPARED,
342            "Unexpected dequeueBuffer() in %s state", dbgStateStr());
343    mDbgState = DBG_STATE_GLES;
344
345    VDS_LOGV("dequeueBuffer %dx%d fmt=%d usage=%#x", w, h, format, usage);
346
347    status_t result = NO_ERROR;
348    Source source = fbSourceForCompositionType(mCompositionType);
349
350    if (source == SOURCE_SINK) {
351
352        if (mOutputProducerSlot < 0) {
353            // Last chance bailout if something bad happened earlier. For example,
354            // in a GLES configuration, if the sink disappears then dequeueBuffer
355            // will fail, the GLES driver won't queue a buffer, but SurfaceFlinger
356            // will soldier on. So we end up here without a buffer. There should
357            // be lots of scary messages in the log just before this.
358            VDS_LOGE("dequeueBuffer: no buffer, bailing out");
359            return NO_MEMORY;
360        }
361
362        // We already dequeued the output buffer. If the GLES driver wants
363        // something incompatible, we have to cancel and get a new one. This
364        // will mean that HWC will see a different output buffer between
365        // prepare and set, but since we're in GLES-only mode already it
366        // shouldn't matter.
367
368        usage |= GRALLOC_USAGE_HW_COMPOSER;
369        const sp<GraphicBuffer>& buf = mProducerBuffers[mOutputProducerSlot];
370        if ((usage & ~buf->getUsage()) != 0 ||
371                (format != 0 && format != buf->getPixelFormat()) ||
372                (w != 0 && w != mSinkBufferWidth) ||
373                (h != 0 && h != mSinkBufferHeight)) {
374            VDS_LOGV("dequeueBuffer: dequeueing new output buffer: "
375                    "want %dx%d fmt=%d use=%#x, "
376                    "have %dx%d fmt=%d use=%#x",
377                    w, h, format, usage,
378                    mSinkBufferWidth, mSinkBufferHeight,
379                    buf->getPixelFormat(), buf->getUsage());
380            mOutputFormat = format;
381            mOutputUsage = usage;
382            result = refreshOutputBuffer();
383            if (result < 0)
384                return result;
385        }
386    }
387
388    if (source == SOURCE_SINK) {
389        *pslot = mOutputProducerSlot;
390        *fence = mOutputFence;
391    } else {
392        int sslot;
393        result = dequeueBuffer(source, format, usage, &sslot, fence);
394        if (result >= 0) {
395            *pslot = mapSource2ProducerSlot(source, sslot);
396        }
397    }
398    return result;
399}
400
401status_t VirtualDisplaySurface::detachBuffer(int /* slot */) {
402    VDS_LOGE("detachBuffer is not available for VirtualDisplaySurface");
403    return INVALID_OPERATION;
404}
405
406status_t VirtualDisplaySurface::detachNextBuffer(
407        sp<GraphicBuffer>* /* outBuffer */, sp<Fence>* /* outFence */) {
408    VDS_LOGE("detachNextBuffer is not available for VirtualDisplaySurface");
409    return INVALID_OPERATION;
410}
411
412status_t VirtualDisplaySurface::attachBuffer(int* /* outSlot */,
413        const sp<GraphicBuffer>& /* buffer */) {
414    VDS_LOGE("attachBuffer is not available for VirtualDisplaySurface");
415    return INVALID_OPERATION;
416}
417
418status_t VirtualDisplaySurface::queueBuffer(int pslot,
419        const QueueBufferInput& input, QueueBufferOutput* output) {
420    if (mDisplayId < 0)
421        return mSource[SOURCE_SINK]->queueBuffer(pslot, input, output);
422
423    VDS_LOGW_IF(mDbgState != DBG_STATE_GLES,
424            "Unexpected queueBuffer(pslot=%d) in %s state", pslot,
425            dbgStateStr());
426    mDbgState = DBG_STATE_GLES_DONE;
427
428    VDS_LOGV("queueBuffer pslot=%d", pslot);
429
430    status_t result;
431    if (mCompositionType == COMPOSITION_MIXED) {
432        // Queue the buffer back into the scratch pool
433        QueueBufferOutput scratchQBO;
434        int sslot = mapProducer2SourceSlot(SOURCE_SCRATCH, pslot);
435        result = mSource[SOURCE_SCRATCH]->queueBuffer(sslot, input, &scratchQBO);
436        if (result != NO_ERROR)
437            return result;
438
439        // Now acquire the buffer from the scratch pool -- should be the same
440        // slot and fence as we just queued.
441        Mutex::Autolock lock(mMutex);
442        BufferItem item;
443        result = acquireBufferLocked(&item, 0);
444        if (result != NO_ERROR)
445            return result;
446        VDS_LOGW_IF(item.mSlot != sslot,
447                "queueBuffer: acquired sslot %d from SCRATCH after queueing sslot %d",
448                item.mSlot, sslot);
449        mFbProducerSlot = mapSource2ProducerSlot(SOURCE_SCRATCH, item.mSlot);
450        mFbFence = mSlots[item.mSlot].mFence;
451
452    } else {
453        LOG_FATAL_IF(mCompositionType != COMPOSITION_GLES,
454                "Unexpected queueBuffer in state %s for compositionType %s",
455                dbgStateStr(), dbgCompositionTypeStr(mCompositionType));
456
457        // Extract the GLES release fence for HWC to acquire
458        int64_t timestamp;
459        bool isAutoTimestamp;
460        android_dataspace dataSpace;
461        Rect crop;
462        int scalingMode;
463        uint32_t transform;
464        input.deflate(&timestamp, &isAutoTimestamp, &dataSpace, &crop,
465                &scalingMode, &transform, &mFbFence);
466
467        mFbProducerSlot = pslot;
468        mOutputFence = mFbFence;
469    }
470
471    *output = mQueueBufferOutput;
472    return NO_ERROR;
473}
474
475status_t VirtualDisplaySurface::cancelBuffer(int pslot,
476        const sp<Fence>& fence) {
477    if (mDisplayId < 0)
478        return mSource[SOURCE_SINK]->cancelBuffer(mapProducer2SourceSlot(SOURCE_SINK, pslot), fence);
479
480    VDS_LOGW_IF(mDbgState != DBG_STATE_GLES,
481            "Unexpected cancelBuffer(pslot=%d) in %s state", pslot,
482            dbgStateStr());
483    VDS_LOGV("cancelBuffer pslot=%d", pslot);
484    Source source = fbSourceForCompositionType(mCompositionType);
485    return mSource[source]->cancelBuffer(
486            mapProducer2SourceSlot(source, pslot), fence);
487}
488
489int VirtualDisplaySurface::query(int what, int* value) {
490    switch (what) {
491        case NATIVE_WINDOW_WIDTH:
492            *value = mSinkBufferWidth;
493            break;
494        case NATIVE_WINDOW_HEIGHT:
495            *value = mSinkBufferHeight;
496            break;
497        default:
498            return mSource[SOURCE_SINK]->query(what, value);
499    }
500    return NO_ERROR;
501}
502
503status_t VirtualDisplaySurface::connect(const sp<IProducerListener>& listener,
504        int api, bool producerControlledByApp,
505        QueueBufferOutput* output) {
506    QueueBufferOutput qbo;
507    status_t result = mSource[SOURCE_SINK]->connect(listener, api,
508            producerControlledByApp, &qbo);
509    if (result == NO_ERROR) {
510        updateQueueBufferOutput(qbo);
511        *output = mQueueBufferOutput;
512    }
513    return result;
514}
515
516status_t VirtualDisplaySurface::disconnect(int api) {
517    return mSource[SOURCE_SINK]->disconnect(api);
518}
519
520status_t VirtualDisplaySurface::setSidebandStream(const sp<NativeHandle>& /*stream*/) {
521    return INVALID_OPERATION;
522}
523
524void VirtualDisplaySurface::allocateBuffers(uint32_t /* width */,
525        uint32_t /* height */, PixelFormat /* format */, uint32_t /* usage */) {
526    // TODO: Should we actually allocate buffers for a virtual display?
527}
528
529status_t VirtualDisplaySurface::allowAllocation(bool /* allow */) {
530    return INVALID_OPERATION;
531}
532
533status_t VirtualDisplaySurface::setGenerationNumber(uint32_t /* generation */) {
534    ALOGE("setGenerationNumber not supported on VirtualDisplaySurface");
535    return INVALID_OPERATION;
536}
537
538String8 VirtualDisplaySurface::getConsumerName() const {
539    return String8("VirtualDisplaySurface");
540}
541
542uint64_t VirtualDisplaySurface::getNextFrameNumber() const {
543    return 0;
544}
545
546void VirtualDisplaySurface::updateQueueBufferOutput(
547        const QueueBufferOutput& qbo) {
548    uint32_t w, h, transformHint, numPendingBuffers;
549    qbo.deflate(&w, &h, &transformHint, &numPendingBuffers);
550    mQueueBufferOutput.inflate(w, h, 0, numPendingBuffers);
551}
552
553void VirtualDisplaySurface::resetPerFrameState() {
554    mCompositionType = COMPOSITION_UNKNOWN;
555    mFbFence = Fence::NO_FENCE;
556    mOutputFence = Fence::NO_FENCE;
557    mOutputProducerSlot = -1;
558    mFbProducerSlot = -1;
559}
560
561status_t VirtualDisplaySurface::refreshOutputBuffer() {
562    if (mOutputProducerSlot >= 0) {
563        mSource[SOURCE_SINK]->cancelBuffer(
564                mapProducer2SourceSlot(SOURCE_SINK, mOutputProducerSlot),
565                mOutputFence);
566    }
567
568    int sslot;
569    status_t result = dequeueBuffer(SOURCE_SINK, mOutputFormat, mOutputUsage,
570            &sslot, &mOutputFence);
571    if (result < 0)
572        return result;
573    mOutputProducerSlot = mapSource2ProducerSlot(SOURCE_SINK, sslot);
574
575    // On GLES-only frames, we don't have the right output buffer acquire fence
576    // until after GLES calls queueBuffer(). So here we just set the buffer
577    // (for use in HWC prepare) but not the fence; we'll call this again with
578    // the proper fence once we have it.
579    result = mHwc.setOutputBuffer(mDisplayId, Fence::NO_FENCE,
580            mProducerBuffers[mOutputProducerSlot]);
581
582    return result;
583}
584
585// This slot mapping function is its own inverse, so two copies are unnecessary.
586// Both are kept to make the intent clear where the function is called, and for
587// the (unlikely) chance that we switch to a different mapping function.
588int VirtualDisplaySurface::mapSource2ProducerSlot(Source source, int sslot) {
589    if (source == SOURCE_SCRATCH) {
590        return BufferQueue::NUM_BUFFER_SLOTS - sslot - 1;
591    } else {
592        return sslot;
593    }
594}
595int VirtualDisplaySurface::mapProducer2SourceSlot(Source source, int pslot) {
596    return mapSource2ProducerSlot(source, pslot);
597}
598
599VirtualDisplaySurface::Source
600VirtualDisplaySurface::fbSourceForCompositionType(CompositionType type) {
601    return type == COMPOSITION_MIXED ? SOURCE_SCRATCH : SOURCE_SINK;
602}
603
604const char* VirtualDisplaySurface::dbgStateStr() const {
605    switch (mDbgState) {
606        case DBG_STATE_IDLE:      return "IDLE";
607        case DBG_STATE_PREPARED:  return "PREPARED";
608        case DBG_STATE_GLES:      return "GLES";
609        case DBG_STATE_GLES_DONE: return "GLES_DONE";
610        case DBG_STATE_HWC:       return "HWC";
611        default:                  return "INVALID";
612    }
613}
614
615const char* VirtualDisplaySurface::dbgSourceStr(Source s) {
616    switch (s) {
617        case SOURCE_SINK:    return "SINK";
618        case SOURCE_SCRATCH: return "SCRATCH";
619        default:             return "INVALID";
620    }
621}
622
623// ---------------------------------------------------------------------------
624} // namespace android
625// ---------------------------------------------------------------------------
626