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