Layer.cpp revision e8067a7d996105d9e03d75e6593e28b795fa9336
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/compiler.h> 22#include <cutils/native_handle.h> 23#include <cutils/properties.h> 24 25#include <utils/Errors.h> 26#include <utils/Log.h> 27#include <utils/StopWatch.h> 28 29#include <ui/GraphicBuffer.h> 30#include <ui/PixelFormat.h> 31 32#include <surfaceflinger/Surface.h> 33 34#include "clz.h" 35#include "DisplayHardware/DisplayHardware.h" 36#include "DisplayHardware/HWComposer.h" 37#include "GLExtensions.h" 38#include "Layer.h" 39#include "SurfaceFlinger.h" 40#include "SurfaceTextureLayer.h" 41 42#define DEBUG_RESIZE 0 43 44 45namespace android { 46 47// --------------------------------------------------------------------------- 48 49Layer::Layer(SurfaceFlinger* flinger, 50 DisplayID display, const sp<Client>& client) 51 : LayerBaseClient(flinger, display, client), 52 mTextureName(-1U), 53 mQueuedFrames(0), 54 mCurrentTransform(0), 55 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE), 56 mCurrentOpacity(true), 57 mFormat(PIXEL_FORMAT_NONE), 58 mGLExtensions(GLExtensions::getInstance()), 59 mOpaqueLayer(true), 60 mNeedsDithering(false), 61 mSecure(false), 62 mProtectedByApp(false) 63{ 64 mCurrentCrop.makeInvalid(); 65 glGenTextures(1, &mTextureName); 66} 67 68void Layer::destroy(RefBase const* base) { 69 mFlinger->destroyLayer(static_cast<LayerBase const*>(base)); 70} 71 72void Layer::onFirstRef() 73{ 74 LayerBaseClient::onFirstRef(); 75 setDestroyer(this); 76 77 struct FrameQueuedListener : public SurfaceTexture::FrameAvailableListener { 78 FrameQueuedListener(Layer* layer) : mLayer(layer) { } 79 private: 80 wp<Layer> mLayer; 81 virtual void onFrameAvailable() { 82 sp<Layer> that(mLayer.promote()); 83 if (that != 0) { 84 that->onFrameQueued(); 85 } 86 } 87 }; 88 mSurfaceTexture = new SurfaceTextureLayer(mTextureName, this); 89 mSurfaceTexture->setFrameAvailableListener(new FrameQueuedListener(this)); 90 mSurfaceTexture->setSynchronousMode(true); 91 mSurfaceTexture->setBufferCountServer(2); 92} 93 94Layer::~Layer() 95{ 96 glDeleteTextures(1, &mTextureName); 97} 98 99void Layer::onFrameQueued() { 100 android_atomic_inc(&mQueuedFrames); 101 mFlinger->signalEvent(); 102} 103 104// called with SurfaceFlinger::mStateLock as soon as the layer is entered 105// in the purgatory list 106void Layer::onRemoved() 107{ 108 mSurfaceTexture->abandon(); 109} 110 111sp<ISurface> Layer::createSurface() 112{ 113 class BSurface : public BnSurface, public LayerCleaner { 114 wp<const Layer> mOwner; 115 virtual sp<ISurfaceTexture> getSurfaceTexture() const { 116 sp<ISurfaceTexture> res; 117 sp<const Layer> that( mOwner.promote() ); 118 if (that != NULL) { 119 res = that->mSurfaceTexture; 120 } 121 return res; 122 } 123 public: 124 BSurface(const sp<SurfaceFlinger>& flinger, 125 const sp<Layer>& layer) 126 : LayerCleaner(flinger, layer), mOwner(layer) { } 127 }; 128 sp<ISurface> sur(new BSurface(mFlinger, this)); 129 return sur; 130} 131 132status_t Layer::setBuffers( uint32_t w, uint32_t h, 133 PixelFormat format, uint32_t flags) 134{ 135 // this surfaces pixel format 136 PixelFormatInfo info; 137 status_t err = getPixelFormatInfo(format, &info); 138 if (err) return err; 139 140 // the display's pixel format 141 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 142 uint32_t const maxSurfaceDims = min( 143 hw.getMaxTextureSize(), hw.getMaxViewportDims()); 144 145 // never allow a surface larger than what our underlying GL implementation 146 // can handle. 147 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) { 148 return BAD_VALUE; 149 } 150 151 PixelFormatInfo displayInfo; 152 getPixelFormatInfo(hw.getFormat(), &displayInfo); 153 const uint32_t hwFlags = hw.getFlags(); 154 155 mFormat = format; 156 157 mSecure = (flags & ISurfaceComposer::eSecure) ? true : false; 158 mProtectedByApp = (flags & ISurfaceComposer::eProtectedByApp) ? true : false; 159 mOpaqueLayer = (flags & ISurfaceComposer::eOpaque); 160 mCurrentOpacity = getOpacityForFormat(format); 161 162 mSurfaceTexture->setDefaultBufferSize(w, h); 163 mSurfaceTexture->setDefaultBufferFormat(format); 164 165 // we use the red index 166 int displayRedSize = displayInfo.getSize(PixelFormatInfo::INDEX_RED); 167 int layerRedsize = info.getSize(PixelFormatInfo::INDEX_RED); 168 mNeedsDithering = layerRedsize > displayRedSize; 169 170 return NO_ERROR; 171} 172 173void Layer::setGeometry(hwc_layer_t* hwcl) 174{ 175 LayerBaseClient::setGeometry(hwcl); 176 177 hwcl->flags &= ~HWC_SKIP_LAYER; 178 179 // we can't do alpha-fade with the hwc HAL 180 const State& s(drawingState()); 181 if (s.alpha < 0xFF) { 182 hwcl->flags = HWC_SKIP_LAYER; 183 } 184 185 /* 186 * Transformations are applied in this order: 187 * 1) buffer orientation/flip/mirror 188 * 2) state transformation (window manager) 189 * 3) layer orientation (screen orientation) 190 * (NOTE: the matrices are multiplied in reverse order) 191 */ 192 193 const Transform bufferOrientation(mCurrentTransform); 194 const Transform& stateTransform(s.transform); 195 const Transform layerOrientation(mOrientation); 196 197 const Transform tr(layerOrientation * stateTransform * bufferOrientation); 198 199 // this gives us only the "orientation" component of the transform 200 const uint32_t finalTransform = tr.getOrientation(); 201 202 // we can only handle simple transformation 203 if (finalTransform & Transform::ROT_INVALID) { 204 hwcl->flags = HWC_SKIP_LAYER; 205 } else { 206 hwcl->transform = finalTransform; 207 } 208} 209 210void Layer::setPerFrameData(hwc_layer_t* hwcl) { 211 const sp<GraphicBuffer>& buffer(mActiveBuffer); 212 if (buffer == NULL) { 213 // this can happen if the client never drew into this layer yet, 214 // or if we ran out of memory. In that case, don't let 215 // HWC handle it. 216 hwcl->flags |= HWC_SKIP_LAYER; 217 hwcl->handle = NULL; 218 } else { 219 hwcl->handle = buffer->handle; 220 } 221 222 if (isCropped()) { 223 hwcl->sourceCrop.left = mCurrentCrop.left; 224 hwcl->sourceCrop.top = mCurrentCrop.top; 225 hwcl->sourceCrop.right = mCurrentCrop.right; 226 hwcl->sourceCrop.bottom = mCurrentCrop.bottom; 227 } else { 228 hwcl->sourceCrop.left = 0; 229 hwcl->sourceCrop.top = 0; 230 if (buffer != NULL) { 231 hwcl->sourceCrop.right = buffer->width; 232 hwcl->sourceCrop.bottom = buffer->height; 233 } else { 234 hwcl->sourceCrop.right = mTransformedBounds.width(); 235 hwcl->sourceCrop.bottom = mTransformedBounds.height(); 236 } 237 } 238} 239 240static inline uint16_t pack565(int r, int g, int b) { 241 return (r<<11)|(g<<5)|b; 242} 243void Layer::onDraw(const Region& clip) const 244{ 245 if (CC_UNLIKELY(mActiveBuffer == 0)) { 246 // the texture has not been created yet, this Layer has 247 // in fact never been drawn into. This happens frequently with 248 // SurfaceView because the WindowManager can't know when the client 249 // has drawn the first time. 250 251 // If there is nothing under us, we paint the screen in black, otherwise 252 // we just skip this update. 253 254 // figure out if there is something below us 255 Region under; 256 const SurfaceFlinger::LayerVector& drawingLayers(mFlinger->mDrawingState.layersSortedByZ); 257 const size_t count = drawingLayers.size(); 258 for (size_t i=0 ; i<count ; ++i) { 259 const sp<LayerBase>& layer(drawingLayers[i]); 260 if (layer.get() == static_cast<LayerBase const*>(this)) 261 break; 262 under.orSelf(layer->visibleRegionScreen); 263 } 264 // if not everything below us is covered, we plug the holes! 265 Region holes(clip.subtract(under)); 266 if (!holes.isEmpty()) { 267 clearWithOpenGL(holes, 0, 0, 0, 1); 268 } 269 return; 270 } 271 272 GLenum target = mSurfaceTexture->getCurrentTextureTarget(); 273 glBindTexture(target, mTextureName); 274 if (getFiltering() || needsFiltering() || isFixedSize() || isCropped()) { 275 // TODO: we could be more subtle with isFixedSize() 276 glTexParameterx(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 277 glTexParameterx(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 278 } else { 279 glTexParameterx(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); 280 glTexParameterx(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); 281 } 282 glEnable(target); 283 glMatrixMode(GL_TEXTURE); 284 glLoadMatrixf(mTextureMatrix); 285 glMatrixMode(GL_MODELVIEW); 286 287 drawWithOpenGL(clip); 288 289 glDisable(target); 290} 291 292// As documented in libhardware header, formats in the range 293// 0x100 - 0x1FF are specific to the HAL implementation, and 294// are known to have no alpha channel 295// TODO: move definition for device-specific range into 296// hardware.h, instead of using hard-coded values here. 297#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF) 298 299bool Layer::getOpacityForFormat(uint32_t format) 300{ 301 if (HARDWARE_IS_DEVICE_FORMAT(format)) { 302 return true; 303 } 304 PixelFormatInfo info; 305 status_t err = getPixelFormatInfo(PixelFormat(format), &info); 306 // in case of error (unknown format), we assume no blending 307 return (err || info.h_alpha <= info.l_alpha); 308} 309 310 311bool Layer::isOpaque() const 312{ 313 // if we don't have a buffer yet, we're translucent regardless of the 314 // layer's opaque flag. 315 if (mActiveBuffer == 0) { 316 return false; 317 } 318 319 // if the layer has the opaque flag, then we're always opaque, 320 // otherwise we use the current buffer's format. 321 return mOpaqueLayer || mCurrentOpacity; 322} 323 324bool Layer::isProtected() const 325{ 326 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer); 327 return (activeBuffer != 0) && 328 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED); 329} 330 331uint32_t Layer::doTransaction(uint32_t flags) 332{ 333 const Layer::State& front(drawingState()); 334 const Layer::State& temp(currentState()); 335 336 const bool sizeChanged = (front.requested_w != temp.requested_w) || 337 (front.requested_h != temp.requested_h); 338 339 if (sizeChanged) { 340 // the size changed, we need to ask our client to request a new buffer 341 LOGD_IF(DEBUG_RESIZE, 342 "doTransaction: " 343 "resize (layer=%p), requested (%dx%d), drawing (%d,%d), " 344 "scalingMode=%d", 345 this, 346 int(temp.requested_w), int(temp.requested_h), 347 int(front.requested_w), int(front.requested_h), 348 mCurrentScalingMode); 349 350 if (!isFixedSize()) { 351 // we're being resized and there is a freeze display request, 352 // acquire a freeze lock, so that the screen stays put 353 // until we've redrawn at the new size; this is to avoid 354 // glitches upon orientation changes. 355 if (mFlinger->hasFreezeRequest()) { 356 // if the surface is hidden, don't try to acquire the 357 // freeze lock, since hidden surfaces may never redraw 358 if (!(front.flags & ISurfaceComposer::eLayerHidden)) { 359 mFreezeLock = mFlinger->getFreezeLock(); 360 } 361 } 362 363 // this will make sure LayerBase::doTransaction doesn't update 364 // the drawing state's size 365 Layer::State& editDraw(mDrawingState); 366 editDraw.requested_w = temp.requested_w; 367 editDraw.requested_h = temp.requested_h; 368 369 // record the new size, form this point on, when the client request 370 // a buffer, it'll get the new size. 371 mSurfaceTexture->setDefaultBufferSize(temp.requested_w, temp.requested_h); 372 } 373 } 374 375 if (temp.sequence != front.sequence) { 376 if (temp.flags & ISurfaceComposer::eLayerHidden || temp.alpha == 0) { 377 // this surface is now hidden, so it shouldn't hold a freeze lock 378 // (it may never redraw, which is fine if it is hidden) 379 mFreezeLock.clear(); 380 } 381 } 382 383 return LayerBase::doTransaction(flags); 384} 385 386bool Layer::isFixedSize() const { 387 return mCurrentScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE; 388} 389 390bool Layer::isCropped() const { 391 return !mCurrentCrop.isEmpty(); 392} 393 394// ---------------------------------------------------------------------------- 395// pageflip handling... 396// ---------------------------------------------------------------------------- 397 398void Layer::lockPageFlip(bool& recomputeVisibleRegions) 399{ 400 if (mQueuedFrames > 0) { 401 const bool oldOpacity = isOpaque(); 402 403 // signal another event if we have more frames pending 404 if (android_atomic_dec(&mQueuedFrames) > 1) { 405 mFlinger->signalEvent(); 406 } 407 408 if (mSurfaceTexture->updateTexImage() < NO_ERROR) { 409 // something happened! 410 recomputeVisibleRegions = true; 411 return; 412 } 413 414 mActiveBuffer = mSurfaceTexture->getCurrentBuffer(); 415 mSurfaceTexture->getTransformMatrix(mTextureMatrix); 416 417 const Rect crop(mSurfaceTexture->getCurrentCrop()); 418 const uint32_t transform(mSurfaceTexture->getCurrentTransform()); 419 const uint32_t scalingMode(mSurfaceTexture->getCurrentScalingMode()); 420 if ((crop != mCurrentCrop) || 421 (transform != mCurrentTransform) || 422 (scalingMode != mCurrentScalingMode)) 423 { 424 mCurrentCrop = crop; 425 mCurrentTransform = transform; 426 mCurrentScalingMode = scalingMode; 427 mFlinger->invalidateHwcGeometry(); 428 } 429 430 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format); 431 if (oldOpacity != isOpaque()) { 432 recomputeVisibleRegions = true; 433 } 434 435 const GLenum target(mSurfaceTexture->getCurrentTextureTarget()); 436 glTexParameterx(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 437 glTexParameterx(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 438 439 // update the layer size and release freeze-lock 440 const Layer::State& front(drawingState()); 441 442 // FIXME: mPostedDirtyRegion = dirty & bounds 443 mPostedDirtyRegion.set(front.w, front.h); 444 445 446 if ((front.w != front.requested_w) || 447 (front.h != front.requested_h)) 448 { 449 // check that we received a buffer of the right size 450 // (Take the buffer's orientation into account) 451 sp<GraphicBuffer> newFrontBuffer(mActiveBuffer); 452 uint32_t bufWidth = newFrontBuffer->getWidth(); 453 uint32_t bufHeight = newFrontBuffer->getHeight(); 454 if (mCurrentTransform & Transform::ROT_90) { 455 swap(bufWidth, bufHeight); 456 } 457 458 if (isFixedSize() || 459 (bufWidth == front.requested_w && 460 bufHeight == front.requested_h)) 461 { 462 // Here we pretend the transaction happened by updating the 463 // current and drawing states. Drawing state is only accessed 464 // in this thread, no need to have it locked 465 Layer::State& editDraw(mDrawingState); 466 editDraw.w = editDraw.requested_w; 467 editDraw.h = editDraw.requested_h; 468 469 // We also need to update the current state so that we don't 470 // end-up doing too much work during the next transaction. 471 // NOTE: We actually don't need hold the transaction lock here 472 // because State::w and State::h are only accessed from 473 // this thread 474 Layer::State& editTemp(currentState()); 475 editTemp.w = editDraw.w; 476 editTemp.h = editDraw.h; 477 478 // recompute visible region 479 recomputeVisibleRegions = true; 480 481 // we now have the correct size, unfreeze the screen 482 mFreezeLock.clear(); 483 } 484 485 LOGD_IF(DEBUG_RESIZE, 486 "lockPageFlip : " 487 " (layer=%p), buffer (%ux%u, tr=%02x), " 488 "requested (%dx%d)", 489 this, 490 bufWidth, bufHeight, mCurrentTransform, 491 front.requested_w, front.requested_h); 492 } 493 } 494} 495 496void Layer::unlockPageFlip( 497 const Transform& planeTransform, Region& outDirtyRegion) 498{ 499 Region dirtyRegion(mPostedDirtyRegion); 500 if (!dirtyRegion.isEmpty()) { 501 mPostedDirtyRegion.clear(); 502 // The dirty region is given in the layer's coordinate space 503 // transform the dirty region by the surface's transformation 504 // and the global transformation. 505 const Layer::State& s(drawingState()); 506 const Transform tr(planeTransform * s.transform); 507 dirtyRegion = tr.transform(dirtyRegion); 508 509 // At this point, the dirty region is in screen space. 510 // Make sure it's constrained by the visible region (which 511 // is in screen space as well). 512 dirtyRegion.andSelf(visibleRegionScreen); 513 outDirtyRegion.orSelf(dirtyRegion); 514 } 515 if (visibleRegionScreen.isEmpty()) { 516 // an invisible layer should not hold a freeze-lock 517 // (because it may never be updated and therefore never release it) 518 mFreezeLock.clear(); 519 } 520} 521 522void Layer::dump(String8& result, char* buffer, size_t SIZE) const 523{ 524 LayerBaseClient::dump(result, buffer, SIZE); 525 526 sp<const GraphicBuffer> buf0(mActiveBuffer); 527 uint32_t w0=0, h0=0, s0=0, f0=0; 528 if (buf0 != 0) { 529 w0 = buf0->getWidth(); 530 h0 = buf0->getHeight(); 531 s0 = buf0->getStride(); 532 f0 = buf0->format; 533 } 534 snprintf(buffer, SIZE, 535 " " 536 "format=%2d, activeBuffer=[%3ux%3u:%3u,%3u]," 537 " freezeLock=%p, queued-frames=%d\n", 538 mFormat, w0, h0, s0,f0, 539 getFreezeLock().get(), mQueuedFrames); 540 541 result.append(buffer); 542 543 if (mSurfaceTexture != 0) { 544 mSurfaceTexture->dump(result, " ", buffer, SIZE); 545 } 546} 547 548uint32_t Layer::getEffectiveUsage(uint32_t usage) const 549{ 550 // TODO: should we do something special if mSecure is set? 551 if (mProtectedByApp) { 552 // need a hardware-protected path to external video sink 553 usage |= GraphicBuffer::USAGE_PROTECTED; 554 } 555 return usage; 556} 557 558// --------------------------------------------------------------------------- 559 560 561}; // namespace android 562