• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include <ui/Surface.h>
31 
32 #include "clz.h"
33 #include "Layer.h"
34 #include "SurfaceFlinger.h"
35 #include "DisplayHardware/DisplayHardware.h"
36 
37 
38 #define DEBUG_RESIZE    0
39 
40 
41 namespace android {
42 
43 // ---------------------------------------------------------------------------
44 
45 const uint32_t Layer::typeInfo = LayerBaseClient::typeInfo | 4;
46 const char* const Layer::typeID = "Layer";
47 
48 // ---------------------------------------------------------------------------
49 
Layer(SurfaceFlinger * flinger,DisplayID display,const sp<Client> & c,int32_t i)50 Layer::Layer(SurfaceFlinger* flinger, DisplayID display,
51         const sp<Client>& c, int32_t i)
52     :   LayerBaseClient(flinger, display, c, i),
53         mSecure(false),
54         mNoEGLImageForSwBuffers(false),
55         mNeedsBlending(true),
56         mNeedsDithering(false)
57 {
58     // no OpenGL operation is possible here, since we might not be
59     // in the OpenGL thread.
60     mFrontBufferIndex = lcblk->getFrontBuffer();
61 }
62 
~Layer()63 Layer::~Layer()
64 {
65     destroy();
66     // the actual buffers will be destroyed here
67 }
68 
destroy()69 void Layer::destroy()
70 {
71     for (size_t i=0 ; i<NUM_BUFFERS ; i++) {
72         if (mTextures[i].name != -1U) {
73             glDeleteTextures(1, &mTextures[i].name);
74             mTextures[i].name = -1U;
75         }
76         if (mTextures[i].image != EGL_NO_IMAGE_KHR) {
77             EGLDisplay dpy(mFlinger->graphicPlane(0).getEGLDisplay());
78             eglDestroyImageKHR(dpy, mTextures[i].image);
79             mTextures[i].image = EGL_NO_IMAGE_KHR;
80         }
81         Mutex::Autolock _l(mLock);
82         mBuffers[i].clear();
83         mWidth = mHeight = 0;
84     }
85     mSurface.clear();
86 }
87 
createSurface() const88 sp<LayerBaseClient::Surface> Layer::createSurface() const
89 {
90     return mSurface;
91 }
92 
ditch()93 status_t Layer::ditch()
94 {
95     // the layer is not on screen anymore. free as much resources as possible
96     destroy();
97     return NO_ERROR;
98 }
99 
setBuffers(uint32_t w,uint32_t h,PixelFormat format,uint32_t flags)100 status_t Layer::setBuffers( uint32_t w, uint32_t h,
101                             PixelFormat format, uint32_t flags)
102 {
103     // this surfaces pixel format
104     PixelFormatInfo info;
105     status_t err = getPixelFormatInfo(format, &info);
106     if (err) return err;
107 
108     // the display's pixel format
109     const DisplayHardware& hw(graphicPlane(0).displayHardware());
110     PixelFormatInfo displayInfo;
111     getPixelFormatInfo(hw.getFormat(), &displayInfo);
112     const uint32_t hwFlags = hw.getFlags();
113 
114     mFormat = format;
115     mWidth = w;
116     mHeight = h;
117     mSecure = (flags & ISurfaceComposer::eSecure) ? true : false;
118     mNeedsBlending = (info.h_alpha - info.l_alpha) > 0;
119     mNoEGLImageForSwBuffers = !(hwFlags & DisplayHardware::CACHED_BUFFERS);
120 
121     // we use the red index
122     int displayRedSize = displayInfo.getSize(PixelFormatInfo::INDEX_RED);
123     int layerRedsize = info.getSize(PixelFormatInfo::INDEX_RED);
124     mNeedsDithering = layerRedsize > displayRedSize;
125 
126     for (size_t i=0 ; i<NUM_BUFFERS ; i++) {
127         mBuffers[i] = new GraphicBuffer();
128     }
129     mSurface = new SurfaceLayer(mFlinger, clientIndex(), this);
130     return NO_ERROR;
131 }
132 
reloadTexture(const Region & dirty)133 void Layer::reloadTexture(const Region& dirty)
134 {
135     Mutex::Autolock _l(mLock);
136     sp<GraphicBuffer> buffer(getFrontBufferLocked());
137     int index = mFrontBufferIndex;
138 
139     // create the new texture name if needed
140     if (UNLIKELY(mTextures[index].name == -1U)) {
141         mTextures[index].name = createTexture();
142         mTextures[index].width = 0;
143         mTextures[index].height = 0;
144     }
145 
146 #ifdef EGL_ANDROID_image_native_buffer
147     if (mFlags & DisplayHardware::DIRECT_TEXTURE) {
148         if (buffer->usage & GraphicBuffer::USAGE_HW_TEXTURE) {
149             if (mTextures[index].dirty) {
150                 initializeEglImage(buffer, &mTextures[index]);
151             }
152         } else {
153             if (mHybridBuffer==0 || (mHybridBuffer->width != buffer->width ||
154                     mHybridBuffer->height != buffer->height)) {
155                 mHybridBuffer.clear();
156                 mHybridBuffer = new GraphicBuffer(
157                         buffer->width, buffer->height, buffer->format,
158                         GraphicBuffer::USAGE_SW_WRITE_OFTEN |
159                         GraphicBuffer::USAGE_HW_TEXTURE);
160                 initializeEglImage(
161                         mHybridBuffer, &mTextures[0]);
162             }
163 
164             GGLSurface t;
165             status_t res = buffer->lock(&t, GRALLOC_USAGE_SW_READ_OFTEN);
166             LOGE_IF(res, "error %d (%s) locking buffer %p",
167                     res, strerror(res), buffer.get());
168             if (res == NO_ERROR) {
169                 Texture* const texture(&mTextures[0]);
170 
171                 glBindTexture(GL_TEXTURE_2D, texture->name);
172 
173                 sp<GraphicBuffer> buf(mHybridBuffer);
174                 void* vaddr;
175                 res = buf->lock(GraphicBuffer::USAGE_SW_WRITE_OFTEN, &vaddr);
176                 if (res == NO_ERROR) {
177                     int bpp = 0;
178                     switch (t.format) {
179                     case GGL_PIXEL_FORMAT_RGB_565:
180                     case GGL_PIXEL_FORMAT_RGBA_4444:
181                         bpp = 2;
182                         break;
183                     case GGL_PIXEL_FORMAT_RGBA_8888:
184                     case GGL_PIXEL_FORMAT_RGBX_8888:
185                         bpp = 4;
186                         break;
187                     case GGL_PIXEL_FORMAT_YCbCr_422_SP:
188                     case GGL_PIXEL_FORMAT_YCbCr_420_SP:
189                         // just show the Y plane of YUV buffers
190                         bpp = 1;
191                         break;
192                     default:
193                         // oops, we don't handle this format!
194                         LOGE("layer %p, texture=%d, using format %d, which is not "
195                                 "supported by the GL", this, texture->name, t.format);
196                     }
197                     if (bpp) {
198                         const Rect bounds(dirty.getBounds());
199                         size_t src_stride = t.stride;
200                         size_t dst_stride = buf->stride;
201                         if (src_stride == dst_stride &&
202                             bounds.width() == t.width &&
203                             bounds.height() == t.height)
204                         {
205                             memcpy(vaddr, t.data, t.height * t.stride * bpp);
206                         } else {
207                             GLubyte const * src = t.data +
208                                 (bounds.left + bounds.top * src_stride) * bpp;
209                             GLubyte * dst = (GLubyte *)vaddr +
210                                 (bounds.left + bounds.top * dst_stride) * bpp;
211                             const size_t length = bounds.width() * bpp;
212                             size_t h = bounds.height();
213                             src_stride *= bpp;
214                             dst_stride *= bpp;
215                             while (h--) {
216                                 memcpy(dst, src, length);
217                                 dst += dst_stride;
218                                 src += src_stride;
219                             }
220                         }
221                     }
222                     buf->unlock();
223                 }
224                 buffer->unlock();
225             }
226         }
227     } else
228 #endif
229     {
230         for (size_t i=0 ; i<NUM_BUFFERS ; i++) {
231             mTextures[i].image = EGL_NO_IMAGE_KHR;
232         }
233         GGLSurface t;
234         status_t res = buffer->lock(&t, GRALLOC_USAGE_SW_READ_OFTEN);
235         LOGE_IF(res, "error %d (%s) locking buffer %p",
236                 res, strerror(res), buffer.get());
237         if (res == NO_ERROR) {
238             loadTexture(&mTextures[0], dirty, t);
239             buffer->unlock();
240         }
241     }
242 }
243 
onDraw(const Region & clip) const244 void Layer::onDraw(const Region& clip) const
245 {
246     int index = mFrontBufferIndex;
247     if (mTextures[index].image == EGL_NO_IMAGE_KHR)
248         index = 0;
249     GLuint textureName = mTextures[index].name;
250     if (UNLIKELY(textureName == -1LU)) {
251         // the texture has not been created yet, this Layer has
252         // in fact never been drawn into. this happens frequently with
253         // SurfaceView.
254         clearWithOpenGL(clip);
255         return;
256     }
257     drawWithOpenGL(clip, mTextures[index]);
258 }
259 
requestBuffer(int index,int usage)260 sp<GraphicBuffer> Layer::requestBuffer(int index, int usage)
261 {
262     sp<GraphicBuffer> buffer;
263 
264     // this ensures our client doesn't go away while we're accessing
265     // the shared area.
266     sp<Client> ourClient(client.promote());
267     if (ourClient == 0) {
268         // oops, the client is already gone
269         return buffer;
270     }
271 
272     /*
273      * This is called from the client's Surface::dequeue(). This can happen
274      * at any time, especially while we're in the middle of using the
275      * buffer 'index' as our front buffer.
276      *
277      * Make sure the buffer we're resizing is not the front buffer and has been
278      * dequeued. Once this condition is asserted, we are guaranteed that this
279      * buffer cannot become the front buffer under our feet, since we're called
280      * from Surface::dequeue()
281      */
282     status_t err = lcblk->assertReallocate(index);
283     LOGE_IF(err, "assertReallocate(%d) failed (%s)", index, strerror(-err));
284     if (err != NO_ERROR) {
285         // the surface may have died
286         return buffer;
287     }
288 
289     uint32_t w, h;
290     { // scope for the lock
291         Mutex::Autolock _l(mLock);
292         w = mWidth;
293         h = mHeight;
294         buffer = mBuffers[index];
295 
296         // destroy() could have been called before we get here, we log it
297         // because it's uncommon, and the code below should handle it
298         LOGW_IF(buffer==0,
299                 "mBuffers[%d] is null (mWidth=%d, mHeight=%d)",
300                 index, w, h);
301 
302         mBuffers[index].clear();
303     }
304 
305     const uint32_t effectiveUsage = getEffectiveUsage(usage);
306     if (buffer!=0 && buffer->getStrongCount() == 1) {
307         err = buffer->reallocate(w, h, mFormat, effectiveUsage);
308     } else {
309         // here we have to reallocate a new buffer because we could have a
310         // client in our process with a reference to it (eg: status bar),
311         // and we can't release the handle under its feet.
312         buffer.clear();
313         buffer = new GraphicBuffer(w, h, mFormat, effectiveUsage);
314         err = buffer->initCheck();
315     }
316 
317     if (err || buffer->handle == 0) {
318         LOGE_IF(err || buffer->handle == 0,
319                 "Layer::requestBuffer(this=%p), index=%d, w=%d, h=%d failed (%s)",
320                 this, index, w, h, strerror(-err));
321     } else {
322         LOGD_IF(DEBUG_RESIZE,
323                 "Layer::requestBuffer(this=%p), index=%d, w=%d, h=%d, handle=%p",
324                 this, index, w, h, buffer->handle);
325     }
326 
327     if (err == NO_ERROR && buffer->handle != 0) {
328         Mutex::Autolock _l(mLock);
329         if (mWidth && mHeight) {
330             // and we have new buffer
331             mBuffers[index] = buffer;
332             // texture is now dirty...
333             mTextures[index].dirty = true;
334         } else {
335             // oops we got killed while we were allocating the buffer
336             buffer.clear();
337         }
338     }
339     return buffer;
340 }
341 
getEffectiveUsage(uint32_t usage) const342 uint32_t Layer::getEffectiveUsage(uint32_t usage) const
343 {
344     /*
345      *  buffers used for software rendering, but h/w composition
346      *  are allocated with SW_READ_OFTEN | SW_WRITE_OFTEN | HW_TEXTURE
347      *
348      *  buffers used for h/w rendering and h/w composition
349      *  are allocated with  HW_RENDER | HW_TEXTURE
350      *
351      *  buffers used with h/w rendering and either NPOT or no egl_image_ext
352      *  are allocated with SW_READ_RARELY | HW_RENDER
353      *
354      */
355 
356     if (mSecure) {
357         // secure buffer, don't store it into the GPU
358         usage = GraphicBuffer::USAGE_SW_READ_OFTEN |
359                 GraphicBuffer::USAGE_SW_WRITE_OFTEN;
360     } else {
361         // it's allowed to modify the usage flags here, but generally
362         // the requested flags should be honored.
363         if (mNoEGLImageForSwBuffers) {
364             if (usage & GraphicBuffer::USAGE_HW_MASK) {
365                 // request EGLImage for h/w buffers only
366                 usage |= GraphicBuffer::USAGE_HW_TEXTURE;
367             }
368         } else {
369             // request EGLImage for all buffers
370             usage |= GraphicBuffer::USAGE_HW_TEXTURE;
371         }
372     }
373     return usage;
374 }
375 
doTransaction(uint32_t flags)376 uint32_t Layer::doTransaction(uint32_t flags)
377 {
378     const Layer::State& front(drawingState());
379     const Layer::State& temp(currentState());
380 
381     if ((front.requested_w != temp.requested_w) ||
382         (front.requested_h != temp.requested_h)) {
383         // the size changed, we need to ask our client to request a new buffer
384         LOGD_IF(DEBUG_RESIZE,
385                     "resize (layer=%p), requested (%dx%d), "
386                     "drawing (%d,%d), (%dx%d), (%dx%d)",
387                     this,
388                     int(temp.requested_w), int(temp.requested_h),
389                     int(front.requested_w), int(front.requested_h),
390                     int(mBuffers[0]->getWidth()), int(mBuffers[0]->getHeight()),
391                     int(mBuffers[1]->getWidth()), int(mBuffers[1]->getHeight()));
392 
393         // we're being resized and there is a freeze display request,
394         // acquire a freeze lock, so that the screen stays put
395         // until we've redrawn at the new size; this is to avoid
396         // glitches upon orientation changes.
397         if (mFlinger->hasFreezeRequest()) {
398             // if the surface is hidden, don't try to acquire the
399             // freeze lock, since hidden surfaces may never redraw
400             if (!(front.flags & ISurfaceComposer::eLayerHidden)) {
401                 mFreezeLock = mFlinger->getFreezeLock();
402             }
403         }
404 
405         // this will make sure LayerBase::doTransaction doesn't update
406         // the drawing state's size
407         Layer::State& editDraw(mDrawingState);
408         editDraw.requested_w = temp.requested_w;
409         editDraw.requested_h = temp.requested_h;
410 
411         // record the new size, form this point on, when the client request a
412         // buffer, it'll get the new size.
413         setDrawingSize(temp.requested_w, temp.requested_h);
414 
415         // all buffers need reallocation
416         lcblk->reallocate();
417     }
418 
419     if (temp.sequence != front.sequence) {
420         if (temp.flags & ISurfaceComposer::eLayerHidden || temp.alpha == 0) {
421             // this surface is now hidden, so it shouldn't hold a freeze lock
422             // (it may never redraw, which is fine if it is hidden)
423             mFreezeLock.clear();
424         }
425     }
426 
427     return LayerBase::doTransaction(flags);
428 }
429 
setDrawingSize(uint32_t w,uint32_t h)430 void Layer::setDrawingSize(uint32_t w, uint32_t h) {
431     Mutex::Autolock _l(mLock);
432     mWidth = w;
433     mHeight = h;
434 }
435 
436 // ----------------------------------------------------------------------------
437 // pageflip handling...
438 // ----------------------------------------------------------------------------
439 
lockPageFlip(bool & recomputeVisibleRegions)440 void Layer::lockPageFlip(bool& recomputeVisibleRegions)
441 {
442     ssize_t buf = lcblk->retireAndLock();
443     if (buf < NO_ERROR) {
444         //LOGW("nothing to retire (%s)", strerror(-buf));
445         // NOTE: here the buffer is locked because we will used
446         // for composition later in the loop
447         return;
448     }
449 
450     // we retired a buffer, which becomes the new front buffer
451     mFrontBufferIndex = buf;
452 
453     // get the dirty region
454     sp<GraphicBuffer> newFrontBuffer(getBuffer(buf));
455     const Region dirty(lcblk->getDirtyRegion(buf));
456     mPostedDirtyRegion = dirty.intersect( newFrontBuffer->getBounds() );
457 
458     const Layer::State& front(drawingState());
459     if (newFrontBuffer->getWidth()  == front.requested_w &&
460         newFrontBuffer->getHeight() == front.requested_h)
461     {
462         if ((front.w != front.requested_w) ||
463             (front.h != front.requested_h))
464         {
465             // Here we pretend the transaction happened by updating the
466             // current and drawing states. Drawing state is only accessed
467             // in this thread, no need to have it locked
468             Layer::State& editDraw(mDrawingState);
469             editDraw.w = editDraw.requested_w;
470             editDraw.h = editDraw.requested_h;
471 
472             // We also need to update the current state so that we don't
473             // end-up doing too much work during the next transaction.
474             // NOTE: We actually don't need hold the transaction lock here
475             // because State::w and State::h are only accessed from
476             // this thread
477             Layer::State& editTemp(currentState());
478             editTemp.w = editDraw.w;
479             editTemp.h = editDraw.h;
480 
481             // recompute visible region
482             recomputeVisibleRegions = true;
483         }
484 
485         // we now have the correct size, unfreeze the screen
486         mFreezeLock.clear();
487     }
488 
489     if (lcblk->getQueuedCount()) {
490         // signal an event if we have more buffers waiting
491         mFlinger->signalEvent();
492     }
493 
494     if (!mPostedDirtyRegion.isEmpty()) {
495         reloadTexture( mPostedDirtyRegion );
496     }
497 }
498 
unlockPageFlip(const Transform & planeTransform,Region & outDirtyRegion)499 void Layer::unlockPageFlip(
500         const Transform& planeTransform, Region& outDirtyRegion)
501 {
502     Region dirtyRegion(mPostedDirtyRegion);
503     if (!dirtyRegion.isEmpty()) {
504         mPostedDirtyRegion.clear();
505         // The dirty region is given in the layer's coordinate space
506         // transform the dirty region by the surface's transformation
507         // and the global transformation.
508         const Layer::State& s(drawingState());
509         const Transform tr(planeTransform * s.transform);
510         dirtyRegion = tr.transform(dirtyRegion);
511 
512         // At this point, the dirty region is in screen space.
513         // Make sure it's constrained by the visible region (which
514         // is in screen space as well).
515         dirtyRegion.andSelf(visibleRegionScreen);
516         outDirtyRegion.orSelf(dirtyRegion);
517     }
518 }
519 
finishPageFlip()520 void Layer::finishPageFlip()
521 {
522     status_t err = lcblk->unlock( mFrontBufferIndex );
523     LOGE_IF(err!=NO_ERROR,
524             "layer %p, buffer=%d wasn't locked!",
525             this, mFrontBufferIndex);
526 }
527 
528 // ---------------------------------------------------------------------------
529 
SurfaceLayer(const sp<SurfaceFlinger> & flinger,SurfaceID id,const sp<Layer> & owner)530 Layer::SurfaceLayer::SurfaceLayer(const sp<SurfaceFlinger>& flinger,
531         SurfaceID id, const sp<Layer>& owner)
532     : Surface(flinger, id, owner->getIdentity(), owner)
533 {
534 }
535 
~SurfaceLayer()536 Layer::SurfaceLayer::~SurfaceLayer()
537 {
538 }
539 
requestBuffer(int index,int usage)540 sp<GraphicBuffer> Layer::SurfaceLayer::requestBuffer(int index, int usage)
541 {
542     sp<GraphicBuffer> buffer;
543     sp<Layer> owner(getOwner());
544     if (owner != 0) {
545         LOGE_IF(uint32_t(index)>=NUM_BUFFERS,
546                 "getBuffer() index (%d) out of range", index);
547         if (uint32_t(index) < NUM_BUFFERS) {
548             buffer = owner->requestBuffer(index, usage);
549         }
550     }
551     return buffer;
552 }
553 
554 // ---------------------------------------------------------------------------
555 
556 
557 }; // namespace android
558