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