blob: c21f0c26a175e947c2dd39720355724f3cc92f5d [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 Carr7bf247e2017-05-18 14:02:49 -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 Carr7bf247e2017-05-18 14:02:49 -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();
Chia-I Wu38512252017-05-17 14:36:16 -0700301
302#ifdef USE_HWC2
303 clearHwcLayers();
304#endif
305
Robert Carr1f0a16a2016-10-24 16:27:39 -0700306 for (const auto& child : mCurrentChildren) {
307 child->onRemoved();
308 }
Mathias Agopian48d819a2009-09-10 19:41:18 -0700309}
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700310
Mathias Agopian13127d82013-03-05 17:47:11 -0800311// ---------------------------------------------------------------------------
312// set-up
313// ---------------------------------------------------------------------------
314
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700315const String8& Layer::getName() const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800316 return mName;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800317}
318
Mathias Agopianf9d93272009-06-19 17:00:27 -0700319status_t Layer::setBuffers( uint32_t w, uint32_t h,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800320 PixelFormat format, uint32_t flags)
321{
Mathias Agopianca99fb82010-04-14 16:43:44 -0700322 uint32_t const maxSurfaceDims = min(
Mathias Agopiana4912602012-07-12 14:25:33 -0700323 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
Mathias Agopianca99fb82010-04-14 16:43:44 -0700324
325 // never allow a surface larger than what our underlying GL implementation
326 // can handle.
327 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
Mathias Agopianff615cc2012-02-24 14:58:36 -0800328 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700329 return BAD_VALUE;
330 }
331
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700332 mFormat = format;
Mathias Agopianeff062c2010-08-25 14:59:15 -0700333
Riley Andrews03414a12014-07-01 14:22:59 -0700334 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
Mathias Agopian3165cc22012-08-08 19:42:09 -0700335 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700336 mCurrentOpacity = getOpacityForFormat(format);
337
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800338 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
339 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
340 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700341
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800342 return NO_ERROR;
343}
344
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700345sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800346 Mutex::Autolock _l(mLock);
347
348 LOG_ALWAYS_FATAL_IF(mHasSurface,
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700349 "Layer::getHandle() has already been called");
Mathias Agopian13127d82013-03-05 17:47:11 -0800350
351 mHasSurface = true;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700352
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700353 return new Handle(mFlinger, this);
Mathias Agopian13127d82013-03-05 17:47:11 -0800354}
355
Dan Stozab9b08832014-03-13 11:55:57 -0700356sp<IGraphicBufferProducer> Layer::getProducer() const {
357 return mProducer;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700358}
359
Mathias Agopian13127d82013-03-05 17:47:11 -0800360// ---------------------------------------------------------------------------
361// h/w composer set-up
362// ---------------------------------------------------------------------------
363
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800364Rect Layer::getContentCrop() const {
365 // this is the crop rectangle that applies to the buffer
366 // itself (as opposed to the window)
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700367 Rect crop;
368 if (!mCurrentCrop.isEmpty()) {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800369 // if the buffer crop is defined, we use that
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700370 crop = mCurrentCrop;
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800371 } else if (mActiveBuffer != NULL) {
372 // otherwise we use the whole buffer
373 crop = mActiveBuffer->getBounds();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700374 } else {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800375 // if we don't have a buffer yet, we use an empty/invalid crop
Mathias Agopian4fec8732012-06-29 14:12:52 -0700376 crop.makeInvalid();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700377 }
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700378 return crop;
379}
380
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700381static Rect reduce(const Rect& win, const Region& exclude) {
382 if (CC_LIKELY(exclude.isEmpty())) {
383 return win;
384 }
385 if (exclude.isRect()) {
386 return win.reduce(exclude.getBounds());
387 }
388 return Region(win).subtract(exclude).getBounds();
389}
390
Robert Carr1f0a16a2016-10-24 16:27:39 -0700391Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
392 const Layer::State& s(getDrawingState());
393 Rect win(s.active.w, s.active.h);
394
395 if (!s.crop.isEmpty()) {
396 win.intersect(s.crop, &win);
397 }
398
399 Transform t = getTransform();
400 win = t.transform(win);
401
402 const sp<Layer>& p = getParent();
403 // Now we need to calculate the parent bounds, so we can clip ourselves to those.
404 // When calculating the parent bounds for purposes of clipping,
405 // we don't need to constrain the parent to its transparent region.
406 // The transparent region is an optimization based on the
407 // buffer contents of the layer, but does not affect the space allocated to
408 // it by policy, and thus children should be allowed to extend into the
409 // parent's transparent region. In fact one of the main uses, is to reduce
410 // buffer allocation size in cases where a child window sits behind a main window
411 // (by marking the hole in the parent window as a transparent region)
412 if (p != nullptr) {
413 Rect bounds = p->computeScreenBounds(false);
414 bounds.intersect(win, &win);
415 }
416
417 if (reduceTransparentRegion) {
418 auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
419 win = reduce(win, screenTransparentRegion);
420 }
421
422 return win;
423}
424
Mathias Agopian13127d82013-03-05 17:47:11 -0800425Rect Layer::computeBounds() const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700426 const Layer::State& s(getDrawingState());
Michael Lentine6c925ed2014-09-26 17:55:01 -0700427 return computeBounds(s.activeTransparentRegion);
428}
429
430Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
431 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800432 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700433
434 if (!s.crop.isEmpty()) {
435 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -0800436 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700437
438 Rect bounds = win;
439 const auto& p = getParent();
440 if (p != nullptr) {
Robert Carrde9ec442017-02-08 17:43:36 -0800441 // Look in computeScreenBounds recursive call for explanation of
442 // why we pass false here.
443 bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700444 }
445
446 Transform t = getTransform();
447 if (p != nullptr) {
448 win = t.transform(win);
449 win.intersect(bounds, &win);
450 win = t.inverse().transform(win);
451 }
452
Mathias Agopian6c7f25a2013-05-09 20:37:10 -0700453 // subtract the transparent region and snap to the bounds
Michael Lentine6c925ed2014-09-26 17:55:01 -0700454 return reduce(win, activeTransparentRegion);
Mathias Agopian13127d82013-03-05 17:47:11 -0800455}
456
Robert Carr1f0a16a2016-10-24 16:27:39 -0700457Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
Robert Carrb5d3d262016-03-25 15:08:13 -0700458 // the crop is the area of the window that gets cropped, but not
Mathias Agopian13127d82013-03-05 17:47:11 -0800459 // scaled in any ways.
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700460 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800461
462 // apply the projection's clipping to the window crop in
463 // layerstack space, and convert-back to layer space.
Mathias Agopian6b442672013-07-09 21:24:52 -0700464 // if there are no window scaling involved, this operation will map to full
465 // pixels in the buffer.
466 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
467 // a viewport clipping and a window transform. we should use floating point to fix this.
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700468
469 Rect activeCrop(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700470 if (!s.crop.isEmpty()) {
471 activeCrop = s.crop;
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700472 }
473
Robert Carr1f0a16a2016-10-24 16:27:39 -0700474 Transform t = getTransform();
475 activeCrop = t.transform(activeCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000476 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
477 activeCrop.clear();
478 }
Robert Carrb5d3d262016-03-25 15:08:13 -0700479 if (!s.finalCrop.isEmpty()) {
480 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000481 activeCrop.clear();
482 }
483 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700484 return activeCrop;
485}
486
Dan Stoza5a423ea2017-02-16 14:10:39 -0800487FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
Robert Carr1f0a16a2016-10-24 16:27:39 -0700488 // the content crop is the area of the content that gets scaled to the
489 // layer's size. This is in buffer space.
Dan Stoza5a423ea2017-02-16 14:10:39 -0800490 FloatRect crop = getContentCrop().toFloatRect();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700491
492 // In addition there is a WM-specified crop we pull from our drawing state.
493 const State& s(getDrawingState());
494
495 // Screen space to make reduction to parent crop clearer.
496 Rect activeCrop = computeInitialCrop(hw);
497 const auto& p = getParent();
498 if (p != nullptr) {
499 auto parentCrop = p->computeInitialCrop(hw);
500 activeCrop.intersect(parentCrop, &activeCrop);
501 }
502 Transform t = getTransform();
503 // Back to layer space to work with the content crop.
504 activeCrop = t.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800505
Michael Lentine28ea2172014-11-19 18:32:37 -0800506 // This needs to be here as transform.transform(Rect) computes the
507 // transformed rect and then takes the bounding box of the result before
508 // returning. This means
509 // transform.inverse().transform(transform.transform(Rect)) != Rect
510 // in which case we need to make sure the final rect is clipped to the
511 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000512 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
513 activeCrop.clear();
514 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800515
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700516 // subtract the transparent region and snap to the bounds
517 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
518
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000519 // Transform the window crop to match the buffer coordinate system,
520 // which means using the inverse of the current transform set on the
521 // SurfaceFlingerConsumer.
522 uint32_t invTransform = mCurrentTransform;
Robert Carrcae605c2017-03-29 12:10:31 -0700523 if (getTransformToDisplayInverse()) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000524 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700525 * the code below applies the primary display's inverse transform to the
526 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000527 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700528 uint32_t invTransformOrient =
529 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000530 // calculate the inverse transform
531 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
532 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
533 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800534 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000535 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700536 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
537 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800538 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000539
540 int winWidth = s.active.w;
541 int winHeight = s.active.h;
542 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
543 // If the activeCrop has been rotate the ends are rotated but not
544 // the space itself so when transforming ends back we can't rely on
545 // a modification of the axes of rotation. To account for this we
546 // need to reorient the inverse rotation in terms of the current
547 // axes of rotation.
548 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
549 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
550 if (is_h_flipped == is_v_flipped) {
551 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
552 NATIVE_WINDOW_TRANSFORM_FLIP_H;
553 }
554 winWidth = s.active.h;
555 winHeight = s.active.w;
556 }
557 const Rect winCrop = activeCrop.transform(
558 invTransform, s.active.w, s.active.h);
559
560 // below, crop is intersected with winCrop expressed in crop's coordinate space
561 float xScale = crop.getWidth() / float(winWidth);
562 float yScale = crop.getHeight() / float(winHeight);
563
564 float insetL = winCrop.left * xScale;
565 float insetT = winCrop.top * yScale;
566 float insetR = (winWidth - winCrop.right ) * xScale;
567 float insetB = (winHeight - winCrop.bottom) * yScale;
568
569 crop.left += insetL;
570 crop.top += insetT;
571 crop.right -= insetR;
572 crop.bottom -= insetB;
573
Mathias Agopian13127d82013-03-05 17:47:11 -0800574 return crop;
575}
576
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000577#ifdef USE_HWC2
Robert Carrae060832016-11-28 10:51:00 -0800578void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000579#else
580void Layer::setGeometry(
581 const sp<const DisplayDevice>& hw,
582 HWComposer::HWCLayerInterface& layer)
583#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700584{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000585#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800586 const auto hwcId = displayDevice->getHwcDisplayId();
587 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000588#else
589 layer.setDefaultState();
590#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700591
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700592 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000593#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800594 hwcInfo.forceClientComposition = false;
595
596 if (isSecure() && !displayDevice->isSecure()) {
597 hwcInfo.forceClientComposition = true;
598 }
599
600 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000601#else
602 layer.setSkip(false);
603
604 if (isSecure() && !hw->isSecure()) {
605 layer.setSkip(true);
606 }
607#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700608
Mathias Agopian13127d82013-03-05 17:47:11 -0800609 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700610 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000611#ifdef USE_HWC2
David Revemanecf0fa52017-03-03 11:32:44 -0500612 auto blendMode = HWC2::BlendMode::None;
Robert Carr6452f122017-03-21 10:41:29 -0700613 if (!isOpaque(s) || getAlpha() != 1.0f) {
David Revemanecf0fa52017-03-03 11:32:44 -0500614 blendMode = mPremultipliedAlpha ?
Dan Stoza9e56aa02015-11-02 13:00:03 -0800615 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800616 }
David Revemanecf0fa52017-03-03 11:32:44 -0500617 auto error = hwcLayer->setBlendMode(blendMode);
618 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
619 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
620 to_string(error).c_str(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000621#else
Robert Carr6452f122017-03-21 10:41:29 -0700622 if (!isOpaque(s) || getAlpha() != 0xFF) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000623 layer.setBlending(mPremultipliedAlpha ?
624 HWC_BLENDING_PREMULT :
625 HWC_BLENDING_COVERAGE);
626 }
627#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800628
629 // apply the layer's transform, followed by the display's global transform
630 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700631 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700632 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -0700633 if (!s.crop.isEmpty()) {
634 Rect activeCrop(s.crop);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700635 activeCrop = t.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000636#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000637 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000638#else
639 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
640#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000641 activeCrop.clear();
642 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700643 activeCrop = t.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800644 // This needs to be here as transform.transform(Rect) computes the
645 // transformed rect and then takes the bounding box of the result before
646 // returning. This means
647 // transform.inverse().transform(transform.transform(Rect)) != Rect
648 // in which case we need to make sure the final rect is clipped to the
649 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000650 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
651 activeCrop.clear();
652 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700653 // mark regions outside the crop as transparent
654 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
655 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
656 s.active.w, s.active.h));
657 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
658 activeCrop.left, activeCrop.bottom));
659 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
660 s.active.w, activeCrop.bottom));
661 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700662
663 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700664 if (!s.finalCrop.isEmpty()) {
665 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000666 frame.clear();
667 }
668 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000669#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000670 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
671 frame.clear();
672 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800673 const Transform& tr(displayDevice->getTransform());
674 Rect transformedFrame = tr.transform(frame);
David Revemanecf0fa52017-03-03 11:32:44 -0500675 error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700676 if (error != HWC2::Error::None) {
677 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
678 mName.string(), transformedFrame.left, transformedFrame.top,
679 transformedFrame.right, transformedFrame.bottom,
680 to_string(error).c_str(), static_cast<int32_t>(error));
681 } else {
682 hwcInfo.displayFrame = transformedFrame;
683 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800684
Dan Stoza5a423ea2017-02-16 14:10:39 -0800685 FloatRect sourceCrop = computeCrop(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800686 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700687 if (error != HWC2::Error::None) {
688 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
689 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
690 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
691 static_cast<int32_t>(error));
692 } else {
693 hwcInfo.sourceCrop = sourceCrop;
694 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800695
Robert Carr6452f122017-03-21 10:41:29 -0700696 float alpha = getAlpha();
697 error = hwcLayer->setPlaneAlpha(alpha);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800698 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
Robert Carr6452f122017-03-21 10:41:29 -0700699 "%s (%d)", mName.string(), alpha, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800700 static_cast<int32_t>(error));
701
Robert Carrae060832016-11-28 10:51:00 -0800702 error = hwcLayer->setZOrder(z);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800703 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
Robert Carrae060832016-11-28 10:51:00 -0800704 mName.string(), z, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800705 static_cast<int32_t>(error));
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500706
Albert Chaulk2a589632017-05-04 16:59:44 -0400707 int type = s.type;
708 int appId = s.appId;
709 sp<Layer> parent = mParent.promote();
710 if (parent.get()) {
711 auto& parentState = parent->getDrawingState();
712 type = parentState.type;
713 appId = parentState.appId;
714 }
715
716 error = hwcLayer->setInfo(type, appId);
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500717 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
718 mName.string(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000719#else
720 if (!frame.intersect(hw->getViewport(), &frame)) {
721 frame.clear();
722 }
723 const Transform& tr(hw->getTransform());
724 layer.setFrame(tr.transform(frame));
725 layer.setCrop(computeCrop(hw));
Robert Carr6452f122017-03-21 10:41:29 -0700726 layer.setPlaneAlpha(getAlpha());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000727#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800728
Mathias Agopian29a367b2011-07-12 14:51:45 -0700729 /*
730 * Transformations are applied in this order:
731 * 1) buffer orientation/flip/mirror
732 * 2) state transformation (window manager)
733 * 3) layer orientation (screen orientation)
734 * (NOTE: the matrices are multiplied in reverse order)
735 */
736
737 const Transform bufferOrientation(mCurrentTransform);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700738 Transform transform(tr * t * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700739
Robert Carrcae605c2017-03-29 12:10:31 -0700740 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700741 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700742 * the code below applies the primary display's inverse transform to the
743 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700744 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700745 uint32_t invTransform =
746 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700747 // calculate the inverse transform
748 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
749 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
750 NATIVE_WINDOW_TRANSFORM_FLIP_H;
751 }
Robert Carrcae605c2017-03-29 12:10:31 -0700752
753 /*
754 * Here we cancel out the orientation component of the WM transform.
755 * The scaling and translate components are already included in our bounds
756 * computation so it's enough to just omit it in the composition.
757 * See comment in onDraw with ref to b/36727915 for why.
758 */
759 transform = Transform(invTransform) * tr * bufferOrientation;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700760 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700761
762 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800763 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000764#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800765 if (orientation & Transform::ROT_INVALID) {
766 // we can only handle simple transformation
767 hwcInfo.forceClientComposition = true;
768 } else {
769 auto transform = static_cast<HWC2::Transform>(orientation);
770 auto error = hwcLayer->setTransform(transform);
771 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
772 "%s (%d)", mName.string(), to_string(transform).c_str(),
773 to_string(error).c_str(), static_cast<int32_t>(error));
774 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000775#else
776 if (orientation & Transform::ROT_INVALID) {
777 // we can only handle simple transformation
778 layer.setSkip(true);
779 } else {
780 layer.setTransform(orientation);
781 }
782#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700783}
784
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000785#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800786void Layer::forceClientComposition(int32_t hwcId) {
787 if (mHwcLayers.count(hwcId) == 0) {
788 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
789 return;
790 }
791
792 mHwcLayers[hwcId].forceClientComposition = true;
793}
Dan Stoza9e56aa02015-11-02 13:00:03 -0800794
Dan Stoza9e56aa02015-11-02 13:00:03 -0800795void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
796 // Apply this display's projection's viewport to the visible region
797 // before giving it to the HWC HAL.
798 const Transform& tr = displayDevice->getTransform();
799 const auto& viewport = displayDevice->getViewport();
800 Region visible = tr.transform(visibleRegion.intersect(viewport));
801 auto hwcId = displayDevice->getHwcDisplayId();
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800802 auto& hwcInfo = mHwcLayers[hwcId];
803 auto& hwcLayer = hwcInfo.layer;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800804 auto error = hwcLayer->setVisibleRegion(visible);
805 if (error != HWC2::Error::None) {
806 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
807 to_string(error).c_str(), static_cast<int32_t>(error));
808 visible.dump(LOG_TAG);
809 }
810
811 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
812 if (error != HWC2::Error::None) {
813 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
814 to_string(error).c_str(), static_cast<int32_t>(error));
815 surfaceDamageRegion.dump(LOG_TAG);
816 }
817
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700818 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800819 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700820 setCompositionType(hwcId, HWC2::Composition::Sideband);
821 ALOGV("[%s] Requesting Sideband composition", mName.string());
822 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800823 if (error != HWC2::Error::None) {
824 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
825 mName.string(), mSidebandStream->handle(),
826 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800827 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700828 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800829 }
830
Dan Stoza0a21df72016-07-20 12:52:38 -0700831 // Client layers
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800832 if (hwcInfo.forceClientComposition ||
Dan Stoza0a21df72016-07-20 12:52:38 -0700833 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700834 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800835 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700836 return;
837 }
838
Dan Stoza0a21df72016-07-20 12:52:38 -0700839 // SolidColor layers
840 if (mActiveBuffer == nullptr) {
841 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700842
843 // For now, we only support black for DimLayer
Dan Stoza0a21df72016-07-20 12:52:38 -0700844 error = hwcLayer->setColor({0, 0, 0, 255});
845 if (error != HWC2::Error::None) {
846 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
847 to_string(error).c_str(), static_cast<int32_t>(error));
848 }
Dan Stozac6c89542016-07-27 10:16:52 -0700849
850 // Clear out the transform, because it doesn't make sense absent a
851 // source buffer
852 error = hwcLayer->setTransform(HWC2::Transform::None);
853 if (error != HWC2::Error::None) {
854 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
855 to_string(error).c_str(), static_cast<int32_t>(error));
856 }
857
Dan Stoza0a21df72016-07-20 12:52:38 -0700858 return;
859 }
860
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700861 // Device or Cursor layers
862 if (mPotentialCursor) {
863 ALOGV("[%s] Requesting Cursor composition", mName.string());
864 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800865 } else {
866 ALOGV("[%s] Requesting Device composition", mName.string());
867 setCompositionType(hwcId, HWC2::Composition::Device);
868 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700869
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700870 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
871 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
872 if (error != HWC2::Error::None) {
873 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
874 mCurrentState.dataSpace, to_string(error).c_str(),
875 static_cast<int32_t>(error));
876 }
877
Chia-I Wu06d63de2017-01-04 14:58:51 +0800878 uint32_t hwcSlot = 0;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400879 sp<GraphicBuffer> hwcBuffer;
880 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
881 &hwcSlot, &hwcBuffer);
Chia-I Wu06d63de2017-01-04 14:58:51 +0800882
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700883 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400884 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700885 if (error != HWC2::Error::None) {
886 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
887 mActiveBuffer->handle, to_string(error).c_str(),
888 static_cast<int32_t>(error));
889 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800890}
Courtney Goeltzenleuchter9551fd32016-10-20 17:18:15 -0600891
892android_dataspace Layer::getDataSpace() const {
893 return mCurrentState.dataSpace;
894}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000895#else
896void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
897 HWComposer::HWCLayerInterface& layer) {
898 // we have to set the visible region on every frame because
899 // we currently free it during onLayerDisplayed(), which is called
900 // after HWComposer::commit() -- every frame.
901 // Apply this display's projection's viewport to the visible region
902 // before giving it to the HWC HAL.
903 const Transform& tr = hw->getTransform();
904 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
905 layer.setVisibleRegionScreen(visible);
906 layer.setSurfaceDamage(surfaceDamageRegion);
907 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700908
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000909 if (mSidebandStream.get()) {
910 layer.setSidebandStream(mSidebandStream);
911 } else {
912 // NOTE: buffer can be NULL if the client never drew into this
913 // layer yet, or if we ran out of memory
914 layer.setBuffer(mActiveBuffer);
915 }
916}
917#endif
918
919#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800920void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
921 auto hwcId = displayDevice->getHwcDisplayId();
922 if (mHwcLayers.count(hwcId) == 0 ||
923 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
924 return;
925 }
926
927 // This gives us only the "orientation" component of the transform
928 const State& s(getCurrentState());
929
930 // Apply the layer's transform, followed by the display's global transform
931 // Here we're guaranteed that the layer's transform preserves rects
932 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700933 if (!s.crop.isEmpty()) {
934 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800935 }
936 // Subtract the transparent region and snap to the bounds
937 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700938 Rect frame(getTransform().transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800939 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -0700940 if (!s.finalCrop.isEmpty()) {
941 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000942 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800943 auto& displayTransform(displayDevice->getTransform());
944 auto position = displayTransform.transform(frame);
945
946 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
947 position.top);
948 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
949 "to (%d, %d): %s (%d)", mName.string(), position.left,
950 position.top, to_string(error).c_str(),
951 static_cast<int32_t>(error));
952}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000953#else
954void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
955 HWComposer::HWCLayerInterface& layer) {
956 int fenceFd = -1;
957
958 // TODO: there is a possible optimization here: we only need to set the
959 // acquire fence the first time a new buffer is acquired on EACH display.
960
961 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
962 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
963 if (fence->isValid()) {
964 fenceFd = fence->dup();
965 if (fenceFd == -1) {
966 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
967 }
968 }
969 }
970 layer.setAcquireFenceFd(fenceFd);
971}
972
973Rect Layer::getPosition(
974 const sp<const DisplayDevice>& hw)
975{
976 // this gives us only the "orientation" component of the transform
977 const State& s(getCurrentState());
978
979 // apply the layer's transform, followed by the display's global transform
980 // here we're guaranteed that the layer's transform preserves rects
981 Rect win(s.active.w, s.active.h);
982 if (!s.crop.isEmpty()) {
983 win.intersect(s.crop, &win);
984 }
985 // subtract the transparent region and snap to the bounds
986 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700987 Rect frame(getTransform().transform(bounds));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000988 frame.intersect(hw->getViewport(), &frame);
989 if (!s.finalCrop.isEmpty()) {
990 frame.intersect(s.finalCrop, &frame);
991 }
992 const Transform& tr(hw->getTransform());
993 return Rect(tr.transform(frame));
994}
995#endif
Riley Andrews03414a12014-07-01 14:22:59 -0700996
Mathias Agopian13127d82013-03-05 17:47:11 -0800997// ---------------------------------------------------------------------------
998// drawing...
999// ---------------------------------------------------------------------------
1000
1001void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -08001002 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -08001003}
1004
Dan Stozac7014012014-02-14 15:03:43 -08001005void Layer::draw(const sp<const DisplayDevice>& hw,
1006 bool useIdentityTransform) const {
1007 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001008}
1009
Dan Stozac7014012014-02-14 15:03:43 -08001010void Layer::draw(const sp<const DisplayDevice>& hw) const {
1011 onDraw(hw, Region(hw->bounds()), false);
1012}
1013
Robert Carrcae605c2017-03-29 12:10:31 -07001014static constexpr mat4 inverseOrientation(uint32_t transform) {
1015 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1016 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1017 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1018 mat4 tr;
1019
1020 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1021 tr = tr * rot90;
1022 }
1023 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1024 tr = tr * flipH;
1025 }
1026 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1027 tr = tr * flipV;
1028 }
1029 return inverse(tr);
1030}
1031
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001032/*
1033 * onDraw will draw the current layer onto the presentable buffer
1034 */
Dan Stozac7014012014-02-14 15:03:43 -08001035void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
1036 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001037{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001038 ATRACE_CALL();
1039
Mathias Agopiana67932f2011-04-20 14:20:59 -07001040 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001041 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -07001042 // in fact never been drawn into. This happens frequently with
1043 // SurfaceView because the WindowManager can't know when the client
1044 // has drawn the first time.
1045
1046 // If there is nothing under us, we paint the screen in black, otherwise
1047 // we just skip this update.
1048
1049 // figure out if there is something below us
1050 Region under;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001051 bool finished = false;
Dan Stoza412903f2017-04-27 13:42:17 -07001052 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001053 if (finished || layer == static_cast<Layer const*>(this)) {
1054 finished = true;
1055 return;
1056 }
Mathias Agopian42977342012-08-05 00:40:46 -07001057 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Robert Carr1f0a16a2016-10-24 16:27:39 -07001058 });
Mathias Agopian179169e2010-05-06 20:21:45 -07001059 // if not everything below us is covered, we plug the holes!
1060 Region holes(clip.subtract(under));
1061 if (!holes.isEmpty()) {
Fabien Sanglard17487192016-12-07 13:03:32 -08001062 clearWithOpenGL(hw, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -07001063 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001064 return;
1065 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001066
Andy McFadden97eba892012-12-11 15:21:45 -08001067 // Bind the current buffer to the GL texture, and wait for it to be
1068 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001069 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1070 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -08001071 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -07001072 // Go ahead and draw the buffer anyway; no matter what we do the screen
1073 // is probably going to have something visibly wrong.
1074 }
1075
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001076 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1077
Mathias Agopian875d8e12013-06-07 15:35:48 -07001078 RenderEngine& engine(mFlinger->getRenderEngine());
1079
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001080 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -07001081 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -07001082 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -07001083
1084 // Query the texture matrix given our current filtering mode.
1085 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001086 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1087 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -07001088
Robert Carrcae605c2017-03-29 12:10:31 -07001089 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001090
1091 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -07001092 * the code below applies the primary display's inverse transform to
1093 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001094 */
Pablo Ceballos021623b2016-04-15 17:31:51 -07001095 uint32_t transform =
1096 DisplayDevice::getPrimaryDisplayOrientationTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001097 mat4 tr = inverseOrientation(transform);
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001098
Robert Carrcae605c2017-03-29 12:10:31 -07001099 /**
1100 * TODO(b/36727915): This is basically a hack.
1101 *
1102 * Ensure that regardless of the parent transformation,
1103 * this buffer is always transformed from native display
1104 * orientation to display orientation. For example, in the case
1105 * of a camera where the buffer remains in native orientation,
1106 * we want the pixels to always be upright.
1107 */
1108 if (getParent() != nullptr) {
1109 const auto parentTransform = getParent()->getTransform();
1110 tr = tr * inverseOrientation(parentTransform.getOrientation());
1111 }
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001112
1113 // and finally apply it to the original texture matrix
1114 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1115 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1116 }
1117
Jamie Genniscbb1a952012-05-08 17:05:52 -07001118 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -07001119 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1120 mTexture.setFiltering(useFiltering);
1121 mTexture.setMatrix(textureMatrix);
1122
1123 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -07001124 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001125 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -07001126 }
Fabien Sanglard85789802016-12-07 13:08:24 -08001127 drawWithOpenGL(hw, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001128 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001129}
1130
Mathias Agopian13127d82013-03-05 17:47:11 -08001131
Dan Stozac7014012014-02-14 15:03:43 -08001132void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard17487192016-12-07 13:03:32 -08001133 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -08001134 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001135{
Mathias Agopian19733a32013-08-28 18:13:56 -07001136 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -08001137 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -07001138 engine.setupFillWithColor(red, green, blue, alpha);
1139 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -08001140}
1141
1142void Layer::clearWithOpenGL(
Fabien Sanglard17487192016-12-07 13:03:32 -08001143 const sp<const DisplayDevice>& hw) const {
1144 clearWithOpenGL(hw, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001145}
1146
Dan Stozac7014012014-02-14 15:03:43 -08001147void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard85789802016-12-07 13:08:24 -08001148 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001149 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001150
Dan Stozac7014012014-02-14 15:03:43 -08001151 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001152
Mathias Agopian13127d82013-03-05 17:47:11 -08001153 /*
1154 * NOTE: the way we compute the texture coordinates here produces
1155 * different results than when we take the HWC path -- in the later case
1156 * the "source crop" is rounded to texel boundaries.
1157 * This can produce significantly different results when the texture
1158 * is scaled by a large amount.
1159 *
1160 * The GL code below is more logical (imho), and the difference with
1161 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001162 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001163 * GL composition when a buffer scaling is applied (maybe with some
1164 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1165 * like more of a hack.
1166 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001167 Rect win(computeBounds());
1168
Robert Carr1f0a16a2016-10-24 16:27:39 -07001169 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -07001170 if (!s.finalCrop.isEmpty()) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001171 win = t.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001172 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001173 win.clear();
1174 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001175 win = t.inverse().transform(win);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001176 if (!win.intersect(computeBounds(), &win)) {
1177 win.clear();
1178 }
1179 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001180
Mathias Agopian3f844832013-08-07 21:24:32 -07001181 float left = float(win.left) / float(s.active.w);
1182 float top = float(win.top) / float(s.active.h);
1183 float right = float(win.right) / float(s.active.w);
1184 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001185
Mathias Agopian875d8e12013-06-07 15:35:48 -07001186 // TODO: we probably want to generate the texture coords with the mesh
1187 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001188 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1189 texCoords[0] = vec2(left, 1.0f - top);
1190 texCoords[1] = vec2(left, 1.0f - bottom);
1191 texCoords[2] = vec2(right, 1.0f - bottom);
1192 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001193
Mathias Agopian875d8e12013-06-07 15:35:48 -07001194 RenderEngine& engine(mFlinger->getRenderEngine());
Robert Carr6452f122017-03-21 10:41:29 -07001195 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), getAlpha());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001196#ifdef USE_HWC2
1197 engine.setSourceDataSpace(mCurrentState.dataSpace);
1198#endif
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001199 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001200 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001201}
1202
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001203#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001204void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1205 bool callIntoHwc) {
1206 if (mHwcLayers.count(hwcId) == 0) {
1207 ALOGE("setCompositionType called without a valid HWC layer");
1208 return;
1209 }
1210 auto& hwcInfo = mHwcLayers[hwcId];
1211 auto& hwcLayer = hwcInfo.layer;
1212 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1213 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1214 if (hwcInfo.compositionType != type) {
1215 ALOGV(" actually setting");
1216 hwcInfo.compositionType = type;
1217 if (callIntoHwc) {
1218 auto error = hwcLayer->setCompositionType(type);
1219 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1220 "composition type %s: %s (%d)", mName.string(),
1221 to_string(type).c_str(), to_string(error).c_str(),
1222 static_cast<int32_t>(error));
1223 }
1224 }
1225}
1226
1227HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001228 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1229 // If we're querying the composition type for a display that does not
1230 // have a HWC counterpart, then it will always be Client
1231 return HWC2::Composition::Client;
1232 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001233 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001234 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001235 return HWC2::Composition::Invalid;
1236 }
1237 return mHwcLayers.at(hwcId).compositionType;
1238}
1239
1240void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1241 if (mHwcLayers.count(hwcId) == 0) {
1242 ALOGE("setClearClientTarget called without a valid HWC layer");
1243 return;
1244 }
1245 mHwcLayers[hwcId].clearClientTarget = clear;
1246}
1247
1248bool Layer::getClearClientTarget(int32_t hwcId) const {
1249 if (mHwcLayers.count(hwcId) == 0) {
1250 ALOGE("getClearClientTarget called without a valid HWC layer");
1251 return false;
1252 }
1253 return mHwcLayers.at(hwcId).clearClientTarget;
1254}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001255#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001256
Ruben Brunk1681d952014-06-27 15:51:55 -07001257uint32_t Layer::getProducerStickyTransform() const {
1258 int producerStickyTransform = 0;
1259 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1260 if (ret != OK) {
1261 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1262 strerror(-ret), ret);
1263 return 0;
1264 }
1265 return static_cast<uint32_t>(producerStickyTransform);
1266}
1267
Dan Stozac5da2712016-07-20 15:38:12 -07001268bool Layer::latchUnsignaledBuffers() {
1269 static bool propertyLoaded = false;
1270 static bool latch = false;
1271 static std::mutex mutex;
1272 std::lock_guard<std::mutex> lock(mutex);
1273 if (!propertyLoaded) {
1274 char value[PROPERTY_VALUE_MAX] = {};
1275 property_get("debug.sf.latch_unsignaled", value, "0");
1276 latch = atoi(value);
1277 propertyLoaded = true;
1278 }
1279 return latch;
1280}
1281
Dan Stozacac35382016-01-27 12:21:06 -08001282uint64_t Layer::getHeadFrameNumber() const {
1283 Mutex::Autolock lock(mQueueItemLock);
1284 if (!mQueueItems.empty()) {
1285 return mQueueItems[0].mFrameNumber;
1286 } else {
1287 return mCurrentFrameNumber;
1288 }
1289}
1290
Dan Stoza1ce65812016-06-15 16:26:27 -07001291bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001292#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001293 if (latchUnsignaledBuffers()) {
1294 return true;
1295 }
1296
Dan Stoza1ce65812016-06-15 16:26:27 -07001297 Mutex::Autolock lock(mQueueItemLock);
1298 if (mQueueItems.empty()) {
1299 return true;
1300 }
1301 if (mQueueItems[0].mIsDroppable) {
1302 // Even though this buffer's fence may not have signaled yet, it could
1303 // be replaced by another buffer before it has a chance to, which means
1304 // that it's possible to get into a situation where a buffer is never
1305 // able to be latched. To avoid this, grab this buffer anyway.
1306 return true;
1307 }
1308 return mQueueItems[0].mFence->getSignalTime() != INT64_MAX;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001309#else
1310 return true;
1311#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001312}
1313
Dan Stozacac35382016-01-27 12:21:06 -08001314bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1315 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1316 // Don't bother with a SyncPoint, since we've already latched the
1317 // relevant frame
1318 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001319 }
1320
Dan Stozacac35382016-01-27 12:21:06 -08001321 Mutex::Autolock lock(mLocalSyncPointMutex);
1322 mLocalSyncPoints.push_back(point);
1323 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001324}
1325
Mathias Agopian13127d82013-03-05 17:47:11 -08001326void Layer::setFiltering(bool filtering) {
1327 mFiltering = filtering;
1328}
1329
1330bool Layer::getFiltering() const {
1331 return mFiltering;
1332}
1333
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001334// As documented in libhardware header, formats in the range
1335// 0x100 - 0x1FF are specific to the HAL implementation, and
1336// are known to have no alpha channel
1337// TODO: move definition for device-specific range into
1338// hardware.h, instead of using hard-coded values here.
1339#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1340
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001341bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001342 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1343 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001344 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001345 switch (format) {
1346 case HAL_PIXEL_FORMAT_RGBA_8888:
1347 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001348 case HAL_PIXEL_FORMAT_RGBA_FP16:
Romain Guy541f2262017-02-10 18:50:17 -08001349 case HAL_PIXEL_FORMAT_RGBA_1010102:
Mathias Agopiandd533712013-07-26 15:31:39 -07001350 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001351 }
1352 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001353 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001354}
1355
Mathias Agopian13127d82013-03-05 17:47:11 -08001356// ----------------------------------------------------------------------------
1357// local state
1358// ----------------------------------------------------------------------------
1359
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001360static void boundPoint(vec2* point, const Rect& crop) {
1361 if (point->x < crop.left) {
1362 point->x = crop.left;
1363 }
1364 if (point->x > crop.right) {
1365 point->x = crop.right;
1366 }
1367 if (point->y < crop.top) {
1368 point->y = crop.top;
1369 }
1370 if (point->y > crop.bottom) {
1371 point->y = crop.bottom;
1372 }
1373}
1374
Dan Stozac7014012014-02-14 15:03:43 -08001375void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1376 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001377{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001378 const Layer::State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001379 const Transform hwTransform(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001380 const uint32_t hw_h = hw->getHeight();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001381 Rect win = computeBounds();
Mathias Agopian3f844832013-08-07 21:24:32 -07001382
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001383 vec2 lt = vec2(win.left, win.top);
1384 vec2 lb = vec2(win.left, win.bottom);
1385 vec2 rb = vec2(win.right, win.bottom);
1386 vec2 rt = vec2(win.right, win.top);
1387
Robert Carr1f0a16a2016-10-24 16:27:39 -07001388 Transform layerTransform = getTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001389 if (!useIdentityTransform) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001390 lt = layerTransform.transform(lt);
1391 lb = layerTransform.transform(lb);
1392 rb = layerTransform.transform(rb);
1393 rt = layerTransform.transform(rt);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001394 }
1395
Robert Carrb5d3d262016-03-25 15:08:13 -07001396 if (!s.finalCrop.isEmpty()) {
1397 boundPoint(&lt, s.finalCrop);
1398 boundPoint(&lb, s.finalCrop);
1399 boundPoint(&rb, s.finalCrop);
1400 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001401 }
1402
Mathias Agopianff2ed702013-09-01 21:36:12 -07001403 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001404 position[0] = hwTransform.transform(lt);
1405 position[1] = hwTransform.transform(lb);
1406 position[2] = hwTransform.transform(rb);
1407 position[3] = hwTransform.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001408 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001409 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001410 }
1411}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001412
Andy McFadden4125a4f2014-01-29 17:17:11 -08001413bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001414{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001415 // if we don't have a buffer yet, we're translucent regardless of the
1416 // layer's opaque flag.
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001417 if (mActiveBuffer == 0) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001418 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001419 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001420
1421 // if the layer has the opaque flag, then we're always opaque,
1422 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001423 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001424}
1425
Dan Stoza23116082015-06-18 14:58:39 -07001426bool Layer::isSecure() const
1427{
1428 const Layer::State& s(mDrawingState);
1429 return (s.flags & layer_state_t::eLayerSecure);
1430}
1431
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001432bool Layer::isProtected() const
1433{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001434 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001435 return (activeBuffer != 0) &&
1436 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1437}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001438
Mathias Agopian13127d82013-03-05 17:47:11 -08001439bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001440 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001441}
1442
1443bool Layer::isCropped() const {
1444 return !mCurrentCrop.isEmpty();
1445}
1446
1447bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1448 return mNeedsFiltering || hw->needsFiltering();
1449}
1450
1451void Layer::setVisibleRegion(const Region& visibleRegion) {
1452 // always called from main thread
1453 this->visibleRegion = visibleRegion;
1454}
1455
1456void Layer::setCoveredRegion(const Region& coveredRegion) {
1457 // always called from main thread
1458 this->coveredRegion = coveredRegion;
1459}
1460
1461void Layer::setVisibleNonTransparentRegion(const Region&
1462 setVisibleNonTransparentRegion) {
1463 // always called from main thread
1464 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1465}
1466
1467// ----------------------------------------------------------------------------
1468// transaction
1469// ----------------------------------------------------------------------------
1470
Dan Stoza7dde5992015-05-22 09:51:44 -07001471void Layer::pushPendingState() {
1472 if (!mCurrentState.modified) {
1473 return;
1474 }
1475
Dan Stoza7dde5992015-05-22 09:51:44 -07001476 // If this transaction is waiting on the receipt of a frame, generate a sync
1477 // point and send it to the remote layer.
Robert Carr0d480722017-01-10 16:42:54 -08001478 if (mCurrentState.barrierLayer != nullptr) {
1479 sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1480 if (barrierLayer == nullptr) {
1481 ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
Dan Stoza7dde5992015-05-22 09:51:44 -07001482 // If we can't promote the layer we are intended to wait on,
1483 // then it is expired or otherwise invalid. Allow this transaction
1484 // to be applied as per normal (no synchronization).
Robert Carr0d480722017-01-10 16:42:54 -08001485 mCurrentState.barrierLayer = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001486 } else {
1487 auto syncPoint = std::make_shared<SyncPoint>(
1488 mCurrentState.frameNumber);
Robert Carr0d480722017-01-10 16:42:54 -08001489 if (barrierLayer->addSyncPoint(syncPoint)) {
Dan Stozacac35382016-01-27 12:21:06 -08001490 mRemoteSyncPoints.push_back(std::move(syncPoint));
1491 } else {
1492 // We already missed the frame we're supposed to synchronize
1493 // on, so go ahead and apply the state update
Robert Carr0d480722017-01-10 16:42:54 -08001494 mCurrentState.barrierLayer = nullptr;
Dan Stozacac35382016-01-27 12:21:06 -08001495 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001496 }
1497
Dan Stoza7dde5992015-05-22 09:51:44 -07001498 // Wake us up to check if the frame has been received
1499 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001500 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001501 }
1502 mPendingStates.push_back(mCurrentState);
1503}
1504
Pablo Ceballos05289c22016-04-14 15:49:55 -07001505void Layer::popPendingState(State* stateToCommit) {
1506 auto oldFlags = stateToCommit->flags;
1507 *stateToCommit = mPendingStates[0];
1508 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1509 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001510
1511 mPendingStates.removeAt(0);
1512}
1513
Pablo Ceballos05289c22016-04-14 15:49:55 -07001514bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001515 bool stateUpdateAvailable = false;
1516 while (!mPendingStates.empty()) {
Robert Carr0d480722017-01-10 16:42:54 -08001517 if (mPendingStates[0].barrierLayer != nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001518 if (mRemoteSyncPoints.empty()) {
1519 // If we don't have a sync point for this, apply it anyway. It
1520 // will be visually wrong, but it should keep us from getting
1521 // into too much trouble.
1522 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001523 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001524 stateUpdateAvailable = true;
1525 continue;
1526 }
1527
Dan Stozacac35382016-01-27 12:21:06 -08001528 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1529 mPendingStates[0].frameNumber) {
1530 ALOGE("[%s] Unexpected sync point frame number found",
1531 mName.string());
1532
1533 // Signal our end of the sync point and then dispose of it
1534 mRemoteSyncPoints.front()->setTransactionApplied();
1535 mRemoteSyncPoints.pop_front();
1536 continue;
1537 }
1538
Dan Stoza7dde5992015-05-22 09:51:44 -07001539 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1540 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001541 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001542 stateUpdateAvailable = true;
1543
1544 // Signal our end of the sync point and then dispose of it
1545 mRemoteSyncPoints.front()->setTransactionApplied();
1546 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001547 } else {
1548 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001549 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001550 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001551 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001552 stateUpdateAvailable = true;
1553 }
1554 }
1555
1556 // If we still have pending updates, wake SurfaceFlinger back up and point
1557 // it at this layer so we can process them
1558 if (!mPendingStates.empty()) {
1559 setTransactionFlags(eTransactionNeeded);
1560 mFlinger->setTransactionFlags(eTraversalNeeded);
1561 }
1562
1563 mCurrentState.modified = false;
1564 return stateUpdateAvailable;
1565}
1566
1567void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001568 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001569 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001570 Mutex::Autolock lock(mLocalSyncPointMutex);
1571 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001572 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001573 point->setFrameAvailable();
1574 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001575 }
1576}
1577
Mathias Agopian13127d82013-03-05 17:47:11 -08001578uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001579 ATRACE_CALL();
1580
Dan Stoza7dde5992015-05-22 09:51:44 -07001581 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001582 Layer::State c = getCurrentState();
1583 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001584 return 0;
1585 }
1586
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001587 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001588
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001589 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1590 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001591
1592 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001593 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001594 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001595 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001596 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001597 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001598 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001599 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001600 this, getName().string(), mCurrentTransform,
1601 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001602 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001603 c.crop.left,
1604 c.crop.top,
1605 c.crop.right,
1606 c.crop.bottom,
1607 c.crop.getWidth(),
1608 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001609 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001610 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001611 s.crop.left,
1612 s.crop.top,
1613 s.crop.right,
1614 s.crop.bottom,
1615 s.crop.getWidth(),
1616 s.crop.getHeight(),
1617 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001618
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001619 // record the new size, form this point on, when the client request
1620 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001621 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001622 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001623 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001624
Robert Carr82364e32016-05-15 11:27:47 -07001625 const bool resizePending = (c.requested.w != c.active.w) ||
1626 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001627 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001628 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001629 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001630 // if we have a pending resize, unless we are in fixed-size mode.
1631 // the drawing state will be updated only once we receive a buffer
1632 // with the correct size.
1633 //
1634 // in particular, we want to make sure the clip (which is part
1635 // of the geometry state) is latched together with the size but is
1636 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001637 //
1638 // If a sideband stream is attached, however, we want to skip this
1639 // optimization so that transactions aren't missed when a buffer
1640 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001641
1642 flags |= eDontUpdateGeometryState;
1643 }
1644 }
1645
Robert Carr7bf247e2017-05-18 14:02:49 -07001646 // Here we apply various requested geometry states, depending on our
1647 // latching configuration. See Layer.h for a detailed discussion of
1648 // how geometry latching is controlled.
1649 if (!(flags & eDontUpdateGeometryState)) {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001650 Layer::State& editCurrentState(getCurrentState());
Robert Carr7bf247e2017-05-18 14:02:49 -07001651
1652 // If mFreezeGeometryUpdates is true we are in the setGeometryAppliesWithResize
1653 // mode, which causes attributes which normally latch regardless of scaling mode,
1654 // to be delayed. We copy the requested state to the active state making sure
1655 // to respect these rules (again see Layer.h for a detailed discussion).
1656 //
1657 // There is an awkward asymmetry in the handling of the crop states in the position
1658 // states, as can be seen below. Largely this arises from position and transform
1659 // being stored in the same data structure while having different latching rules.
1660 // b/38182305
1661 //
1662 // Careful that "c" and editCurrentState may not begin as equivalent due to
1663 // applyPendingStates in the presence of deferred transactions.
1664 if (mFreezeGeometryUpdates) {
Robert Carr82364e32016-05-15 11:27:47 -07001665 float tx = c.active.transform.tx();
1666 float ty = c.active.transform.ty();
1667 c.active = c.requested;
1668 c.active.transform.set(tx, ty);
1669 editCurrentState.active = c.active;
1670 } else {
1671 editCurrentState.active = editCurrentState.requested;
1672 c.active = c.requested;
1673 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001674 }
1675
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001676 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001677 // invalidate and recompute the visible regions if needed
1678 flags |= Layer::eVisibleRegion;
1679 }
1680
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001681 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001682 // invalidate and recompute the visible regions if needed
1683 flags |= eVisibleRegion;
1684 this->contentDirty = true;
1685
1686 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001687 const uint8_t type = c.active.transform.getType();
1688 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001689 (type >= Transform::SCALE));
1690 }
1691
Dan Stozac8145172016-04-28 16:29:06 -07001692 // If the layer is hidden, signal and clear out all local sync points so
1693 // that transactions for layers depending on this layer's frames becoming
1694 // visible are not blocked
1695 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001696 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001697 }
1698
Mathias Agopian13127d82013-03-05 17:47:11 -08001699 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001700 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001701 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001702}
1703
Pablo Ceballos05289c22016-04-14 15:49:55 -07001704void Layer::commitTransaction(const State& stateToCommit) {
1705 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001706}
1707
Mathias Agopian13127d82013-03-05 17:47:11 -08001708uint32_t Layer::getTransactionFlags(uint32_t flags) {
1709 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1710}
1711
1712uint32_t Layer::setTransactionFlags(uint32_t flags) {
1713 return android_atomic_or(flags, &mTransactionFlags);
1714}
1715
Robert Carr82364e32016-05-15 11:27:47 -07001716bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001717 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001718 return false;
1719 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001720
1721 // We update the requested and active position simultaneously because
1722 // we want to apply the position portion of the transform matrix immediately,
1723 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001724 mCurrentState.requested.transform.set(x, y);
Robert Carr7bf247e2017-05-18 14:02:49 -07001725 if (immediate && !mFreezeGeometryUpdates) {
1726 // Here we directly update the active state
1727 // unlike other setters, because we store it within
1728 // the transform, but use different latching rules.
1729 // b/38182305
Robert Carr82364e32016-05-15 11:27:47 -07001730 mCurrentState.active.transform.set(x, y);
1731 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001732 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001733
Dan Stoza7dde5992015-05-22 09:51:44 -07001734 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001735 setTransactionFlags(eTransactionNeeded);
1736 return true;
1737}
Robert Carr82364e32016-05-15 11:27:47 -07001738
Robert Carr1f0a16a2016-10-24 16:27:39 -07001739bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1740 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1741 if (idx < 0) {
1742 return false;
1743 }
1744 if (childLayer->setLayer(z)) {
1745 mCurrentChildren.removeAt(idx);
1746 mCurrentChildren.add(childLayer);
1747 }
1748 return true;
1749}
1750
Robert Carrae060832016-11-28 10:51:00 -08001751bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001752 if (mCurrentState.z == z)
1753 return false;
1754 mCurrentState.sequence++;
1755 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001756 mCurrentState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001757
1758 // Discard all relative layering.
1759 if (mCurrentState.zOrderRelativeOf != nullptr) {
1760 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1761 if (strongRelative != nullptr) {
1762 strongRelative->removeZOrderRelative(this);
1763 }
1764 mCurrentState.zOrderRelativeOf = nullptr;
1765 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001766 setTransactionFlags(eTransactionNeeded);
1767 return true;
1768}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001769
Robert Carrdb66e622017-04-10 16:55:57 -07001770void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1771 mCurrentState.zOrderRelatives.remove(relative);
1772 mCurrentState.sequence++;
1773 mCurrentState.modified = true;
1774 setTransactionFlags(eTransactionNeeded);
1775}
1776
1777void Layer::addZOrderRelative(const wp<Layer>& relative) {
1778 mCurrentState.zOrderRelatives.add(relative);
1779 mCurrentState.modified = true;
1780 mCurrentState.sequence++;
1781 setTransactionFlags(eTransactionNeeded);
1782}
1783
1784bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1785 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1786 if (handle == nullptr) {
1787 return false;
1788 }
1789 sp<Layer> relative = handle->owner.promote();
1790 if (relative == nullptr) {
1791 return false;
1792 }
1793
1794 mCurrentState.sequence++;
1795 mCurrentState.modified = true;
1796 mCurrentState.z = z;
1797
1798 mCurrentState.zOrderRelativeOf = relative;
1799 relative->addZOrderRelative(this);
1800
1801 setTransactionFlags(eTransactionNeeded);
1802
1803 return true;
1804}
1805
Mathias Agopian13127d82013-03-05 17:47:11 -08001806bool Layer::setSize(uint32_t w, uint32_t h) {
1807 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1808 return false;
1809 mCurrentState.requested.w = w;
1810 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001811 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001812 setTransactionFlags(eTransactionNeeded);
1813 return true;
1814}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001815#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001816bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001817#else
1818bool Layer::setAlpha(uint8_t alpha) {
1819#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001820 if (mCurrentState.alpha == alpha)
1821 return false;
1822 mCurrentState.sequence++;
1823 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001824 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001825 setTransactionFlags(eTransactionNeeded);
1826 return true;
1827}
1828bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1829 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001830 mCurrentState.requested.transform.set(
Robert Carrcb6e1e32017-02-21 19:48:26 -08001831 matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001832 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001833 setTransactionFlags(eTransactionNeeded);
1834 return true;
1835}
1836bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001837 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001838 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001839 setTransactionFlags(eTransactionNeeded);
1840 return true;
1841}
1842bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1843 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1844 if (mCurrentState.flags == newFlags)
1845 return false;
1846 mCurrentState.sequence++;
1847 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001848 mCurrentState.mask = mask;
1849 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001850 setTransactionFlags(eTransactionNeeded);
1851 return true;
1852}
Robert Carr99e27f02016-06-16 15:18:02 -07001853
1854bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001855 if (mCurrentState.requestedCrop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001856 return false;
1857 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001858 mCurrentState.requestedCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001859 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr99e27f02016-06-16 15:18:02 -07001860 mCurrentState.crop = crop;
1861 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001862 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1863
Dan Stoza7dde5992015-05-22 09:51:44 -07001864 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001865 setTransactionFlags(eTransactionNeeded);
1866 return true;
1867}
Robert Carr8d5227b2017-03-16 15:41:03 -07001868
1869bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001870 if (mCurrentState.requestedFinalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001871 return false;
1872 mCurrentState.sequence++;
Robert Carr8d5227b2017-03-16 15:41:03 -07001873 mCurrentState.requestedFinalCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001874 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr8d5227b2017-03-16 15:41:03 -07001875 mCurrentState.finalCrop = crop;
1876 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001877 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1878
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001879 mCurrentState.modified = true;
1880 setTransactionFlags(eTransactionNeeded);
1881 return true;
1882}
Mathias Agopian13127d82013-03-05 17:47:11 -08001883
Robert Carrc3574f72016-03-24 12:19:32 -07001884bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1885 if (scalingMode == mOverrideScalingMode)
1886 return false;
1887 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001888 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001889 return true;
1890}
1891
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001892void Layer::setInfo(uint32_t type, uint32_t appId) {
1893 mCurrentState.appId = appId;
1894 mCurrentState.type = type;
1895 mCurrentState.modified = true;
1896 setTransactionFlags(eTransactionNeeded);
1897}
1898
Robert Carrc3574f72016-03-24 12:19:32 -07001899uint32_t Layer::getEffectiveScalingMode() const {
1900 if (mOverrideScalingMode >= 0) {
1901 return mOverrideScalingMode;
1902 }
1903 return mCurrentScalingMode;
1904}
1905
Mathias Agopian13127d82013-03-05 17:47:11 -08001906bool Layer::setLayerStack(uint32_t layerStack) {
1907 if (mCurrentState.layerStack == layerStack)
1908 return false;
1909 mCurrentState.sequence++;
1910 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001911 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001912 setTransactionFlags(eTransactionNeeded);
1913 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001914}
1915
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07001916bool Layer::setDataSpace(android_dataspace dataSpace) {
1917 if (mCurrentState.dataSpace == dataSpace)
1918 return false;
1919 mCurrentState.sequence++;
1920 mCurrentState.dataSpace = dataSpace;
1921 mCurrentState.modified = true;
1922 setTransactionFlags(eTransactionNeeded);
1923 return true;
1924}
1925
Robert Carr1f0a16a2016-10-24 16:27:39 -07001926uint32_t Layer::getLayerStack() const {
1927 auto p = getParent();
1928 if (p == nullptr) {
1929 return getDrawingState().layerStack;
1930 }
1931 return p->getLayerStack();
1932}
1933
Robert Carr0d480722017-01-10 16:42:54 -08001934void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
Dan Stoza7dde5992015-05-22 09:51:44 -07001935 uint64_t frameNumber) {
Robert Carr0d480722017-01-10 16:42:54 -08001936 mCurrentState.barrierLayer = barrierLayer;
Dan Stoza7dde5992015-05-22 09:51:44 -07001937 mCurrentState.frameNumber = frameNumber;
1938 // We don't set eTransactionNeeded, because just receiving a deferral
1939 // request without any other state updates shouldn't actually induce a delay
1940 mCurrentState.modified = true;
1941 pushPendingState();
Robert Carr0d480722017-01-10 16:42:54 -08001942 mCurrentState.barrierLayer = nullptr;
Dan Stoza792e5292016-02-11 11:43:58 -08001943 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07001944 mCurrentState.modified = false;
Robert Carr0d480722017-01-10 16:42:54 -08001945 ALOGE("Deferred transaction");
1946}
1947
1948void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
1949 uint64_t frameNumber) {
1950 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
1951 deferTransactionUntil(handle->owner.promote(), frameNumber);
Dan Stoza7dde5992015-05-22 09:51:44 -07001952}
1953
Dan Stozaee44edd2015-03-23 15:50:23 -07001954void Layer::useSurfaceDamage() {
1955 if (mFlinger->mForceFullDamage) {
1956 surfaceDamageRegion = Region::INVALID_REGION;
1957 } else {
1958 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1959 }
1960}
1961
1962void Layer::useEmptyDamage() {
1963 surfaceDamageRegion.clear();
1964}
1965
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001966// ----------------------------------------------------------------------------
1967// pageflip handling...
1968// ----------------------------------------------------------------------------
1969
Dan Stoza6b9454d2014-11-07 16:00:59 -08001970bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001971 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07001972 return true;
1973 }
1974
Dan Stoza6b9454d2014-11-07 16:00:59 -08001975 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001976 if (mQueueItems.empty()) {
1977 return false;
1978 }
1979 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001980 nsecs_t expectedPresent =
1981 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001982
1983 // Ignore timestamps more than a second in the future
1984 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1985 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1986 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1987 expectedPresent);
1988
1989 bool isDue = timestamp < expectedPresent;
1990 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001991}
1992
Brian Andersond6927fb2016-07-23 23:37:30 -07001993bool Layer::onPreComposition(nsecs_t refreshStartTime) {
1994 if (mBufferLatched) {
1995 Mutex::Autolock lock(mFrameEventHistoryMutex);
1996 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
1997 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08001998 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001999 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002000}
2001
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002002bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
Brian Anderson3d4039d2016-09-23 16:31:30 -07002003 const std::shared_ptr<FenceTime>& presentFence,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002004 const CompositorTiming& compositorTiming) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002005 mAcquireTimeline.updateSignalTimes();
2006 mReleaseTimeline.updateSignalTimes();
2007
Brian Andersond6927fb2016-07-23 23:37:30 -07002008 // mFrameLatencyNeeded is true when a new frame was latched for the
2009 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08002010 if (!mFrameLatencyNeeded)
2011 return false;
2012
Fabien Sanglard28e98082016-12-05 10:19:46 -08002013 // Update mFrameEventHistory.
2014 {
2015 Mutex::Autolock lock(mFrameEventHistoryMutex);
2016 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002017 glDoneFence, presentFence, compositorTiming);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002018 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08002019
2020 // Update mFrameTracker.
2021 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
2022 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
2023
Brian Anderson3d4039d2016-09-23 16:31:30 -07002024 std::shared_ptr<FenceTime> frameReadyFence =
2025 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08002026 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002027 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002028 } else {
2029 // There was no fence for this frame, so assume that it was ready
2030 // to be presented at the desired present time.
2031 mFrameTracker.setFrameReadyTime(desiredPresentTime);
2032 }
2033
Brian Anderson3d4039d2016-09-23 16:31:30 -07002034 if (presentFence->isValid()) {
2035 mFrameTracker.setActualPresentFence(
2036 std::shared_ptr<FenceTime>(presentFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002037 } else {
2038 // The HWC doesn't support present fences, so use the refresh
2039 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002040 mFrameTracker.setActualPresentTime(
2041 mFlinger->getHwComposer().getRefreshTimestamp(
2042 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002043 }
2044
2045 mFrameTracker.advanceFrame();
2046 mFrameLatencyNeeded = false;
2047 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002048}
2049
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002050#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07002051void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Brian Anderson5ea5e592016-12-01 16:54:33 -08002052 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2053 return;
2054 }
2055
Brian Anderson3d4039d2016-09-23 16:31:30 -07002056 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002057 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002058 mReleaseTimeline.push(releaseFenceTime);
2059
2060 Mutex::Autolock lock(mFrameEventHistoryMutex);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002061 if (mPreviousFrameNumber != 0) {
2062 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2063 dequeueReadyTime, std::move(releaseFenceTime));
2064 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002065}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002066#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002067
Robert Carr1f0a16a2016-10-24 16:27:39 -07002068bool Layer::isHiddenByPolicy() const {
2069 const Layer::State& s(mDrawingState);
2070 const auto& parent = getParent();
2071 if (parent != nullptr && parent->isHiddenByPolicy()) {
2072 return true;
2073 }
2074 return s.flags & layer_state_t::eLayerHidden;
2075}
2076
Mathias Agopianda27af92012-09-13 18:17:13 -07002077bool Layer::isVisible() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002078#ifdef USE_HWC2
Robert Carr6452f122017-03-21 10:41:29 -07002079 return !(isHiddenByPolicy()) && getAlpha() > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08002080 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002081#else
Robert Carr6452f122017-03-21 10:41:29 -07002082 return !(isHiddenByPolicy()) && getAlpha()
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002083 && (mActiveBuffer != NULL || mSidebandStream != NULL);
2084#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07002085}
2086
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002087bool Layer::allTransactionsSignaled() {
2088 auto headFrameNumber = getHeadFrameNumber();
2089 bool matchingFramesFound = false;
2090 bool allTransactionsApplied = true;
2091 Mutex::Autolock lock(mLocalSyncPointMutex);
2092
2093 for (auto& point : mLocalSyncPoints) {
2094 if (point->getFrameNumber() > headFrameNumber) {
2095 break;
2096 }
2097 matchingFramesFound = true;
2098
2099 if (!point->frameIsAvailable()) {
2100 // We haven't notified the remote layer that the frame for
2101 // this point is available yet. Notify it now, and then
2102 // abort this attempt to latch.
2103 point->setFrameAvailable();
2104 allTransactionsApplied = false;
2105 break;
2106 }
2107
2108 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2109 }
2110 return !matchingFramesFound || allTransactionsApplied;
2111}
2112
Brian Andersond6927fb2016-07-23 23:37:30 -07002113Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002114{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08002115 ATRACE_CALL();
2116
Jesse Hall399184a2014-03-03 15:42:54 -08002117 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2118 // mSidebandStreamChanged was true
2119 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07002120 if (mSidebandStream != NULL) {
2121 setTransactionFlags(eTransactionNeeded);
2122 mFlinger->setTransactionFlags(eTraversalNeeded);
2123 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07002124 recomputeVisibleRegions = true;
2125
2126 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07002127 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08002128 }
2129
Mathias Agopian4fec8732012-06-29 14:12:52 -07002130 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07002131 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2132 return outDirtyRegion;
2133 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002134
Fabien Sanglard223eb912016-10-13 10:15:06 -07002135 // if we've already called updateTexImage() without going through
2136 // a composition step, we have to skip this layer at this point
2137 // because we cannot call updateTeximage() without a corresponding
2138 // compositionComplete() call.
2139 // we'll trigger an update in onPreComposition().
2140 if (mRefreshPending) {
2141 return outDirtyRegion;
2142 }
2143
2144 // If the head buffer's acquire fence hasn't signaled yet, return and
2145 // try again later
2146 if (!headFenceHasSignaled()) {
2147 mFlinger->signalLayerUpdate();
2148 return outDirtyRegion;
2149 }
2150
2151 // Capture the old state of the layer for comparisons later
2152 const State& s(getDrawingState());
2153 const bool oldOpacity = isOpaque(s);
2154 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2155
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002156 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002157 mFlinger->signalLayerUpdate();
2158 return outDirtyRegion;
2159 }
2160
2161 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2162 // of the buffer queue isn't modified when the buffer queue is returning
2163 // BufferItem's that weren't actually queued. This can happen in shared
2164 // buffer mode.
2165 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002166 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2167 getProducerStickyTransform() != 0, mName.string(),
Robert Carr7bf247e2017-05-18 14:02:49 -07002168 mOverrideScalingMode, mFreezeGeometryUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002169 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2170 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2171 mLastFrameNumberReceived);
2172 if (updateResult == BufferQueue::PRESENT_LATER) {
2173 // Producer doesn't want buffer to be displayed yet. Signal a
2174 // layer update so we check again at the next opportunity.
2175 mFlinger->signalLayerUpdate();
2176 return outDirtyRegion;
2177 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2178 // If the buffer has been rejected, remove it from the shadow queue
2179 // and return early
2180 if (queuedBuffer) {
2181 Mutex::Autolock lock(mQueueItemLock);
2182 mQueueItems.removeAt(0);
2183 android_atomic_dec(&mQueuedFrames);
2184 }
2185 return outDirtyRegion;
2186 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2187 // This can occur if something goes wrong when trying to create the
2188 // EGLImage for this buffer. If this happens, the buffer has already
2189 // been released, so we need to clean up the queue and bug out
2190 // early.
2191 if (queuedBuffer) {
2192 Mutex::Autolock lock(mQueueItemLock);
2193 mQueueItems.clear();
2194 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002195 }
2196
Fabien Sanglard223eb912016-10-13 10:15:06 -07002197 // Once we have hit this state, the shadow queue may no longer
2198 // correctly reflect the incoming BufferQueue's contents, so even if
2199 // updateTexImage starts working, the only safe course of action is
2200 // to continue to ignore updates.
2201 mUpdateTexImageFailed = true;
2202
2203 return outDirtyRegion;
2204 }
2205
2206 if (queuedBuffer) {
2207 // Autolock scope
2208 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2209
2210 Mutex::Autolock lock(mQueueItemLock);
2211
2212 // Remove any stale buffers that have been dropped during
2213 // updateTexImage
2214 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2215 mQueueItems.removeAt(0);
2216 android_atomic_dec(&mQueuedFrames);
2217 }
2218
2219 mQueueItems.removeAt(0);
2220 }
2221
2222
2223 // Decrement the queued-frames count. Signal another event if we
2224 // have more frames pending.
2225 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2226 || mAutoRefresh) {
2227 mFlinger->signalLayerUpdate();
2228 }
2229
Fabien Sanglard223eb912016-10-13 10:15:06 -07002230 // update the active buffer
Chia-I Wu06d63de2017-01-04 14:58:51 +08002231 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2232 &mActiveBufferSlot);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002233 if (mActiveBuffer == NULL) {
2234 // this can only happen if the very first buffer was rejected.
2235 return outDirtyRegion;
2236 }
2237
Brian Andersond6927fb2016-07-23 23:37:30 -07002238 mBufferLatched = true;
2239 mPreviousFrameNumber = mCurrentFrameNumber;
2240 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2241
2242 {
2243 Mutex::Autolock lock(mFrameEventHistoryMutex);
2244 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2245#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002246 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002247 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002248 mReleaseTimeline.push(releaseFenceTime);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002249 if (mPreviousFrameNumber != 0) {
2250 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2251 latchTime, std::move(releaseFenceTime));
2252 }
Brian Andersond6927fb2016-07-23 23:37:30 -07002253#endif
2254 }
2255
Fabien Sanglard223eb912016-10-13 10:15:06 -07002256 mRefreshPending = true;
2257 mFrameLatencyNeeded = true;
2258 if (oldActiveBuffer == NULL) {
2259 // the first time we receive a buffer, we need to trigger a
2260 // geometry invalidation.
2261 recomputeVisibleRegions = true;
2262 }
2263
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002264 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2265
Fabien Sanglard223eb912016-10-13 10:15:06 -07002266 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2267 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2268 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2269 if ((crop != mCurrentCrop) ||
2270 (transform != mCurrentTransform) ||
2271 (scalingMode != mCurrentScalingMode))
2272 {
2273 mCurrentCrop = crop;
2274 mCurrentTransform = transform;
2275 mCurrentScalingMode = scalingMode;
2276 recomputeVisibleRegions = true;
2277 }
2278
2279 if (oldActiveBuffer != NULL) {
2280 uint32_t bufWidth = mActiveBuffer->getWidth();
2281 uint32_t bufHeight = mActiveBuffer->getHeight();
2282 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2283 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002284 recomputeVisibleRegions = true;
2285 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002286 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002287
Fabien Sanglard223eb912016-10-13 10:15:06 -07002288 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2289 if (oldOpacity != isOpaque(s)) {
2290 recomputeVisibleRegions = true;
2291 }
Dan Stozacac35382016-01-27 12:21:06 -08002292
Fabien Sanglard223eb912016-10-13 10:15:06 -07002293 // Remove any sync points corresponding to the buffer which was just
2294 // latched
2295 {
2296 Mutex::Autolock lock(mLocalSyncPointMutex);
2297 auto point = mLocalSyncPoints.begin();
2298 while (point != mLocalSyncPoints.end()) {
2299 if (!(*point)->frameIsAvailable() ||
2300 !(*point)->transactionIsApplied()) {
2301 // This sync point must have been added since we started
2302 // latching. Don't drop it yet.
2303 ++point;
2304 continue;
2305 }
2306
2307 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2308 point = mLocalSyncPoints.erase(point);
2309 } else {
2310 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002311 }
2312 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002313 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002314
2315 // FIXME: postedRegion should be dirty & bounds
2316 Region dirtyRegion(Rect(s.active.w, s.active.h));
2317
2318 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002319 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002320
Mathias Agopian4fec8732012-06-29 14:12:52 -07002321 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002322}
2323
Mathias Agopiana67932f2011-04-20 14:20:59 -07002324uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002325{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002326 // TODO: should we do something special if mSecure is set?
2327 if (mProtectedByApp) {
2328 // need a hardware-protected path to external video sink
2329 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002330 }
Riley Andrews03414a12014-07-01 14:22:59 -07002331 if (mPotentialCursor) {
2332 usage |= GraphicBuffer::USAGE_CURSOR;
2333 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002334 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002335 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002336}
2337
Mathias Agopian84300952012-11-21 16:02:13 -08002338void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002339 uint32_t orientation = 0;
2340 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002341 // The transform hint is used to improve performance, but we can
2342 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002343 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002344 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002345 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002346 if (orientation & Transform::ROT_INVALID) {
2347 orientation = 0;
2348 }
2349 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002350 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002351}
2352
Mathias Agopian13127d82013-03-05 17:47:11 -08002353// ----------------------------------------------------------------------------
2354// debugging
2355// ----------------------------------------------------------------------------
2356
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002357void Layer::dump(String8& result, Colorizer& colorizer) const
Mathias Agopian13127d82013-03-05 17:47:11 -08002358{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002359 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08002360
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002361 colorizer.colorize(result, Colorizer::GREEN);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002362 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002363 "+ %s %p (%s)\n",
2364 getTypeId(), this, getName().string());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002365 colorizer.reset(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002366
Mathias Agopian2ca79392013-04-02 18:30:32 -07002367 s.activeTransparentRegion.dump(result, "transparentRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002368 visibleRegion.dump(result, "visibleRegion");
Dan Stozaee44edd2015-03-23 15:50:23 -07002369 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002370 sp<Client> client(mClientRef.promote());
2371
Mathias Agopian74d211a2013-04-22 16:55:35 +02002372 result.appendFormat( " "
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002373 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2374 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
Mathias Agopian13127d82013-03-05 17:47:11 -08002375 "isOpaque=%1d, invalidate=%1d, "
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002376#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08002377 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002378#else
2379 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2380#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08002381 " client=%p\n",
Robert Carr1f0a16a2016-10-24 16:27:39 -07002382 getLayerStack(), s.z,
2383 s.active.transform.tx(), s.active.transform.ty(),
2384 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07002385 s.crop.left, s.crop.top,
2386 s.crop.right, s.crop.bottom,
2387 s.finalCrop.left, s.finalCrop.top,
2388 s.finalCrop.right, s.finalCrop.bottom,
Andy McFadden4125a4f2014-01-29 17:17:11 -08002389 isOpaque(s), contentDirty,
Mathias Agopian13127d82013-03-05 17:47:11 -08002390 s.alpha, s.flags,
Robert Carr3dcabfa2016-03-01 18:36:58 -08002391 s.active.transform[0][0], s.active.transform[0][1],
2392 s.active.transform[1][0], s.active.transform[1][1],
Mathias Agopian13127d82013-03-05 17:47:11 -08002393 client.get());
Mathias Agopian13127d82013-03-05 17:47:11 -08002394
2395 sp<const GraphicBuffer> buf0(mActiveBuffer);
2396 uint32_t w0=0, h0=0, s0=0, f0=0;
2397 if (buf0 != 0) {
2398 w0 = buf0->getWidth();
2399 h0 = buf0->getHeight();
2400 s0 = buf0->getStride();
2401 f0 = buf0->format;
2402 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02002403 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002404 " "
2405 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2406 " queued-frames=%d, mRefreshPending=%d\n",
2407 mFormat, w0, h0, s0,f0,
2408 mQueuedFrames, mRefreshPending);
2409
Mathias Agopian13127d82013-03-05 17:47:11 -08002410 if (mSurfaceFlingerConsumer != 0) {
Colin Cross3d1d2802016-09-26 18:10:16 -07002411 mSurfaceFlingerConsumer->dumpState(result, " ");
Mathias Agopian13127d82013-03-05 17:47:11 -08002412 }
2413}
2414
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002415#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002416void Layer::miniDumpHeader(String8& result) {
2417 result.append("----------------------------------------");
2418 result.append("---------------------------------------\n");
2419 result.append(" Layer name\n");
2420 result.append(" Z | ");
2421 result.append(" Comp Type | ");
2422 result.append(" Disp Frame (LTRB) | ");
2423 result.append(" Source Crop (LTRB)\n");
2424 result.append("----------------------------------------");
2425 result.append("---------------------------------------\n");
2426}
2427
2428void Layer::miniDump(String8& result, int32_t hwcId) const {
2429 if (mHwcLayers.count(hwcId) == 0) {
2430 return;
2431 }
2432
2433 String8 name;
2434 if (mName.length() > 77) {
2435 std::string shortened;
2436 shortened.append(mName.string(), 36);
2437 shortened.append("[...]");
2438 shortened.append(mName.string() + (mName.length() - 36), 36);
2439 name = shortened.c_str();
2440 } else {
2441 name = mName;
2442 }
2443
2444 result.appendFormat(" %s\n", name.string());
2445
2446 const Layer::State& layerState(getDrawingState());
2447 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2448 result.appendFormat(" %10u | ", layerState.z);
2449 result.appendFormat("%10s | ",
2450 to_string(getCompositionType(hwcId)).c_str());
2451 const Rect& frame = hwcInfo.displayFrame;
2452 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2453 frame.right, frame.bottom);
Dan Stoza5a423ea2017-02-16 14:10:39 -08002454 const FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002455 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2456 crop.right, crop.bottom);
2457
2458 result.append("- - - - - - - - - - - - - - - - - - - - ");
2459 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2460}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002461#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002462
Svetoslavd85084b2014-03-20 10:28:31 -07002463void Layer::dumpFrameStats(String8& result) const {
2464 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002465}
2466
Svetoslavd85084b2014-03-20 10:28:31 -07002467void Layer::clearFrameStats() {
2468 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002469}
2470
Jamie Gennis6547ff42013-07-16 20:12:42 -07002471void Layer::logFrameStats() {
2472 mFrameTracker.logAndResetStats(mName);
2473}
2474
Svetoslavd85084b2014-03-20 10:28:31 -07002475void Layer::getFrameStats(FrameStats* outStats) const {
2476 mFrameTracker.getStats(outStats);
2477}
2478
Brian Andersond6927fb2016-07-23 23:37:30 -07002479void Layer::dumpFrameEvents(String8& result) {
2480 result.appendFormat("- Layer %s (%s, %p)\n",
2481 getName().string(), getTypeId(), this);
2482 Mutex::Autolock lock(mFrameEventHistoryMutex);
2483 mFrameEventHistory.checkFencesForCompletion();
2484 mFrameEventHistory.dump(result);
2485}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002486
Brian Anderson5ea5e592016-12-01 16:54:33 -08002487void Layer::onDisconnect() {
2488 Mutex::Autolock lock(mFrameEventHistoryMutex);
2489 mFrameEventHistory.onDisconnect();
2490}
2491
Brian Anderson3890c392016-07-25 12:48:08 -07002492void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2493 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002494 Mutex::Autolock lock(mFrameEventHistoryMutex);
2495 if (newTimestamps) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002496 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002497 mFrameEventHistory.addQueue(*newTimestamps);
2498 }
2499
Brian Anderson3890c392016-07-25 12:48:08 -07002500 if (outDelta) {
2501 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002502 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002503}
Dan Stozae77c7662016-05-13 11:37:28 -07002504
2505std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2506 bool forceFlush) {
2507 std::vector<OccupancyTracker::Segment> history;
2508 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2509 &history);
2510 if (result != NO_ERROR) {
2511 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2512 result);
2513 return {};
2514 }
2515 return history;
2516}
2517
Robert Carr367c5682016-06-20 11:55:28 -07002518bool Layer::getTransformToDisplayInverse() const {
2519 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2520}
2521
Robert Carr1f0a16a2016-10-24 16:27:39 -07002522void Layer::addChild(const sp<Layer>& layer) {
2523 mCurrentChildren.add(layer);
2524 layer->setParent(this);
2525}
2526
2527ssize_t Layer::removeChild(const sp<Layer>& layer) {
2528 layer->setParent(nullptr);
2529 return mCurrentChildren.remove(layer);
2530}
2531
Robert Carr1db73f62016-12-21 12:58:51 -08002532bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2533 sp<Handle> handle = nullptr;
2534 sp<Layer> newParent = nullptr;
2535 if (newParentHandle == nullptr) {
2536 return false;
2537 }
2538 handle = static_cast<Handle*>(newParentHandle.get());
2539 newParent = handle->owner.promote();
2540 if (newParent == nullptr) {
2541 ALOGE("Unable to promote Layer handle");
2542 return false;
2543 }
2544
2545 for (const sp<Layer>& child : mCurrentChildren) {
Robert Carr98b0fd52017-06-01 14:59:25 -07002546 // We don't call addChild as we need to delay updating the child's parent pointer until
2547 // a transaction occurs. Remember a refresh could occur in between now and the next
2548 // transaction, in which case the Layer's parent pointer would be updated, but changes
2549 // made to the parent in the same transaction would not have applied.
2550 // This means that the following kind of scenario wont work:
2551 //
2552 // 1. Existing and visible child and parent surface exist
2553 // 2. Create new surface hidden
2554 // 3. Open transaction
2555 // 4. Show the new surface, and reparent the old surface's children to it.
2556 // 5. Close transaction.
2557 //
2558 // If we were to update the parent pointer immediately, then the child surface
2559 // could disappear for one frame as it pointed at the new parent which
2560 // hasn't yet become visible as the transaction hasn't yet occurred.
2561 //
2562 // Instead we defer the reparenting to commitChildList which happens as part
2563 // of the global transaction.
2564 newParent->mCurrentChildren.add(child);
Robert Carr1db73f62016-12-21 12:58:51 -08002565
2566 sp<Client> client(child->mClientRef.promote());
2567 if (client != nullptr) {
2568 client->setParentLayer(newParent);
2569 }
2570 }
2571 mCurrentChildren.clear();
2572
2573 return true;
2574}
2575
Robert Carr9524cb32017-02-13 11:32:32 -08002576bool Layer::detachChildren() {
Dan Stoza412903f2017-04-27 13:42:17 -07002577 traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
Robert Carr9524cb32017-02-13 11:32:32 -08002578 if (child == this) {
2579 return;
2580 }
2581
2582 sp<Client> client(child->mClientRef.promote());
2583 if (client != nullptr) {
2584 client->detachLayer(child);
2585 }
2586 });
2587
2588 return true;
2589}
2590
Robert Carr1f0a16a2016-10-24 16:27:39 -07002591void Layer::setParent(const sp<Layer>& layer) {
2592 mParent = layer;
2593}
2594
2595void Layer::clearSyncPoints() {
2596 for (const auto& child : mCurrentChildren) {
2597 child->clearSyncPoints();
2598 }
2599
2600 Mutex::Autolock lock(mLocalSyncPointMutex);
2601 for (auto& point : mLocalSyncPoints) {
2602 point->setFrameAvailable();
2603 }
2604 mLocalSyncPoints.clear();
2605}
2606
2607int32_t Layer::getZ() const {
2608 return mDrawingState.z;
2609}
2610
Dan Stoza412903f2017-04-27 13:42:17 -07002611LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2612 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2613 "makeTraversalList received invalid stateSet");
2614 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2615 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2616 const State& state = useDrawing ? mDrawingState : mCurrentState;
2617
2618 if (state.zOrderRelatives.size() == 0) {
2619 return children;
Robert Carrdb66e622017-04-10 16:55:57 -07002620 }
2621 LayerVector traverse;
2622
Dan Stoza412903f2017-04-27 13:42:17 -07002623 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07002624 sp<Layer> strongRelative = weakRelative.promote();
2625 if (strongRelative != nullptr) {
2626 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07002627 }
2628 }
2629
Dan Stoza412903f2017-04-27 13:42:17 -07002630 for (const sp<Layer>& child : children) {
Robert Carrdb66e622017-04-10 16:55:57 -07002631 traverse.add(child);
2632 }
2633
2634 return traverse;
2635}
2636
Robert Carr1f0a16a2016-10-24 16:27:39 -07002637/**
Robert Carrdb66e622017-04-10 16:55:57 -07002638 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002639 */
Dan Stoza412903f2017-04-27 13:42:17 -07002640void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2641 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002642
Robert Carr1f0a16a2016-10-24 16:27:39 -07002643 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002644 for (; i < list.size(); i++) {
2645 const auto& relative = list[i];
2646 if (relative->getZ() >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002647 break;
Robert Carrdb66e622017-04-10 16:55:57 -07002648 }
Dan Stoza412903f2017-04-27 13:42:17 -07002649 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002650 }
Dan Stoza412903f2017-04-27 13:42:17 -07002651 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07002652 for (; i < list.size(); i++) {
2653 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002654 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002655 }
2656}
2657
2658/**
Robert Carrdb66e622017-04-10 16:55:57 -07002659 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002660 */
Dan Stoza412903f2017-04-27 13:42:17 -07002661void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2662 const LayerVector::Visitor& visitor) {
2663 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002664
Robert Carr1f0a16a2016-10-24 16:27:39 -07002665 int32_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002666 for (i = list.size()-1; i>=0; i--) {
2667 const auto& relative = list[i];
2668 if (relative->getZ() < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002669 break;
2670 }
Dan Stoza412903f2017-04-27 13:42:17 -07002671 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002672 }
Dan Stoza412903f2017-04-27 13:42:17 -07002673 visitor(this);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002674 for (; i>=0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002675 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002676 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002677 }
2678}
2679
2680Transform Layer::getTransform() const {
2681 Transform t;
2682 const auto& p = getParent();
2683 if (p != nullptr) {
2684 t = p->getTransform();
Robert Carr9b429f42017-04-17 14:56:57 -07002685
2686 // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2687 // it isFixedSize) then there may be additional scaling not accounted
2688 // for in the transform. We need to mirror this scaling in child surfaces
2689 // or we will break the contract where WM can treat child surfaces as
2690 // pixels in the parent surface.
2691 if (p->isFixedSize()) {
Robert Carr1725eee2017-04-26 18:32:15 -07002692 int bufferWidth;
2693 int bufferHeight;
2694 if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2695 bufferWidth = p->mActiveBuffer->getWidth();
2696 bufferHeight = p->mActiveBuffer->getHeight();
2697 } else {
2698 bufferHeight = p->mActiveBuffer->getWidth();
2699 bufferWidth = p->mActiveBuffer->getHeight();
2700 }
Robert Carr9b429f42017-04-17 14:56:57 -07002701 float sx = p->getDrawingState().active.w /
Robert Carr1725eee2017-04-26 18:32:15 -07002702 static_cast<float>(bufferWidth);
Robert Carr9b429f42017-04-17 14:56:57 -07002703 float sy = p->getDrawingState().active.h /
Robert Carr1725eee2017-04-26 18:32:15 -07002704 static_cast<float>(bufferHeight);
Robert Carr9b429f42017-04-17 14:56:57 -07002705 Transform extraParentScaling;
2706 extraParentScaling.set(sx, 0, 0, sy);
2707 t = t * extraParentScaling;
2708 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002709 }
2710 return t * getDrawingState().active.transform;
2711}
2712
Robert Carr6452f122017-03-21 10:41:29 -07002713#ifdef USE_HWC2
2714float Layer::getAlpha() const {
2715 const auto& p = getParent();
2716
2717 float parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0;
2718 return parentAlpha * getDrawingState().alpha;
2719}
2720#else
2721uint8_t Layer::getAlpha() const {
2722 const auto& p = getParent();
2723
2724 float parentAlpha = (p != nullptr) ? (p->getAlpha() / 255.0f) : 1.0;
2725 float drawingAlpha = getDrawingState().alpha / 255.0f;
2726 drawingAlpha = drawingAlpha * parentAlpha;
2727 return static_cast<uint8_t>(std::round(drawingAlpha * 255));
2728}
2729#endif
2730
Robert Carr1f0a16a2016-10-24 16:27:39 -07002731void Layer::commitChildList() {
2732 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2733 const auto& child = mCurrentChildren[i];
Robert Carr98b0fd52017-06-01 14:59:25 -07002734 child->setParent(this);
2735
Robert Carr1f0a16a2016-10-24 16:27:39 -07002736 child->commitChildList();
2737 }
2738 mDrawingChildren = mCurrentChildren;
2739}
2740
Mathias Agopian13127d82013-03-05 17:47:11 -08002741// ---------------------------------------------------------------------------
2742
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002743}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002744
2745#if defined(__gl_h_)
2746#error "don't include gl/gl.h in this file"
2747#endif
2748
2749#if defined(__gl2_h_)
2750#error "don't include gl2/gl2.h in this file"
2751#endif