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