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