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