Layer.cpp revision d606de6bb6877dc4ab93ec0be0c6bda4a8ee1ce8
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/properties.h>
22#include <cutils/native_handle.h>
23
24#include <utils/Errors.h>
25#include <utils/Log.h>
26#include <utils/StopWatch.h>
27
28#include <ui/GraphicBuffer.h>
29#include <ui/PixelFormat.h>
30
31#include <surfaceflinger/Surface.h>
32
33#include "clz.h"
34#include "Layer.h"
35#include "SurfaceFlinger.h"
36#include "DisplayHardware/DisplayHardware.h"
37
38
39#define DEBUG_RESIZE    0
40
41
42namespace android {
43
44template <typename T> inline T min(T a, T b) {
45    return a<b ? a : b;
46}
47
48// ---------------------------------------------------------------------------
49
50Layer::Layer(SurfaceFlinger* flinger, DisplayID display,
51        const sp<Client>& client, int32_t i)
52    :   LayerBaseClient(flinger, display, client, i),
53        lcblk(NULL),
54        mSecure(false),
55        mNeedsBlending(true),
56        mNeedsDithering(false),
57        mTextureManager(mFlags),
58        mBufferManager(mTextureManager)
59{
60    // no OpenGL operation is possible here, since we might not be
61    // in the OpenGL thread.
62    lcblk = new SharedBufferServer(
63            client->ctrlblk, i, mBufferManager.getBufferCount(),
64            getIdentity());
65
66   mBufferManager.setActiveBufferIndex( lcblk->getFrontBuffer() );
67}
68
69Layer::~Layer()
70{
71    destroy();
72    // the actual buffers will be destroyed here
73    delete lcblk;
74}
75
76// called with SurfaceFlinger::mStateLock as soon as the layer is entered
77// in the purgatory list
78void Layer::onRemoved()
79{
80    // wake up the condition
81    lcblk->setStatus(NO_INIT);
82}
83
84void Layer::destroy()
85{
86    EGLDisplay dpy(mFlinger->graphicPlane(0).getEGLDisplay());
87    mBufferManager.destroy(dpy);
88
89    mSurface.clear();
90
91    Mutex::Autolock _l(mLock);
92    mWidth = mHeight = 0;
93}
94
95sp<LayerBaseClient::Surface> Layer::createSurface() const
96{
97    return mSurface;
98}
99
100status_t Layer::ditch()
101{
102    // the layer is not on screen anymore. free as much resources as possible
103    mFreezeLock.clear();
104    destroy();
105    return NO_ERROR;
106}
107
108status_t Layer::setBuffers( uint32_t w, uint32_t h,
109                            PixelFormat format, uint32_t flags)
110{
111    // this surfaces pixel format
112    PixelFormatInfo info;
113    status_t err = getPixelFormatInfo(format, &info);
114    if (err) return err;
115
116    // the display's pixel format
117    const DisplayHardware& hw(graphicPlane(0).displayHardware());
118    uint32_t const maxSurfaceDims = min(
119            hw.getMaxTextureSize(), hw.getMaxViewportDims());
120
121    // never allow a surface larger than what our underlying GL implementation
122    // can handle.
123    if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
124        return BAD_VALUE;
125    }
126
127    PixelFormatInfo displayInfo;
128    getPixelFormatInfo(hw.getFormat(), &displayInfo);
129    const uint32_t hwFlags = hw.getFlags();
130
131    mFormat = format;
132    mWidth  = w;
133    mHeight = h;
134    mSecure = (flags & ISurfaceComposer::eSecure) ? true : false;
135    mNeedsBlending = (info.h_alpha - info.l_alpha) > 0;
136
137    // we use the red index
138    int displayRedSize = displayInfo.getSize(PixelFormatInfo::INDEX_RED);
139    int layerRedsize = info.getSize(PixelFormatInfo::INDEX_RED);
140    mNeedsDithering = layerRedsize > displayRedSize;
141
142    mSurface = new SurfaceLayer(mFlinger, clientIndex(), this);
143    return NO_ERROR;
144}
145
146void Layer::reloadTexture(const Region& dirty)
147{
148    sp<GraphicBuffer> buffer(mBufferManager.getActiveBuffer());
149    if (buffer == NULL) {
150        // this situation can happen if we ran out of memory for instance.
151        // not much we can do. continue to use whatever texture was bound
152        // to this context.
153        return;
154    }
155
156#ifdef EGL_ANDROID_image_native_buffer
157    if (mFlags & DisplayHardware::DIRECT_TEXTURE) {
158        EGLDisplay dpy(mFlinger->graphicPlane(0).getEGLDisplay());
159        if (mBufferManager.initEglImage(dpy, buffer) != NO_ERROR) {
160            // not sure what we can do here...
161            mFlags &= ~DisplayHardware::DIRECT_TEXTURE;
162            goto slowpath;
163        }
164    } else
165#endif
166    {
167slowpath:
168        GGLSurface t;
169        status_t res = buffer->lock(&t, GRALLOC_USAGE_SW_READ_OFTEN);
170        LOGE_IF(res, "error %d (%s) locking buffer %p",
171                res, strerror(res), buffer.get());
172        if (res == NO_ERROR) {
173            mBufferManager.loadTexture(dirty, t);
174            buffer->unlock();
175        }
176    }
177}
178
179void Layer::onDraw(const Region& clip) const
180{
181    Texture tex(mBufferManager.getActiveTexture());
182    if (tex.name == -1LU) {
183        // the texture has not been created yet, this Layer has
184        // in fact never been drawn into. This happens frequently with
185        // SurfaceView because the WindowManager can't know when the client
186        // has drawn the first time.
187
188        // If there is nothing under us, we paint the screen in black, otherwise
189        // we just skip this update.
190
191        // figure out if there is something below us
192        Region under;
193        const SurfaceFlinger::LayerVector& drawingLayers(mFlinger->mDrawingState.layersSortedByZ);
194        const size_t count = drawingLayers.size();
195        for (size_t i=0 ; i<count ; ++i) {
196            const sp<LayerBase>& layer(drawingLayers[i]);
197            if (layer.get() == static_cast<LayerBase const*>(this))
198                break;
199            under.orSelf(layer->visibleRegionScreen);
200        }
201        // if not everything below us is covered, we plug the holes!
202        Region holes(clip.subtract(under));
203        if (!holes.isEmpty()) {
204            clearWithOpenGL(holes);
205        }
206        return;
207    }
208    drawWithOpenGL(clip, tex);
209}
210
211sp<GraphicBuffer> Layer::requestBuffer(int index, int usage)
212{
213    sp<GraphicBuffer> buffer;
214
215    // this ensures our client doesn't go away while we're accessing
216    // the shared area.
217    sp<Client> ourClient(client.promote());
218    if (ourClient == 0) {
219        // oops, the client is already gone
220        return buffer;
221    }
222
223    /*
224     * This is called from the client's Surface::dequeue(). This can happen
225     * at any time, especially while we're in the middle of using the
226     * buffer 'index' as our front buffer.
227     *
228     * Make sure the buffer we're resizing is not the front buffer and has been
229     * dequeued. Once this condition is asserted, we are guaranteed that this
230     * buffer cannot become the front buffer under our feet, since we're called
231     * from Surface::dequeue()
232     */
233    status_t err = lcblk->assertReallocate(index);
234    LOGE_IF(err, "assertReallocate(%d) failed (%s)", index, strerror(-err));
235    if (err != NO_ERROR) {
236        // the surface may have died
237        return buffer;
238    }
239
240    uint32_t w, h;
241    { // scope for the lock
242        Mutex::Autolock _l(mLock);
243        w = mWidth;
244        h = mHeight;
245        buffer = mBufferManager.detachBuffer(index);
246    }
247
248    const uint32_t effectiveUsage = getEffectiveUsage(usage);
249    if (buffer!=0 && buffer->getStrongCount() == 1) {
250        err = buffer->reallocate(w, h, mFormat, effectiveUsage);
251    } else {
252        // here we have to reallocate a new buffer because we could have a
253        // client in our process with a reference to it (eg: status bar),
254        // and we can't release the handle under its feet.
255        buffer.clear();
256        buffer = new GraphicBuffer(w, h, mFormat, effectiveUsage);
257        err = buffer->initCheck();
258    }
259
260    if (err || buffer->handle == 0) {
261        LOGE_IF(err || buffer->handle == 0,
262                "Layer::requestBuffer(this=%p), index=%d, w=%d, h=%d failed (%s)",
263                this, index, w, h, strerror(-err));
264    } else {
265        LOGD_IF(DEBUG_RESIZE,
266                "Layer::requestBuffer(this=%p), index=%d, w=%d, h=%d, handle=%p",
267                this, index, w, h, buffer->handle);
268    }
269
270    if (err == NO_ERROR && buffer->handle != 0) {
271        Mutex::Autolock _l(mLock);
272        if (mWidth && mHeight) {
273            mBufferManager.attachBuffer(index, buffer);
274        } else {
275            // oops we got killed while we were allocating the buffer
276            buffer.clear();
277        }
278    }
279    return buffer;
280}
281
282uint32_t Layer::getEffectiveUsage(uint32_t usage) const
283{
284    /*
285     *  buffers used for software rendering, but h/w composition
286     *  are allocated with SW_READ_OFTEN | SW_WRITE_OFTEN | HW_TEXTURE
287     *
288     *  buffers used for h/w rendering and h/w composition
289     *  are allocated with  HW_RENDER | HW_TEXTURE
290     *
291     *  buffers used with h/w rendering and either NPOT or no egl_image_ext
292     *  are allocated with SW_READ_RARELY | HW_RENDER
293     *
294     */
295
296    if (mSecure) {
297        // secure buffer, don't store it into the GPU
298        usage = GraphicBuffer::USAGE_SW_READ_OFTEN |
299                GraphicBuffer::USAGE_SW_WRITE_OFTEN;
300    } else {
301        // it's allowed to modify the usage flags here, but generally
302        // the requested flags should be honored.
303        // request EGLImage for all buffers
304        usage |= GraphicBuffer::USAGE_HW_TEXTURE;
305    }
306    return usage;
307}
308
309uint32_t Layer::doTransaction(uint32_t flags)
310{
311    const Layer::State& front(drawingState());
312    const Layer::State& temp(currentState());
313
314    if ((front.requested_w != temp.requested_w) ||
315        (front.requested_h != temp.requested_h)) {
316        // the size changed, we need to ask our client to request a new buffer
317        LOGD_IF(DEBUG_RESIZE,
318                    "resize (layer=%p), requested (%dx%d), drawing (%d,%d)",
319                    this,
320                    int(temp.requested_w), int(temp.requested_h),
321                    int(front.requested_w), int(front.requested_h));
322
323        // we're being resized and there is a freeze display request,
324        // acquire a freeze lock, so that the screen stays put
325        // until we've redrawn at the new size; this is to avoid
326        // glitches upon orientation changes.
327        if (mFlinger->hasFreezeRequest()) {
328            // if the surface is hidden, don't try to acquire the
329            // freeze lock, since hidden surfaces may never redraw
330            if (!(front.flags & ISurfaceComposer::eLayerHidden)) {
331                mFreezeLock = mFlinger->getFreezeLock();
332            }
333        }
334
335        // this will make sure LayerBase::doTransaction doesn't update
336        // the drawing state's size
337        Layer::State& editDraw(mDrawingState);
338        editDraw.requested_w = temp.requested_w;
339        editDraw.requested_h = temp.requested_h;
340
341        // record the new size, form this point on, when the client request a
342        // buffer, it'll get the new size.
343        setDrawingSize(temp.requested_w, temp.requested_h);
344
345        // all buffers need reallocation
346        lcblk->reallocate();
347    }
348
349    if (temp.sequence != front.sequence) {
350        if (temp.flags & ISurfaceComposer::eLayerHidden || temp.alpha == 0) {
351            // this surface is now hidden, so it shouldn't hold a freeze lock
352            // (it may never redraw, which is fine if it is hidden)
353            mFreezeLock.clear();
354        }
355    }
356
357    return LayerBase::doTransaction(flags);
358}
359
360void Layer::setDrawingSize(uint32_t w, uint32_t h) {
361    Mutex::Autolock _l(mLock);
362    mWidth = w;
363    mHeight = h;
364}
365
366// ----------------------------------------------------------------------------
367// pageflip handling...
368// ----------------------------------------------------------------------------
369
370void Layer::lockPageFlip(bool& recomputeVisibleRegions)
371{
372    ssize_t buf = lcblk->retireAndLock();
373    if (buf == NOT_ENOUGH_DATA) {
374        // NOTE: This is not an error, it simply means there is nothing to
375        // retire. The buffer is locked because we will use it
376        // for composition later in the loop
377        return;
378    }
379
380    if (buf < NO_ERROR) {
381        LOGE("retireAndLock() buffer index (%d) out of range", buf);
382        mPostedDirtyRegion.clear();
383        return;
384    }
385
386    // we retired a buffer, which becomes the new front buffer
387    if (mBufferManager.setActiveBufferIndex(buf) < NO_ERROR) {
388        LOGE("retireAndLock() buffer index (%d) out of range", buf);
389        mPostedDirtyRegion.clear();
390        return;
391    }
392
393    // get the dirty region
394    sp<GraphicBuffer> newFrontBuffer(getBuffer(buf));
395    if (newFrontBuffer != NULL) {
396        // compute the posted region
397        const Region dirty(lcblk->getDirtyRegion(buf));
398        mPostedDirtyRegion = dirty.intersect( newFrontBuffer->getBounds() );
399
400        // update the layer size and release freeze-lock
401        const Layer::State& front(drawingState());
402        if (newFrontBuffer->getWidth()  == front.requested_w &&
403            newFrontBuffer->getHeight() == front.requested_h)
404        {
405            if ((front.w != front.requested_w) ||
406                (front.h != front.requested_h))
407            {
408                // Here we pretend the transaction happened by updating the
409                // current and drawing states. Drawing state is only accessed
410                // in this thread, no need to have it locked
411                Layer::State& editDraw(mDrawingState);
412                editDraw.w = editDraw.requested_w;
413                editDraw.h = editDraw.requested_h;
414
415                // We also need to update the current state so that we don't
416                // end-up doing too much work during the next transaction.
417                // NOTE: We actually don't need hold the transaction lock here
418                // because State::w and State::h are only accessed from
419                // this thread
420                Layer::State& editTemp(currentState());
421                editTemp.w = editDraw.w;
422                editTemp.h = editDraw.h;
423
424                // recompute visible region
425                recomputeVisibleRegions = true;
426            }
427
428            // we now have the correct size, unfreeze the screen
429            mFreezeLock.clear();
430        }
431    } else {
432        // this should not happen unless we ran out of memory while
433        // allocating the buffer. we're hoping that things will get back
434        // to normal the next time the app tries to draw into this buffer.
435        // meanwhile, pretend the screen didn't update.
436        mPostedDirtyRegion.clear();
437    }
438
439    if (lcblk->getQueuedCount()) {
440        // signal an event if we have more buffers waiting
441        mFlinger->signalEvent();
442    }
443
444    /* a buffer was posted, so we need to call reloadTexture(), which
445     * will update our internal data structures (eg: EGLImageKHR or
446     * texture names). we need to do this even if mPostedDirtyRegion is
447     * empty -- it's orthogonal to the fact that a new buffer was posted,
448     * for instance, a degenerate case could be that the user did an empty
449     * update but repainted the buffer with appropriate content (after a
450     * resize for instance).
451     */
452    reloadTexture( mPostedDirtyRegion );
453}
454
455void Layer::unlockPageFlip(
456        const Transform& planeTransform, Region& outDirtyRegion)
457{
458    Region dirtyRegion(mPostedDirtyRegion);
459    if (!dirtyRegion.isEmpty()) {
460        mPostedDirtyRegion.clear();
461        // The dirty region is given in the layer's coordinate space
462        // transform the dirty region by the surface's transformation
463        // and the global transformation.
464        const Layer::State& s(drawingState());
465        const Transform tr(planeTransform * s.transform);
466        dirtyRegion = tr.transform(dirtyRegion);
467
468        // At this point, the dirty region is in screen space.
469        // Make sure it's constrained by the visible region (which
470        // is in screen space as well).
471        dirtyRegion.andSelf(visibleRegionScreen);
472        outDirtyRegion.orSelf(dirtyRegion);
473    }
474    if (visibleRegionScreen.isEmpty()) {
475        // an invisible layer should not hold a freeze-lock
476        // (because it may never be updated and therefore never release it)
477        mFreezeLock.clear();
478    }
479}
480
481void Layer::finishPageFlip()
482{
483    int buf = mBufferManager.getActiveBufferIndex();
484    status_t err = lcblk->unlock( buf );
485    LOGE_IF(err!=NO_ERROR, "layer %p, buffer=%d wasn't locked!", this, buf);
486}
487
488
489void Layer::dump(String8& result, char* buffer, size_t SIZE) const
490{
491    LayerBaseClient::dump(result, buffer, SIZE);
492
493    SharedBufferStack::Statistics stats = lcblk->getStats();
494    result.append( lcblk->dump("      ") );
495    sp<const GraphicBuffer> buf0(getBuffer(0));
496    sp<const GraphicBuffer> buf1(getBuffer(1));
497    uint32_t w0=0, h0=0, s0=0;
498    uint32_t w1=0, h1=0, s1=0;
499    if (buf0 != 0) {
500        w0 = buf0->getWidth();
501        h0 = buf0->getHeight();
502        s0 = buf0->getStride();
503    }
504    if (buf1 != 0) {
505        w1 = buf1->getWidth();
506        h1 = buf1->getHeight();
507        s1 = buf1->getStride();
508    }
509    snprintf(buffer, SIZE,
510            "      "
511            "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u],"
512            " freezeLock=%p, dq-q-time=%u us\n",
513            pixelFormat(),
514            w0, h0, s0, w1, h1, s1,
515            getFreezeLock().get(), stats.totalTime);
516
517    result.append(buffer);
518}
519
520// ---------------------------------------------------------------------------
521
522Layer::BufferManager::BufferManager(TextureManager& tm)
523    : mTextureManager(tm), mActiveBuffer(0), mFailover(false)
524{
525}
526
527size_t Layer::BufferManager::getBufferCount() const {
528    return NUM_BUFFERS;
529}
530
531// only for debugging
532sp<GraphicBuffer> Layer::BufferManager::getBuffer(size_t index) const {
533    return mBufferData[index].buffer;
534}
535
536status_t Layer::BufferManager::setActiveBufferIndex(size_t index) {
537    // TODO: need to validate 'index'
538    mActiveBuffer = index;
539    return NO_ERROR;
540}
541
542size_t Layer::BufferManager::getActiveBufferIndex() const {
543    return mActiveBuffer;
544}
545
546Texture Layer::BufferManager::getActiveTexture() const {
547    return mFailover ? mFailoverTexture : mBufferData[mActiveBuffer].texture;
548}
549
550sp<GraphicBuffer> Layer::BufferManager::getActiveBuffer() const {
551    Mutex::Autolock _l(mLock);
552    return mBufferData[mActiveBuffer].buffer;
553}
554
555sp<GraphicBuffer> Layer::BufferManager::detachBuffer(size_t index)
556{
557    sp<GraphicBuffer> buffer;
558    Mutex::Autolock _l(mLock);
559    buffer = mBufferData[index].buffer;
560    mBufferData[index].buffer = 0;
561    return buffer;
562}
563
564status_t Layer::BufferManager::attachBuffer(size_t index,
565        const sp<GraphicBuffer>& buffer)
566{
567    Mutex::Autolock _l(mLock);
568    mBufferData[index].buffer = buffer;
569    mBufferData[index].texture.dirty = true;
570    return NO_ERROR;
571}
572
573status_t Layer::BufferManager::destroyTexture(Texture* tex, EGLDisplay dpy)
574{
575    if (tex->name != -1U) {
576        glDeleteTextures(1, &tex->name);
577        tex->name = -1U;
578    }
579    if (tex->image != EGL_NO_IMAGE_KHR) {
580        eglDestroyImageKHR(dpy, tex->image);
581        tex->image = EGL_NO_IMAGE_KHR;
582    }
583    return NO_ERROR;
584}
585
586status_t Layer::BufferManager::destroy(EGLDisplay dpy)
587{
588    Mutex::Autolock _l(mLock);
589    for (size_t i=0 ; i<NUM_BUFFERS ; i++) {
590        destroyTexture(&mBufferData[i].texture, dpy);
591        mBufferData[i].buffer = 0;
592    }
593    destroyTexture(&mFailoverTexture, dpy);
594    return NO_ERROR;
595}
596
597status_t Layer::BufferManager::initEglImage(EGLDisplay dpy,
598        const sp<GraphicBuffer>& buffer)
599{
600    size_t index = mActiveBuffer;
601    Texture& texture(mBufferData[index].texture);
602    status_t err = mTextureManager.initEglImage(&texture, dpy, buffer);
603    // if EGLImage fails, we switch to regular texture mode, and we
604    // free all resources associated with using EGLImages.
605    if (err == NO_ERROR) {
606        mFailover = false;
607        destroyTexture(&mFailoverTexture, dpy);
608    } else {
609        mFailover = true;
610        for (size_t i=0 ; i<NUM_BUFFERS ; i++) {
611            destroyTexture(&mBufferData[i].texture, dpy);
612        }
613    }
614    return err;
615}
616
617status_t Layer::BufferManager::loadTexture(
618        const Region& dirty, const GGLSurface& t)
619{
620    return mTextureManager.loadTexture(&mFailoverTexture, dirty, t);
621}
622
623// ---------------------------------------------------------------------------
624
625Layer::SurfaceLayer::SurfaceLayer(const sp<SurfaceFlinger>& flinger,
626        SurfaceID id, const sp<Layer>& owner)
627    : Surface(flinger, id, owner->getIdentity(), owner)
628{
629}
630
631Layer::SurfaceLayer::~SurfaceLayer()
632{
633}
634
635sp<GraphicBuffer> Layer::SurfaceLayer::requestBuffer(int index, int usage)
636{
637    sp<GraphicBuffer> buffer;
638    sp<Layer> owner(getOwner());
639    if (owner != 0) {
640        buffer = owner->requestBuffer(index, usage);
641    }
642    return buffer;
643}
644
645// ---------------------------------------------------------------------------
646
647
648}; // namespace android
649