VirtualDisplaySurface.cpp revision 19e3e06e3c65a7c001a6fe0971744ba5ff536515
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}
96
97VirtualDisplaySurface::~VirtualDisplaySurface() {
98}
99
100status_t VirtualDisplaySurface::beginFrame(bool mustRecompose) {
101    if (mDisplayId < 0)
102        return NO_ERROR;
103
104    mMustRecompose = mustRecompose;
105
106    VDS_LOGW_IF(mDbgState != DBG_STATE_IDLE,
107            "Unexpected beginFrame() in %s state", dbgStateStr());
108    mDbgState = DBG_STATE_BEGUN;
109
110    return refreshOutputBuffer();
111}
112
113status_t VirtualDisplaySurface::prepareFrame(CompositionType compositionType) {
114    if (mDisplayId < 0)
115        return NO_ERROR;
116
117    VDS_LOGW_IF(mDbgState != DBG_STATE_BEGUN,
118            "Unexpected prepareFrame() in %s state", dbgStateStr());
119    mDbgState = DBG_STATE_PREPARED;
120
121    mCompositionType = compositionType;
122    if (sForceHwcCopy && mCompositionType == COMPOSITION_GLES) {
123        // Some hardware can do RGB->YUV conversion more efficiently in hardware
124        // controlled by HWC than in hardware controlled by the video encoder.
125        // Forcing GLES-composed frames to go through an extra copy by the HWC
126        // allows the format conversion to happen there, rather than passing RGB
127        // directly to the consumer.
128        //
129        // On the other hand, when the consumer prefers RGB or can consume RGB
130        // inexpensively, this forces an unnecessary copy.
131        mCompositionType = COMPOSITION_MIXED;
132    }
133
134    if (mCompositionType != mDbgLastCompositionType) {
135        VDS_LOGV("prepareFrame: composition type changed to %s",
136                dbgCompositionTypeStr(mCompositionType));
137        mDbgLastCompositionType = mCompositionType;
138    }
139
140    if (mCompositionType != COMPOSITION_GLES &&
141            (mOutputFormat != mDefaultOutputFormat ||
142             mOutputUsage != GRALLOC_USAGE_HW_COMPOSER)) {
143        // We must have just switched from GLES-only to MIXED or HWC
144        // composition. Stop using the format and usage requested by the GLES
145        // driver; they may be suboptimal when HWC is writing to the output
146        // buffer. For example, if the output is going to a video encoder, and
147        // HWC can write directly to YUV, some hardware can skip a
148        // memory-to-memory RGB-to-YUV conversion step.
149        //
150        // If we just switched *to* GLES-only mode, we'll change the
151        // format/usage and get a new buffer when the GLES driver calls
152        // dequeueBuffer().
153        mOutputFormat = mDefaultOutputFormat;
154        mOutputUsage = GRALLOC_USAGE_HW_COMPOSER;
155        refreshOutputBuffer();
156    }
157
158    return NO_ERROR;
159}
160
161status_t VirtualDisplaySurface::compositionComplete() {
162    return NO_ERROR;
163}
164
165status_t VirtualDisplaySurface::advanceFrame() {
166    if (mDisplayId < 0)
167        return NO_ERROR;
168
169    if (mCompositionType == COMPOSITION_HWC) {
170        VDS_LOGW_IF(mDbgState != DBG_STATE_PREPARED,
171                "Unexpected advanceFrame() in %s state on HWC frame",
172                dbgStateStr());
173    } else {
174        VDS_LOGW_IF(mDbgState != DBG_STATE_GLES_DONE,
175                "Unexpected advanceFrame() in %s state on GLES/MIXED frame",
176                dbgStateStr());
177    }
178    mDbgState = DBG_STATE_HWC;
179
180    if (mOutputProducerSlot < 0 ||
181            (mCompositionType != COMPOSITION_HWC && mFbProducerSlot < 0)) {
182        // Last chance bailout if something bad happened earlier. For example,
183        // in a GLES configuration, if the sink disappears then dequeueBuffer
184        // will fail, the GLES driver won't queue a buffer, but SurfaceFlinger
185        // will soldier on. So we end up here without a buffer. There should
186        // be lots of scary messages in the log just before this.
187        VDS_LOGE("advanceFrame: no buffer, bailing out");
188        return NO_MEMORY;
189    }
190
191    sp<GraphicBuffer> fbBuffer = mFbProducerSlot >= 0 ?
192            mProducerBuffers[mFbProducerSlot] : sp<GraphicBuffer>(NULL);
193    sp<GraphicBuffer> outBuffer = mProducerBuffers[mOutputProducerSlot];
194    VDS_LOGV("advanceFrame: fb=%d(%p) out=%d(%p)",
195            mFbProducerSlot, fbBuffer.get(),
196            mOutputProducerSlot, outBuffer.get());
197
198    // At this point we know the output buffer acquire fence,
199    // so update HWC state with it.
200    mHwc.setOutputBuffer(mDisplayId, mOutputFence, outBuffer);
201
202    status_t result = NO_ERROR;
203    if (fbBuffer != NULL) {
204        result = mHwc.fbPost(mDisplayId, mFbFence, fbBuffer);
205    }
206
207    return result;
208}
209
210void VirtualDisplaySurface::onFrameCommitted() {
211    if (mDisplayId < 0)
212        return;
213
214    VDS_LOGW_IF(mDbgState != DBG_STATE_HWC,
215            "Unexpected onFrameCommitted() in %s state", dbgStateStr());
216    mDbgState = DBG_STATE_IDLE;
217
218    sp<Fence> fbFence = mHwc.getAndResetReleaseFence(mDisplayId);
219    if (mCompositionType == COMPOSITION_MIXED && mFbProducerSlot >= 0) {
220        // release the scratch buffer back to the pool
221        Mutex::Autolock lock(mMutex);
222        int sslot = mapProducer2SourceSlot(SOURCE_SCRATCH, mFbProducerSlot);
223        VDS_LOGV("onFrameCommitted: release scratch sslot=%d", sslot);
224        addReleaseFenceLocked(sslot, mProducerBuffers[mFbProducerSlot], fbFence);
225        releaseBufferLocked(sslot, mProducerBuffers[mFbProducerSlot],
226                EGL_NO_DISPLAY, EGL_NO_SYNC_KHR);
227    }
228
229    if (mOutputProducerSlot >= 0) {
230        int sslot = mapProducer2SourceSlot(SOURCE_SINK, mOutputProducerSlot);
231        QueueBufferOutput qbo;
232        sp<Fence> outFence = mHwc.getLastRetireFence(mDisplayId);
233        VDS_LOGV("onFrameCommitted: queue sink sslot=%d", sslot);
234        if (mMustRecompose) {
235            status_t result = mSource[SOURCE_SINK]->queueBuffer(sslot,
236                    QueueBufferInput(
237                        systemTime(), false /* isAutoTimestamp */,
238                        HAL_DATASPACE_UNKNOWN,
239                        Rect(mSinkBufferWidth, mSinkBufferHeight),
240                        NATIVE_WINDOW_SCALING_MODE_FREEZE, 0 /* transform */,
241                        true /* async*/,
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    // Don't let a slow consumer block us
297    bool async = (source == SOURCE_SINK);
298
299    status_t result = mSource[source]->dequeueBuffer(sslot, fence, async,
300            mSinkBufferWidth, mSinkBufferHeight, format, usage);
301    if (result < 0)
302        return result;
303    int pslot = mapSource2ProducerSlot(source, *sslot);
304    VDS_LOGV("dequeueBuffer(%s): sslot=%d pslot=%d result=%d",
305            dbgSourceStr(source), *sslot, pslot, result);
306    uint64_t sourceBit = static_cast<uint64_t>(source) << pslot;
307
308    if ((mProducerSlotSource & (1ULL << pslot)) != sourceBit) {
309        // This slot was previously dequeued from the other source; must
310        // re-request the buffer.
311        result |= BUFFER_NEEDS_REALLOCATION;
312        mProducerSlotSource &= ~(1ULL << pslot);
313        mProducerSlotSource |= sourceBit;
314    }
315
316    if (result & RELEASE_ALL_BUFFERS) {
317        for (uint32_t i = 0; i < BufferQueue::NUM_BUFFER_SLOTS; i++) {
318            if ((mProducerSlotSource & (1ULL << i)) == sourceBit)
319                mProducerBuffers[i].clear();
320        }
321    }
322    if (result & BUFFER_NEEDS_REALLOCATION) {
323        result = mSource[source]->requestBuffer(*sslot, &mProducerBuffers[pslot]);
324        if (result < 0) {
325            mProducerBuffers[pslot].clear();
326            mSource[source]->cancelBuffer(*sslot, *fence);
327            return result;
328        }
329        VDS_LOGV("dequeueBuffer(%s): buffers[%d]=%p fmt=%d usage=%#x",
330                dbgSourceStr(source), pslot, mProducerBuffers[pslot].get(),
331                mProducerBuffers[pslot]->getPixelFormat(),
332                mProducerBuffers[pslot]->getUsage());
333    }
334
335    return result;
336}
337
338status_t VirtualDisplaySurface::dequeueBuffer(int* pslot, sp<Fence>* fence, bool async,
339        uint32_t w, uint32_t h, PixelFormat format, uint32_t usage) {
340    if (mDisplayId < 0)
341        return mSource[SOURCE_SINK]->dequeueBuffer(pslot, fence, async, w, h, format, usage);
342
343    VDS_LOGW_IF(mDbgState != DBG_STATE_PREPARED,
344            "Unexpected dequeueBuffer() in %s state", dbgStateStr());
345    mDbgState = DBG_STATE_GLES;
346
347    VDS_LOGW_IF(!async, "EGL called dequeueBuffer with !async despite eglSwapInterval(0)");
348    VDS_LOGV("dequeueBuffer %dx%d fmt=%d usage=%#x", w, h, format, usage);
349
350    status_t result = NO_ERROR;
351    Source source = fbSourceForCompositionType(mCompositionType);
352
353    if (source == SOURCE_SINK) {
354
355        if (mOutputProducerSlot < 0) {
356            // Last chance bailout if something bad happened earlier. For example,
357            // in a GLES configuration, if the sink disappears then dequeueBuffer
358            // will fail, the GLES driver won't queue a buffer, but SurfaceFlinger
359            // will soldier on. So we end up here without a buffer. There should
360            // be lots of scary messages in the log just before this.
361            VDS_LOGE("dequeueBuffer: no buffer, bailing out");
362            return NO_MEMORY;
363        }
364
365        // We already dequeued the output buffer. If the GLES driver wants
366        // something incompatible, we have to cancel and get a new one. This
367        // will mean that HWC will see a different output buffer between
368        // prepare and set, but since we're in GLES-only mode already it
369        // shouldn't matter.
370
371        usage |= GRALLOC_USAGE_HW_COMPOSER;
372        const sp<GraphicBuffer>& buf = mProducerBuffers[mOutputProducerSlot];
373        if ((usage & ~buf->getUsage()) != 0 ||
374                (format != 0 && format != buf->getPixelFormat()) ||
375                (w != 0 && w != mSinkBufferWidth) ||
376                (h != 0 && h != mSinkBufferHeight)) {
377            VDS_LOGV("dequeueBuffer: dequeueing new output buffer: "
378                    "want %dx%d fmt=%d use=%#x, "
379                    "have %dx%d fmt=%d use=%#x",
380                    w, h, format, usage,
381                    mSinkBufferWidth, mSinkBufferHeight,
382                    buf->getPixelFormat(), buf->getUsage());
383            mOutputFormat = format;
384            mOutputUsage = usage;
385            result = refreshOutputBuffer();
386            if (result < 0)
387                return result;
388        }
389    }
390
391    if (source == SOURCE_SINK) {
392        *pslot = mOutputProducerSlot;
393        *fence = mOutputFence;
394    } else {
395        int sslot;
396        result = dequeueBuffer(source, format, usage, &sslot, fence);
397        if (result >= 0) {
398            *pslot = mapSource2ProducerSlot(source, sslot);
399        }
400    }
401    return result;
402}
403
404status_t VirtualDisplaySurface::detachBuffer(int /* slot */) {
405    VDS_LOGE("detachBuffer is not available for VirtualDisplaySurface");
406    return INVALID_OPERATION;
407}
408
409status_t VirtualDisplaySurface::detachNextBuffer(
410        sp<GraphicBuffer>* /* outBuffer */, sp<Fence>* /* outFence */) {
411    VDS_LOGE("detachNextBuffer is not available for VirtualDisplaySurface");
412    return INVALID_OPERATION;
413}
414
415status_t VirtualDisplaySurface::attachBuffer(int* /* outSlot */,
416        const sp<GraphicBuffer>& /* buffer */) {
417    VDS_LOGE("attachBuffer is not available for VirtualDisplaySurface");
418    return INVALID_OPERATION;
419}
420
421status_t VirtualDisplaySurface::queueBuffer(int pslot,
422        const QueueBufferInput& input, QueueBufferOutput* output) {
423    if (mDisplayId < 0)
424        return mSource[SOURCE_SINK]->queueBuffer(pslot, input, output);
425
426    VDS_LOGW_IF(mDbgState != DBG_STATE_GLES,
427            "Unexpected queueBuffer(pslot=%d) in %s state", pslot,
428            dbgStateStr());
429    mDbgState = DBG_STATE_GLES_DONE;
430
431    VDS_LOGV("queueBuffer pslot=%d", pslot);
432
433    status_t result;
434    if (mCompositionType == COMPOSITION_MIXED) {
435        // Queue the buffer back into the scratch pool
436        QueueBufferOutput scratchQBO;
437        int sslot = mapProducer2SourceSlot(SOURCE_SCRATCH, pslot);
438        result = mSource[SOURCE_SCRATCH]->queueBuffer(sslot, input, &scratchQBO);
439        if (result != NO_ERROR)
440            return result;
441
442        // Now acquire the buffer from the scratch pool -- should be the same
443        // slot and fence as we just queued.
444        Mutex::Autolock lock(mMutex);
445        BufferItem item;
446        result = acquireBufferLocked(&item, 0);
447        if (result != NO_ERROR)
448            return result;
449        VDS_LOGW_IF(item.mBuf != sslot,
450                "queueBuffer: acquired sslot %d from SCRATCH after queueing sslot %d",
451                item.mBuf, sslot);
452        mFbProducerSlot = mapSource2ProducerSlot(SOURCE_SCRATCH, item.mBuf);
453        mFbFence = mSlots[item.mBuf].mFence;
454
455    } else {
456        LOG_FATAL_IF(mCompositionType != COMPOSITION_GLES,
457                "Unexpected queueBuffer in state %s for compositionType %s",
458                dbgStateStr(), dbgCompositionTypeStr(mCompositionType));
459
460        // Extract the GLES release fence for HWC to acquire
461        int64_t timestamp;
462        bool isAutoTimestamp;
463        android_dataspace dataSpace;
464        Rect crop;
465        int scalingMode;
466        uint32_t transform;
467        bool async;
468        input.deflate(&timestamp, &isAutoTimestamp, &dataSpace, &crop,
469                &scalingMode, &transform, &async, &mFbFence);
470
471        mFbProducerSlot = pslot;
472        mOutputFence = mFbFence;
473    }
474
475    *output = mQueueBufferOutput;
476    return NO_ERROR;
477}
478
479void VirtualDisplaySurface::cancelBuffer(int pslot, const sp<Fence>& fence) {
480    if (mDisplayId < 0)
481        return mSource[SOURCE_SINK]->cancelBuffer(mapProducer2SourceSlot(SOURCE_SINK, pslot), fence);
482
483    VDS_LOGW_IF(mDbgState != DBG_STATE_GLES,
484            "Unexpected cancelBuffer(pslot=%d) in %s state", pslot,
485            dbgStateStr());
486    VDS_LOGV("cancelBuffer pslot=%d", pslot);
487    Source source = fbSourceForCompositionType(mCompositionType);
488    return mSource[source]->cancelBuffer(
489            mapProducer2SourceSlot(source, pslot), fence);
490}
491
492int VirtualDisplaySurface::query(int what, int* value) {
493    switch (what) {
494        case NATIVE_WINDOW_WIDTH:
495            *value = mSinkBufferWidth;
496            break;
497        case NATIVE_WINDOW_HEIGHT:
498            *value = mSinkBufferHeight;
499            break;
500        default:
501            return mSource[SOURCE_SINK]->query(what, value);
502    }
503    return NO_ERROR;
504}
505
506status_t VirtualDisplaySurface::connect(const sp<IProducerListener>& listener,
507        int api, bool producerControlledByApp,
508        QueueBufferOutput* output) {
509    QueueBufferOutput qbo;
510    status_t result = mSource[SOURCE_SINK]->connect(listener, api,
511            producerControlledByApp, &qbo);
512    if (result == NO_ERROR) {
513        updateQueueBufferOutput(qbo);
514        *output = mQueueBufferOutput;
515    }
516    return result;
517}
518
519status_t VirtualDisplaySurface::disconnect(int api) {
520    return mSource[SOURCE_SINK]->disconnect(api);
521}
522
523status_t VirtualDisplaySurface::setSidebandStream(const sp<NativeHandle>& /*stream*/) {
524    return INVALID_OPERATION;
525}
526
527void VirtualDisplaySurface::allocateBuffers(bool /* async */,
528        uint32_t /* width */, uint32_t /* height */, PixelFormat /* format */,
529        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