VirtualDisplaySurface.cpp revision 7c3ba8aa288755fad78ddbabcee0ad5a0610ac1c
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
178#ifndef USE_HWC2
179status_t VirtualDisplaySurface::compositionComplete() {
180    return NO_ERROR;
181}
182#endif
183
184status_t VirtualDisplaySurface::advanceFrame() {
185    if (mDisplayId < 0)
186        return NO_ERROR;
187
188    if (mCompositionType == COMPOSITION_HWC) {
189        VDS_LOGW_IF(mDbgState != DBG_STATE_PREPARED,
190                "Unexpected advanceFrame() in %s state on HWC frame",
191                dbgStateStr());
192    } else {
193        VDS_LOGW_IF(mDbgState != DBG_STATE_GLES_DONE,
194                "Unexpected advanceFrame() in %s state on GLES/MIXED frame",
195                dbgStateStr());
196    }
197    mDbgState = DBG_STATE_HWC;
198
199    if (mOutputProducerSlot < 0 ||
200            (mCompositionType != COMPOSITION_HWC && mFbProducerSlot < 0)) {
201        // Last chance bailout if something bad happened earlier. For example,
202        // in a GLES configuration, if the sink disappears then dequeueBuffer
203        // will fail, the GLES driver won't queue a buffer, but SurfaceFlinger
204        // will soldier on. So we end up here without a buffer. There should
205        // be lots of scary messages in the log just before this.
206        VDS_LOGE("advanceFrame: no buffer, bailing out");
207        return NO_MEMORY;
208    }
209
210    sp<GraphicBuffer> fbBuffer = mFbProducerSlot >= 0 ?
211            mProducerBuffers[mFbProducerSlot] : sp<GraphicBuffer>(NULL);
212    sp<GraphicBuffer> outBuffer = mProducerBuffers[mOutputProducerSlot];
213    VDS_LOGV("advanceFrame: fb=%d(%p) out=%d(%p)",
214            mFbProducerSlot, fbBuffer.get(),
215            mOutputProducerSlot, outBuffer.get());
216
217    // At this point we know the output buffer acquire fence,
218    // so update HWC state with it.
219    mHwc.setOutputBuffer(mDisplayId, mOutputFence, outBuffer);
220
221    status_t result = NO_ERROR;
222    if (fbBuffer != NULL) {
223#ifdef USE_HWC2
224        // TODO: Correctly propagate the dataspace from GL composition
225        result = mHwc.setClientTarget(mDisplayId, mFbFence, fbBuffer,
226                HAL_DATASPACE_UNKNOWN);
227#else
228        result = mHwc.fbPost(mDisplayId, mFbFence, fbBuffer);
229#endif
230    }
231
232    return result;
233}
234
235void VirtualDisplaySurface::onFrameCommitted() {
236    if (mDisplayId < 0)
237        return;
238
239    VDS_LOGW_IF(mDbgState != DBG_STATE_HWC,
240            "Unexpected onFrameCommitted() in %s state", dbgStateStr());
241    mDbgState = DBG_STATE_IDLE;
242
243#ifdef USE_HWC2
244    sp<Fence> retireFence = mHwc.getRetireFence(mDisplayId);
245#else
246    sp<Fence> fbFence = mHwc.getAndResetReleaseFence(mDisplayId);
247#endif
248    if (mCompositionType == COMPOSITION_MIXED && mFbProducerSlot >= 0) {
249        // release the scratch buffer back to the pool
250        Mutex::Autolock lock(mMutex);
251        int sslot = mapProducer2SourceSlot(SOURCE_SCRATCH, mFbProducerSlot);
252        VDS_LOGV("onFrameCommitted: release scratch sslot=%d", sslot);
253#ifdef USE_HWC2
254        addReleaseFenceLocked(sslot, mProducerBuffers[mFbProducerSlot],
255                retireFence);
256#else
257        addReleaseFenceLocked(sslot, mProducerBuffers[mFbProducerSlot], fbFence);
258#endif
259        releaseBufferLocked(sslot, mProducerBuffers[mFbProducerSlot],
260                EGL_NO_DISPLAY, EGL_NO_SYNC_KHR);
261    }
262
263    if (mOutputProducerSlot >= 0) {
264        int sslot = mapProducer2SourceSlot(SOURCE_SINK, mOutputProducerSlot);
265        QueueBufferOutput qbo;
266#ifndef USE_HWC2
267        sp<Fence> outFence = mHwc.getLastRetireFence(mDisplayId);
268#endif
269        VDS_LOGV("onFrameCommitted: queue sink sslot=%d", sslot);
270        if (mMustRecompose) {
271            status_t result = mSource[SOURCE_SINK]->queueBuffer(sslot,
272                    QueueBufferInput(
273                        systemTime(), false /* isAutoTimestamp */,
274                        HAL_DATASPACE_UNKNOWN,
275                        Rect(mSinkBufferWidth, mSinkBufferHeight),
276                        NATIVE_WINDOW_SCALING_MODE_FREEZE, 0 /* transform */,
277#ifdef USE_HWC2
278                        retireFence),
279#else
280                        outFence),
281#endif
282                    &qbo);
283            if (result == NO_ERROR) {
284                updateQueueBufferOutput(qbo);
285            }
286        } else {
287            // If the surface hadn't actually been updated, then we only went
288            // through the motions of updating the display to keep our state
289            // machine happy. We cancel the buffer to avoid triggering another
290            // re-composition and causing an infinite loop.
291#ifdef USE_HWC2
292            mSource[SOURCE_SINK]->cancelBuffer(sslot, retireFence);
293#else
294            mSource[SOURCE_SINK]->cancelBuffer(sslot, outFence);
295#endif
296        }
297    }
298
299    resetPerFrameState();
300}
301
302void VirtualDisplaySurface::dumpAsString(String8& /* result */) const {
303}
304
305void VirtualDisplaySurface::resizeBuffers(const uint32_t w, const uint32_t h) {
306    mQueueBufferOutput.width = w;
307    mQueueBufferOutput.height = h;
308    mSinkBufferWidth = w;
309    mSinkBufferHeight = h;
310}
311
312const sp<Fence>& VirtualDisplaySurface::getClientTargetAcquireFence() const {
313    return mFbFence;
314}
315
316status_t VirtualDisplaySurface::requestBuffer(int pslot,
317        sp<GraphicBuffer>* outBuf) {
318    if (mDisplayId < 0)
319        return mSource[SOURCE_SINK]->requestBuffer(pslot, outBuf);
320
321    VDS_LOGW_IF(mDbgState != DBG_STATE_GLES,
322            "Unexpected requestBuffer pslot=%d in %s state",
323            pslot, dbgStateStr());
324
325    *outBuf = mProducerBuffers[pslot];
326    return NO_ERROR;
327}
328
329status_t VirtualDisplaySurface::setMaxDequeuedBufferCount(
330        int maxDequeuedBuffers) {
331    return mSource[SOURCE_SINK]->setMaxDequeuedBufferCount(maxDequeuedBuffers);
332}
333
334status_t VirtualDisplaySurface::setAsyncMode(bool async) {
335    return mSource[SOURCE_SINK]->setAsyncMode(async);
336}
337
338status_t VirtualDisplaySurface::dequeueBuffer(Source source,
339        PixelFormat format, uint32_t usage, int* sslot, sp<Fence>* fence) {
340    LOG_FATAL_IF(mDisplayId < 0, "mDisplayId=%d but should not be < 0.", mDisplayId);
341
342    status_t result = mSource[source]->dequeueBuffer(sslot, fence,
343            mSinkBufferWidth, mSinkBufferHeight, format, usage, nullptr);
344    if (result < 0)
345        return result;
346    int pslot = mapSource2ProducerSlot(source, *sslot);
347    VDS_LOGV("dequeueBuffer(%s): sslot=%d pslot=%d result=%d",
348            dbgSourceStr(source), *sslot, pslot, result);
349    uint64_t sourceBit = static_cast<uint64_t>(source) << pslot;
350
351    if ((mProducerSlotSource & (1ULL << pslot)) != sourceBit) {
352        // This slot was previously dequeued from the other source; must
353        // re-request the buffer.
354        result |= BUFFER_NEEDS_REALLOCATION;
355        mProducerSlotSource &= ~(1ULL << pslot);
356        mProducerSlotSource |= sourceBit;
357    }
358
359    if (result & RELEASE_ALL_BUFFERS) {
360        for (uint32_t i = 0; i < BufferQueue::NUM_BUFFER_SLOTS; i++) {
361            if ((mProducerSlotSource & (1ULL << i)) == sourceBit)
362                mProducerBuffers[i].clear();
363        }
364    }
365    if (result & BUFFER_NEEDS_REALLOCATION) {
366        result = mSource[source]->requestBuffer(*sslot, &mProducerBuffers[pslot]);
367        if (result < 0) {
368            mProducerBuffers[pslot].clear();
369            mSource[source]->cancelBuffer(*sslot, *fence);
370            return result;
371        }
372        VDS_LOGV("dequeueBuffer(%s): buffers[%d]=%p fmt=%d usage=%#x",
373                dbgSourceStr(source), pslot, mProducerBuffers[pslot].get(),
374                mProducerBuffers[pslot]->getPixelFormat(),
375                mProducerBuffers[pslot]->getUsage());
376    }
377
378    return result;
379}
380
381status_t VirtualDisplaySurface::dequeueBuffer(int* pslot, sp<Fence>* fence,
382        uint32_t w, uint32_t h, PixelFormat format, uint32_t usage,
383        FrameEventHistoryDelta* outTimestamps) {
384    if (mDisplayId < 0) {
385        return mSource[SOURCE_SINK]->dequeueBuffer(
386                pslot, fence, w, h, format, usage, outTimestamps);
387    }
388
389    VDS_LOGW_IF(mDbgState != DBG_STATE_PREPARED,
390            "Unexpected dequeueBuffer() in %s state", dbgStateStr());
391    mDbgState = DBG_STATE_GLES;
392
393    VDS_LOGV("dequeueBuffer %dx%d fmt=%d usage=%#x", w, h, format, usage);
394
395    status_t result = NO_ERROR;
396    Source source = fbSourceForCompositionType(mCompositionType);
397
398    if (source == SOURCE_SINK) {
399
400        if (mOutputProducerSlot < 0) {
401            // Last chance bailout if something bad happened earlier. For example,
402            // in a GLES configuration, if the sink disappears then dequeueBuffer
403            // will fail, the GLES driver won't queue a buffer, but SurfaceFlinger
404            // will soldier on. So we end up here without a buffer. There should
405            // be lots of scary messages in the log just before this.
406            VDS_LOGE("dequeueBuffer: no buffer, bailing out");
407            return NO_MEMORY;
408        }
409
410        // We already dequeued the output buffer. If the GLES driver wants
411        // something incompatible, we have to cancel and get a new one. This
412        // will mean that HWC will see a different output buffer between
413        // prepare and set, but since we're in GLES-only mode already it
414        // shouldn't matter.
415
416        usage |= GRALLOC_USAGE_HW_COMPOSER;
417        const sp<GraphicBuffer>& buf = mProducerBuffers[mOutputProducerSlot];
418        if ((usage & ~buf->getUsage()) != 0 ||
419                (format != 0 && format != buf->getPixelFormat()) ||
420                (w != 0 && w != mSinkBufferWidth) ||
421                (h != 0 && h != mSinkBufferHeight)) {
422            VDS_LOGV("dequeueBuffer: dequeueing new output buffer: "
423                    "want %dx%d fmt=%d use=%#x, "
424                    "have %dx%d fmt=%d use=%#x",
425                    w, h, format, usage,
426                    mSinkBufferWidth, mSinkBufferHeight,
427                    buf->getPixelFormat(), buf->getUsage());
428            mOutputFormat = format;
429            mOutputUsage = usage;
430            result = refreshOutputBuffer();
431            if (result < 0)
432                return result;
433        }
434    }
435
436    if (source == SOURCE_SINK) {
437        *pslot = mOutputProducerSlot;
438        *fence = mOutputFence;
439    } else {
440        int sslot;
441        result = dequeueBuffer(source, format, usage, &sslot, fence);
442        if (result >= 0) {
443            *pslot = mapSource2ProducerSlot(source, sslot);
444        }
445    }
446    return result;
447}
448
449status_t VirtualDisplaySurface::detachBuffer(int /* slot */) {
450    VDS_LOGE("detachBuffer is not available for VirtualDisplaySurface");
451    return INVALID_OPERATION;
452}
453
454status_t VirtualDisplaySurface::detachNextBuffer(
455        sp<GraphicBuffer>* /* outBuffer */, sp<Fence>* /* outFence */) {
456    VDS_LOGE("detachNextBuffer is not available for VirtualDisplaySurface");
457    return INVALID_OPERATION;
458}
459
460status_t VirtualDisplaySurface::attachBuffer(int* /* outSlot */,
461        const sp<GraphicBuffer>& /* buffer */) {
462    VDS_LOGE("attachBuffer is not available for VirtualDisplaySurface");
463    return INVALID_OPERATION;
464}
465
466status_t VirtualDisplaySurface::queueBuffer(int pslot,
467        const QueueBufferInput& input, QueueBufferOutput* output) {
468    if (mDisplayId < 0)
469        return mSource[SOURCE_SINK]->queueBuffer(pslot, input, output);
470
471    VDS_LOGW_IF(mDbgState != DBG_STATE_GLES,
472            "Unexpected queueBuffer(pslot=%d) in %s state", pslot,
473            dbgStateStr());
474    mDbgState = DBG_STATE_GLES_DONE;
475
476    VDS_LOGV("queueBuffer pslot=%d", pslot);
477
478    status_t result;
479    if (mCompositionType == COMPOSITION_MIXED) {
480        // Queue the buffer back into the scratch pool
481        QueueBufferOutput scratchQBO;
482        int sslot = mapProducer2SourceSlot(SOURCE_SCRATCH, pslot);
483        result = mSource[SOURCE_SCRATCH]->queueBuffer(sslot, input, &scratchQBO);
484        if (result != NO_ERROR)
485            return result;
486
487        // Now acquire the buffer from the scratch pool -- should be the same
488        // slot and fence as we just queued.
489        Mutex::Autolock lock(mMutex);
490        BufferItem item;
491        result = acquireBufferLocked(&item, 0);
492        if (result != NO_ERROR)
493            return result;
494        VDS_LOGW_IF(item.mSlot != sslot,
495                "queueBuffer: acquired sslot %d from SCRATCH after queueing sslot %d",
496                item.mSlot, sslot);
497        mFbProducerSlot = mapSource2ProducerSlot(SOURCE_SCRATCH, item.mSlot);
498        mFbFence = mSlots[item.mSlot].mFence;
499
500    } else {
501        LOG_FATAL_IF(mCompositionType != COMPOSITION_GLES,
502                "Unexpected queueBuffer in state %s for compositionType %s",
503                dbgStateStr(), dbgCompositionTypeStr(mCompositionType));
504
505        // Extract the GLES release fence for HWC to acquire
506        int64_t timestamp;
507        bool isAutoTimestamp;
508        android_dataspace dataSpace;
509        Rect crop;
510        int scalingMode;
511        uint32_t transform;
512        input.deflate(&timestamp, &isAutoTimestamp, &dataSpace, &crop,
513                &scalingMode, &transform, &mFbFence);
514
515        mFbProducerSlot = pslot;
516        mOutputFence = mFbFence;
517    }
518
519    *output = mQueueBufferOutput;
520    return NO_ERROR;
521}
522
523status_t VirtualDisplaySurface::cancelBuffer(int pslot,
524        const sp<Fence>& fence) {
525    if (mDisplayId < 0)
526        return mSource[SOURCE_SINK]->cancelBuffer(mapProducer2SourceSlot(SOURCE_SINK, pslot), fence);
527
528    VDS_LOGW_IF(mDbgState != DBG_STATE_GLES,
529            "Unexpected cancelBuffer(pslot=%d) in %s state", pslot,
530            dbgStateStr());
531    VDS_LOGV("cancelBuffer pslot=%d", pslot);
532    Source source = fbSourceForCompositionType(mCompositionType);
533    return mSource[source]->cancelBuffer(
534            mapProducer2SourceSlot(source, pslot), fence);
535}
536
537int VirtualDisplaySurface::query(int what, int* value) {
538    switch (what) {
539        case NATIVE_WINDOW_WIDTH:
540            *value = mSinkBufferWidth;
541            break;
542        case NATIVE_WINDOW_HEIGHT:
543            *value = mSinkBufferHeight;
544            break;
545        default:
546            return mSource[SOURCE_SINK]->query(what, value);
547    }
548    return NO_ERROR;
549}
550
551status_t VirtualDisplaySurface::connect(const sp<IProducerListener>& listener,
552        int api, bool producerControlledByApp,
553        QueueBufferOutput* output) {
554    QueueBufferOutput qbo;
555    status_t result = mSource[SOURCE_SINK]->connect(listener, api,
556            producerControlledByApp, &qbo);
557    if (result == NO_ERROR) {
558        updateQueueBufferOutput(qbo);
559        *output = mQueueBufferOutput;
560    }
561    return result;
562}
563
564status_t VirtualDisplaySurface::disconnect(int api, DisconnectMode mode) {
565    return mSource[SOURCE_SINK]->disconnect(api, mode);
566}
567
568status_t VirtualDisplaySurface::setSidebandStream(const sp<NativeHandle>& /*stream*/) {
569    return INVALID_OPERATION;
570}
571
572void VirtualDisplaySurface::allocateBuffers(uint32_t /* width */,
573        uint32_t /* height */, PixelFormat /* format */, uint32_t /* usage */) {
574    // TODO: Should we actually allocate buffers for a virtual display?
575}
576
577status_t VirtualDisplaySurface::allowAllocation(bool /* allow */) {
578    return INVALID_OPERATION;
579}
580
581status_t VirtualDisplaySurface::setGenerationNumber(uint32_t /* generation */) {
582    ALOGE("setGenerationNumber not supported on VirtualDisplaySurface");
583    return INVALID_OPERATION;
584}
585
586String8 VirtualDisplaySurface::getConsumerName() const {
587    return String8("VirtualDisplaySurface");
588}
589
590status_t VirtualDisplaySurface::setSharedBufferMode(bool /*sharedBufferMode*/) {
591    ALOGE("setSharedBufferMode not supported on VirtualDisplaySurface");
592    return INVALID_OPERATION;
593}
594
595status_t VirtualDisplaySurface::setAutoRefresh(bool /*autoRefresh*/) {
596    ALOGE("setAutoRefresh not supported on VirtualDisplaySurface");
597    return INVALID_OPERATION;
598}
599
600status_t VirtualDisplaySurface::setDequeueTimeout(nsecs_t /* timeout */) {
601    ALOGE("setDequeueTimeout not supported on VirtualDisplaySurface");
602    return INVALID_OPERATION;
603}
604
605status_t VirtualDisplaySurface::getLastQueuedBuffer(
606        sp<GraphicBuffer>* /*outBuffer*/, sp<Fence>* /*outFence*/,
607        float[16] /* outTransformMatrix*/) {
608    ALOGE("getLastQueuedBuffer not supported on VirtualDisplaySurface");
609    return INVALID_OPERATION;
610}
611
612status_t VirtualDisplaySurface::getUniqueId(uint64_t* /*outId*/) const {
613    ALOGE("getUniqueId not supported on VirtualDisplaySurface");
614    return INVALID_OPERATION;
615}
616
617void VirtualDisplaySurface::updateQueueBufferOutput(
618        const QueueBufferOutput& qbo) {
619    mQueueBufferOutput = qbo;
620    mQueueBufferOutput.transformHint = 0;
621}
622
623void VirtualDisplaySurface::resetPerFrameState() {
624    mCompositionType = COMPOSITION_UNKNOWN;
625    mFbFence = Fence::NO_FENCE;
626    mOutputFence = Fence::NO_FENCE;
627    mOutputProducerSlot = -1;
628    mFbProducerSlot = -1;
629}
630
631status_t VirtualDisplaySurface::refreshOutputBuffer() {
632    if (mOutputProducerSlot >= 0) {
633        mSource[SOURCE_SINK]->cancelBuffer(
634                mapProducer2SourceSlot(SOURCE_SINK, mOutputProducerSlot),
635                mOutputFence);
636    }
637
638    int sslot;
639    status_t result = dequeueBuffer(SOURCE_SINK, mOutputFormat, mOutputUsage,
640            &sslot, &mOutputFence);
641    if (result < 0)
642        return result;
643    mOutputProducerSlot = mapSource2ProducerSlot(SOURCE_SINK, sslot);
644
645    // On GLES-only frames, we don't have the right output buffer acquire fence
646    // until after GLES calls queueBuffer(). So here we just set the buffer
647    // (for use in HWC prepare) but not the fence; we'll call this again with
648    // the proper fence once we have it.
649    result = mHwc.setOutputBuffer(mDisplayId, Fence::NO_FENCE,
650            mProducerBuffers[mOutputProducerSlot]);
651
652    return result;
653}
654
655// This slot mapping function is its own inverse, so two copies are unnecessary.
656// Both are kept to make the intent clear where the function is called, and for
657// the (unlikely) chance that we switch to a different mapping function.
658int VirtualDisplaySurface::mapSource2ProducerSlot(Source source, int sslot) {
659    if (source == SOURCE_SCRATCH) {
660        return BufferQueue::NUM_BUFFER_SLOTS - sslot - 1;
661    } else {
662        return sslot;
663    }
664}
665int VirtualDisplaySurface::mapProducer2SourceSlot(Source source, int pslot) {
666    return mapSource2ProducerSlot(source, pslot);
667}
668
669VirtualDisplaySurface::Source
670VirtualDisplaySurface::fbSourceForCompositionType(CompositionType type) {
671    return type == COMPOSITION_MIXED ? SOURCE_SCRATCH : SOURCE_SINK;
672}
673
674const char* VirtualDisplaySurface::dbgStateStr() const {
675    switch (mDbgState) {
676        case DBG_STATE_IDLE:      return "IDLE";
677        case DBG_STATE_PREPARED:  return "PREPARED";
678        case DBG_STATE_GLES:      return "GLES";
679        case DBG_STATE_GLES_DONE: return "GLES_DONE";
680        case DBG_STATE_HWC:       return "HWC";
681        default:                  return "INVALID";
682    }
683}
684
685const char* VirtualDisplaySurface::dbgSourceStr(Source s) {
686    switch (s) {
687        case SOURCE_SINK:    return "SINK";
688        case SOURCE_SCRATCH: return "SCRATCH";
689        default:             return "INVALID";
690    }
691}
692
693// ---------------------------------------------------------------------------
694} // namespace android
695// ---------------------------------------------------------------------------
696