blob: 6f430a386f9dcb7d22798fa7fe382fa84665f739 [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
Robert Carr41b08b52017-06-01 16:11:34 -0700402 if (!s.finalCrop.isEmpty()) {
403 win.intersect(s.finalCrop, &win);
404 }
405
Robert Carr1f0a16a2016-10-24 16:27:39 -0700406 const sp<Layer>& p = getParent();
407 // Now we need to calculate the parent bounds, so we can clip ourselves to those.
408 // When calculating the parent bounds for purposes of clipping,
409 // we don't need to constrain the parent to its transparent region.
410 // The transparent region is an optimization based on the
411 // buffer contents of the layer, but does not affect the space allocated to
412 // it by policy, and thus children should be allowed to extend into the
413 // parent's transparent region. In fact one of the main uses, is to reduce
414 // buffer allocation size in cases where a child window sits behind a main window
415 // (by marking the hole in the parent window as a transparent region)
416 if (p != nullptr) {
417 Rect bounds = p->computeScreenBounds(false);
418 bounds.intersect(win, &win);
419 }
420
421 if (reduceTransparentRegion) {
422 auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
423 win = reduce(win, screenTransparentRegion);
424 }
425
426 return win;
427}
428
Mathias Agopian13127d82013-03-05 17:47:11 -0800429Rect Layer::computeBounds() const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700430 const Layer::State& s(getDrawingState());
Michael Lentine6c925ed2014-09-26 17:55:01 -0700431 return computeBounds(s.activeTransparentRegion);
432}
433
434Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
435 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800436 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700437
438 if (!s.crop.isEmpty()) {
439 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -0800440 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700441
442 Rect bounds = win;
443 const auto& p = getParent();
444 if (p != nullptr) {
Robert Carrde9ec442017-02-08 17:43:36 -0800445 // Look in computeScreenBounds recursive call for explanation of
446 // why we pass false here.
447 bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700448 }
449
450 Transform t = getTransform();
451 if (p != nullptr) {
452 win = t.transform(win);
453 win.intersect(bounds, &win);
454 win = t.inverse().transform(win);
455 }
456
Mathias Agopian6c7f25a2013-05-09 20:37:10 -0700457 // subtract the transparent region and snap to the bounds
Michael Lentine6c925ed2014-09-26 17:55:01 -0700458 return reduce(win, activeTransparentRegion);
Mathias Agopian13127d82013-03-05 17:47:11 -0800459}
460
Robert Carr1f0a16a2016-10-24 16:27:39 -0700461Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
Robert Carrb5d3d262016-03-25 15:08:13 -0700462 // the crop is the area of the window that gets cropped, but not
Mathias Agopian13127d82013-03-05 17:47:11 -0800463 // scaled in any ways.
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700464 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800465
466 // apply the projection's clipping to the window crop in
467 // layerstack space, and convert-back to layer space.
Mathias Agopian6b442672013-07-09 21:24:52 -0700468 // if there are no window scaling involved, this operation will map to full
469 // pixels in the buffer.
470 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
471 // a viewport clipping and a window transform. we should use floating point to fix this.
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700472
473 Rect activeCrop(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700474 if (!s.crop.isEmpty()) {
475 activeCrop = s.crop;
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700476 }
477
Robert Carr1f0a16a2016-10-24 16:27:39 -0700478 Transform t = getTransform();
479 activeCrop = t.transform(activeCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000480 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
481 activeCrop.clear();
482 }
Robert Carrb5d3d262016-03-25 15:08:13 -0700483 if (!s.finalCrop.isEmpty()) {
484 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000485 activeCrop.clear();
486 }
487 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700488 return activeCrop;
489}
490
Dan Stoza5a423ea2017-02-16 14:10:39 -0800491FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
Robert Carr1f0a16a2016-10-24 16:27:39 -0700492 // the content crop is the area of the content that gets scaled to the
493 // layer's size. This is in buffer space.
Dan Stoza5a423ea2017-02-16 14:10:39 -0800494 FloatRect crop = getContentCrop().toFloatRect();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700495
496 // In addition there is a WM-specified crop we pull from our drawing state.
497 const State& s(getDrawingState());
498
499 // Screen space to make reduction to parent crop clearer.
500 Rect activeCrop = computeInitialCrop(hw);
501 const auto& p = getParent();
502 if (p != nullptr) {
503 auto parentCrop = p->computeInitialCrop(hw);
504 activeCrop.intersect(parentCrop, &activeCrop);
505 }
506 Transform t = getTransform();
507 // Back to layer space to work with the content crop.
508 activeCrop = t.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800509
Michael Lentine28ea2172014-11-19 18:32:37 -0800510 // This needs to be here as transform.transform(Rect) computes the
511 // transformed rect and then takes the bounding box of the result before
512 // returning. This means
513 // transform.inverse().transform(transform.transform(Rect)) != Rect
514 // in which case we need to make sure the final rect is clipped to the
515 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000516 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
517 activeCrop.clear();
518 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800519
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700520 // subtract the transparent region and snap to the bounds
521 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
522
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000523 // Transform the window crop to match the buffer coordinate system,
524 // which means using the inverse of the current transform set on the
525 // SurfaceFlingerConsumer.
526 uint32_t invTransform = mCurrentTransform;
Robert Carrcae605c2017-03-29 12:10:31 -0700527 if (getTransformToDisplayInverse()) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000528 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700529 * the code below applies the primary display's inverse transform to the
530 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000531 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700532 uint32_t invTransformOrient =
533 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000534 // calculate the inverse transform
535 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
536 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
537 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800538 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000539 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700540 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
541 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800542 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000543
544 int winWidth = s.active.w;
545 int winHeight = s.active.h;
546 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
547 // If the activeCrop has been rotate the ends are rotated but not
548 // the space itself so when transforming ends back we can't rely on
549 // a modification of the axes of rotation. To account for this we
550 // need to reorient the inverse rotation in terms of the current
551 // axes of rotation.
552 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
553 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
554 if (is_h_flipped == is_v_flipped) {
555 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
556 NATIVE_WINDOW_TRANSFORM_FLIP_H;
557 }
558 winWidth = s.active.h;
559 winHeight = s.active.w;
560 }
561 const Rect winCrop = activeCrop.transform(
562 invTransform, s.active.w, s.active.h);
563
564 // below, crop is intersected with winCrop expressed in crop's coordinate space
565 float xScale = crop.getWidth() / float(winWidth);
566 float yScale = crop.getHeight() / float(winHeight);
567
568 float insetL = winCrop.left * xScale;
569 float insetT = winCrop.top * yScale;
570 float insetR = (winWidth - winCrop.right ) * xScale;
571 float insetB = (winHeight - winCrop.bottom) * yScale;
572
573 crop.left += insetL;
574 crop.top += insetT;
575 crop.right -= insetR;
576 crop.bottom -= insetB;
577
Mathias Agopian13127d82013-03-05 17:47:11 -0800578 return crop;
579}
580
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000581#ifdef USE_HWC2
Robert Carrae060832016-11-28 10:51:00 -0800582void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000583#else
584void Layer::setGeometry(
585 const sp<const DisplayDevice>& hw,
586 HWComposer::HWCLayerInterface& layer)
587#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700588{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000589#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800590 const auto hwcId = displayDevice->getHwcDisplayId();
591 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000592#else
593 layer.setDefaultState();
594#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700595
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700596 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000597#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800598 hwcInfo.forceClientComposition = false;
599
600 if (isSecure() && !displayDevice->isSecure()) {
601 hwcInfo.forceClientComposition = true;
602 }
603
604 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000605#else
606 layer.setSkip(false);
607
608 if (isSecure() && !hw->isSecure()) {
609 layer.setSkip(true);
610 }
611#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700612
Mathias Agopian13127d82013-03-05 17:47:11 -0800613 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700614 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000615#ifdef USE_HWC2
David Revemanecf0fa52017-03-03 11:32:44 -0500616 auto blendMode = HWC2::BlendMode::None;
Robert Carr6452f122017-03-21 10:41:29 -0700617 if (!isOpaque(s) || getAlpha() != 1.0f) {
David Revemanecf0fa52017-03-03 11:32:44 -0500618 blendMode = mPremultipliedAlpha ?
Dan Stoza9e56aa02015-11-02 13:00:03 -0800619 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800620 }
David Revemanecf0fa52017-03-03 11:32:44 -0500621 auto error = hwcLayer->setBlendMode(blendMode);
622 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
623 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
624 to_string(error).c_str(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000625#else
Robert Carr6452f122017-03-21 10:41:29 -0700626 if (!isOpaque(s) || getAlpha() != 0xFF) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000627 layer.setBlending(mPremultipliedAlpha ?
628 HWC_BLENDING_PREMULT :
629 HWC_BLENDING_COVERAGE);
630 }
631#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800632
633 // apply the layer's transform, followed by the display's global transform
634 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700635 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700636 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -0700637 if (!s.crop.isEmpty()) {
638 Rect activeCrop(s.crop);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700639 activeCrop = t.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000640#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000641 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000642#else
643 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
644#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000645 activeCrop.clear();
646 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700647 activeCrop = t.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800648 // This needs to be here as transform.transform(Rect) computes the
649 // transformed rect and then takes the bounding box of the result before
650 // returning. This means
651 // transform.inverse().transform(transform.transform(Rect)) != Rect
652 // in which case we need to make sure the final rect is clipped to the
653 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000654 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
655 activeCrop.clear();
656 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700657 // mark regions outside the crop as transparent
658 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
659 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
660 s.active.w, s.active.h));
661 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
662 activeCrop.left, activeCrop.bottom));
663 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
664 s.active.w, activeCrop.bottom));
665 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700666
667 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700668 if (!s.finalCrop.isEmpty()) {
669 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000670 frame.clear();
671 }
672 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000673#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000674 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
675 frame.clear();
676 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800677 const Transform& tr(displayDevice->getTransform());
678 Rect transformedFrame = tr.transform(frame);
David Revemanecf0fa52017-03-03 11:32:44 -0500679 error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700680 if (error != HWC2::Error::None) {
681 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
682 mName.string(), transformedFrame.left, transformedFrame.top,
683 transformedFrame.right, transformedFrame.bottom,
684 to_string(error).c_str(), static_cast<int32_t>(error));
685 } else {
686 hwcInfo.displayFrame = transformedFrame;
687 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800688
Dan Stoza5a423ea2017-02-16 14:10:39 -0800689 FloatRect sourceCrop = computeCrop(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800690 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700691 if (error != HWC2::Error::None) {
692 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
693 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
694 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
695 static_cast<int32_t>(error));
696 } else {
697 hwcInfo.sourceCrop = sourceCrop;
698 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800699
Robert Carr6452f122017-03-21 10:41:29 -0700700 float alpha = getAlpha();
701 error = hwcLayer->setPlaneAlpha(alpha);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800702 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
Robert Carr6452f122017-03-21 10:41:29 -0700703 "%s (%d)", mName.string(), alpha, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800704 static_cast<int32_t>(error));
705
Robert Carrae060832016-11-28 10:51:00 -0800706 error = hwcLayer->setZOrder(z);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800707 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
Robert Carrae060832016-11-28 10:51:00 -0800708 mName.string(), z, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800709 static_cast<int32_t>(error));
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500710
Albert Chaulk2a589632017-05-04 16:59:44 -0400711 int type = s.type;
712 int appId = s.appId;
713 sp<Layer> parent = mParent.promote();
714 if (parent.get()) {
715 auto& parentState = parent->getDrawingState();
716 type = parentState.type;
717 appId = parentState.appId;
718 }
719
720 error = hwcLayer->setInfo(type, appId);
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500721 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
722 mName.string(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000723#else
724 if (!frame.intersect(hw->getViewport(), &frame)) {
725 frame.clear();
726 }
727 const Transform& tr(hw->getTransform());
728 layer.setFrame(tr.transform(frame));
729 layer.setCrop(computeCrop(hw));
Robert Carr6452f122017-03-21 10:41:29 -0700730 layer.setPlaneAlpha(getAlpha());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000731#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800732
Mathias Agopian29a367b2011-07-12 14:51:45 -0700733 /*
734 * Transformations are applied in this order:
735 * 1) buffer orientation/flip/mirror
736 * 2) state transformation (window manager)
737 * 3) layer orientation (screen orientation)
738 * (NOTE: the matrices are multiplied in reverse order)
739 */
740
741 const Transform bufferOrientation(mCurrentTransform);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700742 Transform transform(tr * t * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700743
Robert Carrcae605c2017-03-29 12:10:31 -0700744 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700745 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700746 * the code below applies the primary display's inverse transform to the
747 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700748 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700749 uint32_t invTransform =
750 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700751 // calculate the inverse transform
752 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
753 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
754 NATIVE_WINDOW_TRANSFORM_FLIP_H;
755 }
Robert Carrcae605c2017-03-29 12:10:31 -0700756
757 /*
758 * Here we cancel out the orientation component of the WM transform.
759 * The scaling and translate components are already included in our bounds
760 * computation so it's enough to just omit it in the composition.
761 * See comment in onDraw with ref to b/36727915 for why.
762 */
763 transform = Transform(invTransform) * tr * bufferOrientation;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700764 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700765
766 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800767 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000768#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800769 if (orientation & Transform::ROT_INVALID) {
770 // we can only handle simple transformation
771 hwcInfo.forceClientComposition = true;
772 } else {
773 auto transform = static_cast<HWC2::Transform>(orientation);
774 auto error = hwcLayer->setTransform(transform);
775 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
776 "%s (%d)", mName.string(), to_string(transform).c_str(),
777 to_string(error).c_str(), static_cast<int32_t>(error));
778 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000779#else
780 if (orientation & Transform::ROT_INVALID) {
781 // we can only handle simple transformation
782 layer.setSkip(true);
783 } else {
784 layer.setTransform(orientation);
785 }
786#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700787}
788
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000789#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800790void Layer::forceClientComposition(int32_t hwcId) {
791 if (mHwcLayers.count(hwcId) == 0) {
792 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
793 return;
794 }
795
796 mHwcLayers[hwcId].forceClientComposition = true;
797}
Dan Stoza9e56aa02015-11-02 13:00:03 -0800798
Dan Stoza9e56aa02015-11-02 13:00:03 -0800799void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
800 // Apply this display's projection's viewport to the visible region
801 // before giving it to the HWC HAL.
802 const Transform& tr = displayDevice->getTransform();
803 const auto& viewport = displayDevice->getViewport();
804 Region visible = tr.transform(visibleRegion.intersect(viewport));
805 auto hwcId = displayDevice->getHwcDisplayId();
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800806 auto& hwcInfo = mHwcLayers[hwcId];
807 auto& hwcLayer = hwcInfo.layer;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800808 auto error = hwcLayer->setVisibleRegion(visible);
809 if (error != HWC2::Error::None) {
810 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
811 to_string(error).c_str(), static_cast<int32_t>(error));
812 visible.dump(LOG_TAG);
813 }
814
815 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
816 if (error != HWC2::Error::None) {
817 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
818 to_string(error).c_str(), static_cast<int32_t>(error));
819 surfaceDamageRegion.dump(LOG_TAG);
820 }
821
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700822 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800823 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700824 setCompositionType(hwcId, HWC2::Composition::Sideband);
825 ALOGV("[%s] Requesting Sideband composition", mName.string());
826 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800827 if (error != HWC2::Error::None) {
828 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
829 mName.string(), mSidebandStream->handle(),
830 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800831 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700832 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800833 }
834
Dan Stoza0a21df72016-07-20 12:52:38 -0700835 // Client layers
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800836 if (hwcInfo.forceClientComposition ||
Dan Stoza0a21df72016-07-20 12:52:38 -0700837 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700838 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800839 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700840 return;
841 }
842
Dan Stoza0a21df72016-07-20 12:52:38 -0700843 // SolidColor layers
844 if (mActiveBuffer == nullptr) {
845 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700846
847 // For now, we only support black for DimLayer
Dan Stoza0a21df72016-07-20 12:52:38 -0700848 error = hwcLayer->setColor({0, 0, 0, 255});
849 if (error != HWC2::Error::None) {
850 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
851 to_string(error).c_str(), static_cast<int32_t>(error));
852 }
Dan Stozac6c89542016-07-27 10:16:52 -0700853
854 // Clear out the transform, because it doesn't make sense absent a
855 // source buffer
856 error = hwcLayer->setTransform(HWC2::Transform::None);
857 if (error != HWC2::Error::None) {
858 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
859 to_string(error).c_str(), static_cast<int32_t>(error));
860 }
861
Dan Stoza0a21df72016-07-20 12:52:38 -0700862 return;
863 }
864
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700865 // Device or Cursor layers
866 if (mPotentialCursor) {
867 ALOGV("[%s] Requesting Cursor composition", mName.string());
868 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800869 } else {
870 ALOGV("[%s] Requesting Device composition", mName.string());
871 setCompositionType(hwcId, HWC2::Composition::Device);
872 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700873
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700874 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
875 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
876 if (error != HWC2::Error::None) {
877 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
878 mCurrentState.dataSpace, to_string(error).c_str(),
879 static_cast<int32_t>(error));
880 }
881
Chia-I Wu06d63de2017-01-04 14:58:51 +0800882 uint32_t hwcSlot = 0;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400883 sp<GraphicBuffer> hwcBuffer;
884 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
885 &hwcSlot, &hwcBuffer);
Chia-I Wu06d63de2017-01-04 14:58:51 +0800886
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700887 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400888 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700889 if (error != HWC2::Error::None) {
890 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
891 mActiveBuffer->handle, to_string(error).c_str(),
892 static_cast<int32_t>(error));
893 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894}
Courtney Goeltzenleuchter9551fd32016-10-20 17:18:15 -0600895
896android_dataspace Layer::getDataSpace() const {
897 return mCurrentState.dataSpace;
898}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000899#else
900void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
901 HWComposer::HWCLayerInterface& layer) {
902 // we have to set the visible region on every frame because
903 // we currently free it during onLayerDisplayed(), which is called
904 // after HWComposer::commit() -- every frame.
905 // Apply this display's projection's viewport to the visible region
906 // before giving it to the HWC HAL.
907 const Transform& tr = hw->getTransform();
908 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
909 layer.setVisibleRegionScreen(visible);
910 layer.setSurfaceDamage(surfaceDamageRegion);
911 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700912
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000913 if (mSidebandStream.get()) {
914 layer.setSidebandStream(mSidebandStream);
915 } else {
916 // NOTE: buffer can be NULL if the client never drew into this
917 // layer yet, or if we ran out of memory
918 layer.setBuffer(mActiveBuffer);
919 }
920}
921#endif
922
923#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800924void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
925 auto hwcId = displayDevice->getHwcDisplayId();
926 if (mHwcLayers.count(hwcId) == 0 ||
927 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
928 return;
929 }
930
931 // This gives us only the "orientation" component of the transform
932 const State& s(getCurrentState());
933
934 // Apply the layer's transform, followed by the display's global transform
935 // Here we're guaranteed that the layer's transform preserves rects
936 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700937 if (!s.crop.isEmpty()) {
938 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800939 }
940 // Subtract the transparent region and snap to the bounds
941 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700942 Rect frame(getTransform().transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800943 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -0700944 if (!s.finalCrop.isEmpty()) {
945 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000946 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800947 auto& displayTransform(displayDevice->getTransform());
948 auto position = displayTransform.transform(frame);
949
950 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
951 position.top);
952 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
953 "to (%d, %d): %s (%d)", mName.string(), position.left,
954 position.top, to_string(error).c_str(),
955 static_cast<int32_t>(error));
956}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000957#else
958void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
959 HWComposer::HWCLayerInterface& layer) {
960 int fenceFd = -1;
961
962 // TODO: there is a possible optimization here: we only need to set the
963 // acquire fence the first time a new buffer is acquired on EACH display.
964
965 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
966 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
967 if (fence->isValid()) {
968 fenceFd = fence->dup();
969 if (fenceFd == -1) {
970 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
971 }
972 }
973 }
974 layer.setAcquireFenceFd(fenceFd);
975}
976
977Rect Layer::getPosition(
978 const sp<const DisplayDevice>& hw)
979{
980 // this gives us only the "orientation" component of the transform
981 const State& s(getCurrentState());
982
983 // apply the layer's transform, followed by the display's global transform
984 // here we're guaranteed that the layer's transform preserves rects
985 Rect win(s.active.w, s.active.h);
986 if (!s.crop.isEmpty()) {
987 win.intersect(s.crop, &win);
988 }
989 // subtract the transparent region and snap to the bounds
990 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700991 Rect frame(getTransform().transform(bounds));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000992 frame.intersect(hw->getViewport(), &frame);
993 if (!s.finalCrop.isEmpty()) {
994 frame.intersect(s.finalCrop, &frame);
995 }
996 const Transform& tr(hw->getTransform());
997 return Rect(tr.transform(frame));
998}
999#endif
Riley Andrews03414a12014-07-01 14:22:59 -07001000
Mathias Agopian13127d82013-03-05 17:47:11 -08001001// ---------------------------------------------------------------------------
1002// drawing...
1003// ---------------------------------------------------------------------------
1004
1005void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -08001006 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -08001007}
1008
Dan Stozac7014012014-02-14 15:03:43 -08001009void Layer::draw(const sp<const DisplayDevice>& hw,
1010 bool useIdentityTransform) const {
1011 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001012}
1013
Dan Stozac7014012014-02-14 15:03:43 -08001014void Layer::draw(const sp<const DisplayDevice>& hw) const {
1015 onDraw(hw, Region(hw->bounds()), false);
1016}
1017
Robert Carrcae605c2017-03-29 12:10:31 -07001018static constexpr mat4 inverseOrientation(uint32_t transform) {
1019 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1020 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1021 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1022 mat4 tr;
1023
1024 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1025 tr = tr * rot90;
1026 }
1027 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1028 tr = tr * flipH;
1029 }
1030 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1031 tr = tr * flipV;
1032 }
1033 return inverse(tr);
1034}
1035
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001036/*
1037 * onDraw will draw the current layer onto the presentable buffer
1038 */
Dan Stozac7014012014-02-14 15:03:43 -08001039void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
1040 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001041{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001042 ATRACE_CALL();
1043
Mathias Agopiana67932f2011-04-20 14:20:59 -07001044 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001045 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -07001046 // in fact never been drawn into. This happens frequently with
1047 // SurfaceView because the WindowManager can't know when the client
1048 // has drawn the first time.
1049
1050 // If there is nothing under us, we paint the screen in black, otherwise
1051 // we just skip this update.
1052
1053 // figure out if there is something below us
1054 Region under;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001055 bool finished = false;
Dan Stoza412903f2017-04-27 13:42:17 -07001056 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001057 if (finished || layer == static_cast<Layer const*>(this)) {
1058 finished = true;
1059 return;
1060 }
Mathias Agopian42977342012-08-05 00:40:46 -07001061 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Robert Carr1f0a16a2016-10-24 16:27:39 -07001062 });
Mathias Agopian179169e2010-05-06 20:21:45 -07001063 // if not everything below us is covered, we plug the holes!
1064 Region holes(clip.subtract(under));
1065 if (!holes.isEmpty()) {
Fabien Sanglard17487192016-12-07 13:03:32 -08001066 clearWithOpenGL(hw, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -07001067 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001068 return;
1069 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001070
Andy McFadden97eba892012-12-11 15:21:45 -08001071 // Bind the current buffer to the GL texture, and wait for it to be
1072 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001073 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1074 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -08001075 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -07001076 // Go ahead and draw the buffer anyway; no matter what we do the screen
1077 // is probably going to have something visibly wrong.
1078 }
1079
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001080 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1081
Mathias Agopian875d8e12013-06-07 15:35:48 -07001082 RenderEngine& engine(mFlinger->getRenderEngine());
1083
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001084 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -07001085 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -07001086 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -07001087
1088 // Query the texture matrix given our current filtering mode.
1089 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001090 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1091 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -07001092
Robert Carrcae605c2017-03-29 12:10:31 -07001093 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001094
1095 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -07001096 * the code below applies the primary display's inverse transform to
1097 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001098 */
Pablo Ceballos021623b2016-04-15 17:31:51 -07001099 uint32_t transform =
1100 DisplayDevice::getPrimaryDisplayOrientationTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001101 mat4 tr = inverseOrientation(transform);
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001102
Robert Carrcae605c2017-03-29 12:10:31 -07001103 /**
1104 * TODO(b/36727915): This is basically a hack.
1105 *
1106 * Ensure that regardless of the parent transformation,
1107 * this buffer is always transformed from native display
1108 * orientation to display orientation. For example, in the case
1109 * of a camera where the buffer remains in native orientation,
1110 * we want the pixels to always be upright.
1111 */
1112 if (getParent() != nullptr) {
1113 const auto parentTransform = getParent()->getTransform();
1114 tr = tr * inverseOrientation(parentTransform.getOrientation());
1115 }
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001116
1117 // and finally apply it to the original texture matrix
1118 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1119 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1120 }
1121
Jamie Genniscbb1a952012-05-08 17:05:52 -07001122 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -07001123 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1124 mTexture.setFiltering(useFiltering);
1125 mTexture.setMatrix(textureMatrix);
1126
1127 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -07001128 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001129 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -07001130 }
Fabien Sanglard85789802016-12-07 13:08:24 -08001131 drawWithOpenGL(hw, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001132 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001133}
1134
Mathias Agopian13127d82013-03-05 17:47:11 -08001135
Dan Stozac7014012014-02-14 15:03:43 -08001136void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard17487192016-12-07 13:03:32 -08001137 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -08001138 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001139{
Mathias Agopian19733a32013-08-28 18:13:56 -07001140 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -08001141 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -07001142 engine.setupFillWithColor(red, green, blue, alpha);
1143 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -08001144}
1145
1146void Layer::clearWithOpenGL(
Fabien Sanglard17487192016-12-07 13:03:32 -08001147 const sp<const DisplayDevice>& hw) const {
1148 clearWithOpenGL(hw, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001149}
1150
Dan Stozac7014012014-02-14 15:03:43 -08001151void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard85789802016-12-07 13:08:24 -08001152 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001153 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001154
Dan Stozac7014012014-02-14 15:03:43 -08001155 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001156
Mathias Agopian13127d82013-03-05 17:47:11 -08001157 /*
1158 * NOTE: the way we compute the texture coordinates here produces
1159 * different results than when we take the HWC path -- in the later case
1160 * the "source crop" is rounded to texel boundaries.
1161 * This can produce significantly different results when the texture
1162 * is scaled by a large amount.
1163 *
1164 * The GL code below is more logical (imho), and the difference with
1165 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001166 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001167 * GL composition when a buffer scaling is applied (maybe with some
1168 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1169 * like more of a hack.
1170 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001171 Rect win(computeBounds());
1172
Robert Carr1f0a16a2016-10-24 16:27:39 -07001173 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -07001174 if (!s.finalCrop.isEmpty()) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001175 win = t.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001176 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001177 win.clear();
1178 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001179 win = t.inverse().transform(win);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001180 if (!win.intersect(computeBounds(), &win)) {
1181 win.clear();
1182 }
1183 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001184
Mathias Agopian3f844832013-08-07 21:24:32 -07001185 float left = float(win.left) / float(s.active.w);
1186 float top = float(win.top) / float(s.active.h);
1187 float right = float(win.right) / float(s.active.w);
1188 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001189
Mathias Agopian875d8e12013-06-07 15:35:48 -07001190 // TODO: we probably want to generate the texture coords with the mesh
1191 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001192 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1193 texCoords[0] = vec2(left, 1.0f - top);
1194 texCoords[1] = vec2(left, 1.0f - bottom);
1195 texCoords[2] = vec2(right, 1.0f - bottom);
1196 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001197
Mathias Agopian875d8e12013-06-07 15:35:48 -07001198 RenderEngine& engine(mFlinger->getRenderEngine());
Robert Carr6452f122017-03-21 10:41:29 -07001199 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), getAlpha());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001200#ifdef USE_HWC2
1201 engine.setSourceDataSpace(mCurrentState.dataSpace);
1202#endif
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001203 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001204 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001205}
1206
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001207#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001208void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1209 bool callIntoHwc) {
1210 if (mHwcLayers.count(hwcId) == 0) {
1211 ALOGE("setCompositionType called without a valid HWC layer");
1212 return;
1213 }
1214 auto& hwcInfo = mHwcLayers[hwcId];
1215 auto& hwcLayer = hwcInfo.layer;
1216 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1217 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1218 if (hwcInfo.compositionType != type) {
1219 ALOGV(" actually setting");
1220 hwcInfo.compositionType = type;
1221 if (callIntoHwc) {
1222 auto error = hwcLayer->setCompositionType(type);
1223 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1224 "composition type %s: %s (%d)", mName.string(),
1225 to_string(type).c_str(), to_string(error).c_str(),
1226 static_cast<int32_t>(error));
1227 }
1228 }
1229}
1230
1231HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001232 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1233 // If we're querying the composition type for a display that does not
1234 // have a HWC counterpart, then it will always be Client
1235 return HWC2::Composition::Client;
1236 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001237 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001238 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001239 return HWC2::Composition::Invalid;
1240 }
1241 return mHwcLayers.at(hwcId).compositionType;
1242}
1243
1244void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1245 if (mHwcLayers.count(hwcId) == 0) {
1246 ALOGE("setClearClientTarget called without a valid HWC layer");
1247 return;
1248 }
1249 mHwcLayers[hwcId].clearClientTarget = clear;
1250}
1251
1252bool Layer::getClearClientTarget(int32_t hwcId) const {
1253 if (mHwcLayers.count(hwcId) == 0) {
1254 ALOGE("getClearClientTarget called without a valid HWC layer");
1255 return false;
1256 }
1257 return mHwcLayers.at(hwcId).clearClientTarget;
1258}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001259#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001260
Ruben Brunk1681d952014-06-27 15:51:55 -07001261uint32_t Layer::getProducerStickyTransform() const {
1262 int producerStickyTransform = 0;
1263 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1264 if (ret != OK) {
1265 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1266 strerror(-ret), ret);
1267 return 0;
1268 }
1269 return static_cast<uint32_t>(producerStickyTransform);
1270}
1271
Dan Stozac5da2712016-07-20 15:38:12 -07001272bool Layer::latchUnsignaledBuffers() {
1273 static bool propertyLoaded = false;
1274 static bool latch = false;
1275 static std::mutex mutex;
1276 std::lock_guard<std::mutex> lock(mutex);
1277 if (!propertyLoaded) {
1278 char value[PROPERTY_VALUE_MAX] = {};
1279 property_get("debug.sf.latch_unsignaled", value, "0");
1280 latch = atoi(value);
1281 propertyLoaded = true;
1282 }
1283 return latch;
1284}
1285
Dan Stozacac35382016-01-27 12:21:06 -08001286uint64_t Layer::getHeadFrameNumber() const {
1287 Mutex::Autolock lock(mQueueItemLock);
1288 if (!mQueueItems.empty()) {
1289 return mQueueItems[0].mFrameNumber;
1290 } else {
1291 return mCurrentFrameNumber;
1292 }
1293}
1294
Dan Stoza1ce65812016-06-15 16:26:27 -07001295bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001296#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001297 if (latchUnsignaledBuffers()) {
1298 return true;
1299 }
1300
Dan Stoza1ce65812016-06-15 16:26:27 -07001301 Mutex::Autolock lock(mQueueItemLock);
1302 if (mQueueItems.empty()) {
1303 return true;
1304 }
1305 if (mQueueItems[0].mIsDroppable) {
1306 // Even though this buffer's fence may not have signaled yet, it could
1307 // be replaced by another buffer before it has a chance to, which means
1308 // that it's possible to get into a situation where a buffer is never
1309 // able to be latched. To avoid this, grab this buffer anyway.
1310 return true;
1311 }
1312 return mQueueItems[0].mFence->getSignalTime() != INT64_MAX;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001313#else
1314 return true;
1315#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001316}
1317
Dan Stozacac35382016-01-27 12:21:06 -08001318bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1319 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1320 // Don't bother with a SyncPoint, since we've already latched the
1321 // relevant frame
1322 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001323 }
1324
Dan Stozacac35382016-01-27 12:21:06 -08001325 Mutex::Autolock lock(mLocalSyncPointMutex);
1326 mLocalSyncPoints.push_back(point);
1327 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001328}
1329
Mathias Agopian13127d82013-03-05 17:47:11 -08001330void Layer::setFiltering(bool filtering) {
1331 mFiltering = filtering;
1332}
1333
1334bool Layer::getFiltering() const {
1335 return mFiltering;
1336}
1337
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001338// As documented in libhardware header, formats in the range
1339// 0x100 - 0x1FF are specific to the HAL implementation, and
1340// are known to have no alpha channel
1341// TODO: move definition for device-specific range into
1342// hardware.h, instead of using hard-coded values here.
1343#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1344
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001345bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001346 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1347 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001348 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001349 switch (format) {
1350 case HAL_PIXEL_FORMAT_RGBA_8888:
1351 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001352 case HAL_PIXEL_FORMAT_RGBA_FP16:
Romain Guy541f2262017-02-10 18:50:17 -08001353 case HAL_PIXEL_FORMAT_RGBA_1010102:
Mathias Agopiandd533712013-07-26 15:31:39 -07001354 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001355 }
1356 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001357 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001358}
1359
Mathias Agopian13127d82013-03-05 17:47:11 -08001360// ----------------------------------------------------------------------------
1361// local state
1362// ----------------------------------------------------------------------------
1363
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001364static void boundPoint(vec2* point, const Rect& crop) {
1365 if (point->x < crop.left) {
1366 point->x = crop.left;
1367 }
1368 if (point->x > crop.right) {
1369 point->x = crop.right;
1370 }
1371 if (point->y < crop.top) {
1372 point->y = crop.top;
1373 }
1374 if (point->y > crop.bottom) {
1375 point->y = crop.bottom;
1376 }
1377}
1378
Dan Stozac7014012014-02-14 15:03:43 -08001379void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1380 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001381{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001382 const Layer::State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001383 const Transform hwTransform(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001384 const uint32_t hw_h = hw->getHeight();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001385 Rect win = computeBounds();
Mathias Agopian3f844832013-08-07 21:24:32 -07001386
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001387 vec2 lt = vec2(win.left, win.top);
1388 vec2 lb = vec2(win.left, win.bottom);
1389 vec2 rb = vec2(win.right, win.bottom);
1390 vec2 rt = vec2(win.right, win.top);
1391
Robert Carr1f0a16a2016-10-24 16:27:39 -07001392 Transform layerTransform = getTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001393 if (!useIdentityTransform) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001394 lt = layerTransform.transform(lt);
1395 lb = layerTransform.transform(lb);
1396 rb = layerTransform.transform(rb);
1397 rt = layerTransform.transform(rt);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001398 }
1399
Robert Carrb5d3d262016-03-25 15:08:13 -07001400 if (!s.finalCrop.isEmpty()) {
1401 boundPoint(&lt, s.finalCrop);
1402 boundPoint(&lb, s.finalCrop);
1403 boundPoint(&rb, s.finalCrop);
1404 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001405 }
1406
Mathias Agopianff2ed702013-09-01 21:36:12 -07001407 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001408 position[0] = hwTransform.transform(lt);
1409 position[1] = hwTransform.transform(lb);
1410 position[2] = hwTransform.transform(rb);
1411 position[3] = hwTransform.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001412 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001413 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001414 }
1415}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001416
Andy McFadden4125a4f2014-01-29 17:17:11 -08001417bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001418{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001419 // if we don't have a buffer yet, we're translucent regardless of the
1420 // layer's opaque flag.
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001421 if (mActiveBuffer == 0) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001422 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001423 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001424
1425 // if the layer has the opaque flag, then we're always opaque,
1426 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001427 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001428}
1429
Dan Stoza23116082015-06-18 14:58:39 -07001430bool Layer::isSecure() const
1431{
1432 const Layer::State& s(mDrawingState);
1433 return (s.flags & layer_state_t::eLayerSecure);
1434}
1435
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001436bool Layer::isProtected() const
1437{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001438 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001439 return (activeBuffer != 0) &&
1440 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1441}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001442
Mathias Agopian13127d82013-03-05 17:47:11 -08001443bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001444 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001445}
1446
1447bool Layer::isCropped() const {
1448 return !mCurrentCrop.isEmpty();
1449}
1450
1451bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1452 return mNeedsFiltering || hw->needsFiltering();
1453}
1454
1455void Layer::setVisibleRegion(const Region& visibleRegion) {
1456 // always called from main thread
1457 this->visibleRegion = visibleRegion;
1458}
1459
1460void Layer::setCoveredRegion(const Region& coveredRegion) {
1461 // always called from main thread
1462 this->coveredRegion = coveredRegion;
1463}
1464
1465void Layer::setVisibleNonTransparentRegion(const Region&
1466 setVisibleNonTransparentRegion) {
1467 // always called from main thread
1468 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1469}
1470
1471// ----------------------------------------------------------------------------
1472// transaction
1473// ----------------------------------------------------------------------------
1474
Dan Stoza7dde5992015-05-22 09:51:44 -07001475void Layer::pushPendingState() {
1476 if (!mCurrentState.modified) {
1477 return;
1478 }
1479
Dan Stoza7dde5992015-05-22 09:51:44 -07001480 // If this transaction is waiting on the receipt of a frame, generate a sync
1481 // point and send it to the remote layer.
Robert Carr0d480722017-01-10 16:42:54 -08001482 if (mCurrentState.barrierLayer != nullptr) {
1483 sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1484 if (barrierLayer == nullptr) {
1485 ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
Dan Stoza7dde5992015-05-22 09:51:44 -07001486 // If we can't promote the layer we are intended to wait on,
1487 // then it is expired or otherwise invalid. Allow this transaction
1488 // to be applied as per normal (no synchronization).
Robert Carr0d480722017-01-10 16:42:54 -08001489 mCurrentState.barrierLayer = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001490 } else {
1491 auto syncPoint = std::make_shared<SyncPoint>(
1492 mCurrentState.frameNumber);
Robert Carr0d480722017-01-10 16:42:54 -08001493 if (barrierLayer->addSyncPoint(syncPoint)) {
Dan Stozacac35382016-01-27 12:21:06 -08001494 mRemoteSyncPoints.push_back(std::move(syncPoint));
1495 } else {
1496 // We already missed the frame we're supposed to synchronize
1497 // on, so go ahead and apply the state update
Robert Carr0d480722017-01-10 16:42:54 -08001498 mCurrentState.barrierLayer = nullptr;
Dan Stozacac35382016-01-27 12:21:06 -08001499 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001500 }
1501
Dan Stoza7dde5992015-05-22 09:51:44 -07001502 // Wake us up to check if the frame has been received
1503 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001504 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001505 }
1506 mPendingStates.push_back(mCurrentState);
1507}
1508
Pablo Ceballos05289c22016-04-14 15:49:55 -07001509void Layer::popPendingState(State* stateToCommit) {
1510 auto oldFlags = stateToCommit->flags;
1511 *stateToCommit = mPendingStates[0];
1512 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1513 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001514
1515 mPendingStates.removeAt(0);
1516}
1517
Pablo Ceballos05289c22016-04-14 15:49:55 -07001518bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001519 bool stateUpdateAvailable = false;
1520 while (!mPendingStates.empty()) {
Robert Carr0d480722017-01-10 16:42:54 -08001521 if (mPendingStates[0].barrierLayer != nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001522 if (mRemoteSyncPoints.empty()) {
1523 // If we don't have a sync point for this, apply it anyway. It
1524 // will be visually wrong, but it should keep us from getting
1525 // into too much trouble.
1526 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001527 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001528 stateUpdateAvailable = true;
1529 continue;
1530 }
1531
Dan Stozacac35382016-01-27 12:21:06 -08001532 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1533 mPendingStates[0].frameNumber) {
1534 ALOGE("[%s] Unexpected sync point frame number found",
1535 mName.string());
1536
1537 // Signal our end of the sync point and then dispose of it
1538 mRemoteSyncPoints.front()->setTransactionApplied();
1539 mRemoteSyncPoints.pop_front();
1540 continue;
1541 }
1542
Dan Stoza7dde5992015-05-22 09:51:44 -07001543 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1544 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001545 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001546 stateUpdateAvailable = true;
1547
1548 // Signal our end of the sync point and then dispose of it
1549 mRemoteSyncPoints.front()->setTransactionApplied();
1550 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001551 } else {
1552 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001553 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001554 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001555 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001556 stateUpdateAvailable = true;
1557 }
1558 }
1559
1560 // If we still have pending updates, wake SurfaceFlinger back up and point
1561 // it at this layer so we can process them
1562 if (!mPendingStates.empty()) {
1563 setTransactionFlags(eTransactionNeeded);
1564 mFlinger->setTransactionFlags(eTraversalNeeded);
1565 }
1566
1567 mCurrentState.modified = false;
1568 return stateUpdateAvailable;
1569}
1570
1571void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001572 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001573 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001574 Mutex::Autolock lock(mLocalSyncPointMutex);
1575 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001576 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001577 point->setFrameAvailable();
1578 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001579 }
1580}
1581
Mathias Agopian13127d82013-03-05 17:47:11 -08001582uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001583 ATRACE_CALL();
1584
Dan Stoza7dde5992015-05-22 09:51:44 -07001585 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001586 Layer::State c = getCurrentState();
1587 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001588 return 0;
1589 }
1590
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001591 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001592
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001593 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1594 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001595
1596 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001597 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001598 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001599 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001600 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001601 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001602 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001603 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001604 this, getName().string(), mCurrentTransform,
1605 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001606 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001607 c.crop.left,
1608 c.crop.top,
1609 c.crop.right,
1610 c.crop.bottom,
1611 c.crop.getWidth(),
1612 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001613 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001614 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001615 s.crop.left,
1616 s.crop.top,
1617 s.crop.right,
1618 s.crop.bottom,
1619 s.crop.getWidth(),
1620 s.crop.getHeight(),
1621 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001622
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001623 // record the new size, form this point on, when the client request
1624 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001625 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001626 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001627 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001628
Robert Carr82364e32016-05-15 11:27:47 -07001629 const bool resizePending = (c.requested.w != c.active.w) ||
1630 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001631 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001632 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001633 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001634 // if we have a pending resize, unless we are in fixed-size mode.
1635 // the drawing state will be updated only once we receive a buffer
1636 // with the correct size.
1637 //
1638 // in particular, we want to make sure the clip (which is part
1639 // of the geometry state) is latched together with the size but is
1640 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001641 //
1642 // If a sideband stream is attached, however, we want to skip this
1643 // optimization so that transactions aren't missed when a buffer
1644 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001645
1646 flags |= eDontUpdateGeometryState;
1647 }
1648 }
1649
Robert Carr7bf247e2017-05-18 14:02:49 -07001650 // Here we apply various requested geometry states, depending on our
1651 // latching configuration. See Layer.h for a detailed discussion of
1652 // how geometry latching is controlled.
1653 if (!(flags & eDontUpdateGeometryState)) {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001654 Layer::State& editCurrentState(getCurrentState());
Robert Carr7bf247e2017-05-18 14:02:49 -07001655
1656 // If mFreezeGeometryUpdates is true we are in the setGeometryAppliesWithResize
1657 // mode, which causes attributes which normally latch regardless of scaling mode,
1658 // to be delayed. We copy the requested state to the active state making sure
1659 // to respect these rules (again see Layer.h for a detailed discussion).
1660 //
1661 // There is an awkward asymmetry in the handling of the crop states in the position
1662 // states, as can be seen below. Largely this arises from position and transform
1663 // being stored in the same data structure while having different latching rules.
1664 // b/38182305
1665 //
1666 // Careful that "c" and editCurrentState may not begin as equivalent due to
1667 // applyPendingStates in the presence of deferred transactions.
1668 if (mFreezeGeometryUpdates) {
Robert Carr82364e32016-05-15 11:27:47 -07001669 float tx = c.active.transform.tx();
1670 float ty = c.active.transform.ty();
1671 c.active = c.requested;
1672 c.active.transform.set(tx, ty);
1673 editCurrentState.active = c.active;
1674 } else {
1675 editCurrentState.active = editCurrentState.requested;
1676 c.active = c.requested;
1677 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001678 }
1679
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001680 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001681 // invalidate and recompute the visible regions if needed
1682 flags |= Layer::eVisibleRegion;
1683 }
1684
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001685 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001686 // invalidate and recompute the visible regions if needed
1687 flags |= eVisibleRegion;
1688 this->contentDirty = true;
1689
1690 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001691 const uint8_t type = c.active.transform.getType();
1692 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001693 (type >= Transform::SCALE));
1694 }
1695
Dan Stozac8145172016-04-28 16:29:06 -07001696 // If the layer is hidden, signal and clear out all local sync points so
1697 // that transactions for layers depending on this layer's frames becoming
1698 // visible are not blocked
1699 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001700 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001701 }
1702
Mathias Agopian13127d82013-03-05 17:47:11 -08001703 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001704 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001705 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001706}
1707
Pablo Ceballos05289c22016-04-14 15:49:55 -07001708void Layer::commitTransaction(const State& stateToCommit) {
1709 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001710}
1711
Mathias Agopian13127d82013-03-05 17:47:11 -08001712uint32_t Layer::getTransactionFlags(uint32_t flags) {
1713 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1714}
1715
1716uint32_t Layer::setTransactionFlags(uint32_t flags) {
1717 return android_atomic_or(flags, &mTransactionFlags);
1718}
1719
Robert Carr82364e32016-05-15 11:27:47 -07001720bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001721 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001722 return false;
1723 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001724
1725 // We update the requested and active position simultaneously because
1726 // we want to apply the position portion of the transform matrix immediately,
1727 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001728 mCurrentState.requested.transform.set(x, y);
Robert Carr7bf247e2017-05-18 14:02:49 -07001729 if (immediate && !mFreezeGeometryUpdates) {
1730 // Here we directly update the active state
1731 // unlike other setters, because we store it within
1732 // the transform, but use different latching rules.
1733 // b/38182305
Robert Carr82364e32016-05-15 11:27:47 -07001734 mCurrentState.active.transform.set(x, y);
1735 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001736 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001737
Dan Stoza7dde5992015-05-22 09:51:44 -07001738 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001739 setTransactionFlags(eTransactionNeeded);
1740 return true;
1741}
Robert Carr82364e32016-05-15 11:27:47 -07001742
Robert Carr1f0a16a2016-10-24 16:27:39 -07001743bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1744 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1745 if (idx < 0) {
1746 return false;
1747 }
1748 if (childLayer->setLayer(z)) {
1749 mCurrentChildren.removeAt(idx);
1750 mCurrentChildren.add(childLayer);
1751 }
1752 return true;
1753}
1754
Robert Carrae060832016-11-28 10:51:00 -08001755bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001756 if (mCurrentState.z == z)
1757 return false;
1758 mCurrentState.sequence++;
1759 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001760 mCurrentState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001761
1762 // Discard all relative layering.
1763 if (mCurrentState.zOrderRelativeOf != nullptr) {
1764 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1765 if (strongRelative != nullptr) {
1766 strongRelative->removeZOrderRelative(this);
1767 }
1768 mCurrentState.zOrderRelativeOf = nullptr;
1769 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001770 setTransactionFlags(eTransactionNeeded);
1771 return true;
1772}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001773
Robert Carrdb66e622017-04-10 16:55:57 -07001774void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1775 mCurrentState.zOrderRelatives.remove(relative);
1776 mCurrentState.sequence++;
1777 mCurrentState.modified = true;
1778 setTransactionFlags(eTransactionNeeded);
1779}
1780
1781void Layer::addZOrderRelative(const wp<Layer>& relative) {
1782 mCurrentState.zOrderRelatives.add(relative);
1783 mCurrentState.modified = true;
1784 mCurrentState.sequence++;
1785 setTransactionFlags(eTransactionNeeded);
1786}
1787
1788bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1789 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1790 if (handle == nullptr) {
1791 return false;
1792 }
1793 sp<Layer> relative = handle->owner.promote();
1794 if (relative == nullptr) {
1795 return false;
1796 }
1797
1798 mCurrentState.sequence++;
1799 mCurrentState.modified = true;
1800 mCurrentState.z = z;
1801
1802 mCurrentState.zOrderRelativeOf = relative;
1803 relative->addZOrderRelative(this);
1804
1805 setTransactionFlags(eTransactionNeeded);
1806
1807 return true;
1808}
1809
Mathias Agopian13127d82013-03-05 17:47:11 -08001810bool Layer::setSize(uint32_t w, uint32_t h) {
1811 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1812 return false;
1813 mCurrentState.requested.w = w;
1814 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001815 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001816 setTransactionFlags(eTransactionNeeded);
1817 return true;
1818}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001819#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001820bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001821#else
1822bool Layer::setAlpha(uint8_t alpha) {
1823#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001824 if (mCurrentState.alpha == alpha)
1825 return false;
1826 mCurrentState.sequence++;
1827 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001828 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001829 setTransactionFlags(eTransactionNeeded);
1830 return true;
1831}
1832bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1833 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001834 mCurrentState.requested.transform.set(
Robert Carrcb6e1e32017-02-21 19:48:26 -08001835 matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001836 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001837 setTransactionFlags(eTransactionNeeded);
1838 return true;
1839}
1840bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001841 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001842 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001843 setTransactionFlags(eTransactionNeeded);
1844 return true;
1845}
1846bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1847 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1848 if (mCurrentState.flags == newFlags)
1849 return false;
1850 mCurrentState.sequence++;
1851 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001852 mCurrentState.mask = mask;
1853 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001854 setTransactionFlags(eTransactionNeeded);
1855 return true;
1856}
Robert Carr99e27f02016-06-16 15:18:02 -07001857
1858bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001859 if (mCurrentState.requestedCrop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001860 return false;
1861 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001862 mCurrentState.requestedCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001863 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr99e27f02016-06-16 15:18:02 -07001864 mCurrentState.crop = crop;
1865 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001866 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1867
Dan Stoza7dde5992015-05-22 09:51:44 -07001868 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001869 setTransactionFlags(eTransactionNeeded);
1870 return true;
1871}
Robert Carr8d5227b2017-03-16 15:41:03 -07001872
1873bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001874 if (mCurrentState.requestedFinalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001875 return false;
1876 mCurrentState.sequence++;
Robert Carr8d5227b2017-03-16 15:41:03 -07001877 mCurrentState.requestedFinalCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001878 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr8d5227b2017-03-16 15:41:03 -07001879 mCurrentState.finalCrop = crop;
1880 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001881 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1882
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001883 mCurrentState.modified = true;
1884 setTransactionFlags(eTransactionNeeded);
1885 return true;
1886}
Mathias Agopian13127d82013-03-05 17:47:11 -08001887
Robert Carrc3574f72016-03-24 12:19:32 -07001888bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1889 if (scalingMode == mOverrideScalingMode)
1890 return false;
1891 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001892 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001893 return true;
1894}
1895
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001896void Layer::setInfo(uint32_t type, uint32_t appId) {
1897 mCurrentState.appId = appId;
1898 mCurrentState.type = type;
1899 mCurrentState.modified = true;
1900 setTransactionFlags(eTransactionNeeded);
1901}
1902
Robert Carrc3574f72016-03-24 12:19:32 -07001903uint32_t Layer::getEffectiveScalingMode() const {
1904 if (mOverrideScalingMode >= 0) {
1905 return mOverrideScalingMode;
1906 }
1907 return mCurrentScalingMode;
1908}
1909
Mathias Agopian13127d82013-03-05 17:47:11 -08001910bool Layer::setLayerStack(uint32_t layerStack) {
1911 if (mCurrentState.layerStack == layerStack)
1912 return false;
1913 mCurrentState.sequence++;
1914 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001915 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001916 setTransactionFlags(eTransactionNeeded);
1917 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001918}
1919
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07001920bool Layer::setDataSpace(android_dataspace dataSpace) {
1921 if (mCurrentState.dataSpace == dataSpace)
1922 return false;
1923 mCurrentState.sequence++;
1924 mCurrentState.dataSpace = dataSpace;
1925 mCurrentState.modified = true;
1926 setTransactionFlags(eTransactionNeeded);
1927 return true;
1928}
1929
Robert Carr1f0a16a2016-10-24 16:27:39 -07001930uint32_t Layer::getLayerStack() const {
1931 auto p = getParent();
1932 if (p == nullptr) {
1933 return getDrawingState().layerStack;
1934 }
1935 return p->getLayerStack();
1936}
1937
Robert Carr0d480722017-01-10 16:42:54 -08001938void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
Dan Stoza7dde5992015-05-22 09:51:44 -07001939 uint64_t frameNumber) {
Robert Carr0d480722017-01-10 16:42:54 -08001940 mCurrentState.barrierLayer = barrierLayer;
Dan Stoza7dde5992015-05-22 09:51:44 -07001941 mCurrentState.frameNumber = frameNumber;
1942 // We don't set eTransactionNeeded, because just receiving a deferral
1943 // request without any other state updates shouldn't actually induce a delay
1944 mCurrentState.modified = true;
1945 pushPendingState();
Robert Carr0d480722017-01-10 16:42:54 -08001946 mCurrentState.barrierLayer = nullptr;
Dan Stoza792e5292016-02-11 11:43:58 -08001947 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07001948 mCurrentState.modified = false;
Robert Carr0d480722017-01-10 16:42:54 -08001949 ALOGE("Deferred transaction");
1950}
1951
1952void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
1953 uint64_t frameNumber) {
1954 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
1955 deferTransactionUntil(handle->owner.promote(), frameNumber);
Dan Stoza7dde5992015-05-22 09:51:44 -07001956}
1957
Dan Stozaee44edd2015-03-23 15:50:23 -07001958void Layer::useSurfaceDamage() {
1959 if (mFlinger->mForceFullDamage) {
1960 surfaceDamageRegion = Region::INVALID_REGION;
1961 } else {
1962 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1963 }
1964}
1965
1966void Layer::useEmptyDamage() {
1967 surfaceDamageRegion.clear();
1968}
1969
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001970// ----------------------------------------------------------------------------
1971// pageflip handling...
1972// ----------------------------------------------------------------------------
1973
Dan Stoza6b9454d2014-11-07 16:00:59 -08001974bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001975 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07001976 return true;
1977 }
1978
Dan Stoza6b9454d2014-11-07 16:00:59 -08001979 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001980 if (mQueueItems.empty()) {
1981 return false;
1982 }
1983 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001984 nsecs_t expectedPresent =
1985 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001986
1987 // Ignore timestamps more than a second in the future
1988 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1989 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1990 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1991 expectedPresent);
1992
1993 bool isDue = timestamp < expectedPresent;
1994 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001995}
1996
Brian Andersond6927fb2016-07-23 23:37:30 -07001997bool Layer::onPreComposition(nsecs_t refreshStartTime) {
1998 if (mBufferLatched) {
1999 Mutex::Autolock lock(mFrameEventHistoryMutex);
2000 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
2001 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08002002 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08002003 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002004}
2005
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002006bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
Brian Anderson3d4039d2016-09-23 16:31:30 -07002007 const std::shared_ptr<FenceTime>& presentFence,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002008 const CompositorTiming& compositorTiming) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002009 mAcquireTimeline.updateSignalTimes();
2010 mReleaseTimeline.updateSignalTimes();
2011
Brian Andersond6927fb2016-07-23 23:37:30 -07002012 // mFrameLatencyNeeded is true when a new frame was latched for the
2013 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08002014 if (!mFrameLatencyNeeded)
2015 return false;
2016
Fabien Sanglard28e98082016-12-05 10:19:46 -08002017 // Update mFrameEventHistory.
2018 {
2019 Mutex::Autolock lock(mFrameEventHistoryMutex);
2020 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002021 glDoneFence, presentFence, compositorTiming);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002022 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08002023
2024 // Update mFrameTracker.
2025 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
2026 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
2027
Brian Anderson3d4039d2016-09-23 16:31:30 -07002028 std::shared_ptr<FenceTime> frameReadyFence =
2029 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08002030 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002031 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002032 } else {
2033 // There was no fence for this frame, so assume that it was ready
2034 // to be presented at the desired present time.
2035 mFrameTracker.setFrameReadyTime(desiredPresentTime);
2036 }
2037
Brian Anderson3d4039d2016-09-23 16:31:30 -07002038 if (presentFence->isValid()) {
2039 mFrameTracker.setActualPresentFence(
2040 std::shared_ptr<FenceTime>(presentFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002041 } else {
2042 // The HWC doesn't support present fences, so use the refresh
2043 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002044 mFrameTracker.setActualPresentTime(
2045 mFlinger->getHwComposer().getRefreshTimestamp(
2046 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002047 }
2048
2049 mFrameTracker.advanceFrame();
2050 mFrameLatencyNeeded = false;
2051 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002052}
2053
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002054#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07002055void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Brian Anderson5ea5e592016-12-01 16:54:33 -08002056 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2057 return;
2058 }
2059
Brian Anderson3d4039d2016-09-23 16:31:30 -07002060 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002061 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002062 mReleaseTimeline.push(releaseFenceTime);
2063
2064 Mutex::Autolock lock(mFrameEventHistoryMutex);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002065 if (mPreviousFrameNumber != 0) {
2066 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2067 dequeueReadyTime, std::move(releaseFenceTime));
2068 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002069}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002070#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002071
Robert Carr1f0a16a2016-10-24 16:27:39 -07002072bool Layer::isHiddenByPolicy() const {
2073 const Layer::State& s(mDrawingState);
2074 const auto& parent = getParent();
2075 if (parent != nullptr && parent->isHiddenByPolicy()) {
2076 return true;
2077 }
2078 return s.flags & layer_state_t::eLayerHidden;
2079}
2080
Mathias Agopianda27af92012-09-13 18:17:13 -07002081bool Layer::isVisible() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002082#ifdef USE_HWC2
Robert Carr6452f122017-03-21 10:41:29 -07002083 return !(isHiddenByPolicy()) && getAlpha() > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08002084 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002085#else
Robert Carr6452f122017-03-21 10:41:29 -07002086 return !(isHiddenByPolicy()) && getAlpha()
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002087 && (mActiveBuffer != NULL || mSidebandStream != NULL);
2088#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07002089}
2090
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002091bool Layer::allTransactionsSignaled() {
2092 auto headFrameNumber = getHeadFrameNumber();
2093 bool matchingFramesFound = false;
2094 bool allTransactionsApplied = true;
2095 Mutex::Autolock lock(mLocalSyncPointMutex);
2096
2097 for (auto& point : mLocalSyncPoints) {
2098 if (point->getFrameNumber() > headFrameNumber) {
2099 break;
2100 }
2101 matchingFramesFound = true;
2102
2103 if (!point->frameIsAvailable()) {
2104 // We haven't notified the remote layer that the frame for
2105 // this point is available yet. Notify it now, and then
2106 // abort this attempt to latch.
2107 point->setFrameAvailable();
2108 allTransactionsApplied = false;
2109 break;
2110 }
2111
2112 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2113 }
2114 return !matchingFramesFound || allTransactionsApplied;
2115}
2116
Brian Andersond6927fb2016-07-23 23:37:30 -07002117Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002118{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08002119 ATRACE_CALL();
2120
Jesse Hall399184a2014-03-03 15:42:54 -08002121 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2122 // mSidebandStreamChanged was true
2123 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07002124 if (mSidebandStream != NULL) {
2125 setTransactionFlags(eTransactionNeeded);
2126 mFlinger->setTransactionFlags(eTraversalNeeded);
2127 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07002128 recomputeVisibleRegions = true;
2129
2130 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07002131 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08002132 }
2133
Mathias Agopian4fec8732012-06-29 14:12:52 -07002134 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07002135 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2136 return outDirtyRegion;
2137 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002138
Fabien Sanglard223eb912016-10-13 10:15:06 -07002139 // if we've already called updateTexImage() without going through
2140 // a composition step, we have to skip this layer at this point
2141 // because we cannot call updateTeximage() without a corresponding
2142 // compositionComplete() call.
2143 // we'll trigger an update in onPreComposition().
2144 if (mRefreshPending) {
2145 return outDirtyRegion;
2146 }
2147
2148 // If the head buffer's acquire fence hasn't signaled yet, return and
2149 // try again later
2150 if (!headFenceHasSignaled()) {
2151 mFlinger->signalLayerUpdate();
2152 return outDirtyRegion;
2153 }
2154
2155 // Capture the old state of the layer for comparisons later
2156 const State& s(getDrawingState());
2157 const bool oldOpacity = isOpaque(s);
2158 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2159
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002160 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002161 mFlinger->signalLayerUpdate();
2162 return outDirtyRegion;
2163 }
2164
2165 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2166 // of the buffer queue isn't modified when the buffer queue is returning
2167 // BufferItem's that weren't actually queued. This can happen in shared
2168 // buffer mode.
2169 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002170 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2171 getProducerStickyTransform() != 0, mName.string(),
Robert Carr7bf247e2017-05-18 14:02:49 -07002172 mOverrideScalingMode, mFreezeGeometryUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002173 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2174 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2175 mLastFrameNumberReceived);
2176 if (updateResult == BufferQueue::PRESENT_LATER) {
2177 // Producer doesn't want buffer to be displayed yet. Signal a
2178 // layer update so we check again at the next opportunity.
2179 mFlinger->signalLayerUpdate();
2180 return outDirtyRegion;
2181 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2182 // If the buffer has been rejected, remove it from the shadow queue
2183 // and return early
2184 if (queuedBuffer) {
2185 Mutex::Autolock lock(mQueueItemLock);
2186 mQueueItems.removeAt(0);
2187 android_atomic_dec(&mQueuedFrames);
2188 }
2189 return outDirtyRegion;
2190 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2191 // This can occur if something goes wrong when trying to create the
2192 // EGLImage for this buffer. If this happens, the buffer has already
2193 // been released, so we need to clean up the queue and bug out
2194 // early.
2195 if (queuedBuffer) {
2196 Mutex::Autolock lock(mQueueItemLock);
2197 mQueueItems.clear();
2198 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002199 }
2200
Fabien Sanglard223eb912016-10-13 10:15:06 -07002201 // Once we have hit this state, the shadow queue may no longer
2202 // correctly reflect the incoming BufferQueue's contents, so even if
2203 // updateTexImage starts working, the only safe course of action is
2204 // to continue to ignore updates.
2205 mUpdateTexImageFailed = true;
2206
2207 return outDirtyRegion;
2208 }
2209
2210 if (queuedBuffer) {
2211 // Autolock scope
2212 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2213
2214 Mutex::Autolock lock(mQueueItemLock);
2215
2216 // Remove any stale buffers that have been dropped during
2217 // updateTexImage
2218 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2219 mQueueItems.removeAt(0);
2220 android_atomic_dec(&mQueuedFrames);
2221 }
2222
2223 mQueueItems.removeAt(0);
2224 }
2225
2226
2227 // Decrement the queued-frames count. Signal another event if we
2228 // have more frames pending.
2229 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2230 || mAutoRefresh) {
2231 mFlinger->signalLayerUpdate();
2232 }
2233
Fabien Sanglard223eb912016-10-13 10:15:06 -07002234 // update the active buffer
Chia-I Wu06d63de2017-01-04 14:58:51 +08002235 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2236 &mActiveBufferSlot);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002237 if (mActiveBuffer == NULL) {
2238 // this can only happen if the very first buffer was rejected.
2239 return outDirtyRegion;
2240 }
2241
Brian Andersond6927fb2016-07-23 23:37:30 -07002242 mBufferLatched = true;
2243 mPreviousFrameNumber = mCurrentFrameNumber;
2244 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2245
2246 {
2247 Mutex::Autolock lock(mFrameEventHistoryMutex);
2248 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2249#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002250 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002251 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002252 mReleaseTimeline.push(releaseFenceTime);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002253 if (mPreviousFrameNumber != 0) {
2254 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2255 latchTime, std::move(releaseFenceTime));
2256 }
Brian Andersond6927fb2016-07-23 23:37:30 -07002257#endif
2258 }
2259
Fabien Sanglard223eb912016-10-13 10:15:06 -07002260 mRefreshPending = true;
2261 mFrameLatencyNeeded = true;
2262 if (oldActiveBuffer == NULL) {
2263 // the first time we receive a buffer, we need to trigger a
2264 // geometry invalidation.
2265 recomputeVisibleRegions = true;
2266 }
2267
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002268 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2269
Fabien Sanglard223eb912016-10-13 10:15:06 -07002270 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2271 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2272 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2273 if ((crop != mCurrentCrop) ||
2274 (transform != mCurrentTransform) ||
2275 (scalingMode != mCurrentScalingMode))
2276 {
2277 mCurrentCrop = crop;
2278 mCurrentTransform = transform;
2279 mCurrentScalingMode = scalingMode;
2280 recomputeVisibleRegions = true;
2281 }
2282
2283 if (oldActiveBuffer != NULL) {
2284 uint32_t bufWidth = mActiveBuffer->getWidth();
2285 uint32_t bufHeight = mActiveBuffer->getHeight();
2286 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2287 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002288 recomputeVisibleRegions = true;
2289 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002290 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002291
Fabien Sanglard223eb912016-10-13 10:15:06 -07002292 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2293 if (oldOpacity != isOpaque(s)) {
2294 recomputeVisibleRegions = true;
2295 }
Dan Stozacac35382016-01-27 12:21:06 -08002296
Fabien Sanglard223eb912016-10-13 10:15:06 -07002297 // Remove any sync points corresponding to the buffer which was just
2298 // latched
2299 {
2300 Mutex::Autolock lock(mLocalSyncPointMutex);
2301 auto point = mLocalSyncPoints.begin();
2302 while (point != mLocalSyncPoints.end()) {
2303 if (!(*point)->frameIsAvailable() ||
2304 !(*point)->transactionIsApplied()) {
2305 // This sync point must have been added since we started
2306 // latching. Don't drop it yet.
2307 ++point;
2308 continue;
2309 }
2310
2311 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2312 point = mLocalSyncPoints.erase(point);
2313 } else {
2314 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002315 }
2316 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002317 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002318
2319 // FIXME: postedRegion should be dirty & bounds
2320 Region dirtyRegion(Rect(s.active.w, s.active.h));
2321
2322 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002323 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002324
Mathias Agopian4fec8732012-06-29 14:12:52 -07002325 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002326}
2327
Mathias Agopiana67932f2011-04-20 14:20:59 -07002328uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002329{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002330 // TODO: should we do something special if mSecure is set?
2331 if (mProtectedByApp) {
2332 // need a hardware-protected path to external video sink
2333 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002334 }
Riley Andrews03414a12014-07-01 14:22:59 -07002335 if (mPotentialCursor) {
2336 usage |= GraphicBuffer::USAGE_CURSOR;
2337 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002338 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002339 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002340}
2341
Mathias Agopian84300952012-11-21 16:02:13 -08002342void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002343 uint32_t orientation = 0;
2344 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002345 // The transform hint is used to improve performance, but we can
2346 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002347 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002348 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002349 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002350 if (orientation & Transform::ROT_INVALID) {
2351 orientation = 0;
2352 }
2353 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002354 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002355}
2356
Mathias Agopian13127d82013-03-05 17:47:11 -08002357// ----------------------------------------------------------------------------
2358// debugging
2359// ----------------------------------------------------------------------------
2360
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002361void Layer::dump(String8& result, Colorizer& colorizer) const
Mathias Agopian13127d82013-03-05 17:47:11 -08002362{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002363 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08002364
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002365 colorizer.colorize(result, Colorizer::GREEN);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002366 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002367 "+ %s %p (%s)\n",
2368 getTypeId(), this, getName().string());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002369 colorizer.reset(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002370
Mathias Agopian2ca79392013-04-02 18:30:32 -07002371 s.activeTransparentRegion.dump(result, "transparentRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002372 visibleRegion.dump(result, "visibleRegion");
Dan Stozaee44edd2015-03-23 15:50:23 -07002373 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002374 sp<Client> client(mClientRef.promote());
2375
Mathias Agopian74d211a2013-04-22 16:55:35 +02002376 result.appendFormat( " "
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002377 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2378 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
Mathias Agopian13127d82013-03-05 17:47:11 -08002379 "isOpaque=%1d, invalidate=%1d, "
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002380#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08002381 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002382#else
2383 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2384#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08002385 " client=%p\n",
Robert Carr1f0a16a2016-10-24 16:27:39 -07002386 getLayerStack(), s.z,
2387 s.active.transform.tx(), s.active.transform.ty(),
2388 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07002389 s.crop.left, s.crop.top,
2390 s.crop.right, s.crop.bottom,
2391 s.finalCrop.left, s.finalCrop.top,
2392 s.finalCrop.right, s.finalCrop.bottom,
Andy McFadden4125a4f2014-01-29 17:17:11 -08002393 isOpaque(s), contentDirty,
Mathias Agopian13127d82013-03-05 17:47:11 -08002394 s.alpha, s.flags,
Robert Carr3dcabfa2016-03-01 18:36:58 -08002395 s.active.transform[0][0], s.active.transform[0][1],
2396 s.active.transform[1][0], s.active.transform[1][1],
Mathias Agopian13127d82013-03-05 17:47:11 -08002397 client.get());
Mathias Agopian13127d82013-03-05 17:47:11 -08002398
2399 sp<const GraphicBuffer> buf0(mActiveBuffer);
2400 uint32_t w0=0, h0=0, s0=0, f0=0;
2401 if (buf0 != 0) {
2402 w0 = buf0->getWidth();
2403 h0 = buf0->getHeight();
2404 s0 = buf0->getStride();
2405 f0 = buf0->format;
2406 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02002407 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002408 " "
2409 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2410 " queued-frames=%d, mRefreshPending=%d\n",
2411 mFormat, w0, h0, s0,f0,
2412 mQueuedFrames, mRefreshPending);
2413
Mathias Agopian13127d82013-03-05 17:47:11 -08002414 if (mSurfaceFlingerConsumer != 0) {
Colin Cross3d1d2802016-09-26 18:10:16 -07002415 mSurfaceFlingerConsumer->dumpState(result, " ");
Mathias Agopian13127d82013-03-05 17:47:11 -08002416 }
2417}
2418
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002419#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002420void Layer::miniDumpHeader(String8& result) {
2421 result.append("----------------------------------------");
2422 result.append("---------------------------------------\n");
2423 result.append(" Layer name\n");
2424 result.append(" Z | ");
2425 result.append(" Comp Type | ");
2426 result.append(" Disp Frame (LTRB) | ");
2427 result.append(" Source Crop (LTRB)\n");
2428 result.append("----------------------------------------");
2429 result.append("---------------------------------------\n");
2430}
2431
2432void Layer::miniDump(String8& result, int32_t hwcId) const {
2433 if (mHwcLayers.count(hwcId) == 0) {
2434 return;
2435 }
2436
2437 String8 name;
2438 if (mName.length() > 77) {
2439 std::string shortened;
2440 shortened.append(mName.string(), 36);
2441 shortened.append("[...]");
2442 shortened.append(mName.string() + (mName.length() - 36), 36);
2443 name = shortened.c_str();
2444 } else {
2445 name = mName;
2446 }
2447
2448 result.appendFormat(" %s\n", name.string());
2449
2450 const Layer::State& layerState(getDrawingState());
2451 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2452 result.appendFormat(" %10u | ", layerState.z);
2453 result.appendFormat("%10s | ",
2454 to_string(getCompositionType(hwcId)).c_str());
2455 const Rect& frame = hwcInfo.displayFrame;
2456 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2457 frame.right, frame.bottom);
Dan Stoza5a423ea2017-02-16 14:10:39 -08002458 const FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002459 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2460 crop.right, crop.bottom);
2461
2462 result.append("- - - - - - - - - - - - - - - - - - - - ");
2463 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2464}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002465#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002466
Svetoslavd85084b2014-03-20 10:28:31 -07002467void Layer::dumpFrameStats(String8& result) const {
2468 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002469}
2470
Svetoslavd85084b2014-03-20 10:28:31 -07002471void Layer::clearFrameStats() {
2472 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002473}
2474
Jamie Gennis6547ff42013-07-16 20:12:42 -07002475void Layer::logFrameStats() {
2476 mFrameTracker.logAndResetStats(mName);
2477}
2478
Svetoslavd85084b2014-03-20 10:28:31 -07002479void Layer::getFrameStats(FrameStats* outStats) const {
2480 mFrameTracker.getStats(outStats);
2481}
2482
Brian Andersond6927fb2016-07-23 23:37:30 -07002483void Layer::dumpFrameEvents(String8& result) {
2484 result.appendFormat("- Layer %s (%s, %p)\n",
2485 getName().string(), getTypeId(), this);
2486 Mutex::Autolock lock(mFrameEventHistoryMutex);
2487 mFrameEventHistory.checkFencesForCompletion();
2488 mFrameEventHistory.dump(result);
2489}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002490
Brian Anderson5ea5e592016-12-01 16:54:33 -08002491void Layer::onDisconnect() {
2492 Mutex::Autolock lock(mFrameEventHistoryMutex);
2493 mFrameEventHistory.onDisconnect();
2494}
2495
Brian Anderson3890c392016-07-25 12:48:08 -07002496void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2497 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002498 Mutex::Autolock lock(mFrameEventHistoryMutex);
2499 if (newTimestamps) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002500 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002501 mFrameEventHistory.addQueue(*newTimestamps);
2502 }
2503
Brian Anderson3890c392016-07-25 12:48:08 -07002504 if (outDelta) {
2505 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002506 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002507}
Dan Stozae77c7662016-05-13 11:37:28 -07002508
2509std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2510 bool forceFlush) {
2511 std::vector<OccupancyTracker::Segment> history;
2512 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2513 &history);
2514 if (result != NO_ERROR) {
2515 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2516 result);
2517 return {};
2518 }
2519 return history;
2520}
2521
Robert Carr367c5682016-06-20 11:55:28 -07002522bool Layer::getTransformToDisplayInverse() const {
2523 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2524}
2525
Robert Carr1f0a16a2016-10-24 16:27:39 -07002526void Layer::addChild(const sp<Layer>& layer) {
2527 mCurrentChildren.add(layer);
2528 layer->setParent(this);
2529}
2530
2531ssize_t Layer::removeChild(const sp<Layer>& layer) {
2532 layer->setParent(nullptr);
2533 return mCurrentChildren.remove(layer);
2534}
2535
Robert Carr1db73f62016-12-21 12:58:51 -08002536bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2537 sp<Handle> handle = nullptr;
2538 sp<Layer> newParent = nullptr;
2539 if (newParentHandle == nullptr) {
2540 return false;
2541 }
2542 handle = static_cast<Handle*>(newParentHandle.get());
2543 newParent = handle->owner.promote();
2544 if (newParent == nullptr) {
2545 ALOGE("Unable to promote Layer handle");
2546 return false;
2547 }
2548
2549 for (const sp<Layer>& child : mCurrentChildren) {
Robert Carr98b0fd52017-06-01 14:59:25 -07002550 // We don't call addChild as we need to delay updating the child's parent pointer until
2551 // a transaction occurs. Remember a refresh could occur in between now and the next
2552 // transaction, in which case the Layer's parent pointer would be updated, but changes
2553 // made to the parent in the same transaction would not have applied.
2554 // This means that the following kind of scenario wont work:
2555 //
2556 // 1. Existing and visible child and parent surface exist
2557 // 2. Create new surface hidden
2558 // 3. Open transaction
2559 // 4. Show the new surface, and reparent the old surface's children to it.
2560 // 5. Close transaction.
2561 //
2562 // If we were to update the parent pointer immediately, then the child surface
2563 // could disappear for one frame as it pointed at the new parent which
2564 // hasn't yet become visible as the transaction hasn't yet occurred.
2565 //
2566 // Instead we defer the reparenting to commitChildList which happens as part
2567 // of the global transaction.
2568 newParent->mCurrentChildren.add(child);
Robert Carr1db73f62016-12-21 12:58:51 -08002569
2570 sp<Client> client(child->mClientRef.promote());
2571 if (client != nullptr) {
2572 client->setParentLayer(newParent);
2573 }
2574 }
2575 mCurrentChildren.clear();
2576
2577 return true;
2578}
2579
Robert Carr9524cb32017-02-13 11:32:32 -08002580bool Layer::detachChildren() {
Dan Stoza412903f2017-04-27 13:42:17 -07002581 traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
Robert Carr9524cb32017-02-13 11:32:32 -08002582 if (child == this) {
2583 return;
2584 }
2585
2586 sp<Client> client(child->mClientRef.promote());
2587 if (client != nullptr) {
2588 client->detachLayer(child);
2589 }
2590 });
2591
2592 return true;
2593}
2594
Robert Carr1f0a16a2016-10-24 16:27:39 -07002595void Layer::setParent(const sp<Layer>& layer) {
2596 mParent = layer;
2597}
2598
2599void Layer::clearSyncPoints() {
2600 for (const auto& child : mCurrentChildren) {
2601 child->clearSyncPoints();
2602 }
2603
2604 Mutex::Autolock lock(mLocalSyncPointMutex);
2605 for (auto& point : mLocalSyncPoints) {
2606 point->setFrameAvailable();
2607 }
2608 mLocalSyncPoints.clear();
2609}
2610
2611int32_t Layer::getZ() const {
2612 return mDrawingState.z;
2613}
2614
Dan Stoza412903f2017-04-27 13:42:17 -07002615LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2616 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2617 "makeTraversalList received invalid stateSet");
2618 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2619 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2620 const State& state = useDrawing ? mDrawingState : mCurrentState;
2621
2622 if (state.zOrderRelatives.size() == 0) {
2623 return children;
Robert Carrdb66e622017-04-10 16:55:57 -07002624 }
2625 LayerVector traverse;
2626
Dan Stoza412903f2017-04-27 13:42:17 -07002627 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07002628 sp<Layer> strongRelative = weakRelative.promote();
2629 if (strongRelative != nullptr) {
2630 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07002631 }
2632 }
2633
Dan Stoza412903f2017-04-27 13:42:17 -07002634 for (const sp<Layer>& child : children) {
Robert Carrdb66e622017-04-10 16:55:57 -07002635 traverse.add(child);
2636 }
2637
2638 return traverse;
2639}
2640
Robert Carr1f0a16a2016-10-24 16:27:39 -07002641/**
Robert Carrdb66e622017-04-10 16:55:57 -07002642 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002643 */
Dan Stoza412903f2017-04-27 13:42:17 -07002644void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2645 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002646
Robert Carr1f0a16a2016-10-24 16:27:39 -07002647 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002648 for (; i < list.size(); i++) {
2649 const auto& relative = list[i];
2650 if (relative->getZ() >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002651 break;
Robert Carrdb66e622017-04-10 16:55:57 -07002652 }
Dan Stoza412903f2017-04-27 13:42:17 -07002653 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002654 }
Dan Stoza412903f2017-04-27 13:42:17 -07002655 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07002656 for (; i < list.size(); i++) {
2657 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002658 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002659 }
2660}
2661
2662/**
Robert Carrdb66e622017-04-10 16:55:57 -07002663 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002664 */
Dan Stoza412903f2017-04-27 13:42:17 -07002665void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2666 const LayerVector::Visitor& visitor) {
2667 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002668
Robert Carr1f0a16a2016-10-24 16:27:39 -07002669 int32_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002670 for (i = list.size()-1; i>=0; i--) {
2671 const auto& relative = list[i];
2672 if (relative->getZ() < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002673 break;
2674 }
Dan Stoza412903f2017-04-27 13:42:17 -07002675 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002676 }
Dan Stoza412903f2017-04-27 13:42:17 -07002677 visitor(this);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002678 for (; i>=0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002679 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002680 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002681 }
2682}
2683
2684Transform Layer::getTransform() const {
2685 Transform t;
2686 const auto& p = getParent();
2687 if (p != nullptr) {
2688 t = p->getTransform();
Robert Carr9b429f42017-04-17 14:56:57 -07002689
2690 // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2691 // it isFixedSize) then there may be additional scaling not accounted
2692 // for in the transform. We need to mirror this scaling in child surfaces
2693 // or we will break the contract where WM can treat child surfaces as
2694 // pixels in the parent surface.
2695 if (p->isFixedSize()) {
Robert Carr1725eee2017-04-26 18:32:15 -07002696 int bufferWidth;
2697 int bufferHeight;
2698 if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2699 bufferWidth = p->mActiveBuffer->getWidth();
2700 bufferHeight = p->mActiveBuffer->getHeight();
2701 } else {
2702 bufferHeight = p->mActiveBuffer->getWidth();
2703 bufferWidth = p->mActiveBuffer->getHeight();
2704 }
Robert Carr9b429f42017-04-17 14:56:57 -07002705 float sx = p->getDrawingState().active.w /
Robert Carr1725eee2017-04-26 18:32:15 -07002706 static_cast<float>(bufferWidth);
Robert Carr9b429f42017-04-17 14:56:57 -07002707 float sy = p->getDrawingState().active.h /
Robert Carr1725eee2017-04-26 18:32:15 -07002708 static_cast<float>(bufferHeight);
Robert Carr9b429f42017-04-17 14:56:57 -07002709 Transform extraParentScaling;
2710 extraParentScaling.set(sx, 0, 0, sy);
2711 t = t * extraParentScaling;
2712 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002713 }
2714 return t * getDrawingState().active.transform;
2715}
2716
Robert Carr6452f122017-03-21 10:41:29 -07002717#ifdef USE_HWC2
2718float Layer::getAlpha() const {
2719 const auto& p = getParent();
2720
2721 float parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0;
2722 return parentAlpha * getDrawingState().alpha;
2723}
2724#else
2725uint8_t Layer::getAlpha() const {
2726 const auto& p = getParent();
2727
2728 float parentAlpha = (p != nullptr) ? (p->getAlpha() / 255.0f) : 1.0;
2729 float drawingAlpha = getDrawingState().alpha / 255.0f;
2730 drawingAlpha = drawingAlpha * parentAlpha;
2731 return static_cast<uint8_t>(std::round(drawingAlpha * 255));
2732}
2733#endif
2734
Robert Carr1f0a16a2016-10-24 16:27:39 -07002735void Layer::commitChildList() {
2736 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2737 const auto& child = mCurrentChildren[i];
Robert Carr98b0fd52017-06-01 14:59:25 -07002738 child->setParent(this);
2739
Robert Carr1f0a16a2016-10-24 16:27:39 -07002740 child->commitChildList();
2741 }
2742 mDrawingChildren = mCurrentChildren;
2743}
2744
Mathias Agopian13127d82013-03-05 17:47:11 -08002745// ---------------------------------------------------------------------------
2746
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002748
2749#if defined(__gl_h_)
2750#error "don't include gl/gl.h in this file"
2751#endif
2752
2753#if defined(__gl2_h_)
2754#error "don't include gl2/gl2.h in this file"
2755#endif