Layer.cpp revision e8696a40e09b24b634214684d18526187b316a2f
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#include <stdlib.h>
18#include <stdint.h>
19#include <sys/types.h>
20
21#include <cutils/compiler.h>
22#include <cutils/native_handle.h>
23#include <cutils/properties.h>
24
25#include <utils/Errors.h>
26#include <utils/Log.h>
27#include <utils/StopWatch.h>
28
29#include <ui/GraphicBuffer.h>
30#include <ui/PixelFormat.h>
31
32#include <surfaceflinger/Surface.h>
33
34#include "clz.h"
35#include "DisplayHardware/DisplayHardware.h"
36#include "DisplayHardware/HWComposer.h"
37#include "GLExtensions.h"
38#include "Layer.h"
39#include "SurfaceFlinger.h"
40#include "SurfaceTextureLayer.h"
41
42#define DEBUG_RESIZE    0
43
44
45namespace android {
46
47// ---------------------------------------------------------------------------
48
49Layer::Layer(SurfaceFlinger* flinger,
50        DisplayID display, const sp<Client>& client)
51    :   LayerBaseClient(flinger, display, client),
52        mTextureName(-1U),
53        mQueuedFrames(0),
54        mCurrentTransform(0),
55        mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
56        mCurrentOpacity(true),
57        mFormat(PIXEL_FORMAT_NONE),
58        mGLExtensions(GLExtensions::getInstance()),
59        mOpaqueLayer(true),
60        mNeedsDithering(false),
61        mSecure(false),
62        mProtectedByApp(false)
63{
64    mCurrentCrop.makeInvalid();
65    glGenTextures(1, &mTextureName);
66
67    mFrameLatencyNeeded = false;
68    mFrameLatencyOffset = 0;
69    for (int i = 0; i < 128; i++) {
70        mFrameLatencies[i] = 0;
71    }
72}
73
74void Layer::onLayerDisplayed() {
75    if (mFrameLatencyNeeded) {
76        int64_t now = systemTime(SYSTEM_TIME_MONOTONIC);
77        mFrameLatencies[mFrameLatencyOffset] = now -
78                mSurfaceTexture->getTimestamp();
79        mFrameLatencyOffset = (mFrameLatencyOffset + 1) % 128;
80        mFrameLatencyNeeded = false;
81    }
82}
83
84void Layer::onFirstRef()
85{
86    LayerBaseClient::onFirstRef();
87
88    struct FrameQueuedListener : public SurfaceTexture::FrameAvailableListener {
89        FrameQueuedListener(Layer* layer) : mLayer(layer) { }
90    private:
91        wp<Layer> mLayer;
92        virtual void onFrameAvailable() {
93            sp<Layer> that(mLayer.promote());
94            if (that != 0) {
95                that->onFrameQueued();
96            }
97        }
98    };
99    mSurfaceTexture = new SurfaceTextureLayer(mTextureName, this);
100    mSurfaceTexture->setFrameAvailableListener(new FrameQueuedListener(this));
101    mSurfaceTexture->setSynchronousMode(true);
102    mSurfaceTexture->setBufferCountServer(2);
103}
104
105Layer::~Layer()
106{
107    mFlinger->postMessageAsync(
108            new SurfaceFlinger::MessageDestroyGLTexture(mTextureName) );
109}
110
111void Layer::onFrameQueued() {
112    android_atomic_inc(&mQueuedFrames);
113    mFlinger->signalEvent();
114}
115
116// called with SurfaceFlinger::mStateLock as soon as the layer is entered
117// in the purgatory list
118void Layer::onRemoved()
119{
120    mSurfaceTexture->abandon();
121}
122
123void Layer::setName(const String8& name) {
124    LayerBase::setName(name);
125    mSurfaceTexture->setName(name);
126}
127
128sp<ISurface> Layer::createSurface()
129{
130    class BSurface : public BnSurface, public LayerCleaner {
131        wp<const Layer> mOwner;
132        virtual sp<ISurfaceTexture> getSurfaceTexture() const {
133            sp<ISurfaceTexture> res;
134            sp<const Layer> that( mOwner.promote() );
135            if (that != NULL) {
136                res = that->mSurfaceTexture;
137            }
138            return res;
139        }
140    public:
141        BSurface(const sp<SurfaceFlinger>& flinger,
142                const sp<Layer>& layer)
143            : LayerCleaner(flinger, layer), mOwner(layer) { }
144    };
145    sp<ISurface> sur(new BSurface(mFlinger, this));
146    return sur;
147}
148
149wp<IBinder> Layer::getSurfaceTextureBinder() const
150{
151    return mSurfaceTexture->asBinder();
152}
153
154status_t Layer::setBuffers( uint32_t w, uint32_t h,
155                            PixelFormat format, uint32_t flags)
156{
157    // this surfaces pixel format
158    PixelFormatInfo info;
159    status_t err = getPixelFormatInfo(format, &info);
160    if (err) return err;
161
162    // the display's pixel format
163    const DisplayHardware& hw(graphicPlane(0).displayHardware());
164    uint32_t const maxSurfaceDims = min(
165            hw.getMaxTextureSize(), hw.getMaxViewportDims());
166
167    // never allow a surface larger than what our underlying GL implementation
168    // can handle.
169    if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
170        return BAD_VALUE;
171    }
172
173    PixelFormatInfo displayInfo;
174    getPixelFormatInfo(hw.getFormat(), &displayInfo);
175    const uint32_t hwFlags = hw.getFlags();
176
177    mFormat = format;
178
179    mSecure = (flags & ISurfaceComposer::eSecure) ? true : false;
180    mProtectedByApp = (flags & ISurfaceComposer::eProtectedByApp) ? true : false;
181    mOpaqueLayer = (flags & ISurfaceComposer::eOpaque);
182    mCurrentOpacity = getOpacityForFormat(format);
183
184    mSurfaceTexture->setDefaultBufferSize(w, h);
185    mSurfaceTexture->setDefaultBufferFormat(format);
186
187    // we use the red index
188    int displayRedSize = displayInfo.getSize(PixelFormatInfo::INDEX_RED);
189    int layerRedsize = info.getSize(PixelFormatInfo::INDEX_RED);
190    mNeedsDithering = layerRedsize > displayRedSize;
191
192    return NO_ERROR;
193}
194
195void Layer::setGeometry(hwc_layer_t* hwcl)
196{
197    LayerBaseClient::setGeometry(hwcl);
198
199    hwcl->flags &= ~HWC_SKIP_LAYER;
200
201    // we can't do alpha-fade with the hwc HAL
202    const State& s(drawingState());
203    if (s.alpha < 0xFF) {
204        hwcl->flags = HWC_SKIP_LAYER;
205    }
206
207    /*
208     * Transformations are applied in this order:
209     * 1) buffer orientation/flip/mirror
210     * 2) state transformation (window manager)
211     * 3) layer orientation (screen orientation)
212     * mTransform is already the composition of (2) and (3)
213     * (NOTE: the matrices are multiplied in reverse order)
214     */
215
216    const Transform bufferOrientation(mCurrentTransform);
217    const Transform tr(mTransform * bufferOrientation);
218
219    // this gives us only the "orientation" component of the transform
220    const uint32_t finalTransform = tr.getOrientation();
221
222    // we can only handle simple transformation
223    if (finalTransform & Transform::ROT_INVALID) {
224        hwcl->flags = HWC_SKIP_LAYER;
225    } else {
226        hwcl->transform = finalTransform;
227    }
228
229    if (isCropped()) {
230        hwcl->sourceCrop.left   = mCurrentCrop.left;
231        hwcl->sourceCrop.top    = mCurrentCrop.top;
232        hwcl->sourceCrop.right  = mCurrentCrop.right;
233        hwcl->sourceCrop.bottom = mCurrentCrop.bottom;
234    } else {
235        const sp<GraphicBuffer>& buffer(mActiveBuffer);
236        hwcl->sourceCrop.left   = 0;
237        hwcl->sourceCrop.top    = 0;
238        if (buffer != NULL) {
239            hwcl->sourceCrop.right  = buffer->width;
240            hwcl->sourceCrop.bottom = buffer->height;
241        } else {
242            hwcl->sourceCrop.right  = mTransformedBounds.width();
243            hwcl->sourceCrop.bottom = mTransformedBounds.height();
244        }
245    }
246}
247
248void Layer::setPerFrameData(hwc_layer_t* hwcl) {
249    const sp<GraphicBuffer>& buffer(mActiveBuffer);
250    if (buffer == NULL) {
251        // this can happen if the client never drew into this layer yet,
252        // or if we ran out of memory. In that case, don't let
253        // HWC handle it.
254        hwcl->flags |= HWC_SKIP_LAYER;
255        hwcl->handle = NULL;
256    } else {
257        hwcl->handle = buffer->handle;
258    }
259}
260
261void Layer::onDraw(const Region& clip) const
262{
263    if (CC_UNLIKELY(mActiveBuffer == 0)) {
264        // the texture has not been created yet, this Layer has
265        // in fact never been drawn into. This happens frequently with
266        // SurfaceView because the WindowManager can't know when the client
267        // has drawn the first time.
268
269        // If there is nothing under us, we paint the screen in black, otherwise
270        // we just skip this update.
271
272        // figure out if there is something below us
273        Region under;
274        const SurfaceFlinger::LayerVector& drawingLayers(
275                mFlinger->mDrawingState.layersSortedByZ);
276        const size_t count = drawingLayers.size();
277        for (size_t i=0 ; i<count ; ++i) {
278            const sp<LayerBase>& layer(drawingLayers[i]);
279            if (layer.get() == static_cast<LayerBase const*>(this))
280                break;
281            under.orSelf(layer->visibleRegionScreen);
282        }
283        // if not everything below us is covered, we plug the holes!
284        Region holes(clip.subtract(under));
285        if (!holes.isEmpty()) {
286            clearWithOpenGL(holes, 0, 0, 0, 1);
287        }
288        return;
289    }
290
291    if (!isProtected()) {
292        glBindTexture(GL_TEXTURE_EXTERNAL_OES, mTextureName);
293        GLenum filter = GL_NEAREST;
294        if (getFiltering() || needsFiltering() || isFixedSize() || isCropped()) {
295            // TODO: we could be more subtle with isFixedSize()
296            filter = GL_LINEAR;
297        }
298        glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, filter);
299        glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, filter);
300        glMatrixMode(GL_TEXTURE);
301        glLoadMatrixf(mTextureMatrix);
302        glMatrixMode(GL_MODELVIEW);
303        glDisable(GL_TEXTURE_2D);
304        glEnable(GL_TEXTURE_EXTERNAL_OES);
305    } else {
306        glBindTexture(GL_TEXTURE_2D, mFlinger->getProtectedTexName());
307        glMatrixMode(GL_TEXTURE);
308        glLoadIdentity();
309        glMatrixMode(GL_MODELVIEW);
310        glDisable(GL_TEXTURE_EXTERNAL_OES);
311        glEnable(GL_TEXTURE_2D);
312    }
313
314    drawWithOpenGL(clip);
315
316    glDisable(GL_TEXTURE_EXTERNAL_OES);
317    glDisable(GL_TEXTURE_2D);
318}
319
320// As documented in libhardware header, formats in the range
321// 0x100 - 0x1FF are specific to the HAL implementation, and
322// are known to have no alpha channel
323// TODO: move definition for device-specific range into
324// hardware.h, instead of using hard-coded values here.
325#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
326
327bool Layer::getOpacityForFormat(uint32_t format)
328{
329    if (HARDWARE_IS_DEVICE_FORMAT(format)) {
330        return true;
331    }
332    PixelFormatInfo info;
333    status_t err = getPixelFormatInfo(PixelFormat(format), &info);
334    // in case of error (unknown format), we assume no blending
335    return (err || info.h_alpha <= info.l_alpha);
336}
337
338
339bool Layer::isOpaque() const
340{
341    // if we don't have a buffer yet, we're translucent regardless of the
342    // layer's opaque flag.
343    if (mActiveBuffer == 0) {
344        return false;
345    }
346
347    // if the layer has the opaque flag, then we're always opaque,
348    // otherwise we use the current buffer's format.
349    return mOpaqueLayer || mCurrentOpacity;
350}
351
352bool Layer::isProtected() const
353{
354    const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
355    return (activeBuffer != 0) &&
356            (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
357}
358
359uint32_t Layer::doTransaction(uint32_t flags)
360{
361    const Layer::State& front(drawingState());
362    const Layer::State& temp(currentState());
363
364    const bool sizeChanged = (front.requested_w != temp.requested_w) ||
365            (front.requested_h != temp.requested_h);
366
367    if (sizeChanged) {
368        // the size changed, we need to ask our client to request a new buffer
369        ALOGD_IF(DEBUG_RESIZE,
370                "doTransaction: "
371                "resize (layer=%p), requested (%dx%d), drawing (%d,%d), "
372                "scalingMode=%d",
373                this,
374                int(temp.requested_w), int(temp.requested_h),
375                int(front.requested_w), int(front.requested_h),
376                mCurrentScalingMode);
377
378        if (!isFixedSize()) {
379            // this will make sure LayerBase::doTransaction doesn't update
380            // the drawing state's size
381            Layer::State& editDraw(mDrawingState);
382            editDraw.requested_w = temp.requested_w;
383            editDraw.requested_h = temp.requested_h;
384        }
385
386        // record the new size, form this point on, when the client request
387        // a buffer, it'll get the new size.
388        mSurfaceTexture->setDefaultBufferSize(temp.requested_w,
389                temp.requested_h);
390    }
391
392    return LayerBase::doTransaction(flags);
393}
394
395bool Layer::isFixedSize() const {
396    return mCurrentScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE;
397}
398
399bool Layer::isCropped() const {
400    return !mCurrentCrop.isEmpty();
401}
402
403// ----------------------------------------------------------------------------
404// pageflip handling...
405// ----------------------------------------------------------------------------
406
407void Layer::lockPageFlip(bool& recomputeVisibleRegions)
408{
409    if (mQueuedFrames > 0) {
410        // Capture the old state of the layer for comparisons later
411        const bool oldOpacity = isOpaque();
412        sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
413
414        // signal another event if we have more frames pending
415        if (android_atomic_dec(&mQueuedFrames) > 1) {
416            mFlinger->signalEvent();
417        }
418
419        if (mSurfaceTexture->updateTexImage() < NO_ERROR) {
420            // something happened!
421            recomputeVisibleRegions = true;
422            return;
423        }
424
425        // update the active buffer
426        mActiveBuffer = mSurfaceTexture->getCurrentBuffer();
427        mFrameLatencyNeeded = true;
428
429        const Rect crop(mSurfaceTexture->getCurrentCrop());
430        const uint32_t transform(mSurfaceTexture->getCurrentTransform());
431        const uint32_t scalingMode(mSurfaceTexture->getCurrentScalingMode());
432        if ((crop != mCurrentCrop) ||
433            (transform != mCurrentTransform) ||
434            (scalingMode != mCurrentScalingMode))
435        {
436            mCurrentCrop = crop;
437            mCurrentTransform = transform;
438            mCurrentScalingMode = scalingMode;
439            mFlinger->invalidateHwcGeometry();
440        }
441
442        GLfloat textureMatrix[16];
443        mSurfaceTexture->getTransformMatrix(textureMatrix);
444        if (memcmp(textureMatrix, mTextureMatrix, sizeof(textureMatrix))) {
445            memcpy(mTextureMatrix, textureMatrix, sizeof(textureMatrix));
446            mFlinger->invalidateHwcGeometry();
447        }
448
449        uint32_t bufWidth  = mActiveBuffer->getWidth();
450        uint32_t bufHeight = mActiveBuffer->getHeight();
451        if (oldActiveBuffer != NULL) {
452            if (bufWidth != uint32_t(oldActiveBuffer->width) ||
453                bufHeight != uint32_t(oldActiveBuffer->height)) {
454                mFlinger->invalidateHwcGeometry();
455            }
456        }
457
458        mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
459        if (oldOpacity != isOpaque()) {
460            recomputeVisibleRegions = true;
461        }
462
463        glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
464        glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
465
466        // update the layer size if needed
467        const Layer::State& front(drawingState());
468
469        // FIXME: mPostedDirtyRegion = dirty & bounds
470        mPostedDirtyRegion.set(front.w, front.h);
471
472        if ((front.w != front.requested_w) ||
473            (front.h != front.requested_h))
474        {
475            // check that we received a buffer of the right size
476            // (Take the buffer's orientation into account)
477            if (mCurrentTransform & Transform::ROT_90) {
478                swap(bufWidth, bufHeight);
479            }
480
481            if (isFixedSize() ||
482                    (bufWidth == front.requested_w &&
483                    bufHeight == front.requested_h))
484            {
485                // Here we pretend the transaction happened by updating the
486                // current and drawing states. Drawing state is only accessed
487                // in this thread, no need to have it locked
488                Layer::State& editDraw(mDrawingState);
489                editDraw.w = editDraw.requested_w;
490                editDraw.h = editDraw.requested_h;
491
492                // We also need to update the current state so that we don't
493                // end-up doing too much work during the next transaction.
494                // NOTE: We actually don't need hold the transaction lock here
495                // because State::w and State::h are only accessed from
496                // this thread
497                Layer::State& editTemp(currentState());
498                editTemp.w = editDraw.w;
499                editTemp.h = editDraw.h;
500
501                // recompute visible region
502                recomputeVisibleRegions = true;
503            }
504
505            ALOGD_IF(DEBUG_RESIZE,
506                    "lockPageFlip : "
507                    "       (layer=%p), buffer (%ux%u, tr=%02x), "
508                    "requested (%dx%d)",
509                    this,
510                    bufWidth, bufHeight, mCurrentTransform,
511                    front.requested_w, front.requested_h);
512        }
513    }
514}
515
516void Layer::unlockPageFlip(
517        const Transform& planeTransform, Region& outDirtyRegion)
518{
519    Region dirtyRegion(mPostedDirtyRegion);
520    if (!dirtyRegion.isEmpty()) {
521        mPostedDirtyRegion.clear();
522        // The dirty region is given in the layer's coordinate space
523        // transform the dirty region by the surface's transformation
524        // and the global transformation.
525        const Layer::State& s(drawingState());
526        const Transform tr(planeTransform * s.transform);
527        dirtyRegion = tr.transform(dirtyRegion);
528
529        // At this point, the dirty region is in screen space.
530        // Make sure it's constrained by the visible region (which
531        // is in screen space as well).
532        dirtyRegion.andSelf(visibleRegionScreen);
533        outDirtyRegion.orSelf(dirtyRegion);
534    }
535}
536
537void Layer::dump(String8& result, char* buffer, size_t SIZE) const
538{
539    LayerBaseClient::dump(result, buffer, SIZE);
540
541    sp<const GraphicBuffer> buf0(mActiveBuffer);
542    uint32_t w0=0, h0=0, s0=0, f0=0;
543    if (buf0 != 0) {
544        w0 = buf0->getWidth();
545        h0 = buf0->getHeight();
546        s0 = buf0->getStride();
547        f0 = buf0->format;
548    }
549    snprintf(buffer, SIZE,
550            "      "
551            "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
552            " transform-hint=0x%02x, queued-frames=%d\n",
553            mFormat, w0, h0, s0,f0,
554            getTransformHint(), mQueuedFrames);
555
556    result.append(buffer);
557
558    const int64_t* l = mFrameLatencies;
559    int o = mFrameLatencyOffset;
560    for (int i = 0; i < 128; i += 8) {
561        snprintf(buffer, SIZE,
562                "      "
563                "% 12lld % 12lld % 12lld % 12lld "
564                "% 12lld % 12lld % 12lld % 12lld\n",
565                l[(o+i+0)%128], l[(o+i+1)%128], l[(o+i+2)%128], l[(o+i+3)%128],
566                l[(o+i+4)%128], l[(o+i+5)%128], l[(o+i+6)%128], l[(o+i+7)%128]);
567        result.append(buffer);
568    }
569
570    if (mSurfaceTexture != 0) {
571        mSurfaceTexture->dump(result, "            ", buffer, SIZE);
572    }
573}
574
575uint32_t Layer::getEffectiveUsage(uint32_t usage) const
576{
577    // TODO: should we do something special if mSecure is set?
578    if (mProtectedByApp) {
579        // need a hardware-protected path to external video sink
580        usage |= GraphicBuffer::USAGE_PROTECTED;
581    }
582    usage |= GraphicBuffer::USAGE_HW_COMPOSER;
583    return usage;
584}
585
586uint32_t Layer::getTransformHint() const {
587    uint32_t orientation = 0;
588    if (!mFlinger->mDebugDisableTransformHint) {
589        orientation = getPlaneOrientation();
590        if (orientation & Transform::ROT_INVALID) {
591            orientation = 0;
592        }
593    }
594    return orientation;
595}
596
597// ---------------------------------------------------------------------------
598
599
600}; // namespace android
601