blob: 3cbc2f41944e70b571bef0ff5a346beebee60058 [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
Courtney Goeltzenleuchter36c44dc2017-04-14 09:33:16 -060037#include <ui/DebugUtils.h>
Mathias Agopian3330b202009-10-05 17:07:12 -070038#include <ui/GraphicBuffer.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080039#include <ui/PixelFormat.h>
Mathias Agopian9cce3252010-02-09 17:46:37 -080040
Dan Stoza6b9454d2014-11-07 16:00:59 -080041#include <gui/BufferItem.h>
Mathias Agopiana9347642017-02-13 16:42:28 -080042#include <gui/BufferQueue.h>
Mathias Agopian90ac7992012-02-25 18:48:35 -080043#include <gui/Surface.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080044
45#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020046#include "Colorizer.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070047#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080048#include "Layer.h"
Fabien Sanglard7b1563a2016-10-13 12:05:28 -070049#include "LayerRejecter.h"
Dan Stozab9b08832014-03-13 11:55:57 -070050#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080051#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080052
Mathias Agopian1b031492012-06-20 17:51:20 -070053#include "DisplayHardware/HWComposer.h"
54
Mathias Agopian875d8e12013-06-07 15:35:48 -070055#include "RenderEngine/RenderEngine.h"
56
Dan Stozac5da2712016-07-20 15:38:12 -070057#include <mutex>
58
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059#define DEBUG_RESIZE 0
60
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061namespace android {
62
63// ---------------------------------------------------------------------------
64
Mathias Agopian13127d82013-03-05 17:47:11 -080065int32_t Layer::sSequence = 1;
66
Mathias Agopian4d9b8222013-03-12 17:11:48 -070067Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
68 const String8& name, uint32_t w, uint32_t h, uint32_t flags)
Mathias Agopian13127d82013-03-05 17:47:11 -080069 : contentDirty(false),
70 sequence(uint32_t(android_atomic_inc(&sSequence))),
71 mFlinger(flinger),
Mathias Agopiana67932f2011-04-20 14:20:59 -070072 mTextureName(-1U),
Mathias Agopian13127d82013-03-05 17:47:11 -080073 mPremultipliedAlpha(true),
74 mName("unnamed"),
Mathias Agopian13127d82013-03-05 17:47:11 -080075 mFormat(PIXEL_FORMAT_NONE),
Mathias Agopian13127d82013-03-05 17:47:11 -080076 mTransactionFlags(0),
Dan Stoza7dde5992015-05-22 09:51:44 -070077 mPendingStateMutex(),
78 mPendingStates(),
Mathias Agopiana67932f2011-04-20 14:20:59 -070079 mQueuedFrames(0),
Jesse Hall399184a2014-03-03 15:42:54 -080080 mSidebandStreamChanged(false),
Mathias Agopiana9347642017-02-13 16:42:28 -080081 mActiveBufferSlot(BufferQueue::INVALID_BUFFER_SLOT),
Mathias Agopiana67932f2011-04-20 14:20:59 -070082 mCurrentTransform(0),
Mathias Agopian933389f2011-07-18 16:15:08 -070083 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
Robert Carrc3574f72016-03-24 12:19:32 -070084 mOverrideScalingMode(-1),
Mathias Agopiana67932f2011-04-20 14:20:59 -070085 mCurrentOpacity(true),
Brian Andersond6927fb2016-07-23 23:37:30 -070086 mBufferLatched(false),
Dan Stozacac35382016-01-27 12:21:06 -080087 mCurrentFrameNumber(0),
Brian Anderson8cc8b102016-10-21 12:43:09 -070088 mPreviousFrameNumber(0),
Mathias Agopian4d143ee2012-02-23 20:05:39 -080089 mRefreshPending(false),
Mathias Agopian82d7ab62012-01-19 18:34:40 -080090 mFrameLatencyNeeded(false),
Mathias Agopian13127d82013-03-05 17:47:11 -080091 mFiltering(false),
92 mNeedsFiltering(false),
Mathias Agopian5cdc8992013-08-13 20:51:23 -070093 mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
Fabien Sanglard9d96de42016-10-11 00:15:18 +000094#ifndef USE_HWC2
95 mIsGlesComposition(false),
96#endif
Mathias Agopian13127d82013-03-05 17:47:11 -080097 mProtectedByApp(false),
98 mHasSurface(false),
Riley Andrews03414a12014-07-01 14:22:59 -070099 mClientRef(client),
Dan Stozaa4650a52015-05-12 12:56:16 -0700100 mPotentialCursor(false),
101 mQueueItemLock(),
102 mQueueItemCondition(),
103 mQueueItems(),
Dan Stoza65476f32015-05-14 09:27:25 -0700104 mLastFrameNumberReceived(0),
Pablo Ceballos04839ab2015-11-13 13:39:23 -0800105 mUpdateTexImageFailed(false),
Robert Carr82364e32016-05-15 11:27:47 -0700106 mAutoRefresh(false),
107 mFreezePositionUpdates(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800108{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000109#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800110 ALOGV("Creating Layer %s", name.string());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000111#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -0800112
Mathias Agopiana67932f2011-04-20 14:20:59 -0700113 mCurrentCrop.makeInvalid();
Mathias Agopian3f844832013-08-07 21:24:32 -0700114 mFlinger->getRenderEngine().genTextures(1, &mTextureName);
Mathias Agopian49457ac2013-08-14 18:20:17 -0700115 mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700116
117 uint32_t layerFlags = 0;
118 if (flags & ISurfaceComposerClient::eHidden)
Andy McFadden4125a4f2014-01-29 17:17:11 -0800119 layerFlags |= layer_state_t::eLayerHidden;
120 if (flags & ISurfaceComposerClient::eOpaque)
121 layerFlags |= layer_state_t::eLayerOpaque;
Dan Stoza23116082015-06-18 14:58:39 -0700122 if (flags & ISurfaceComposerClient::eSecure)
123 layerFlags |= layer_state_t::eLayerSecure;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700124
125 if (flags & ISurfaceComposerClient::eNonPremultiplied)
126 mPremultipliedAlpha = false;
127
128 mName = name;
Dan Stozaf7ba41a2017-05-10 15:11:11 -0700129 mTransactionName = String8("TX - ") + mName;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700130
131 mCurrentState.active.w = w;
132 mCurrentState.active.h = h;
Robert Carr3dcabfa2016-03-01 18:36:58 -0800133 mCurrentState.active.transform.set(0, 0);
Robert Carrb5d3d262016-03-25 15:08:13 -0700134 mCurrentState.crop.makeInvalid();
135 mCurrentState.finalCrop.makeInvalid();
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700136 mCurrentState.z = 0;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000137#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800138 mCurrentState.alpha = 1.0f;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000139#else
140 mCurrentState.alpha = 0xFF;
141#endif
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700142 mCurrentState.layerStack = 0;
143 mCurrentState.flags = layerFlags;
144 mCurrentState.sequence = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700145 mCurrentState.requested = mCurrentState.active;
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700146 mCurrentState.dataSpace = HAL_DATASPACE_UNKNOWN;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500147 mCurrentState.appId = 0;
148 mCurrentState.type = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700149
150 // drawing state & current state are identical
151 mDrawingState = mCurrentState;
Jamie Gennis6547ff42013-07-16 20:12:42 -0700152
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000153#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800154 const auto& hwc = flinger->getHwComposer();
155 const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
156 nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000157#else
158 nsecs_t displayPeriod =
159 flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
160#endif
Jamie Gennis6547ff42013-07-16 20:12:42 -0700161 mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -0800162
163 CompositorTiming compositorTiming;
164 flinger->getCompositorTiming(&compositorTiming);
165 mFrameEventHistory.initializeCompositorTiming(compositorTiming);
Jamie Gennise8696a42012-01-15 18:54:57 -0800166}
167
Mathias Agopian3f844832013-08-07 21:24:32 -0700168void Layer::onFirstRef() {
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800169 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
Dan Stozab3d0bdf2014-04-07 16:33:59 -0700170 sp<IGraphicBufferProducer> producer;
171 sp<IGraphicBufferConsumer> consumer;
Mathias Agopian0556d792017-03-22 15:49:32 -0700172 BufferQueue::createBufferQueue(&producer, &consumer, true);
Robert Carr1db73f62016-12-21 12:58:51 -0800173 mProducer = new MonitoredProducer(producer, mFlinger, this);
Irvel468051e2016-06-13 16:44:44 -0700174 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800175 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Jesse Hall399184a2014-03-03 15:42:54 -0800176 mSurfaceFlingerConsumer->setContentsChangedListener(this);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700177 mSurfaceFlingerConsumer->setName(mName);
Daniel Lamb2675792012-02-23 14:35:13 -0800178
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800179 if (mFlinger->isLayerTripleBufferingDisabled()) {
180 mProducer->setMaxDequeuedBufferCount(2);
181 }
Andy McFadden69052052012-09-14 16:10:11 -0700182
Mathias Agopian84300952012-11-21 16:02:13 -0800183 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
184 updateTransformHint(hw);
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700185}
186
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700187Layer::~Layer() {
Pablo Ceballos8ea4e7b2016-03-03 15:20:02 -0800188 sp<Client> c(mClientRef.promote());
189 if (c != 0) {
190 c->detachLayer(this);
191 }
192
Dan Stozacac35382016-01-27 12:21:06 -0800193 for (auto& point : mRemoteSyncPoints) {
194 point->setTransactionApplied();
195 }
Dan Stozac8145172016-04-28 16:29:06 -0700196 for (auto& point : mLocalSyncPoints) {
197 point->setFrameAvailable();
198 }
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700199 mFlinger->deleteTextureAsync(mTextureName);
Jamie Gennis6547ff42013-07-16 20:12:42 -0700200 mFrameTracker.logAndResetStats(mName);
Mathias Agopian96f08192010-06-02 23:28:45 -0700201}
202
Mathias Agopian13127d82013-03-05 17:47:11 -0800203// ---------------------------------------------------------------------------
204// callbacks
205// ---------------------------------------------------------------------------
206
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000207#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800208void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
209 if (mHwcLayers.empty()) {
210 return;
211 }
212 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
213}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000214#else
215void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
216 HWComposer::HWCLayerInterface* layer) {
217 if (layer) {
218 layer->onDisplayed();
219 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
220 }
221}
222#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800223
Dan Stoza6b9454d2014-11-07 16:00:59 -0800224void Layer::onFrameAvailable(const BufferItem& item) {
225 // Add this buffer from our internal queue tracker
226 { // Autolock scope
227 Mutex::Autolock lock(mQueueItemLock);
Irvel468051e2016-06-13 16:44:44 -0700228 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
229 item.mGraphicBuffer->getHeight(), item.mFrameNumber);
Dan Stozaa4650a52015-05-12 12:56:16 -0700230 // Reset the frame number tracker when we receive the first buffer after
231 // a frame number reset
232 if (item.mFrameNumber == 1) {
233 mLastFrameNumberReceived = 0;
234 }
235
236 // Ensure that callbacks are handled in order
237 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
238 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
239 ms2ns(500));
240 if (result != NO_ERROR) {
241 ALOGE("[%s] Timed out waiting on callback", mName.string());
242 }
243 }
244
Dan Stoza6b9454d2014-11-07 16:00:59 -0800245 mQueueItems.push_back(item);
Dan Stozaecc50402015-04-28 14:42:06 -0700246 android_atomic_inc(&mQueuedFrames);
Dan Stozaa4650a52015-05-12 12:56:16 -0700247
248 // Wake up any pending callbacks
249 mLastFrameNumberReceived = item.mFrameNumber;
250 mQueueItemCondition.broadcast();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800251 }
252
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800253 mFlinger->signalLayerUpdate();
Mathias Agopian579b3f82010-06-08 19:54:15 -0700254}
255
Dan Stoza6b9454d2014-11-07 16:00:59 -0800256void Layer::onFrameReplaced(const BufferItem& item) {
Dan Stoza7dde5992015-05-22 09:51:44 -0700257 { // Autolock scope
258 Mutex::Autolock lock(mQueueItemLock);
Dan Stozaa4650a52015-05-12 12:56:16 -0700259
Dan Stoza7dde5992015-05-22 09:51:44 -0700260 // Ensure that callbacks are handled in order
261 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
262 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
263 ms2ns(500));
264 if (result != NO_ERROR) {
265 ALOGE("[%s] Timed out waiting on callback", mName.string());
266 }
Dan Stozaa4650a52015-05-12 12:56:16 -0700267 }
Dan Stoza7dde5992015-05-22 09:51:44 -0700268
269 if (mQueueItems.empty()) {
270 ALOGE("Can't replace a frame on an empty queue");
271 return;
272 }
Pablo Ceballos4d85da42016-04-19 20:11:56 -0700273 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
Dan Stoza7dde5992015-05-22 09:51:44 -0700274
275 // Wake up any pending callbacks
276 mLastFrameNumberReceived = item.mFrameNumber;
277 mQueueItemCondition.broadcast();
Dan Stozaa4650a52015-05-12 12:56:16 -0700278 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800279}
280
Jesse Hall399184a2014-03-03 15:42:54 -0800281void Layer::onSidebandStreamChanged() {
282 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
283 // mSidebandStreamChanged was false
284 mFlinger->signalLayerUpdate();
285 }
286}
287
Mathias Agopian67106042013-03-14 19:18:13 -0700288// called with SurfaceFlinger::mStateLock from the drawing thread after
289// the layer has been remove from the current state list (and just before
290// it's removed from the drawing state list)
Mathias Agopian13127d82013-03-05 17:47:11 -0800291void Layer::onRemoved() {
Robert Carr5edb1ad2017-04-25 10:54:24 -0700292 if (mCurrentState.zOrderRelativeOf != nullptr) {
293 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
294 if (strongRelative != nullptr) {
295 strongRelative->removeZOrderRelative(this);
296 }
297 mCurrentState.zOrderRelativeOf = nullptr;
298 }
299
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800300 mSurfaceFlingerConsumer->abandon();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700301 for (const auto& child : mCurrentChildren) {
302 child->onRemoved();
303 }
Mathias Agopian48d819a2009-09-10 19:41:18 -0700304}
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700305
Mathias Agopian13127d82013-03-05 17:47:11 -0800306// ---------------------------------------------------------------------------
307// set-up
308// ---------------------------------------------------------------------------
309
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700310const String8& Layer::getName() const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800311 return mName;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800312}
313
Mathias Agopianf9d93272009-06-19 17:00:27 -0700314status_t Layer::setBuffers( uint32_t w, uint32_t h,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800315 PixelFormat format, uint32_t flags)
316{
Mathias Agopianca99fb82010-04-14 16:43:44 -0700317 uint32_t const maxSurfaceDims = min(
Mathias Agopiana4912602012-07-12 14:25:33 -0700318 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
Mathias Agopianca99fb82010-04-14 16:43:44 -0700319
320 // never allow a surface larger than what our underlying GL implementation
321 // can handle.
322 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
Mathias Agopianff615cc2012-02-24 14:58:36 -0800323 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700324 return BAD_VALUE;
325 }
326
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700327 mFormat = format;
Mathias Agopianeff062c2010-08-25 14:59:15 -0700328
Riley Andrews03414a12014-07-01 14:22:59 -0700329 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
Mathias Agopian3165cc22012-08-08 19:42:09 -0700330 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700331 mCurrentOpacity = getOpacityForFormat(format);
332
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800333 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
334 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
335 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700336
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800337 return NO_ERROR;
338}
339
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700340sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800341 Mutex::Autolock _l(mLock);
342
343 LOG_ALWAYS_FATAL_IF(mHasSurface,
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700344 "Layer::getHandle() has already been called");
Mathias Agopian13127d82013-03-05 17:47:11 -0800345
346 mHasSurface = true;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700347
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700348 return new Handle(mFlinger, this);
Mathias Agopian13127d82013-03-05 17:47:11 -0800349}
350
Dan Stozab9b08832014-03-13 11:55:57 -0700351sp<IGraphicBufferProducer> Layer::getProducer() const {
352 return mProducer;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700353}
354
Mathias Agopian13127d82013-03-05 17:47:11 -0800355// ---------------------------------------------------------------------------
356// h/w composer set-up
357// ---------------------------------------------------------------------------
358
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800359Rect Layer::getContentCrop() const {
360 // this is the crop rectangle that applies to the buffer
361 // itself (as opposed to the window)
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700362 Rect crop;
363 if (!mCurrentCrop.isEmpty()) {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800364 // if the buffer crop is defined, we use that
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700365 crop = mCurrentCrop;
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800366 } else if (mActiveBuffer != NULL) {
367 // otherwise we use the whole buffer
368 crop = mActiveBuffer->getBounds();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700369 } else {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800370 // if we don't have a buffer yet, we use an empty/invalid crop
Mathias Agopian4fec8732012-06-29 14:12:52 -0700371 crop.makeInvalid();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700372 }
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700373 return crop;
374}
375
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700376static Rect reduce(const Rect& win, const Region& exclude) {
377 if (CC_LIKELY(exclude.isEmpty())) {
378 return win;
379 }
380 if (exclude.isRect()) {
381 return win.reduce(exclude.getBounds());
382 }
383 return Region(win).subtract(exclude).getBounds();
384}
385
Robert Carr1f0a16a2016-10-24 16:27:39 -0700386Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
387 const Layer::State& s(getDrawingState());
388 Rect win(s.active.w, s.active.h);
389
390 if (!s.crop.isEmpty()) {
391 win.intersect(s.crop, &win);
392 }
393
394 Transform t = getTransform();
395 win = t.transform(win);
396
397 const sp<Layer>& p = getParent();
398 // Now we need to calculate the parent bounds, so we can clip ourselves to those.
399 // When calculating the parent bounds for purposes of clipping,
400 // we don't need to constrain the parent to its transparent region.
401 // The transparent region is an optimization based on the
402 // buffer contents of the layer, but does not affect the space allocated to
403 // it by policy, and thus children should be allowed to extend into the
404 // parent's transparent region. In fact one of the main uses, is to reduce
405 // buffer allocation size in cases where a child window sits behind a main window
406 // (by marking the hole in the parent window as a transparent region)
407 if (p != nullptr) {
408 Rect bounds = p->computeScreenBounds(false);
409 bounds.intersect(win, &win);
410 }
411
412 if (reduceTransparentRegion) {
413 auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
414 win = reduce(win, screenTransparentRegion);
415 }
416
417 return win;
418}
419
Mathias Agopian13127d82013-03-05 17:47:11 -0800420Rect Layer::computeBounds() const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700421 const Layer::State& s(getDrawingState());
Michael Lentine6c925ed2014-09-26 17:55:01 -0700422 return computeBounds(s.activeTransparentRegion);
423}
424
425Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
426 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800427 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700428
429 if (!s.crop.isEmpty()) {
430 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -0800431 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700432
433 Rect bounds = win;
434 const auto& p = getParent();
435 if (p != nullptr) {
Robert Carrde9ec442017-02-08 17:43:36 -0800436 // Look in computeScreenBounds recursive call for explanation of
437 // why we pass false here.
438 bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700439 }
440
441 Transform t = getTransform();
442 if (p != nullptr) {
443 win = t.transform(win);
444 win.intersect(bounds, &win);
445 win = t.inverse().transform(win);
446 }
447
Mathias Agopian6c7f25a2013-05-09 20:37:10 -0700448 // subtract the transparent region and snap to the bounds
Michael Lentine6c925ed2014-09-26 17:55:01 -0700449 return reduce(win, activeTransparentRegion);
Mathias Agopian13127d82013-03-05 17:47:11 -0800450}
451
Robert Carr1f0a16a2016-10-24 16:27:39 -0700452Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
Robert Carrb5d3d262016-03-25 15:08:13 -0700453 // the crop is the area of the window that gets cropped, but not
Mathias Agopian13127d82013-03-05 17:47:11 -0800454 // scaled in any ways.
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700455 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800456
457 // apply the projection's clipping to the window crop in
458 // layerstack space, and convert-back to layer space.
Mathias Agopian6b442672013-07-09 21:24:52 -0700459 // if there are no window scaling involved, this operation will map to full
460 // pixels in the buffer.
461 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
462 // a viewport clipping and a window transform. we should use floating point to fix this.
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700463
464 Rect activeCrop(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700465 if (!s.crop.isEmpty()) {
466 activeCrop = s.crop;
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700467 }
468
Robert Carr1f0a16a2016-10-24 16:27:39 -0700469 Transform t = getTransform();
470 activeCrop = t.transform(activeCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000471 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
472 activeCrop.clear();
473 }
Robert Carrb5d3d262016-03-25 15:08:13 -0700474 if (!s.finalCrop.isEmpty()) {
475 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000476 activeCrop.clear();
477 }
478 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700479 return activeCrop;
480}
481
Dan Stoza5a423ea2017-02-16 14:10:39 -0800482FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
Robert Carr1f0a16a2016-10-24 16:27:39 -0700483 // the content crop is the area of the content that gets scaled to the
484 // layer's size. This is in buffer space.
Dan Stoza5a423ea2017-02-16 14:10:39 -0800485 FloatRect crop = getContentCrop().toFloatRect();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700486
487 // In addition there is a WM-specified crop we pull from our drawing state.
488 const State& s(getDrawingState());
489
490 // Screen space to make reduction to parent crop clearer.
491 Rect activeCrop = computeInitialCrop(hw);
492 const auto& p = getParent();
493 if (p != nullptr) {
494 auto parentCrop = p->computeInitialCrop(hw);
495 activeCrop.intersect(parentCrop, &activeCrop);
496 }
497 Transform t = getTransform();
498 // Back to layer space to work with the content crop.
499 activeCrop = t.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800500
Michael Lentine28ea2172014-11-19 18:32:37 -0800501 // This needs to be here as transform.transform(Rect) computes the
502 // transformed rect and then takes the bounding box of the result before
503 // returning. This means
504 // transform.inverse().transform(transform.transform(Rect)) != Rect
505 // in which case we need to make sure the final rect is clipped to the
506 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000507 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
508 activeCrop.clear();
509 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800510
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700511 // subtract the transparent region and snap to the bounds
512 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
513
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000514 // Transform the window crop to match the buffer coordinate system,
515 // which means using the inverse of the current transform set on the
516 // SurfaceFlingerConsumer.
517 uint32_t invTransform = mCurrentTransform;
Robert Carrcae605c2017-03-29 12:10:31 -0700518 if (getTransformToDisplayInverse()) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000519 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700520 * the code below applies the primary display's inverse transform to the
521 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000522 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700523 uint32_t invTransformOrient =
524 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000525 // calculate the inverse transform
526 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
527 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
528 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800529 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000530 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700531 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
532 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800533 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000534
535 int winWidth = s.active.w;
536 int winHeight = s.active.h;
537 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
538 // If the activeCrop has been rotate the ends are rotated but not
539 // the space itself so when transforming ends back we can't rely on
540 // a modification of the axes of rotation. To account for this we
541 // need to reorient the inverse rotation in terms of the current
542 // axes of rotation.
543 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
544 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
545 if (is_h_flipped == is_v_flipped) {
546 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
547 NATIVE_WINDOW_TRANSFORM_FLIP_H;
548 }
549 winWidth = s.active.h;
550 winHeight = s.active.w;
551 }
552 const Rect winCrop = activeCrop.transform(
553 invTransform, s.active.w, s.active.h);
554
555 // below, crop is intersected with winCrop expressed in crop's coordinate space
556 float xScale = crop.getWidth() / float(winWidth);
557 float yScale = crop.getHeight() / float(winHeight);
558
559 float insetL = winCrop.left * xScale;
560 float insetT = winCrop.top * yScale;
561 float insetR = (winWidth - winCrop.right ) * xScale;
562 float insetB = (winHeight - winCrop.bottom) * yScale;
563
564 crop.left += insetL;
565 crop.top += insetT;
566 crop.right -= insetR;
567 crop.bottom -= insetB;
568
Mathias Agopian13127d82013-03-05 17:47:11 -0800569 return crop;
570}
571
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000572#ifdef USE_HWC2
Robert Carrae060832016-11-28 10:51:00 -0800573void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000574#else
575void Layer::setGeometry(
576 const sp<const DisplayDevice>& hw,
577 HWComposer::HWCLayerInterface& layer)
578#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700579{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000580#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800581 const auto hwcId = displayDevice->getHwcDisplayId();
582 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000583#else
584 layer.setDefaultState();
585#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700586
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700587 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000588#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800589 hwcInfo.forceClientComposition = false;
590
591 if (isSecure() && !displayDevice->isSecure()) {
592 hwcInfo.forceClientComposition = true;
593 }
594
595 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000596#else
597 layer.setSkip(false);
598
599 if (isSecure() && !hw->isSecure()) {
600 layer.setSkip(true);
601 }
602#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700603
Mathias Agopian13127d82013-03-05 17:47:11 -0800604 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700605 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000606#ifdef USE_HWC2
David Revemanecf0fa52017-03-03 11:32:44 -0500607 auto blendMode = HWC2::BlendMode::None;
Robert Carr6452f122017-03-21 10:41:29 -0700608 if (!isOpaque(s) || getAlpha() != 1.0f) {
David Revemanecf0fa52017-03-03 11:32:44 -0500609 blendMode = mPremultipliedAlpha ?
Dan Stoza9e56aa02015-11-02 13:00:03 -0800610 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800611 }
David Revemanecf0fa52017-03-03 11:32:44 -0500612 auto error = hwcLayer->setBlendMode(blendMode);
613 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
614 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
615 to_string(error).c_str(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000616#else
Robert Carr6452f122017-03-21 10:41:29 -0700617 if (!isOpaque(s) || getAlpha() != 0xFF) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000618 layer.setBlending(mPremultipliedAlpha ?
619 HWC_BLENDING_PREMULT :
620 HWC_BLENDING_COVERAGE);
621 }
622#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800623
624 // apply the layer's transform, followed by the display's global transform
625 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700626 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700627 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -0700628 if (!s.crop.isEmpty()) {
629 Rect activeCrop(s.crop);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700630 activeCrop = t.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000631#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000632 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000633#else
634 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
635#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000636 activeCrop.clear();
637 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700638 activeCrop = t.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800639 // This needs to be here as transform.transform(Rect) computes the
640 // transformed rect and then takes the bounding box of the result before
641 // returning. This means
642 // transform.inverse().transform(transform.transform(Rect)) != Rect
643 // in which case we need to make sure the final rect is clipped to the
644 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000645 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
646 activeCrop.clear();
647 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700648 // mark regions outside the crop as transparent
649 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
650 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
651 s.active.w, s.active.h));
652 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
653 activeCrop.left, activeCrop.bottom));
654 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
655 s.active.w, activeCrop.bottom));
656 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700657
658 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700659 if (!s.finalCrop.isEmpty()) {
660 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000661 frame.clear();
662 }
663 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000664#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000665 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
666 frame.clear();
667 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800668 const Transform& tr(displayDevice->getTransform());
669 Rect transformedFrame = tr.transform(frame);
David Revemanecf0fa52017-03-03 11:32:44 -0500670 error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700671 if (error != HWC2::Error::None) {
672 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
673 mName.string(), transformedFrame.left, transformedFrame.top,
674 transformedFrame.right, transformedFrame.bottom,
675 to_string(error).c_str(), static_cast<int32_t>(error));
676 } else {
677 hwcInfo.displayFrame = transformedFrame;
678 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800679
Dan Stoza5a423ea2017-02-16 14:10:39 -0800680 FloatRect sourceCrop = computeCrop(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800681 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700682 if (error != HWC2::Error::None) {
683 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
684 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
685 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
686 static_cast<int32_t>(error));
687 } else {
688 hwcInfo.sourceCrop = sourceCrop;
689 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800690
Robert Carr6452f122017-03-21 10:41:29 -0700691 float alpha = getAlpha();
692 error = hwcLayer->setPlaneAlpha(alpha);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800693 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
Robert Carr6452f122017-03-21 10:41:29 -0700694 "%s (%d)", mName.string(), alpha, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800695 static_cast<int32_t>(error));
696
Robert Carrae060832016-11-28 10:51:00 -0800697 error = hwcLayer->setZOrder(z);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800698 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
Robert Carrae060832016-11-28 10:51:00 -0800699 mName.string(), z, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800700 static_cast<int32_t>(error));
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500701
702 error = hwcLayer->setInfo(s.type, s.appId);
703 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
704 mName.string(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000705#else
706 if (!frame.intersect(hw->getViewport(), &frame)) {
707 frame.clear();
708 }
709 const Transform& tr(hw->getTransform());
710 layer.setFrame(tr.transform(frame));
711 layer.setCrop(computeCrop(hw));
Robert Carr6452f122017-03-21 10:41:29 -0700712 layer.setPlaneAlpha(getAlpha());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000713#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800714
Mathias Agopian29a367b2011-07-12 14:51:45 -0700715 /*
716 * Transformations are applied in this order:
717 * 1) buffer orientation/flip/mirror
718 * 2) state transformation (window manager)
719 * 3) layer orientation (screen orientation)
720 * (NOTE: the matrices are multiplied in reverse order)
721 */
722
723 const Transform bufferOrientation(mCurrentTransform);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700724 Transform transform(tr * t * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700725
Robert Carrcae605c2017-03-29 12:10:31 -0700726 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700727 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700728 * the code below applies the primary display's inverse transform to the
729 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700730 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700731 uint32_t invTransform =
732 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700733 // calculate the inverse transform
734 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
735 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
736 NATIVE_WINDOW_TRANSFORM_FLIP_H;
737 }
Robert Carrcae605c2017-03-29 12:10:31 -0700738
739 /*
740 * Here we cancel out the orientation component of the WM transform.
741 * The scaling and translate components are already included in our bounds
742 * computation so it's enough to just omit it in the composition.
743 * See comment in onDraw with ref to b/36727915 for why.
744 */
745 transform = Transform(invTransform) * tr * bufferOrientation;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700746 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700747
748 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800749 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000750#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800751 if (orientation & Transform::ROT_INVALID) {
752 // we can only handle simple transformation
753 hwcInfo.forceClientComposition = true;
754 } else {
755 auto transform = static_cast<HWC2::Transform>(orientation);
756 auto error = hwcLayer->setTransform(transform);
757 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
758 "%s (%d)", mName.string(), to_string(transform).c_str(),
759 to_string(error).c_str(), static_cast<int32_t>(error));
760 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000761#else
762 if (orientation & Transform::ROT_INVALID) {
763 // we can only handle simple transformation
764 layer.setSkip(true);
765 } else {
766 layer.setTransform(orientation);
767 }
768#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700769}
770
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000771#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800772void Layer::forceClientComposition(int32_t hwcId) {
773 if (mHwcLayers.count(hwcId) == 0) {
774 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
775 return;
776 }
777
778 mHwcLayers[hwcId].forceClientComposition = true;
779}
Dan Stoza9e56aa02015-11-02 13:00:03 -0800780
Dan Stoza9e56aa02015-11-02 13:00:03 -0800781void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
782 // Apply this display's projection's viewport to the visible region
783 // before giving it to the HWC HAL.
784 const Transform& tr = displayDevice->getTransform();
785 const auto& viewport = displayDevice->getViewport();
786 Region visible = tr.transform(visibleRegion.intersect(viewport));
787 auto hwcId = displayDevice->getHwcDisplayId();
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800788 auto& hwcInfo = mHwcLayers[hwcId];
789 auto& hwcLayer = hwcInfo.layer;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800790 auto error = hwcLayer->setVisibleRegion(visible);
791 if (error != HWC2::Error::None) {
792 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
793 to_string(error).c_str(), static_cast<int32_t>(error));
794 visible.dump(LOG_TAG);
795 }
796
797 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
798 if (error != HWC2::Error::None) {
799 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
800 to_string(error).c_str(), static_cast<int32_t>(error));
801 surfaceDamageRegion.dump(LOG_TAG);
802 }
803
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700804 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800805 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700806 setCompositionType(hwcId, HWC2::Composition::Sideband);
807 ALOGV("[%s] Requesting Sideband composition", mName.string());
808 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800809 if (error != HWC2::Error::None) {
810 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
811 mName.string(), mSidebandStream->handle(),
812 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800813 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700814 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800815 }
816
Dan Stoza0a21df72016-07-20 12:52:38 -0700817 // Client layers
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800818 if (hwcInfo.forceClientComposition ||
Dan Stoza0a21df72016-07-20 12:52:38 -0700819 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700820 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800821 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700822 return;
823 }
824
Dan Stoza0a21df72016-07-20 12:52:38 -0700825 // SolidColor layers
826 if (mActiveBuffer == nullptr) {
827 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700828
829 // For now, we only support black for DimLayer
Dan Stoza0a21df72016-07-20 12:52:38 -0700830 error = hwcLayer->setColor({0, 0, 0, 255});
831 if (error != HWC2::Error::None) {
832 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
833 to_string(error).c_str(), static_cast<int32_t>(error));
834 }
Dan Stozac6c89542016-07-27 10:16:52 -0700835
836 // Clear out the transform, because it doesn't make sense absent a
837 // source buffer
838 error = hwcLayer->setTransform(HWC2::Transform::None);
839 if (error != HWC2::Error::None) {
840 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
841 to_string(error).c_str(), static_cast<int32_t>(error));
842 }
843
Dan Stoza0a21df72016-07-20 12:52:38 -0700844 return;
845 }
846
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700847 // Device or Cursor layers
848 if (mPotentialCursor) {
849 ALOGV("[%s] Requesting Cursor composition", mName.string());
850 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800851 } else {
852 ALOGV("[%s] Requesting Device composition", mName.string());
853 setCompositionType(hwcId, HWC2::Composition::Device);
854 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700855
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700856 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
857 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
858 if (error != HWC2::Error::None) {
859 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
860 mCurrentState.dataSpace, to_string(error).c_str(),
861 static_cast<int32_t>(error));
862 }
863
Chia-I Wu06d63de2017-01-04 14:58:51 +0800864 uint32_t hwcSlot = 0;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400865 sp<GraphicBuffer> hwcBuffer;
866 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
867 &hwcSlot, &hwcBuffer);
Chia-I Wu06d63de2017-01-04 14:58:51 +0800868
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700869 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400870 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700871 if (error != HWC2::Error::None) {
872 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
873 mActiveBuffer->handle, to_string(error).c_str(),
874 static_cast<int32_t>(error));
875 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800876}
Courtney Goeltzenleuchter9551fd32016-10-20 17:18:15 -0600877
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000878#else
879void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
880 HWComposer::HWCLayerInterface& layer) {
881 // we have to set the visible region on every frame because
882 // we currently free it during onLayerDisplayed(), which is called
883 // after HWComposer::commit() -- every frame.
884 // Apply this display's projection's viewport to the visible region
885 // before giving it to the HWC HAL.
886 const Transform& tr = hw->getTransform();
887 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
888 layer.setVisibleRegionScreen(visible);
889 layer.setSurfaceDamage(surfaceDamageRegion);
890 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700891
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000892 if (mSidebandStream.get()) {
893 layer.setSidebandStream(mSidebandStream);
894 } else {
895 // NOTE: buffer can be NULL if the client never drew into this
896 // layer yet, or if we ran out of memory
897 layer.setBuffer(mActiveBuffer);
898 }
899}
900#endif
901
902#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800903void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
904 auto hwcId = displayDevice->getHwcDisplayId();
905 if (mHwcLayers.count(hwcId) == 0 ||
906 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
907 return;
908 }
909
910 // This gives us only the "orientation" component of the transform
911 const State& s(getCurrentState());
912
913 // Apply the layer's transform, followed by the display's global transform
914 // Here we're guaranteed that the layer's transform preserves rects
915 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700916 if (!s.crop.isEmpty()) {
917 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800918 }
919 // Subtract the transparent region and snap to the bounds
920 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700921 Rect frame(getTransform().transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800922 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -0700923 if (!s.finalCrop.isEmpty()) {
924 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000925 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800926 auto& displayTransform(displayDevice->getTransform());
927 auto position = displayTransform.transform(frame);
928
929 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
930 position.top);
931 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
932 "to (%d, %d): %s (%d)", mName.string(), position.left,
933 position.top, to_string(error).c_str(),
934 static_cast<int32_t>(error));
935}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000936#else
937void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
938 HWComposer::HWCLayerInterface& layer) {
939 int fenceFd = -1;
940
941 // TODO: there is a possible optimization here: we only need to set the
942 // acquire fence the first time a new buffer is acquired on EACH display.
943
944 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
945 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
946 if (fence->isValid()) {
947 fenceFd = fence->dup();
948 if (fenceFd == -1) {
949 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
950 }
951 }
952 }
953 layer.setAcquireFenceFd(fenceFd);
954}
955
956Rect Layer::getPosition(
957 const sp<const DisplayDevice>& hw)
958{
959 // this gives us only the "orientation" component of the transform
960 const State& s(getCurrentState());
961
962 // apply the layer's transform, followed by the display's global transform
963 // here we're guaranteed that the layer's transform preserves rects
964 Rect win(s.active.w, s.active.h);
965 if (!s.crop.isEmpty()) {
966 win.intersect(s.crop, &win);
967 }
968 // subtract the transparent region and snap to the bounds
969 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700970 Rect frame(getTransform().transform(bounds));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000971 frame.intersect(hw->getViewport(), &frame);
972 if (!s.finalCrop.isEmpty()) {
973 frame.intersect(s.finalCrop, &frame);
974 }
975 const Transform& tr(hw->getTransform());
976 return Rect(tr.transform(frame));
977}
978#endif
Riley Andrews03414a12014-07-01 14:22:59 -0700979
Mathias Agopian13127d82013-03-05 17:47:11 -0800980// ---------------------------------------------------------------------------
981// drawing...
982// ---------------------------------------------------------------------------
983
984void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -0800985 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -0800986}
987
Dan Stozac7014012014-02-14 15:03:43 -0800988void Layer::draw(const sp<const DisplayDevice>& hw,
989 bool useIdentityTransform) const {
990 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -0800991}
992
Dan Stozac7014012014-02-14 15:03:43 -0800993void Layer::draw(const sp<const DisplayDevice>& hw) const {
994 onDraw(hw, Region(hw->bounds()), false);
995}
996
Robert Carrcae605c2017-03-29 12:10:31 -0700997static constexpr mat4 inverseOrientation(uint32_t transform) {
998 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
999 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1000 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1001 mat4 tr;
1002
1003 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1004 tr = tr * rot90;
1005 }
1006 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1007 tr = tr * flipH;
1008 }
1009 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1010 tr = tr * flipV;
1011 }
1012 return inverse(tr);
1013}
1014
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001015/*
1016 * onDraw will draw the current layer onto the presentable buffer
1017 */
Dan Stozac7014012014-02-14 15:03:43 -08001018void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
1019 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001020{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001021 ATRACE_CALL();
1022
Mathias Agopiana67932f2011-04-20 14:20:59 -07001023 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001024 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -07001025 // in fact never been drawn into. This happens frequently with
1026 // SurfaceView because the WindowManager can't know when the client
1027 // has drawn the first time.
1028
1029 // If there is nothing under us, we paint the screen in black, otherwise
1030 // we just skip this update.
1031
1032 // figure out if there is something below us
1033 Region under;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001034 bool finished = false;
Dan Stoza412903f2017-04-27 13:42:17 -07001035 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001036 if (finished || layer == static_cast<Layer const*>(this)) {
1037 finished = true;
1038 return;
1039 }
Mathias Agopian42977342012-08-05 00:40:46 -07001040 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Robert Carr1f0a16a2016-10-24 16:27:39 -07001041 });
Mathias Agopian179169e2010-05-06 20:21:45 -07001042 // if not everything below us is covered, we plug the holes!
1043 Region holes(clip.subtract(under));
1044 if (!holes.isEmpty()) {
Fabien Sanglard17487192016-12-07 13:03:32 -08001045 clearWithOpenGL(hw, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -07001046 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001047 return;
1048 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001049
Andy McFadden97eba892012-12-11 15:21:45 -08001050 // Bind the current buffer to the GL texture, and wait for it to be
1051 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001052 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1053 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -08001054 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -07001055 // Go ahead and draw the buffer anyway; no matter what we do the screen
1056 // is probably going to have something visibly wrong.
1057 }
1058
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001059 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1060
Mathias Agopian875d8e12013-06-07 15:35:48 -07001061 RenderEngine& engine(mFlinger->getRenderEngine());
1062
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001063 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -07001064 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -07001065 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -07001066
1067 // Query the texture matrix given our current filtering mode.
1068 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001069 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1070 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -07001071
Robert Carrcae605c2017-03-29 12:10:31 -07001072 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001073
1074 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -07001075 * the code below applies the primary display's inverse transform to
1076 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001077 */
Pablo Ceballos021623b2016-04-15 17:31:51 -07001078 uint32_t transform =
1079 DisplayDevice::getPrimaryDisplayOrientationTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001080 mat4 tr = inverseOrientation(transform);
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001081
Robert Carrcae605c2017-03-29 12:10:31 -07001082 /**
1083 * TODO(b/36727915): This is basically a hack.
1084 *
1085 * Ensure that regardless of the parent transformation,
1086 * this buffer is always transformed from native display
1087 * orientation to display orientation. For example, in the case
1088 * of a camera where the buffer remains in native orientation,
1089 * we want the pixels to always be upright.
1090 */
1091 if (getParent() != nullptr) {
1092 const auto parentTransform = getParent()->getTransform();
1093 tr = tr * inverseOrientation(parentTransform.getOrientation());
1094 }
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001095
1096 // and finally apply it to the original texture matrix
1097 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1098 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1099 }
1100
Jamie Genniscbb1a952012-05-08 17:05:52 -07001101 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -07001102 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1103 mTexture.setFiltering(useFiltering);
1104 mTexture.setMatrix(textureMatrix);
1105
1106 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -07001107 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001108 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -07001109 }
Fabien Sanglard85789802016-12-07 13:08:24 -08001110 drawWithOpenGL(hw, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001111 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001112}
1113
Mathias Agopian13127d82013-03-05 17:47:11 -08001114
Dan Stozac7014012014-02-14 15:03:43 -08001115void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard17487192016-12-07 13:03:32 -08001116 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -08001117 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001118{
Mathias Agopian19733a32013-08-28 18:13:56 -07001119 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -08001120 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -07001121 engine.setupFillWithColor(red, green, blue, alpha);
1122 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -08001123}
1124
1125void Layer::clearWithOpenGL(
Fabien Sanglard17487192016-12-07 13:03:32 -08001126 const sp<const DisplayDevice>& hw) const {
1127 clearWithOpenGL(hw, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001128}
1129
Dan Stozac7014012014-02-14 15:03:43 -08001130void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard85789802016-12-07 13:08:24 -08001131 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001132 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001133
Dan Stozac7014012014-02-14 15:03:43 -08001134 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001135
Mathias Agopian13127d82013-03-05 17:47:11 -08001136 /*
1137 * NOTE: the way we compute the texture coordinates here produces
1138 * different results than when we take the HWC path -- in the later case
1139 * the "source crop" is rounded to texel boundaries.
1140 * This can produce significantly different results when the texture
1141 * is scaled by a large amount.
1142 *
1143 * The GL code below is more logical (imho), and the difference with
1144 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001145 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001146 * GL composition when a buffer scaling is applied (maybe with some
1147 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1148 * like more of a hack.
1149 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001150 Rect win(computeBounds());
1151
Robert Carr1f0a16a2016-10-24 16:27:39 -07001152 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -07001153 if (!s.finalCrop.isEmpty()) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001154 win = t.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001155 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001156 win.clear();
1157 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001158 win = t.inverse().transform(win);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001159 if (!win.intersect(computeBounds(), &win)) {
1160 win.clear();
1161 }
1162 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001163
Mathias Agopian3f844832013-08-07 21:24:32 -07001164 float left = float(win.left) / float(s.active.w);
1165 float top = float(win.top) / float(s.active.h);
1166 float right = float(win.right) / float(s.active.w);
1167 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001168
Mathias Agopian875d8e12013-06-07 15:35:48 -07001169 // TODO: we probably want to generate the texture coords with the mesh
1170 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001171 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1172 texCoords[0] = vec2(left, 1.0f - top);
1173 texCoords[1] = vec2(left, 1.0f - bottom);
1174 texCoords[2] = vec2(right, 1.0f - bottom);
1175 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001176
Mathias Agopian875d8e12013-06-07 15:35:48 -07001177 RenderEngine& engine(mFlinger->getRenderEngine());
Robert Carr6452f122017-03-21 10:41:29 -07001178 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), getAlpha());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001179#ifdef USE_HWC2
1180 engine.setSourceDataSpace(mCurrentState.dataSpace);
1181#endif
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001182 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001183 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001184}
1185
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001186#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001187void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1188 bool callIntoHwc) {
1189 if (mHwcLayers.count(hwcId) == 0) {
1190 ALOGE("setCompositionType called without a valid HWC layer");
1191 return;
1192 }
1193 auto& hwcInfo = mHwcLayers[hwcId];
1194 auto& hwcLayer = hwcInfo.layer;
1195 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1196 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1197 if (hwcInfo.compositionType != type) {
1198 ALOGV(" actually setting");
1199 hwcInfo.compositionType = type;
1200 if (callIntoHwc) {
1201 auto error = hwcLayer->setCompositionType(type);
1202 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1203 "composition type %s: %s (%d)", mName.string(),
1204 to_string(type).c_str(), to_string(error).c_str(),
1205 static_cast<int32_t>(error));
1206 }
1207 }
1208}
1209
1210HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001211 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1212 // If we're querying the composition type for a display that does not
1213 // have a HWC counterpart, then it will always be Client
1214 return HWC2::Composition::Client;
1215 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001216 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001217 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001218 return HWC2::Composition::Invalid;
1219 }
1220 return mHwcLayers.at(hwcId).compositionType;
1221}
1222
1223void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1224 if (mHwcLayers.count(hwcId) == 0) {
1225 ALOGE("setClearClientTarget called without a valid HWC layer");
1226 return;
1227 }
1228 mHwcLayers[hwcId].clearClientTarget = clear;
1229}
1230
1231bool Layer::getClearClientTarget(int32_t hwcId) const {
1232 if (mHwcLayers.count(hwcId) == 0) {
1233 ALOGE("getClearClientTarget called without a valid HWC layer");
1234 return false;
1235 }
1236 return mHwcLayers.at(hwcId).clearClientTarget;
1237}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001238#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001239
Ruben Brunk1681d952014-06-27 15:51:55 -07001240uint32_t Layer::getProducerStickyTransform() const {
1241 int producerStickyTransform = 0;
1242 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1243 if (ret != OK) {
1244 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1245 strerror(-ret), ret);
1246 return 0;
1247 }
1248 return static_cast<uint32_t>(producerStickyTransform);
1249}
1250
Dan Stozac5da2712016-07-20 15:38:12 -07001251bool Layer::latchUnsignaledBuffers() {
1252 static bool propertyLoaded = false;
1253 static bool latch = false;
1254 static std::mutex mutex;
1255 std::lock_guard<std::mutex> lock(mutex);
1256 if (!propertyLoaded) {
1257 char value[PROPERTY_VALUE_MAX] = {};
1258 property_get("debug.sf.latch_unsignaled", value, "0");
1259 latch = atoi(value);
1260 propertyLoaded = true;
1261 }
1262 return latch;
1263}
1264
Dan Stozacac35382016-01-27 12:21:06 -08001265uint64_t Layer::getHeadFrameNumber() const {
1266 Mutex::Autolock lock(mQueueItemLock);
1267 if (!mQueueItems.empty()) {
1268 return mQueueItems[0].mFrameNumber;
1269 } else {
1270 return mCurrentFrameNumber;
1271 }
1272}
1273
Dan Stoza1ce65812016-06-15 16:26:27 -07001274bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001275#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001276 if (latchUnsignaledBuffers()) {
1277 return true;
1278 }
1279
Dan Stoza1ce65812016-06-15 16:26:27 -07001280 Mutex::Autolock lock(mQueueItemLock);
1281 if (mQueueItems.empty()) {
1282 return true;
1283 }
1284 if (mQueueItems[0].mIsDroppable) {
1285 // Even though this buffer's fence may not have signaled yet, it could
1286 // be replaced by another buffer before it has a chance to, which means
1287 // that it's possible to get into a situation where a buffer is never
1288 // able to be latched. To avoid this, grab this buffer anyway.
1289 return true;
1290 }
1291 return mQueueItems[0].mFence->getSignalTime() != INT64_MAX;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001292#else
1293 return true;
1294#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001295}
1296
Dan Stozacac35382016-01-27 12:21:06 -08001297bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1298 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1299 // Don't bother with a SyncPoint, since we've already latched the
1300 // relevant frame
1301 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001302 }
1303
Dan Stozacac35382016-01-27 12:21:06 -08001304 Mutex::Autolock lock(mLocalSyncPointMutex);
1305 mLocalSyncPoints.push_back(point);
1306 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001307}
1308
Mathias Agopian13127d82013-03-05 17:47:11 -08001309void Layer::setFiltering(bool filtering) {
1310 mFiltering = filtering;
1311}
1312
1313bool Layer::getFiltering() const {
1314 return mFiltering;
1315}
1316
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001317// As documented in libhardware header, formats in the range
1318// 0x100 - 0x1FF are specific to the HAL implementation, and
1319// are known to have no alpha channel
1320// TODO: move definition for device-specific range into
1321// hardware.h, instead of using hard-coded values here.
1322#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1323
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001324bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001325 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1326 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001327 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001328 switch (format) {
1329 case HAL_PIXEL_FORMAT_RGBA_8888:
1330 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001331 case HAL_PIXEL_FORMAT_RGBA_FP16:
Romain Guy541f2262017-02-10 18:50:17 -08001332 case HAL_PIXEL_FORMAT_RGBA_1010102:
Mathias Agopiandd533712013-07-26 15:31:39 -07001333 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001334 }
1335 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001336 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001337}
1338
Mathias Agopian13127d82013-03-05 17:47:11 -08001339// ----------------------------------------------------------------------------
1340// local state
1341// ----------------------------------------------------------------------------
1342
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001343static void boundPoint(vec2* point, const Rect& crop) {
1344 if (point->x < crop.left) {
1345 point->x = crop.left;
1346 }
1347 if (point->x > crop.right) {
1348 point->x = crop.right;
1349 }
1350 if (point->y < crop.top) {
1351 point->y = crop.top;
1352 }
1353 if (point->y > crop.bottom) {
1354 point->y = crop.bottom;
1355 }
1356}
1357
Dan Stozac7014012014-02-14 15:03:43 -08001358void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1359 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001360{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001361 const Layer::State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001362 const Transform hwTransform(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001363 const uint32_t hw_h = hw->getHeight();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001364 Rect win = computeBounds();
Mathias Agopian3f844832013-08-07 21:24:32 -07001365
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001366 vec2 lt = vec2(win.left, win.top);
1367 vec2 lb = vec2(win.left, win.bottom);
1368 vec2 rb = vec2(win.right, win.bottom);
1369 vec2 rt = vec2(win.right, win.top);
1370
Robert Carr1f0a16a2016-10-24 16:27:39 -07001371 Transform layerTransform = getTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001372 if (!useIdentityTransform) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001373 lt = layerTransform.transform(lt);
1374 lb = layerTransform.transform(lb);
1375 rb = layerTransform.transform(rb);
1376 rt = layerTransform.transform(rt);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001377 }
1378
Robert Carrb5d3d262016-03-25 15:08:13 -07001379 if (!s.finalCrop.isEmpty()) {
1380 boundPoint(&lt, s.finalCrop);
1381 boundPoint(&lb, s.finalCrop);
1382 boundPoint(&rb, s.finalCrop);
1383 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001384 }
1385
Mathias Agopianff2ed702013-09-01 21:36:12 -07001386 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001387 position[0] = hwTransform.transform(lt);
1388 position[1] = hwTransform.transform(lb);
1389 position[2] = hwTransform.transform(rb);
1390 position[3] = hwTransform.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001391 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001392 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001393 }
1394}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001395
Andy McFadden4125a4f2014-01-29 17:17:11 -08001396bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001397{
neo.hee6fd41d2017-02-17 14:35:33 +08001398 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
Mathias Agopiana67932f2011-04-20 14:20:59 -07001399 // layer's opaque flag.
neo.hee6fd41d2017-02-17 14:35:33 +08001400 if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001401 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001402 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001403
1404 // if the layer has the opaque flag, then we're always opaque,
1405 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001406 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001407}
1408
Dan Stoza23116082015-06-18 14:58:39 -07001409bool Layer::isSecure() const
1410{
1411 const Layer::State& s(mDrawingState);
1412 return (s.flags & layer_state_t::eLayerSecure);
1413}
1414
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001415bool Layer::isProtected() const
1416{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001417 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001418 return (activeBuffer != 0) &&
1419 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1420}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001421
Mathias Agopian13127d82013-03-05 17:47:11 -08001422bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001423 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001424}
1425
1426bool Layer::isCropped() const {
1427 return !mCurrentCrop.isEmpty();
1428}
1429
1430bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1431 return mNeedsFiltering || hw->needsFiltering();
1432}
1433
1434void Layer::setVisibleRegion(const Region& visibleRegion) {
1435 // always called from main thread
1436 this->visibleRegion = visibleRegion;
1437}
1438
1439void Layer::setCoveredRegion(const Region& coveredRegion) {
1440 // always called from main thread
1441 this->coveredRegion = coveredRegion;
1442}
1443
1444void Layer::setVisibleNonTransparentRegion(const Region&
1445 setVisibleNonTransparentRegion) {
1446 // always called from main thread
1447 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1448}
1449
1450// ----------------------------------------------------------------------------
1451// transaction
1452// ----------------------------------------------------------------------------
1453
Dan Stoza7dde5992015-05-22 09:51:44 -07001454void Layer::pushPendingState() {
1455 if (!mCurrentState.modified) {
1456 return;
1457 }
1458
Dan Stoza7dde5992015-05-22 09:51:44 -07001459 // If this transaction is waiting on the receipt of a frame, generate a sync
1460 // point and send it to the remote layer.
Robert Carr0d480722017-01-10 16:42:54 -08001461 if (mCurrentState.barrierLayer != nullptr) {
1462 sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1463 if (barrierLayer == nullptr) {
1464 ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
Dan Stoza7dde5992015-05-22 09:51:44 -07001465 // If we can't promote the layer we are intended to wait on,
1466 // then it is expired or otherwise invalid. Allow this transaction
1467 // to be applied as per normal (no synchronization).
Robert Carr0d480722017-01-10 16:42:54 -08001468 mCurrentState.barrierLayer = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001469 } else {
1470 auto syncPoint = std::make_shared<SyncPoint>(
1471 mCurrentState.frameNumber);
Robert Carr0d480722017-01-10 16:42:54 -08001472 if (barrierLayer->addSyncPoint(syncPoint)) {
Dan Stozacac35382016-01-27 12:21:06 -08001473 mRemoteSyncPoints.push_back(std::move(syncPoint));
1474 } else {
1475 // We already missed the frame we're supposed to synchronize
1476 // on, so go ahead and apply the state update
Robert Carr0d480722017-01-10 16:42:54 -08001477 mCurrentState.barrierLayer = nullptr;
Dan Stozacac35382016-01-27 12:21:06 -08001478 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001479 }
1480
Dan Stoza7dde5992015-05-22 09:51:44 -07001481 // Wake us up to check if the frame has been received
1482 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001483 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001484 }
1485 mPendingStates.push_back(mCurrentState);
Dan Stozaf7ba41a2017-05-10 15:11:11 -07001486 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
Dan Stoza7dde5992015-05-22 09:51:44 -07001487}
1488
Pablo Ceballos05289c22016-04-14 15:49:55 -07001489void Layer::popPendingState(State* stateToCommit) {
1490 auto oldFlags = stateToCommit->flags;
1491 *stateToCommit = mPendingStates[0];
1492 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1493 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001494
1495 mPendingStates.removeAt(0);
Dan Stozaf7ba41a2017-05-10 15:11:11 -07001496 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
Dan Stoza7dde5992015-05-22 09:51:44 -07001497}
1498
Pablo Ceballos05289c22016-04-14 15:49:55 -07001499bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001500 bool stateUpdateAvailable = false;
1501 while (!mPendingStates.empty()) {
Robert Carr0d480722017-01-10 16:42:54 -08001502 if (mPendingStates[0].barrierLayer != nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001503 if (mRemoteSyncPoints.empty()) {
1504 // If we don't have a sync point for this, apply it anyway. It
1505 // will be visually wrong, but it should keep us from getting
1506 // into too much trouble.
1507 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001508 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001509 stateUpdateAvailable = true;
1510 continue;
1511 }
1512
Dan Stozacac35382016-01-27 12:21:06 -08001513 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1514 mPendingStates[0].frameNumber) {
1515 ALOGE("[%s] Unexpected sync point frame number found",
1516 mName.string());
1517
1518 // Signal our end of the sync point and then dispose of it
1519 mRemoteSyncPoints.front()->setTransactionApplied();
1520 mRemoteSyncPoints.pop_front();
1521 continue;
1522 }
1523
Dan Stoza7dde5992015-05-22 09:51:44 -07001524 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1525 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001526 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001527 stateUpdateAvailable = true;
1528
1529 // Signal our end of the sync point and then dispose of it
1530 mRemoteSyncPoints.front()->setTransactionApplied();
1531 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001532 } else {
1533 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001534 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001535 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001536 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001537 stateUpdateAvailable = true;
1538 }
1539 }
1540
1541 // If we still have pending updates, wake SurfaceFlinger back up and point
1542 // it at this layer so we can process them
1543 if (!mPendingStates.empty()) {
1544 setTransactionFlags(eTransactionNeeded);
1545 mFlinger->setTransactionFlags(eTraversalNeeded);
1546 }
1547
1548 mCurrentState.modified = false;
1549 return stateUpdateAvailable;
1550}
1551
1552void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001553 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001554 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001555 Mutex::Autolock lock(mLocalSyncPointMutex);
1556 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001557 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001558 point->setFrameAvailable();
1559 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001560 }
1561}
1562
Mathias Agopian13127d82013-03-05 17:47:11 -08001563uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001564 ATRACE_CALL();
1565
Dan Stoza7dde5992015-05-22 09:51:44 -07001566 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001567 Layer::State c = getCurrentState();
1568 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001569 return 0;
1570 }
1571
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001572 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001573
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001574 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1575 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001576
1577 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001578 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001579 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001580 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001581 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001582 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001583 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001584 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001585 this, getName().string(), mCurrentTransform,
1586 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001587 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001588 c.crop.left,
1589 c.crop.top,
1590 c.crop.right,
1591 c.crop.bottom,
1592 c.crop.getWidth(),
1593 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001594 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001595 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001596 s.crop.left,
1597 s.crop.top,
1598 s.crop.right,
1599 s.crop.bottom,
1600 s.crop.getWidth(),
1601 s.crop.getHeight(),
1602 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001603
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001604 // record the new size, form this point on, when the client request
1605 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001606 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001607 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001608 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001609
Robert Carr82364e32016-05-15 11:27:47 -07001610 const bool resizePending = (c.requested.w != c.active.w) ||
1611 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001612 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001613 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001614 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001615 // if we have a pending resize, unless we are in fixed-size mode.
1616 // the drawing state will be updated only once we receive a buffer
1617 // with the correct size.
1618 //
1619 // in particular, we want to make sure the clip (which is part
1620 // of the geometry state) is latched together with the size but is
1621 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001622 //
1623 // If a sideband stream is attached, however, we want to skip this
1624 // optimization so that transactions aren't missed when a buffer
1625 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001626
1627 flags |= eDontUpdateGeometryState;
1628 }
1629 }
1630
Mathias Agopian13127d82013-03-05 17:47:11 -08001631 // always set active to requested, unless we're asked not to
1632 // this is used by Layer, which special cases resizes.
1633 if (flags & eDontUpdateGeometryState) {
1634 } else {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001635 Layer::State& editCurrentState(getCurrentState());
Robert Carr82364e32016-05-15 11:27:47 -07001636 if (mFreezePositionUpdates) {
1637 float tx = c.active.transform.tx();
1638 float ty = c.active.transform.ty();
1639 c.active = c.requested;
1640 c.active.transform.set(tx, ty);
1641 editCurrentState.active = c.active;
1642 } else {
1643 editCurrentState.active = editCurrentState.requested;
1644 c.active = c.requested;
1645 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001646 }
1647
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001648 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001649 // invalidate and recompute the visible regions if needed
1650 flags |= Layer::eVisibleRegion;
1651 }
1652
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001653 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001654 // invalidate and recompute the visible regions if needed
1655 flags |= eVisibleRegion;
1656 this->contentDirty = true;
1657
1658 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001659 const uint8_t type = c.active.transform.getType();
1660 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001661 (type >= Transform::SCALE));
1662 }
1663
Dan Stozac8145172016-04-28 16:29:06 -07001664 // If the layer is hidden, signal and clear out all local sync points so
1665 // that transactions for layers depending on this layer's frames becoming
1666 // visible are not blocked
1667 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001668 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001669 }
1670
Mathias Agopian13127d82013-03-05 17:47:11 -08001671 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001672 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001673 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001674}
1675
Pablo Ceballos05289c22016-04-14 15:49:55 -07001676void Layer::commitTransaction(const State& stateToCommit) {
1677 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001678}
1679
Mathias Agopian13127d82013-03-05 17:47:11 -08001680uint32_t Layer::getTransactionFlags(uint32_t flags) {
1681 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1682}
1683
1684uint32_t Layer::setTransactionFlags(uint32_t flags) {
1685 return android_atomic_or(flags, &mTransactionFlags);
1686}
1687
Robert Carr82364e32016-05-15 11:27:47 -07001688bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001689 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001690 return false;
1691 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001692
1693 // We update the requested and active position simultaneously because
1694 // we want to apply the position portion of the transform matrix immediately,
1695 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001696 mCurrentState.requested.transform.set(x, y);
Robert Carr82364e32016-05-15 11:27:47 -07001697 if (immediate && !mFreezePositionUpdates) {
1698 mCurrentState.active.transform.set(x, y);
1699 }
1700 mFreezePositionUpdates = mFreezePositionUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001701
Dan Stoza7dde5992015-05-22 09:51:44 -07001702 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001703 setTransactionFlags(eTransactionNeeded);
1704 return true;
1705}
Robert Carr82364e32016-05-15 11:27:47 -07001706
Robert Carr1f0a16a2016-10-24 16:27:39 -07001707bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1708 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1709 if (idx < 0) {
1710 return false;
1711 }
1712 if (childLayer->setLayer(z)) {
1713 mCurrentChildren.removeAt(idx);
1714 mCurrentChildren.add(childLayer);
1715 }
1716 return true;
1717}
1718
Robert Carrae060832016-11-28 10:51:00 -08001719bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001720 if (mCurrentState.z == z)
1721 return false;
1722 mCurrentState.sequence++;
1723 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001724 mCurrentState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001725
1726 // Discard all relative layering.
1727 if (mCurrentState.zOrderRelativeOf != nullptr) {
1728 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1729 if (strongRelative != nullptr) {
1730 strongRelative->removeZOrderRelative(this);
1731 }
1732 mCurrentState.zOrderRelativeOf = nullptr;
1733 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001734 setTransactionFlags(eTransactionNeeded);
1735 return true;
1736}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001737
Robert Carrdb66e622017-04-10 16:55:57 -07001738void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1739 mCurrentState.zOrderRelatives.remove(relative);
1740 mCurrentState.sequence++;
1741 mCurrentState.modified = true;
1742 setTransactionFlags(eTransactionNeeded);
1743}
1744
1745void Layer::addZOrderRelative(const wp<Layer>& relative) {
1746 mCurrentState.zOrderRelatives.add(relative);
1747 mCurrentState.modified = true;
1748 mCurrentState.sequence++;
1749 setTransactionFlags(eTransactionNeeded);
1750}
1751
1752bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1753 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1754 if (handle == nullptr) {
1755 return false;
1756 }
1757 sp<Layer> relative = handle->owner.promote();
1758 if (relative == nullptr) {
1759 return false;
1760 }
1761
1762 mCurrentState.sequence++;
1763 mCurrentState.modified = true;
1764 mCurrentState.z = z;
1765
1766 mCurrentState.zOrderRelativeOf = relative;
1767 relative->addZOrderRelative(this);
1768
1769 setTransactionFlags(eTransactionNeeded);
1770
1771 return true;
1772}
1773
Mathias Agopian13127d82013-03-05 17:47:11 -08001774bool Layer::setSize(uint32_t w, uint32_t h) {
1775 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1776 return false;
1777 mCurrentState.requested.w = w;
1778 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001779 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001780 setTransactionFlags(eTransactionNeeded);
1781 return true;
1782}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001783#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001784bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001785#else
1786bool Layer::setAlpha(uint8_t alpha) {
1787#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001788 if (mCurrentState.alpha == alpha)
1789 return false;
1790 mCurrentState.sequence++;
1791 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001792 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001793 setTransactionFlags(eTransactionNeeded);
1794 return true;
1795}
1796bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1797 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001798 mCurrentState.requested.transform.set(
Robert Carrcb6e1e32017-02-21 19:48:26 -08001799 matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001800 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001801 setTransactionFlags(eTransactionNeeded);
1802 return true;
1803}
1804bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001805 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001806 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001807 setTransactionFlags(eTransactionNeeded);
1808 return true;
1809}
1810bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1811 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1812 if (mCurrentState.flags == newFlags)
1813 return false;
1814 mCurrentState.sequence++;
1815 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001816 mCurrentState.mask = mask;
1817 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001818 setTransactionFlags(eTransactionNeeded);
1819 return true;
1820}
Robert Carr99e27f02016-06-16 15:18:02 -07001821
1822bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001823 if (mCurrentState.crop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001824 return false;
1825 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001826 mCurrentState.requestedCrop = crop;
1827 if (immediate) {
1828 mCurrentState.crop = crop;
1829 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001830 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001831 setTransactionFlags(eTransactionNeeded);
1832 return true;
1833}
Robert Carr8d5227b2017-03-16 15:41:03 -07001834
1835bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001836 if (mCurrentState.finalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001837 return false;
1838 mCurrentState.sequence++;
Robert Carr8d5227b2017-03-16 15:41:03 -07001839 mCurrentState.requestedFinalCrop = crop;
1840 if (immediate) {
1841 mCurrentState.finalCrop = crop;
1842 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001843 mCurrentState.modified = true;
1844 setTransactionFlags(eTransactionNeeded);
1845 return true;
1846}
Mathias Agopian13127d82013-03-05 17:47:11 -08001847
Robert Carrc3574f72016-03-24 12:19:32 -07001848bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1849 if (scalingMode == mOverrideScalingMode)
1850 return false;
1851 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001852 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001853 return true;
1854}
1855
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001856void Layer::setInfo(uint32_t type, uint32_t appId) {
1857 mCurrentState.appId = appId;
1858 mCurrentState.type = type;
1859 mCurrentState.modified = true;
1860 setTransactionFlags(eTransactionNeeded);
1861}
1862
Robert Carrc3574f72016-03-24 12:19:32 -07001863uint32_t Layer::getEffectiveScalingMode() const {
1864 if (mOverrideScalingMode >= 0) {
1865 return mOverrideScalingMode;
1866 }
1867 return mCurrentScalingMode;
1868}
1869
Mathias Agopian13127d82013-03-05 17:47:11 -08001870bool Layer::setLayerStack(uint32_t layerStack) {
1871 if (mCurrentState.layerStack == layerStack)
1872 return false;
1873 mCurrentState.sequence++;
1874 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001875 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001876 setTransactionFlags(eTransactionNeeded);
1877 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001878}
1879
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07001880bool Layer::setDataSpace(android_dataspace dataSpace) {
1881 if (mCurrentState.dataSpace == dataSpace)
1882 return false;
1883 mCurrentState.sequence++;
1884 mCurrentState.dataSpace = dataSpace;
1885 mCurrentState.modified = true;
1886 setTransactionFlags(eTransactionNeeded);
1887 return true;
1888}
1889
Courtney Goeltzenleuchter532b2632017-05-05 16:34:38 -06001890android_dataspace Layer::getDataSpace() const {
1891 return mCurrentState.dataSpace;
1892}
1893
Robert Carr1f0a16a2016-10-24 16:27:39 -07001894uint32_t Layer::getLayerStack() const {
1895 auto p = getParent();
1896 if (p == nullptr) {
1897 return getDrawingState().layerStack;
1898 }
1899 return p->getLayerStack();
1900}
1901
Robert Carr0d480722017-01-10 16:42:54 -08001902void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
Dan Stoza7dde5992015-05-22 09:51:44 -07001903 uint64_t frameNumber) {
Robert Carr0d480722017-01-10 16:42:54 -08001904 mCurrentState.barrierLayer = barrierLayer;
Dan Stoza7dde5992015-05-22 09:51:44 -07001905 mCurrentState.frameNumber = frameNumber;
1906 // We don't set eTransactionNeeded, because just receiving a deferral
1907 // request without any other state updates shouldn't actually induce a delay
1908 mCurrentState.modified = true;
1909 pushPendingState();
Robert Carr0d480722017-01-10 16:42:54 -08001910 mCurrentState.barrierLayer = nullptr;
Dan Stoza792e5292016-02-11 11:43:58 -08001911 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07001912 mCurrentState.modified = false;
Robert Carr0d480722017-01-10 16:42:54 -08001913 ALOGE("Deferred transaction");
1914}
1915
1916void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
1917 uint64_t frameNumber) {
1918 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
1919 deferTransactionUntil(handle->owner.promote(), frameNumber);
Dan Stoza7dde5992015-05-22 09:51:44 -07001920}
1921
Dan Stozaee44edd2015-03-23 15:50:23 -07001922void Layer::useSurfaceDamage() {
1923 if (mFlinger->mForceFullDamage) {
1924 surfaceDamageRegion = Region::INVALID_REGION;
1925 } else {
1926 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1927 }
1928}
1929
1930void Layer::useEmptyDamage() {
1931 surfaceDamageRegion.clear();
1932}
1933
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001934// ----------------------------------------------------------------------------
1935// pageflip handling...
1936// ----------------------------------------------------------------------------
1937
Dan Stoza6b9454d2014-11-07 16:00:59 -08001938bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001939 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07001940 return true;
1941 }
1942
Dan Stoza6b9454d2014-11-07 16:00:59 -08001943 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001944 if (mQueueItems.empty()) {
1945 return false;
1946 }
1947 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001948 nsecs_t expectedPresent =
1949 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001950
1951 // Ignore timestamps more than a second in the future
1952 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1953 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1954 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1955 expectedPresent);
1956
1957 bool isDue = timestamp < expectedPresent;
1958 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001959}
1960
Brian Andersond6927fb2016-07-23 23:37:30 -07001961bool Layer::onPreComposition(nsecs_t refreshStartTime) {
1962 if (mBufferLatched) {
1963 Mutex::Autolock lock(mFrameEventHistoryMutex);
1964 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
1965 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08001966 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001967 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001968}
1969
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001970bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
Brian Anderson3d4039d2016-09-23 16:31:30 -07001971 const std::shared_ptr<FenceTime>& presentFence,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001972 const CompositorTiming& compositorTiming) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001973 mAcquireTimeline.updateSignalTimes();
1974 mReleaseTimeline.updateSignalTimes();
1975
Brian Andersond6927fb2016-07-23 23:37:30 -07001976 // mFrameLatencyNeeded is true when a new frame was latched for the
1977 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08001978 if (!mFrameLatencyNeeded)
1979 return false;
1980
Fabien Sanglard28e98082016-12-05 10:19:46 -08001981 // Update mFrameEventHistory.
1982 {
1983 Mutex::Autolock lock(mFrameEventHistoryMutex);
1984 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001985 glDoneFence, presentFence, compositorTiming);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001986 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08001987
1988 // Update mFrameTracker.
1989 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1990 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1991
Brian Anderson3d4039d2016-09-23 16:31:30 -07001992 std::shared_ptr<FenceTime> frameReadyFence =
1993 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08001994 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001995 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001996 } else {
1997 // There was no fence for this frame, so assume that it was ready
1998 // to be presented at the desired present time.
1999 mFrameTracker.setFrameReadyTime(desiredPresentTime);
2000 }
2001
Brian Anderson3d4039d2016-09-23 16:31:30 -07002002 if (presentFence->isValid()) {
2003 mFrameTracker.setActualPresentFence(
2004 std::shared_ptr<FenceTime>(presentFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002005 } else {
2006 // The HWC doesn't support present fences, so use the refresh
2007 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002008 mFrameTracker.setActualPresentTime(
2009 mFlinger->getHwComposer().getRefreshTimestamp(
2010 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002011 }
2012
2013 mFrameTracker.advanceFrame();
2014 mFrameLatencyNeeded = false;
2015 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002016}
2017
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002018#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07002019void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Brian Anderson5ea5e592016-12-01 16:54:33 -08002020 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2021 return;
2022 }
2023
Brian Anderson3d4039d2016-09-23 16:31:30 -07002024 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002025 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002026 mReleaseTimeline.push(releaseFenceTime);
2027
2028 Mutex::Autolock lock(mFrameEventHistoryMutex);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002029 if (mPreviousFrameNumber != 0) {
2030 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2031 dequeueReadyTime, std::move(releaseFenceTime));
2032 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002033}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002034#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002035
Robert Carr1f0a16a2016-10-24 16:27:39 -07002036bool Layer::isHiddenByPolicy() const {
2037 const Layer::State& s(mDrawingState);
2038 const auto& parent = getParent();
2039 if (parent != nullptr && parent->isHiddenByPolicy()) {
2040 return true;
2041 }
2042 return s.flags & layer_state_t::eLayerHidden;
2043}
2044
Mathias Agopianda27af92012-09-13 18:17:13 -07002045bool Layer::isVisible() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002046#ifdef USE_HWC2
Robert Carr6452f122017-03-21 10:41:29 -07002047 return !(isHiddenByPolicy()) && getAlpha() > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08002048 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002049#else
Robert Carr6452f122017-03-21 10:41:29 -07002050 return !(isHiddenByPolicy()) && getAlpha()
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002051 && (mActiveBuffer != NULL || mSidebandStream != NULL);
2052#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07002053}
2054
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002055bool Layer::allTransactionsSignaled() {
2056 auto headFrameNumber = getHeadFrameNumber();
2057 bool matchingFramesFound = false;
2058 bool allTransactionsApplied = true;
2059 Mutex::Autolock lock(mLocalSyncPointMutex);
2060
2061 for (auto& point : mLocalSyncPoints) {
2062 if (point->getFrameNumber() > headFrameNumber) {
2063 break;
2064 }
2065 matchingFramesFound = true;
2066
2067 if (!point->frameIsAvailable()) {
2068 // We haven't notified the remote layer that the frame for
2069 // this point is available yet. Notify it now, and then
2070 // abort this attempt to latch.
2071 point->setFrameAvailable();
2072 allTransactionsApplied = false;
2073 break;
2074 }
2075
2076 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2077 }
2078 return !matchingFramesFound || allTransactionsApplied;
2079}
2080
Brian Andersond6927fb2016-07-23 23:37:30 -07002081Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002082{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08002083 ATRACE_CALL();
2084
Jesse Hall399184a2014-03-03 15:42:54 -08002085 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2086 // mSidebandStreamChanged was true
2087 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07002088 if (mSidebandStream != NULL) {
2089 setTransactionFlags(eTransactionNeeded);
2090 mFlinger->setTransactionFlags(eTraversalNeeded);
2091 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07002092 recomputeVisibleRegions = true;
2093
2094 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07002095 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08002096 }
2097
Mathias Agopian4fec8732012-06-29 14:12:52 -07002098 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07002099 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2100 return outDirtyRegion;
2101 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002102
Fabien Sanglard223eb912016-10-13 10:15:06 -07002103 // if we've already called updateTexImage() without going through
2104 // a composition step, we have to skip this layer at this point
2105 // because we cannot call updateTeximage() without a corresponding
2106 // compositionComplete() call.
2107 // we'll trigger an update in onPreComposition().
2108 if (mRefreshPending) {
2109 return outDirtyRegion;
2110 }
2111
2112 // If the head buffer's acquire fence hasn't signaled yet, return and
2113 // try again later
2114 if (!headFenceHasSignaled()) {
2115 mFlinger->signalLayerUpdate();
2116 return outDirtyRegion;
2117 }
2118
2119 // Capture the old state of the layer for comparisons later
2120 const State& s(getDrawingState());
2121 const bool oldOpacity = isOpaque(s);
2122 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2123
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002124 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002125 mFlinger->signalLayerUpdate();
2126 return outDirtyRegion;
2127 }
2128
2129 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2130 // of the buffer queue isn't modified when the buffer queue is returning
2131 // BufferItem's that weren't actually queued. This can happen in shared
2132 // buffer mode.
2133 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002134 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2135 getProducerStickyTransform() != 0, mName.string(),
2136 mOverrideScalingMode, mFreezePositionUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002137 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2138 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2139 mLastFrameNumberReceived);
2140 if (updateResult == BufferQueue::PRESENT_LATER) {
2141 // Producer doesn't want buffer to be displayed yet. Signal a
2142 // layer update so we check again at the next opportunity.
2143 mFlinger->signalLayerUpdate();
2144 return outDirtyRegion;
2145 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2146 // If the buffer has been rejected, remove it from the shadow queue
2147 // and return early
2148 if (queuedBuffer) {
2149 Mutex::Autolock lock(mQueueItemLock);
2150 mQueueItems.removeAt(0);
2151 android_atomic_dec(&mQueuedFrames);
2152 }
2153 return outDirtyRegion;
2154 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2155 // This can occur if something goes wrong when trying to create the
2156 // EGLImage for this buffer. If this happens, the buffer has already
2157 // been released, so we need to clean up the queue and bug out
2158 // early.
2159 if (queuedBuffer) {
2160 Mutex::Autolock lock(mQueueItemLock);
2161 mQueueItems.clear();
2162 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002163 }
2164
Fabien Sanglard223eb912016-10-13 10:15:06 -07002165 // Once we have hit this state, the shadow queue may no longer
2166 // correctly reflect the incoming BufferQueue's contents, so even if
2167 // updateTexImage starts working, the only safe course of action is
2168 // to continue to ignore updates.
2169 mUpdateTexImageFailed = true;
2170
2171 return outDirtyRegion;
2172 }
2173
2174 if (queuedBuffer) {
2175 // Autolock scope
2176 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2177
2178 Mutex::Autolock lock(mQueueItemLock);
2179
2180 // Remove any stale buffers that have been dropped during
2181 // updateTexImage
2182 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2183 mQueueItems.removeAt(0);
2184 android_atomic_dec(&mQueuedFrames);
2185 }
2186
2187 mQueueItems.removeAt(0);
2188 }
2189
2190
2191 // Decrement the queued-frames count. Signal another event if we
2192 // have more frames pending.
2193 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2194 || mAutoRefresh) {
2195 mFlinger->signalLayerUpdate();
2196 }
2197
Fabien Sanglard223eb912016-10-13 10:15:06 -07002198 // update the active buffer
Chia-I Wu06d63de2017-01-04 14:58:51 +08002199 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2200 &mActiveBufferSlot);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002201 if (mActiveBuffer == NULL) {
2202 // this can only happen if the very first buffer was rejected.
2203 return outDirtyRegion;
2204 }
2205
Brian Andersond6927fb2016-07-23 23:37:30 -07002206 mBufferLatched = true;
2207 mPreviousFrameNumber = mCurrentFrameNumber;
2208 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2209
2210 {
2211 Mutex::Autolock lock(mFrameEventHistoryMutex);
2212 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2213#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002214 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002215 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002216 mReleaseTimeline.push(releaseFenceTime);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002217 if (mPreviousFrameNumber != 0) {
2218 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2219 latchTime, std::move(releaseFenceTime));
2220 }
Brian Andersond6927fb2016-07-23 23:37:30 -07002221#endif
2222 }
2223
Fabien Sanglard223eb912016-10-13 10:15:06 -07002224 mRefreshPending = true;
2225 mFrameLatencyNeeded = true;
2226 if (oldActiveBuffer == NULL) {
2227 // the first time we receive a buffer, we need to trigger a
2228 // geometry invalidation.
2229 recomputeVisibleRegions = true;
2230 }
2231
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002232 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2233
Fabien Sanglard223eb912016-10-13 10:15:06 -07002234 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2235 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2236 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2237 if ((crop != mCurrentCrop) ||
2238 (transform != mCurrentTransform) ||
2239 (scalingMode != mCurrentScalingMode))
2240 {
2241 mCurrentCrop = crop;
2242 mCurrentTransform = transform;
2243 mCurrentScalingMode = scalingMode;
2244 recomputeVisibleRegions = true;
2245 }
2246
2247 if (oldActiveBuffer != NULL) {
2248 uint32_t bufWidth = mActiveBuffer->getWidth();
2249 uint32_t bufHeight = mActiveBuffer->getHeight();
2250 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2251 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002252 recomputeVisibleRegions = true;
2253 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002254 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002255
Fabien Sanglard223eb912016-10-13 10:15:06 -07002256 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2257 if (oldOpacity != isOpaque(s)) {
2258 recomputeVisibleRegions = true;
2259 }
Dan Stozacac35382016-01-27 12:21:06 -08002260
Fabien Sanglard223eb912016-10-13 10:15:06 -07002261 // Remove any sync points corresponding to the buffer which was just
2262 // latched
2263 {
2264 Mutex::Autolock lock(mLocalSyncPointMutex);
2265 auto point = mLocalSyncPoints.begin();
2266 while (point != mLocalSyncPoints.end()) {
2267 if (!(*point)->frameIsAvailable() ||
2268 !(*point)->transactionIsApplied()) {
2269 // This sync point must have been added since we started
2270 // latching. Don't drop it yet.
2271 ++point;
2272 continue;
2273 }
2274
2275 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2276 point = mLocalSyncPoints.erase(point);
2277 } else {
2278 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002279 }
2280 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002281 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002282
2283 // FIXME: postedRegion should be dirty & bounds
2284 Region dirtyRegion(Rect(s.active.w, s.active.h));
2285
2286 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002287 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002288
Mathias Agopian4fec8732012-06-29 14:12:52 -07002289 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002290}
2291
Mathias Agopiana67932f2011-04-20 14:20:59 -07002292uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002293{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002294 // TODO: should we do something special if mSecure is set?
2295 if (mProtectedByApp) {
2296 // need a hardware-protected path to external video sink
2297 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002298 }
Riley Andrews03414a12014-07-01 14:22:59 -07002299 if (mPotentialCursor) {
2300 usage |= GraphicBuffer::USAGE_CURSOR;
2301 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002302 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002303 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002304}
2305
Mathias Agopian84300952012-11-21 16:02:13 -08002306void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002307 uint32_t orientation = 0;
2308 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002309 // The transform hint is used to improve performance, but we can
2310 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002311 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002312 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002313 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002314 if (orientation & Transform::ROT_INVALID) {
2315 orientation = 0;
2316 }
2317 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002318 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002319}
2320
Mathias Agopian13127d82013-03-05 17:47:11 -08002321// ----------------------------------------------------------------------------
2322// debugging
2323// ----------------------------------------------------------------------------
2324
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002325void Layer::dump(String8& result, Colorizer& colorizer) const
Mathias Agopian13127d82013-03-05 17:47:11 -08002326{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002327 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08002328
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002329 colorizer.colorize(result, Colorizer::GREEN);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002330 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002331 "+ %s %p (%s)\n",
2332 getTypeId(), this, getName().string());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002333 colorizer.reset(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002334
Mathias Agopian2ca79392013-04-02 18:30:32 -07002335 s.activeTransparentRegion.dump(result, "transparentRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002336 visibleRegion.dump(result, "visibleRegion");
Dan Stozaee44edd2015-03-23 15:50:23 -07002337 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002338 sp<Client> client(mClientRef.promote());
Courtney Goeltzenleuchter36c44dc2017-04-14 09:33:16 -06002339 PixelFormat pf = PIXEL_FORMAT_UNKNOWN;
2340 const sp<GraphicBuffer>& buffer(getActiveBuffer());
2341 if (buffer != NULL) {
2342 pf = buffer->getPixelFormat();
2343 }
Mathias Agopian13127d82013-03-05 17:47:11 -08002344
Mathias Agopian74d211a2013-04-22 16:55:35 +02002345 result.appendFormat( " "
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002346 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2347 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
Mathias Agopian13127d82013-03-05 17:47:11 -08002348 "isOpaque=%1d, invalidate=%1d, "
Courtney Goeltzenleuchter36c44dc2017-04-14 09:33:16 -06002349 "dataspace=%s, pixelformat=%s "
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002350#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08002351 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002352#else
2353 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2354#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08002355 " client=%p\n",
Robert Carr1f0a16a2016-10-24 16:27:39 -07002356 getLayerStack(), s.z,
2357 s.active.transform.tx(), s.active.transform.ty(),
2358 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07002359 s.crop.left, s.crop.top,
2360 s.crop.right, s.crop.bottom,
2361 s.finalCrop.left, s.finalCrop.top,
2362 s.finalCrop.right, s.finalCrop.bottom,
Andy McFadden4125a4f2014-01-29 17:17:11 -08002363 isOpaque(s), contentDirty,
Courtney Goeltzenleuchter36c44dc2017-04-14 09:33:16 -06002364 dataspaceDetails(getDataSpace()).c_str(), decodePixelFormat(pf).c_str(),
Mathias Agopian13127d82013-03-05 17:47:11 -08002365 s.alpha, s.flags,
Robert Carr3dcabfa2016-03-01 18:36:58 -08002366 s.active.transform[0][0], s.active.transform[0][1],
2367 s.active.transform[1][0], s.active.transform[1][1],
Mathias Agopian13127d82013-03-05 17:47:11 -08002368 client.get());
Mathias Agopian13127d82013-03-05 17:47:11 -08002369
2370 sp<const GraphicBuffer> buf0(mActiveBuffer);
2371 uint32_t w0=0, h0=0, s0=0, f0=0;
2372 if (buf0 != 0) {
2373 w0 = buf0->getWidth();
2374 h0 = buf0->getHeight();
2375 s0 = buf0->getStride();
2376 f0 = buf0->format;
2377 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02002378 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002379 " "
2380 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2381 " queued-frames=%d, mRefreshPending=%d\n",
2382 mFormat, w0, h0, s0,f0,
2383 mQueuedFrames, mRefreshPending);
2384
Mathias Agopian13127d82013-03-05 17:47:11 -08002385 if (mSurfaceFlingerConsumer != 0) {
Colin Cross3d1d2802016-09-26 18:10:16 -07002386 mSurfaceFlingerConsumer->dumpState(result, " ");
Mathias Agopian13127d82013-03-05 17:47:11 -08002387 }
2388}
2389
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002390#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002391void Layer::miniDumpHeader(String8& result) {
2392 result.append("----------------------------------------");
2393 result.append("---------------------------------------\n");
2394 result.append(" Layer name\n");
2395 result.append(" Z | ");
2396 result.append(" Comp Type | ");
2397 result.append(" Disp Frame (LTRB) | ");
2398 result.append(" Source Crop (LTRB)\n");
2399 result.append("----------------------------------------");
2400 result.append("---------------------------------------\n");
2401}
2402
2403void Layer::miniDump(String8& result, int32_t hwcId) const {
2404 if (mHwcLayers.count(hwcId) == 0) {
2405 return;
2406 }
2407
2408 String8 name;
2409 if (mName.length() > 77) {
2410 std::string shortened;
2411 shortened.append(mName.string(), 36);
2412 shortened.append("[...]");
2413 shortened.append(mName.string() + (mName.length() - 36), 36);
2414 name = shortened.c_str();
2415 } else {
2416 name = mName;
2417 }
2418
2419 result.appendFormat(" %s\n", name.string());
2420
2421 const Layer::State& layerState(getDrawingState());
2422 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2423 result.appendFormat(" %10u | ", layerState.z);
2424 result.appendFormat("%10s | ",
2425 to_string(getCompositionType(hwcId)).c_str());
2426 const Rect& frame = hwcInfo.displayFrame;
2427 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2428 frame.right, frame.bottom);
Dan Stoza5a423ea2017-02-16 14:10:39 -08002429 const FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002430 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2431 crop.right, crop.bottom);
2432
2433 result.append("- - - - - - - - - - - - - - - - - - - - ");
2434 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2435}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002436#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002437
Svetoslavd85084b2014-03-20 10:28:31 -07002438void Layer::dumpFrameStats(String8& result) const {
2439 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002440}
2441
Svetoslavd85084b2014-03-20 10:28:31 -07002442void Layer::clearFrameStats() {
2443 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002444}
2445
Jamie Gennis6547ff42013-07-16 20:12:42 -07002446void Layer::logFrameStats() {
2447 mFrameTracker.logAndResetStats(mName);
2448}
2449
Svetoslavd85084b2014-03-20 10:28:31 -07002450void Layer::getFrameStats(FrameStats* outStats) const {
2451 mFrameTracker.getStats(outStats);
2452}
2453
Brian Andersond6927fb2016-07-23 23:37:30 -07002454void Layer::dumpFrameEvents(String8& result) {
2455 result.appendFormat("- Layer %s (%s, %p)\n",
2456 getName().string(), getTypeId(), this);
2457 Mutex::Autolock lock(mFrameEventHistoryMutex);
2458 mFrameEventHistory.checkFencesForCompletion();
2459 mFrameEventHistory.dump(result);
2460}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002461
Brian Anderson5ea5e592016-12-01 16:54:33 -08002462void Layer::onDisconnect() {
2463 Mutex::Autolock lock(mFrameEventHistoryMutex);
2464 mFrameEventHistory.onDisconnect();
2465}
2466
Brian Anderson3890c392016-07-25 12:48:08 -07002467void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2468 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002469 Mutex::Autolock lock(mFrameEventHistoryMutex);
2470 if (newTimestamps) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002471 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002472 mFrameEventHistory.addQueue(*newTimestamps);
2473 }
2474
Brian Anderson3890c392016-07-25 12:48:08 -07002475 if (outDelta) {
2476 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002477 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002478}
Dan Stozae77c7662016-05-13 11:37:28 -07002479
2480std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2481 bool forceFlush) {
2482 std::vector<OccupancyTracker::Segment> history;
2483 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2484 &history);
2485 if (result != NO_ERROR) {
2486 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2487 result);
2488 return {};
2489 }
2490 return history;
2491}
2492
Robert Carr367c5682016-06-20 11:55:28 -07002493bool Layer::getTransformToDisplayInverse() const {
2494 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2495}
2496
Robert Carr1f0a16a2016-10-24 16:27:39 -07002497void Layer::addChild(const sp<Layer>& layer) {
2498 mCurrentChildren.add(layer);
2499 layer->setParent(this);
2500}
2501
2502ssize_t Layer::removeChild(const sp<Layer>& layer) {
2503 layer->setParent(nullptr);
2504 return mCurrentChildren.remove(layer);
2505}
2506
Robert Carr1db73f62016-12-21 12:58:51 -08002507bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2508 sp<Handle> handle = nullptr;
2509 sp<Layer> newParent = nullptr;
2510 if (newParentHandle == nullptr) {
2511 return false;
2512 }
2513 handle = static_cast<Handle*>(newParentHandle.get());
2514 newParent = handle->owner.promote();
2515 if (newParent == nullptr) {
2516 ALOGE("Unable to promote Layer handle");
2517 return false;
2518 }
2519
2520 for (const sp<Layer>& child : mCurrentChildren) {
2521 newParent->addChild(child);
2522
2523 sp<Client> client(child->mClientRef.promote());
2524 if (client != nullptr) {
2525 client->setParentLayer(newParent);
2526 }
2527 }
2528 mCurrentChildren.clear();
2529
2530 return true;
2531}
2532
Robert Carr9524cb32017-02-13 11:32:32 -08002533bool Layer::detachChildren() {
Dan Stoza412903f2017-04-27 13:42:17 -07002534 traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
Robert Carr9524cb32017-02-13 11:32:32 -08002535 if (child == this) {
2536 return;
2537 }
2538
2539 sp<Client> client(child->mClientRef.promote());
2540 if (client != nullptr) {
2541 client->detachLayer(child);
2542 }
2543 });
2544
2545 return true;
2546}
2547
Robert Carr1f0a16a2016-10-24 16:27:39 -07002548void Layer::setParent(const sp<Layer>& layer) {
2549 mParent = layer;
2550}
2551
2552void Layer::clearSyncPoints() {
2553 for (const auto& child : mCurrentChildren) {
2554 child->clearSyncPoints();
2555 }
2556
2557 Mutex::Autolock lock(mLocalSyncPointMutex);
2558 for (auto& point : mLocalSyncPoints) {
2559 point->setFrameAvailable();
2560 }
2561 mLocalSyncPoints.clear();
2562}
2563
2564int32_t Layer::getZ() const {
2565 return mDrawingState.z;
2566}
2567
Dan Stoza412903f2017-04-27 13:42:17 -07002568LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2569 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2570 "makeTraversalList received invalid stateSet");
2571 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2572 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2573 const State& state = useDrawing ? mDrawingState : mCurrentState;
2574
2575 if (state.zOrderRelatives.size() == 0) {
2576 return children;
Robert Carrdb66e622017-04-10 16:55:57 -07002577 }
2578 LayerVector traverse;
2579
Dan Stoza412903f2017-04-27 13:42:17 -07002580 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07002581 sp<Layer> strongRelative = weakRelative.promote();
2582 if (strongRelative != nullptr) {
2583 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07002584 }
2585 }
2586
Dan Stoza412903f2017-04-27 13:42:17 -07002587 for (const sp<Layer>& child : children) {
Robert Carrdb66e622017-04-10 16:55:57 -07002588 traverse.add(child);
2589 }
2590
2591 return traverse;
2592}
2593
Robert Carr1f0a16a2016-10-24 16:27:39 -07002594/**
Robert Carrdb66e622017-04-10 16:55:57 -07002595 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002596 */
Dan Stoza412903f2017-04-27 13:42:17 -07002597void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2598 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002599
Robert Carr1f0a16a2016-10-24 16:27:39 -07002600 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002601 for (; i < list.size(); i++) {
2602 const auto& relative = list[i];
2603 if (relative->getZ() >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002604 break;
Robert Carrdb66e622017-04-10 16:55:57 -07002605 }
Dan Stoza412903f2017-04-27 13:42:17 -07002606 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002607 }
Dan Stoza412903f2017-04-27 13:42:17 -07002608 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07002609 for (; i < list.size(); i++) {
2610 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002611 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002612 }
2613}
2614
2615/**
Robert Carrdb66e622017-04-10 16:55:57 -07002616 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002617 */
Dan Stoza412903f2017-04-27 13:42:17 -07002618void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2619 const LayerVector::Visitor& visitor) {
2620 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002621
Robert Carr1f0a16a2016-10-24 16:27:39 -07002622 int32_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002623 for (i = list.size()-1; i>=0; i--) {
2624 const auto& relative = list[i];
2625 if (relative->getZ() < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002626 break;
2627 }
Dan Stoza412903f2017-04-27 13:42:17 -07002628 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002629 }
Dan Stoza412903f2017-04-27 13:42:17 -07002630 visitor(this);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002631 for (; i>=0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002632 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002633 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002634 }
2635}
2636
2637Transform Layer::getTransform() const {
2638 Transform t;
2639 const auto& p = getParent();
2640 if (p != nullptr) {
2641 t = p->getTransform();
Robert Carr9b429f42017-04-17 14:56:57 -07002642
2643 // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2644 // it isFixedSize) then there may be additional scaling not accounted
2645 // for in the transform. We need to mirror this scaling in child surfaces
2646 // or we will break the contract where WM can treat child surfaces as
2647 // pixels in the parent surface.
2648 if (p->isFixedSize()) {
Robert Carr1725eee2017-04-26 18:32:15 -07002649 int bufferWidth;
2650 int bufferHeight;
2651 if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2652 bufferWidth = p->mActiveBuffer->getWidth();
2653 bufferHeight = p->mActiveBuffer->getHeight();
2654 } else {
2655 bufferHeight = p->mActiveBuffer->getWidth();
2656 bufferWidth = p->mActiveBuffer->getHeight();
2657 }
Robert Carr9b429f42017-04-17 14:56:57 -07002658 float sx = p->getDrawingState().active.w /
Robert Carr1725eee2017-04-26 18:32:15 -07002659 static_cast<float>(bufferWidth);
Robert Carr9b429f42017-04-17 14:56:57 -07002660 float sy = p->getDrawingState().active.h /
Robert Carr1725eee2017-04-26 18:32:15 -07002661 static_cast<float>(bufferHeight);
Robert Carr9b429f42017-04-17 14:56:57 -07002662 Transform extraParentScaling;
2663 extraParentScaling.set(sx, 0, 0, sy);
2664 t = t * extraParentScaling;
2665 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002666 }
2667 return t * getDrawingState().active.transform;
2668}
2669
Robert Carr6452f122017-03-21 10:41:29 -07002670#ifdef USE_HWC2
2671float Layer::getAlpha() const {
2672 const auto& p = getParent();
2673
2674 float parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0;
2675 return parentAlpha * getDrawingState().alpha;
2676}
2677#else
2678uint8_t Layer::getAlpha() const {
2679 const auto& p = getParent();
2680
2681 float parentAlpha = (p != nullptr) ? (p->getAlpha() / 255.0f) : 1.0;
2682 float drawingAlpha = getDrawingState().alpha / 255.0f;
2683 drawingAlpha = drawingAlpha * parentAlpha;
2684 return static_cast<uint8_t>(std::round(drawingAlpha * 255));
2685}
2686#endif
2687
Robert Carr1f0a16a2016-10-24 16:27:39 -07002688void Layer::commitChildList() {
2689 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2690 const auto& child = mCurrentChildren[i];
2691 child->commitChildList();
2692 }
2693 mDrawingChildren = mCurrentChildren;
2694}
2695
Mathias Agopian13127d82013-03-05 17:47:11 -08002696// ---------------------------------------------------------------------------
2697
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002698}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002699
2700#if defined(__gl_h_)
2701#error "don't include gl/gl.h in this file"
2702#endif
2703
2704#if defined(__gl2_h_)
2705#error "don't include gl2/gl2.h in this file"
2706#endif