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 LOG_NDEBUG 0
18 #undef LOG_TAG
19 #define LOG_TAG "Layer"
20 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
22 #include <stdlib.h>
23 #include <stdint.h>
24 #include <sys/types.h>
25 #include <math.h>
26
27 #include <cutils/compiler.h>
28 #include <cutils/native_handle.h>
29 #include <cutils/properties.h>
30
31 #include <utils/Errors.h>
32 #include <utils/Log.h>
33 #include <utils/NativeHandle.h>
34 #include <utils/StopWatch.h>
35 #include <utils/Trace.h>
36
37 #include <ui/GraphicBuffer.h>
38 #include <ui/PixelFormat.h>
39
40 #include <gui/BufferItem.h>
41 #include <gui/BufferQueue.h>
42 #include <gui/Surface.h>
43
44 #include "clz.h"
45 #include "Colorizer.h"
46 #include "DisplayDevice.h"
47 #include "Layer.h"
48 #include "LayerRejecter.h"
49 #include "MonitoredProducer.h"
50 #include "SurfaceFlinger.h"
51
52 #include "DisplayHardware/HWComposer.h"
53
54 #include "RenderEngine/RenderEngine.h"
55
56 #include <mutex>
57
58 #define DEBUG_RESIZE 0
59
60 namespace android {
61
62 // ---------------------------------------------------------------------------
63
64 int32_t Layer::sSequence = 1;
65
Layer(SurfaceFlinger * flinger,const sp<Client> & client,const String8 & name,uint32_t w,uint32_t h,uint32_t flags)66 Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
67 const String8& name, uint32_t w, uint32_t h, uint32_t flags)
68 : contentDirty(false),
69 sequence(uint32_t(android_atomic_inc(&sSequence))),
70 mFlinger(flinger),
71 mTextureName(-1U),
72 mPremultipliedAlpha(true),
73 mName("unnamed"),
74 mFormat(PIXEL_FORMAT_NONE),
75 mTransactionFlags(0),
76 mPendingStateMutex(),
77 mPendingStates(),
78 mQueuedFrames(0),
79 mSidebandStreamChanged(false),
80 mActiveBufferSlot(BufferQueue::INVALID_BUFFER_SLOT),
81 mCurrentTransform(0),
82 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
83 mOverrideScalingMode(-1),
84 mCurrentOpacity(true),
85 mBufferLatched(false),
86 mCurrentFrameNumber(0),
87 mPreviousFrameNumber(0),
88 mRefreshPending(false),
89 mFrameLatencyNeeded(false),
90 mFiltering(false),
91 mNeedsFiltering(false),
92 mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
93 #ifndef USE_HWC2
94 mIsGlesComposition(false),
95 #endif
96 mProtectedByApp(false),
97 mHasSurface(false),
98 mClientRef(client),
99 mPotentialCursor(false),
100 mQueueItemLock(),
101 mQueueItemCondition(),
102 mQueueItems(),
103 mLastFrameNumberReceived(0),
104 mUpdateTexImageFailed(false),
105 mAutoRefresh(false),
106 mFreezeGeometryUpdates(false)
107 {
108 #ifdef USE_HWC2
109 ALOGV("Creating Layer %s", name.string());
110 #endif
111
112 mCurrentCrop.makeInvalid();
113 mFlinger->getRenderEngine().genTextures(1, &mTextureName);
114 mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
115
116 uint32_t layerFlags = 0;
117 if (flags & ISurfaceComposerClient::eHidden)
118 layerFlags |= layer_state_t::eLayerHidden;
119 if (flags & ISurfaceComposerClient::eOpaque)
120 layerFlags |= layer_state_t::eLayerOpaque;
121 if (flags & ISurfaceComposerClient::eSecure)
122 layerFlags |= layer_state_t::eLayerSecure;
123
124 if (flags & ISurfaceComposerClient::eNonPremultiplied)
125 mPremultipliedAlpha = false;
126
127 mName = name;
128
129 mCurrentState.active.w = w;
130 mCurrentState.active.h = h;
131 mCurrentState.active.transform.set(0, 0);
132 mCurrentState.crop.makeInvalid();
133 mCurrentState.finalCrop.makeInvalid();
134 mCurrentState.requestedFinalCrop = mCurrentState.finalCrop;
135 mCurrentState.requestedCrop = mCurrentState.crop;
136 mCurrentState.z = 0;
137 #ifdef USE_HWC2
138 mCurrentState.alpha = 1.0f;
139 #else
140 mCurrentState.alpha = 0xFF;
141 #endif
142 mCurrentState.layerStack = 0;
143 mCurrentState.flags = layerFlags;
144 mCurrentState.sequence = 0;
145 mCurrentState.requested = mCurrentState.active;
146 mCurrentState.dataSpace = HAL_DATASPACE_UNKNOWN;
147 mCurrentState.appId = 0;
148 mCurrentState.type = 0;
149
150 // drawing state & current state are identical
151 mDrawingState = mCurrentState;
152
153 #ifdef USE_HWC2
154 const auto& hwc = flinger->getHwComposer();
155 const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
156 nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
157 #else
158 nsecs_t displayPeriod =
159 flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
160 #endif
161 mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
162
163 CompositorTiming compositorTiming;
164 flinger->getCompositorTiming(&compositorTiming);
165 mFrameEventHistory.initializeCompositorTiming(compositorTiming);
166 }
167
onFirstRef()168 void Layer::onFirstRef() {
169 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
170 sp<IGraphicBufferProducer> producer;
171 sp<IGraphicBufferConsumer> consumer;
172 BufferQueue::createBufferQueue(&producer, &consumer, true);
173 mProducer = new MonitoredProducer(producer, mFlinger, this);
174 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
175 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
176 mSurfaceFlingerConsumer->setContentsChangedListener(this);
177 mSurfaceFlingerConsumer->setName(mName);
178
179 if (mFlinger->isLayerTripleBufferingDisabled()) {
180 mProducer->setMaxDequeuedBufferCount(2);
181 }
182
183 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
184 updateTransformHint(hw);
185 }
186
~Layer()187 Layer::~Layer() {
188 sp<Client> c(mClientRef.promote());
189 if (c != 0) {
190 c->detachLayer(this);
191 }
192
193 for (auto& point : mRemoteSyncPoints) {
194 point->setTransactionApplied();
195 }
196 for (auto& point : mLocalSyncPoints) {
197 point->setFrameAvailable();
198 }
199 mFlinger->deleteTextureAsync(mTextureName);
200 mFrameTracker.logAndResetStats(mName);
201 }
202
203 // ---------------------------------------------------------------------------
204 // callbacks
205 // ---------------------------------------------------------------------------
206
207 #ifdef USE_HWC2
onLayerDisplayed(const sp<Fence> & releaseFence)208 void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
209 if (mHwcLayers.empty()) {
210 return;
211 }
212 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
213 }
214 #else
onLayerDisplayed(const sp<const DisplayDevice> &,HWComposer::HWCLayerInterface * layer)215 void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
216 HWComposer::HWCLayerInterface* layer) {
217 if (layer) {
218 layer->onDisplayed();
219 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
220 }
221 }
222 #endif
223
onFrameAvailable(const BufferItem & item)224 void Layer::onFrameAvailable(const BufferItem& item) {
225 // Add this buffer from our internal queue tracker
226 { // Autolock scope
227 Mutex::Autolock lock(mQueueItemLock);
228 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
229 item.mGraphicBuffer->getHeight(), item.mFrameNumber);
230 // Reset the frame number tracker when we receive the first buffer after
231 // a frame number reset
232 if (item.mFrameNumber == 1) {
233 mLastFrameNumberReceived = 0;
234 }
235
236 // Ensure that callbacks are handled in order
237 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
238 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
239 ms2ns(500));
240 if (result != NO_ERROR) {
241 ALOGE("[%s] Timed out waiting on callback", mName.string());
242 }
243 }
244
245 mQueueItems.push_back(item);
246 android_atomic_inc(&mQueuedFrames);
247
248 // Wake up any pending callbacks
249 mLastFrameNumberReceived = item.mFrameNumber;
250 mQueueItemCondition.broadcast();
251 }
252
253 mFlinger->signalLayerUpdate();
254 }
255
onFrameReplaced(const BufferItem & item)256 void Layer::onFrameReplaced(const BufferItem& item) {
257 { // Autolock scope
258 Mutex::Autolock lock(mQueueItemLock);
259
260 // Ensure that callbacks are handled in order
261 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
262 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
263 ms2ns(500));
264 if (result != NO_ERROR) {
265 ALOGE("[%s] Timed out waiting on callback", mName.string());
266 }
267 }
268
269 if (mQueueItems.empty()) {
270 ALOGE("Can't replace a frame on an empty queue");
271 return;
272 }
273 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
274
275 // Wake up any pending callbacks
276 mLastFrameNumberReceived = item.mFrameNumber;
277 mQueueItemCondition.broadcast();
278 }
279 }
280
onSidebandStreamChanged()281 void Layer::onSidebandStreamChanged() {
282 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
283 // mSidebandStreamChanged was false
284 mFlinger->signalLayerUpdate();
285 }
286 }
287
288 // called with SurfaceFlinger::mStateLock from the drawing thread after
289 // the layer has been remove from the current state list (and just before
290 // it's removed from the drawing state list)
onRemoved()291 void Layer::onRemoved() {
292 if (mCurrentState.zOrderRelativeOf != nullptr) {
293 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
294 if (strongRelative != nullptr) {
295 strongRelative->removeZOrderRelative(this);
296 }
297 mCurrentState.zOrderRelativeOf = nullptr;
298 }
299
300 mSurfaceFlingerConsumer->abandon();
301
302 #ifdef USE_HWC2
303 clearHwcLayers();
304 #endif
305
306 for (const auto& child : mCurrentChildren) {
307 child->onRemoved();
308 }
309 }
310
311 // ---------------------------------------------------------------------------
312 // set-up
313 // ---------------------------------------------------------------------------
314
getName() const315 const String8& Layer::getName() const {
316 return mName;
317 }
318
setBuffers(uint32_t w,uint32_t h,PixelFormat format,uint32_t flags)319 status_t Layer::setBuffers( uint32_t w, uint32_t h,
320 PixelFormat format, uint32_t flags)
321 {
322 uint32_t const maxSurfaceDims = min(
323 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
324
325 // never allow a surface larger than what our underlying GL implementation
326 // can handle.
327 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
328 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
329 return BAD_VALUE;
330 }
331
332 mFormat = format;
333
334 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
335 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
336 mCurrentOpacity = getOpacityForFormat(format);
337
338 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
339 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
340 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
341
342 return NO_ERROR;
343 }
344
getHandle()345 sp<IBinder> Layer::getHandle() {
346 Mutex::Autolock _l(mLock);
347
348 LOG_ALWAYS_FATAL_IF(mHasSurface,
349 "Layer::getHandle() has already been called");
350
351 mHasSurface = true;
352
353 return new Handle(mFlinger, this);
354 }
355
getProducer() const356 sp<IGraphicBufferProducer> Layer::getProducer() const {
357 return mProducer;
358 }
359
360 // ---------------------------------------------------------------------------
361 // h/w composer set-up
362 // ---------------------------------------------------------------------------
363
getContentCrop() const364 Rect Layer::getContentCrop() const {
365 // this is the crop rectangle that applies to the buffer
366 // itself (as opposed to the window)
367 Rect crop;
368 if (!mCurrentCrop.isEmpty()) {
369 // if the buffer crop is defined, we use that
370 crop = mCurrentCrop;
371 } else if (mActiveBuffer != NULL) {
372 // otherwise we use the whole buffer
373 crop = mActiveBuffer->getBounds();
374 } else {
375 // if we don't have a buffer yet, we use an empty/invalid crop
376 crop.makeInvalid();
377 }
378 return crop;
379 }
380
reduce(const Rect & win,const Region & exclude)381 static Rect reduce(const Rect& win, const Region& exclude) {
382 if (CC_LIKELY(exclude.isEmpty())) {
383 return win;
384 }
385 if (exclude.isRect()) {
386 return win.reduce(exclude.getBounds());
387 }
388 return Region(win).subtract(exclude).getBounds();
389 }
390
computeScreenBounds(bool reduceTransparentRegion) const391 Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
392 const Layer::State& s(getDrawingState());
393 Rect win(s.active.w, s.active.h);
394
395 if (!s.crop.isEmpty()) {
396 win.intersect(s.crop, &win);
397 }
398
399 Transform t = getTransform();
400 win = t.transform(win);
401
402 if (!s.finalCrop.isEmpty()) {
403 win.intersect(s.finalCrop, &win);
404 }
405
406 const sp<Layer>& p = mDrawingParent.promote();
407 // Now we need to calculate the parent bounds, so we can clip ourselves to those.
408 // When calculating the parent bounds for purposes of clipping,
409 // we don't need to constrain the parent to its transparent region.
410 // The transparent region is an optimization based on the
411 // buffer contents of the layer, but does not affect the space allocated to
412 // it by policy, and thus children should be allowed to extend into the
413 // parent's transparent region. In fact one of the main uses, is to reduce
414 // buffer allocation size in cases where a child window sits behind a main window
415 // (by marking the hole in the parent window as a transparent region)
416 if (p != nullptr) {
417 Rect bounds = p->computeScreenBounds(false);
418 bounds.intersect(win, &win);
419 }
420
421 if (reduceTransparentRegion) {
422 auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
423 win = reduce(win, screenTransparentRegion);
424 }
425
426 return win;
427 }
428
computeBounds() const429 Rect Layer::computeBounds() const {
430 const Layer::State& s(getDrawingState());
431 return computeBounds(s.activeTransparentRegion);
432 }
433
computeBounds(const Region & activeTransparentRegion) const434 Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
435 const Layer::State& s(getDrawingState());
436 Rect win(s.active.w, s.active.h);
437
438 if (!s.crop.isEmpty()) {
439 win.intersect(s.crop, &win);
440 }
441
442 Rect bounds = win;
443 const auto& p = mDrawingParent.promote();
444 if (p != nullptr) {
445 // Look in computeScreenBounds recursive call for explanation of
446 // why we pass false here.
447 bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
448 }
449
450 Transform t = getTransform();
451 if (p != nullptr) {
452 win = t.transform(win);
453 win.intersect(bounds, &win);
454 win = t.inverse().transform(win);
455 }
456
457 // subtract the transparent region and snap to the bounds
458 return reduce(win, activeTransparentRegion);
459 }
460
computeInitialCrop(const sp<const DisplayDevice> & hw) const461 Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
462 // the crop is the area of the window that gets cropped, but not
463 // scaled in any ways.
464 const State& s(getDrawingState());
465
466 // apply the projection's clipping to the window crop in
467 // layerstack space, and convert-back to layer space.
468 // if there are no window scaling involved, this operation will map to full
469 // pixels in the buffer.
470 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
471 // a viewport clipping and a window transform. we should use floating point to fix this.
472
473 Rect activeCrop(s.active.w, s.active.h);
474 if (!s.crop.isEmpty()) {
475 activeCrop = s.crop;
476 }
477
478 Transform t = getTransform();
479 activeCrop = t.transform(activeCrop);
480 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
481 activeCrop.clear();
482 }
483 if (!s.finalCrop.isEmpty()) {
484 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
485 activeCrop.clear();
486 }
487 }
488 return activeCrop;
489 }
490
computeCrop(const sp<const DisplayDevice> & hw) const491 FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
492 // the content crop is the area of the content that gets scaled to the
493 // layer's size. This is in buffer space.
494 FloatRect crop = getContentCrop().toFloatRect();
495
496 // In addition there is a WM-specified crop we pull from our drawing state.
497 const State& s(getDrawingState());
498
499 // Screen space to make reduction to parent crop clearer.
500 Rect activeCrop = computeInitialCrop(hw);
501 const auto& p = mDrawingParent.promote();
502 if (p != nullptr) {
503 auto parentCrop = p->computeInitialCrop(hw);
504 activeCrop.intersect(parentCrop, &activeCrop);
505 }
506 Transform t = getTransform();
507 // Back to layer space to work with the content crop.
508 activeCrop = t.inverse().transform(activeCrop);
509
510 // This needs to be here as transform.transform(Rect) computes the
511 // transformed rect and then takes the bounding box of the result before
512 // returning. This means
513 // transform.inverse().transform(transform.transform(Rect)) != Rect
514 // in which case we need to make sure the final rect is clipped to the
515 // display bounds.
516 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
517 activeCrop.clear();
518 }
519
520 // subtract the transparent region and snap to the bounds
521 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
522
523 // Transform the window crop to match the buffer coordinate system,
524 // which means using the inverse of the current transform set on the
525 // SurfaceFlingerConsumer.
526 uint32_t invTransform = mCurrentTransform;
527 if (getTransformToDisplayInverse()) {
528 /*
529 * the code below applies the primary display's inverse transform to the
530 * buffer
531 */
532 uint32_t invTransformOrient =
533 DisplayDevice::getPrimaryDisplayOrientationTransform();
534 // calculate the inverse transform
535 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
536 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
537 NATIVE_WINDOW_TRANSFORM_FLIP_H;
538 }
539 // and apply to the current transform
540 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
541 .getOrientation();
542 }
543
544 int winWidth = s.active.w;
545 int winHeight = s.active.h;
546 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
547 // If the activeCrop has been rotate the ends are rotated but not
548 // the space itself so when transforming ends back we can't rely on
549 // a modification of the axes of rotation. To account for this we
550 // need to reorient the inverse rotation in terms of the current
551 // axes of rotation.
552 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
553 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
554 if (is_h_flipped == is_v_flipped) {
555 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
556 NATIVE_WINDOW_TRANSFORM_FLIP_H;
557 }
558 winWidth = s.active.h;
559 winHeight = s.active.w;
560 }
561 const Rect winCrop = activeCrop.transform(
562 invTransform, s.active.w, s.active.h);
563
564 // below, crop is intersected with winCrop expressed in crop's coordinate space
565 float xScale = crop.getWidth() / float(winWidth);
566 float yScale = crop.getHeight() / float(winHeight);
567
568 float insetL = winCrop.left * xScale;
569 float insetT = winCrop.top * yScale;
570 float insetR = (winWidth - winCrop.right ) * xScale;
571 float insetB = (winHeight - winCrop.bottom) * yScale;
572
573 crop.left += insetL;
574 crop.top += insetT;
575 crop.right -= insetR;
576 crop.bottom -= insetB;
577
578 return crop;
579 }
580
581 #ifdef USE_HWC2
setGeometry(const sp<const DisplayDevice> & displayDevice,uint32_t z)582 void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
583 #else
584 void Layer::setGeometry(
585 const sp<const DisplayDevice>& hw,
586 HWComposer::HWCLayerInterface& layer)
587 #endif
588 {
589 #ifdef USE_HWC2
590 const auto hwcId = displayDevice->getHwcDisplayId();
591 auto& hwcInfo = mHwcLayers[hwcId];
592 #else
593 layer.setDefaultState();
594 #endif
595
596 // enable this layer
597 #ifdef USE_HWC2
598 hwcInfo.forceClientComposition = false;
599
600 if (isSecure() && !displayDevice->isSecure()) {
601 hwcInfo.forceClientComposition = true;
602 }
603
604 auto& hwcLayer = hwcInfo.layer;
605 #else
606 layer.setSkip(false);
607
608 if (isSecure() && !hw->isSecure()) {
609 layer.setSkip(true);
610 }
611 #endif
612
613 // this gives us only the "orientation" component of the transform
614 const State& s(getDrawingState());
615 #ifdef USE_HWC2
616 auto blendMode = HWC2::BlendMode::None;
617 if (!isOpaque(s) || getAlpha() != 1.0f) {
618 blendMode = mPremultipliedAlpha ?
619 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
620 }
621 auto error = hwcLayer->setBlendMode(blendMode);
622 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
623 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
624 to_string(error).c_str(), static_cast<int32_t>(error));
625 #else
626 if (!isOpaque(s) || getAlpha() != 0xFF) {
627 layer.setBlending(mPremultipliedAlpha ?
628 HWC_BLENDING_PREMULT :
629 HWC_BLENDING_COVERAGE);
630 }
631 #endif
632
633 // apply the layer's transform, followed by the display's global transform
634 // here we're guaranteed that the layer's transform preserves rects
635 Region activeTransparentRegion(s.activeTransparentRegion);
636 Transform t = getTransform();
637 if (!s.crop.isEmpty()) {
638 Rect activeCrop(s.crop);
639 activeCrop = t.transform(activeCrop);
640 #ifdef USE_HWC2
641 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
642 #else
643 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
644 #endif
645 activeCrop.clear();
646 }
647 activeCrop = t.inverse().transform(activeCrop, true);
648 // This needs to be here as transform.transform(Rect) computes the
649 // transformed rect and then takes the bounding box of the result before
650 // returning. This means
651 // transform.inverse().transform(transform.transform(Rect)) != Rect
652 // in which case we need to make sure the final rect is clipped to the
653 // display bounds.
654 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
655 activeCrop.clear();
656 }
657 // mark regions outside the crop as transparent
658 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
659 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
660 s.active.w, s.active.h));
661 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
662 activeCrop.left, activeCrop.bottom));
663 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
664 s.active.w, activeCrop.bottom));
665 }
666
667 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
668 if (!s.finalCrop.isEmpty()) {
669 if(!frame.intersect(s.finalCrop, &frame)) {
670 frame.clear();
671 }
672 }
673 #ifdef USE_HWC2
674 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
675 frame.clear();
676 }
677 const Transform& tr(displayDevice->getTransform());
678 Rect transformedFrame = tr.transform(frame);
679 error = hwcLayer->setDisplayFrame(transformedFrame);
680 if (error != HWC2::Error::None) {
681 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
682 mName.string(), transformedFrame.left, transformedFrame.top,
683 transformedFrame.right, transformedFrame.bottom,
684 to_string(error).c_str(), static_cast<int32_t>(error));
685 } else {
686 hwcInfo.displayFrame = transformedFrame;
687 }
688
689 FloatRect sourceCrop = computeCrop(displayDevice);
690 error = hwcLayer->setSourceCrop(sourceCrop);
691 if (error != HWC2::Error::None) {
692 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
693 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
694 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
695 static_cast<int32_t>(error));
696 } else {
697 hwcInfo.sourceCrop = sourceCrop;
698 }
699
700 float alpha = getAlpha();
701 error = hwcLayer->setPlaneAlpha(alpha);
702 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
703 "%s (%d)", mName.string(), alpha, to_string(error).c_str(),
704 static_cast<int32_t>(error));
705
706 error = hwcLayer->setZOrder(z);
707 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
708 mName.string(), z, to_string(error).c_str(),
709 static_cast<int32_t>(error));
710
711 int type = s.type;
712 int appId = s.appId;
713 sp<Layer> parent = mDrawingParent.promote();
714 if (parent.get()) {
715 auto& parentState = parent->getDrawingState();
716 type = parentState.type;
717 appId = parentState.appId;
718 }
719
720 error = hwcLayer->setInfo(type, appId);
721 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
722 mName.string(), static_cast<int32_t>(error));
723 #else
724 if (!frame.intersect(hw->getViewport(), &frame)) {
725 frame.clear();
726 }
727 const Transform& tr(hw->getTransform());
728 layer.setFrame(tr.transform(frame));
729 layer.setCrop(computeCrop(hw));
730 layer.setPlaneAlpha(getAlpha());
731 #endif
732
733 /*
734 * Transformations are applied in this order:
735 * 1) buffer orientation/flip/mirror
736 * 2) state transformation (window manager)
737 * 3) layer orientation (screen orientation)
738 * (NOTE: the matrices are multiplied in reverse order)
739 */
740
741 const Transform bufferOrientation(mCurrentTransform);
742 Transform transform(tr * t * bufferOrientation);
743
744 if (getTransformToDisplayInverse()) {
745 /*
746 * the code below applies the primary display's inverse transform to the
747 * buffer
748 */
749 uint32_t invTransform =
750 DisplayDevice::getPrimaryDisplayOrientationTransform();
751 // calculate the inverse transform
752 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
753 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
754 NATIVE_WINDOW_TRANSFORM_FLIP_H;
755 }
756
757 /*
758 * Here we cancel out the orientation component of the WM transform.
759 * The scaling and translate components are already included in our bounds
760 * computation so it's enough to just omit it in the composition.
761 * See comment in onDraw with ref to b/36727915 for why.
762 */
763 transform = Transform(invTransform) * tr * bufferOrientation;
764 }
765
766 // this gives us only the "orientation" component of the transform
767 const uint32_t orientation = transform.getOrientation();
768 #ifdef USE_HWC2
769 if (orientation & Transform::ROT_INVALID) {
770 // we can only handle simple transformation
771 hwcInfo.forceClientComposition = true;
772 } else {
773 auto transform = static_cast<HWC2::Transform>(orientation);
774 auto error = hwcLayer->setTransform(transform);
775 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
776 "%s (%d)", mName.string(), to_string(transform).c_str(),
777 to_string(error).c_str(), static_cast<int32_t>(error));
778 }
779 #else
780 if (orientation & Transform::ROT_INVALID) {
781 // we can only handle simple transformation
782 layer.setSkip(true);
783 } else {
784 layer.setTransform(orientation);
785 }
786 #endif
787 }
788
789 #ifdef USE_HWC2
790 void Layer::forceClientComposition(int32_t hwcId) {
791 if (mHwcLayers.count(hwcId) == 0) {
792 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
793 return;
794 }
795
796 mHwcLayers[hwcId].forceClientComposition = true;
797 }
798
799 void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
800 // Apply this display's projection's viewport to the visible region
801 // before giving it to the HWC HAL.
802 const Transform& tr = displayDevice->getTransform();
803 const auto& viewport = displayDevice->getViewport();
804 Region visible = tr.transform(visibleRegion.intersect(viewport));
805 auto hwcId = displayDevice->getHwcDisplayId();
806 auto& hwcInfo = mHwcLayers[hwcId];
807 auto& hwcLayer = hwcInfo.layer;
808 auto error = hwcLayer->setVisibleRegion(visible);
809 if (error != HWC2::Error::None) {
810 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
811 to_string(error).c_str(), static_cast<int32_t>(error));
812 visible.dump(LOG_TAG);
813 }
814
815 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
816 if (error != HWC2::Error::None) {
817 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
818 to_string(error).c_str(), static_cast<int32_t>(error));
819 surfaceDamageRegion.dump(LOG_TAG);
820 }
821
822 // Sideband layers
823 if (mSidebandStream.get()) {
824 setCompositionType(hwcId, HWC2::Composition::Sideband);
825 ALOGV("[%s] Requesting Sideband composition", mName.string());
826 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
827 if (error != HWC2::Error::None) {
828 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
829 mName.string(), mSidebandStream->handle(),
830 to_string(error).c_str(), static_cast<int32_t>(error));
831 }
832 return;
833 }
834
835 // Client layers
836 if (hwcInfo.forceClientComposition ||
837 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
838 ALOGV("[%s] Requesting Client composition", mName.string());
839 setCompositionType(hwcId, HWC2::Composition::Client);
840 return;
841 }
842
843 // SolidColor layers
844 if (mActiveBuffer == nullptr) {
845 setCompositionType(hwcId, HWC2::Composition::SolidColor);
846
847 // For now, we only support black for DimLayer
848 error = hwcLayer->setColor({0, 0, 0, 255});
849 if (error != HWC2::Error::None) {
850 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
851 to_string(error).c_str(), static_cast<int32_t>(error));
852 }
853
854 // Clear out the transform, because it doesn't make sense absent a
855 // source buffer
856 error = hwcLayer->setTransform(HWC2::Transform::None);
857 if (error != HWC2::Error::None) {
858 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
859 to_string(error).c_str(), static_cast<int32_t>(error));
860 }
861
862 return;
863 }
864
865 // Device or Cursor layers
866 if (mPotentialCursor) {
867 ALOGV("[%s] Requesting Cursor composition", mName.string());
868 setCompositionType(hwcId, HWC2::Composition::Cursor);
869 } else {
870 ALOGV("[%s] Requesting Device composition", mName.string());
871 setCompositionType(hwcId, HWC2::Composition::Device);
872 }
873
874 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
875 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
876 if (error != HWC2::Error::None) {
877 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
878 mCurrentState.dataSpace, to_string(error).c_str(),
879 static_cast<int32_t>(error));
880 }
881
882 uint32_t hwcSlot = 0;
883 sp<GraphicBuffer> hwcBuffer;
884 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
885 &hwcSlot, &hwcBuffer);
886
887 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
888 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
889 if (error != HWC2::Error::None) {
890 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
891 mActiveBuffer->handle, to_string(error).c_str(),
892 static_cast<int32_t>(error));
893 }
894 }
895
896 android_dataspace Layer::getDataSpace() const {
897 return mCurrentState.dataSpace;
898 }
899 #else
900 void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
901 HWComposer::HWCLayerInterface& layer) {
902 // we have to set the visible region on every frame because
903 // we currently free it during onLayerDisplayed(), which is called
904 // after HWComposer::commit() -- every frame.
905 // Apply this display's projection's viewport to the visible region
906 // before giving it to the HWC HAL.
907 const Transform& tr = hw->getTransform();
908 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
909 layer.setVisibleRegionScreen(visible);
910 layer.setSurfaceDamage(surfaceDamageRegion);
911 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
912
913 if (mSidebandStream.get()) {
914 layer.setSidebandStream(mSidebandStream);
915 } else {
916 // NOTE: buffer can be NULL if the client never drew into this
917 // layer yet, or if we ran out of memory
918 layer.setBuffer(mActiveBuffer);
919 }
920 }
921 #endif
922
923 #ifdef USE_HWC2
924 void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
925 auto hwcId = displayDevice->getHwcDisplayId();
926 if (mHwcLayers.count(hwcId) == 0 ||
927 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
928 return;
929 }
930
931 // This gives us only the "orientation" component of the transform
932 const State& s(getCurrentState());
933
934 // Apply the layer's transform, followed by the display's global transform
935 // Here we're guaranteed that the layer's transform preserves rects
936 Rect win(s.active.w, s.active.h);
937 if (!s.crop.isEmpty()) {
938 win.intersect(s.crop, &win);
939 }
940 // Subtract the transparent region and snap to the bounds
941 Rect bounds = reduce(win, s.activeTransparentRegion);
942 Rect frame(getTransform().transform(bounds));
943 frame.intersect(displayDevice->getViewport(), &frame);
944 if (!s.finalCrop.isEmpty()) {
945 frame.intersect(s.finalCrop, &frame);
946 }
947 auto& displayTransform(displayDevice->getTransform());
948 auto position = displayTransform.transform(frame);
949
950 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
951 position.top);
952 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
953 "to (%d, %d): %s (%d)", mName.string(), position.left,
954 position.top, to_string(error).c_str(),
955 static_cast<int32_t>(error));
956 }
957 #else
958 void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
959 HWComposer::HWCLayerInterface& layer) {
960 int fenceFd = -1;
961
962 // TODO: there is a possible optimization here: we only need to set the
963 // acquire fence the first time a new buffer is acquired on EACH display.
964
965 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
966 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
967 if (fence->isValid()) {
968 fenceFd = fence->dup();
969 if (fenceFd == -1) {
970 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
971 }
972 }
973 }
974 layer.setAcquireFenceFd(fenceFd);
975 }
976
977 Rect Layer::getPosition(
978 const sp<const DisplayDevice>& hw)
979 {
980 // this gives us only the "orientation" component of the transform
981 const State& s(getCurrentState());
982
983 // apply the layer's transform, followed by the display's global transform
984 // here we're guaranteed that the layer's transform preserves rects
985 Rect win(s.active.w, s.active.h);
986 if (!s.crop.isEmpty()) {
987 win.intersect(s.crop, &win);
988 }
989 // subtract the transparent region and snap to the bounds
990 Rect bounds = reduce(win, s.activeTransparentRegion);
991 Rect frame(getTransform().transform(bounds));
992 frame.intersect(hw->getViewport(), &frame);
993 if (!s.finalCrop.isEmpty()) {
994 frame.intersect(s.finalCrop, &frame);
995 }
996 const Transform& tr(hw->getTransform());
997 return Rect(tr.transform(frame));
998 }
999 #endif
1000
1001 // ---------------------------------------------------------------------------
1002 // drawing...
1003 // ---------------------------------------------------------------------------
1004
1005 void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
1006 onDraw(hw, clip, false);
1007 }
1008
1009 void Layer::draw(const sp<const DisplayDevice>& hw,
1010 bool useIdentityTransform) const {
1011 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
1012 }
1013
1014 void Layer::draw(const sp<const DisplayDevice>& hw) const {
1015 onDraw(hw, Region(hw->bounds()), false);
1016 }
1017
1018 static constexpr mat4 inverseOrientation(uint32_t transform) {
1019 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1020 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1021 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1022 mat4 tr;
1023
1024 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1025 tr = tr * rot90;
1026 }
1027 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1028 tr = tr * flipH;
1029 }
1030 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1031 tr = tr * flipV;
1032 }
1033 return inverse(tr);
1034 }
1035
1036 /*
1037 * onDraw will draw the current layer onto the presentable buffer
1038 */
1039 void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
1040 bool useIdentityTransform) const
1041 {
1042 ATRACE_CALL();
1043
1044 if (CC_UNLIKELY(mActiveBuffer == 0)) {
1045 // the texture has not been created yet, this Layer has
1046 // in fact never been drawn into. This happens frequently with
1047 // SurfaceView because the WindowManager can't know when the client
1048 // has drawn the first time.
1049
1050 // If there is nothing under us, we paint the screen in black, otherwise
1051 // we just skip this update.
1052
1053 // figure out if there is something below us
1054 Region under;
1055 bool finished = false;
1056 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
1057 if (finished || layer == static_cast<Layer const*>(this)) {
1058 finished = true;
1059 return;
1060 }
1061 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
1062 });
1063 // if not everything below us is covered, we plug the holes!
1064 Region holes(clip.subtract(under));
1065 if (!holes.isEmpty()) {
1066 clearWithOpenGL(hw, 0, 0, 0, 1);
1067 }
1068 return;
1069 }
1070
1071 // Bind the current buffer to the GL texture, and wait for it to be
1072 // ready for us to draw into.
1073 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1074 if (err != NO_ERROR) {
1075 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
1076 // Go ahead and draw the buffer anyway; no matter what we do the screen
1077 // is probably going to have something visibly wrong.
1078 }
1079
1080 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1081
1082 RenderEngine& engine(mFlinger->getRenderEngine());
1083
1084 if (!blackOutLayer) {
1085 // TODO: we could be more subtle with isFixedSize()
1086 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
1087
1088 // Query the texture matrix given our current filtering mode.
1089 float textureMatrix[16];
1090 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1091 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
1092
1093 if (getTransformToDisplayInverse()) {
1094
1095 /*
1096 * the code below applies the primary display's inverse transform to
1097 * the texture transform
1098 */
1099 uint32_t transform =
1100 DisplayDevice::getPrimaryDisplayOrientationTransform();
1101 mat4 tr = inverseOrientation(transform);
1102
1103 /**
1104 * TODO(b/36727915): This is basically a hack.
1105 *
1106 * Ensure that regardless of the parent transformation,
1107 * this buffer is always transformed from native display
1108 * orientation to display orientation. For example, in the case
1109 * of a camera where the buffer remains in native orientation,
1110 * we want the pixels to always be upright.
1111 */
1112 sp<Layer> p = mDrawingParent.promote();
1113 if (p != nullptr) {
1114 const auto parentTransform = p->getTransform();
1115 tr = tr * inverseOrientation(parentTransform.getOrientation());
1116 }
1117
1118 // and finally apply it to the original texture matrix
1119 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1120 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1121 }
1122
1123 // Set things up for texturing.
1124 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1125 mTexture.setFiltering(useFiltering);
1126 mTexture.setMatrix(textureMatrix);
1127
1128 engine.setupLayerTexturing(mTexture);
1129 } else {
1130 engine.setupLayerBlackedOut();
1131 }
1132 drawWithOpenGL(hw, useIdentityTransform);
1133 engine.disableTexturing();
1134 }
1135
1136
1137 void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
1138 float red, float green, float blue,
1139 float alpha) const
1140 {
1141 RenderEngine& engine(mFlinger->getRenderEngine());
1142 computeGeometry(hw, mMesh, false);
1143 engine.setupFillWithColor(red, green, blue, alpha);
1144 engine.drawMesh(mMesh);
1145 }
1146
1147 void Layer::clearWithOpenGL(
1148 const sp<const DisplayDevice>& hw) const {
1149 clearWithOpenGL(hw, 0,0,0,0);
1150 }
1151
1152 void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
1153 bool useIdentityTransform) const {
1154 const State& s(getDrawingState());
1155
1156 computeGeometry(hw, mMesh, useIdentityTransform);
1157
1158 /*
1159 * NOTE: the way we compute the texture coordinates here produces
1160 * different results than when we take the HWC path -- in the later case
1161 * the "source crop" is rounded to texel boundaries.
1162 * This can produce significantly different results when the texture
1163 * is scaled by a large amount.
1164 *
1165 * The GL code below is more logical (imho), and the difference with
1166 * HWC is due to a limitation of the HWC API to integers -- a question
1167 * is suspend is whether we should ignore this problem or revert to
1168 * GL composition when a buffer scaling is applied (maybe with some
1169 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1170 * like more of a hack.
1171 */
1172 Rect win(computeBounds());
1173
1174 Transform t = getTransform();
1175 if (!s.finalCrop.isEmpty()) {
1176 win = t.transform(win);
1177 if (!win.intersect(s.finalCrop, &win)) {
1178 win.clear();
1179 }
1180 win = t.inverse().transform(win);
1181 if (!win.intersect(computeBounds(), &win)) {
1182 win.clear();
1183 }
1184 }
1185
1186 float left = float(win.left) / float(s.active.w);
1187 float top = float(win.top) / float(s.active.h);
1188 float right = float(win.right) / float(s.active.w);
1189 float bottom = float(win.bottom) / float(s.active.h);
1190
1191 // TODO: we probably want to generate the texture coords with the mesh
1192 // here we assume that we only have 4 vertices
1193 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1194 texCoords[0] = vec2(left, 1.0f - top);
1195 texCoords[1] = vec2(left, 1.0f - bottom);
1196 texCoords[2] = vec2(right, 1.0f - bottom);
1197 texCoords[3] = vec2(right, 1.0f - top);
1198
1199 RenderEngine& engine(mFlinger->getRenderEngine());
1200 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), getAlpha());
1201 #ifdef USE_HWC2
1202 engine.setSourceDataSpace(mCurrentState.dataSpace);
1203 #endif
1204 engine.drawMesh(mMesh);
1205 engine.disableBlending();
1206 }
1207
1208 #ifdef USE_HWC2
1209 void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1210 bool callIntoHwc) {
1211 if (mHwcLayers.count(hwcId) == 0) {
1212 ALOGE("setCompositionType called without a valid HWC layer");
1213 return;
1214 }
1215 auto& hwcInfo = mHwcLayers[hwcId];
1216 auto& hwcLayer = hwcInfo.layer;
1217 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1218 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1219 if (hwcInfo.compositionType != type) {
1220 ALOGV(" actually setting");
1221 hwcInfo.compositionType = type;
1222 if (callIntoHwc) {
1223 auto error = hwcLayer->setCompositionType(type);
1224 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1225 "composition type %s: %s (%d)", mName.string(),
1226 to_string(type).c_str(), to_string(error).c_str(),
1227 static_cast<int32_t>(error));
1228 }
1229 }
1230 }
1231
1232 HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
1233 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1234 // If we're querying the composition type for a display that does not
1235 // have a HWC counterpart, then it will always be Client
1236 return HWC2::Composition::Client;
1237 }
1238 if (mHwcLayers.count(hwcId) == 0) {
1239 ALOGE("getCompositionType called with an invalid HWC layer");
1240 return HWC2::Composition::Invalid;
1241 }
1242 return mHwcLayers.at(hwcId).compositionType;
1243 }
1244
1245 void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1246 if (mHwcLayers.count(hwcId) == 0) {
1247 ALOGE("setClearClientTarget called without a valid HWC layer");
1248 return;
1249 }
1250 mHwcLayers[hwcId].clearClientTarget = clear;
1251 }
1252
1253 bool Layer::getClearClientTarget(int32_t hwcId) const {
1254 if (mHwcLayers.count(hwcId) == 0) {
1255 ALOGE("getClearClientTarget called without a valid HWC layer");
1256 return false;
1257 }
1258 return mHwcLayers.at(hwcId).clearClientTarget;
1259 }
1260 #endif
1261
1262 uint32_t Layer::getProducerStickyTransform() const {
1263 int producerStickyTransform = 0;
1264 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1265 if (ret != OK) {
1266 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1267 strerror(-ret), ret);
1268 return 0;
1269 }
1270 return static_cast<uint32_t>(producerStickyTransform);
1271 }
1272
1273 bool Layer::latchUnsignaledBuffers() {
1274 static bool propertyLoaded = false;
1275 static bool latch = false;
1276 static std::mutex mutex;
1277 std::lock_guard<std::mutex> lock(mutex);
1278 if (!propertyLoaded) {
1279 char value[PROPERTY_VALUE_MAX] = {};
1280 property_get("debug.sf.latch_unsignaled", value, "0");
1281 latch = atoi(value);
1282 propertyLoaded = true;
1283 }
1284 return latch;
1285 }
1286
1287 uint64_t Layer::getHeadFrameNumber() const {
1288 Mutex::Autolock lock(mQueueItemLock);
1289 if (!mQueueItems.empty()) {
1290 return mQueueItems[0].mFrameNumber;
1291 } else {
1292 return mCurrentFrameNumber;
1293 }
1294 }
1295
1296 bool Layer::headFenceHasSignaled() const {
1297 #ifdef USE_HWC2
1298 if (latchUnsignaledBuffers()) {
1299 return true;
1300 }
1301
1302 Mutex::Autolock lock(mQueueItemLock);
1303 if (mQueueItems.empty()) {
1304 return true;
1305 }
1306 if (mQueueItems[0].mIsDroppable) {
1307 // Even though this buffer's fence may not have signaled yet, it could
1308 // be replaced by another buffer before it has a chance to, which means
1309 // that it's possible to get into a situation where a buffer is never
1310 // able to be latched. To avoid this, grab this buffer anyway.
1311 return true;
1312 }
1313 return mQueueItems[0].mFence->getSignalTime() != INT64_MAX;
1314 #else
1315 return true;
1316 #endif
1317 }
1318
1319 bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1320 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1321 // Don't bother with a SyncPoint, since we've already latched the
1322 // relevant frame
1323 return false;
1324 }
1325
1326 Mutex::Autolock lock(mLocalSyncPointMutex);
1327 mLocalSyncPoints.push_back(point);
1328 return true;
1329 }
1330
1331 void Layer::setFiltering(bool filtering) {
1332 mFiltering = filtering;
1333 }
1334
1335 bool Layer::getFiltering() const {
1336 return mFiltering;
1337 }
1338
1339 // As documented in libhardware header, formats in the range
1340 // 0x100 - 0x1FF are specific to the HAL implementation, and
1341 // are known to have no alpha channel
1342 // TODO: move definition for device-specific range into
1343 // hardware.h, instead of using hard-coded values here.
1344 #define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1345
1346 bool Layer::getOpacityForFormat(uint32_t format) {
1347 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1348 return true;
1349 }
1350 switch (format) {
1351 case HAL_PIXEL_FORMAT_RGBA_8888:
1352 case HAL_PIXEL_FORMAT_BGRA_8888:
1353 case HAL_PIXEL_FORMAT_RGBA_FP16:
1354 case HAL_PIXEL_FORMAT_RGBA_1010102:
1355 return false;
1356 }
1357 // in all other case, we have no blending (also for unknown formats)
1358 return true;
1359 }
1360
1361 // ----------------------------------------------------------------------------
1362 // local state
1363 // ----------------------------------------------------------------------------
1364
1365 static void boundPoint(vec2* point, const Rect& crop) {
1366 if (point->x < crop.left) {
1367 point->x = crop.left;
1368 }
1369 if (point->x > crop.right) {
1370 point->x = crop.right;
1371 }
1372 if (point->y < crop.top) {
1373 point->y = crop.top;
1374 }
1375 if (point->y > crop.bottom) {
1376 point->y = crop.bottom;
1377 }
1378 }
1379
1380 void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1381 bool useIdentityTransform) const
1382 {
1383 const Layer::State& s(getDrawingState());
1384 const Transform hwTransform(hw->getTransform());
1385 const uint32_t hw_h = hw->getHeight();
1386 Rect win = computeBounds();
1387
1388 vec2 lt = vec2(win.left, win.top);
1389 vec2 lb = vec2(win.left, win.bottom);
1390 vec2 rb = vec2(win.right, win.bottom);
1391 vec2 rt = vec2(win.right, win.top);
1392
1393 Transform layerTransform = getTransform();
1394 if (!useIdentityTransform) {
1395 lt = layerTransform.transform(lt);
1396 lb = layerTransform.transform(lb);
1397 rb = layerTransform.transform(rb);
1398 rt = layerTransform.transform(rt);
1399 }
1400
1401 if (!s.finalCrop.isEmpty()) {
1402 boundPoint(<, s.finalCrop);
1403 boundPoint(&lb, s.finalCrop);
1404 boundPoint(&rb, s.finalCrop);
1405 boundPoint(&rt, s.finalCrop);
1406 }
1407
1408 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
1409 position[0] = hwTransform.transform(lt);
1410 position[1] = hwTransform.transform(lb);
1411 position[2] = hwTransform.transform(rb);
1412 position[3] = hwTransform.transform(rt);
1413 for (size_t i=0 ; i<4 ; i++) {
1414 position[i].y = hw_h - position[i].y;
1415 }
1416 }
1417
1418 bool Layer::isOpaque(const Layer::State& s) const
1419 {
1420 // if we don't have a buffer yet, we're translucent regardless of the
1421 // layer's opaque flag.
1422 if (mActiveBuffer == 0) {
1423 return false;
1424 }
1425
1426 // if the layer has the opaque flag, then we're always opaque,
1427 // otherwise we use the current buffer's format.
1428 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
1429 }
1430
1431 bool Layer::isSecure() const
1432 {
1433 const Layer::State& s(mDrawingState);
1434 return (s.flags & layer_state_t::eLayerSecure);
1435 }
1436
1437 bool Layer::isProtected() const
1438 {
1439 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
1440 return (activeBuffer != 0) &&
1441 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1442 }
1443
1444 bool Layer::isFixedSize() const {
1445 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1446 }
1447
1448 bool Layer::isCropped() const {
1449 return !mCurrentCrop.isEmpty();
1450 }
1451
1452 bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1453 return mNeedsFiltering || hw->needsFiltering();
1454 }
1455
1456 void Layer::setVisibleRegion(const Region& visibleRegion) {
1457 // always called from main thread
1458 this->visibleRegion = visibleRegion;
1459 }
1460
1461 void Layer::setCoveredRegion(const Region& coveredRegion) {
1462 // always called from main thread
1463 this->coveredRegion = coveredRegion;
1464 }
1465
1466 void Layer::setVisibleNonTransparentRegion(const Region&
1467 setVisibleNonTransparentRegion) {
1468 // always called from main thread
1469 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1470 }
1471
1472 // ----------------------------------------------------------------------------
1473 // transaction
1474 // ----------------------------------------------------------------------------
1475
1476 void Layer::pushPendingState() {
1477 if (!mCurrentState.modified) {
1478 return;
1479 }
1480
1481 // If this transaction is waiting on the receipt of a frame, generate a sync
1482 // point and send it to the remote layer.
1483 if (mCurrentState.barrierLayer != nullptr) {
1484 sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1485 if (barrierLayer == nullptr) {
1486 ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
1487 // If we can't promote the layer we are intended to wait on,
1488 // then it is expired or otherwise invalid. Allow this transaction
1489 // to be applied as per normal (no synchronization).
1490 mCurrentState.barrierLayer = nullptr;
1491 } else {
1492 auto syncPoint = std::make_shared<SyncPoint>(
1493 mCurrentState.frameNumber);
1494 if (barrierLayer->addSyncPoint(syncPoint)) {
1495 mRemoteSyncPoints.push_back(std::move(syncPoint));
1496 } else {
1497 // We already missed the frame we're supposed to synchronize
1498 // on, so go ahead and apply the state update
1499 mCurrentState.barrierLayer = nullptr;
1500 }
1501 }
1502
1503 // Wake us up to check if the frame has been received
1504 setTransactionFlags(eTransactionNeeded);
1505 mFlinger->setTransactionFlags(eTraversalNeeded);
1506 }
1507 mPendingStates.push_back(mCurrentState);
1508 }
1509
1510 void Layer::popPendingState(State* stateToCommit) {
1511 auto oldFlags = stateToCommit->flags;
1512 *stateToCommit = mPendingStates[0];
1513 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1514 (stateToCommit->flags & stateToCommit->mask);
1515
1516 mPendingStates.removeAt(0);
1517 }
1518
1519 bool Layer::applyPendingStates(State* stateToCommit) {
1520 bool stateUpdateAvailable = false;
1521 while (!mPendingStates.empty()) {
1522 if (mPendingStates[0].barrierLayer != nullptr) {
1523 if (mRemoteSyncPoints.empty()) {
1524 // If we don't have a sync point for this, apply it anyway. It
1525 // will be visually wrong, but it should keep us from getting
1526 // into too much trouble.
1527 ALOGE("[%s] No local sync point found", mName.string());
1528 popPendingState(stateToCommit);
1529 stateUpdateAvailable = true;
1530 continue;
1531 }
1532
1533 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1534 mPendingStates[0].frameNumber) {
1535 ALOGE("[%s] Unexpected sync point frame number found",
1536 mName.string());
1537
1538 // Signal our end of the sync point and then dispose of it
1539 mRemoteSyncPoints.front()->setTransactionApplied();
1540 mRemoteSyncPoints.pop_front();
1541 continue;
1542 }
1543
1544 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1545 // Apply the state update
1546 popPendingState(stateToCommit);
1547 stateUpdateAvailable = true;
1548
1549 // Signal our end of the sync point and then dispose of it
1550 mRemoteSyncPoints.front()->setTransactionApplied();
1551 mRemoteSyncPoints.pop_front();
1552 } else {
1553 break;
1554 }
1555 } else {
1556 popPendingState(stateToCommit);
1557 stateUpdateAvailable = true;
1558 }
1559 }
1560
1561 // If we still have pending updates, wake SurfaceFlinger back up and point
1562 // it at this layer so we can process them
1563 if (!mPendingStates.empty()) {
1564 setTransactionFlags(eTransactionNeeded);
1565 mFlinger->setTransactionFlags(eTraversalNeeded);
1566 }
1567
1568 mCurrentState.modified = false;
1569 return stateUpdateAvailable;
1570 }
1571
1572 void Layer::notifyAvailableFrames() {
1573 auto headFrameNumber = getHeadFrameNumber();
1574 bool headFenceSignaled = headFenceHasSignaled();
1575 Mutex::Autolock lock(mLocalSyncPointMutex);
1576 for (auto& point : mLocalSyncPoints) {
1577 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
1578 point->setFrameAvailable();
1579 }
1580 }
1581 }
1582
1583 uint32_t Layer::doTransaction(uint32_t flags) {
1584 ATRACE_CALL();
1585
1586 pushPendingState();
1587 Layer::State c = getCurrentState();
1588 if (!applyPendingStates(&c)) {
1589 return 0;
1590 }
1591
1592 const Layer::State& s(getDrawingState());
1593
1594 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1595 (c.requested.h != s.requested.h);
1596
1597 if (sizeChanged) {
1598 // the size changed, we need to ask our client to request a new buffer
1599 ALOGD_IF(DEBUG_RESIZE,
1600 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
1601 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1602 " requested={ wh={%4u,%4u} }}\n"
1603 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1604 " requested={ wh={%4u,%4u} }}\n",
1605 this, getName().string(), mCurrentTransform,
1606 getEffectiveScalingMode(),
1607 c.active.w, c.active.h,
1608 c.crop.left,
1609 c.crop.top,
1610 c.crop.right,
1611 c.crop.bottom,
1612 c.crop.getWidth(),
1613 c.crop.getHeight(),
1614 c.requested.w, c.requested.h,
1615 s.active.w, s.active.h,
1616 s.crop.left,
1617 s.crop.top,
1618 s.crop.right,
1619 s.crop.bottom,
1620 s.crop.getWidth(),
1621 s.crop.getHeight(),
1622 s.requested.w, s.requested.h);
1623
1624 // record the new size, form this point on, when the client request
1625 // a buffer, it'll get the new size.
1626 mSurfaceFlingerConsumer->setDefaultBufferSize(
1627 c.requested.w, c.requested.h);
1628 }
1629
1630 const bool resizePending = (c.requested.w != c.active.w) ||
1631 (c.requested.h != c.active.h);
1632 if (!isFixedSize()) {
1633 if (resizePending && mSidebandStream == NULL) {
1634 // don't let Layer::doTransaction update the drawing state
1635 // if we have a pending resize, unless we are in fixed-size mode.
1636 // the drawing state will be updated only once we receive a buffer
1637 // with the correct size.
1638 //
1639 // in particular, we want to make sure the clip (which is part
1640 // of the geometry state) is latched together with the size but is
1641 // latched immediately when no resizing is involved.
1642 //
1643 // If a sideband stream is attached, however, we want to skip this
1644 // optimization so that transactions aren't missed when a buffer
1645 // never arrives
1646
1647 flags |= eDontUpdateGeometryState;
1648 }
1649 }
1650
1651 // Here we apply various requested geometry states, depending on our
1652 // latching configuration. See Layer.h for a detailed discussion of
1653 // how geometry latching is controlled.
1654 if (!(flags & eDontUpdateGeometryState)) {
1655 Layer::State& editCurrentState(getCurrentState());
1656
1657 // If mFreezeGeometryUpdates is true we are in the setGeometryAppliesWithResize
1658 // mode, which causes attributes which normally latch regardless of scaling mode,
1659 // to be delayed. We copy the requested state to the active state making sure
1660 // to respect these rules (again see Layer.h for a detailed discussion).
1661 //
1662 // There is an awkward asymmetry in the handling of the crop states in the position
1663 // states, as can be seen below. Largely this arises from position and transform
1664 // being stored in the same data structure while having different latching rules.
1665 // b/38182305
1666 //
1667 // Careful that "c" and editCurrentState may not begin as equivalent due to
1668 // applyPendingStates in the presence of deferred transactions.
1669 if (mFreezeGeometryUpdates) {
1670 float tx = c.active.transform.tx();
1671 float ty = c.active.transform.ty();
1672 c.active = c.requested;
1673 c.active.transform.set(tx, ty);
1674 editCurrentState.active = c.active;
1675 } else {
1676 editCurrentState.active = editCurrentState.requested;
1677 c.active = c.requested;
1678 }
1679 }
1680
1681 if (s.active != c.active) {
1682 // invalidate and recompute the visible regions if needed
1683 flags |= Layer::eVisibleRegion;
1684 }
1685
1686 if (c.sequence != s.sequence) {
1687 // invalidate and recompute the visible regions if needed
1688 flags |= eVisibleRegion;
1689 this->contentDirty = true;
1690
1691 // we may use linear filtering, if the matrix scales us
1692 const uint8_t type = c.active.transform.getType();
1693 mNeedsFiltering = (!c.active.transform.preserveRects() ||
1694 (type >= Transform::SCALE));
1695 }
1696
1697 // If the layer is hidden, signal and clear out all local sync points so
1698 // that transactions for layers depending on this layer's frames becoming
1699 // visible are not blocked
1700 if (c.flags & layer_state_t::eLayerHidden) {
1701 clearSyncPoints();
1702 }
1703
1704 // Commit the transaction
1705 commitTransaction(c);
1706 return flags;
1707 }
1708
1709 void Layer::commitTransaction(const State& stateToCommit) {
1710 mDrawingState = stateToCommit;
1711 }
1712
1713 uint32_t Layer::getTransactionFlags(uint32_t flags) {
1714 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1715 }
1716
1717 uint32_t Layer::setTransactionFlags(uint32_t flags) {
1718 return android_atomic_or(flags, &mTransactionFlags);
1719 }
1720
1721 bool Layer::setPosition(float x, float y, bool immediate) {
1722 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
1723 return false;
1724 mCurrentState.sequence++;
1725
1726 // We update the requested and active position simultaneously because
1727 // we want to apply the position portion of the transform matrix immediately,
1728 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
1729 mCurrentState.requested.transform.set(x, y);
1730 if (immediate && !mFreezeGeometryUpdates) {
1731 // Here we directly update the active state
1732 // unlike other setters, because we store it within
1733 // the transform, but use different latching rules.
1734 // b/38182305
1735 mCurrentState.active.transform.set(x, y);
1736 }
1737 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1738
1739 mCurrentState.modified = true;
1740 setTransactionFlags(eTransactionNeeded);
1741 return true;
1742 }
1743
1744 bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1745 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1746 if (idx < 0) {
1747 return false;
1748 }
1749 if (childLayer->setLayer(z)) {
1750 mCurrentChildren.removeAt(idx);
1751 mCurrentChildren.add(childLayer);
1752 }
1753 return true;
1754 }
1755
1756 bool Layer::setLayer(int32_t z) {
1757 if (mCurrentState.z == z)
1758 return false;
1759 mCurrentState.sequence++;
1760 mCurrentState.z = z;
1761 mCurrentState.modified = true;
1762
1763 // Discard all relative layering.
1764 if (mCurrentState.zOrderRelativeOf != nullptr) {
1765 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1766 if (strongRelative != nullptr) {
1767 strongRelative->removeZOrderRelative(this);
1768 }
1769 mCurrentState.zOrderRelativeOf = nullptr;
1770 }
1771 setTransactionFlags(eTransactionNeeded);
1772 return true;
1773 }
1774
1775 void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1776 mCurrentState.zOrderRelatives.remove(relative);
1777 mCurrentState.sequence++;
1778 mCurrentState.modified = true;
1779 setTransactionFlags(eTransactionNeeded);
1780 }
1781
1782 void Layer::addZOrderRelative(const wp<Layer>& relative) {
1783 mCurrentState.zOrderRelatives.add(relative);
1784 mCurrentState.modified = true;
1785 mCurrentState.sequence++;
1786 setTransactionFlags(eTransactionNeeded);
1787 }
1788
1789 bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1790 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1791 if (handle == nullptr) {
1792 return false;
1793 }
1794 sp<Layer> relative = handle->owner.promote();
1795 if (relative == nullptr) {
1796 return false;
1797 }
1798
1799 mCurrentState.sequence++;
1800 mCurrentState.modified = true;
1801 mCurrentState.z = z;
1802
1803 mCurrentState.zOrderRelativeOf = relative;
1804 relative->addZOrderRelative(this);
1805
1806 setTransactionFlags(eTransactionNeeded);
1807
1808 return true;
1809 }
1810
1811 bool Layer::setSize(uint32_t w, uint32_t h) {
1812 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1813 return false;
1814 mCurrentState.requested.w = w;
1815 mCurrentState.requested.h = h;
1816 mCurrentState.modified = true;
1817 setTransactionFlags(eTransactionNeeded);
1818 return true;
1819 }
1820 #ifdef USE_HWC2
1821 bool Layer::setAlpha(float alpha) {
1822 #else
1823 bool Layer::setAlpha(uint8_t alpha) {
1824 #endif
1825 if (mCurrentState.alpha == alpha)
1826 return false;
1827 mCurrentState.sequence++;
1828 mCurrentState.alpha = alpha;
1829 mCurrentState.modified = true;
1830 setTransactionFlags(eTransactionNeeded);
1831 return true;
1832 }
1833 bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1834 mCurrentState.sequence++;
1835 mCurrentState.requested.transform.set(
1836 matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
1837 mCurrentState.modified = true;
1838 setTransactionFlags(eTransactionNeeded);
1839 return true;
1840 }
1841 bool Layer::setTransparentRegionHint(const Region& transparent) {
1842 mCurrentState.requestedTransparentRegion = transparent;
1843 mCurrentState.modified = true;
1844 setTransactionFlags(eTransactionNeeded);
1845 return true;
1846 }
1847 bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1848 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1849 if (mCurrentState.flags == newFlags)
1850 return false;
1851 mCurrentState.sequence++;
1852 mCurrentState.flags = newFlags;
1853 mCurrentState.mask = mask;
1854 mCurrentState.modified = true;
1855 setTransactionFlags(eTransactionNeeded);
1856 return true;
1857 }
1858
1859 bool Layer::setCrop(const Rect& crop, bool immediate) {
1860 if (mCurrentState.requestedCrop == crop)
1861 return false;
1862 mCurrentState.sequence++;
1863 mCurrentState.requestedCrop = crop;
1864 if (immediate && !mFreezeGeometryUpdates) {
1865 mCurrentState.crop = crop;
1866 }
1867 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1868
1869 mCurrentState.modified = true;
1870 setTransactionFlags(eTransactionNeeded);
1871 return true;
1872 }
1873
1874 bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
1875 if (mCurrentState.requestedFinalCrop == crop)
1876 return false;
1877 mCurrentState.sequence++;
1878 mCurrentState.requestedFinalCrop = crop;
1879 if (immediate && !mFreezeGeometryUpdates) {
1880 mCurrentState.finalCrop = crop;
1881 }
1882 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1883
1884 mCurrentState.modified = true;
1885 setTransactionFlags(eTransactionNeeded);
1886 return true;
1887 }
1888
1889 bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1890 if (scalingMode == mOverrideScalingMode)
1891 return false;
1892 mOverrideScalingMode = scalingMode;
1893 setTransactionFlags(eTransactionNeeded);
1894 return true;
1895 }
1896
1897 void Layer::setInfo(uint32_t type, uint32_t appId) {
1898 mCurrentState.appId = appId;
1899 mCurrentState.type = type;
1900 mCurrentState.modified = true;
1901 setTransactionFlags(eTransactionNeeded);
1902 }
1903
1904 uint32_t Layer::getEffectiveScalingMode() const {
1905 if (mOverrideScalingMode >= 0) {
1906 return mOverrideScalingMode;
1907 }
1908 return mCurrentScalingMode;
1909 }
1910
1911 bool Layer::setLayerStack(uint32_t layerStack) {
1912 if (mCurrentState.layerStack == layerStack)
1913 return false;
1914 mCurrentState.sequence++;
1915 mCurrentState.layerStack = layerStack;
1916 mCurrentState.modified = true;
1917 setTransactionFlags(eTransactionNeeded);
1918 return true;
1919 }
1920
1921 bool Layer::setDataSpace(android_dataspace dataSpace) {
1922 if (mCurrentState.dataSpace == dataSpace)
1923 return false;
1924 mCurrentState.sequence++;
1925 mCurrentState.dataSpace = dataSpace;
1926 mCurrentState.modified = true;
1927 setTransactionFlags(eTransactionNeeded);
1928 return true;
1929 }
1930
1931 uint32_t Layer::getLayerStack() const {
1932 auto p = mDrawingParent.promote();
1933 if (p == nullptr) {
1934 return getDrawingState().layerStack;
1935 }
1936 return p->getLayerStack();
1937 }
1938
1939 void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
1940 uint64_t frameNumber) {
1941 mCurrentState.barrierLayer = barrierLayer;
1942 mCurrentState.frameNumber = frameNumber;
1943 // We don't set eTransactionNeeded, because just receiving a deferral
1944 // request without any other state updates shouldn't actually induce a delay
1945 mCurrentState.modified = true;
1946 pushPendingState();
1947 mCurrentState.barrierLayer = nullptr;
1948 mCurrentState.frameNumber = 0;
1949 mCurrentState.modified = false;
1950 }
1951
1952 void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
1953 uint64_t frameNumber) {
1954 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
1955 deferTransactionUntil(handle->owner.promote(), frameNumber);
1956 }
1957
1958 void Layer::useSurfaceDamage() {
1959 if (mFlinger->mForceFullDamage) {
1960 surfaceDamageRegion = Region::INVALID_REGION;
1961 } else {
1962 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1963 }
1964 }
1965
1966 void Layer::useEmptyDamage() {
1967 surfaceDamageRegion.clear();
1968 }
1969
1970 // ----------------------------------------------------------------------------
1971 // pageflip handling...
1972 // ----------------------------------------------------------------------------
1973
1974 bool Layer::shouldPresentNow(const DispSync& dispSync) const {
1975 if (mSidebandStreamChanged || mAutoRefresh) {
1976 return true;
1977 }
1978
1979 Mutex::Autolock lock(mQueueItemLock);
1980 if (mQueueItems.empty()) {
1981 return false;
1982 }
1983 auto timestamp = mQueueItems[0].mTimestamp;
1984 nsecs_t expectedPresent =
1985 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
1986
1987 // Ignore timestamps more than a second in the future
1988 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1989 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1990 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1991 expectedPresent);
1992
1993 bool isDue = timestamp < expectedPresent;
1994 return isDue || !isPlausible;
1995 }
1996
1997 bool Layer::onPreComposition(nsecs_t refreshStartTime) {
1998 if (mBufferLatched) {
1999 Mutex::Autolock lock(mFrameEventHistoryMutex);
2000 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
2001 }
2002 mRefreshPending = false;
2003 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
2004 }
2005
2006 bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
2007 const std::shared_ptr<FenceTime>& presentFence,
2008 const CompositorTiming& compositorTiming) {
2009 mAcquireTimeline.updateSignalTimes();
2010 mReleaseTimeline.updateSignalTimes();
2011
2012 // mFrameLatencyNeeded is true when a new frame was latched for the
2013 // composition.
2014 if (!mFrameLatencyNeeded)
2015 return false;
2016
2017 // Update mFrameEventHistory.
2018 {
2019 Mutex::Autolock lock(mFrameEventHistoryMutex);
2020 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
2021 glDoneFence, presentFence, compositorTiming);
2022 }
2023
2024 // Update mFrameTracker.
2025 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
2026 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
2027
2028 std::shared_ptr<FenceTime> frameReadyFence =
2029 mSurfaceFlingerConsumer->getCurrentFenceTime();
2030 if (frameReadyFence->isValid()) {
2031 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
2032 } else {
2033 // There was no fence for this frame, so assume that it was ready
2034 // to be presented at the desired present time.
2035 mFrameTracker.setFrameReadyTime(desiredPresentTime);
2036 }
2037
2038 if (presentFence->isValid()) {
2039 mFrameTracker.setActualPresentFence(
2040 std::shared_ptr<FenceTime>(presentFence));
2041 } else {
2042 // The HWC doesn't support present fences, so use the refresh
2043 // timestamp instead.
2044 mFrameTracker.setActualPresentTime(
2045 mFlinger->getHwComposer().getRefreshTimestamp(
2046 HWC_DISPLAY_PRIMARY));
2047 }
2048
2049 mFrameTracker.advanceFrame();
2050 mFrameLatencyNeeded = false;
2051 return true;
2052 }
2053
2054 #ifdef USE_HWC2
2055 void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2056 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2057 return;
2058 }
2059
2060 auto releaseFenceTime = std::make_shared<FenceTime>(
2061 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
2062 mReleaseTimeline.push(releaseFenceTime);
2063
2064 Mutex::Autolock lock(mFrameEventHistoryMutex);
2065 if (mPreviousFrameNumber != 0) {
2066 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2067 dequeueReadyTime, std::move(releaseFenceTime));
2068 }
2069 }
2070 #endif
2071
2072 bool Layer::isHiddenByPolicy() const {
2073 const Layer::State& s(mDrawingState);
2074 const auto& parent = mDrawingParent.promote();
2075 if (parent != nullptr && parent->isHiddenByPolicy()) {
2076 return true;
2077 }
2078 return s.flags & layer_state_t::eLayerHidden;
2079 }
2080
2081 bool Layer::isVisible() const {
2082 #ifdef USE_HWC2
2083 return !(isHiddenByPolicy()) && getAlpha() > 0.0f
2084 && (mActiveBuffer != NULL || mSidebandStream != NULL);
2085 #else
2086 return !(isHiddenByPolicy()) && getAlpha()
2087 && (mActiveBuffer != NULL || mSidebandStream != NULL);
2088 #endif
2089 }
2090
2091 bool Layer::allTransactionsSignaled() {
2092 auto headFrameNumber = getHeadFrameNumber();
2093 bool matchingFramesFound = false;
2094 bool allTransactionsApplied = true;
2095 Mutex::Autolock lock(mLocalSyncPointMutex);
2096
2097 for (auto& point : mLocalSyncPoints) {
2098 if (point->getFrameNumber() > headFrameNumber) {
2099 break;
2100 }
2101 matchingFramesFound = true;
2102
2103 if (!point->frameIsAvailable()) {
2104 // We haven't notified the remote layer that the frame for
2105 // this point is available yet. Notify it now, and then
2106 // abort this attempt to latch.
2107 point->setFrameAvailable();
2108 allTransactionsApplied = false;
2109 break;
2110 }
2111
2112 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2113 }
2114 return !matchingFramesFound || allTransactionsApplied;
2115 }
2116
2117 Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
2118 {
2119 ATRACE_CALL();
2120
2121 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2122 // mSidebandStreamChanged was true
2123 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
2124 if (mSidebandStream != NULL) {
2125 setTransactionFlags(eTransactionNeeded);
2126 mFlinger->setTransactionFlags(eTraversalNeeded);
2127 }
2128 recomputeVisibleRegions = true;
2129
2130 const State& s(getDrawingState());
2131 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
2132 }
2133
2134 Region outDirtyRegion;
2135 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2136 return outDirtyRegion;
2137 }
2138
2139 // if we've already called updateTexImage() without going through
2140 // a composition step, we have to skip this layer at this point
2141 // because we cannot call updateTeximage() without a corresponding
2142 // compositionComplete() call.
2143 // we'll trigger an update in onPreComposition().
2144 if (mRefreshPending) {
2145 return outDirtyRegion;
2146 }
2147
2148 // If the head buffer's acquire fence hasn't signaled yet, return and
2149 // try again later
2150 if (!headFenceHasSignaled()) {
2151 mFlinger->signalLayerUpdate();
2152 return outDirtyRegion;
2153 }
2154
2155 // Capture the old state of the layer for comparisons later
2156 const State& s(getDrawingState());
2157 const bool oldOpacity = isOpaque(s);
2158 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2159
2160 if (!allTransactionsSignaled()) {
2161 mFlinger->signalLayerUpdate();
2162 return outDirtyRegion;
2163 }
2164
2165 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2166 // of the buffer queue isn't modified when the buffer queue is returning
2167 // BufferItem's that weren't actually queued. This can happen in shared
2168 // buffer mode.
2169 bool queuedBuffer = false;
2170 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2171 getProducerStickyTransform() != 0, mName.string(),
2172 mOverrideScalingMode, mFreezeGeometryUpdates);
2173 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2174 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2175 mLastFrameNumberReceived);
2176 if (updateResult == BufferQueue::PRESENT_LATER) {
2177 // Producer doesn't want buffer to be displayed yet. Signal a
2178 // layer update so we check again at the next opportunity.
2179 mFlinger->signalLayerUpdate();
2180 return outDirtyRegion;
2181 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2182 // If the buffer has been rejected, remove it from the shadow queue
2183 // and return early
2184 if (queuedBuffer) {
2185 Mutex::Autolock lock(mQueueItemLock);
2186 mQueueItems.removeAt(0);
2187 android_atomic_dec(&mQueuedFrames);
2188 }
2189 return outDirtyRegion;
2190 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2191 // This can occur if something goes wrong when trying to create the
2192 // EGLImage for this buffer. If this happens, the buffer has already
2193 // been released, so we need to clean up the queue and bug out
2194 // early.
2195 if (queuedBuffer) {
2196 Mutex::Autolock lock(mQueueItemLock);
2197 mQueueItems.clear();
2198 android_atomic_and(0, &mQueuedFrames);
2199 }
2200
2201 // Once we have hit this state, the shadow queue may no longer
2202 // correctly reflect the incoming BufferQueue's contents, so even if
2203 // updateTexImage starts working, the only safe course of action is
2204 // to continue to ignore updates.
2205 mUpdateTexImageFailed = true;
2206
2207 return outDirtyRegion;
2208 }
2209
2210 if (queuedBuffer) {
2211 // Autolock scope
2212 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2213
2214 Mutex::Autolock lock(mQueueItemLock);
2215
2216 // Remove any stale buffers that have been dropped during
2217 // updateTexImage
2218 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2219 mQueueItems.removeAt(0);
2220 android_atomic_dec(&mQueuedFrames);
2221 }
2222
2223 mQueueItems.removeAt(0);
2224 }
2225
2226
2227 // Decrement the queued-frames count. Signal another event if we
2228 // have more frames pending.
2229 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2230 || mAutoRefresh) {
2231 mFlinger->signalLayerUpdate();
2232 }
2233
2234 // update the active buffer
2235 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2236 &mActiveBufferSlot);
2237 if (mActiveBuffer == NULL) {
2238 // this can only happen if the very first buffer was rejected.
2239 return outDirtyRegion;
2240 }
2241
2242 mBufferLatched = true;
2243 mPreviousFrameNumber = mCurrentFrameNumber;
2244 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2245
2246 {
2247 Mutex::Autolock lock(mFrameEventHistoryMutex);
2248 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2249 #ifndef USE_HWC2
2250 auto releaseFenceTime = std::make_shared<FenceTime>(
2251 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
2252 mReleaseTimeline.push(releaseFenceTime);
2253 if (mPreviousFrameNumber != 0) {
2254 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2255 latchTime, std::move(releaseFenceTime));
2256 }
2257 #endif
2258 }
2259
2260 mRefreshPending = true;
2261 mFrameLatencyNeeded = true;
2262 if (oldActiveBuffer == NULL) {
2263 // the first time we receive a buffer, we need to trigger a
2264 // geometry invalidation.
2265 recomputeVisibleRegions = true;
2266 }
2267
2268 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2269
2270 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2271 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2272 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2273 if ((crop != mCurrentCrop) ||
2274 (transform != mCurrentTransform) ||
2275 (scalingMode != mCurrentScalingMode))
2276 {
2277 mCurrentCrop = crop;
2278 mCurrentTransform = transform;
2279 mCurrentScalingMode = scalingMode;
2280 recomputeVisibleRegions = true;
2281 }
2282
2283 if (oldActiveBuffer != NULL) {
2284 uint32_t bufWidth = mActiveBuffer->getWidth();
2285 uint32_t bufHeight = mActiveBuffer->getHeight();
2286 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2287 bufHeight != uint32_t(oldActiveBuffer->height)) {
2288 recomputeVisibleRegions = true;
2289 }
2290 }
2291
2292 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2293 if (oldOpacity != isOpaque(s)) {
2294 recomputeVisibleRegions = true;
2295 }
2296
2297 // Remove any sync points corresponding to the buffer which was just
2298 // latched
2299 {
2300 Mutex::Autolock lock(mLocalSyncPointMutex);
2301 auto point = mLocalSyncPoints.begin();
2302 while (point != mLocalSyncPoints.end()) {
2303 if (!(*point)->frameIsAvailable() ||
2304 !(*point)->transactionIsApplied()) {
2305 // This sync point must have been added since we started
2306 // latching. Don't drop it yet.
2307 ++point;
2308 continue;
2309 }
2310
2311 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2312 point = mLocalSyncPoints.erase(point);
2313 } else {
2314 ++point;
2315 }
2316 }
2317 }
2318
2319 // FIXME: postedRegion should be dirty & bounds
2320 Region dirtyRegion(Rect(s.active.w, s.active.h));
2321
2322 // transform the dirty region to window-manager space
2323 outDirtyRegion = (getTransform().transform(dirtyRegion));
2324
2325 return outDirtyRegion;
2326 }
2327
2328 uint32_t Layer::getEffectiveUsage(uint32_t usage) const
2329 {
2330 // TODO: should we do something special if mSecure is set?
2331 if (mProtectedByApp) {
2332 // need a hardware-protected path to external video sink
2333 usage |= GraphicBuffer::USAGE_PROTECTED;
2334 }
2335 if (mPotentialCursor) {
2336 usage |= GraphicBuffer::USAGE_CURSOR;
2337 }
2338 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
2339 return usage;
2340 }
2341
2342 void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
2343 uint32_t orientation = 0;
2344 if (!mFlinger->mDebugDisableTransformHint) {
2345 // The transform hint is used to improve performance, but we can
2346 // only have a single transform hint, it cannot
2347 // apply to all displays.
2348 const Transform& planeTransform(hw->getTransform());
2349 orientation = planeTransform.getOrientation();
2350 if (orientation & Transform::ROT_INVALID) {
2351 orientation = 0;
2352 }
2353 }
2354 mSurfaceFlingerConsumer->setTransformHint(orientation);
2355 }
2356
2357 // ----------------------------------------------------------------------------
2358 // debugging
2359 // ----------------------------------------------------------------------------
2360
2361 void Layer::dump(String8& result, Colorizer& colorizer) const
2362 {
2363 const Layer::State& s(getDrawingState());
2364
2365 colorizer.colorize(result, Colorizer::GREEN);
2366 result.appendFormat(
2367 "+ %s %p (%s)\n",
2368 getTypeId(), this, getName().string());
2369 colorizer.reset(result);
2370
2371 s.activeTransparentRegion.dump(result, "transparentRegion");
2372 visibleRegion.dump(result, "visibleRegion");
2373 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
2374 sp<Client> client(mClientRef.promote());
2375
2376 result.appendFormat( " "
2377 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2378 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
2379 "isOpaque=%1d, invalidate=%1d, "
2380 #ifdef USE_HWC2
2381 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2382 #else
2383 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2384 #endif
2385 " client=%p\n",
2386 getLayerStack(), s.z,
2387 s.active.transform.tx(), s.active.transform.ty(),
2388 s.active.w, s.active.h,
2389 s.crop.left, s.crop.top,
2390 s.crop.right, s.crop.bottom,
2391 s.finalCrop.left, s.finalCrop.top,
2392 s.finalCrop.right, s.finalCrop.bottom,
2393 isOpaque(s), contentDirty,
2394 s.alpha, s.flags,
2395 s.active.transform[0][0], s.active.transform[0][1],
2396 s.active.transform[1][0], s.active.transform[1][1],
2397 client.get());
2398
2399 sp<const GraphicBuffer> buf0(mActiveBuffer);
2400 uint32_t w0=0, h0=0, s0=0, f0=0;
2401 if (buf0 != 0) {
2402 w0 = buf0->getWidth();
2403 h0 = buf0->getHeight();
2404 s0 = buf0->getStride();
2405 f0 = buf0->format;
2406 }
2407 result.appendFormat(
2408 " "
2409 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2410 " queued-frames=%d, mRefreshPending=%d\n",
2411 mFormat, w0, h0, s0,f0,
2412 mQueuedFrames, mRefreshPending);
2413
2414 if (mSurfaceFlingerConsumer != 0) {
2415 mSurfaceFlingerConsumer->dumpState(result, " ");
2416 }
2417 }
2418
2419 #ifdef USE_HWC2
2420 void Layer::miniDumpHeader(String8& result) {
2421 result.append("----------------------------------------");
2422 result.append("---------------------------------------\n");
2423 result.append(" Layer name\n");
2424 result.append(" Z | ");
2425 result.append(" Comp Type | ");
2426 result.append(" Disp Frame (LTRB) | ");
2427 result.append(" Source Crop (LTRB)\n");
2428 result.append("----------------------------------------");
2429 result.append("---------------------------------------\n");
2430 }
2431
2432 void Layer::miniDump(String8& result, int32_t hwcId) const {
2433 if (mHwcLayers.count(hwcId) == 0) {
2434 return;
2435 }
2436
2437 String8 name;
2438 if (mName.length() > 77) {
2439 std::string shortened;
2440 shortened.append(mName.string(), 36);
2441 shortened.append("[...]");
2442 shortened.append(mName.string() + (mName.length() - 36), 36);
2443 name = shortened.c_str();
2444 } else {
2445 name = mName;
2446 }
2447
2448 result.appendFormat(" %s\n", name.string());
2449
2450 const Layer::State& layerState(getDrawingState());
2451 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2452 result.appendFormat(" %10u | ", layerState.z);
2453 result.appendFormat("%10s | ",
2454 to_string(getCompositionType(hwcId)).c_str());
2455 const Rect& frame = hwcInfo.displayFrame;
2456 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2457 frame.right, frame.bottom);
2458 const FloatRect& crop = hwcInfo.sourceCrop;
2459 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2460 crop.right, crop.bottom);
2461
2462 result.append("- - - - - - - - - - - - - - - - - - - - ");
2463 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2464 }
2465 #endif
2466
2467 void Layer::dumpFrameStats(String8& result) const {
2468 mFrameTracker.dumpStats(result);
2469 }
2470
2471 void Layer::clearFrameStats() {
2472 mFrameTracker.clearStats();
2473 }
2474
2475 void Layer::logFrameStats() {
2476 mFrameTracker.logAndResetStats(mName);
2477 }
2478
2479 void Layer::getFrameStats(FrameStats* outStats) const {
2480 mFrameTracker.getStats(outStats);
2481 }
2482
2483 void Layer::dumpFrameEvents(String8& result) {
2484 result.appendFormat("- Layer %s (%s, %p)\n",
2485 getName().string(), getTypeId(), this);
2486 Mutex::Autolock lock(mFrameEventHistoryMutex);
2487 mFrameEventHistory.checkFencesForCompletion();
2488 mFrameEventHistory.dump(result);
2489 }
2490
2491 void Layer::onDisconnect() {
2492 Mutex::Autolock lock(mFrameEventHistoryMutex);
2493 mFrameEventHistory.onDisconnect();
2494 }
2495
2496 void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2497 FrameEventHistoryDelta *outDelta) {
2498 Mutex::Autolock lock(mFrameEventHistoryMutex);
2499 if (newTimestamps) {
2500 mAcquireTimeline.push(newTimestamps->acquireFence);
2501 mFrameEventHistory.addQueue(*newTimestamps);
2502 }
2503
2504 if (outDelta) {
2505 mFrameEventHistory.getAndResetDelta(outDelta);
2506 }
2507 }
2508
2509 std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2510 bool forceFlush) {
2511 std::vector<OccupancyTracker::Segment> history;
2512 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2513 &history);
2514 if (result != NO_ERROR) {
2515 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2516 result);
2517 return {};
2518 }
2519 return history;
2520 }
2521
2522 bool Layer::getTransformToDisplayInverse() const {
2523 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2524 }
2525
2526 size_t Layer::getChildrenCount() const {
2527 size_t count = 0;
2528 for (const sp<Layer>& child : mCurrentChildren) {
2529 count += 1 + child->getChildrenCount();
2530 }
2531 return count;
2532 }
2533
2534 void Layer::addChild(const sp<Layer>& layer) {
2535 mCurrentChildren.add(layer);
2536 layer->setParent(this);
2537 }
2538
2539 ssize_t Layer::removeChild(const sp<Layer>& layer) {
2540 layer->setParent(nullptr);
2541 return mCurrentChildren.remove(layer);
2542 }
2543
2544 bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2545 sp<Handle> handle = nullptr;
2546 sp<Layer> newParent = nullptr;
2547 if (newParentHandle == nullptr) {
2548 return false;
2549 }
2550 handle = static_cast<Handle*>(newParentHandle.get());
2551 newParent = handle->owner.promote();
2552 if (newParent == nullptr) {
2553 ALOGE("Unable to promote Layer handle");
2554 return false;
2555 }
2556
2557 for (const sp<Layer>& child : mCurrentChildren) {
2558 newParent->addChild(child);
2559
2560 sp<Client> client(child->mClientRef.promote());
2561 if (client != nullptr) {
2562 client->setParentLayer(newParent);
2563 }
2564 }
2565 mCurrentChildren.clear();
2566
2567 return true;
2568 }
2569
2570 bool Layer::detachChildren() {
2571 traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
2572 if (child == this) {
2573 return;
2574 }
2575
2576 sp<Client> client(child->mClientRef.promote());
2577 if (client != nullptr) {
2578 client->detachLayer(child);
2579 }
2580 });
2581
2582 return true;
2583 }
2584
2585 void Layer::setParent(const sp<Layer>& layer) {
2586 mCurrentParent = layer;
2587 }
2588
2589 void Layer::clearSyncPoints() {
2590 for (const auto& child : mCurrentChildren) {
2591 child->clearSyncPoints();
2592 }
2593
2594 Mutex::Autolock lock(mLocalSyncPointMutex);
2595 for (auto& point : mLocalSyncPoints) {
2596 point->setFrameAvailable();
2597 }
2598 mLocalSyncPoints.clear();
2599 }
2600
2601 int32_t Layer::getZ() const {
2602 return mDrawingState.z;
2603 }
2604
2605 LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2606 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2607 "makeTraversalList received invalid stateSet");
2608 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2609 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2610 const State& state = useDrawing ? mDrawingState : mCurrentState;
2611
2612 if (state.zOrderRelatives.size() == 0) {
2613 return children;
2614 }
2615 LayerVector traverse;
2616
2617 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2618 sp<Layer> strongRelative = weakRelative.promote();
2619 if (strongRelative != nullptr) {
2620 traverse.add(strongRelative);
2621 }
2622 }
2623
2624 for (const sp<Layer>& child : children) {
2625 traverse.add(child);
2626 }
2627
2628 return traverse;
2629 }
2630
2631 /**
2632 * Negatively signed relatives are before 'this' in Z-order.
2633 */
2634 void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2635 LayerVector list = makeTraversalList(stateSet);
2636
2637 size_t i = 0;
2638 for (; i < list.size(); i++) {
2639 const auto& relative = list[i];
2640 if (relative->getZ() >= 0) {
2641 break;
2642 }
2643 relative->traverseInZOrder(stateSet, visitor);
2644 }
2645 visitor(this);
2646 for (; i < list.size(); i++) {
2647 const auto& relative = list[i];
2648 relative->traverseInZOrder(stateSet, visitor);
2649 }
2650 }
2651
2652 /**
2653 * Positively signed relatives are before 'this' in reverse Z-order.
2654 */
2655 void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2656 const LayerVector::Visitor& visitor) {
2657 LayerVector list = makeTraversalList(stateSet);
2658
2659 int32_t i = 0;
2660 for (i = list.size()-1; i>=0; i--) {
2661 const auto& relative = list[i];
2662 if (relative->getZ() < 0) {
2663 break;
2664 }
2665 relative->traverseInReverseZOrder(stateSet, visitor);
2666 }
2667 visitor(this);
2668 for (; i>=0; i--) {
2669 const auto& relative = list[i];
2670 relative->traverseInReverseZOrder(stateSet, visitor);
2671 }
2672 }
2673
2674 Transform Layer::getTransform() const {
2675 Transform t;
2676 const auto& p = mDrawingParent.promote();
2677 if (p != nullptr) {
2678 t = p->getTransform();
2679
2680 // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2681 // it isFixedSize) then there may be additional scaling not accounted
2682 // for in the transform. We need to mirror this scaling in child surfaces
2683 // or we will break the contract where WM can treat child surfaces as
2684 // pixels in the parent surface.
2685 if (p->isFixedSize()) {
2686 int bufferWidth;
2687 int bufferHeight;
2688 if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2689 bufferWidth = p->mActiveBuffer->getWidth();
2690 bufferHeight = p->mActiveBuffer->getHeight();
2691 } else {
2692 bufferHeight = p->mActiveBuffer->getWidth();
2693 bufferWidth = p->mActiveBuffer->getHeight();
2694 }
2695 float sx = p->getDrawingState().active.w /
2696 static_cast<float>(bufferWidth);
2697 float sy = p->getDrawingState().active.h /
2698 static_cast<float>(bufferHeight);
2699 Transform extraParentScaling;
2700 extraParentScaling.set(sx, 0, 0, sy);
2701 t = t * extraParentScaling;
2702 }
2703 }
2704 return t * getDrawingState().active.transform;
2705 }
2706
2707 #ifdef USE_HWC2
2708 float Layer::getAlpha() const {
2709 const auto& p = mDrawingParent.promote();
2710
2711 float parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0;
2712 return parentAlpha * getDrawingState().alpha;
2713 }
2714 #else
2715 uint8_t Layer::getAlpha() const {
2716 const auto& p = mDrawingParent.promote();
2717
2718 float parentAlpha = (p != nullptr) ? (p->getAlpha() / 255.0f) : 1.0;
2719 float drawingAlpha = getDrawingState().alpha / 255.0f;
2720 drawingAlpha = drawingAlpha * parentAlpha;
2721 return static_cast<uint8_t>(std::round(drawingAlpha * 255));
2722 }
2723 #endif
2724
2725 void Layer::commitChildList() {
2726 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2727 const auto& child = mCurrentChildren[i];
2728 child->commitChildList();
2729 }
2730 mDrawingChildren = mCurrentChildren;
2731 mDrawingParent = mCurrentParent;
2732 }
2733
2734 // ---------------------------------------------------------------------------
2735
2736 }; // namespace android
2737
2738 #if defined(__gl_h_)
2739 #error "don't include gl/gl.h in this file"
2740 #endif
2741
2742 #if defined(__gl2_h_)
2743 #error "don't include gl2/gl2.h in this file"
2744 #endif
2745