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 #ifndef ANDROID_LAYER_H 18 #define ANDROID_LAYER_H 19 20 #include <sys/types.h> 21 22 #include <compositionengine/LayerFE.h> 23 #include <gui/BufferQueue.h> 24 #include <gui/ISurfaceComposerClient.h> 25 #include <gui/LayerState.h> 26 #include <input/InputWindow.h> 27 #include <layerproto/LayerProtoHeader.h> 28 #include <math/vec4.h> 29 #include <renderengine/Mesh.h> 30 #include <renderengine/Texture.h> 31 #include <ui/FloatRect.h> 32 #include <ui/FrameStats.h> 33 #include <ui/GraphicBuffer.h> 34 #include <ui/PixelFormat.h> 35 #include <ui/Region.h> 36 #include <ui/Transform.h> 37 #include <utils/RefBase.h> 38 #include <utils/String8.h> 39 #include <utils/Timers.h> 40 41 #include <cstdint> 42 #include <list> 43 #include <optional> 44 #include <vector> 45 46 #include "Client.h" 47 #include "FrameTracker.h" 48 #include "LayerVector.h" 49 #include "MonitoredProducer.h" 50 #include "SurfaceFlinger.h" 51 #include "TransactionCompletedThread.h" 52 53 #include "DisplayHardware/ComposerHal.h" 54 #include "DisplayHardware/HWComposer.h" 55 #include "RenderArea.h" 56 57 using namespace android::surfaceflinger; 58 59 namespace android { 60 61 // --------------------------------------------------------------------------- 62 63 class Client; 64 class Colorizer; 65 class DisplayDevice; 66 class GraphicBuffer; 67 class SurfaceFlinger; 68 class LayerDebugInfo; 69 70 namespace compositionengine { 71 class Layer; 72 class OutputLayer; 73 struct LayerFECompositionState; 74 } 75 76 namespace impl { 77 class SurfaceInterceptor; 78 } 79 80 // --------------------------------------------------------------------------- 81 82 struct LayerCreationArgs { LayerCreationArgsLayerCreationArgs83 LayerCreationArgs(SurfaceFlinger* flinger, const sp<Client>& client, const String8& name, 84 uint32_t w, uint32_t h, uint32_t flags, LayerMetadata metadata) 85 : flinger(flinger), client(client), name(name), w(w), h(h), flags(flags), 86 metadata(std::move(metadata)) {} 87 88 SurfaceFlinger* flinger; 89 const sp<Client>& client; 90 const String8& name; 91 uint32_t w; 92 uint32_t h; 93 uint32_t flags; 94 LayerMetadata metadata; 95 }; 96 97 class Layer : public virtual compositionengine::LayerFE { 98 static std::atomic<int32_t> sSequence; 99 100 public: 101 mutable bool contentDirty{false}; 102 // regions below are in window-manager space 103 Region visibleRegion; 104 Region coveredRegion; 105 Region visibleNonTransparentRegion; 106 Region surfaceDamageRegion; 107 108 // Layer serial number. This gives layers an explicit ordering, so we 109 // have a stable sort order when their layer stack and Z-order are 110 // the same. 111 int32_t sequence{sSequence++}; 112 113 enum { // flags for doTransaction() 114 eDontUpdateGeometryState = 0x00000001, 115 eVisibleRegion = 0x00000002, 116 eInputInfoChanged = 0x00000004 117 }; 118 119 struct Geometry { 120 uint32_t w; 121 uint32_t h; 122 ui::Transform transform; 123 124 inline bool operator==(const Geometry& rhs) const { 125 return (w == rhs.w && h == rhs.h) && (transform.tx() == rhs.transform.tx()) && 126 (transform.ty() == rhs.transform.ty()); 127 } 128 inline bool operator!=(const Geometry& rhs) const { return !operator==(rhs); } 129 }; 130 131 struct RoundedCornerState { 132 RoundedCornerState() = default; RoundedCornerStateRoundedCornerState133 RoundedCornerState(FloatRect cropRect, float radius) 134 : cropRect(cropRect), radius(radius) {} 135 136 // Rounded rectangle in local layer coordinate space. 137 FloatRect cropRect = FloatRect(); 138 // Radius of the rounded rectangle. 139 float radius = 0.0f; 140 }; 141 142 struct State { 143 Geometry active_legacy; 144 Geometry requested_legacy; 145 int32_t z; 146 147 // The identifier of the layer stack this layer belongs to. A layer can 148 // only be associated to a single layer stack. A layer stack is a 149 // z-ordered group of layers which can be associated to one or more 150 // displays. Using the same layer stack on different displays is a way 151 // to achieve mirroring. 152 uint32_t layerStack; 153 154 uint8_t flags; 155 uint8_t reserved[2]; 156 int32_t sequence; // changes when visible regions can change 157 bool modified; 158 159 // Crop is expressed in layer space coordinate. 160 Rect crop_legacy; 161 Rect requestedCrop_legacy; 162 163 // If set, defers this state update until the identified Layer 164 // receives a frame with the given frameNumber 165 wp<Layer> barrierLayer_legacy; 166 uint64_t frameNumber_legacy; 167 168 // the transparentRegion hint is a bit special, it's latched only 169 // when we receive a buffer -- this is because it's "content" 170 // dependent. 171 Region activeTransparentRegion_legacy; 172 Region requestedTransparentRegion_legacy; 173 174 LayerMetadata metadata; 175 176 // If non-null, a Surface this Surface's Z-order is interpreted relative to. 177 wp<Layer> zOrderRelativeOf; 178 179 // A list of surfaces whose Z-order is interpreted relative to ours. 180 SortedVector<wp<Layer>> zOrderRelatives; 181 182 half4 color; 183 float cornerRadius; 184 185 bool inputInfoChanged; 186 InputWindowInfo inputInfo; 187 wp<Layer> touchableRegionCrop; 188 189 // dataspace is only used by BufferStateLayer and ColorLayer 190 ui::Dataspace dataspace; 191 192 // The fields below this point are only used by BufferStateLayer 193 Geometry active; 194 195 uint32_t transform; 196 bool transformToDisplayInverse; 197 198 Rect crop; 199 Region transparentRegionHint; 200 201 sp<GraphicBuffer> buffer; 202 client_cache_t clientCacheId; 203 sp<Fence> acquireFence; 204 HdrMetadata hdrMetadata; 205 Region surfaceDamageRegion; 206 int32_t api; 207 208 sp<NativeHandle> sidebandStream; 209 mat4 colorTransform; 210 bool hasColorTransform; 211 212 // pointer to background color layer that, if set, appears below the buffer state layer 213 // and the buffer state layer's children. Z order will be set to 214 // INT_MIN 215 sp<Layer> bgColorLayer; 216 217 // The deque of callback handles for this frame. The back of the deque contains the most 218 // recent callback handle. 219 std::deque<sp<CallbackHandle>> callbackHandles; 220 bool colorSpaceAgnostic; 221 }; 222 223 explicit Layer(const LayerCreationArgs& args); 224 virtual ~Layer(); 225 setPrimaryDisplayOnly()226 void setPrimaryDisplayOnly() { mPrimaryDisplayOnly = true; } getPrimaryDisplayOnly()227 bool getPrimaryDisplayOnly() const { return mPrimaryDisplayOnly; } 228 229 // ------------------------------------------------------------------------ 230 // Geometry setting functions. 231 // 232 // The following group of functions are used to specify the layers 233 // bounds, and the mapping of the texture on to those bounds. According 234 // to various settings changes to them may apply immediately, or be delayed until 235 // a pending resize is completed by the producer submitting a buffer. For example 236 // if we were to change the buffer size, and update the matrix ahead of the 237 // new buffer arriving, then we would be stretching the buffer to a different 238 // aspect before and after the buffer arriving, which probably isn't what we wanted. 239 // 240 // The first set of geometry functions are controlled by the scaling mode, described 241 // in window.h. The scaling mode may be set by the client, as it submits buffers. 242 // This value may be overriden through SurfaceControl, with setOverrideScalingMode. 243 // 244 // Put simply, if our scaling mode is SCALING_MODE_FREEZE, then 245 // matrix updates will not be applied while a resize is pending 246 // and the size and transform will remain in their previous state 247 // until a new buffer is submitted. If the scaling mode is another value 248 // then the old-buffer will immediately be scaled to the pending size 249 // and the new matrix will be immediately applied following this scaling 250 // transformation. 251 252 // Set the default buffer size for the assosciated Producer, in pixels. This is 253 // also the rendered size of the layer prior to any transformations. Parent 254 // or local matrix transformations will not affect the size of the buffer, 255 // but may affect it's on-screen size or clipping. 256 virtual bool setSize(uint32_t w, uint32_t h); 257 // Set a 2x2 transformation matrix on the layer. This transform 258 // will be applied after parent transforms, but before any final 259 // producer specified transform. 260 virtual bool setMatrix(const layer_state_t::matrix22_t& matrix, 261 bool allowNonRectPreservingTransforms); 262 263 // This second set of geometry attributes are controlled by 264 // setGeometryAppliesWithResize, and their default mode is to be 265 // immediate. If setGeometryAppliesWithResize is specified 266 // while a resize is pending, then update of these attributes will 267 // be delayed until the resize completes. 268 269 // setPosition operates in parent buffer space (pre parent-transform) or display 270 // space for top-level layers. 271 virtual bool setPosition(float x, float y, bool immediate); 272 // Buffer space 273 virtual bool setCrop_legacy(const Rect& crop, bool immediate); 274 275 // TODO(b/38182121): Could we eliminate the various latching modes by 276 // using the layer hierarchy? 277 // ----------------------------------------------------------------------- 278 virtual bool setLayer(int32_t z); 279 virtual bool setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ); 280 281 virtual bool setAlpha(float alpha); setColor(const half3 &)282 virtual bool setColor(const half3& /*color*/) { return false; }; 283 284 // Set rounded corner radius for this layer and its children. 285 // 286 // We only support 1 radius per layer in the hierarchy, where parent layers have precedence. 287 // The shape of the rounded corner rectangle is specified by the crop rectangle of the layer 288 // from which we inferred the rounded corner radius. 289 virtual bool setCornerRadius(float cornerRadius); 290 virtual bool setTransparentRegionHint(const Region& transparent); 291 virtual bool setFlags(uint8_t flags, uint8_t mask); 292 virtual bool setLayerStack(uint32_t layerStack); 293 virtual uint32_t getLayerStack() const; 294 virtual void deferTransactionUntil_legacy(const sp<IBinder>& barrierHandle, 295 uint64_t frameNumber); 296 virtual void deferTransactionUntil_legacy(const sp<Layer>& barrierLayer, uint64_t frameNumber); 297 virtual bool setOverrideScalingMode(int32_t overrideScalingMode); 298 virtual bool setMetadata(const LayerMetadata& data); 299 virtual bool reparentChildren(const sp<IBinder>& layer); 300 virtual void setChildrenDrawingParent(const sp<Layer>& layer); 301 virtual bool reparent(const sp<IBinder>& newParentHandle); 302 virtual bool detachChildren(); 303 bool attachChildren(); isLayerDetached()304 bool isLayerDetached() const { return mLayerDetached; } 305 virtual bool setColorTransform(const mat4& matrix); 306 virtual mat4 getColorTransform() const; 307 virtual bool hasColorTransform() const; isColorSpaceAgnostic()308 virtual bool isColorSpaceAgnostic() const { return mDrawingState.colorSpaceAgnostic; } 309 310 // Used only to set BufferStateLayer state setTransform(uint32_t)311 virtual bool setTransform(uint32_t /*transform*/) { return false; }; setTransformToDisplayInverse(bool)312 virtual bool setTransformToDisplayInverse(bool /*transformToDisplayInverse*/) { return false; }; setCrop(const Rect &)313 virtual bool setCrop(const Rect& /*crop*/) { return false; }; setFrame(const Rect &)314 virtual bool setFrame(const Rect& /*frame*/) { return false; }; setBuffer(const sp<GraphicBuffer> &,nsecs_t,nsecs_t,const client_cache_t &)315 virtual bool setBuffer(const sp<GraphicBuffer>& /*buffer*/, nsecs_t /*postTime*/, 316 nsecs_t /*desiredPresentTime*/, 317 const client_cache_t& /*clientCacheId*/) { 318 return false; 319 }; setAcquireFence(const sp<Fence> &)320 virtual bool setAcquireFence(const sp<Fence>& /*fence*/) { return false; }; setDataspace(ui::Dataspace)321 virtual bool setDataspace(ui::Dataspace /*dataspace*/) { return false; }; setHdrMetadata(const HdrMetadata &)322 virtual bool setHdrMetadata(const HdrMetadata& /*hdrMetadata*/) { return false; }; setSurfaceDamageRegion(const Region &)323 virtual bool setSurfaceDamageRegion(const Region& /*surfaceDamage*/) { return false; }; setApi(int32_t)324 virtual bool setApi(int32_t /*api*/) { return false; }; setSidebandStream(const sp<NativeHandle> &)325 virtual bool setSidebandStream(const sp<NativeHandle>& /*sidebandStream*/) { return false; }; setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>> &)326 virtual bool setTransactionCompletedListeners( 327 const std::vector<sp<CallbackHandle>>& /*handles*/) { 328 return false; 329 }; 330 virtual bool setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace); 331 virtual bool setColorSpaceAgnostic(const bool agnostic); 332 getDataSpace()333 ui::Dataspace getDataSpace() const { return mCurrentDataSpace; } 334 335 // Before color management is introduced, contents on Android have to be 336 // desaturated in order to match what they appears like visually. 337 // With color management, these contents will appear desaturated, thus 338 // needed to be saturated so that they match what they are designed for 339 // visually. 340 bool isLegacyDataSpace() const; 341 342 virtual std::shared_ptr<compositionengine::Layer> getCompositionLayer() const; 343 344 // If we have received a new buffer this frame, we will pass its surface 345 // damage down to hardware composer. Otherwise, we must send a region with 346 // one empty rect. useSurfaceDamage()347 virtual void useSurfaceDamage() {} useEmptyDamage()348 virtual void useEmptyDamage() {} 349 getTransactionFlags()350 uint32_t getTransactionFlags() const { return mTransactionFlags; } 351 uint32_t getTransactionFlags(uint32_t flags); 352 uint32_t setTransactionFlags(uint32_t flags); 353 354 // Deprecated, please use compositionengine::Output::belongsInOutput() 355 // instead. 356 // TODO(lpique): Move the remaining callers (screencap) to the new function. belongsToDisplay(uint32_t layerStack,bool isPrimaryDisplay)357 bool belongsToDisplay(uint32_t layerStack, bool isPrimaryDisplay) const { 358 return getLayerStack() == layerStack && (!mPrimaryDisplayOnly || isPrimaryDisplay); 359 } 360 361 void computeGeometry(const RenderArea& renderArea, renderengine::Mesh& mesh, 362 bool useIdentityTransform) const; 363 FloatRect getBounds(const Region& activeTransparentRegion) const; 364 FloatRect getBounds() const; 365 366 // Compute bounds for the layer and cache the results. 367 void computeBounds(FloatRect parentBounds, ui::Transform parentTransform); 368 369 // Returns the buffer scale transform if a scaling mode is set. 370 ui::Transform getBufferScaleTransform() const; 371 372 // Get effective layer transform, taking into account all its parent transform with any 373 // scaling if the parent scaling more is not NATIVE_WINDOW_SCALING_MODE_FREEZE. 374 ui::Transform getTransformWithScale(const ui::Transform& bufferScaleTransform) const; 375 376 // Returns the bounds of the layer without any buffer scaling. 377 FloatRect getBoundsPreScaling(const ui::Transform& bufferScaleTransform) const; 378 getSequence()379 int32_t getSequence() const { return sequence; } 380 381 // ----------------------------------------------------------------------- 382 // Virtuals 383 virtual const char* getTypeId() const = 0; 384 385 /* 386 * isOpaque - true if this surface is opaque 387 * 388 * This takes into account the buffer format (i.e. whether or not the 389 * pixel format includes an alpha channel) and the "opaque" flag set 390 * on the layer. It does not examine the current plane alpha value. 391 */ isOpaque(const Layer::State &)392 virtual bool isOpaque(const Layer::State&) const { return false; } 393 394 /* 395 * isSecure - true if this surface is secure, that is if it prevents 396 * screenshots or VNC servers. 397 */ 398 bool isSecure() const; 399 400 /* 401 * isVisible - true if this layer is visible, false otherwise 402 */ 403 virtual bool isVisible() const = 0; 404 405 /* 406 * isHiddenByPolicy - true if this layer has been forced invisible. 407 * just because this is false, doesn't mean isVisible() is true. 408 * For example if this layer has no active buffer, it may not be hidden by 409 * policy, but it still can not be visible. 410 */ 411 bool isHiddenByPolicy() const; 412 413 /* 414 * Returns whether this layer can receive input. 415 */ 416 virtual bool canReceiveInput() const; 417 418 /* 419 * isProtected - true if the layer may contain protected content in the 420 * GRALLOC_USAGE_PROTECTED sense. 421 */ isProtected()422 virtual bool isProtected() const { return false; } 423 424 /* 425 * isFixedSize - true if content has a fixed size 426 */ isFixedSize()427 virtual bool isFixedSize() const { return true; } 428 429 /* 430 * usesSourceCrop - true if content should use a source crop 431 */ usesSourceCrop()432 virtual bool usesSourceCrop() const { return false; } 433 434 // Most layers aren't created from the main thread, and therefore need to 435 // grab the SF state lock to access HWC, but ContainerLayer does, so we need 436 // to avoid grabbing the lock again to avoid deadlock isCreatedFromMainThread()437 virtual bool isCreatedFromMainThread() const { return false; } 438 439 bool isRemovedFromCurrentState() const; 440 441 void writeToProto(LayerProto* layerInfo, LayerVector::StateSet stateSet, 442 uint32_t traceFlags = SurfaceTracing::TRACE_ALL); 443 444 void writeToProto(LayerProto* layerInfo, const sp<DisplayDevice>& displayDevice, 445 uint32_t traceFlags = SurfaceTracing::TRACE_ALL); 446 getActiveGeometry(const Layer::State & s)447 virtual Geometry getActiveGeometry(const Layer::State& s) const { return s.active_legacy; } getActiveWidth(const Layer::State & s)448 virtual uint32_t getActiveWidth(const Layer::State& s) const { return s.active_legacy.w; } getActiveHeight(const Layer::State & s)449 virtual uint32_t getActiveHeight(const Layer::State& s) const { return s.active_legacy.h; } getActiveTransform(const Layer::State & s)450 virtual ui::Transform getActiveTransform(const Layer::State& s) const { 451 return s.active_legacy.transform; 452 } getActiveTransparentRegion(const Layer::State & s)453 virtual Region getActiveTransparentRegion(const Layer::State& s) const { 454 return s.activeTransparentRegion_legacy; 455 } getCrop(const Layer::State & s)456 virtual Rect getCrop(const Layer::State& s) const { return s.crop_legacy; } 457 458 protected: 459 virtual bool prepareClientLayer(const RenderArea& renderArea, const Region& clip, 460 bool useIdentityTransform, Region& clearRegion, 461 const bool supportProtectedContent, 462 renderengine::LayerSettings& layer); 463 464 public: 465 /* 466 * compositionengine::LayerFE overrides 467 */ 468 void latchCompositionState(compositionengine::LayerFECompositionState&, 469 bool includeGeometry) const override; 470 void onLayerDisplayed(const sp<Fence>& releaseFence) override; 471 const char* getDebugName() const override; 472 473 protected: 474 void latchGeometry(compositionengine::LayerFECompositionState& outState) const; 475 476 public: setDefaultBufferSize(uint32_t,uint32_t)477 virtual void setDefaultBufferSize(uint32_t /*w*/, uint32_t /*h*/) {} 478 isHdrY410()479 virtual bool isHdrY410() const { return false; } 480 481 void forceClientComposition(const sp<DisplayDevice>& display); 482 bool getForceClientComposition(const sp<DisplayDevice>& display); 483 virtual void setPerFrameData(const sp<const DisplayDevice>& display, 484 const ui::Transform& transform, const Rect& viewport, 485 int32_t supportedPerFrameMetadata, 486 const ui::Dataspace targetDataspace) = 0; 487 488 // callIntoHwc exists so we can update our local state and call 489 // acceptDisplayChanges without unnecessarily updating the device's state 490 void setCompositionType(const sp<const DisplayDevice>& display, 491 Hwc2::IComposerClient::Composition type); 492 Hwc2::IComposerClient::Composition getCompositionType( 493 const sp<const DisplayDevice>& display) const; 494 bool getClearClientTarget(const sp<const DisplayDevice>& display) const; 495 void updateCursorPosition(const sp<const DisplayDevice>& display); 496 shouldPresentNow(nsecs_t)497 virtual bool shouldPresentNow(nsecs_t /*expectedPresentTime*/) const { return false; } setTransformHint(uint32_t)498 virtual void setTransformHint(uint32_t /*orientation*/) const { } 499 500 /* 501 * called before composition. 502 * returns true if the layer has pending updates. 503 */ 504 virtual bool onPreComposition(nsecs_t refreshStartTime) = 0; 505 506 /* 507 * called after composition. 508 * returns true if the layer latched a new buffer this frame. 509 */ onPostComposition(const std::optional<DisplayId> &,const std::shared_ptr<FenceTime> &,const std::shared_ptr<FenceTime> &,const CompositorTiming &)510 virtual bool onPostComposition(const std::optional<DisplayId>& /*displayId*/, 511 const std::shared_ptr<FenceTime>& /*glDoneFence*/, 512 const std::shared_ptr<FenceTime>& /*presentFence*/, 513 const CompositorTiming& /*compositorTiming*/) { 514 return false; 515 } 516 517 // If a buffer was replaced this frame, release the former buffer releasePendingBuffer(nsecs_t)518 virtual void releasePendingBuffer(nsecs_t /*dequeueReadyTime*/) { } 519 520 /* 521 * prepareClientLayer - populates a renderengine::LayerSettings to passed to 522 * RenderEngine::drawLayers. Returns true if the layer can be used, and 523 * false otherwise. 524 */ 525 bool prepareClientLayer(const RenderArea& renderArea, const Region& clip, Region& clearRegion, 526 const bool supportProtectedContent, renderengine::LayerSettings& layer); 527 bool prepareClientLayer(const RenderArea& renderArea, bool useIdentityTransform, 528 Region& clearRegion, const bool supportProtectedContent, 529 renderengine::LayerSettings& layer); 530 531 /* 532 * doTransaction - process the transaction. This is a good place to figure 533 * out which attributes of the surface have changed. 534 */ 535 uint32_t doTransaction(uint32_t transactionFlags); 536 537 /* 538 * setVisibleRegion - called to set the new visible region. This gives 539 * a chance to update the new visible region or record the fact it changed. 540 */ 541 void setVisibleRegion(const Region& visibleRegion); 542 543 /* 544 * setCoveredRegion - called when the covered region changes. The covered 545 * region corresponds to any area of the surface that is covered 546 * (transparently or not) by another surface. 547 */ 548 void setCoveredRegion(const Region& coveredRegion); 549 550 /* 551 * setVisibleNonTransparentRegion - called when the visible and 552 * non-transparent region changes. 553 */ 554 void setVisibleNonTransparentRegion(const Region& visibleNonTransparentRegion); 555 556 /* 557 * Clear the visible, covered, and non-transparent regions. 558 */ 559 void clearVisibilityRegions(); 560 561 /* 562 * latchBuffer - called each time the screen is redrawn and returns whether 563 * the visible regions need to be recomputed (this is a fairly heavy 564 * operation, so this should be set only if needed). Typically this is used 565 * to figure out if the content or size of a surface has changed. 566 */ latchBuffer(bool &,nsecs_t)567 virtual bool latchBuffer(bool& /*recomputeVisibleRegions*/, nsecs_t /*latchTime*/) { 568 return {}; 569 } 570 isBufferLatched()571 virtual bool isBufferLatched() const { return false; } 572 573 /* 574 * Remove relative z for the layer if its relative parent is not part of the 575 * provided layer tree. 576 */ 577 void removeRelativeZ(const std::vector<Layer*>& layersInTree); 578 579 /* 580 * Remove from current state and mark for removal. 581 */ 582 void removeFromCurrentState(); 583 584 /* 585 * called with the state lock from a binder thread when the layer is 586 * removed from the current list to the pending removal list 587 */ 588 void onRemovedFromCurrentState(); 589 590 /* 591 * Called when the layer is added back to the current state list. 592 */ 593 void addToCurrentState(); 594 595 // Updates the transform hint in our SurfaceFlingerConsumer to match 596 // the current orientation of the display device. 597 void updateTransformHint(const sp<const DisplayDevice>& display) const; 598 599 /* 600 * returns the rectangle that crops the content of the layer and scales it 601 * to the layer's size. 602 */ 603 Rect getContentCrop() const; 604 605 /* 606 * Returns if a frame is ready 607 */ hasReadyFrame()608 virtual bool hasReadyFrame() const { return false; } 609 getQueuedFrameCount()610 virtual int32_t getQueuedFrameCount() const { return 0; } 611 612 // ----------------------------------------------------------------------- 613 614 bool hasHwcLayer(const sp<const DisplayDevice>& displayDevice); 615 HWC2::Layer* getHwcLayer(const sp<const DisplayDevice>& displayDevice); 616 getDrawingState()617 inline const State& getDrawingState() const { return mDrawingState; } getCurrentState()618 inline const State& getCurrentState() const { return mCurrentState; } getCurrentState()619 inline State& getCurrentState() { return mCurrentState; } 620 621 LayerDebugInfo getLayerDebugInfo() const; 622 623 /* always call base class first */ 624 static void miniDumpHeader(std::string& result); 625 void miniDump(std::string& result, const sp<DisplayDevice>& display) const; 626 void dumpFrameStats(std::string& result) const; 627 void dumpFrameEvents(std::string& result); 628 void clearFrameStats(); 629 void logFrameStats(); 630 void getFrameStats(FrameStats* outStats) const; 631 getOccupancyHistory(bool)632 virtual std::vector<OccupancyTracker::Segment> getOccupancyHistory(bool /*forceFlush*/) { 633 return {}; 634 } 635 636 void onDisconnect(); 637 void addAndGetFrameTimestamps(const NewFrameEventsEntry* newEntry, 638 FrameEventHistoryDelta* outDelta); 639 getTransformToDisplayInverse()640 virtual bool getTransformToDisplayInverse() const { return false; } 641 642 ui::Transform getTransform() const; 643 644 // Returns the Alpha of the Surface, accounting for the Alpha 645 // of parent Surfaces in the hierarchy (alpha's will be multiplied 646 // down the hierarchy). 647 half getAlpha() const; 648 half4 getColor() const; 649 650 // Returns how rounded corners should be drawn for this layer. 651 // This will traverse the hierarchy until it reaches its root, finding topmost rounded 652 // corner definition and converting it into current layer's coordinates. 653 // As of now, only 1 corner radius per display list is supported. Subsequent ones will be 654 // ignored. 655 RoundedCornerState getRoundedCornerState() const; 656 657 void traverseInReverseZOrder(LayerVector::StateSet stateSet, 658 const LayerVector::Visitor& visitor); 659 void traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor); 660 661 /** 662 * Traverse only children in z order, ignoring relative layers that are not children of the 663 * parent. 664 */ 665 void traverseChildrenInZOrder(LayerVector::StateSet stateSet, 666 const LayerVector::Visitor& visitor); 667 668 size_t getChildrenCount() const; 669 void addChild(const sp<Layer>& layer); 670 // Returns index if removed, or negative value otherwise 671 // for symmetry with Vector::remove 672 ssize_t removeChild(const sp<Layer>& layer); getParent()673 sp<Layer> getParent() const { return mCurrentParent.promote(); } hasParent()674 bool hasParent() const { return getParent() != nullptr; } 675 Rect getScreenBounds(bool reduceTransparentRegion = true) const; 676 bool setChildLayer(const sp<Layer>& childLayer, int32_t z); 677 bool setChildRelativeLayer(const sp<Layer>& childLayer, 678 const sp<IBinder>& relativeToHandle, int32_t relativeZ); 679 680 // Copy the current list of children to the drawing state. Called by 681 // SurfaceFlinger to complete a transaction. 682 void commitChildList(); 683 int32_t getZ() const; 684 virtual void pushPendingState(); 685 686 /** 687 * Returns active buffer size in the correct orientation. Buffer size is determined by undoing 688 * any buffer transformations. If the layer has no buffer then return INVALID_RECT. 689 */ getBufferSize(const Layer::State &)690 virtual Rect getBufferSize(const Layer::State&) const { return Rect::INVALID_RECT; } 691 692 /** 693 * Returns the source bounds. If the bounds are not defined, it is inferred from the 694 * buffer size. Failing that, the bounds are determined from the passed in parent bounds. 695 * For the root layer, this is the display viewport size. 696 */ computeSourceBounds(const FloatRect & parentBounds)697 virtual FloatRect computeSourceBounds(const FloatRect& parentBounds) const { 698 return parentBounds; 699 } 700 701 compositionengine::OutputLayer* findOutputLayerForDisplay( 702 const sp<const DisplayDevice>& display) const; 703 704 protected: 705 // constant 706 sp<SurfaceFlinger> mFlinger; 707 /* 708 * Trivial class, used to ensure that mFlinger->onLayerDestroyed(mLayer) 709 * is called. 710 */ 711 class LayerCleaner { 712 sp<SurfaceFlinger> mFlinger; 713 sp<Layer> mLayer; 714 715 protected: ~LayerCleaner()716 ~LayerCleaner() { 717 // destroy client resources 718 mFlinger->onHandleDestroyed(mLayer); 719 } 720 721 public: LayerCleaner(const sp<SurfaceFlinger> & flinger,const sp<Layer> & layer)722 LayerCleaner(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer) 723 : mFlinger(flinger), mLayer(layer) {} 724 }; 725 726 friend class impl::SurfaceInterceptor; 727 728 // For unit tests 729 friend class TestableSurfaceFlinger; 730 731 virtual void commitTransaction(const State& stateToCommit); 732 733 uint32_t getEffectiveUsage(uint32_t usage) const; 734 735 /** 736 * Setup rounded corners coordinates of this layer, taking into account the layer bounds and 737 * crop coordinates, transforming them into layer space. 738 */ 739 void setupRoundedCornersCropCoordinates(Rect win, const FloatRect& roundedCornersCrop) const; 740 void setParent(const sp<Layer>& layer); 741 LayerVector makeTraversalList(LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers); 742 void addZOrderRelative(const wp<Layer>& relative); 743 void removeZOrderRelative(const wp<Layer>& relative); 744 745 class SyncPoint { 746 public: SyncPoint(uint64_t frameNumber,wp<Layer> requestedSyncLayer)747 explicit SyncPoint(uint64_t frameNumber, wp<Layer> requestedSyncLayer) 748 : mFrameNumber(frameNumber), 749 mFrameIsAvailable(false), 750 mTransactionIsApplied(false), 751 mRequestedSyncLayer(requestedSyncLayer) {} 752 getFrameNumber()753 uint64_t getFrameNumber() const { return mFrameNumber; } 754 frameIsAvailable()755 bool frameIsAvailable() const { return mFrameIsAvailable; } 756 setFrameAvailable()757 void setFrameAvailable() { mFrameIsAvailable = true; } 758 transactionIsApplied()759 bool transactionIsApplied() const { return mTransactionIsApplied; } 760 setTransactionApplied()761 void setTransactionApplied() { mTransactionIsApplied = true; } 762 getRequestedSyncLayer()763 sp<Layer> getRequestedSyncLayer() { return mRequestedSyncLayer.promote(); } 764 765 private: 766 const uint64_t mFrameNumber; 767 std::atomic<bool> mFrameIsAvailable; 768 std::atomic<bool> mTransactionIsApplied; 769 wp<Layer> mRequestedSyncLayer; 770 }; 771 772 // SyncPoints which will be signaled when the correct frame is at the head 773 // of the queue and dropped after the frame has been latched. Protected by 774 // mLocalSyncPointMutex. 775 Mutex mLocalSyncPointMutex; 776 std::list<std::shared_ptr<SyncPoint>> mLocalSyncPoints; 777 778 // SyncPoints which will be signaled and then dropped when the transaction 779 // is applied 780 std::list<std::shared_ptr<SyncPoint>> mRemoteSyncPoints; 781 782 // Returns false if the relevant frame has already been latched 783 bool addSyncPoint(const std::shared_ptr<SyncPoint>& point); 784 785 void popPendingState(State* stateToCommit); 786 virtual bool applyPendingStates(State* stateToCommit); 787 virtual uint32_t doTransactionResize(uint32_t flags, Layer::State* stateToCommit); 788 789 // Returns mCurrentScaling mode (originating from the 790 // Client) or mOverrideScalingMode mode (originating from 791 // the Surface Controller) if set. getEffectiveScalingMode()792 virtual uint32_t getEffectiveScalingMode() const { return 0; } 793 794 public: 795 /* 796 * The layer handle is just a BBinder object passed to the client 797 * (remote process) -- we don't keep any reference on our side such that 798 * the dtor is called when the remote side let go of its reference. 799 * 800 * LayerCleaner ensures that mFlinger->onLayerDestroyed() is called for 801 * this layer when the handle is destroyed. 802 */ 803 class Handle : public BBinder, public LayerCleaner { 804 public: Handle(const sp<SurfaceFlinger> & flinger,const sp<Layer> & layer)805 Handle(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer) 806 : LayerCleaner(flinger, layer), owner(layer) {} 807 808 wp<Layer> owner; 809 }; 810 811 // Creates a new handle each time, so we only expect 812 // this to be called once. 813 sp<IBinder> getHandle(); 814 const String8& getName() const; notifyAvailableFrames()815 virtual void notifyAvailableFrames() {} getPixelFormat()816 virtual PixelFormat getPixelFormat() const { return PIXEL_FORMAT_NONE; } 817 bool getPremultipledAlpha() const; 818 819 bool mPendingHWCDestroy{false}; 820 void setInputInfo(const InputWindowInfo& info); 821 822 InputWindowInfo fillInputInfo(); 823 bool hasInput() const; 824 825 protected: 826 // ----------------------------------------------------------------------- 827 bool usingRelativeZ(LayerVector::StateSet stateSet) const; 828 829 bool mPremultipliedAlpha{true}; 830 String8 mName; 831 String8 mTransactionName; // A cached version of "TX - " + mName for systraces 832 833 bool mPrimaryDisplayOnly = false; 834 835 // these are protected by an external lock 836 State mCurrentState; 837 State mDrawingState; 838 std::atomic<uint32_t> mTransactionFlags{0}; 839 840 // Accessed from main thread and binder threads 841 Mutex mPendingStateMutex; 842 Vector<State> mPendingStates; 843 844 // Timestamp history for UIAutomation. Thread safe. 845 FrameTracker mFrameTracker; 846 847 // Timestamp history for the consumer to query. 848 // Accessed by both consumer and producer on main and binder threads. 849 Mutex mFrameEventHistoryMutex; 850 ConsumerFrameEventHistory mFrameEventHistory; 851 FenceTimeline mAcquireTimeline; 852 FenceTimeline mReleaseTimeline; 853 854 // main thread 855 sp<NativeHandle> mSidebandStream; 856 // Active buffer fields 857 sp<GraphicBuffer> mActiveBuffer; 858 sp<Fence> mActiveBufferFence; 859 // False if the buffer and its contents have been previously used for GPU 860 // composition, true otherwise. 861 bool mIsActiveBufferUpdatedForGpu = true; 862 863 ui::Dataspace mCurrentDataSpace = ui::Dataspace::UNKNOWN; 864 Rect mCurrentCrop; 865 uint32_t mCurrentTransform{0}; 866 // We encode unset as -1. 867 int32_t mOverrideScalingMode{-1}; 868 std::atomic<uint64_t> mCurrentFrameNumber{0}; 869 bool mFrameLatencyNeeded{false}; 870 // Whether filtering is needed b/c of the drawingstate 871 bool mNeedsFiltering{false}; 872 873 std::atomic<bool> mRemovedFromCurrentState{false}; 874 875 // page-flip thread (currently main thread) 876 bool mProtectedByApp{false}; // application requires protected path to external sink 877 878 // protected by mLock 879 mutable Mutex mLock; 880 881 const wp<Client> mClientRef; 882 883 // This layer can be a cursor on some displays. 884 bool mPotentialCursor{false}; 885 886 bool mFreezeGeometryUpdates{false}; 887 888 // Child list about to be committed/used for editing. 889 LayerVector mCurrentChildren{LayerVector::StateSet::Current}; 890 // Child list used for rendering. 891 LayerVector mDrawingChildren{LayerVector::StateSet::Drawing}; 892 893 wp<Layer> mCurrentParent; 894 wp<Layer> mDrawingParent; 895 896 // Can only be accessed with the SF state lock held. 897 bool mLayerDetached{false}; 898 // Can only be accessed with the SF state lock held. 899 bool mChildrenChanged{false}; 900 901 // Window types from WindowManager.LayoutParams 902 const int mWindowType; 903 904 // This is populated if the layer is registered with Scheduler for tracking purposes. 905 std::unique_ptr<scheduler::LayerHistory::LayerHandle> mSchedulerLayerHandle; 906 907 private: 908 /** 909 * Returns an unsorted vector of all layers that are part of this tree. 910 * That includes the current layer and all its descendants. 911 */ 912 std::vector<Layer*> getLayersInTree(LayerVector::StateSet stateSet); 913 /** 914 * Traverses layers that are part of this tree in the correct z order. 915 * layersInTree must be sorted before calling this method. 916 */ 917 void traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree, 918 LayerVector::StateSet stateSet, 919 const LayerVector::Visitor& visitor); 920 LayerVector makeChildrenTraversalList(LayerVector::StateSet stateSet, 921 const std::vector<Layer*>& layersInTree); 922 /** 923 * Returns the cropped buffer size or the layer crop if the layer has no buffer. Return 924 * INVALID_RECT if the layer has no buffer and no crop. 925 * A layer with an invalid buffer size and no crop is considered to be boundless. The layer 926 * bounds are constrained by its parent bounds. 927 */ 928 Rect getCroppedBufferSize(const Layer::State& s) const; 929 930 // Cached properties computed from drawing state 931 // Effective transform taking into account parent transforms and any parent scaling. 932 ui::Transform mEffectiveTransform; 933 934 // Bounds of the layer before any transformation is applied and before it has been cropped 935 // by its parents. 936 FloatRect mSourceBounds; 937 938 // Bounds of the layer in layer space. This is the mSourceBounds cropped by its layer crop and 939 // its parent bounds. 940 FloatRect mBounds; 941 942 // Layer bounds in screen space. 943 FloatRect mScreenBounds; 944 945 void setZOrderRelativeOf(const wp<Layer>& relativeOf); 946 947 bool mGetHandleCalled = false; 948 949 void removeRemoteSyncPoints(); 950 }; 951 952 } // namespace android 953 954 #define RETURN_IF_NO_HWC_LAYER(displayDevice, ...) \ 955 do { \ 956 if (!hasHwcLayer(displayDevice)) { \ 957 ALOGE("[%s] %s failed: no HWC layer found for display %s", mName.string(), \ 958 __FUNCTION__, displayDevice->getDebugName().c_str()); \ 959 return __VA_ARGS__; \ 960 } \ 961 } while (false) 962 963 #endif // ANDROID_LAYER_H 964