Layer.cpp revision ab0225e3308c2cc6d399e967be16e766468437ac
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 "GLExtensions.h"
35#include "Layer.h"
36#include "SurfaceFlinger.h"
37#include "DisplayHardware/DisplayHardware.h"
38#include "DisplayHardware/HWComposer.h"
39
40
41#define DEBUG_RESIZE    0
42
43
44namespace android {
45
46template <typename T> inline T min(T a, T b) {
47    return a<b ? a : b;
48}
49
50// ---------------------------------------------------------------------------
51
52Layer::Layer(SurfaceFlinger* flinger,
53        DisplayID display, const sp<Client>& client)
54    :   LayerBaseClient(flinger, display, client),
55        mGLExtensions(GLExtensions::getInstance()),
56        mNeedsBlending(true),
57        mNeedsDithering(false),
58        mSecure(false),
59        mProtectedByApp(false),
60        mProtectedByDRM(false),
61        mTextureManager(),
62        mBufferManager(mTextureManager),
63        mWidth(0), mHeight(0), mNeedsScaling(false), mFixedSize(false)
64{
65}
66
67Layer::~Layer()
68{
69    // FIXME: must be called from the main UI thread
70    EGLDisplay dpy(mFlinger->graphicPlane(0).getEGLDisplay());
71    mBufferManager.destroy(dpy);
72
73    // we can use getUserClientUnsafe here because we know we're
74    // single-threaded at that point.
75    sp<UserClient> ourClient(mUserClientRef.getUserClientUnsafe());
76    if (ourClient != 0) {
77        ourClient->detachLayer(this);
78    }
79}
80
81status_t Layer::setToken(const sp<UserClient>& userClient,
82        SharedClient* sharedClient, int32_t token)
83{
84    sp<SharedBufferServer> lcblk = new SharedBufferServer(
85            sharedClient, token, mBufferManager.getDefaultBufferCount(),
86            getIdentity());
87
88
89    sp<UserClient> ourClient(mUserClientRef.getClient());
90
91    /*
92     *  Here it is guaranteed that userClient != ourClient
93     *  (see UserClient::getTokenForSurface()).
94     *
95     *  We release the token used by this surface in ourClient below.
96     *  This should be safe to do so now, since this layer won't be attached
97     *  to this client, it should be okay to reuse that id.
98     *
99     *  If this causes problems, an other solution would be to keep a list
100     *  of all the {UserClient, token} ever used and release them when the
101     *  Layer is destroyed.
102     *
103     */
104
105    if (ourClient != 0) {
106        ourClient->detachLayer(this);
107    }
108
109    status_t err = mUserClientRef.setToken(userClient, lcblk, token);
110    LOGE_IF(err != NO_ERROR,
111            "ClientRef::setToken(%p, %p, %u) failed",
112            userClient.get(), lcblk.get(), token);
113
114    if (err == NO_ERROR) {
115        // we need to free the buffers associated with this surface
116    }
117
118    return err;
119}
120
121int32_t Layer::getToken() const
122{
123    return mUserClientRef.getToken();
124}
125
126sp<UserClient> Layer::getClient() const
127{
128    return mUserClientRef.getClient();
129}
130
131// called with SurfaceFlinger::mStateLock as soon as the layer is entered
132// in the purgatory list
133void Layer::onRemoved()
134{
135    ClientRef::Access sharedClient(mUserClientRef);
136    SharedBufferServer* lcblk(sharedClient.get());
137    if (lcblk) {
138        // wake up the condition
139        lcblk->setStatus(NO_INIT);
140    }
141}
142
143sp<LayerBaseClient::Surface> Layer::createSurface() const
144{
145    sp<Surface> sur(new SurfaceLayer(mFlinger, const_cast<Layer *>(this)));
146    return sur;
147}
148
149status_t Layer::ditch()
150{
151    // NOTE: Called from the main UI thread
152
153    // the layer is not on screen anymore. free as much resources as possible
154    mFreezeLock.clear();
155
156    Mutex::Autolock _l(mLock);
157    mWidth = mHeight = 0;
158    return NO_ERROR;
159}
160
161status_t Layer::setBuffers( uint32_t w, uint32_t h,
162                            PixelFormat format, uint32_t flags)
163{
164    // this surfaces pixel format
165    PixelFormatInfo info;
166    status_t err = getPixelFormatInfo(format, &info);
167    if (err) return err;
168
169    // the display's pixel format
170    const DisplayHardware& hw(graphicPlane(0).displayHardware());
171    uint32_t const maxSurfaceDims = min(
172            hw.getMaxTextureSize(), hw.getMaxViewportDims());
173
174    // never allow a surface larger than what our underlying GL implementation
175    // can handle.
176    if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
177        return BAD_VALUE;
178    }
179
180    PixelFormatInfo displayInfo;
181    getPixelFormatInfo(hw.getFormat(), &displayInfo);
182    const uint32_t hwFlags = hw.getFlags();
183
184    mFormat = format;
185    mWidth  = w;
186    mHeight = h;
187
188    mReqFormat = format;
189    mReqWidth = w;
190    mReqHeight = h;
191
192    mSecure = (flags & ISurfaceComposer::eSecure) ? true : false;
193    mProtectedByApp = (flags & ISurfaceComposer::eProtectedByApp) ? true : false;
194    mProtectedByDRM = (flags & ISurfaceComposer::eProtectedByDRM) ? true : false;
195    mNeedsBlending = (info.h_alpha - info.l_alpha) > 0 &&
196            (flags & ISurfaceComposer::eOpaque) == 0;
197
198    // we use the red index
199    int displayRedSize = displayInfo.getSize(PixelFormatInfo::INDEX_RED);
200    int layerRedsize = info.getSize(PixelFormatInfo::INDEX_RED);
201    mNeedsDithering = layerRedsize > displayRedSize;
202
203    return NO_ERROR;
204}
205
206void Layer::setGeometry(hwc_layer_t* hwcl)
207{
208    hwcl->compositionType = HWC_FRAMEBUFFER;
209    hwcl->hints = 0;
210    hwcl->flags = 0;
211    hwcl->transform = 0;
212    hwcl->blending = HWC_BLENDING_NONE;
213
214    // we can't do alpha-fade with the hwc HAL
215    const State& s(drawingState());
216    if (s.alpha < 0xFF) {
217        hwcl->flags = HWC_SKIP_LAYER;
218        return;
219    }
220
221    // we can only handle simple transformation
222    if (mOrientation & Transform::ROT_INVALID) {
223        hwcl->flags = HWC_SKIP_LAYER;
224        return;
225    }
226
227    Transform tr(Transform(mOrientation) * Transform(mBufferTransform));
228    hwcl->transform = tr.getOrientation();
229
230    if (needsBlending()) {
231        hwcl->blending = mPremultipliedAlpha ?
232                HWC_BLENDING_PREMULT : HWC_BLENDING_COVERAGE;
233    }
234
235    hwcl->displayFrame.left   = mTransformedBounds.left;
236    hwcl->displayFrame.top    = mTransformedBounds.top;
237    hwcl->displayFrame.right  = mTransformedBounds.right;
238    hwcl->displayFrame.bottom = mTransformedBounds.bottom;
239
240    hwcl->visibleRegionScreen.rects =
241            reinterpret_cast<hwc_rect_t const *>(
242                    visibleRegionScreen.getArray(
243                            &hwcl->visibleRegionScreen.numRects));
244}
245
246void Layer::setPerFrameData(hwc_layer_t* hwcl) {
247    sp<GraphicBuffer> buffer(mBufferManager.getActiveBuffer());
248    if (buffer == NULL) {
249        // this can happen if the client never drew into this layer yet,
250        // or if we ran out of memory. In that case, don't let
251        // HWC handle it.
252        hwcl->flags |= HWC_SKIP_LAYER;
253        hwcl->handle = NULL;
254        return;
255    }
256    hwcl->handle = buffer->handle;
257
258    if (!mBufferCrop.isEmpty()) {
259        hwcl->sourceCrop.left   = mBufferCrop.left;
260        hwcl->sourceCrop.top    = mBufferCrop.top;
261        hwcl->sourceCrop.right  = mBufferCrop.right;
262        hwcl->sourceCrop.bottom = mBufferCrop.bottom;
263    } else {
264        hwcl->sourceCrop.left   = 0;
265        hwcl->sourceCrop.top    = 0;
266        hwcl->sourceCrop.right  = buffer->width;
267        hwcl->sourceCrop.bottom = buffer->height;
268    }
269}
270
271void Layer::reloadTexture(const Region& dirty)
272{
273    sp<GraphicBuffer> buffer(mBufferManager.getActiveBuffer());
274    if (buffer == NULL) {
275        // this situation can happen if we ran out of memory for instance.
276        // not much we can do. continue to use whatever texture was bound
277        // to this context.
278        return;
279    }
280
281    if (mGLExtensions.haveDirectTexture()) {
282        EGLDisplay dpy(mFlinger->graphicPlane(0).getEGLDisplay());
283        if (mBufferManager.initEglImage(dpy, buffer) != NO_ERROR) {
284            // not sure what we can do here...
285            goto slowpath;
286        }
287    } else {
288slowpath:
289        GGLSurface t;
290        if (buffer->usage & GRALLOC_USAGE_SW_READ_MASK) {
291            status_t res = buffer->lock(&t, GRALLOC_USAGE_SW_READ_OFTEN);
292            LOGE_IF(res, "error %d (%s) locking buffer %p",
293                    res, strerror(res), buffer.get());
294            if (res == NO_ERROR) {
295                mBufferManager.loadTexture(dirty, t);
296                buffer->unlock();
297            }
298        } else {
299            // we can't do anything
300        }
301    }
302}
303
304void Layer::drawForSreenShot() const
305{
306    const bool currentFiltering = mNeedsFiltering;
307    const_cast<Layer*>(this)->mNeedsFiltering = true;
308    LayerBase::drawForSreenShot();
309    const_cast<Layer*>(this)->mNeedsFiltering = currentFiltering;
310}
311
312void Layer::onDraw(const Region& clip) const
313{
314    Texture tex(mBufferManager.getActiveTexture());
315    if (tex.name == -1LU) {
316        // the texture has not been created yet, this Layer has
317        // in fact never been drawn into. This happens frequently with
318        // SurfaceView because the WindowManager can't know when the client
319        // has drawn the first time.
320
321        // If there is nothing under us, we paint the screen in black, otherwise
322        // we just skip this update.
323
324        // figure out if there is something below us
325        Region under;
326        const SurfaceFlinger::LayerVector& drawingLayers(mFlinger->mDrawingState.layersSortedByZ);
327        const size_t count = drawingLayers.size();
328        for (size_t i=0 ; i<count ; ++i) {
329            const sp<LayerBase>& layer(drawingLayers[i]);
330            if (layer.get() == static_cast<LayerBase const*>(this))
331                break;
332            under.orSelf(layer->visibleRegionScreen);
333        }
334        // if not everything below us is covered, we plug the holes!
335        Region holes(clip.subtract(under));
336        if (!holes.isEmpty()) {
337            clearWithOpenGL(holes, 0, 0, 0, 1);
338        }
339        return;
340    }
341    drawWithOpenGL(clip, tex);
342}
343
344// As documented in libhardware header, formats in the range
345// 0x100 - 0x1FF are specific to the HAL implementation, and
346// are known to have no alpha channel
347// TODO: move definition for device-specific range into
348// hardware.h, instead of using hard-coded values here.
349#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
350
351bool Layer::needsBlending(const sp<GraphicBuffer>& buffer) const
352{
353    // If buffers where set with eOpaque flag, all buffers are known to
354    // be opaque without having to check their actual format
355    if (mNeedsBlending && buffer != NULL) {
356        PixelFormat format = buffer->getPixelFormat();
357
358        if (HARDWARE_IS_DEVICE_FORMAT(format)) {
359            return false;
360        }
361
362        PixelFormatInfo info;
363        status_t err = getPixelFormatInfo(format, &info);
364        if (!err && info.h_alpha <= info.l_alpha) {
365            return false;
366        }
367    }
368
369    // Return opacity as determined from flags and format options
370    // passed to setBuffers()
371    return mNeedsBlending;
372}
373
374bool Layer::needsBlending() const
375{
376    if (mBufferManager.hasActiveBuffer()) {
377        return needsBlending(mBufferManager.getActiveBuffer());
378    }
379
380    return mNeedsBlending;
381}
382
383bool Layer::needsFiltering() const
384{
385    if (!(mFlags & DisplayHardware::SLOW_CONFIG)) {
386        // if our buffer is not the same size than ourselves,
387        // we need filtering.
388        Mutex::Autolock _l(mLock);
389        if (mNeedsScaling)
390            return true;
391    }
392    return LayerBase::needsFiltering();
393}
394
395
396status_t Layer::setBufferCount(int bufferCount)
397{
398    ClientRef::Access sharedClient(mUserClientRef);
399    SharedBufferServer* lcblk(sharedClient.get());
400    if (!lcblk) {
401        // oops, the client is already gone
402        return DEAD_OBJECT;
403    }
404
405    // NOTE: lcblk->resize() is protected by an internal lock
406    status_t err = lcblk->resize(bufferCount);
407    if (err == NO_ERROR) {
408        EGLDisplay dpy(mFlinger->graphicPlane(0).getEGLDisplay());
409        mBufferManager.resize(bufferCount, mFlinger, dpy);
410    }
411
412    return err;
413}
414
415sp<GraphicBuffer> Layer::requestBuffer(int index,
416        uint32_t reqWidth, uint32_t reqHeight, uint32_t reqFormat,
417        uint32_t usage)
418{
419    sp<GraphicBuffer> buffer;
420
421    if (int32_t(reqWidth | reqHeight | reqFormat) < 0)
422        return buffer;
423
424    if ((!reqWidth && reqHeight) || (reqWidth && !reqHeight))
425        return buffer;
426
427    // this ensures our client doesn't go away while we're accessing
428    // the shared area.
429    ClientRef::Access sharedClient(mUserClientRef);
430    SharedBufferServer* lcblk(sharedClient.get());
431    if (!lcblk) {
432        // oops, the client is already gone
433        return buffer;
434    }
435
436    /*
437     * This is called from the client's Surface::dequeue(). This can happen
438     * at any time, especially while we're in the middle of using the
439     * buffer 'index' as our front buffer.
440     */
441
442    status_t err = NO_ERROR;
443    uint32_t w, h, f;
444    { // scope for the lock
445        Mutex::Autolock _l(mLock);
446
447        // zero means default
448        const bool fixedSize = reqWidth && reqHeight;
449        if (!reqFormat) reqFormat = mFormat;
450        if (!reqWidth)  reqWidth = mWidth;
451        if (!reqHeight) reqHeight = mHeight;
452
453        w = reqWidth;
454        h = reqHeight;
455        f = reqFormat;
456
457        if ((reqWidth != mReqWidth) || (reqHeight != mReqHeight) ||
458                (reqFormat != mReqFormat)) {
459            mReqWidth  = reqWidth;
460            mReqHeight = reqHeight;
461            mReqFormat = reqFormat;
462            mFixedSize = fixedSize;
463            mNeedsScaling = mWidth != mReqWidth || mHeight != mReqHeight;
464
465            lcblk->reallocateAllExcept(index);
466        }
467    }
468
469    // here we have to reallocate a new buffer because the buffer could be
470    // used as the front buffer, or by a client in our process
471    // (eg: status bar), and we can't release the handle under its feet.
472    const uint32_t effectiveUsage = getEffectiveUsage(usage);
473    buffer = new GraphicBuffer(w, h, f, effectiveUsage);
474    err = buffer->initCheck();
475
476    if (err || buffer->handle == 0) {
477        GraphicBuffer::dumpAllocationsToSystemLog();
478        LOGE_IF(err || buffer->handle == 0,
479                "Layer::requestBuffer(this=%p), index=%d, w=%d, h=%d failed (%s)",
480                this, index, w, h, strerror(-err));
481    } else {
482        LOGD_IF(DEBUG_RESIZE,
483                "Layer::requestBuffer(this=%p), index=%d, w=%d, h=%d, handle=%p",
484                this, index, w, h, buffer->handle);
485    }
486
487    if (err == NO_ERROR && buffer->handle != 0) {
488        Mutex::Autolock _l(mLock);
489        mBufferManager.attachBuffer(index, buffer);
490    }
491    return buffer;
492}
493
494uint32_t Layer::getEffectiveUsage(uint32_t usage) const
495{
496    /*
497     *  buffers used for software rendering, but h/w composition
498     *  are allocated with SW_READ_OFTEN | SW_WRITE_OFTEN | HW_TEXTURE
499     *
500     *  buffers used for h/w rendering and h/w composition
501     *  are allocated with  HW_RENDER | HW_TEXTURE
502     *
503     *  buffers used with h/w rendering and either NPOT or no egl_image_ext
504     *  are allocated with SW_READ_RARELY | HW_RENDER
505     *
506     */
507
508    if (mSecure) {
509        // secure buffer, don't store it into the GPU
510        usage = GraphicBuffer::USAGE_SW_READ_OFTEN |
511                GraphicBuffer::USAGE_SW_WRITE_OFTEN;
512    } else {
513        // it's allowed to modify the usage flags here, but generally
514        // the requested flags should be honored.
515        // request EGLImage for all buffers
516        usage |= GraphicBuffer::USAGE_HW_TEXTURE;
517    }
518    if (mProtectedByApp || mProtectedByDRM) {
519        // need a hardware-protected path to external video sink
520        usage |= GraphicBuffer::USAGE_PROTECTED;
521    }
522    return usage;
523}
524
525uint32_t Layer::doTransaction(uint32_t flags)
526{
527    const Layer::State& front(drawingState());
528    const Layer::State& temp(currentState());
529
530    const bool sizeChanged = (front.requested_w != temp.requested_w) ||
531            (front.requested_h != temp.requested_h);
532
533    if (sizeChanged) {
534        // the size changed, we need to ask our client to request a new buffer
535        LOGD_IF(DEBUG_RESIZE,
536                "resize (layer=%p), requested (%dx%d), drawing (%d,%d)",
537                this,
538                int(temp.requested_w), int(temp.requested_h),
539                int(front.requested_w), int(front.requested_h));
540
541        if (!isFixedSize()) {
542            // we're being resized and there is a freeze display request,
543            // acquire a freeze lock, so that the screen stays put
544            // until we've redrawn at the new size; this is to avoid
545            // glitches upon orientation changes.
546            if (mFlinger->hasFreezeRequest()) {
547                // if the surface is hidden, don't try to acquire the
548                // freeze lock, since hidden surfaces may never redraw
549                if (!(front.flags & ISurfaceComposer::eLayerHidden)) {
550                    mFreezeLock = mFlinger->getFreezeLock();
551                }
552            }
553
554            // this will make sure LayerBase::doTransaction doesn't update
555            // the drawing state's size
556            Layer::State& editDraw(mDrawingState);
557            editDraw.requested_w = temp.requested_w;
558            editDraw.requested_h = temp.requested_h;
559
560            // record the new size, form this point on, when the client request
561            // a buffer, it'll get the new size.
562            setBufferSize(temp.requested_w, temp.requested_h);
563
564            ClientRef::Access sharedClient(mUserClientRef);
565            SharedBufferServer* lcblk(sharedClient.get());
566            if (lcblk) {
567                // all buffers need reallocation
568                lcblk->reallocateAll();
569            }
570        } else {
571            // record the new size
572            setBufferSize(temp.requested_w, temp.requested_h);
573        }
574    }
575
576    if (temp.sequence != front.sequence) {
577        if (temp.flags & ISurfaceComposer::eLayerHidden || temp.alpha == 0) {
578            // this surface is now hidden, so it shouldn't hold a freeze lock
579            // (it may never redraw, which is fine if it is hidden)
580            mFreezeLock.clear();
581        }
582    }
583
584    return LayerBase::doTransaction(flags);
585}
586
587void Layer::setBufferSize(uint32_t w, uint32_t h) {
588    Mutex::Autolock _l(mLock);
589    mWidth = w;
590    mHeight = h;
591    mNeedsScaling = mWidth != mReqWidth || mHeight != mReqHeight;
592}
593
594bool Layer::isFixedSize() const {
595    Mutex::Autolock _l(mLock);
596    return mFixedSize;
597}
598
599// ----------------------------------------------------------------------------
600// pageflip handling...
601// ----------------------------------------------------------------------------
602
603void Layer::lockPageFlip(bool& recomputeVisibleRegions)
604{
605    ClientRef::Access sharedClient(mUserClientRef);
606    SharedBufferServer* lcblk(sharedClient.get());
607    if (!lcblk) {
608        // client died
609        recomputeVisibleRegions = true;
610        return;
611    }
612
613    ssize_t buf = lcblk->retireAndLock();
614    if (buf == NOT_ENOUGH_DATA) {
615        // NOTE: This is not an error, it simply means there is nothing to
616        // retire. The buffer is locked because we will use it
617        // for composition later in the loop
618        return;
619    }
620
621    if (buf < NO_ERROR) {
622        LOGE("retireAndLock() buffer index (%d) out of range", int(buf));
623        mPostedDirtyRegion.clear();
624        return;
625    }
626
627    // we retired a buffer, which becomes the new front buffer
628
629    const bool noActiveBuffer = !mBufferManager.hasActiveBuffer();
630    const bool activeBlending =
631            noActiveBuffer ? true : needsBlending(mBufferManager.getActiveBuffer());
632
633    if (mBufferManager.setActiveBufferIndex(buf) < NO_ERROR) {
634        LOGE("retireAndLock() buffer index (%d) out of range", int(buf));
635        mPostedDirtyRegion.clear();
636        return;
637    }
638
639    if (noActiveBuffer) {
640        // we didn't have an active buffer, we need to recompute
641        // our visible region
642        recomputeVisibleRegions = true;
643    }
644
645    sp<GraphicBuffer> newFrontBuffer(getBuffer(buf));
646    if (newFrontBuffer != NULL) {
647        if (!noActiveBuffer && activeBlending != needsBlending(newFrontBuffer)) {
648            // new buffer has different opacity than previous active buffer, need
649            // to recompute visible regions accordingly
650            recomputeVisibleRegions = true;
651        }
652
653        // get the dirty region
654        // compute the posted region
655        const Region dirty(lcblk->getDirtyRegion(buf));
656        mPostedDirtyRegion = dirty.intersect( newFrontBuffer->getBounds() );
657
658        // update the layer size and release freeze-lock
659        const Layer::State& front(drawingState());
660        if (newFrontBuffer->getWidth()  == front.requested_w &&
661            newFrontBuffer->getHeight() == front.requested_h)
662        {
663            if ((front.w != front.requested_w) ||
664                (front.h != front.requested_h))
665            {
666                // Here we pretend the transaction happened by updating the
667                // current and drawing states. Drawing state is only accessed
668                // in this thread, no need to have it locked
669                Layer::State& editDraw(mDrawingState);
670                editDraw.w = editDraw.requested_w;
671                editDraw.h = editDraw.requested_h;
672
673                // We also need to update the current state so that we don't
674                // end-up doing too much work during the next transaction.
675                // NOTE: We actually don't need hold the transaction lock here
676                // because State::w and State::h are only accessed from
677                // this thread
678                Layer::State& editTemp(currentState());
679                editTemp.w = editDraw.w;
680                editTemp.h = editDraw.h;
681
682                // recompute visible region
683                recomputeVisibleRegions = true;
684            }
685
686            // we now have the correct size, unfreeze the screen
687            mFreezeLock.clear();
688        }
689
690        // get the crop region
691        setBufferCrop( lcblk->getCrop(buf) );
692
693        // get the transformation
694        setBufferTransform( lcblk->getTransform(buf) );
695
696    } else {
697        // this should not happen unless we ran out of memory while
698        // allocating the buffer. we're hoping that things will get back
699        // to normal the next time the app tries to draw into this buffer.
700        // meanwhile, pretend the screen didn't update.
701        mPostedDirtyRegion.clear();
702    }
703
704    if (lcblk->getQueuedCount()) {
705        // signal an event if we have more buffers waiting
706        mFlinger->signalEvent();
707    }
708
709    /* a buffer was posted, so we need to call reloadTexture(), which
710     * will update our internal data structures (eg: EGLImageKHR or
711     * texture names). we need to do this even if mPostedDirtyRegion is
712     * empty -- it's orthogonal to the fact that a new buffer was posted,
713     * for instance, a degenerate case could be that the user did an empty
714     * update but repainted the buffer with appropriate content (after a
715     * resize for instance).
716     */
717    reloadTexture( mPostedDirtyRegion );
718}
719
720void Layer::unlockPageFlip(
721        const Transform& planeTransform, Region& outDirtyRegion)
722{
723    Region dirtyRegion(mPostedDirtyRegion);
724    if (!dirtyRegion.isEmpty()) {
725        mPostedDirtyRegion.clear();
726        // The dirty region is given in the layer's coordinate space
727        // transform the dirty region by the surface's transformation
728        // and the global transformation.
729        const Layer::State& s(drawingState());
730        const Transform tr(planeTransform * s.transform);
731        dirtyRegion = tr.transform(dirtyRegion);
732
733        // At this point, the dirty region is in screen space.
734        // Make sure it's constrained by the visible region (which
735        // is in screen space as well).
736        dirtyRegion.andSelf(visibleRegionScreen);
737        outDirtyRegion.orSelf(dirtyRegion);
738    }
739    if (visibleRegionScreen.isEmpty()) {
740        // an invisible layer should not hold a freeze-lock
741        // (because it may never be updated and therefore never release it)
742        mFreezeLock.clear();
743    }
744}
745
746void Layer::dump(String8& result, char* buffer, size_t SIZE) const
747{
748    LayerBaseClient::dump(result, buffer, SIZE);
749
750    ClientRef::Access sharedClient(mUserClientRef);
751    SharedBufferServer* lcblk(sharedClient.get());
752    uint32_t totalTime = 0;
753    if (lcblk) {
754        SharedBufferStack::Statistics stats = lcblk->getStats();
755        totalTime= stats.totalTime;
756        result.append( lcblk->dump("      ") );
757    }
758
759    sp<const GraphicBuffer> buf0(getBuffer(0));
760    sp<const GraphicBuffer> buf1(getBuffer(1));
761    uint32_t w0=0, h0=0, s0=0;
762    uint32_t w1=0, h1=0, s1=0;
763    if (buf0 != 0) {
764        w0 = buf0->getWidth();
765        h0 = buf0->getHeight();
766        s0 = buf0->getStride();
767    }
768    if (buf1 != 0) {
769        w1 = buf1->getWidth();
770        h1 = buf1->getHeight();
771        s1 = buf1->getStride();
772    }
773    snprintf(buffer, SIZE,
774            "      "
775            "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u],"
776            " freezeLock=%p, dq-q-time=%u us\n",
777            mFormat, w0, h0, s0, w1, h1, s1,
778            getFreezeLock().get(), totalTime);
779
780    result.append(buffer);
781}
782
783// ---------------------------------------------------------------------------
784
785Layer::ClientRef::ClientRef()
786    : mControlBlock(0), mToken(-1) {
787}
788
789Layer::ClientRef::~ClientRef() {
790}
791
792int32_t Layer::ClientRef::getToken() const {
793    Mutex::Autolock _l(mLock);
794    return mToken;
795}
796
797sp<UserClient> Layer::ClientRef::getClient() const {
798    Mutex::Autolock _l(mLock);
799    return mUserClient.promote();
800}
801
802status_t Layer::ClientRef::setToken(const sp<UserClient>& uc,
803        const sp<SharedBufferServer>& sharedClient, int32_t token) {
804    Mutex::Autolock _l(mLock);
805
806    { // scope for strong mUserClient reference
807        sp<UserClient> userClient(mUserClient.promote());
808        if (mUserClient != 0 && mControlBlock != 0) {
809            mControlBlock->setStatus(NO_INIT);
810        }
811    }
812
813    mUserClient = uc;
814    mToken = token;
815    mControlBlock = sharedClient;
816    return NO_ERROR;
817}
818
819sp<UserClient> Layer::ClientRef::getUserClientUnsafe() const {
820    return mUserClient.promote();
821}
822
823// this class gives us access to SharedBufferServer safely
824// it makes sure the UserClient (and its associated shared memory)
825// won't go away while we're accessing it.
826Layer::ClientRef::Access::Access(const ClientRef& ref)
827    : mControlBlock(0)
828{
829    Mutex::Autolock _l(ref.mLock);
830    mUserClientStrongRef = ref.mUserClient.promote();
831    if (mUserClientStrongRef != 0)
832        mControlBlock = ref.mControlBlock;
833}
834
835Layer::ClientRef::Access::~Access()
836{
837}
838
839// ---------------------------------------------------------------------------
840
841Layer::BufferManager::BufferManager(TextureManager& tm)
842    : mNumBuffers(NUM_BUFFERS), mTextureManager(tm),
843      mActiveBufferIndex(-1), mFailover(false)
844{
845}
846
847Layer::BufferManager::~BufferManager()
848{
849}
850
851status_t Layer::BufferManager::resize(size_t size,
852        const sp<SurfaceFlinger>& flinger, EGLDisplay dpy)
853{
854    Mutex::Autolock _l(mLock);
855
856    if (size < mNumBuffers) {
857        // Move the active texture into slot 0
858        BufferData activeBufferData = mBufferData[mActiveBufferIndex];
859        mBufferData[mActiveBufferIndex] = mBufferData[0];
860        mBufferData[0] = activeBufferData;
861        mActiveBufferIndex = 0;
862
863        // Free the buffers that are no longer needed.
864        for (size_t i = size; i < mNumBuffers; i++) {
865            mBufferData[i].buffer = 0;
866
867            // Create a message to destroy the textures on SurfaceFlinger's GL
868            // thread.
869            class MessageDestroyTexture : public MessageBase {
870                Image mTexture;
871                EGLDisplay mDpy;
872             public:
873                MessageDestroyTexture(const Image& texture, EGLDisplay dpy)
874                    : mTexture(texture), mDpy(dpy) { }
875                virtual bool handler() {
876                    status_t err = Layer::BufferManager::destroyTexture(
877                            &mTexture, mDpy);
878                    LOGE_IF(err<0, "error destroying texture: %d (%s)",
879                            mTexture.name, strerror(-err));
880                    return true; // XXX: err == 0;  ????
881                }
882            };
883
884            MessageDestroyTexture *msg = new MessageDestroyTexture(
885                    mBufferData[i].texture, dpy);
886
887            // Don't allow this texture to be cleaned up by
888            // BufferManager::destroy.
889            mBufferData[i].texture.name = -1U;
890            mBufferData[i].texture.image = EGL_NO_IMAGE_KHR;
891
892            // Post the message to the SurfaceFlinger object.
893            flinger->postMessageAsync(msg);
894        }
895    }
896
897    mNumBuffers = size;
898    return NO_ERROR;
899}
900
901// only for debugging
902sp<GraphicBuffer> Layer::BufferManager::getBuffer(size_t index) const {
903    return mBufferData[index].buffer;
904}
905
906status_t Layer::BufferManager::setActiveBufferIndex(size_t index) {
907    BufferData const * const buffers = mBufferData;
908    Mutex::Autolock _l(mLock);
909    mActiveBuffer = buffers[index].buffer;
910    mActiveBufferIndex = index;
911    return NO_ERROR;
912}
913
914size_t Layer::BufferManager::getActiveBufferIndex() const {
915    return mActiveBufferIndex;
916}
917
918Texture Layer::BufferManager::getActiveTexture() const {
919    Texture res;
920    if (mFailover || mActiveBufferIndex<0) {
921        res = mFailoverTexture;
922    } else {
923        static_cast<Image&>(res) = mBufferData[mActiveBufferIndex].texture;
924    }
925    return res;
926}
927
928sp<GraphicBuffer> Layer::BufferManager::getActiveBuffer() const {
929    return mActiveBuffer;
930}
931
932bool Layer::BufferManager::hasActiveBuffer() const {
933    return mActiveBufferIndex >= 0;
934}
935
936sp<GraphicBuffer> Layer::BufferManager::detachBuffer(size_t index)
937{
938    BufferData* const buffers = mBufferData;
939    sp<GraphicBuffer> buffer;
940    Mutex::Autolock _l(mLock);
941    buffer = buffers[index].buffer;
942    buffers[index].buffer = 0;
943    return buffer;
944}
945
946status_t Layer::BufferManager::attachBuffer(size_t index,
947        const sp<GraphicBuffer>& buffer)
948{
949    BufferData* const buffers = mBufferData;
950    Mutex::Autolock _l(mLock);
951    buffers[index].buffer = buffer;
952    buffers[index].texture.dirty = true;
953    return NO_ERROR;
954}
955
956status_t Layer::BufferManager::destroy(EGLDisplay dpy)
957{
958    BufferData* const buffers = mBufferData;
959    size_t num;
960    { // scope for the lock
961        Mutex::Autolock _l(mLock);
962        num = mNumBuffers;
963        for (size_t i=0 ; i<num ; i++) {
964            buffers[i].buffer = 0;
965        }
966    }
967    for (size_t i=0 ; i<num ; i++) {
968        destroyTexture(&buffers[i].texture, dpy);
969    }
970    destroyTexture(&mFailoverTexture, dpy);
971    return NO_ERROR;
972}
973
974status_t Layer::BufferManager::initEglImage(EGLDisplay dpy,
975        const sp<GraphicBuffer>& buffer)
976{
977    status_t err = NO_INIT;
978    ssize_t index = mActiveBufferIndex;
979    if (index >= 0) {
980        if (!mFailover) {
981            Image& texture(mBufferData[index].texture);
982            err = mTextureManager.initEglImage(&texture, dpy, buffer);
983            // if EGLImage fails, we switch to regular texture mode, and we
984            // free all resources associated with using EGLImages.
985            if (err == NO_ERROR) {
986                mFailover = false;
987                destroyTexture(&mFailoverTexture, dpy);
988            } else {
989                mFailover = true;
990                const size_t num = mNumBuffers;
991                for (size_t i=0 ; i<num ; i++) {
992                    destroyTexture(&mBufferData[i].texture, dpy);
993                }
994            }
995        } else {
996            // we failed once, don't try again
997            err = BAD_VALUE;
998        }
999    }
1000    return err;
1001}
1002
1003status_t Layer::BufferManager::loadTexture(
1004        const Region& dirty, const GGLSurface& t)
1005{
1006    return mTextureManager.loadTexture(&mFailoverTexture, dirty, t);
1007}
1008
1009status_t Layer::BufferManager::destroyTexture(Image* tex, EGLDisplay dpy)
1010{
1011    if (tex->name != -1U) {
1012        glDeleteTextures(1, &tex->name);
1013        tex->name = -1U;
1014    }
1015    if (tex->image != EGL_NO_IMAGE_KHR) {
1016        eglDestroyImageKHR(dpy, tex->image);
1017        tex->image = EGL_NO_IMAGE_KHR;
1018    }
1019    return NO_ERROR;
1020}
1021
1022// ---------------------------------------------------------------------------
1023
1024Layer::SurfaceLayer::SurfaceLayer(const sp<SurfaceFlinger>& flinger,
1025        const sp<Layer>& owner)
1026    : Surface(flinger, owner->getIdentity(), owner)
1027{
1028}
1029
1030Layer::SurfaceLayer::~SurfaceLayer()
1031{
1032}
1033
1034sp<GraphicBuffer> Layer::SurfaceLayer::requestBuffer(int index,
1035        uint32_t w, uint32_t h, uint32_t format, uint32_t usage)
1036{
1037    sp<GraphicBuffer> buffer;
1038    sp<Layer> owner(getOwner());
1039    if (owner != 0) {
1040        /*
1041         * requestBuffer() cannot be called from the main thread
1042         * as it could cause a dead-lock, since it may have to wait
1043         * on conditions updated my the main thread.
1044         */
1045        buffer = owner->requestBuffer(index, w, h, format, usage);
1046    }
1047    return buffer;
1048}
1049
1050status_t Layer::SurfaceLayer::setBufferCount(int bufferCount)
1051{
1052    status_t err = DEAD_OBJECT;
1053    sp<Layer> owner(getOwner());
1054    if (owner != 0) {
1055        /*
1056         * setBufferCount() cannot be called from the main thread
1057         * as it could cause a dead-lock, since it may have to wait
1058         * on conditions updated my the main thread.
1059         */
1060        err = owner->setBufferCount(bufferCount);
1061    }
1062    return err;
1063}
1064
1065// ---------------------------------------------------------------------------
1066
1067
1068}; // namespace android
1069