blob: 50d8998f65ebc55a7ffebc4c13e02196d14683f1 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
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
Dan Stoza9e56aa02015-11-02 13:00:03 -080017//#define LOG_NDEBUG 0
18#undef LOG_TAG
19#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080020#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <stdlib.h>
23#include <stdint.h>
24#include <sys/types.h>
Mathias Agopian13127d82013-03-05 17:47:11 -080025#include <math.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080026
Mathias Agopiana67932f2011-04-20 14:20:59 -070027#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070028#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070029#include <cutils/properties.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
31#include <utils/Errors.h>
32#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080033#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080034#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080035#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080036
Mathias Agopian3330b202009-10-05 17:07:12 -070037#include <ui/GraphicBuffer.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080038#include <ui/PixelFormat.h>
Mathias Agopian9cce3252010-02-09 17:46:37 -080039
Dan Stoza6b9454d2014-11-07 16:00:59 -080040#include <gui/BufferItem.h>
Mathias Agopiana9347642017-02-13 16:42:28 -080041#include <gui/BufferQueue.h>
Mathias Agopian90ac7992012-02-25 18:48:35 -080042#include <gui/Surface.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080043
44#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020045#include "Colorizer.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070046#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080047#include "Layer.h"
Fabien Sanglard7b1563a2016-10-13 12:05:28 -070048#include "LayerRejecter.h"
Dan Stozab9b08832014-03-13 11:55:57 -070049#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080050#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080051
Mathias Agopian1b031492012-06-20 17:51:20 -070052#include "DisplayHardware/HWComposer.h"
53
Mathias Agopian875d8e12013-06-07 15:35:48 -070054#include "RenderEngine/RenderEngine.h"
55
Dan Stozac5da2712016-07-20 15:38:12 -070056#include <mutex>
57
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058#define DEBUG_RESIZE 0
59
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060namespace android {
61
62// ---------------------------------------------------------------------------
63
Mathias Agopian13127d82013-03-05 17:47:11 -080064int32_t Layer::sSequence = 1;
65
Mathias Agopian4d9b8222013-03-12 17:11:48 -070066Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
67 const String8& name, uint32_t w, uint32_t h, uint32_t flags)
Mathias Agopian13127d82013-03-05 17:47:11 -080068 : contentDirty(false),
69 sequence(uint32_t(android_atomic_inc(&sSequence))),
70 mFlinger(flinger),
Mathias Agopiana67932f2011-04-20 14:20:59 -070071 mTextureName(-1U),
Mathias Agopian13127d82013-03-05 17:47:11 -080072 mPremultipliedAlpha(true),
73 mName("unnamed"),
Mathias Agopian13127d82013-03-05 17:47:11 -080074 mFormat(PIXEL_FORMAT_NONE),
Mathias Agopian13127d82013-03-05 17:47:11 -080075 mTransactionFlags(0),
Dan Stoza7dde5992015-05-22 09:51:44 -070076 mPendingStateMutex(),
77 mPendingStates(),
Mathias Agopiana67932f2011-04-20 14:20:59 -070078 mQueuedFrames(0),
Jesse Hall399184a2014-03-03 15:42:54 -080079 mSidebandStreamChanged(false),
Mathias Agopiana9347642017-02-13 16:42:28 -080080 mActiveBufferSlot(BufferQueue::INVALID_BUFFER_SLOT),
Mathias Agopiana67932f2011-04-20 14:20:59 -070081 mCurrentTransform(0),
Mathias Agopian933389f2011-07-18 16:15:08 -070082 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
Robert Carrc3574f72016-03-24 12:19:32 -070083 mOverrideScalingMode(-1),
Mathias Agopiana67932f2011-04-20 14:20:59 -070084 mCurrentOpacity(true),
Brian Andersond6927fb2016-07-23 23:37:30 -070085 mBufferLatched(false),
Dan Stozacac35382016-01-27 12:21:06 -080086 mCurrentFrameNumber(0),
Brian Anderson8cc8b102016-10-21 12:43:09 -070087 mPreviousFrameNumber(0),
Mathias Agopian4d143ee2012-02-23 20:05:39 -080088 mRefreshPending(false),
Mathias Agopian82d7ab62012-01-19 18:34:40 -080089 mFrameLatencyNeeded(false),
Mathias Agopian13127d82013-03-05 17:47:11 -080090 mFiltering(false),
91 mNeedsFiltering(false),
Mathias Agopian5cdc8992013-08-13 20:51:23 -070092 mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
Fabien Sanglard9d96de42016-10-11 00:15:18 +000093#ifndef USE_HWC2
94 mIsGlesComposition(false),
95#endif
Mathias Agopian13127d82013-03-05 17:47:11 -080096 mProtectedByApp(false),
97 mHasSurface(false),
Riley Andrews03414a12014-07-01 14:22:59 -070098 mClientRef(client),
Dan Stozaa4650a52015-05-12 12:56:16 -070099 mPotentialCursor(false),
100 mQueueItemLock(),
101 mQueueItemCondition(),
102 mQueueItems(),
Dan Stoza65476f32015-05-14 09:27:25 -0700103 mLastFrameNumberReceived(0),
Pablo Ceballos04839ab2015-11-13 13:39:23 -0800104 mUpdateTexImageFailed(false),
Robert Carr82364e32016-05-15 11:27:47 -0700105 mAutoRefresh(false),
Robert Carr1e079c22017-05-09 12:16:54 -0700106 mFreezeGeometryUpdates(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800107{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000108#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800109 ALOGV("Creating Layer %s", name.string());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000110#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -0800111
Mathias Agopiana67932f2011-04-20 14:20:59 -0700112 mCurrentCrop.makeInvalid();
Mathias Agopian3f844832013-08-07 21:24:32 -0700113 mFlinger->getRenderEngine().genTextures(1, &mTextureName);
Mathias Agopian49457ac2013-08-14 18:20:17 -0700114 mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700115
116 uint32_t layerFlags = 0;
117 if (flags & ISurfaceComposerClient::eHidden)
Andy McFadden4125a4f2014-01-29 17:17:11 -0800118 layerFlags |= layer_state_t::eLayerHidden;
119 if (flags & ISurfaceComposerClient::eOpaque)
120 layerFlags |= layer_state_t::eLayerOpaque;
Dan Stoza23116082015-06-18 14:58:39 -0700121 if (flags & ISurfaceComposerClient::eSecure)
122 layerFlags |= layer_state_t::eLayerSecure;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700123
124 if (flags & ISurfaceComposerClient::eNonPremultiplied)
125 mPremultipliedAlpha = false;
126
127 mName = name;
128
129 mCurrentState.active.w = w;
130 mCurrentState.active.h = h;
Robert Carr3dcabfa2016-03-01 18:36:58 -0800131 mCurrentState.active.transform.set(0, 0);
Robert Carrb5d3d262016-03-25 15:08:13 -0700132 mCurrentState.crop.makeInvalid();
133 mCurrentState.finalCrop.makeInvalid();
Robert Carr1e079c22017-05-09 12:16:54 -0700134 mCurrentState.requestedFinalCrop = mCurrentState.finalCrop;
135 mCurrentState.requestedCrop = mCurrentState.crop;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700136 mCurrentState.z = 0;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000137#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800138 mCurrentState.alpha = 1.0f;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000139#else
140 mCurrentState.alpha = 0xFF;
141#endif
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700142 mCurrentState.layerStack = 0;
143 mCurrentState.flags = layerFlags;
144 mCurrentState.sequence = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700145 mCurrentState.requested = mCurrentState.active;
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700146 mCurrentState.dataSpace = HAL_DATASPACE_UNKNOWN;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500147 mCurrentState.appId = 0;
148 mCurrentState.type = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700149
150 // drawing state & current state are identical
151 mDrawingState = mCurrentState;
Jamie Gennis6547ff42013-07-16 20:12:42 -0700152
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000153#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800154 const auto& hwc = flinger->getHwComposer();
155 const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
156 nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000157#else
158 nsecs_t displayPeriod =
159 flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
160#endif
Jamie Gennis6547ff42013-07-16 20:12:42 -0700161 mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -0800162
163 CompositorTiming compositorTiming;
164 flinger->getCompositorTiming(&compositorTiming);
165 mFrameEventHistory.initializeCompositorTiming(compositorTiming);
Jamie Gennise8696a42012-01-15 18:54:57 -0800166}
167
Mathias Agopian3f844832013-08-07 21:24:32 -0700168void Layer::onFirstRef() {
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800169 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
Dan Stozab3d0bdf2014-04-07 16:33:59 -0700170 sp<IGraphicBufferProducer> producer;
171 sp<IGraphicBufferConsumer> consumer;
Mathias Agopian0556d792017-03-22 15:49:32 -0700172 BufferQueue::createBufferQueue(&producer, &consumer, true);
Robert Carr1db73f62016-12-21 12:58:51 -0800173 mProducer = new MonitoredProducer(producer, mFlinger, this);
Irvel468051e2016-06-13 16:44:44 -0700174 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800175 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Jesse Hall399184a2014-03-03 15:42:54 -0800176 mSurfaceFlingerConsumer->setContentsChangedListener(this);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700177 mSurfaceFlingerConsumer->setName(mName);
Daniel Lamb2675792012-02-23 14:35:13 -0800178
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800179 if (mFlinger->isLayerTripleBufferingDisabled()) {
180 mProducer->setMaxDequeuedBufferCount(2);
181 }
Andy McFadden69052052012-09-14 16:10:11 -0700182
Mathias Agopian84300952012-11-21 16:02:13 -0800183 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
184 updateTransformHint(hw);
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700185}
186
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700187Layer::~Layer() {
Pablo Ceballos8ea4e7b2016-03-03 15:20:02 -0800188 sp<Client> c(mClientRef.promote());
189 if (c != 0) {
190 c->detachLayer(this);
191 }
192
Dan Stozacac35382016-01-27 12:21:06 -0800193 for (auto& point : mRemoteSyncPoints) {
194 point->setTransactionApplied();
195 }
Dan Stozac8145172016-04-28 16:29:06 -0700196 for (auto& point : mLocalSyncPoints) {
197 point->setFrameAvailable();
198 }
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700199 mFlinger->deleteTextureAsync(mTextureName);
Jamie Gennis6547ff42013-07-16 20:12:42 -0700200 mFrameTracker.logAndResetStats(mName);
Mathias Agopian96f08192010-06-02 23:28:45 -0700201}
202
Mathias Agopian13127d82013-03-05 17:47:11 -0800203// ---------------------------------------------------------------------------
204// callbacks
205// ---------------------------------------------------------------------------
206
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000207#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800208void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
209 if (mHwcLayers.empty()) {
210 return;
211 }
212 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
213}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000214#else
215void 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
Mathias Agopian13127d82013-03-05 17:47:11 -0800223
Dan Stoza6b9454d2014-11-07 16:00:59 -0800224void Layer::onFrameAvailable(const BufferItem& item) {
225 // Add this buffer from our internal queue tracker
226 { // Autolock scope
227 Mutex::Autolock lock(mQueueItemLock);
Irvel468051e2016-06-13 16:44:44 -0700228 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
229 item.mGraphicBuffer->getHeight(), item.mFrameNumber);
Dan Stozaa4650a52015-05-12 12:56:16 -0700230 // 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
Dan Stoza6b9454d2014-11-07 16:00:59 -0800245 mQueueItems.push_back(item);
Dan Stozaecc50402015-04-28 14:42:06 -0700246 android_atomic_inc(&mQueuedFrames);
Dan Stozaa4650a52015-05-12 12:56:16 -0700247
248 // Wake up any pending callbacks
249 mLastFrameNumberReceived = item.mFrameNumber;
250 mQueueItemCondition.broadcast();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800251 }
252
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800253 mFlinger->signalLayerUpdate();
Mathias Agopian579b3f82010-06-08 19:54:15 -0700254}
255
Dan Stoza6b9454d2014-11-07 16:00:59 -0800256void Layer::onFrameReplaced(const BufferItem& item) {
Dan Stoza7dde5992015-05-22 09:51:44 -0700257 { // Autolock scope
258 Mutex::Autolock lock(mQueueItemLock);
Dan Stozaa4650a52015-05-12 12:56:16 -0700259
Dan Stoza7dde5992015-05-22 09:51:44 -0700260 // 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 }
Dan Stozaa4650a52015-05-12 12:56:16 -0700267 }
Dan Stoza7dde5992015-05-22 09:51:44 -0700268
269 if (mQueueItems.empty()) {
270 ALOGE("Can't replace a frame on an empty queue");
271 return;
272 }
Pablo Ceballos4d85da42016-04-19 20:11:56 -0700273 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
Dan Stoza7dde5992015-05-22 09:51:44 -0700274
275 // Wake up any pending callbacks
276 mLastFrameNumberReceived = item.mFrameNumber;
277 mQueueItemCondition.broadcast();
Dan Stozaa4650a52015-05-12 12:56:16 -0700278 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800279}
280
Jesse Hall399184a2014-03-03 15:42:54 -0800281void Layer::onSidebandStreamChanged() {
282 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
283 // mSidebandStreamChanged was false
284 mFlinger->signalLayerUpdate();
285 }
286}
287
Mathias Agopian67106042013-03-14 19:18:13 -0700288// 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)
Mathias Agopian13127d82013-03-05 17:47:11 -0800291void Layer::onRemoved() {
Robert Carr5edb1ad2017-04-25 10:54:24 -0700292 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
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800300 mSurfaceFlingerConsumer->abandon();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700301 for (const auto& child : mCurrentChildren) {
302 child->onRemoved();
303 }
Mathias Agopian48d819a2009-09-10 19:41:18 -0700304}
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700305
Mathias Agopian13127d82013-03-05 17:47:11 -0800306// ---------------------------------------------------------------------------
307// set-up
308// ---------------------------------------------------------------------------
309
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700310const String8& Layer::getName() const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800311 return mName;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800312}
313
Mathias Agopianf9d93272009-06-19 17:00:27 -0700314status_t Layer::setBuffers( uint32_t w, uint32_t h,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800315 PixelFormat format, uint32_t flags)
316{
Mathias Agopianca99fb82010-04-14 16:43:44 -0700317 uint32_t const maxSurfaceDims = min(
Mathias Agopiana4912602012-07-12 14:25:33 -0700318 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
Mathias Agopianca99fb82010-04-14 16:43:44 -0700319
320 // never allow a surface larger than what our underlying GL implementation
321 // can handle.
322 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
Mathias Agopianff615cc2012-02-24 14:58:36 -0800323 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700324 return BAD_VALUE;
325 }
326
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700327 mFormat = format;
Mathias Agopianeff062c2010-08-25 14:59:15 -0700328
Riley Andrews03414a12014-07-01 14:22:59 -0700329 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
Mathias Agopian3165cc22012-08-08 19:42:09 -0700330 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700331 mCurrentOpacity = getOpacityForFormat(format);
332
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800333 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
334 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
335 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700336
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800337 return NO_ERROR;
338}
339
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700340sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800341 Mutex::Autolock _l(mLock);
342
343 LOG_ALWAYS_FATAL_IF(mHasSurface,
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700344 "Layer::getHandle() has already been called");
Mathias Agopian13127d82013-03-05 17:47:11 -0800345
346 mHasSurface = true;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700347
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700348 return new Handle(mFlinger, this);
Mathias Agopian13127d82013-03-05 17:47:11 -0800349}
350
Dan Stozab9b08832014-03-13 11:55:57 -0700351sp<IGraphicBufferProducer> Layer::getProducer() const {
352 return mProducer;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700353}
354
Mathias Agopian13127d82013-03-05 17:47:11 -0800355// ---------------------------------------------------------------------------
356// h/w composer set-up
357// ---------------------------------------------------------------------------
358
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800359Rect Layer::getContentCrop() const {
360 // this is the crop rectangle that applies to the buffer
361 // itself (as opposed to the window)
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700362 Rect crop;
363 if (!mCurrentCrop.isEmpty()) {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800364 // if the buffer crop is defined, we use that
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700365 crop = mCurrentCrop;
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800366 } else if (mActiveBuffer != NULL) {
367 // otherwise we use the whole buffer
368 crop = mActiveBuffer->getBounds();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700369 } else {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800370 // if we don't have a buffer yet, we use an empty/invalid crop
Mathias Agopian4fec8732012-06-29 14:12:52 -0700371 crop.makeInvalid();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700372 }
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700373 return crop;
374}
375
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700376static Rect reduce(const Rect& win, const Region& exclude) {
377 if (CC_LIKELY(exclude.isEmpty())) {
378 return win;
379 }
380 if (exclude.isRect()) {
381 return win.reduce(exclude.getBounds());
382 }
383 return Region(win).subtract(exclude).getBounds();
384}
385
Robert Carr1f0a16a2016-10-24 16:27:39 -0700386Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
387 const Layer::State& s(getDrawingState());
388 Rect win(s.active.w, s.active.h);
389
390 if (!s.crop.isEmpty()) {
391 win.intersect(s.crop, &win);
392 }
393
394 Transform t = getTransform();
395 win = t.transform(win);
396
397 const sp<Layer>& p = getParent();
398 // Now we need to calculate the parent bounds, so we can clip ourselves to those.
399 // When calculating the parent bounds for purposes of clipping,
400 // we don't need to constrain the parent to its transparent region.
401 // The transparent region is an optimization based on the
402 // buffer contents of the layer, but does not affect the space allocated to
403 // it by policy, and thus children should be allowed to extend into the
404 // parent's transparent region. In fact one of the main uses, is to reduce
405 // buffer allocation size in cases where a child window sits behind a main window
406 // (by marking the hole in the parent window as a transparent region)
407 if (p != nullptr) {
408 Rect bounds = p->computeScreenBounds(false);
409 bounds.intersect(win, &win);
410 }
411
412 if (reduceTransparentRegion) {
413 auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
414 win = reduce(win, screenTransparentRegion);
415 }
416
417 return win;
418}
419
Mathias Agopian13127d82013-03-05 17:47:11 -0800420Rect Layer::computeBounds() const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700421 const Layer::State& s(getDrawingState());
Michael Lentine6c925ed2014-09-26 17:55:01 -0700422 return computeBounds(s.activeTransparentRegion);
423}
424
425Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
426 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800427 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700428
429 if (!s.crop.isEmpty()) {
430 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -0800431 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700432
433 Rect bounds = win;
434 const auto& p = getParent();
435 if (p != nullptr) {
Robert Carrde9ec442017-02-08 17:43:36 -0800436 // Look in computeScreenBounds recursive call for explanation of
437 // why we pass false here.
438 bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700439 }
440
441 Transform t = getTransform();
442 if (p != nullptr) {
443 win = t.transform(win);
444 win.intersect(bounds, &win);
445 win = t.inverse().transform(win);
446 }
447
Mathias Agopian6c7f25a2013-05-09 20:37:10 -0700448 // subtract the transparent region and snap to the bounds
Michael Lentine6c925ed2014-09-26 17:55:01 -0700449 return reduce(win, activeTransparentRegion);
Mathias Agopian13127d82013-03-05 17:47:11 -0800450}
451
Robert Carr1f0a16a2016-10-24 16:27:39 -0700452Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
Robert Carrb5d3d262016-03-25 15:08:13 -0700453 // the crop is the area of the window that gets cropped, but not
Mathias Agopian13127d82013-03-05 17:47:11 -0800454 // scaled in any ways.
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700455 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800456
457 // apply the projection's clipping to the window crop in
458 // layerstack space, and convert-back to layer space.
Mathias Agopian6b442672013-07-09 21:24:52 -0700459 // if there are no window scaling involved, this operation will map to full
460 // pixels in the buffer.
461 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
462 // a viewport clipping and a window transform. we should use floating point to fix this.
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700463
464 Rect activeCrop(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700465 if (!s.crop.isEmpty()) {
466 activeCrop = s.crop;
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700467 }
468
Robert Carr1f0a16a2016-10-24 16:27:39 -0700469 Transform t = getTransform();
470 activeCrop = t.transform(activeCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000471 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
472 activeCrop.clear();
473 }
Robert Carrb5d3d262016-03-25 15:08:13 -0700474 if (!s.finalCrop.isEmpty()) {
475 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000476 activeCrop.clear();
477 }
478 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700479 return activeCrop;
480}
481
Dan Stoza5a423ea2017-02-16 14:10:39 -0800482FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
Robert Carr1f0a16a2016-10-24 16:27:39 -0700483 // the content crop is the area of the content that gets scaled to the
484 // layer's size. This is in buffer space.
Dan Stoza5a423ea2017-02-16 14:10:39 -0800485 FloatRect crop = getContentCrop().toFloatRect();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700486
487 // In addition there is a WM-specified crop we pull from our drawing state.
488 const State& s(getDrawingState());
489
490 // Screen space to make reduction to parent crop clearer.
491 Rect activeCrop = computeInitialCrop(hw);
492 const auto& p = getParent();
493 if (p != nullptr) {
494 auto parentCrop = p->computeInitialCrop(hw);
495 activeCrop.intersect(parentCrop, &activeCrop);
496 }
497 Transform t = getTransform();
498 // Back to layer space to work with the content crop.
499 activeCrop = t.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800500
Michael Lentine28ea2172014-11-19 18:32:37 -0800501 // This needs to be here as transform.transform(Rect) computes the
502 // transformed rect and then takes the bounding box of the result before
503 // returning. This means
504 // transform.inverse().transform(transform.transform(Rect)) != Rect
505 // in which case we need to make sure the final rect is clipped to the
506 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000507 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
508 activeCrop.clear();
509 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800510
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700511 // subtract the transparent region and snap to the bounds
512 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
513
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000514 // Transform the window crop to match the buffer coordinate system,
515 // which means using the inverse of the current transform set on the
516 // SurfaceFlingerConsumer.
517 uint32_t invTransform = mCurrentTransform;
Robert Carrcae605c2017-03-29 12:10:31 -0700518 if (getTransformToDisplayInverse()) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000519 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700520 * the code below applies the primary display's inverse transform to the
521 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000522 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700523 uint32_t invTransformOrient =
524 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000525 // calculate the inverse transform
526 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
527 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
528 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800529 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000530 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700531 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
532 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800533 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000534
535 int winWidth = s.active.w;
536 int winHeight = s.active.h;
537 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
538 // If the activeCrop has been rotate the ends are rotated but not
539 // the space itself so when transforming ends back we can't rely on
540 // a modification of the axes of rotation. To account for this we
541 // need to reorient the inverse rotation in terms of the current
542 // axes of rotation.
543 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
544 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
545 if (is_h_flipped == is_v_flipped) {
546 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
547 NATIVE_WINDOW_TRANSFORM_FLIP_H;
548 }
549 winWidth = s.active.h;
550 winHeight = s.active.w;
551 }
552 const Rect winCrop = activeCrop.transform(
553 invTransform, s.active.w, s.active.h);
554
555 // below, crop is intersected with winCrop expressed in crop's coordinate space
556 float xScale = crop.getWidth() / float(winWidth);
557 float yScale = crop.getHeight() / float(winHeight);
558
559 float insetL = winCrop.left * xScale;
560 float insetT = winCrop.top * yScale;
561 float insetR = (winWidth - winCrop.right ) * xScale;
562 float insetB = (winHeight - winCrop.bottom) * yScale;
563
564 crop.left += insetL;
565 crop.top += insetT;
566 crop.right -= insetR;
567 crop.bottom -= insetB;
568
Mathias Agopian13127d82013-03-05 17:47:11 -0800569 return crop;
570}
571
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000572#ifdef USE_HWC2
Robert Carrae060832016-11-28 10:51:00 -0800573void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000574#else
575void Layer::setGeometry(
576 const sp<const DisplayDevice>& hw,
577 HWComposer::HWCLayerInterface& layer)
578#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700579{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000580#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800581 const auto hwcId = displayDevice->getHwcDisplayId();
582 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000583#else
584 layer.setDefaultState();
585#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700586
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700587 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000588#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800589 hwcInfo.forceClientComposition = false;
590
591 if (isSecure() && !displayDevice->isSecure()) {
592 hwcInfo.forceClientComposition = true;
593 }
594
595 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000596#else
597 layer.setSkip(false);
598
599 if (isSecure() && !hw->isSecure()) {
600 layer.setSkip(true);
601 }
602#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700603
Mathias Agopian13127d82013-03-05 17:47:11 -0800604 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700605 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000606#ifdef USE_HWC2
David Revemanecf0fa52017-03-03 11:32:44 -0500607 auto blendMode = HWC2::BlendMode::None;
Robert Carr6452f122017-03-21 10:41:29 -0700608 if (!isOpaque(s) || getAlpha() != 1.0f) {
David Revemanecf0fa52017-03-03 11:32:44 -0500609 blendMode = mPremultipliedAlpha ?
Dan Stoza9e56aa02015-11-02 13:00:03 -0800610 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800611 }
David Revemanecf0fa52017-03-03 11:32:44 -0500612 auto error = hwcLayer->setBlendMode(blendMode);
613 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
614 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
615 to_string(error).c_str(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000616#else
Robert Carr6452f122017-03-21 10:41:29 -0700617 if (!isOpaque(s) || getAlpha() != 0xFF) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000618 layer.setBlending(mPremultipliedAlpha ?
619 HWC_BLENDING_PREMULT :
620 HWC_BLENDING_COVERAGE);
621 }
622#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800623
624 // apply the layer's transform, followed by the display's global transform
625 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700626 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700627 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -0700628 if (!s.crop.isEmpty()) {
629 Rect activeCrop(s.crop);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700630 activeCrop = t.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000631#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000632 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000633#else
634 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
635#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000636 activeCrop.clear();
637 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700638 activeCrop = t.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800639 // This needs to be here as transform.transform(Rect) computes the
640 // transformed rect and then takes the bounding box of the result before
641 // returning. This means
642 // transform.inverse().transform(transform.transform(Rect)) != Rect
643 // in which case we need to make sure the final rect is clipped to the
644 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000645 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
646 activeCrop.clear();
647 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700648 // mark regions outside the crop as transparent
649 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
650 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
651 s.active.w, s.active.h));
652 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
653 activeCrop.left, activeCrop.bottom));
654 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
655 s.active.w, activeCrop.bottom));
656 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700657
658 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700659 if (!s.finalCrop.isEmpty()) {
660 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000661 frame.clear();
662 }
663 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000664#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000665 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
666 frame.clear();
667 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800668 const Transform& tr(displayDevice->getTransform());
669 Rect transformedFrame = tr.transform(frame);
David Revemanecf0fa52017-03-03 11:32:44 -0500670 error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700671 if (error != HWC2::Error::None) {
672 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
673 mName.string(), transformedFrame.left, transformedFrame.top,
674 transformedFrame.right, transformedFrame.bottom,
675 to_string(error).c_str(), static_cast<int32_t>(error));
676 } else {
677 hwcInfo.displayFrame = transformedFrame;
678 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800679
Dan Stoza5a423ea2017-02-16 14:10:39 -0800680 FloatRect sourceCrop = computeCrop(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800681 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700682 if (error != HWC2::Error::None) {
683 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
684 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
685 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
686 static_cast<int32_t>(error));
687 } else {
688 hwcInfo.sourceCrop = sourceCrop;
689 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800690
Robert Carr6452f122017-03-21 10:41:29 -0700691 float alpha = getAlpha();
692 error = hwcLayer->setPlaneAlpha(alpha);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800693 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
Robert Carr6452f122017-03-21 10:41:29 -0700694 "%s (%d)", mName.string(), alpha, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800695 static_cast<int32_t>(error));
696
Robert Carrae060832016-11-28 10:51:00 -0800697 error = hwcLayer->setZOrder(z);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800698 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
Robert Carrae060832016-11-28 10:51:00 -0800699 mName.string(), z, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800700 static_cast<int32_t>(error));
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500701
Albert Chaulk2a589632017-05-04 16:59:44 -0400702 int type = s.type;
703 int appId = s.appId;
704 sp<Layer> parent = mParent.promote();
705 if (parent.get()) {
706 auto& parentState = parent->getDrawingState();
707 type = parentState.type;
708 appId = parentState.appId;
709 }
710
711 error = hwcLayer->setInfo(type, appId);
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500712 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
713 mName.string(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000714#else
715 if (!frame.intersect(hw->getViewport(), &frame)) {
716 frame.clear();
717 }
718 const Transform& tr(hw->getTransform());
719 layer.setFrame(tr.transform(frame));
720 layer.setCrop(computeCrop(hw));
Robert Carr6452f122017-03-21 10:41:29 -0700721 layer.setPlaneAlpha(getAlpha());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000722#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800723
Mathias Agopian29a367b2011-07-12 14:51:45 -0700724 /*
725 * Transformations are applied in this order:
726 * 1) buffer orientation/flip/mirror
727 * 2) state transformation (window manager)
728 * 3) layer orientation (screen orientation)
729 * (NOTE: the matrices are multiplied in reverse order)
730 */
731
732 const Transform bufferOrientation(mCurrentTransform);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700733 Transform transform(tr * t * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700734
Robert Carrcae605c2017-03-29 12:10:31 -0700735 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700736 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700737 * the code below applies the primary display's inverse transform to the
738 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700739 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700740 uint32_t invTransform =
741 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700742 // calculate the inverse transform
743 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
744 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
745 NATIVE_WINDOW_TRANSFORM_FLIP_H;
746 }
Robert Carrcae605c2017-03-29 12:10:31 -0700747
748 /*
749 * Here we cancel out the orientation component of the WM transform.
750 * The scaling and translate components are already included in our bounds
751 * computation so it's enough to just omit it in the composition.
752 * See comment in onDraw with ref to b/36727915 for why.
753 */
754 transform = Transform(invTransform) * tr * bufferOrientation;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700755 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700756
757 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800758 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000759#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800760 if (orientation & Transform::ROT_INVALID) {
761 // we can only handle simple transformation
762 hwcInfo.forceClientComposition = true;
763 } else {
764 auto transform = static_cast<HWC2::Transform>(orientation);
765 auto error = hwcLayer->setTransform(transform);
766 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
767 "%s (%d)", mName.string(), to_string(transform).c_str(),
768 to_string(error).c_str(), static_cast<int32_t>(error));
769 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000770#else
771 if (orientation & Transform::ROT_INVALID) {
772 // we can only handle simple transformation
773 layer.setSkip(true);
774 } else {
775 layer.setTransform(orientation);
776 }
777#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700778}
779
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000780#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800781void Layer::forceClientComposition(int32_t hwcId) {
782 if (mHwcLayers.count(hwcId) == 0) {
783 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
784 return;
785 }
786
787 mHwcLayers[hwcId].forceClientComposition = true;
788}
Dan Stoza9e56aa02015-11-02 13:00:03 -0800789
Dan Stoza9e56aa02015-11-02 13:00:03 -0800790void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
791 // Apply this display's projection's viewport to the visible region
792 // before giving it to the HWC HAL.
793 const Transform& tr = displayDevice->getTransform();
794 const auto& viewport = displayDevice->getViewport();
795 Region visible = tr.transform(visibleRegion.intersect(viewport));
796 auto hwcId = displayDevice->getHwcDisplayId();
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800797 auto& hwcInfo = mHwcLayers[hwcId];
798 auto& hwcLayer = hwcInfo.layer;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800799 auto error = hwcLayer->setVisibleRegion(visible);
800 if (error != HWC2::Error::None) {
801 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
802 to_string(error).c_str(), static_cast<int32_t>(error));
803 visible.dump(LOG_TAG);
804 }
805
806 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
807 if (error != HWC2::Error::None) {
808 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
809 to_string(error).c_str(), static_cast<int32_t>(error));
810 surfaceDamageRegion.dump(LOG_TAG);
811 }
812
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700813 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800814 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700815 setCompositionType(hwcId, HWC2::Composition::Sideband);
816 ALOGV("[%s] Requesting Sideband composition", mName.string());
817 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800818 if (error != HWC2::Error::None) {
819 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
820 mName.string(), mSidebandStream->handle(),
821 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800822 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700823 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800824 }
825
Dan Stoza0a21df72016-07-20 12:52:38 -0700826 // Client layers
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800827 if (hwcInfo.forceClientComposition ||
Dan Stoza0a21df72016-07-20 12:52:38 -0700828 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700829 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800830 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700831 return;
832 }
833
Dan Stoza0a21df72016-07-20 12:52:38 -0700834 // SolidColor layers
835 if (mActiveBuffer == nullptr) {
836 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700837
838 // For now, we only support black for DimLayer
Dan Stoza0a21df72016-07-20 12:52:38 -0700839 error = hwcLayer->setColor({0, 0, 0, 255});
840 if (error != HWC2::Error::None) {
841 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
842 to_string(error).c_str(), static_cast<int32_t>(error));
843 }
Dan Stozac6c89542016-07-27 10:16:52 -0700844
845 // Clear out the transform, because it doesn't make sense absent a
846 // source buffer
847 error = hwcLayer->setTransform(HWC2::Transform::None);
848 if (error != HWC2::Error::None) {
849 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
850 to_string(error).c_str(), static_cast<int32_t>(error));
851 }
852
Dan Stoza0a21df72016-07-20 12:52:38 -0700853 return;
854 }
855
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700856 // Device or Cursor layers
857 if (mPotentialCursor) {
858 ALOGV("[%s] Requesting Cursor composition", mName.string());
859 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800860 } else {
861 ALOGV("[%s] Requesting Device composition", mName.string());
862 setCompositionType(hwcId, HWC2::Composition::Device);
863 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700864
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700865 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
866 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
867 if (error != HWC2::Error::None) {
868 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
869 mCurrentState.dataSpace, to_string(error).c_str(),
870 static_cast<int32_t>(error));
871 }
872
Chia-I Wu06d63de2017-01-04 14:58:51 +0800873 uint32_t hwcSlot = 0;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400874 sp<GraphicBuffer> hwcBuffer;
875 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
876 &hwcSlot, &hwcBuffer);
Chia-I Wu06d63de2017-01-04 14:58:51 +0800877
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700878 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400879 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700880 if (error != HWC2::Error::None) {
881 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
882 mActiveBuffer->handle, to_string(error).c_str(),
883 static_cast<int32_t>(error));
884 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800885}
Courtney Goeltzenleuchter9551fd32016-10-20 17:18:15 -0600886
887android_dataspace Layer::getDataSpace() const {
888 return mCurrentState.dataSpace;
889}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000890#else
891void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
892 HWComposer::HWCLayerInterface& layer) {
893 // we have to set the visible region on every frame because
894 // we currently free it during onLayerDisplayed(), which is called
895 // after HWComposer::commit() -- every frame.
896 // Apply this display's projection's viewport to the visible region
897 // before giving it to the HWC HAL.
898 const Transform& tr = hw->getTransform();
899 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
900 layer.setVisibleRegionScreen(visible);
901 layer.setSurfaceDamage(surfaceDamageRegion);
902 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700903
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000904 if (mSidebandStream.get()) {
905 layer.setSidebandStream(mSidebandStream);
906 } else {
907 // NOTE: buffer can be NULL if the client never drew into this
908 // layer yet, or if we ran out of memory
909 layer.setBuffer(mActiveBuffer);
910 }
911}
912#endif
913
914#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800915void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
916 auto hwcId = displayDevice->getHwcDisplayId();
917 if (mHwcLayers.count(hwcId) == 0 ||
918 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
919 return;
920 }
921
922 // This gives us only the "orientation" component of the transform
923 const State& s(getCurrentState());
924
925 // Apply the layer's transform, followed by the display's global transform
926 // Here we're guaranteed that the layer's transform preserves rects
927 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700928 if (!s.crop.isEmpty()) {
929 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800930 }
931 // Subtract the transparent region and snap to the bounds
932 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700933 Rect frame(getTransform().transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800934 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -0700935 if (!s.finalCrop.isEmpty()) {
936 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000937 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800938 auto& displayTransform(displayDevice->getTransform());
939 auto position = displayTransform.transform(frame);
940
941 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
942 position.top);
943 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
944 "to (%d, %d): %s (%d)", mName.string(), position.left,
945 position.top, to_string(error).c_str(),
946 static_cast<int32_t>(error));
947}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000948#else
949void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
950 HWComposer::HWCLayerInterface& layer) {
951 int fenceFd = -1;
952
953 // TODO: there is a possible optimization here: we only need to set the
954 // acquire fence the first time a new buffer is acquired on EACH display.
955
956 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
957 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
958 if (fence->isValid()) {
959 fenceFd = fence->dup();
960 if (fenceFd == -1) {
961 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
962 }
963 }
964 }
965 layer.setAcquireFenceFd(fenceFd);
966}
967
968Rect Layer::getPosition(
969 const sp<const DisplayDevice>& hw)
970{
971 // this gives us only the "orientation" component of the transform
972 const State& s(getCurrentState());
973
974 // apply the layer's transform, followed by the display's global transform
975 // here we're guaranteed that the layer's transform preserves rects
976 Rect win(s.active.w, s.active.h);
977 if (!s.crop.isEmpty()) {
978 win.intersect(s.crop, &win);
979 }
980 // subtract the transparent region and snap to the bounds
981 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700982 Rect frame(getTransform().transform(bounds));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000983 frame.intersect(hw->getViewport(), &frame);
984 if (!s.finalCrop.isEmpty()) {
985 frame.intersect(s.finalCrop, &frame);
986 }
987 const Transform& tr(hw->getTransform());
988 return Rect(tr.transform(frame));
989}
990#endif
Riley Andrews03414a12014-07-01 14:22:59 -0700991
Mathias Agopian13127d82013-03-05 17:47:11 -0800992// ---------------------------------------------------------------------------
993// drawing...
994// ---------------------------------------------------------------------------
995
996void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -0800997 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -0800998}
999
Dan Stozac7014012014-02-14 15:03:43 -08001000void Layer::draw(const sp<const DisplayDevice>& hw,
1001 bool useIdentityTransform) const {
1002 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001003}
1004
Dan Stozac7014012014-02-14 15:03:43 -08001005void Layer::draw(const sp<const DisplayDevice>& hw) const {
1006 onDraw(hw, Region(hw->bounds()), false);
1007}
1008
Robert Carrcae605c2017-03-29 12:10:31 -07001009static constexpr mat4 inverseOrientation(uint32_t transform) {
1010 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1011 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1012 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1013 mat4 tr;
1014
1015 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1016 tr = tr * rot90;
1017 }
1018 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1019 tr = tr * flipH;
1020 }
1021 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1022 tr = tr * flipV;
1023 }
1024 return inverse(tr);
1025}
1026
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001027/*
1028 * onDraw will draw the current layer onto the presentable buffer
1029 */
Dan Stozac7014012014-02-14 15:03:43 -08001030void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
1031 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001032{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001033 ATRACE_CALL();
1034
Mathias Agopiana67932f2011-04-20 14:20:59 -07001035 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001036 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -07001037 // in fact never been drawn into. This happens frequently with
1038 // SurfaceView because the WindowManager can't know when the client
1039 // has drawn the first time.
1040
1041 // If there is nothing under us, we paint the screen in black, otherwise
1042 // we just skip this update.
1043
1044 // figure out if there is something below us
1045 Region under;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001046 bool finished = false;
Dan Stoza412903f2017-04-27 13:42:17 -07001047 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001048 if (finished || layer == static_cast<Layer const*>(this)) {
1049 finished = true;
1050 return;
1051 }
Mathias Agopian42977342012-08-05 00:40:46 -07001052 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Robert Carr1f0a16a2016-10-24 16:27:39 -07001053 });
Mathias Agopian179169e2010-05-06 20:21:45 -07001054 // if not everything below us is covered, we plug the holes!
1055 Region holes(clip.subtract(under));
1056 if (!holes.isEmpty()) {
Fabien Sanglard17487192016-12-07 13:03:32 -08001057 clearWithOpenGL(hw, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -07001058 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001059 return;
1060 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001061
Andy McFadden97eba892012-12-11 15:21:45 -08001062 // Bind the current buffer to the GL texture, and wait for it to be
1063 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001064 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1065 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -08001066 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -07001067 // Go ahead and draw the buffer anyway; no matter what we do the screen
1068 // is probably going to have something visibly wrong.
1069 }
1070
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001071 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1072
Mathias Agopian875d8e12013-06-07 15:35:48 -07001073 RenderEngine& engine(mFlinger->getRenderEngine());
1074
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001075 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -07001076 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -07001077 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -07001078
1079 // Query the texture matrix given our current filtering mode.
1080 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001081 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1082 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -07001083
Robert Carrcae605c2017-03-29 12:10:31 -07001084 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001085
1086 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -07001087 * the code below applies the primary display's inverse transform to
1088 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001089 */
Pablo Ceballos021623b2016-04-15 17:31:51 -07001090 uint32_t transform =
1091 DisplayDevice::getPrimaryDisplayOrientationTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001092 mat4 tr = inverseOrientation(transform);
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001093
Robert Carrcae605c2017-03-29 12:10:31 -07001094 /**
1095 * TODO(b/36727915): This is basically a hack.
1096 *
1097 * Ensure that regardless of the parent transformation,
1098 * this buffer is always transformed from native display
1099 * orientation to display orientation. For example, in the case
1100 * of a camera where the buffer remains in native orientation,
1101 * we want the pixels to always be upright.
1102 */
1103 if (getParent() != nullptr) {
1104 const auto parentTransform = getParent()->getTransform();
1105 tr = tr * inverseOrientation(parentTransform.getOrientation());
1106 }
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001107
1108 // and finally apply it to the original texture matrix
1109 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1110 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1111 }
1112
Jamie Genniscbb1a952012-05-08 17:05:52 -07001113 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -07001114 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1115 mTexture.setFiltering(useFiltering);
1116 mTexture.setMatrix(textureMatrix);
1117
1118 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -07001119 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001120 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -07001121 }
Fabien Sanglard85789802016-12-07 13:08:24 -08001122 drawWithOpenGL(hw, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001123 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001124}
1125
Mathias Agopian13127d82013-03-05 17:47:11 -08001126
Dan Stozac7014012014-02-14 15:03:43 -08001127void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard17487192016-12-07 13:03:32 -08001128 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -08001129 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001130{
Mathias Agopian19733a32013-08-28 18:13:56 -07001131 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -08001132 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -07001133 engine.setupFillWithColor(red, green, blue, alpha);
1134 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -08001135}
1136
1137void Layer::clearWithOpenGL(
Fabien Sanglard17487192016-12-07 13:03:32 -08001138 const sp<const DisplayDevice>& hw) const {
1139 clearWithOpenGL(hw, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001140}
1141
Dan Stozac7014012014-02-14 15:03:43 -08001142void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard85789802016-12-07 13:08:24 -08001143 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001144 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001145
Dan Stozac7014012014-02-14 15:03:43 -08001146 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001147
Mathias Agopian13127d82013-03-05 17:47:11 -08001148 /*
1149 * NOTE: the way we compute the texture coordinates here produces
1150 * different results than when we take the HWC path -- in the later case
1151 * the "source crop" is rounded to texel boundaries.
1152 * This can produce significantly different results when the texture
1153 * is scaled by a large amount.
1154 *
1155 * The GL code below is more logical (imho), and the difference with
1156 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001157 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001158 * GL composition when a buffer scaling is applied (maybe with some
1159 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1160 * like more of a hack.
1161 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001162 Rect win(computeBounds());
1163
Robert Carr1f0a16a2016-10-24 16:27:39 -07001164 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -07001165 if (!s.finalCrop.isEmpty()) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001166 win = t.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001167 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001168 win.clear();
1169 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001170 win = t.inverse().transform(win);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001171 if (!win.intersect(computeBounds(), &win)) {
1172 win.clear();
1173 }
1174 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001175
Mathias Agopian3f844832013-08-07 21:24:32 -07001176 float left = float(win.left) / float(s.active.w);
1177 float top = float(win.top) / float(s.active.h);
1178 float right = float(win.right) / float(s.active.w);
1179 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001180
Mathias Agopian875d8e12013-06-07 15:35:48 -07001181 // TODO: we probably want to generate the texture coords with the mesh
1182 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001183 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1184 texCoords[0] = vec2(left, 1.0f - top);
1185 texCoords[1] = vec2(left, 1.0f - bottom);
1186 texCoords[2] = vec2(right, 1.0f - bottom);
1187 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001188
Mathias Agopian875d8e12013-06-07 15:35:48 -07001189 RenderEngine& engine(mFlinger->getRenderEngine());
Robert Carr6452f122017-03-21 10:41:29 -07001190 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), getAlpha());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001191#ifdef USE_HWC2
1192 engine.setSourceDataSpace(mCurrentState.dataSpace);
1193#endif
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001194 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001195 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001196}
1197
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001198#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001199void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1200 bool callIntoHwc) {
1201 if (mHwcLayers.count(hwcId) == 0) {
1202 ALOGE("setCompositionType called without a valid HWC layer");
1203 return;
1204 }
1205 auto& hwcInfo = mHwcLayers[hwcId];
1206 auto& hwcLayer = hwcInfo.layer;
1207 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1208 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1209 if (hwcInfo.compositionType != type) {
1210 ALOGV(" actually setting");
1211 hwcInfo.compositionType = type;
1212 if (callIntoHwc) {
1213 auto error = hwcLayer->setCompositionType(type);
1214 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1215 "composition type %s: %s (%d)", mName.string(),
1216 to_string(type).c_str(), to_string(error).c_str(),
1217 static_cast<int32_t>(error));
1218 }
1219 }
1220}
1221
1222HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001223 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1224 // If we're querying the composition type for a display that does not
1225 // have a HWC counterpart, then it will always be Client
1226 return HWC2::Composition::Client;
1227 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001228 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001229 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001230 return HWC2::Composition::Invalid;
1231 }
1232 return mHwcLayers.at(hwcId).compositionType;
1233}
1234
1235void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1236 if (mHwcLayers.count(hwcId) == 0) {
1237 ALOGE("setClearClientTarget called without a valid HWC layer");
1238 return;
1239 }
1240 mHwcLayers[hwcId].clearClientTarget = clear;
1241}
1242
1243bool Layer::getClearClientTarget(int32_t hwcId) const {
1244 if (mHwcLayers.count(hwcId) == 0) {
1245 ALOGE("getClearClientTarget called without a valid HWC layer");
1246 return false;
1247 }
1248 return mHwcLayers.at(hwcId).clearClientTarget;
1249}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001250#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001251
Ruben Brunk1681d952014-06-27 15:51:55 -07001252uint32_t Layer::getProducerStickyTransform() const {
1253 int producerStickyTransform = 0;
1254 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1255 if (ret != OK) {
1256 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1257 strerror(-ret), ret);
1258 return 0;
1259 }
1260 return static_cast<uint32_t>(producerStickyTransform);
1261}
1262
Dan Stozac5da2712016-07-20 15:38:12 -07001263bool Layer::latchUnsignaledBuffers() {
1264 static bool propertyLoaded = false;
1265 static bool latch = false;
1266 static std::mutex mutex;
1267 std::lock_guard<std::mutex> lock(mutex);
1268 if (!propertyLoaded) {
1269 char value[PROPERTY_VALUE_MAX] = {};
1270 property_get("debug.sf.latch_unsignaled", value, "0");
1271 latch = atoi(value);
1272 propertyLoaded = true;
1273 }
1274 return latch;
1275}
1276
Dan Stozacac35382016-01-27 12:21:06 -08001277uint64_t Layer::getHeadFrameNumber() const {
1278 Mutex::Autolock lock(mQueueItemLock);
1279 if (!mQueueItems.empty()) {
1280 return mQueueItems[0].mFrameNumber;
1281 } else {
1282 return mCurrentFrameNumber;
1283 }
1284}
1285
Dan Stoza1ce65812016-06-15 16:26:27 -07001286bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001287#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001288 if (latchUnsignaledBuffers()) {
1289 return true;
1290 }
1291
Dan Stoza1ce65812016-06-15 16:26:27 -07001292 Mutex::Autolock lock(mQueueItemLock);
1293 if (mQueueItems.empty()) {
1294 return true;
1295 }
1296 if (mQueueItems[0].mIsDroppable) {
1297 // Even though this buffer's fence may not have signaled yet, it could
1298 // be replaced by another buffer before it has a chance to, which means
1299 // that it's possible to get into a situation where a buffer is never
1300 // able to be latched. To avoid this, grab this buffer anyway.
1301 return true;
1302 }
1303 return mQueueItems[0].mFence->getSignalTime() != INT64_MAX;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001304#else
1305 return true;
1306#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001307}
1308
Dan Stozacac35382016-01-27 12:21:06 -08001309bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1310 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1311 // Don't bother with a SyncPoint, since we've already latched the
1312 // relevant frame
1313 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001314 }
1315
Dan Stozacac35382016-01-27 12:21:06 -08001316 Mutex::Autolock lock(mLocalSyncPointMutex);
1317 mLocalSyncPoints.push_back(point);
1318 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001319}
1320
Mathias Agopian13127d82013-03-05 17:47:11 -08001321void Layer::setFiltering(bool filtering) {
1322 mFiltering = filtering;
1323}
1324
1325bool Layer::getFiltering() const {
1326 return mFiltering;
1327}
1328
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001329// As documented in libhardware header, formats in the range
1330// 0x100 - 0x1FF are specific to the HAL implementation, and
1331// are known to have no alpha channel
1332// TODO: move definition for device-specific range into
1333// hardware.h, instead of using hard-coded values here.
1334#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1335
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001336bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001337 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1338 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001339 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001340 switch (format) {
1341 case HAL_PIXEL_FORMAT_RGBA_8888:
1342 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001343 case HAL_PIXEL_FORMAT_RGBA_FP16:
Romain Guy541f2262017-02-10 18:50:17 -08001344 case HAL_PIXEL_FORMAT_RGBA_1010102:
Mathias Agopiandd533712013-07-26 15:31:39 -07001345 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001346 }
1347 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001348 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001349}
1350
Mathias Agopian13127d82013-03-05 17:47:11 -08001351// ----------------------------------------------------------------------------
1352// local state
1353// ----------------------------------------------------------------------------
1354
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001355static void boundPoint(vec2* point, const Rect& crop) {
1356 if (point->x < crop.left) {
1357 point->x = crop.left;
1358 }
1359 if (point->x > crop.right) {
1360 point->x = crop.right;
1361 }
1362 if (point->y < crop.top) {
1363 point->y = crop.top;
1364 }
1365 if (point->y > crop.bottom) {
1366 point->y = crop.bottom;
1367 }
1368}
1369
Dan Stozac7014012014-02-14 15:03:43 -08001370void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1371 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001372{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001373 const Layer::State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001374 const Transform hwTransform(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001375 const uint32_t hw_h = hw->getHeight();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001376 Rect win = computeBounds();
Mathias Agopian3f844832013-08-07 21:24:32 -07001377
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001378 vec2 lt = vec2(win.left, win.top);
1379 vec2 lb = vec2(win.left, win.bottom);
1380 vec2 rb = vec2(win.right, win.bottom);
1381 vec2 rt = vec2(win.right, win.top);
1382
Robert Carr1f0a16a2016-10-24 16:27:39 -07001383 Transform layerTransform = getTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001384 if (!useIdentityTransform) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001385 lt = layerTransform.transform(lt);
1386 lb = layerTransform.transform(lb);
1387 rb = layerTransform.transform(rb);
1388 rt = layerTransform.transform(rt);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001389 }
1390
Robert Carrb5d3d262016-03-25 15:08:13 -07001391 if (!s.finalCrop.isEmpty()) {
1392 boundPoint(&lt, s.finalCrop);
1393 boundPoint(&lb, s.finalCrop);
1394 boundPoint(&rb, s.finalCrop);
1395 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001396 }
1397
Mathias Agopianff2ed702013-09-01 21:36:12 -07001398 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001399 position[0] = hwTransform.transform(lt);
1400 position[1] = hwTransform.transform(lb);
1401 position[2] = hwTransform.transform(rb);
1402 position[3] = hwTransform.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001403 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001404 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001405 }
1406}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001407
Andy McFadden4125a4f2014-01-29 17:17:11 -08001408bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001409{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001410 // if we don't have a buffer yet, we're translucent regardless of the
1411 // layer's opaque flag.
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001412 if (mActiveBuffer == 0) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001413 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001414 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001415
1416 // if the layer has the opaque flag, then we're always opaque,
1417 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001418 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001419}
1420
Dan Stoza23116082015-06-18 14:58:39 -07001421bool Layer::isSecure() const
1422{
1423 const Layer::State& s(mDrawingState);
1424 return (s.flags & layer_state_t::eLayerSecure);
1425}
1426
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001427bool Layer::isProtected() const
1428{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001429 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001430 return (activeBuffer != 0) &&
1431 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1432}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001433
Mathias Agopian13127d82013-03-05 17:47:11 -08001434bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001435 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001436}
1437
1438bool Layer::isCropped() const {
1439 return !mCurrentCrop.isEmpty();
1440}
1441
1442bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1443 return mNeedsFiltering || hw->needsFiltering();
1444}
1445
1446void Layer::setVisibleRegion(const Region& visibleRegion) {
1447 // always called from main thread
1448 this->visibleRegion = visibleRegion;
1449}
1450
1451void Layer::setCoveredRegion(const Region& coveredRegion) {
1452 // always called from main thread
1453 this->coveredRegion = coveredRegion;
1454}
1455
1456void Layer::setVisibleNonTransparentRegion(const Region&
1457 setVisibleNonTransparentRegion) {
1458 // always called from main thread
1459 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1460}
1461
1462// ----------------------------------------------------------------------------
1463// transaction
1464// ----------------------------------------------------------------------------
1465
Dan Stoza7dde5992015-05-22 09:51:44 -07001466void Layer::pushPendingState() {
1467 if (!mCurrentState.modified) {
1468 return;
1469 }
1470
Dan Stoza7dde5992015-05-22 09:51:44 -07001471 // If this transaction is waiting on the receipt of a frame, generate a sync
1472 // point and send it to the remote layer.
Robert Carr0d480722017-01-10 16:42:54 -08001473 if (mCurrentState.barrierLayer != nullptr) {
1474 sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1475 if (barrierLayer == nullptr) {
1476 ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
Dan Stoza7dde5992015-05-22 09:51:44 -07001477 // If we can't promote the layer we are intended to wait on,
1478 // then it is expired or otherwise invalid. Allow this transaction
1479 // to be applied as per normal (no synchronization).
Robert Carr0d480722017-01-10 16:42:54 -08001480 mCurrentState.barrierLayer = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001481 } else {
1482 auto syncPoint = std::make_shared<SyncPoint>(
1483 mCurrentState.frameNumber);
Robert Carr0d480722017-01-10 16:42:54 -08001484 if (barrierLayer->addSyncPoint(syncPoint)) {
Dan Stozacac35382016-01-27 12:21:06 -08001485 mRemoteSyncPoints.push_back(std::move(syncPoint));
1486 } else {
1487 // We already missed the frame we're supposed to synchronize
1488 // on, so go ahead and apply the state update
Robert Carr0d480722017-01-10 16:42:54 -08001489 mCurrentState.barrierLayer = nullptr;
Dan Stozacac35382016-01-27 12:21:06 -08001490 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001491 }
1492
Dan Stoza7dde5992015-05-22 09:51:44 -07001493 // Wake us up to check if the frame has been received
1494 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001495 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001496 }
1497 mPendingStates.push_back(mCurrentState);
1498}
1499
Pablo Ceballos05289c22016-04-14 15:49:55 -07001500void Layer::popPendingState(State* stateToCommit) {
1501 auto oldFlags = stateToCommit->flags;
1502 *stateToCommit = mPendingStates[0];
1503 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1504 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001505
1506 mPendingStates.removeAt(0);
1507}
1508
Pablo Ceballos05289c22016-04-14 15:49:55 -07001509bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001510 bool stateUpdateAvailable = false;
1511 while (!mPendingStates.empty()) {
Robert Carr0d480722017-01-10 16:42:54 -08001512 if (mPendingStates[0].barrierLayer != nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001513 if (mRemoteSyncPoints.empty()) {
1514 // If we don't have a sync point for this, apply it anyway. It
1515 // will be visually wrong, but it should keep us from getting
1516 // into too much trouble.
1517 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001518 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001519 stateUpdateAvailable = true;
1520 continue;
1521 }
1522
Dan Stozacac35382016-01-27 12:21:06 -08001523 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1524 mPendingStates[0].frameNumber) {
1525 ALOGE("[%s] Unexpected sync point frame number found",
1526 mName.string());
1527
1528 // Signal our end of the sync point and then dispose of it
1529 mRemoteSyncPoints.front()->setTransactionApplied();
1530 mRemoteSyncPoints.pop_front();
1531 continue;
1532 }
1533
Dan Stoza7dde5992015-05-22 09:51:44 -07001534 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1535 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001536 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001537 stateUpdateAvailable = true;
1538
1539 // Signal our end of the sync point and then dispose of it
1540 mRemoteSyncPoints.front()->setTransactionApplied();
1541 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001542 } else {
1543 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001544 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001545 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001546 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001547 stateUpdateAvailable = true;
1548 }
1549 }
1550
1551 // If we still have pending updates, wake SurfaceFlinger back up and point
1552 // it at this layer so we can process them
1553 if (!mPendingStates.empty()) {
1554 setTransactionFlags(eTransactionNeeded);
1555 mFlinger->setTransactionFlags(eTraversalNeeded);
1556 }
1557
1558 mCurrentState.modified = false;
1559 return stateUpdateAvailable;
1560}
1561
1562void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001563 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001564 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001565 Mutex::Autolock lock(mLocalSyncPointMutex);
1566 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001567 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001568 point->setFrameAvailable();
1569 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001570 }
1571}
1572
Mathias Agopian13127d82013-03-05 17:47:11 -08001573uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001574 ATRACE_CALL();
1575
Dan Stoza7dde5992015-05-22 09:51:44 -07001576 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001577 Layer::State c = getCurrentState();
1578 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001579 return 0;
1580 }
1581
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001582 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001583
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001584 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1585 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001586
1587 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001588 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001589 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001590 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001591 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001592 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001593 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001594 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001595 this, getName().string(), mCurrentTransform,
1596 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001597 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001598 c.crop.left,
1599 c.crop.top,
1600 c.crop.right,
1601 c.crop.bottom,
1602 c.crop.getWidth(),
1603 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001604 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001605 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001606 s.crop.left,
1607 s.crop.top,
1608 s.crop.right,
1609 s.crop.bottom,
1610 s.crop.getWidth(),
1611 s.crop.getHeight(),
1612 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001613
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001614 // record the new size, form this point on, when the client request
1615 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001616 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001617 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001618 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001619
Robert Carr82364e32016-05-15 11:27:47 -07001620 const bool resizePending = (c.requested.w != c.active.w) ||
1621 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001622 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001623 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001624 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001625 // if we have a pending resize, unless we are in fixed-size mode.
1626 // the drawing state will be updated only once we receive a buffer
1627 // with the correct size.
1628 //
1629 // in particular, we want to make sure the clip (which is part
1630 // of the geometry state) is latched together with the size but is
1631 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001632 //
1633 // If a sideband stream is attached, however, we want to skip this
1634 // optimization so that transactions aren't missed when a buffer
1635 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001636
1637 flags |= eDontUpdateGeometryState;
1638 }
1639 }
1640
Robert Carr1e079c22017-05-09 12:16:54 -07001641 // Here we apply various requested geometry states, depending on our
1642 // latching configuration. See Layer.h for a detailed discussion of
1643 // how geometry latching is controlled.
1644 if (!(flags & eDontUpdateGeometryState)) {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001645 Layer::State& editCurrentState(getCurrentState());
Robert Carr1e079c22017-05-09 12:16:54 -07001646
1647 // If mFreezeGeometryUpdates is true we are in the setGeometryAppliesWithResize
1648 // mode, which causes attributes which normally latch regardless of scaling mode,
1649 // to be delayed. We copy the requested state to the active state making sure
1650 // to respect these rules (again see Layer.h for a detailed discussion).
1651 //
1652 // There is an awkward asymmetry in the handling of the crop states in the position
1653 // states, as can be seen below. Largely this arises from position and transform
1654 // being stored in the same data structure while having different latching rules.
1655 // b/38182305
1656 //
1657 // Careful that "c" and editCurrentState may not begin as equivalent due to
1658 // applyPendingStates in the presence of deferred transactions.
1659 if (mFreezeGeometryUpdates) {
Robert Carr82364e32016-05-15 11:27:47 -07001660 float tx = c.active.transform.tx();
1661 float ty = c.active.transform.ty();
1662 c.active = c.requested;
1663 c.active.transform.set(tx, ty);
1664 editCurrentState.active = c.active;
1665 } else {
1666 editCurrentState.active = editCurrentState.requested;
1667 c.active = c.requested;
Robert Carr1e079c22017-05-09 12:16:54 -07001668 if (c.crop != c.requestedCrop ||
1669 c.finalCrop != c.requestedFinalCrop) {
1670 c.sequence++;
1671 c.crop = c.requestedCrop;
1672 c.finalCrop = c.requestedFinalCrop;
1673 editCurrentState.crop = c.crop;
1674 editCurrentState.finalCrop = c.finalCrop;
1675 }
Robert Carr82364e32016-05-15 11:27:47 -07001676 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001677 }
1678
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001679 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001680 // invalidate and recompute the visible regions if needed
1681 flags |= Layer::eVisibleRegion;
1682 }
1683
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001684 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001685 // invalidate and recompute the visible regions if needed
1686 flags |= eVisibleRegion;
1687 this->contentDirty = true;
1688
1689 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001690 const uint8_t type = c.active.transform.getType();
1691 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001692 (type >= Transform::SCALE));
1693 }
1694
Dan Stozac8145172016-04-28 16:29:06 -07001695 // If the layer is hidden, signal and clear out all local sync points so
1696 // that transactions for layers depending on this layer's frames becoming
1697 // visible are not blocked
1698 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001699 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001700 }
1701
Mathias Agopian13127d82013-03-05 17:47:11 -08001702 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001703 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001704 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001705}
1706
Pablo Ceballos05289c22016-04-14 15:49:55 -07001707void Layer::commitTransaction(const State& stateToCommit) {
1708 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001709}
1710
Mathias Agopian13127d82013-03-05 17:47:11 -08001711uint32_t Layer::getTransactionFlags(uint32_t flags) {
1712 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1713}
1714
1715uint32_t Layer::setTransactionFlags(uint32_t flags) {
1716 return android_atomic_or(flags, &mTransactionFlags);
1717}
1718
Robert Carr82364e32016-05-15 11:27:47 -07001719bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001720 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001721 return false;
1722 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001723
1724 // We update the requested and active position simultaneously because
1725 // we want to apply the position portion of the transform matrix immediately,
1726 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001727 mCurrentState.requested.transform.set(x, y);
Robert Carr1e079c22017-05-09 12:16:54 -07001728 if (immediate && !mFreezeGeometryUpdates) {
1729 // Here we directly update the active state
1730 // unlike other setters, because we store it within
1731 // the transform, but use different latching rules.
1732 // b/38182305
Robert Carr82364e32016-05-15 11:27:47 -07001733 mCurrentState.active.transform.set(x, y);
1734 }
Robert Carr1e079c22017-05-09 12:16:54 -07001735 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001736
Dan Stoza7dde5992015-05-22 09:51:44 -07001737 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001738 setTransactionFlags(eTransactionNeeded);
1739 return true;
1740}
Robert Carr82364e32016-05-15 11:27:47 -07001741
Robert Carr1f0a16a2016-10-24 16:27:39 -07001742bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1743 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1744 if (idx < 0) {
1745 return false;
1746 }
1747 if (childLayer->setLayer(z)) {
1748 mCurrentChildren.removeAt(idx);
1749 mCurrentChildren.add(childLayer);
1750 }
1751 return true;
1752}
1753
Robert Carrae060832016-11-28 10:51:00 -08001754bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001755 if (mCurrentState.z == z)
1756 return false;
1757 mCurrentState.sequence++;
1758 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001759 mCurrentState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001760
1761 // Discard all relative layering.
1762 if (mCurrentState.zOrderRelativeOf != nullptr) {
1763 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1764 if (strongRelative != nullptr) {
1765 strongRelative->removeZOrderRelative(this);
1766 }
1767 mCurrentState.zOrderRelativeOf = nullptr;
1768 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001769 setTransactionFlags(eTransactionNeeded);
1770 return true;
1771}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001772
Robert Carrdb66e622017-04-10 16:55:57 -07001773void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1774 mCurrentState.zOrderRelatives.remove(relative);
1775 mCurrentState.sequence++;
1776 mCurrentState.modified = true;
1777 setTransactionFlags(eTransactionNeeded);
1778}
1779
1780void Layer::addZOrderRelative(const wp<Layer>& relative) {
1781 mCurrentState.zOrderRelatives.add(relative);
1782 mCurrentState.modified = true;
1783 mCurrentState.sequence++;
1784 setTransactionFlags(eTransactionNeeded);
1785}
1786
1787bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1788 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1789 if (handle == nullptr) {
1790 return false;
1791 }
1792 sp<Layer> relative = handle->owner.promote();
1793 if (relative == nullptr) {
1794 return false;
1795 }
1796
1797 mCurrentState.sequence++;
1798 mCurrentState.modified = true;
1799 mCurrentState.z = z;
1800
1801 mCurrentState.zOrderRelativeOf = relative;
1802 relative->addZOrderRelative(this);
1803
1804 setTransactionFlags(eTransactionNeeded);
1805
1806 return true;
1807}
1808
Mathias Agopian13127d82013-03-05 17:47:11 -08001809bool Layer::setSize(uint32_t w, uint32_t h) {
1810 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1811 return false;
1812 mCurrentState.requested.w = w;
1813 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001814 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001815 setTransactionFlags(eTransactionNeeded);
1816 return true;
1817}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001818#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001819bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001820#else
1821bool Layer::setAlpha(uint8_t alpha) {
1822#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001823 if (mCurrentState.alpha == alpha)
1824 return false;
1825 mCurrentState.sequence++;
1826 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001827 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001828 setTransactionFlags(eTransactionNeeded);
1829 return true;
1830}
1831bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1832 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001833 mCurrentState.requested.transform.set(
Robert Carrcb6e1e32017-02-21 19:48:26 -08001834 matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001835 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001836 setTransactionFlags(eTransactionNeeded);
1837 return true;
1838}
1839bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001840 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001841 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001842 setTransactionFlags(eTransactionNeeded);
1843 return true;
1844}
1845bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1846 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1847 if (mCurrentState.flags == newFlags)
1848 return false;
1849 mCurrentState.sequence++;
1850 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001851 mCurrentState.mask = mask;
1852 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001853 setTransactionFlags(eTransactionNeeded);
1854 return true;
1855}
Robert Carr99e27f02016-06-16 15:18:02 -07001856
1857bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carr1e079c22017-05-09 12:16:54 -07001858 if (mCurrentState.requestedCrop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001859 return false;
1860 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001861 mCurrentState.requestedCrop = crop;
Robert Carr1e079c22017-05-09 12:16:54 -07001862 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr99e27f02016-06-16 15:18:02 -07001863 mCurrentState.crop = crop;
1864 }
Robert Carr1e079c22017-05-09 12:16:54 -07001865 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1866
Dan Stoza7dde5992015-05-22 09:51:44 -07001867 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001868 setTransactionFlags(eTransactionNeeded);
1869 return true;
1870}
Robert Carr8d5227b2017-03-16 15:41:03 -07001871
1872bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
Robert Carr1e079c22017-05-09 12:16:54 -07001873 if (mCurrentState.requestedFinalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001874 return false;
1875 mCurrentState.sequence++;
Robert Carr8d5227b2017-03-16 15:41:03 -07001876 mCurrentState.requestedFinalCrop = crop;
Robert Carr1e079c22017-05-09 12:16:54 -07001877 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr8d5227b2017-03-16 15:41:03 -07001878 mCurrentState.finalCrop = crop;
1879 }
Robert Carr1e079c22017-05-09 12:16:54 -07001880 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1881
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001882 mCurrentState.modified = true;
1883 setTransactionFlags(eTransactionNeeded);
1884 return true;
1885}
Mathias Agopian13127d82013-03-05 17:47:11 -08001886
Robert Carrc3574f72016-03-24 12:19:32 -07001887bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1888 if (scalingMode == mOverrideScalingMode)
1889 return false;
1890 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001891 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001892 return true;
1893}
1894
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001895void Layer::setInfo(uint32_t type, uint32_t appId) {
1896 mCurrentState.appId = appId;
1897 mCurrentState.type = type;
1898 mCurrentState.modified = true;
1899 setTransactionFlags(eTransactionNeeded);
1900}
1901
Robert Carrc3574f72016-03-24 12:19:32 -07001902uint32_t Layer::getEffectiveScalingMode() const {
1903 if (mOverrideScalingMode >= 0) {
1904 return mOverrideScalingMode;
1905 }
1906 return mCurrentScalingMode;
1907}
1908
Mathias Agopian13127d82013-03-05 17:47:11 -08001909bool Layer::setLayerStack(uint32_t layerStack) {
1910 if (mCurrentState.layerStack == layerStack)
1911 return false;
1912 mCurrentState.sequence++;
1913 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001914 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001915 setTransactionFlags(eTransactionNeeded);
1916 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001917}
1918
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07001919bool Layer::setDataSpace(android_dataspace dataSpace) {
1920 if (mCurrentState.dataSpace == dataSpace)
1921 return false;
1922 mCurrentState.sequence++;
1923 mCurrentState.dataSpace = dataSpace;
1924 mCurrentState.modified = true;
1925 setTransactionFlags(eTransactionNeeded);
1926 return true;
1927}
1928
Robert Carr1f0a16a2016-10-24 16:27:39 -07001929uint32_t Layer::getLayerStack() const {
1930 auto p = getParent();
1931 if (p == nullptr) {
1932 return getDrawingState().layerStack;
1933 }
1934 return p->getLayerStack();
1935}
1936
Robert Carr0d480722017-01-10 16:42:54 -08001937void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
Dan Stoza7dde5992015-05-22 09:51:44 -07001938 uint64_t frameNumber) {
Robert Carr0d480722017-01-10 16:42:54 -08001939 mCurrentState.barrierLayer = barrierLayer;
Dan Stoza7dde5992015-05-22 09:51:44 -07001940 mCurrentState.frameNumber = frameNumber;
1941 // We don't set eTransactionNeeded, because just receiving a deferral
1942 // request without any other state updates shouldn't actually induce a delay
1943 mCurrentState.modified = true;
1944 pushPendingState();
Robert Carr0d480722017-01-10 16:42:54 -08001945 mCurrentState.barrierLayer = nullptr;
Dan Stoza792e5292016-02-11 11:43:58 -08001946 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07001947 mCurrentState.modified = false;
Robert Carr0d480722017-01-10 16:42:54 -08001948 ALOGE("Deferred transaction");
1949}
1950
1951void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
1952 uint64_t frameNumber) {
1953 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
1954 deferTransactionUntil(handle->owner.promote(), frameNumber);
Dan Stoza7dde5992015-05-22 09:51:44 -07001955}
1956
Dan Stozaee44edd2015-03-23 15:50:23 -07001957void Layer::useSurfaceDamage() {
1958 if (mFlinger->mForceFullDamage) {
1959 surfaceDamageRegion = Region::INVALID_REGION;
1960 } else {
1961 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1962 }
1963}
1964
1965void Layer::useEmptyDamage() {
1966 surfaceDamageRegion.clear();
1967}
1968
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001969// ----------------------------------------------------------------------------
1970// pageflip handling...
1971// ----------------------------------------------------------------------------
1972
Dan Stoza6b9454d2014-11-07 16:00:59 -08001973bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001974 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07001975 return true;
1976 }
1977
Dan Stoza6b9454d2014-11-07 16:00:59 -08001978 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001979 if (mQueueItems.empty()) {
1980 return false;
1981 }
1982 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001983 nsecs_t expectedPresent =
1984 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001985
1986 // Ignore timestamps more than a second in the future
1987 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1988 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1989 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1990 expectedPresent);
1991
1992 bool isDue = timestamp < expectedPresent;
1993 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001994}
1995
Brian Andersond6927fb2016-07-23 23:37:30 -07001996bool Layer::onPreComposition(nsecs_t refreshStartTime) {
1997 if (mBufferLatched) {
1998 Mutex::Autolock lock(mFrameEventHistoryMutex);
1999 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
2000 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08002001 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08002002 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002003}
2004
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002005bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
Brian Anderson3d4039d2016-09-23 16:31:30 -07002006 const std::shared_ptr<FenceTime>& presentFence,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002007 const CompositorTiming& compositorTiming) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002008 mAcquireTimeline.updateSignalTimes();
2009 mReleaseTimeline.updateSignalTimes();
2010
Brian Andersond6927fb2016-07-23 23:37:30 -07002011 // mFrameLatencyNeeded is true when a new frame was latched for the
2012 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08002013 if (!mFrameLatencyNeeded)
2014 return false;
2015
Fabien Sanglard28e98082016-12-05 10:19:46 -08002016 // Update mFrameEventHistory.
2017 {
2018 Mutex::Autolock lock(mFrameEventHistoryMutex);
2019 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002020 glDoneFence, presentFence, compositorTiming);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002021 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08002022
2023 // Update mFrameTracker.
2024 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
2025 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
2026
Brian Anderson3d4039d2016-09-23 16:31:30 -07002027 std::shared_ptr<FenceTime> frameReadyFence =
2028 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08002029 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002030 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002031 } else {
2032 // There was no fence for this frame, so assume that it was ready
2033 // to be presented at the desired present time.
2034 mFrameTracker.setFrameReadyTime(desiredPresentTime);
2035 }
2036
Brian Anderson3d4039d2016-09-23 16:31:30 -07002037 if (presentFence->isValid()) {
2038 mFrameTracker.setActualPresentFence(
2039 std::shared_ptr<FenceTime>(presentFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002040 } else {
2041 // The HWC doesn't support present fences, so use the refresh
2042 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002043 mFrameTracker.setActualPresentTime(
2044 mFlinger->getHwComposer().getRefreshTimestamp(
2045 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002046 }
2047
2048 mFrameTracker.advanceFrame();
2049 mFrameLatencyNeeded = false;
2050 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002051}
2052
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002053#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07002054void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Brian Anderson5ea5e592016-12-01 16:54:33 -08002055 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2056 return;
2057 }
2058
Brian Anderson3d4039d2016-09-23 16:31:30 -07002059 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002060 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002061 mReleaseTimeline.push(releaseFenceTime);
2062
2063 Mutex::Autolock lock(mFrameEventHistoryMutex);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002064 if (mPreviousFrameNumber != 0) {
2065 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2066 dequeueReadyTime, std::move(releaseFenceTime));
2067 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002068}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002069#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002070
Robert Carr1f0a16a2016-10-24 16:27:39 -07002071bool Layer::isHiddenByPolicy() const {
2072 const Layer::State& s(mDrawingState);
2073 const auto& parent = getParent();
2074 if (parent != nullptr && parent->isHiddenByPolicy()) {
2075 return true;
2076 }
2077 return s.flags & layer_state_t::eLayerHidden;
2078}
2079
Mathias Agopianda27af92012-09-13 18:17:13 -07002080bool Layer::isVisible() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002081#ifdef USE_HWC2
Robert Carr6452f122017-03-21 10:41:29 -07002082 return !(isHiddenByPolicy()) && getAlpha() > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08002083 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002084#else
Robert Carr6452f122017-03-21 10:41:29 -07002085 return !(isHiddenByPolicy()) && getAlpha()
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002086 && (mActiveBuffer != NULL || mSidebandStream != NULL);
2087#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07002088}
2089
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002090bool Layer::allTransactionsSignaled() {
2091 auto headFrameNumber = getHeadFrameNumber();
2092 bool matchingFramesFound = false;
2093 bool allTransactionsApplied = true;
2094 Mutex::Autolock lock(mLocalSyncPointMutex);
2095
2096 for (auto& point : mLocalSyncPoints) {
2097 if (point->getFrameNumber() > headFrameNumber) {
2098 break;
2099 }
2100 matchingFramesFound = true;
2101
2102 if (!point->frameIsAvailable()) {
2103 // We haven't notified the remote layer that the frame for
2104 // this point is available yet. Notify it now, and then
2105 // abort this attempt to latch.
2106 point->setFrameAvailable();
2107 allTransactionsApplied = false;
2108 break;
2109 }
2110
2111 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2112 }
2113 return !matchingFramesFound || allTransactionsApplied;
2114}
2115
Brian Andersond6927fb2016-07-23 23:37:30 -07002116Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002117{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08002118 ATRACE_CALL();
2119
Jesse Hall399184a2014-03-03 15:42:54 -08002120 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2121 // mSidebandStreamChanged was true
2122 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07002123 if (mSidebandStream != NULL) {
2124 setTransactionFlags(eTransactionNeeded);
2125 mFlinger->setTransactionFlags(eTraversalNeeded);
2126 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07002127 recomputeVisibleRegions = true;
2128
2129 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07002130 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08002131 }
2132
Mathias Agopian4fec8732012-06-29 14:12:52 -07002133 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07002134 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2135 return outDirtyRegion;
2136 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002137
Fabien Sanglard223eb912016-10-13 10:15:06 -07002138 // if we've already called updateTexImage() without going through
2139 // a composition step, we have to skip this layer at this point
2140 // because we cannot call updateTeximage() without a corresponding
2141 // compositionComplete() call.
2142 // we'll trigger an update in onPreComposition().
2143 if (mRefreshPending) {
2144 return outDirtyRegion;
2145 }
2146
2147 // If the head buffer's acquire fence hasn't signaled yet, return and
2148 // try again later
2149 if (!headFenceHasSignaled()) {
2150 mFlinger->signalLayerUpdate();
2151 return outDirtyRegion;
2152 }
2153
2154 // Capture the old state of the layer for comparisons later
2155 const State& s(getDrawingState());
2156 const bool oldOpacity = isOpaque(s);
2157 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2158
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002159 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002160 mFlinger->signalLayerUpdate();
2161 return outDirtyRegion;
2162 }
2163
2164 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2165 // of the buffer queue isn't modified when the buffer queue is returning
2166 // BufferItem's that weren't actually queued. This can happen in shared
2167 // buffer mode.
2168 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002169 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2170 getProducerStickyTransform() != 0, mName.string(),
Robert Carr1e079c22017-05-09 12:16:54 -07002171 mOverrideScalingMode, mFreezeGeometryUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002172 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2173 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2174 mLastFrameNumberReceived);
2175 if (updateResult == BufferQueue::PRESENT_LATER) {
2176 // Producer doesn't want buffer to be displayed yet. Signal a
2177 // layer update so we check again at the next opportunity.
2178 mFlinger->signalLayerUpdate();
2179 return outDirtyRegion;
2180 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2181 // If the buffer has been rejected, remove it from the shadow queue
2182 // and return early
2183 if (queuedBuffer) {
2184 Mutex::Autolock lock(mQueueItemLock);
2185 mQueueItems.removeAt(0);
2186 android_atomic_dec(&mQueuedFrames);
2187 }
2188 return outDirtyRegion;
2189 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2190 // This can occur if something goes wrong when trying to create the
2191 // EGLImage for this buffer. If this happens, the buffer has already
2192 // been released, so we need to clean up the queue and bug out
2193 // early.
2194 if (queuedBuffer) {
2195 Mutex::Autolock lock(mQueueItemLock);
2196 mQueueItems.clear();
2197 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002198 }
2199
Fabien Sanglard223eb912016-10-13 10:15:06 -07002200 // Once we have hit this state, the shadow queue may no longer
2201 // correctly reflect the incoming BufferQueue's contents, so even if
2202 // updateTexImage starts working, the only safe course of action is
2203 // to continue to ignore updates.
2204 mUpdateTexImageFailed = true;
2205
2206 return outDirtyRegion;
2207 }
2208
2209 if (queuedBuffer) {
2210 // Autolock scope
2211 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2212
2213 Mutex::Autolock lock(mQueueItemLock);
2214
2215 // Remove any stale buffers that have been dropped during
2216 // updateTexImage
2217 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2218 mQueueItems.removeAt(0);
2219 android_atomic_dec(&mQueuedFrames);
2220 }
2221
2222 mQueueItems.removeAt(0);
2223 }
2224
2225
2226 // Decrement the queued-frames count. Signal another event if we
2227 // have more frames pending.
2228 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2229 || mAutoRefresh) {
2230 mFlinger->signalLayerUpdate();
2231 }
2232
Fabien Sanglard223eb912016-10-13 10:15:06 -07002233 // update the active buffer
Chia-I Wu06d63de2017-01-04 14:58:51 +08002234 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2235 &mActiveBufferSlot);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002236 if (mActiveBuffer == NULL) {
2237 // this can only happen if the very first buffer was rejected.
2238 return outDirtyRegion;
2239 }
2240
Brian Andersond6927fb2016-07-23 23:37:30 -07002241 mBufferLatched = true;
2242 mPreviousFrameNumber = mCurrentFrameNumber;
2243 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2244
2245 {
2246 Mutex::Autolock lock(mFrameEventHistoryMutex);
2247 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2248#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002249 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002250 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002251 mReleaseTimeline.push(releaseFenceTime);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002252 if (mPreviousFrameNumber != 0) {
2253 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2254 latchTime, std::move(releaseFenceTime));
2255 }
Brian Andersond6927fb2016-07-23 23:37:30 -07002256#endif
2257 }
2258
Fabien Sanglard223eb912016-10-13 10:15:06 -07002259 mRefreshPending = true;
2260 mFrameLatencyNeeded = true;
2261 if (oldActiveBuffer == NULL) {
2262 // the first time we receive a buffer, we need to trigger a
2263 // geometry invalidation.
2264 recomputeVisibleRegions = true;
2265 }
2266
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002267 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2268
Fabien Sanglard223eb912016-10-13 10:15:06 -07002269 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2270 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2271 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2272 if ((crop != mCurrentCrop) ||
2273 (transform != mCurrentTransform) ||
2274 (scalingMode != mCurrentScalingMode))
2275 {
2276 mCurrentCrop = crop;
2277 mCurrentTransform = transform;
2278 mCurrentScalingMode = scalingMode;
2279 recomputeVisibleRegions = true;
2280 }
2281
2282 if (oldActiveBuffer != NULL) {
2283 uint32_t bufWidth = mActiveBuffer->getWidth();
2284 uint32_t bufHeight = mActiveBuffer->getHeight();
2285 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2286 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002287 recomputeVisibleRegions = true;
2288 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002289 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002290
Fabien Sanglard223eb912016-10-13 10:15:06 -07002291 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2292 if (oldOpacity != isOpaque(s)) {
2293 recomputeVisibleRegions = true;
2294 }
Dan Stozacac35382016-01-27 12:21:06 -08002295
Fabien Sanglard223eb912016-10-13 10:15:06 -07002296 // Remove any sync points corresponding to the buffer which was just
2297 // latched
2298 {
2299 Mutex::Autolock lock(mLocalSyncPointMutex);
2300 auto point = mLocalSyncPoints.begin();
2301 while (point != mLocalSyncPoints.end()) {
2302 if (!(*point)->frameIsAvailable() ||
2303 !(*point)->transactionIsApplied()) {
2304 // This sync point must have been added since we started
2305 // latching. Don't drop it yet.
2306 ++point;
2307 continue;
2308 }
2309
2310 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2311 point = mLocalSyncPoints.erase(point);
2312 } else {
2313 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002314 }
2315 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002316 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002317
2318 // FIXME: postedRegion should be dirty & bounds
2319 Region dirtyRegion(Rect(s.active.w, s.active.h));
2320
2321 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002322 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002323
Mathias Agopian4fec8732012-06-29 14:12:52 -07002324 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002325}
2326
Mathias Agopiana67932f2011-04-20 14:20:59 -07002327uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002328{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002329 // TODO: should we do something special if mSecure is set?
2330 if (mProtectedByApp) {
2331 // need a hardware-protected path to external video sink
2332 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002333 }
Riley Andrews03414a12014-07-01 14:22:59 -07002334 if (mPotentialCursor) {
2335 usage |= GraphicBuffer::USAGE_CURSOR;
2336 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002337 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002338 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002339}
2340
Mathias Agopian84300952012-11-21 16:02:13 -08002341void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002342 uint32_t orientation = 0;
2343 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002344 // The transform hint is used to improve performance, but we can
2345 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002346 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002347 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002348 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002349 if (orientation & Transform::ROT_INVALID) {
2350 orientation = 0;
2351 }
2352 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002353 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002354}
2355
Mathias Agopian13127d82013-03-05 17:47:11 -08002356// ----------------------------------------------------------------------------
2357// debugging
2358// ----------------------------------------------------------------------------
2359
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002360void Layer::dump(String8& result, Colorizer& colorizer) const
Mathias Agopian13127d82013-03-05 17:47:11 -08002361{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002362 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08002363
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002364 colorizer.colorize(result, Colorizer::GREEN);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002365 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002366 "+ %s %p (%s)\n",
2367 getTypeId(), this, getName().string());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002368 colorizer.reset(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002369
Mathias Agopian2ca79392013-04-02 18:30:32 -07002370 s.activeTransparentRegion.dump(result, "transparentRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002371 visibleRegion.dump(result, "visibleRegion");
Dan Stozaee44edd2015-03-23 15:50:23 -07002372 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002373 sp<Client> client(mClientRef.promote());
2374
Mathias Agopian74d211a2013-04-22 16:55:35 +02002375 result.appendFormat( " "
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002376 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2377 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
Mathias Agopian13127d82013-03-05 17:47:11 -08002378 "isOpaque=%1d, invalidate=%1d, "
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002379#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08002380 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002381#else
2382 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2383#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08002384 " client=%p\n",
Robert Carr1f0a16a2016-10-24 16:27:39 -07002385 getLayerStack(), s.z,
2386 s.active.transform.tx(), s.active.transform.ty(),
2387 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07002388 s.crop.left, s.crop.top,
2389 s.crop.right, s.crop.bottom,
2390 s.finalCrop.left, s.finalCrop.top,
2391 s.finalCrop.right, s.finalCrop.bottom,
Andy McFadden4125a4f2014-01-29 17:17:11 -08002392 isOpaque(s), contentDirty,
Mathias Agopian13127d82013-03-05 17:47:11 -08002393 s.alpha, s.flags,
Robert Carr3dcabfa2016-03-01 18:36:58 -08002394 s.active.transform[0][0], s.active.transform[0][1],
2395 s.active.transform[1][0], s.active.transform[1][1],
Mathias Agopian13127d82013-03-05 17:47:11 -08002396 client.get());
Mathias Agopian13127d82013-03-05 17:47:11 -08002397
2398 sp<const GraphicBuffer> buf0(mActiveBuffer);
2399 uint32_t w0=0, h0=0, s0=0, f0=0;
2400 if (buf0 != 0) {
2401 w0 = buf0->getWidth();
2402 h0 = buf0->getHeight();
2403 s0 = buf0->getStride();
2404 f0 = buf0->format;
2405 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02002406 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002407 " "
2408 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2409 " queued-frames=%d, mRefreshPending=%d\n",
2410 mFormat, w0, h0, s0,f0,
2411 mQueuedFrames, mRefreshPending);
2412
Mathias Agopian13127d82013-03-05 17:47:11 -08002413 if (mSurfaceFlingerConsumer != 0) {
Colin Cross3d1d2802016-09-26 18:10:16 -07002414 mSurfaceFlingerConsumer->dumpState(result, " ");
Mathias Agopian13127d82013-03-05 17:47:11 -08002415 }
2416}
2417
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002418#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002419void Layer::miniDumpHeader(String8& result) {
2420 result.append("----------------------------------------");
2421 result.append("---------------------------------------\n");
2422 result.append(" Layer name\n");
2423 result.append(" Z | ");
2424 result.append(" Comp Type | ");
2425 result.append(" Disp Frame (LTRB) | ");
2426 result.append(" Source Crop (LTRB)\n");
2427 result.append("----------------------------------------");
2428 result.append("---------------------------------------\n");
2429}
2430
2431void Layer::miniDump(String8& result, int32_t hwcId) const {
2432 if (mHwcLayers.count(hwcId) == 0) {
2433 return;
2434 }
2435
2436 String8 name;
2437 if (mName.length() > 77) {
2438 std::string shortened;
2439 shortened.append(mName.string(), 36);
2440 shortened.append("[...]");
2441 shortened.append(mName.string() + (mName.length() - 36), 36);
2442 name = shortened.c_str();
2443 } else {
2444 name = mName;
2445 }
2446
2447 result.appendFormat(" %s\n", name.string());
2448
2449 const Layer::State& layerState(getDrawingState());
2450 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2451 result.appendFormat(" %10u | ", layerState.z);
2452 result.appendFormat("%10s | ",
2453 to_string(getCompositionType(hwcId)).c_str());
2454 const Rect& frame = hwcInfo.displayFrame;
2455 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2456 frame.right, frame.bottom);
Dan Stoza5a423ea2017-02-16 14:10:39 -08002457 const FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002458 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2459 crop.right, crop.bottom);
2460
2461 result.append("- - - - - - - - - - - - - - - - - - - - ");
2462 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2463}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002464#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002465
Svetoslavd85084b2014-03-20 10:28:31 -07002466void Layer::dumpFrameStats(String8& result) const {
2467 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002468}
2469
Svetoslavd85084b2014-03-20 10:28:31 -07002470void Layer::clearFrameStats() {
2471 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002472}
2473
Jamie Gennis6547ff42013-07-16 20:12:42 -07002474void Layer::logFrameStats() {
2475 mFrameTracker.logAndResetStats(mName);
2476}
2477
Svetoslavd85084b2014-03-20 10:28:31 -07002478void Layer::getFrameStats(FrameStats* outStats) const {
2479 mFrameTracker.getStats(outStats);
2480}
2481
Brian Andersond6927fb2016-07-23 23:37:30 -07002482void Layer::dumpFrameEvents(String8& result) {
2483 result.appendFormat("- Layer %s (%s, %p)\n",
2484 getName().string(), getTypeId(), this);
2485 Mutex::Autolock lock(mFrameEventHistoryMutex);
2486 mFrameEventHistory.checkFencesForCompletion();
2487 mFrameEventHistory.dump(result);
2488}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002489
Brian Anderson5ea5e592016-12-01 16:54:33 -08002490void Layer::onDisconnect() {
2491 Mutex::Autolock lock(mFrameEventHistoryMutex);
2492 mFrameEventHistory.onDisconnect();
2493}
2494
Brian Anderson3890c392016-07-25 12:48:08 -07002495void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2496 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002497 Mutex::Autolock lock(mFrameEventHistoryMutex);
2498 if (newTimestamps) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002499 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002500 mFrameEventHistory.addQueue(*newTimestamps);
2501 }
2502
Brian Anderson3890c392016-07-25 12:48:08 -07002503 if (outDelta) {
2504 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002505 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002506}
Dan Stozae77c7662016-05-13 11:37:28 -07002507
2508std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2509 bool forceFlush) {
2510 std::vector<OccupancyTracker::Segment> history;
2511 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2512 &history);
2513 if (result != NO_ERROR) {
2514 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2515 result);
2516 return {};
2517 }
2518 return history;
2519}
2520
Robert Carr367c5682016-06-20 11:55:28 -07002521bool Layer::getTransformToDisplayInverse() const {
2522 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2523}
2524
Robert Carr1f0a16a2016-10-24 16:27:39 -07002525void Layer::addChild(const sp<Layer>& layer) {
2526 mCurrentChildren.add(layer);
2527 layer->setParent(this);
2528}
2529
2530ssize_t Layer::removeChild(const sp<Layer>& layer) {
2531 layer->setParent(nullptr);
2532 return mCurrentChildren.remove(layer);
2533}
2534
Robert Carr1db73f62016-12-21 12:58:51 -08002535bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2536 sp<Handle> handle = nullptr;
2537 sp<Layer> newParent = nullptr;
2538 if (newParentHandle == nullptr) {
2539 return false;
2540 }
2541 handle = static_cast<Handle*>(newParentHandle.get());
2542 newParent = handle->owner.promote();
2543 if (newParent == nullptr) {
2544 ALOGE("Unable to promote Layer handle");
2545 return false;
2546 }
2547
2548 for (const sp<Layer>& child : mCurrentChildren) {
2549 newParent->addChild(child);
2550
2551 sp<Client> client(child->mClientRef.promote());
2552 if (client != nullptr) {
2553 client->setParentLayer(newParent);
2554 }
2555 }
2556 mCurrentChildren.clear();
2557
2558 return true;
2559}
2560
Robert Carr9524cb32017-02-13 11:32:32 -08002561bool Layer::detachChildren() {
Dan Stoza412903f2017-04-27 13:42:17 -07002562 traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
Robert Carr9524cb32017-02-13 11:32:32 -08002563 if (child == this) {
2564 return;
2565 }
2566
2567 sp<Client> client(child->mClientRef.promote());
2568 if (client != nullptr) {
2569 client->detachLayer(child);
2570 }
2571 });
2572
2573 return true;
2574}
2575
Robert Carr1f0a16a2016-10-24 16:27:39 -07002576void Layer::setParent(const sp<Layer>& layer) {
2577 mParent = layer;
2578}
2579
2580void Layer::clearSyncPoints() {
2581 for (const auto& child : mCurrentChildren) {
2582 child->clearSyncPoints();
2583 }
2584
2585 Mutex::Autolock lock(mLocalSyncPointMutex);
2586 for (auto& point : mLocalSyncPoints) {
2587 point->setFrameAvailable();
2588 }
2589 mLocalSyncPoints.clear();
2590}
2591
2592int32_t Layer::getZ() const {
2593 return mDrawingState.z;
2594}
2595
Dan Stoza412903f2017-04-27 13:42:17 -07002596LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2597 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2598 "makeTraversalList received invalid stateSet");
2599 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2600 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2601 const State& state = useDrawing ? mDrawingState : mCurrentState;
2602
2603 if (state.zOrderRelatives.size() == 0) {
2604 return children;
Robert Carrdb66e622017-04-10 16:55:57 -07002605 }
2606 LayerVector traverse;
2607
Dan Stoza412903f2017-04-27 13:42:17 -07002608 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07002609 sp<Layer> strongRelative = weakRelative.promote();
2610 if (strongRelative != nullptr) {
2611 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07002612 }
2613 }
2614
Dan Stoza412903f2017-04-27 13:42:17 -07002615 for (const sp<Layer>& child : children) {
Robert Carrdb66e622017-04-10 16:55:57 -07002616 traverse.add(child);
2617 }
2618
2619 return traverse;
2620}
2621
Robert Carr1f0a16a2016-10-24 16:27:39 -07002622/**
Robert Carrdb66e622017-04-10 16:55:57 -07002623 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002624 */
Dan Stoza412903f2017-04-27 13:42:17 -07002625void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2626 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002627
Robert Carr1f0a16a2016-10-24 16:27:39 -07002628 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002629 for (; i < list.size(); i++) {
2630 const auto& relative = list[i];
2631 if (relative->getZ() >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002632 break;
Robert Carrdb66e622017-04-10 16:55:57 -07002633 }
Dan Stoza412903f2017-04-27 13:42:17 -07002634 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002635 }
Dan Stoza412903f2017-04-27 13:42:17 -07002636 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07002637 for (; i < list.size(); i++) {
2638 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002639 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002640 }
2641}
2642
2643/**
Robert Carrdb66e622017-04-10 16:55:57 -07002644 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002645 */
Dan Stoza412903f2017-04-27 13:42:17 -07002646void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2647 const LayerVector::Visitor& visitor) {
2648 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002649
Robert Carr1f0a16a2016-10-24 16:27:39 -07002650 int32_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002651 for (i = list.size()-1; i>=0; i--) {
2652 const auto& relative = list[i];
2653 if (relative->getZ() < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002654 break;
2655 }
Dan Stoza412903f2017-04-27 13:42:17 -07002656 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002657 }
Dan Stoza412903f2017-04-27 13:42:17 -07002658 visitor(this);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002659 for (; i>=0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002660 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002661 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002662 }
2663}
2664
2665Transform Layer::getTransform() const {
2666 Transform t;
2667 const auto& p = getParent();
2668 if (p != nullptr) {
2669 t = p->getTransform();
Robert Carr9b429f42017-04-17 14:56:57 -07002670
2671 // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2672 // it isFixedSize) then there may be additional scaling not accounted
2673 // for in the transform. We need to mirror this scaling in child surfaces
2674 // or we will break the contract where WM can treat child surfaces as
2675 // pixels in the parent surface.
2676 if (p->isFixedSize()) {
Robert Carr1725eee2017-04-26 18:32:15 -07002677 int bufferWidth;
2678 int bufferHeight;
2679 if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2680 bufferWidth = p->mActiveBuffer->getWidth();
2681 bufferHeight = p->mActiveBuffer->getHeight();
2682 } else {
2683 bufferHeight = p->mActiveBuffer->getWidth();
2684 bufferWidth = p->mActiveBuffer->getHeight();
2685 }
Robert Carr9b429f42017-04-17 14:56:57 -07002686 float sx = p->getDrawingState().active.w /
Robert Carr1725eee2017-04-26 18:32:15 -07002687 static_cast<float>(bufferWidth);
Robert Carr9b429f42017-04-17 14:56:57 -07002688 float sy = p->getDrawingState().active.h /
Robert Carr1725eee2017-04-26 18:32:15 -07002689 static_cast<float>(bufferHeight);
Robert Carr9b429f42017-04-17 14:56:57 -07002690 Transform extraParentScaling;
2691 extraParentScaling.set(sx, 0, 0, sy);
2692 t = t * extraParentScaling;
2693 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002694 }
2695 return t * getDrawingState().active.transform;
2696}
2697
Robert Carr6452f122017-03-21 10:41:29 -07002698#ifdef USE_HWC2
2699float Layer::getAlpha() const {
2700 const auto& p = getParent();
2701
2702 float parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0;
2703 return parentAlpha * getDrawingState().alpha;
2704}
2705#else
2706uint8_t Layer::getAlpha() const {
2707 const auto& p = getParent();
2708
2709 float parentAlpha = (p != nullptr) ? (p->getAlpha() / 255.0f) : 1.0;
2710 float drawingAlpha = getDrawingState().alpha / 255.0f;
2711 drawingAlpha = drawingAlpha * parentAlpha;
2712 return static_cast<uint8_t>(std::round(drawingAlpha * 255));
2713}
2714#endif
2715
Robert Carr1f0a16a2016-10-24 16:27:39 -07002716void Layer::commitChildList() {
2717 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2718 const auto& child = mCurrentChildren[i];
2719 child->commitChildList();
2720 }
2721 mDrawingChildren = mCurrentChildren;
2722}
2723
Mathias Agopian13127d82013-03-05 17:47:11 -08002724// ---------------------------------------------------------------------------
2725
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002726}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002727
2728#if defined(__gl_h_)
2729#error "don't include gl/gl.h in this file"
2730#endif
2731
2732#if defined(__gl2_h_)
2733#error "don't include gl2/gl2.h in this file"
2734#endif