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