Layer.cpp revision da9584dc295cc5e6d0b49a97c1e45159249d650b
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        mTextureManager(),
60        mBufferManager(mTextureManager),
61        mWidth(0), mHeight(0), mNeedsScaling(false), mFixedSize(false)
62{
63}
64
65Layer::~Layer()
66{
67    // FIXME: must be called from the main UI thread
68    EGLDisplay dpy(mFlinger->graphicPlane(0).getEGLDisplay());
69    mBufferManager.destroy(dpy);
70
71    // we can use getUserClientUnsafe here because we know we're
72    // single-threaded at that point.
73    sp<UserClient> ourClient(mUserClientRef.getUserClientUnsafe());
74    if (ourClient != 0) {
75        ourClient->detachLayer(this);
76    }
77}
78
79status_t Layer::setToken(const sp<UserClient>& userClient,
80        SharedClient* sharedClient, int32_t token)
81{
82    sp<SharedBufferServer> lcblk = new SharedBufferServer(
83            sharedClient, token, mBufferManager.getDefaultBufferCount(),
84            getIdentity());
85
86
87    sp<UserClient> ourClient(mUserClientRef.getClient());
88
89    /*
90     *  Here it is guaranteed that userClient != ourClient
91     *  (see UserClient::getTokenForSurface()).
92     *
93     *  We release the token used by this surface in ourClient below.
94     *  This should be safe to do so now, since this layer won't be attached
95     *  to this client, it should be okay to reuse that id.
96     *
97     *  If this causes problems, an other solution would be to keep a list
98     *  of all the {UserClient, token} ever used and release them when the
99     *  Layer is destroyed.
100     *
101     */
102
103    if (ourClient != 0) {
104        ourClient->detachLayer(this);
105    }
106
107    status_t err = mUserClientRef.setToken(userClient, lcblk, token);
108    LOGE_IF(err != NO_ERROR,
109            "ClientRef::setToken(%p, %p, %u) failed",
110            userClient.get(), lcblk.get(), token);
111
112    if (err == NO_ERROR) {
113        // we need to free the buffers associated with this surface
114    }
115
116    return err;
117}
118
119int32_t Layer::getToken() const
120{
121    return mUserClientRef.getToken();
122}
123
124sp<UserClient> Layer::getClient() const
125{
126    return mUserClientRef.getClient();
127}
128
129// called with SurfaceFlinger::mStateLock as soon as the layer is entered
130// in the purgatory list
131void Layer::onRemoved()
132{
133    ClientRef::Access sharedClient(mUserClientRef);
134    SharedBufferServer* lcblk(sharedClient.get());
135    if (lcblk) {
136        // wake up the condition
137        lcblk->setStatus(NO_INIT);
138    }
139}
140
141sp<LayerBaseClient::Surface> Layer::createSurface() const
142{
143    return mSurface;
144}
145
146status_t Layer::ditch()
147{
148    // NOTE: Called from the main UI thread
149
150    // the layer is not on screen anymore. free as much resources as possible
151    mFreezeLock.clear();
152
153    EGLDisplay dpy(mFlinger->graphicPlane(0).getEGLDisplay());
154    mBufferManager.destroy(dpy);
155    mSurface.clear();
156
157    Mutex::Autolock _l(mLock);
158    mWidth = mHeight = 0;
159    return NO_ERROR;
160}
161
162status_t Layer::setBuffers( uint32_t w, uint32_t h,
163                            PixelFormat format, uint32_t flags)
164{
165    // this surfaces pixel format
166    PixelFormatInfo info;
167    status_t err = getPixelFormatInfo(format, &info);
168    if (err) return err;
169
170    // the display's pixel format
171    const DisplayHardware& hw(graphicPlane(0).displayHardware());
172    uint32_t const maxSurfaceDims = min(
173            hw.getMaxTextureSize(), hw.getMaxViewportDims());
174
175    // never allow a surface larger than what our underlying GL implementation
176    // can handle.
177    if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
178        return BAD_VALUE;
179    }
180
181    PixelFormatInfo displayInfo;
182    getPixelFormatInfo(hw.getFormat(), &displayInfo);
183    const uint32_t hwFlags = hw.getFlags();
184
185    mFormat = format;
186    mWidth  = w;
187    mHeight = h;
188
189    mReqFormat = format;
190    mReqWidth = w;
191    mReqHeight = h;
192
193    mSecure = (flags & ISurfaceComposer::eSecure) ? true : false;
194    mNeedsBlending = (info.h_alpha - info.l_alpha) > 0 &&
195            (flags & ISurfaceComposer::eOpaque) == 0;
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    mSurface = new SurfaceLayer(mFlinger, this);
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
344bool Layer::needsFiltering() const
345{
346    if (!(mFlags & DisplayHardware::SLOW_CONFIG)) {
347        // if our buffer is not the same size than ourselves,
348        // we need filtering.
349        Mutex::Autolock _l(mLock);
350        if (mNeedsScaling)
351            return true;
352    }
353    return LayerBase::needsFiltering();
354}
355
356
357status_t Layer::setBufferCount(int bufferCount)
358{
359    ClientRef::Access sharedClient(mUserClientRef);
360    SharedBufferServer* lcblk(sharedClient.get());
361    if (!lcblk) {
362        // oops, the client is already gone
363        return DEAD_OBJECT;
364    }
365
366    // NOTE: lcblk->resize() is protected by an internal lock
367    status_t err = lcblk->resize(bufferCount);
368    if (err == NO_ERROR) {
369        EGLDisplay dpy(mFlinger->graphicPlane(0).getEGLDisplay());
370        mBufferManager.resize(bufferCount, mFlinger, dpy);
371    }
372
373    return err;
374}
375
376sp<GraphicBuffer> Layer::requestBuffer(int index,
377        uint32_t reqWidth, uint32_t reqHeight, uint32_t reqFormat,
378        uint32_t usage)
379{
380    sp<GraphicBuffer> buffer;
381
382    if (int32_t(reqWidth | reqHeight | reqFormat) < 0)
383        return buffer;
384
385    if ((!reqWidth && reqHeight) || (reqWidth && !reqHeight))
386        return buffer;
387
388    // this ensures our client doesn't go away while we're accessing
389    // the shared area.
390    ClientRef::Access sharedClient(mUserClientRef);
391    SharedBufferServer* lcblk(sharedClient.get());
392    if (!lcblk) {
393        // oops, the client is already gone
394        return buffer;
395    }
396
397    /*
398     * This is called from the client's Surface::dequeue(). This can happen
399     * at any time, especially while we're in the middle of using the
400     * buffer 'index' as our front buffer.
401     */
402
403    status_t err = NO_ERROR;
404    uint32_t w, h, f;
405    { // scope for the lock
406        Mutex::Autolock _l(mLock);
407
408        // zero means default
409        const bool fixedSize = reqWidth && reqHeight;
410        if (!reqFormat) reqFormat = mFormat;
411        if (!reqWidth)  reqWidth = mWidth;
412        if (!reqHeight) reqHeight = mHeight;
413
414        w = reqWidth;
415        h = reqHeight;
416        f = reqFormat;
417
418        if ((reqWidth != mReqWidth) || (reqHeight != mReqHeight) ||
419                (reqFormat != mReqFormat)) {
420            mReqWidth  = reqWidth;
421            mReqHeight = reqHeight;
422            mReqFormat = reqFormat;
423            mFixedSize = fixedSize;
424            mNeedsScaling = mWidth != mReqWidth || mHeight != mReqHeight;
425
426            lcblk->reallocateAllExcept(index);
427        }
428    }
429
430    // here we have to reallocate a new buffer because the buffer could be
431    // used as the front buffer, or by a client in our process
432    // (eg: status bar), and we can't release the handle under its feet.
433    const uint32_t effectiveUsage = getEffectiveUsage(usage);
434    buffer = new GraphicBuffer(w, h, f, effectiveUsage);
435    err = buffer->initCheck();
436
437    if (err || buffer->handle == 0) {
438        GraphicBuffer::dumpAllocationsToSystemLog();
439        LOGE_IF(err || buffer->handle == 0,
440                "Layer::requestBuffer(this=%p), index=%d, w=%d, h=%d failed (%s)",
441                this, index, w, h, strerror(-err));
442    } else {
443        LOGD_IF(DEBUG_RESIZE,
444                "Layer::requestBuffer(this=%p), index=%d, w=%d, h=%d, handle=%p",
445                this, index, w, h, buffer->handle);
446    }
447
448    if (err == NO_ERROR && buffer->handle != 0) {
449        Mutex::Autolock _l(mLock);
450        mBufferManager.attachBuffer(index, buffer);
451    }
452    return buffer;
453}
454
455uint32_t Layer::getEffectiveUsage(uint32_t usage) const
456{
457    /*
458     *  buffers used for software rendering, but h/w composition
459     *  are allocated with SW_READ_OFTEN | SW_WRITE_OFTEN | HW_TEXTURE
460     *
461     *  buffers used for h/w rendering and h/w composition
462     *  are allocated with  HW_RENDER | HW_TEXTURE
463     *
464     *  buffers used with h/w rendering and either NPOT or no egl_image_ext
465     *  are allocated with SW_READ_RARELY | HW_RENDER
466     *
467     */
468
469    if (mSecure) {
470        // secure buffer, don't store it into the GPU
471        usage = GraphicBuffer::USAGE_SW_READ_OFTEN |
472                GraphicBuffer::USAGE_SW_WRITE_OFTEN;
473    } else {
474        // it's allowed to modify the usage flags here, but generally
475        // the requested flags should be honored.
476        // request EGLImage for all buffers
477        usage |= GraphicBuffer::USAGE_HW_TEXTURE;
478    }
479    return usage;
480}
481
482uint32_t Layer::doTransaction(uint32_t flags)
483{
484    const Layer::State& front(drawingState());
485    const Layer::State& temp(currentState());
486
487    const bool sizeChanged = (front.requested_w != temp.requested_w) ||
488            (front.requested_h != temp.requested_h);
489
490    if (sizeChanged) {
491        // the size changed, we need to ask our client to request a new buffer
492        LOGD_IF(DEBUG_RESIZE,
493                "resize (layer=%p), requested (%dx%d), drawing (%d,%d)",
494                this,
495                int(temp.requested_w), int(temp.requested_h),
496                int(front.requested_w), int(front.requested_h));
497
498        if (!isFixedSize()) {
499            // we're being resized and there is a freeze display request,
500            // acquire a freeze lock, so that the screen stays put
501            // until we've redrawn at the new size; this is to avoid
502            // glitches upon orientation changes.
503            if (mFlinger->hasFreezeRequest()) {
504                // if the surface is hidden, don't try to acquire the
505                // freeze lock, since hidden surfaces may never redraw
506                if (!(front.flags & ISurfaceComposer::eLayerHidden)) {
507                    mFreezeLock = mFlinger->getFreezeLock();
508                }
509            }
510
511            // this will make sure LayerBase::doTransaction doesn't update
512            // the drawing state's size
513            Layer::State& editDraw(mDrawingState);
514            editDraw.requested_w = temp.requested_w;
515            editDraw.requested_h = temp.requested_h;
516
517            // record the new size, form this point on, when the client request
518            // a buffer, it'll get the new size.
519            setBufferSize(temp.requested_w, temp.requested_h);
520
521            ClientRef::Access sharedClient(mUserClientRef);
522            SharedBufferServer* lcblk(sharedClient.get());
523            if (lcblk) {
524                // all buffers need reallocation
525                lcblk->reallocateAll();
526            }
527        } else {
528            // record the new size
529            setBufferSize(temp.requested_w, temp.requested_h);
530        }
531    }
532
533    if (temp.sequence != front.sequence) {
534        if (temp.flags & ISurfaceComposer::eLayerHidden || temp.alpha == 0) {
535            // this surface is now hidden, so it shouldn't hold a freeze lock
536            // (it may never redraw, which is fine if it is hidden)
537            mFreezeLock.clear();
538        }
539    }
540
541    return LayerBase::doTransaction(flags);
542}
543
544void Layer::setBufferSize(uint32_t w, uint32_t h) {
545    Mutex::Autolock _l(mLock);
546    mWidth = w;
547    mHeight = h;
548    mNeedsScaling = mWidth != mReqWidth || mHeight != mReqHeight;
549}
550
551bool Layer::isFixedSize() const {
552    Mutex::Autolock _l(mLock);
553    return mFixedSize;
554}
555
556// ----------------------------------------------------------------------------
557// pageflip handling...
558// ----------------------------------------------------------------------------
559
560void Layer::lockPageFlip(bool& recomputeVisibleRegions)
561{
562    ClientRef::Access sharedClient(mUserClientRef);
563    SharedBufferServer* lcblk(sharedClient.get());
564    if (!lcblk) {
565        // client died
566        recomputeVisibleRegions = true;
567        return;
568    }
569
570    ssize_t buf = lcblk->retireAndLock();
571    if (buf == NOT_ENOUGH_DATA) {
572        // NOTE: This is not an error, it simply means there is nothing to
573        // retire. The buffer is locked because we will use it
574        // for composition later in the loop
575        return;
576    }
577
578    if (buf < NO_ERROR) {
579        LOGE("retireAndLock() buffer index (%d) out of range", int(buf));
580        mPostedDirtyRegion.clear();
581        return;
582    }
583
584    // we retired a buffer, which becomes the new front buffer
585
586    const bool noActiveBuffer = !mBufferManager.hasActiveBuffer();
587    if (mBufferManager.setActiveBufferIndex(buf) < NO_ERROR) {
588        LOGE("retireAndLock() buffer index (%d) out of range", int(buf));
589        mPostedDirtyRegion.clear();
590        return;
591    }
592
593    if (noActiveBuffer) {
594        // we didn't have an active buffer, we need to recompute
595        // our visible region
596        recomputeVisibleRegions = true;
597    }
598
599    sp<GraphicBuffer> newFrontBuffer(getBuffer(buf));
600    if (newFrontBuffer != NULL) {
601        // get the dirty region
602        // compute the posted region
603        const Region dirty(lcblk->getDirtyRegion(buf));
604        mPostedDirtyRegion = dirty.intersect( newFrontBuffer->getBounds() );
605
606        // update the layer size and release freeze-lock
607        const Layer::State& front(drawingState());
608        if (newFrontBuffer->getWidth()  == front.requested_w &&
609            newFrontBuffer->getHeight() == front.requested_h)
610        {
611            if ((front.w != front.requested_w) ||
612                (front.h != front.requested_h))
613            {
614                // Here we pretend the transaction happened by updating the
615                // current and drawing states. Drawing state is only accessed
616                // in this thread, no need to have it locked
617                Layer::State& editDraw(mDrawingState);
618                editDraw.w = editDraw.requested_w;
619                editDraw.h = editDraw.requested_h;
620
621                // We also need to update the current state so that we don't
622                // end-up doing too much work during the next transaction.
623                // NOTE: We actually don't need hold the transaction lock here
624                // because State::w and State::h are only accessed from
625                // this thread
626                Layer::State& editTemp(currentState());
627                editTemp.w = editDraw.w;
628                editTemp.h = editDraw.h;
629
630                // recompute visible region
631                recomputeVisibleRegions = true;
632            }
633
634            // we now have the correct size, unfreeze the screen
635            mFreezeLock.clear();
636        }
637
638        // get the crop region
639        setBufferCrop( lcblk->getCrop(buf) );
640
641        // get the transformation
642        setBufferTransform( lcblk->getTransform(buf) );
643
644    } else {
645        // this should not happen unless we ran out of memory while
646        // allocating the buffer. we're hoping that things will get back
647        // to normal the next time the app tries to draw into this buffer.
648        // meanwhile, pretend the screen didn't update.
649        mPostedDirtyRegion.clear();
650    }
651
652    if (lcblk->getQueuedCount()) {
653        // signal an event if we have more buffers waiting
654        mFlinger->signalEvent();
655    }
656
657    /* a buffer was posted, so we need to call reloadTexture(), which
658     * will update our internal data structures (eg: EGLImageKHR or
659     * texture names). we need to do this even if mPostedDirtyRegion is
660     * empty -- it's orthogonal to the fact that a new buffer was posted,
661     * for instance, a degenerate case could be that the user did an empty
662     * update but repainted the buffer with appropriate content (after a
663     * resize for instance).
664     */
665    reloadTexture( mPostedDirtyRegion );
666}
667
668void Layer::unlockPageFlip(
669        const Transform& planeTransform, Region& outDirtyRegion)
670{
671    Region dirtyRegion(mPostedDirtyRegion);
672    if (!dirtyRegion.isEmpty()) {
673        mPostedDirtyRegion.clear();
674        // The dirty region is given in the layer's coordinate space
675        // transform the dirty region by the surface's transformation
676        // and the global transformation.
677        const Layer::State& s(drawingState());
678        const Transform tr(planeTransform * s.transform);
679        dirtyRegion = tr.transform(dirtyRegion);
680
681        // At this point, the dirty region is in screen space.
682        // Make sure it's constrained by the visible region (which
683        // is in screen space as well).
684        dirtyRegion.andSelf(visibleRegionScreen);
685        outDirtyRegion.orSelf(dirtyRegion);
686    }
687    if (visibleRegionScreen.isEmpty()) {
688        // an invisible layer should not hold a freeze-lock
689        // (because it may never be updated and therefore never release it)
690        mFreezeLock.clear();
691    }
692}
693
694void Layer::finishPageFlip()
695{
696    ClientRef::Access sharedClient(mUserClientRef);
697    SharedBufferServer* lcblk(sharedClient.get());
698    if (lcblk) {
699        int buf = mBufferManager.getActiveBufferIndex();
700        if (buf >= 0) {
701            status_t err = lcblk->unlock( buf );
702            LOGE_IF(err!=NO_ERROR,
703                    "layer %p, buffer=%d wasn't locked!",
704                    this, buf);
705        }
706    }
707}
708
709
710void Layer::dump(String8& result, char* buffer, size_t SIZE) const
711{
712    LayerBaseClient::dump(result, buffer, SIZE);
713
714    ClientRef::Access sharedClient(mUserClientRef);
715    SharedBufferServer* lcblk(sharedClient.get());
716    uint32_t totalTime = 0;
717    if (lcblk) {
718        SharedBufferStack::Statistics stats = lcblk->getStats();
719        totalTime= stats.totalTime;
720        result.append( lcblk->dump("      ") );
721    }
722
723    sp<const GraphicBuffer> buf0(getBuffer(0));
724    sp<const GraphicBuffer> buf1(getBuffer(1));
725    uint32_t w0=0, h0=0, s0=0;
726    uint32_t w1=0, h1=0, s1=0;
727    if (buf0 != 0) {
728        w0 = buf0->getWidth();
729        h0 = buf0->getHeight();
730        s0 = buf0->getStride();
731    }
732    if (buf1 != 0) {
733        w1 = buf1->getWidth();
734        h1 = buf1->getHeight();
735        s1 = buf1->getStride();
736    }
737    snprintf(buffer, SIZE,
738            "      "
739            "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u],"
740            " freezeLock=%p, dq-q-time=%u us\n",
741            mFormat, w0, h0, s0, w1, h1, s1,
742            getFreezeLock().get(), totalTime);
743
744    result.append(buffer);
745}
746
747// ---------------------------------------------------------------------------
748
749Layer::ClientRef::ClientRef()
750    : mControlBlock(0), mToken(-1) {
751}
752
753Layer::ClientRef::~ClientRef() {
754}
755
756int32_t Layer::ClientRef::getToken() const {
757    Mutex::Autolock _l(mLock);
758    return mToken;
759}
760
761sp<UserClient> Layer::ClientRef::getClient() const {
762    Mutex::Autolock _l(mLock);
763    return mUserClient.promote();
764}
765
766status_t Layer::ClientRef::setToken(const sp<UserClient>& uc,
767        const sp<SharedBufferServer>& sharedClient, int32_t token) {
768    Mutex::Autolock _l(mLock);
769
770    { // scope for strong mUserClient reference
771        sp<UserClient> userClient(mUserClient.promote());
772        if (mUserClient != 0 && mControlBlock != 0) {
773            mControlBlock->setStatus(NO_INIT);
774        }
775    }
776
777    mUserClient = uc;
778    mToken = token;
779    mControlBlock = sharedClient;
780    return NO_ERROR;
781}
782
783sp<UserClient> Layer::ClientRef::getUserClientUnsafe() const {
784    return mUserClient.promote();
785}
786
787// this class gives us access to SharedBufferServer safely
788// it makes sure the UserClient (and its associated shared memory)
789// won't go away while we're accessing it.
790Layer::ClientRef::Access::Access(const ClientRef& ref)
791    : mControlBlock(0)
792{
793    Mutex::Autolock _l(ref.mLock);
794    mUserClientStrongRef = ref.mUserClient.promote();
795    if (mUserClientStrongRef != 0)
796        mControlBlock = ref.mControlBlock;
797}
798
799Layer::ClientRef::Access::~Access()
800{
801}
802
803// ---------------------------------------------------------------------------
804
805Layer::BufferManager::BufferManager(TextureManager& tm)
806    : mNumBuffers(NUM_BUFFERS), mTextureManager(tm),
807      mActiveBuffer(-1), mFailover(false)
808{
809}
810
811Layer::BufferManager::~BufferManager()
812{
813}
814
815status_t Layer::BufferManager::resize(size_t size,
816        const sp<SurfaceFlinger>& flinger, EGLDisplay dpy)
817{
818    Mutex::Autolock _l(mLock);
819
820    if (size < mNumBuffers) {
821        // Move the active texture into slot 0
822        BufferData activeBufferData = mBufferData[mActiveBuffer];
823        mBufferData[mActiveBuffer] = mBufferData[0];
824        mBufferData[0] = activeBufferData;
825        mActiveBuffer = 0;
826
827        // Free the buffers that are no longer needed.
828        for (size_t i = size; i < mNumBuffers; i++) {
829            mBufferData[i].buffer = 0;
830
831            // Create a message to destroy the textures on SurfaceFlinger's GL
832            // thread.
833            class MessageDestroyTexture : public MessageBase {
834                Image mTexture;
835                EGLDisplay mDpy;
836             public:
837                MessageDestroyTexture(const Image& texture, EGLDisplay dpy)
838                    : mTexture(texture), mDpy(dpy) { }
839                virtual bool handler() {
840                    status_t err = Layer::BufferManager::destroyTexture(
841                            &mTexture, mDpy);
842                    LOGE_IF(err<0, "error destroying texture: %d (%s)",
843                            mTexture.name, strerror(-err));
844                    return true; // XXX: err == 0;  ????
845                }
846            };
847
848            MessageDestroyTexture *msg = new MessageDestroyTexture(
849                    mBufferData[i].texture, dpy);
850
851            // Don't allow this texture to be cleaned up by
852            // BufferManager::destroy.
853            mBufferData[i].texture.name = -1U;
854            mBufferData[i].texture.image = EGL_NO_IMAGE_KHR;
855
856            // Post the message to the SurfaceFlinger object.
857            flinger->postMessageAsync(msg);
858        }
859    }
860
861    mNumBuffers = size;
862    return NO_ERROR;
863}
864
865// only for debugging
866sp<GraphicBuffer> Layer::BufferManager::getBuffer(size_t index) const {
867    return mBufferData[index].buffer;
868}
869
870status_t Layer::BufferManager::setActiveBufferIndex(size_t index) {
871    mActiveBuffer = index;
872    return NO_ERROR;
873}
874
875size_t Layer::BufferManager::getActiveBufferIndex() const {
876    return mActiveBuffer;
877}
878
879Texture Layer::BufferManager::getActiveTexture() const {
880    Texture res;
881    if (mFailover || mActiveBuffer<0) {
882        res = mFailoverTexture;
883    } else {
884        static_cast<Image&>(res) = mBufferData[mActiveBuffer].texture;
885    }
886    return res;
887}
888
889sp<GraphicBuffer> Layer::BufferManager::getActiveBuffer() const {
890    sp<GraphicBuffer> result;
891    const ssize_t activeBuffer = mActiveBuffer;
892    if (activeBuffer >= 0) {
893        BufferData const * const buffers = mBufferData;
894        Mutex::Autolock _l(mLock);
895        result = buffers[activeBuffer].buffer;
896    }
897    return result;
898}
899
900bool Layer::BufferManager::hasActiveBuffer() const {
901    return mActiveBuffer >= 0;
902}
903
904sp<GraphicBuffer> Layer::BufferManager::detachBuffer(size_t index)
905{
906    BufferData* const buffers = mBufferData;
907    sp<GraphicBuffer> buffer;
908    Mutex::Autolock _l(mLock);
909    buffer = buffers[index].buffer;
910    buffers[index].buffer = 0;
911    return buffer;
912}
913
914status_t Layer::BufferManager::attachBuffer(size_t index,
915        const sp<GraphicBuffer>& buffer)
916{
917    BufferData* const buffers = mBufferData;
918    Mutex::Autolock _l(mLock);
919    buffers[index].buffer = buffer;
920    buffers[index].texture.dirty = true;
921    return NO_ERROR;
922}
923
924status_t Layer::BufferManager::destroy(EGLDisplay dpy)
925{
926    BufferData* const buffers = mBufferData;
927    size_t num;
928    { // scope for the lock
929        Mutex::Autolock _l(mLock);
930        num = mNumBuffers;
931        for (size_t i=0 ; i<num ; i++) {
932            buffers[i].buffer = 0;
933        }
934    }
935    for (size_t i=0 ; i<num ; i++) {
936        destroyTexture(&buffers[i].texture, dpy);
937    }
938    destroyTexture(&mFailoverTexture, dpy);
939    return NO_ERROR;
940}
941
942status_t Layer::BufferManager::initEglImage(EGLDisplay dpy,
943        const sp<GraphicBuffer>& buffer)
944{
945    status_t err = NO_INIT;
946    ssize_t index = mActiveBuffer;
947    if (index >= 0) {
948        if (!mFailover) {
949            Image& texture(mBufferData[index].texture);
950            err = mTextureManager.initEglImage(&texture, dpy, buffer);
951            // if EGLImage fails, we switch to regular texture mode, and we
952            // free all resources associated with using EGLImages.
953            if (err == NO_ERROR) {
954                mFailover = false;
955                destroyTexture(&mFailoverTexture, dpy);
956            } else {
957                mFailover = true;
958                const size_t num = mNumBuffers;
959                for (size_t i=0 ; i<num ; i++) {
960                    destroyTexture(&mBufferData[i].texture, dpy);
961                }
962            }
963        } else {
964            // we failed once, don't try again
965            err = BAD_VALUE;
966        }
967    }
968    return err;
969}
970
971status_t Layer::BufferManager::loadTexture(
972        const Region& dirty, const GGLSurface& t)
973{
974    return mTextureManager.loadTexture(&mFailoverTexture, dirty, t);
975}
976
977status_t Layer::BufferManager::destroyTexture(Image* tex, EGLDisplay dpy)
978{
979    if (tex->name != -1U) {
980        glDeleteTextures(1, &tex->name);
981        tex->name = -1U;
982    }
983    if (tex->image != EGL_NO_IMAGE_KHR) {
984        eglDestroyImageKHR(dpy, tex->image);
985        tex->image = EGL_NO_IMAGE_KHR;
986    }
987    return NO_ERROR;
988}
989
990// ---------------------------------------------------------------------------
991
992Layer::SurfaceLayer::SurfaceLayer(const sp<SurfaceFlinger>& flinger,
993        const sp<Layer>& owner)
994    : Surface(flinger, owner->getIdentity(), owner)
995{
996}
997
998Layer::SurfaceLayer::~SurfaceLayer()
999{
1000}
1001
1002sp<GraphicBuffer> Layer::SurfaceLayer::requestBuffer(int index,
1003        uint32_t w, uint32_t h, uint32_t format, uint32_t usage)
1004{
1005    sp<GraphicBuffer> buffer;
1006    sp<Layer> owner(getOwner());
1007    if (owner != 0) {
1008        /*
1009         * requestBuffer() cannot be called from the main thread
1010         * as it could cause a dead-lock, since it may have to wait
1011         * on conditions updated my the main thread.
1012         */
1013        buffer = owner->requestBuffer(index, w, h, format, usage);
1014    }
1015    return buffer;
1016}
1017
1018status_t Layer::SurfaceLayer::setBufferCount(int bufferCount)
1019{
1020    status_t err = DEAD_OBJECT;
1021    sp<Layer> owner(getOwner());
1022    if (owner != 0) {
1023        /*
1024         * setBufferCount() cannot be called from the main thread
1025         * as it could cause a dead-lock, since it may have to wait
1026         * on conditions updated my the main thread.
1027         */
1028        err = owner->setBufferCount(bufferCount);
1029    }
1030    return err;
1031}
1032
1033// ---------------------------------------------------------------------------
1034
1035
1036}; // namespace android
1037