Layer.cpp revision 2bd1d95efecffad447afd682ffe605bbf8c79d62
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::dump(String8& result, char* buffer, size_t SIZE) const
695{
696    LayerBaseClient::dump(result, buffer, SIZE);
697
698    ClientRef::Access sharedClient(mUserClientRef);
699    SharedBufferServer* lcblk(sharedClient.get());
700    uint32_t totalTime = 0;
701    if (lcblk) {
702        SharedBufferStack::Statistics stats = lcblk->getStats();
703        totalTime= stats.totalTime;
704        result.append( lcblk->dump("      ") );
705    }
706
707    sp<const GraphicBuffer> buf0(getBuffer(0));
708    sp<const GraphicBuffer> buf1(getBuffer(1));
709    uint32_t w0=0, h0=0, s0=0;
710    uint32_t w1=0, h1=0, s1=0;
711    if (buf0 != 0) {
712        w0 = buf0->getWidth();
713        h0 = buf0->getHeight();
714        s0 = buf0->getStride();
715    }
716    if (buf1 != 0) {
717        w1 = buf1->getWidth();
718        h1 = buf1->getHeight();
719        s1 = buf1->getStride();
720    }
721    snprintf(buffer, SIZE,
722            "      "
723            "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u],"
724            " freezeLock=%p, dq-q-time=%u us\n",
725            mFormat, w0, h0, s0, w1, h1, s1,
726            getFreezeLock().get(), totalTime);
727
728    result.append(buffer);
729}
730
731// ---------------------------------------------------------------------------
732
733Layer::ClientRef::ClientRef()
734    : mControlBlock(0), mToken(-1) {
735}
736
737Layer::ClientRef::~ClientRef() {
738}
739
740int32_t Layer::ClientRef::getToken() const {
741    Mutex::Autolock _l(mLock);
742    return mToken;
743}
744
745sp<UserClient> Layer::ClientRef::getClient() const {
746    Mutex::Autolock _l(mLock);
747    return mUserClient.promote();
748}
749
750status_t Layer::ClientRef::setToken(const sp<UserClient>& uc,
751        const sp<SharedBufferServer>& sharedClient, int32_t token) {
752    Mutex::Autolock _l(mLock);
753
754    { // scope for strong mUserClient reference
755        sp<UserClient> userClient(mUserClient.promote());
756        if (mUserClient != 0 && mControlBlock != 0) {
757            mControlBlock->setStatus(NO_INIT);
758        }
759    }
760
761    mUserClient = uc;
762    mToken = token;
763    mControlBlock = sharedClient;
764    return NO_ERROR;
765}
766
767sp<UserClient> Layer::ClientRef::getUserClientUnsafe() const {
768    return mUserClient.promote();
769}
770
771// this class gives us access to SharedBufferServer safely
772// it makes sure the UserClient (and its associated shared memory)
773// won't go away while we're accessing it.
774Layer::ClientRef::Access::Access(const ClientRef& ref)
775    : mControlBlock(0)
776{
777    Mutex::Autolock _l(ref.mLock);
778    mUserClientStrongRef = ref.mUserClient.promote();
779    if (mUserClientStrongRef != 0)
780        mControlBlock = ref.mControlBlock;
781}
782
783Layer::ClientRef::Access::~Access()
784{
785}
786
787// ---------------------------------------------------------------------------
788
789Layer::BufferManager::BufferManager(TextureManager& tm)
790    : mNumBuffers(NUM_BUFFERS), mTextureManager(tm),
791      mActiveBufferIndex(-1), mFailover(false)
792{
793}
794
795Layer::BufferManager::~BufferManager()
796{
797}
798
799status_t Layer::BufferManager::resize(size_t size,
800        const sp<SurfaceFlinger>& flinger, EGLDisplay dpy)
801{
802    Mutex::Autolock _l(mLock);
803
804    if (size < mNumBuffers) {
805        // Move the active texture into slot 0
806        BufferData activeBufferData = mBufferData[mActiveBufferIndex];
807        mBufferData[mActiveBufferIndex] = mBufferData[0];
808        mBufferData[0] = activeBufferData;
809        mActiveBufferIndex = 0;
810
811        // Free the buffers that are no longer needed.
812        for (size_t i = size; i < mNumBuffers; i++) {
813            mBufferData[i].buffer = 0;
814
815            // Create a message to destroy the textures on SurfaceFlinger's GL
816            // thread.
817            class MessageDestroyTexture : public MessageBase {
818                Image mTexture;
819                EGLDisplay mDpy;
820             public:
821                MessageDestroyTexture(const Image& texture, EGLDisplay dpy)
822                    : mTexture(texture), mDpy(dpy) { }
823                virtual bool handler() {
824                    status_t err = Layer::BufferManager::destroyTexture(
825                            &mTexture, mDpy);
826                    LOGE_IF(err<0, "error destroying texture: %d (%s)",
827                            mTexture.name, strerror(-err));
828                    return true; // XXX: err == 0;  ????
829                }
830            };
831
832            MessageDestroyTexture *msg = new MessageDestroyTexture(
833                    mBufferData[i].texture, dpy);
834
835            // Don't allow this texture to be cleaned up by
836            // BufferManager::destroy.
837            mBufferData[i].texture.name = -1U;
838            mBufferData[i].texture.image = EGL_NO_IMAGE_KHR;
839
840            // Post the message to the SurfaceFlinger object.
841            flinger->postMessageAsync(msg);
842        }
843    }
844
845    mNumBuffers = size;
846    return NO_ERROR;
847}
848
849// only for debugging
850sp<GraphicBuffer> Layer::BufferManager::getBuffer(size_t index) const {
851    return mBufferData[index].buffer;
852}
853
854status_t Layer::BufferManager::setActiveBufferIndex(size_t index) {
855    BufferData const * const buffers = mBufferData;
856    Mutex::Autolock _l(mLock);
857    mActiveBuffer = buffers[index].buffer;
858    mActiveBufferIndex = index;
859    return NO_ERROR;
860}
861
862size_t Layer::BufferManager::getActiveBufferIndex() const {
863    return mActiveBufferIndex;
864}
865
866Texture Layer::BufferManager::getActiveTexture() const {
867    Texture res;
868    if (mFailover || mActiveBufferIndex<0) {
869        res = mFailoverTexture;
870    } else {
871        static_cast<Image&>(res) = mBufferData[mActiveBufferIndex].texture;
872    }
873    return res;
874}
875
876sp<GraphicBuffer> Layer::BufferManager::getActiveBuffer() const {
877    return mActiveBuffer;
878}
879
880bool Layer::BufferManager::hasActiveBuffer() const {
881    return mActiveBufferIndex >= 0;
882}
883
884sp<GraphicBuffer> Layer::BufferManager::detachBuffer(size_t index)
885{
886    BufferData* const buffers = mBufferData;
887    sp<GraphicBuffer> buffer;
888    Mutex::Autolock _l(mLock);
889    buffer = buffers[index].buffer;
890    buffers[index].buffer = 0;
891    return buffer;
892}
893
894status_t Layer::BufferManager::attachBuffer(size_t index,
895        const sp<GraphicBuffer>& buffer)
896{
897    BufferData* const buffers = mBufferData;
898    Mutex::Autolock _l(mLock);
899    buffers[index].buffer = buffer;
900    buffers[index].texture.dirty = true;
901    return NO_ERROR;
902}
903
904status_t Layer::BufferManager::destroy(EGLDisplay dpy)
905{
906    BufferData* const buffers = mBufferData;
907    size_t num;
908    { // scope for the lock
909        Mutex::Autolock _l(mLock);
910        num = mNumBuffers;
911        for (size_t i=0 ; i<num ; i++) {
912            buffers[i].buffer = 0;
913        }
914    }
915    for (size_t i=0 ; i<num ; i++) {
916        destroyTexture(&buffers[i].texture, dpy);
917    }
918    destroyTexture(&mFailoverTexture, dpy);
919    return NO_ERROR;
920}
921
922status_t Layer::BufferManager::initEglImage(EGLDisplay dpy,
923        const sp<GraphicBuffer>& buffer)
924{
925    status_t err = NO_INIT;
926    ssize_t index = mActiveBufferIndex;
927    if (index >= 0) {
928        if (!mFailover) {
929            Image& texture(mBufferData[index].texture);
930            err = mTextureManager.initEglImage(&texture, dpy, buffer);
931            // if EGLImage fails, we switch to regular texture mode, and we
932            // free all resources associated with using EGLImages.
933            if (err == NO_ERROR) {
934                mFailover = false;
935                destroyTexture(&mFailoverTexture, dpy);
936            } else {
937                mFailover = true;
938                const size_t num = mNumBuffers;
939                for (size_t i=0 ; i<num ; i++) {
940                    destroyTexture(&mBufferData[i].texture, dpy);
941                }
942            }
943        } else {
944            // we failed once, don't try again
945            err = BAD_VALUE;
946        }
947    }
948    return err;
949}
950
951status_t Layer::BufferManager::loadTexture(
952        const Region& dirty, const GGLSurface& t)
953{
954    return mTextureManager.loadTexture(&mFailoverTexture, dirty, t);
955}
956
957status_t Layer::BufferManager::destroyTexture(Image* tex, EGLDisplay dpy)
958{
959    if (tex->name != -1U) {
960        glDeleteTextures(1, &tex->name);
961        tex->name = -1U;
962    }
963    if (tex->image != EGL_NO_IMAGE_KHR) {
964        eglDestroyImageKHR(dpy, tex->image);
965        tex->image = EGL_NO_IMAGE_KHR;
966    }
967    return NO_ERROR;
968}
969
970// ---------------------------------------------------------------------------
971
972Layer::SurfaceLayer::SurfaceLayer(const sp<SurfaceFlinger>& flinger,
973        const sp<Layer>& owner)
974    : Surface(flinger, owner->getIdentity(), owner)
975{
976}
977
978Layer::SurfaceLayer::~SurfaceLayer()
979{
980}
981
982sp<GraphicBuffer> Layer::SurfaceLayer::requestBuffer(int index,
983        uint32_t w, uint32_t h, uint32_t format, uint32_t usage)
984{
985    sp<GraphicBuffer> buffer;
986    sp<Layer> owner(getOwner());
987    if (owner != 0) {
988        /*
989         * requestBuffer() cannot be called from the main thread
990         * as it could cause a dead-lock, since it may have to wait
991         * on conditions updated my the main thread.
992         */
993        buffer = owner->requestBuffer(index, w, h, format, usage);
994    }
995    return buffer;
996}
997
998status_t Layer::SurfaceLayer::setBufferCount(int bufferCount)
999{
1000    status_t err = DEAD_OBJECT;
1001    sp<Layer> owner(getOwner());
1002    if (owner != 0) {
1003        /*
1004         * setBufferCount() cannot be called from the main thread
1005         * as it could cause a dead-lock, since it may have to wait
1006         * on conditions updated my the main thread.
1007         */
1008        err = owner->setBufferCount(bufferCount);
1009    }
1010    return err;
1011}
1012
1013// ---------------------------------------------------------------------------
1014
1015
1016}; // namespace android
1017