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