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