VirtualDisplaySurface.cpp revision f133d003aaac80a0932a2d8f9efd8493e56f7814
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#include <gui/IProducerListener.h>
23
24// ---------------------------------------------------------------------------
25namespace android {
26// ---------------------------------------------------------------------------
27
28#if defined(FORCE_HWC_COPY_FOR_VIRTUAL_DISPLAYS)
29static const bool sForceHwcCopy = true;
30#else
31static const bool sForceHwcCopy = false;
32#endif
33
34#define VDS_LOGE(msg, ...) ALOGE("[%s] " msg, \
35        mDisplayName.string(), ##__VA_ARGS__)
36#define VDS_LOGW_IF(cond, msg, ...) ALOGW_IF(cond, "[%s] " msg, \
37        mDisplayName.string(), ##__VA_ARGS__)
38#define VDS_LOGV(msg, ...) ALOGV("[%s] " msg, \
39        mDisplayName.string(), ##__VA_ARGS__)
40
41static const char* dbgCompositionTypeStr(DisplaySurface::CompositionType type) {
42    switch (type) {
43        case DisplaySurface::COMPOSITION_UNKNOWN: return "UNKNOWN";
44        case DisplaySurface::COMPOSITION_GLES:    return "GLES";
45        case DisplaySurface::COMPOSITION_HWC:     return "HWC";
46        case DisplaySurface::COMPOSITION_MIXED:   return "MIXED";
47        default:                                  return "<INVALID>";
48    }
49}
50
51VirtualDisplaySurface::VirtualDisplaySurface(HWComposer& hwc, int32_t dispId,
52        const sp<IGraphicBufferProducer>& sink,
53        const sp<IGraphicBufferProducer>& bqProducer,
54        const sp<IGraphicBufferConsumer>& bqConsumer,
55        const String8& name)
56:   ConsumerBase(bqConsumer),
57    mHwc(hwc),
58    mDisplayId(dispId),
59    mDisplayName(name),
60    mOutputUsage(GRALLOC_USAGE_HW_COMPOSER),
61    mProducerSlotSource(0),
62    mDbgState(DBG_STATE_IDLE),
63    mDbgLastCompositionType(COMPOSITION_UNKNOWN),
64    mMustRecompose(false)
65{
66    mSource[SOURCE_SINK] = sink;
67    mSource[SOURCE_SCRATCH] = bqProducer;
68
69    resetPerFrameState();
70
71    int sinkWidth, sinkHeight;
72    sink->query(NATIVE_WINDOW_WIDTH, &sinkWidth);
73    sink->query(NATIVE_WINDOW_HEIGHT, &sinkHeight);
74    mSinkBufferWidth = sinkWidth;
75    mSinkBufferHeight = sinkHeight;
76
77    // Pick the buffer format to request from the sink when not rendering to it
78    // with GLES. If the consumer needs CPU access, use the default format
79    // set by the consumer. Otherwise allow gralloc to decide the format based
80    // on usage bits.
81    int sinkUsage;
82    sink->query(NATIVE_WINDOW_CONSUMER_USAGE_BITS, &sinkUsage);
83    if (sinkUsage & (GRALLOC_USAGE_SW_READ_MASK | GRALLOC_USAGE_SW_WRITE_MASK)) {
84        int sinkFormat;
85        sink->query(NATIVE_WINDOW_FORMAT, &sinkFormat);
86        mDefaultOutputFormat = sinkFormat;
87    } else {
88        mDefaultOutputFormat = HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
89    }
90    mOutputFormat = mDefaultOutputFormat;
91
92    ConsumerBase::mName = String8::format("VDS: %s", mDisplayName.string());
93    mConsumer->setConsumerName(ConsumerBase::mName);
94    mConsumer->setConsumerUsageBits(GRALLOC_USAGE_HW_COMPOSER);
95    mConsumer->setDefaultBufferSize(sinkWidth, sinkHeight);
96    sink->setAsyncMode(true);
97    IGraphicBufferProducer::QueueBufferOutput output;
98    mSource[SOURCE_SCRATCH]->connect(NULL, NATIVE_WINDOW_API_EGL, false, &output);
99}
100
101VirtualDisplaySurface::~VirtualDisplaySurface() {
102    mSource[SOURCE_SCRATCH]->disconnect(NATIVE_WINDOW_API_EGL);
103}
104
105status_t VirtualDisplaySurface::beginFrame(bool mustRecompose) {
106    if (mDisplayId < 0)
107        return NO_ERROR;
108
109    mMustRecompose = mustRecompose;
110
111    VDS_LOGW_IF(mDbgState != DBG_STATE_IDLE,
112            "Unexpected beginFrame() in %s state", dbgStateStr());
113    mDbgState = DBG_STATE_BEGUN;
114
115    return refreshOutputBuffer();
116}
117
118status_t VirtualDisplaySurface::prepareFrame(CompositionType compositionType) {
119    if (mDisplayId < 0)
120        return NO_ERROR;
121
122    VDS_LOGW_IF(mDbgState != DBG_STATE_BEGUN,
123            "Unexpected prepareFrame() in %s state", dbgStateStr());
124    mDbgState = DBG_STATE_PREPARED;
125
126    mCompositionType = compositionType;
127    if (sForceHwcCopy && mCompositionType == COMPOSITION_GLES) {
128        // Some hardware can do RGB->YUV conversion more efficiently in hardware
129        // controlled by HWC than in hardware controlled by the video encoder.
130        // Forcing GLES-composed frames to go through an extra copy by the HWC
131        // allows the format conversion to happen there, rather than passing RGB
132        // directly to the consumer.
133        //
134        // On the other hand, when the consumer prefers RGB or can consume RGB
135        // inexpensively, this forces an unnecessary copy.
136        mCompositionType = COMPOSITION_MIXED;
137    }
138
139    if (mCompositionType != mDbgLastCompositionType) {
140        VDS_LOGV("prepareFrame: composition type changed to %s",
141                dbgCompositionTypeStr(mCompositionType));
142        mDbgLastCompositionType = mCompositionType;
143    }
144
145    if (mCompositionType != COMPOSITION_GLES &&
146            (mOutputFormat != mDefaultOutputFormat ||
147             mOutputUsage != GRALLOC_USAGE_HW_COMPOSER)) {
148        // We must have just switched from GLES-only to MIXED or HWC
149        // composition. Stop using the format and usage requested by the GLES
150        // driver; they may be suboptimal when HWC is writing to the output
151        // buffer. For example, if the output is going to a video encoder, and
152        // HWC can write directly to YUV, some hardware can skip a
153        // memory-to-memory RGB-to-YUV conversion step.
154        //
155        // If we just switched *to* GLES-only mode, we'll change the
156        // format/usage and get a new buffer when the GLES driver calls
157        // dequeueBuffer().
158        mOutputFormat = mDefaultOutputFormat;
159        mOutputUsage = GRALLOC_USAGE_HW_COMPOSER;
160        refreshOutputBuffer();
161    }
162
163    return NO_ERROR;
164}
165
166status_t VirtualDisplaySurface::compositionComplete() {
167    return NO_ERROR;
168}
169
170status_t VirtualDisplaySurface::advanceFrame() {
171    if (mDisplayId < 0)
172        return NO_ERROR;
173
174    if (mCompositionType == COMPOSITION_HWC) {
175        VDS_LOGW_IF(mDbgState != DBG_STATE_PREPARED,
176                "Unexpected advanceFrame() in %s state on HWC frame",
177                dbgStateStr());
178    } else {
179        VDS_LOGW_IF(mDbgState != DBG_STATE_GLES_DONE,
180                "Unexpected advanceFrame() in %s state on GLES/MIXED frame",
181                dbgStateStr());
182    }
183    mDbgState = DBG_STATE_HWC;
184
185    if (mOutputProducerSlot < 0 ||
186            (mCompositionType != COMPOSITION_HWC && mFbProducerSlot < 0)) {
187        // Last chance bailout if something bad happened earlier. For example,
188        // in a GLES configuration, if the sink disappears then dequeueBuffer
189        // will fail, the GLES driver won't queue a buffer, but SurfaceFlinger
190        // will soldier on. So we end up here without a buffer. There should
191        // be lots of scary messages in the log just before this.
192        VDS_LOGE("advanceFrame: no buffer, bailing out");
193        return NO_MEMORY;
194    }
195
196    sp<GraphicBuffer> fbBuffer = mFbProducerSlot >= 0 ?
197            mProducerBuffers[mFbProducerSlot] : sp<GraphicBuffer>(NULL);
198    sp<GraphicBuffer> outBuffer = mProducerBuffers[mOutputProducerSlot];
199    VDS_LOGV("advanceFrame: fb=%d(%p) out=%d(%p)",
200            mFbProducerSlot, fbBuffer.get(),
201            mOutputProducerSlot, outBuffer.get());
202
203    // At this point we know the output buffer acquire fence,
204    // so update HWC state with it.
205    mHwc.setOutputBuffer(mDisplayId, mOutputFence, outBuffer);
206
207    status_t result = NO_ERROR;
208    if (fbBuffer != NULL) {
209        result = mHwc.fbPost(mDisplayId, mFbFence, fbBuffer);
210    }
211
212    return result;
213}
214
215void VirtualDisplaySurface::onFrameCommitted() {
216    if (mDisplayId < 0)
217        return;
218
219    VDS_LOGW_IF(mDbgState != DBG_STATE_HWC,
220            "Unexpected onFrameCommitted() in %s state", dbgStateStr());
221    mDbgState = DBG_STATE_IDLE;
222
223    sp<Fence> fbFence = mHwc.getAndResetReleaseFence(mDisplayId);
224    if (mCompositionType == COMPOSITION_MIXED && mFbProducerSlot >= 0) {
225        // release the scratch buffer back to the pool
226        Mutex::Autolock lock(mMutex);
227        int sslot = mapProducer2SourceSlot(SOURCE_SCRATCH, mFbProducerSlot);
228        VDS_LOGV("onFrameCommitted: release scratch sslot=%d", sslot);
229        addReleaseFenceLocked(sslot, mProducerBuffers[mFbProducerSlot], fbFence);
230        releaseBufferLocked(sslot, mProducerBuffers[mFbProducerSlot],
231                EGL_NO_DISPLAY, EGL_NO_SYNC_KHR);
232    }
233
234    if (mOutputProducerSlot >= 0) {
235        int sslot = mapProducer2SourceSlot(SOURCE_SINK, mOutputProducerSlot);
236        QueueBufferOutput qbo;
237        sp<Fence> outFence = mHwc.getLastRetireFence(mDisplayId);
238        VDS_LOGV("onFrameCommitted: queue sink sslot=%d", sslot);
239        if (mMustRecompose) {
240            status_t result = mSource[SOURCE_SINK]->queueBuffer(sslot,
241                    QueueBufferInput(
242                        systemTime(), false /* isAutoTimestamp */,
243                        HAL_DATASPACE_UNKNOWN,
244                        Rect(mSinkBufferWidth, mSinkBufferHeight),
245                        NATIVE_WINDOW_SCALING_MODE_FREEZE, 0 /* transform */,
246                        outFence),
247                    &qbo);
248            if (result == NO_ERROR) {
249                updateQueueBufferOutput(qbo);
250            }
251        } else {
252            // If the surface hadn't actually been updated, then we only went
253            // through the motions of updating the display to keep our state
254            // machine happy. We cancel the buffer to avoid triggering another
255            // re-composition and causing an infinite loop.
256            mSource[SOURCE_SINK]->cancelBuffer(sslot, outFence);
257        }
258    }
259
260    resetPerFrameState();
261}
262
263void VirtualDisplaySurface::dumpAsString(String8& /* result */) const {
264}
265
266void VirtualDisplaySurface::resizeBuffers(const uint32_t w, const uint32_t h) {
267    uint32_t tmpW, tmpH, transformHint, numPendingBuffers;
268    mQueueBufferOutput.deflate(&tmpW, &tmpH, &transformHint, &numPendingBuffers);
269    mQueueBufferOutput.inflate(w, h, transformHint, numPendingBuffers);
270
271    mSinkBufferWidth = w;
272    mSinkBufferHeight = h;
273}
274
275status_t VirtualDisplaySurface::requestBuffer(int pslot,
276        sp<GraphicBuffer>* outBuf) {
277    if (mDisplayId < 0)
278        return mSource[SOURCE_SINK]->requestBuffer(pslot, outBuf);
279
280    VDS_LOGW_IF(mDbgState != DBG_STATE_GLES,
281            "Unexpected requestBuffer pslot=%d in %s state",
282            pslot, dbgStateStr());
283
284    *outBuf = mProducerBuffers[pslot];
285    return NO_ERROR;
286}
287
288status_t VirtualDisplaySurface::setMaxDequeuedBufferCount(
289        int maxDequeuedBuffers) {
290    return mSource[SOURCE_SINK]->setMaxDequeuedBufferCount(maxDequeuedBuffers);
291}
292
293status_t VirtualDisplaySurface::setAsyncMode(bool async) {
294    return mSource[SOURCE_SINK]->setAsyncMode(async);
295}
296
297status_t VirtualDisplaySurface::dequeueBuffer(Source source,
298        PixelFormat format, uint32_t usage, int* sslot, sp<Fence>* fence) {
299    LOG_FATAL_IF(mDisplayId < 0, "mDisplayId=%d but should not be < 0.", mDisplayId);
300
301    status_t result = mSource[source]->dequeueBuffer(sslot, fence,
302            mSinkBufferWidth, mSinkBufferHeight, format, usage);
303    if (result < 0)
304        return result;
305    int pslot = mapSource2ProducerSlot(source, *sslot);
306    VDS_LOGV("dequeueBuffer(%s): sslot=%d pslot=%d result=%d",
307            dbgSourceStr(source), *sslot, pslot, result);
308    uint64_t sourceBit = static_cast<uint64_t>(source) << pslot;
309
310    if ((mProducerSlotSource & (1ULL << pslot)) != sourceBit) {
311        // This slot was previously dequeued from the other source; must
312        // re-request the buffer.
313        result |= BUFFER_NEEDS_REALLOCATION;
314        mProducerSlotSource &= ~(1ULL << pslot);
315        mProducerSlotSource |= sourceBit;
316    }
317
318    if (result & RELEASE_ALL_BUFFERS) {
319        for (uint32_t i = 0; i < BufferQueue::NUM_BUFFER_SLOTS; i++) {
320            if ((mProducerSlotSource & (1ULL << i)) == sourceBit)
321                mProducerBuffers[i].clear();
322        }
323    }
324    if (result & BUFFER_NEEDS_REALLOCATION) {
325        result = mSource[source]->requestBuffer(*sslot, &mProducerBuffers[pslot]);
326        if (result < 0) {
327            mProducerBuffers[pslot].clear();
328            mSource[source]->cancelBuffer(*sslot, *fence);
329            return result;
330        }
331        VDS_LOGV("dequeueBuffer(%s): buffers[%d]=%p fmt=%d usage=%#x",
332                dbgSourceStr(source), pslot, mProducerBuffers[pslot].get(),
333                mProducerBuffers[pslot]->getPixelFormat(),
334                mProducerBuffers[pslot]->getUsage());
335    }
336
337    return result;
338}
339
340status_t VirtualDisplaySurface::dequeueBuffer(int* pslot, sp<Fence>* fence,
341        uint32_t w, uint32_t h, PixelFormat format, uint32_t usage) {
342    if (mDisplayId < 0)
343        return mSource[SOURCE_SINK]->dequeueBuffer(pslot, fence, w, h, format, usage);
344
345    VDS_LOGW_IF(mDbgState != DBG_STATE_PREPARED,
346            "Unexpected dequeueBuffer() in %s state", dbgStateStr());
347    mDbgState = DBG_STATE_GLES;
348
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.mSlot != sslot,
451                "queueBuffer: acquired sslot %d from SCRATCH after queueing sslot %d",
452                item.mSlot, sslot);
453        mFbProducerSlot = mapSource2ProducerSlot(SOURCE_SCRATCH, item.mSlot);
454        mFbFence = mSlots[item.mSlot].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        input.deflate(&timestamp, &isAutoTimestamp, &dataSpace, &crop,
469                &scalingMode, &transform, &mFbFence);
470
471        mFbProducerSlot = pslot;
472        mOutputFence = mFbFence;
473    }
474
475    *output = mQueueBufferOutput;
476    return NO_ERROR;
477}
478
479status_t VirtualDisplaySurface::cancelBuffer(int pslot,
480        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(uint32_t /* width */,
529        uint32_t /* height */, PixelFormat /* format */, uint32_t /* usage */) {
530    // TODO: Should we actually allocate buffers for a virtual display?
531}
532
533status_t VirtualDisplaySurface::allowAllocation(bool /* allow */) {
534    return INVALID_OPERATION;
535}
536
537status_t VirtualDisplaySurface::setGenerationNumber(uint32_t /* generation */) {
538    ALOGE("setGenerationNumber not supported on VirtualDisplaySurface");
539    return INVALID_OPERATION;
540}
541
542String8 VirtualDisplaySurface::getConsumerName() const {
543    return String8("VirtualDisplaySurface");
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