Layer.cpp revision bf974abe92f7495529916fe0f483f3b56e7c30e3
1/*
2 * Copyright (C) 2007 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 ATRACE_TAG ATRACE_TAG_GRAPHICS
18
19#include <stdlib.h>
20#include <stdint.h>
21#include <sys/types.h>
22#include <math.h>
23
24#include <cutils/compiler.h>
25#include <cutils/native_handle.h>
26#include <cutils/properties.h>
27
28#include <utils/Errors.h>
29#include <utils/Log.h>
30#include <utils/StopWatch.h>
31#include <utils/Trace.h>
32
33#include <ui/GraphicBuffer.h>
34#include <ui/PixelFormat.h>
35
36#include <gui/Surface.h>
37
38#include "clz.h"
39#include "DisplayDevice.h"
40#include "GLExtensions.h"
41#include "Layer.h"
42#include "SurfaceFlinger.h"
43#include "SurfaceTextureLayer.h"
44
45#include "DisplayHardware/HWComposer.h"
46
47#define DEBUG_RESIZE    0
48
49namespace android {
50
51// ---------------------------------------------------------------------------
52
53Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client)
54    :   LayerBaseClient(flinger, client),
55        mTextureName(-1U),
56        mQueuedFrames(0),
57        mCurrentTransform(0),
58        mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
59        mCurrentOpacity(true),
60        mRefreshPending(false),
61        mFrameLatencyNeeded(false),
62        mFormat(PIXEL_FORMAT_NONE),
63        mGLExtensions(GLExtensions::getInstance()),
64        mOpaqueLayer(true),
65        mSecure(false),
66        mProtectedByApp(false)
67{
68    mCurrentCrop.makeInvalid();
69    glGenTextures(1, &mTextureName);
70}
71
72void Layer::onLayerDisplayed(const sp<const DisplayDevice>& hw,
73        HWComposer::HWCLayerInterface* layer) {
74    LayerBaseClient::onLayerDisplayed(hw, layer);
75    if (layer) {
76        mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFenceFd());
77    }
78}
79
80void Layer::onFirstRef()
81{
82    LayerBaseClient::onFirstRef();
83
84    // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
85    sp<BufferQueue> bq = new SurfaceTextureLayer();
86    mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(mTextureName, true,
87            GL_TEXTURE_EXTERNAL_OES, false, bq);
88
89    mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
90    mSurfaceFlingerConsumer->setFrameAvailableListener(this);
91    mSurfaceFlingerConsumer->setSynchronousMode(true);
92
93#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
94#warning "disabling triple buffering"
95    mSurfaceFlingerConsumer->setDefaultMaxBufferCount(2);
96#else
97    mSurfaceFlingerConsumer->setDefaultMaxBufferCount(3);
98#endif
99
100    const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
101    updateTransformHint(hw);
102}
103
104Layer::~Layer()
105{
106    mFlinger->deleteTextureAsync(mTextureName);
107}
108
109void Layer::onFrameAvailable() {
110    android_atomic_inc(&mQueuedFrames);
111    mFlinger->signalLayerUpdate();
112}
113
114// called with SurfaceFlinger::mStateLock as soon as the layer is entered
115// in the purgatory list
116void Layer::onRemoved()
117{
118    mSurfaceFlingerConsumer->abandon();
119}
120
121void Layer::setName(const String8& name) {
122    LayerBase::setName(name);
123    mSurfaceFlingerConsumer->setName(name);
124}
125
126sp<ISurface> Layer::createSurface()
127{
128    class BSurface : public BnSurface, public LayerCleaner {
129        wp<const Layer> mOwner;
130        virtual sp<ISurfaceTexture> getSurfaceTexture() const {
131            sp<ISurfaceTexture> res;
132            sp<const Layer> that( mOwner.promote() );
133            if (that != NULL) {
134                res = that->mSurfaceFlingerConsumer->getBufferQueue();
135            }
136            return res;
137        }
138    public:
139        BSurface(const sp<SurfaceFlinger>& flinger,
140                const sp<Layer>& layer)
141            : LayerCleaner(flinger, layer), mOwner(layer) { }
142    };
143    sp<ISurface> sur(new BSurface(mFlinger, this));
144    return sur;
145}
146
147wp<IBinder> Layer::getSurfaceTextureBinder() const
148{
149    return mSurfaceFlingerConsumer->getBufferQueue()->asBinder();
150}
151
152status_t Layer::setBuffers( uint32_t w, uint32_t h,
153                            PixelFormat format, uint32_t flags)
154{
155    // this surfaces pixel format
156    PixelFormatInfo info;
157    status_t err = getPixelFormatInfo(format, &info);
158    if (err) {
159        ALOGE("unsupported pixelformat %d", format);
160        return err;
161    }
162
163    uint32_t const maxSurfaceDims = min(
164            mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
165
166    // never allow a surface larger than what our underlying GL implementation
167    // can handle.
168    if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
169        ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
170        return BAD_VALUE;
171    }
172
173    mFormat = format;
174
175    mSecure = (flags & ISurfaceComposerClient::eSecure) ? true : false;
176    mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
177    mOpaqueLayer = (flags & ISurfaceComposerClient::eOpaque);
178    mCurrentOpacity = getOpacityForFormat(format);
179
180    mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
181    mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
182    mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
183
184    return NO_ERROR;
185}
186
187Rect Layer::computeBufferCrop() const {
188    // Start with the SurfaceFlingerConsumer's buffer crop...
189    Rect crop;
190    if (!mCurrentCrop.isEmpty()) {
191        crop = mCurrentCrop;
192    } else  if (mActiveBuffer != NULL){
193        crop = Rect(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
194    } else {
195        crop.makeInvalid();
196        return crop;
197    }
198
199    // ... then reduce that in the same proportions as the window crop reduces
200    // the window size.
201    const State& s(drawingState());
202    if (!s.active.crop.isEmpty()) {
203        // Transform the window crop to match the buffer coordinate system,
204        // which means using the inverse of the current transform set on the
205        // SurfaceFlingerConsumer.
206        uint32_t invTransform = mCurrentTransform;
207        int winWidth = s.active.w;
208        int winHeight = s.active.h;
209        if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
210            invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
211                    NATIVE_WINDOW_TRANSFORM_FLIP_H;
212            winWidth = s.active.h;
213            winHeight = s.active.w;
214        }
215        Rect winCrop = s.active.crop.transform(invTransform,
216                s.active.w, s.active.h);
217
218        float xScale = float(crop.width()) / float(winWidth);
219        float yScale = float(crop.height()) / float(winHeight);
220        crop.left += int(ceilf(float(winCrop.left) * xScale));
221        crop.top += int(ceilf(float(winCrop.top) * yScale));
222        crop.right -= int(ceilf(float(winWidth - winCrop.right) * xScale));
223        crop.bottom -= int(ceilf(float(winHeight - winCrop.bottom) * yScale));
224    }
225
226    return crop;
227}
228
229void Layer::setGeometry(
230    const sp<const DisplayDevice>& hw,
231        HWComposer::HWCLayerInterface& layer)
232{
233    LayerBaseClient::setGeometry(hw, layer);
234
235    // enable this layer
236    layer.setSkip(false);
237
238    // we can't do alpha-fade with the hwc HAL
239    const State& s(drawingState());
240    if (s.alpha < 0xFF) {
241        layer.setSkip(true);
242    }
243
244    if (isSecure() && !hw->isSecure()) {
245        layer.setSkip(true);
246    }
247
248    /*
249     * Transformations are applied in this order:
250     * 1) buffer orientation/flip/mirror
251     * 2) state transformation (window manager)
252     * 3) layer orientation (screen orientation)
253     * (NOTE: the matrices are multiplied in reverse order)
254     */
255
256    const Transform bufferOrientation(mCurrentTransform);
257    const Transform tr(hw->getTransform() * s.transform * bufferOrientation);
258
259    // this gives us only the "orientation" component of the transform
260    const uint32_t finalTransform = tr.getOrientation();
261
262    // we can only handle simple transformation
263    if (finalTransform & Transform::ROT_INVALID) {
264        layer.setSkip(true);
265    } else {
266        layer.setTransform(finalTransform);
267    }
268    layer.setCrop(computeBufferCrop());
269}
270
271void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
272        HWComposer::HWCLayerInterface& layer) {
273    LayerBaseClient::setPerFrameData(hw, layer);
274    // NOTE: buffer can be NULL if the client never drew into this
275    // layer yet, or if we ran out of memory
276    layer.setBuffer(mActiveBuffer);
277}
278
279void Layer::setAcquireFence(const sp<const DisplayDevice>& hw,
280        HWComposer::HWCLayerInterface& layer) {
281    int fenceFd = -1;
282
283    // TODO: there is a possible optimization here: we only need to set the
284    // acquire fence the first time a new buffer is acquired on EACH display.
285
286    if (layer.getCompositionType() == HWC_OVERLAY) {
287        sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
288        if (fence.get()) {
289            fenceFd = fence->dup();
290            if (fenceFd == -1) {
291                ALOGW("failed to dup layer fence, skipping sync: %d", errno);
292            }
293        }
294    }
295    layer.setAcquireFenceFd(fenceFd);
296}
297
298void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip) const
299{
300    ATRACE_CALL();
301
302    if (CC_UNLIKELY(mActiveBuffer == 0)) {
303        // the texture has not been created yet, this Layer has
304        // in fact never been drawn into. This happens frequently with
305        // SurfaceView because the WindowManager can't know when the client
306        // has drawn the first time.
307
308        // If there is nothing under us, we paint the screen in black, otherwise
309        // we just skip this update.
310
311        // figure out if there is something below us
312        Region under;
313        const SurfaceFlinger::LayerVector& drawingLayers(
314                mFlinger->mDrawingState.layersSortedByZ);
315        const size_t count = drawingLayers.size();
316        for (size_t i=0 ; i<count ; ++i) {
317            const sp<LayerBase>& layer(drawingLayers[i]);
318            if (layer.get() == static_cast<LayerBase const*>(this))
319                break;
320            under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
321        }
322        // if not everything below us is covered, we plug the holes!
323        Region holes(clip.subtract(under));
324        if (!holes.isEmpty()) {
325            clearWithOpenGL(hw, holes, 0, 0, 0, 1);
326        }
327        return;
328    }
329
330    // Bind the current buffer to the GL texture.
331    status_t err = mSurfaceFlingerConsumer->bindTextureImage();
332    if (err != NO_ERROR) {
333        ALOGW("Layer::onDraw: bindTextureImage failed");
334        // keep going
335    }
336
337    // Wait for the buffer to be ready for us to draw into.
338    err = mSurfaceFlingerConsumer->doGLFenceWait();
339    if (err != OK) {
340        ALOGE("onDraw: failed waiting for fence: %d", err);
341        // Go ahead and draw the buffer anyway; no matter what we do the screen
342        // is probably going to have something visibly wrong.
343    }
344
345    bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
346
347    if (!blackOutLayer) {
348        // TODO: we could be more subtle with isFixedSize()
349        const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
350
351        // Query the texture matrix given our current filtering mode.
352        float textureMatrix[16];
353        mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
354        mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
355
356        // Set things up for texturing.
357        glBindTexture(GL_TEXTURE_EXTERNAL_OES, mTextureName);
358        GLenum filter = GL_NEAREST;
359        if (useFiltering) {
360            filter = GL_LINEAR;
361        }
362        glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, filter);
363        glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, filter);
364        glMatrixMode(GL_TEXTURE);
365        glLoadMatrixf(textureMatrix);
366        glMatrixMode(GL_MODELVIEW);
367        glDisable(GL_TEXTURE_2D);
368        glEnable(GL_TEXTURE_EXTERNAL_OES);
369    } else {
370        glBindTexture(GL_TEXTURE_2D, mFlinger->getProtectedTexName());
371        glMatrixMode(GL_TEXTURE);
372        glLoadIdentity();
373        glMatrixMode(GL_MODELVIEW);
374        glDisable(GL_TEXTURE_EXTERNAL_OES);
375        glEnable(GL_TEXTURE_2D);
376    }
377
378    drawWithOpenGL(hw, clip);
379
380    glDisable(GL_TEXTURE_EXTERNAL_OES);
381    glDisable(GL_TEXTURE_2D);
382}
383
384// As documented in libhardware header, formats in the range
385// 0x100 - 0x1FF are specific to the HAL implementation, and
386// are known to have no alpha channel
387// TODO: move definition for device-specific range into
388// hardware.h, instead of using hard-coded values here.
389#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
390
391bool Layer::getOpacityForFormat(uint32_t format)
392{
393    if (HARDWARE_IS_DEVICE_FORMAT(format)) {
394        return true;
395    }
396    PixelFormatInfo info;
397    status_t err = getPixelFormatInfo(PixelFormat(format), &info);
398    // in case of error (unknown format), we assume no blending
399    return (err || info.h_alpha <= info.l_alpha);
400}
401
402
403bool Layer::isOpaque() const
404{
405    // if we don't have a buffer yet, we're translucent regardless of the
406    // layer's opaque flag.
407    if (mActiveBuffer == 0) {
408        return false;
409    }
410
411    // if the layer has the opaque flag, then we're always opaque,
412    // otherwise we use the current buffer's format.
413    return mOpaqueLayer || mCurrentOpacity;
414}
415
416bool Layer::isProtected() const
417{
418    const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
419    return (activeBuffer != 0) &&
420            (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
421}
422
423uint32_t Layer::doTransaction(uint32_t flags)
424{
425    ATRACE_CALL();
426
427    const Layer::State& front(drawingState());
428    const Layer::State& temp(currentState());
429
430    const bool sizeChanged = (temp.requested.w != front.requested.w) ||
431                             (temp.requested.h != front.requested.h);
432
433    if (sizeChanged) {
434        // the size changed, we need to ask our client to request a new buffer
435        ALOGD_IF(DEBUG_RESIZE,
436                "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
437                "  current={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
438                "            requested={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }}\n"
439                "  drawing={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
440                "            requested={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }}\n",
441                this, (const char*) getName(), mCurrentTransform, mCurrentScalingMode,
442                temp.active.w, temp.active.h,
443                temp.active.crop.left,
444                temp.active.crop.top,
445                temp.active.crop.right,
446                temp.active.crop.bottom,
447                temp.active.crop.getWidth(),
448                temp.active.crop.getHeight(),
449                temp.requested.w, temp.requested.h,
450                temp.requested.crop.left,
451                temp.requested.crop.top,
452                temp.requested.crop.right,
453                temp.requested.crop.bottom,
454                temp.requested.crop.getWidth(),
455                temp.requested.crop.getHeight(),
456                front.active.w, front.active.h,
457                front.active.crop.left,
458                front.active.crop.top,
459                front.active.crop.right,
460                front.active.crop.bottom,
461                front.active.crop.getWidth(),
462                front.active.crop.getHeight(),
463                front.requested.w, front.requested.h,
464                front.requested.crop.left,
465                front.requested.crop.top,
466                front.requested.crop.right,
467                front.requested.crop.bottom,
468                front.requested.crop.getWidth(),
469                front.requested.crop.getHeight());
470
471        // record the new size, form this point on, when the client request
472        // a buffer, it'll get the new size.
473        mSurfaceFlingerConsumer->setDefaultBufferSize(
474                temp.requested.w, temp.requested.h);
475    }
476
477    if (!isFixedSize()) {
478
479        const bool resizePending = (temp.requested.w != temp.active.w) ||
480                                   (temp.requested.h != temp.active.h);
481
482        if (resizePending) {
483            // don't let LayerBase::doTransaction update the drawing state
484            // if we have a pending resize, unless we are in fixed-size mode.
485            // the drawing state will be updated only once we receive a buffer
486            // with the correct size.
487            //
488            // in particular, we want to make sure the clip (which is part
489            // of the geometry state) is latched together with the size but is
490            // latched immediately when no resizing is involved.
491
492            flags |= eDontUpdateGeometryState;
493        }
494    }
495
496    return LayerBase::doTransaction(flags);
497}
498
499bool Layer::isFixedSize() const {
500    return mCurrentScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE;
501}
502
503bool Layer::isCropped() const {
504    return !mCurrentCrop.isEmpty();
505}
506
507// ----------------------------------------------------------------------------
508// pageflip handling...
509// ----------------------------------------------------------------------------
510
511bool Layer::onPreComposition() {
512    mRefreshPending = false;
513    return mQueuedFrames > 0;
514}
515
516void Layer::onPostComposition() {
517    if (mFrameLatencyNeeded) {
518        nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
519        mFrameTracker.setDesiredPresentTime(desiredPresentTime);
520
521        sp<Fence> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFence();
522        if (frameReadyFence != NULL) {
523            mFrameTracker.setFrameReadyFence(frameReadyFence);
524        } else {
525            // There was no fence for this frame, so assume that it was ready
526            // to be presented at the desired present time.
527            mFrameTracker.setFrameReadyTime(desiredPresentTime);
528        }
529
530        const HWComposer& hwc = mFlinger->getHwComposer();
531        sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
532        // XXX: Temporarily don't use the present fence from HWC to work
533        // around a driver bug.
534        presentFence.clear();
535        if (presentFence != NULL) {
536            mFrameTracker.setActualPresentFence(presentFence);
537        } else {
538            // The HWC doesn't support present fences, so use the refresh
539            // timestamp instead.
540            nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
541            mFrameTracker.setActualPresentTime(presentTime);
542        }
543
544        mFrameTracker.advanceFrame();
545        mFrameLatencyNeeded = false;
546    }
547}
548
549bool Layer::isVisible() const {
550    return LayerBaseClient::isVisible() && (mActiveBuffer != NULL);
551}
552
553Region Layer::latchBuffer(bool& recomputeVisibleRegions)
554{
555    ATRACE_CALL();
556
557    Region outDirtyRegion;
558    if (mQueuedFrames > 0) {
559
560        // if we've already called updateTexImage() without going through
561        // a composition step, we have to skip this layer at this point
562        // because we cannot call updateTeximage() without a corresponding
563        // compositionComplete() call.
564        // we'll trigger an update in onPreComposition().
565        if (mRefreshPending) {
566            return outDirtyRegion;
567        }
568
569        // Capture the old state of the layer for comparisons later
570        const bool oldOpacity = isOpaque();
571        sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
572
573        // signal another event if we have more frames pending
574        if (android_atomic_dec(&mQueuedFrames) > 1) {
575            mFlinger->signalLayerUpdate();
576        }
577
578        struct Reject : public SurfaceFlingerConsumer::BufferRejecter {
579            Layer::State& front;
580            Layer::State& current;
581            bool& recomputeVisibleRegions;
582            Reject(Layer::State& front, Layer::State& current,
583                    bool& recomputeVisibleRegions)
584                : front(front), current(current),
585                  recomputeVisibleRegions(recomputeVisibleRegions) {
586            }
587
588            virtual bool reject(const sp<GraphicBuffer>& buf,
589                    const BufferQueue::BufferItem& item) {
590                if (buf == NULL) {
591                    return false;
592                }
593
594                uint32_t bufWidth  = buf->getWidth();
595                uint32_t bufHeight = buf->getHeight();
596
597                // check that we received a buffer of the right size
598                // (Take the buffer's orientation into account)
599                if (item.mTransform & Transform::ROT_90) {
600                    swap(bufWidth, bufHeight);
601                }
602
603
604                bool isFixedSize = item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE;
605                if (front.active != front.requested) {
606
607                    if (isFixedSize ||
608                            (bufWidth == front.requested.w &&
609                             bufHeight == front.requested.h))
610                    {
611                        // Here we pretend the transaction happened by updating the
612                        // current and drawing states. Drawing state is only accessed
613                        // in this thread, no need to have it locked
614                        front.active = front.requested;
615
616                        // We also need to update the current state so that
617                        // we don't end-up overwriting the drawing state with
618                        // this stale current state during the next transaction
619                        //
620                        // NOTE: We don't need to hold the transaction lock here
621                        // because State::active is only accessed from this thread.
622                        current.active = front.active;
623
624                        // recompute visible region
625                        recomputeVisibleRegions = true;
626                    }
627
628                    ALOGD_IF(DEBUG_RESIZE,
629                            "latchBuffer/reject: buffer (%ux%u, tr=%02x), scalingMode=%d\n"
630                            "  drawing={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
631                            "            requested={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }}\n",
632                            bufWidth, bufHeight, item.mTransform, item.mScalingMode,
633                            front.active.w, front.active.h,
634                            front.active.crop.left,
635                            front.active.crop.top,
636                            front.active.crop.right,
637                            front.active.crop.bottom,
638                            front.active.crop.getWidth(),
639                            front.active.crop.getHeight(),
640                            front.requested.w, front.requested.h,
641                            front.requested.crop.left,
642                            front.requested.crop.top,
643                            front.requested.crop.right,
644                            front.requested.crop.bottom,
645                            front.requested.crop.getWidth(),
646                            front.requested.crop.getHeight());
647                }
648
649                if (!isFixedSize) {
650                    if (front.active.w != bufWidth ||
651                        front.active.h != bufHeight) {
652                        // reject this buffer
653                        return true;
654                    }
655                }
656                return false;
657            }
658        };
659
660
661        Reject r(mDrawingState, currentState(), recomputeVisibleRegions);
662
663        if (mSurfaceFlingerConsumer->updateTexImage(&r) != NO_ERROR) {
664            // something happened!
665            recomputeVisibleRegions = true;
666            return outDirtyRegion;
667        }
668
669        // update the active buffer
670        mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer();
671        if (mActiveBuffer == NULL) {
672            // this can only happen if the very first buffer was rejected.
673            return outDirtyRegion;
674        }
675
676        mRefreshPending = true;
677        mFrameLatencyNeeded = true;
678        if (oldActiveBuffer == NULL) {
679             // the first time we receive a buffer, we need to trigger a
680             // geometry invalidation.
681            recomputeVisibleRegions = true;
682         }
683
684        Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
685        const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
686        const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
687        if ((crop != mCurrentCrop) ||
688            (transform != mCurrentTransform) ||
689            (scalingMode != mCurrentScalingMode))
690        {
691            mCurrentCrop = crop;
692            mCurrentTransform = transform;
693            mCurrentScalingMode = scalingMode;
694            recomputeVisibleRegions = true;
695        }
696
697        if (oldActiveBuffer != NULL) {
698            uint32_t bufWidth  = mActiveBuffer->getWidth();
699            uint32_t bufHeight = mActiveBuffer->getHeight();
700            if (bufWidth != uint32_t(oldActiveBuffer->width) ||
701                bufHeight != uint32_t(oldActiveBuffer->height)) {
702                recomputeVisibleRegions = true;
703            }
704        }
705
706        mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
707        if (oldOpacity != isOpaque()) {
708            recomputeVisibleRegions = true;
709        }
710
711        glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
712        glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
713
714        // FIXME: postedRegion should be dirty & bounds
715        const Layer::State& front(drawingState());
716        Region dirtyRegion(Rect(front.active.w, front.active.h));
717
718        // transform the dirty region to window-manager space
719        outDirtyRegion = (front.transform.transform(dirtyRegion));
720    }
721    return outDirtyRegion;
722}
723
724void Layer::dump(String8& result, char* buffer, size_t SIZE) const
725{
726    LayerBaseClient::dump(result, buffer, SIZE);
727
728    sp<const GraphicBuffer> buf0(mActiveBuffer);
729    uint32_t w0=0, h0=0, s0=0, f0=0;
730    if (buf0 != 0) {
731        w0 = buf0->getWidth();
732        h0 = buf0->getHeight();
733        s0 = buf0->getStride();
734        f0 = buf0->format;
735    }
736    snprintf(buffer, SIZE,
737            "      "
738            "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
739            " queued-frames=%d, mRefreshPending=%d\n",
740            mFormat, w0, h0, s0,f0,
741            mQueuedFrames, mRefreshPending);
742
743    result.append(buffer);
744
745    if (mSurfaceFlingerConsumer != 0) {
746        mSurfaceFlingerConsumer->dump(result, "            ", buffer, SIZE);
747    }
748}
749
750void Layer::dumpStats(String8& result, char* buffer, size_t SIZE) const
751{
752    LayerBaseClient::dumpStats(result, buffer, SIZE);
753    const nsecs_t period =
754            mFlinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
755    result.appendFormat("%lld\n", period);
756    mFrameTracker.dump(result);
757}
758
759void Layer::clearStats()
760{
761    LayerBaseClient::clearStats();
762    mFrameTracker.clear();
763}
764
765uint32_t Layer::getEffectiveUsage(uint32_t usage) const
766{
767    // TODO: should we do something special if mSecure is set?
768    if (mProtectedByApp) {
769        // need a hardware-protected path to external video sink
770        usage |= GraphicBuffer::USAGE_PROTECTED;
771    }
772    usage |= GraphicBuffer::USAGE_HW_COMPOSER;
773    return usage;
774}
775
776void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
777    uint32_t orientation = 0;
778    if (!mFlinger->mDebugDisableTransformHint) {
779        // The transform hint is used to improve performance, but we can
780        // only have a single transform hint, it cannot
781        // apply to all displays.
782        const Transform& planeTransform(hw->getTransform());
783        orientation = planeTransform.getOrientation();
784        if (orientation & Transform::ROT_INVALID) {
785            orientation = 0;
786        }
787    }
788    mSurfaceFlingerConsumer->setTransformHint(orientation);
789}
790
791// ---------------------------------------------------------------------------
792
793
794}; // namespace android
795