blob: 5405971afa0e46af350110d5d97d3dbc44a89b10 [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>
Kalle Raitaa099a242017-01-11 11:17:29 -080043#include <gui/LayerDebugInfo.h>
Mathias Agopian90ac7992012-02-25 18:48:35 -080044#include <gui/Surface.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080045
46#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020047#include "Colorizer.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070048#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080049#include "Layer.h"
Fabien Sanglard7b1563a2016-10-13 12:05:28 -070050#include "LayerRejecter.h"
Dan Stozab9b08832014-03-13 11:55:57 -070051#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080052#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080053
Mathias Agopian1b031492012-06-20 17:51:20 -070054#include "DisplayHardware/HWComposer.h"
55
Mathias Agopian875d8e12013-06-07 15:35:48 -070056#include "RenderEngine/RenderEngine.h"
57
Dan Stozac5da2712016-07-20 15:38:12 -070058#include <mutex>
chaviw1d044282017-09-27 12:19:28 -070059#include "LayerProtoHelper.h"
Dan Stozac5da2712016-07-20 15:38:12 -070060
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061#define DEBUG_RESIZE 0
62
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063namespace android {
64
65// ---------------------------------------------------------------------------
66
Mathias Agopian13127d82013-03-05 17:47:11 -080067int32_t Layer::sSequence = 1;
68
Mathias Agopian4d9b8222013-03-12 17:11:48 -070069Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
70 const String8& name, uint32_t w, uint32_t h, uint32_t flags)
Mathias Agopian13127d82013-03-05 17:47:11 -080071 : contentDirty(false),
72 sequence(uint32_t(android_atomic_inc(&sSequence))),
73 mFlinger(flinger),
Ivan Lozano80de6f32017-10-30 11:24:08 -070074 mTextureName(UINT32_MAX),
Mathias Agopian13127d82013-03-05 17:47:11 -080075 mPremultipliedAlpha(true),
76 mName("unnamed"),
Mathias Agopian13127d82013-03-05 17:47:11 -080077 mFormat(PIXEL_FORMAT_NONE),
Mathias Agopian13127d82013-03-05 17:47:11 -080078 mTransactionFlags(0),
Dan Stoza7dde5992015-05-22 09:51:44 -070079 mPendingStateMutex(),
80 mPendingStates(),
Mathias Agopiana67932f2011-04-20 14:20:59 -070081 mQueuedFrames(0),
Jesse Hall399184a2014-03-03 15:42:54 -080082 mSidebandStreamChanged(false),
Mathias Agopiana9347642017-02-13 16:42:28 -080083 mActiveBufferSlot(BufferQueue::INVALID_BUFFER_SLOT),
Mathias Agopiana67932f2011-04-20 14:20:59 -070084 mCurrentTransform(0),
Mathias Agopian933389f2011-07-18 16:15:08 -070085 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
Robert Carrc3574f72016-03-24 12:19:32 -070086 mOverrideScalingMode(-1),
Mathias Agopiana67932f2011-04-20 14:20:59 -070087 mCurrentOpacity(true),
Brian Andersond6927fb2016-07-23 23:37:30 -070088 mBufferLatched(false),
Dan Stozacac35382016-01-27 12:21:06 -080089 mCurrentFrameNumber(0),
Brian Anderson8cc8b102016-10-21 12:43:09 -070090 mPreviousFrameNumber(0),
Mathias Agopian4d143ee2012-02-23 20:05:39 -080091 mRefreshPending(false),
Mathias Agopian82d7ab62012-01-19 18:34:40 -080092 mFrameLatencyNeeded(false),
Mathias Agopian13127d82013-03-05 17:47:11 -080093 mFiltering(false),
94 mNeedsFiltering(false),
Mathias Agopian5cdc8992013-08-13 20:51:23 -070095 mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
Fabien Sanglard9d96de42016-10-11 00:15:18 +000096#ifndef USE_HWC2
97 mIsGlesComposition(false),
98#endif
Mathias Agopian13127d82013-03-05 17:47:11 -080099 mProtectedByApp(false),
100 mHasSurface(false),
Riley Andrews03414a12014-07-01 14:22:59 -0700101 mClientRef(client),
Dan Stozaa4650a52015-05-12 12:56:16 -0700102 mPotentialCursor(false),
103 mQueueItemLock(),
104 mQueueItemCondition(),
105 mQueueItems(),
Dan Stoza65476f32015-05-14 09:27:25 -0700106 mLastFrameNumberReceived(0),
Pablo Ceballos04839ab2015-11-13 13:39:23 -0800107 mUpdateTexImageFailed(false),
Robert Carr82364e32016-05-15 11:27:47 -0700108 mAutoRefresh(false),
Robert Carr7bf247e2017-05-18 14:02:49 -0700109 mFreezeGeometryUpdates(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800110{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000111#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800112 ALOGV("Creating Layer %s", name.string());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000113#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -0800114
Mathias Agopiana67932f2011-04-20 14:20:59 -0700115 mCurrentCrop.makeInvalid();
Mathias Agopian3f844832013-08-07 21:24:32 -0700116 mFlinger->getRenderEngine().genTextures(1, &mTextureName);
Mathias Agopian49457ac2013-08-14 18:20:17 -0700117 mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700118
119 uint32_t layerFlags = 0;
120 if (flags & ISurfaceComposerClient::eHidden)
Andy McFadden4125a4f2014-01-29 17:17:11 -0800121 layerFlags |= layer_state_t::eLayerHidden;
122 if (flags & ISurfaceComposerClient::eOpaque)
123 layerFlags |= layer_state_t::eLayerOpaque;
Dan Stoza23116082015-06-18 14:58:39 -0700124 if (flags & ISurfaceComposerClient::eSecure)
125 layerFlags |= layer_state_t::eLayerSecure;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700126
127 if (flags & ISurfaceComposerClient::eNonPremultiplied)
128 mPremultipliedAlpha = false;
129
130 mName = name;
Dan Stozaf7ba41a2017-05-10 15:11:11 -0700131 mTransactionName = String8("TX - ") + mName;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700132
133 mCurrentState.active.w = w;
134 mCurrentState.active.h = h;
Robert Carr3dcabfa2016-03-01 18:36:58 -0800135 mCurrentState.active.transform.set(0, 0);
Robert Carrb5d3d262016-03-25 15:08:13 -0700136 mCurrentState.crop.makeInvalid();
137 mCurrentState.finalCrop.makeInvalid();
Robert Carr7bf247e2017-05-18 14:02:49 -0700138 mCurrentState.requestedFinalCrop = mCurrentState.finalCrop;
139 mCurrentState.requestedCrop = mCurrentState.crop;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700140 mCurrentState.z = 0;
chaviw13fdc492017-06-27 12:40:18 -0700141 mCurrentState.color.a = 1.0f;
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);
Steven Thomasb02664d2017-07-26 18:48:28 -0700201
202#ifdef USE_HWC2
Chia-I Wuc6657022017-08-15 11:18:17 -0700203 if (!mHwcLayers.empty()) {
204 ALOGE("Found stale hardware composer layers when destroying "
205 "surface flinger layer %s", mName.string());
206 destroyAllHwcLayers();
207 }
Steven Thomasb02664d2017-07-26 18:48:28 -0700208#endif
Mathias Agopian96f08192010-06-02 23:28:45 -0700209}
210
Mathias Agopian13127d82013-03-05 17:47:11 -0800211// ---------------------------------------------------------------------------
212// callbacks
213// ---------------------------------------------------------------------------
214
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000215#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800216void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
217 if (mHwcLayers.empty()) {
218 return;
219 }
220 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
221}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000222#else
223void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
224 HWComposer::HWCLayerInterface* layer) {
225 if (layer) {
226 layer->onDisplayed();
227 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
228 }
229}
230#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800231
Dan Stoza6b9454d2014-11-07 16:00:59 -0800232void Layer::onFrameAvailable(const BufferItem& item) {
233 // Add this buffer from our internal queue tracker
234 { // Autolock scope
235 Mutex::Autolock lock(mQueueItemLock);
Irvel468051e2016-06-13 16:44:44 -0700236 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
237 item.mGraphicBuffer->getHeight(), item.mFrameNumber);
Dan Stozaa4650a52015-05-12 12:56:16 -0700238 // Reset the frame number tracker when we receive the first buffer after
239 // a frame number reset
240 if (item.mFrameNumber == 1) {
241 mLastFrameNumberReceived = 0;
242 }
243
244 // Ensure that callbacks are handled in order
245 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
246 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
247 ms2ns(500));
248 if (result != NO_ERROR) {
249 ALOGE("[%s] Timed out waiting on callback", mName.string());
250 }
251 }
252
Dan Stoza6b9454d2014-11-07 16:00:59 -0800253 mQueueItems.push_back(item);
Dan Stozaecc50402015-04-28 14:42:06 -0700254 android_atomic_inc(&mQueuedFrames);
Dan Stozaa4650a52015-05-12 12:56:16 -0700255
256 // Wake up any pending callbacks
257 mLastFrameNumberReceived = item.mFrameNumber;
258 mQueueItemCondition.broadcast();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800259 }
260
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800261 mFlinger->signalLayerUpdate();
Mathias Agopian579b3f82010-06-08 19:54:15 -0700262}
263
Dan Stoza6b9454d2014-11-07 16:00:59 -0800264void Layer::onFrameReplaced(const BufferItem& item) {
Dan Stoza7dde5992015-05-22 09:51:44 -0700265 { // Autolock scope
266 Mutex::Autolock lock(mQueueItemLock);
Dan Stozaa4650a52015-05-12 12:56:16 -0700267
Dan Stoza7dde5992015-05-22 09:51:44 -0700268 // Ensure that callbacks are handled in order
269 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
270 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
271 ms2ns(500));
272 if (result != NO_ERROR) {
273 ALOGE("[%s] Timed out waiting on callback", mName.string());
274 }
Dan Stozaa4650a52015-05-12 12:56:16 -0700275 }
Dan Stoza7dde5992015-05-22 09:51:44 -0700276
277 if (mQueueItems.empty()) {
278 ALOGE("Can't replace a frame on an empty queue");
279 return;
280 }
Pablo Ceballos4d85da42016-04-19 20:11:56 -0700281 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
Dan Stoza7dde5992015-05-22 09:51:44 -0700282
283 // Wake up any pending callbacks
284 mLastFrameNumberReceived = item.mFrameNumber;
285 mQueueItemCondition.broadcast();
Dan Stozaa4650a52015-05-12 12:56:16 -0700286 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800287}
288
Jesse Hall399184a2014-03-03 15:42:54 -0800289void Layer::onSidebandStreamChanged() {
290 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
291 // mSidebandStreamChanged was false
292 mFlinger->signalLayerUpdate();
293 }
294}
295
Chia-I Wuc6657022017-08-15 11:18:17 -0700296void Layer::onRemovedFromCurrentState() {
297 // the layer is removed from SF mCurrentState to mLayersPendingRemoval
298
Robert Carr5edb1ad2017-04-25 10:54:24 -0700299 if (mCurrentState.zOrderRelativeOf != nullptr) {
300 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
301 if (strongRelative != nullptr) {
302 strongRelative->removeZOrderRelative(this);
Chia-I Wuc6657022017-08-15 11:18:17 -0700303 mFlinger->setTransactionFlags(eTraversalNeeded);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700304 }
305 mCurrentState.zOrderRelativeOf = nullptr;
306 }
307
Chia-I Wuc6657022017-08-15 11:18:17 -0700308 for (const auto& child : mCurrentChildren) {
309 child->onRemovedFromCurrentState();
310 }
311}
Chia-I Wu38512252017-05-17 14:36:16 -0700312
Chia-I Wuc6657022017-08-15 11:18:17 -0700313void Layer::onRemoved() {
314 // the layer is removed from SF mLayersPendingRemoval
315
316 mSurfaceFlingerConsumer->abandon();
Chia-I Wu38512252017-05-17 14:36:16 -0700317#ifdef USE_HWC2
Steven Thomasb02664d2017-07-26 18:48:28 -0700318 destroyAllHwcLayers();
Chia-I Wu38512252017-05-17 14:36:16 -0700319#endif
320
Robert Carr1f0a16a2016-10-24 16:27:39 -0700321 for (const auto& child : mCurrentChildren) {
322 child->onRemoved();
323 }
Mathias Agopian48d819a2009-09-10 19:41:18 -0700324}
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700325
Mathias Agopian13127d82013-03-05 17:47:11 -0800326// ---------------------------------------------------------------------------
327// set-up
328// ---------------------------------------------------------------------------
329
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700330const String8& Layer::getName() const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800331 return mName;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800332}
333
chaviw13fdc492017-06-27 12:40:18 -0700334bool Layer::getPremultipledAlpha() const {
335 return mPremultipliedAlpha;
336}
337
Mathias Agopianf9d93272009-06-19 17:00:27 -0700338status_t Layer::setBuffers( uint32_t w, uint32_t h,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800339 PixelFormat format, uint32_t flags)
340{
Mathias Agopianca99fb82010-04-14 16:43:44 -0700341 uint32_t const maxSurfaceDims = min(
Mathias Agopiana4912602012-07-12 14:25:33 -0700342 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
Mathias Agopianca99fb82010-04-14 16:43:44 -0700343
344 // never allow a surface larger than what our underlying GL implementation
345 // can handle.
346 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
Mathias Agopianff615cc2012-02-24 14:58:36 -0800347 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700348 return BAD_VALUE;
349 }
350
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700351 mFormat = format;
Mathias Agopianeff062c2010-08-25 14:59:15 -0700352
Riley Andrews03414a12014-07-01 14:22:59 -0700353 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
Mathias Agopian3165cc22012-08-08 19:42:09 -0700354 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700355 mCurrentOpacity = getOpacityForFormat(format);
356
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800357 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
358 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
359 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700360
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800361 return NO_ERROR;
362}
363
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700364sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800365 Mutex::Autolock _l(mLock);
366
367 LOG_ALWAYS_FATAL_IF(mHasSurface,
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700368 "Layer::getHandle() has already been called");
Mathias Agopian13127d82013-03-05 17:47:11 -0800369
370 mHasSurface = true;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700371
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700372 return new Handle(mFlinger, this);
Mathias Agopian13127d82013-03-05 17:47:11 -0800373}
374
Dan Stozab9b08832014-03-13 11:55:57 -0700375sp<IGraphicBufferProducer> Layer::getProducer() const {
376 return mProducer;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700377}
378
Mathias Agopian13127d82013-03-05 17:47:11 -0800379// ---------------------------------------------------------------------------
380// h/w composer set-up
381// ---------------------------------------------------------------------------
382
Steven Thomasb02664d2017-07-26 18:48:28 -0700383#ifdef USE_HWC2
384bool Layer::createHwcLayer(HWComposer* hwc, int32_t hwcId) {
385 LOG_ALWAYS_FATAL_IF(mHwcLayers.count(hwcId) != 0,
386 "Already have a layer for hwcId %d", hwcId);
387 HWC2::Layer* layer = hwc->createLayer(hwcId);
388 if (!layer) {
389 return false;
390 }
391 HWCInfo& hwcInfo = mHwcLayers[hwcId];
392 hwcInfo.hwc = hwc;
393 hwcInfo.layer = layer;
394 layer->setLayerDestroyedListener(
395 [this, hwcId] (HWC2::Layer* /*layer*/){mHwcLayers.erase(hwcId);});
396 return true;
397}
398
399void Layer::destroyHwcLayer(int32_t hwcId) {
400 if (mHwcLayers.count(hwcId) == 0) {
401 return;
402 }
403 auto& hwcInfo = mHwcLayers[hwcId];
404 LOG_ALWAYS_FATAL_IF(hwcInfo.layer == nullptr,
405 "Attempt to destroy null layer");
406 LOG_ALWAYS_FATAL_IF(hwcInfo.hwc == nullptr, "Missing HWComposer");
407 hwcInfo.hwc->destroyLayer(hwcId, hwcInfo.layer);
408 // The layer destroyed listener should have cleared the entry from
409 // mHwcLayers. Verify that.
410 LOG_ALWAYS_FATAL_IF(mHwcLayers.count(hwcId) != 0,
411 "Stale layer entry in mHwcLayers");
412}
413
414void Layer::destroyAllHwcLayers() {
415 size_t numLayers = mHwcLayers.size();
416 for (size_t i = 0; i < numLayers; ++i) {
417 LOG_ALWAYS_FATAL_IF(mHwcLayers.empty(), "destroyAllHwcLayers failed");
418 destroyHwcLayer(mHwcLayers.begin()->first);
419 }
420 LOG_ALWAYS_FATAL_IF(!mHwcLayers.empty(),
421 "All hardware composer layers should have been destroyed");
422}
423#endif
424
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800425Rect Layer::getContentCrop() const {
426 // this is the crop rectangle that applies to the buffer
427 // itself (as opposed to the window)
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700428 Rect crop;
429 if (!mCurrentCrop.isEmpty()) {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800430 // if the buffer crop is defined, we use that
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700431 crop = mCurrentCrop;
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800432 } else if (mActiveBuffer != NULL) {
433 // otherwise we use the whole buffer
434 crop = mActiveBuffer->getBounds();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700435 } else {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800436 // if we don't have a buffer yet, we use an empty/invalid crop
Mathias Agopian4fec8732012-06-29 14:12:52 -0700437 crop.makeInvalid();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700438 }
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700439 return crop;
440}
441
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700442static Rect reduce(const Rect& win, const Region& exclude) {
443 if (CC_LIKELY(exclude.isEmpty())) {
444 return win;
445 }
446 if (exclude.isRect()) {
447 return win.reduce(exclude.getBounds());
448 }
449 return Region(win).subtract(exclude).getBounds();
450}
451
Robert Carr1f0a16a2016-10-24 16:27:39 -0700452Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
453 const Layer::State& s(getDrawingState());
454 Rect win(s.active.w, s.active.h);
455
456 if (!s.crop.isEmpty()) {
457 win.intersect(s.crop, &win);
458 }
459
460 Transform t = getTransform();
461 win = t.transform(win);
462
Robert Carr41b08b52017-06-01 16:11:34 -0700463 if (!s.finalCrop.isEmpty()) {
464 win.intersect(s.finalCrop, &win);
465 }
466
Chia-I Wue41dbe62017-06-13 14:10:56 -0700467 const sp<Layer>& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700468 // Now we need to calculate the parent bounds, so we can clip ourselves to those.
469 // When calculating the parent bounds for purposes of clipping,
470 // we don't need to constrain the parent to its transparent region.
471 // The transparent region is an optimization based on the
472 // buffer contents of the layer, but does not affect the space allocated to
473 // it by policy, and thus children should be allowed to extend into the
474 // parent's transparent region. In fact one of the main uses, is to reduce
475 // buffer allocation size in cases where a child window sits behind a main window
476 // (by marking the hole in the parent window as a transparent region)
477 if (p != nullptr) {
478 Rect bounds = p->computeScreenBounds(false);
479 bounds.intersect(win, &win);
480 }
481
482 if (reduceTransparentRegion) {
483 auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
484 win = reduce(win, screenTransparentRegion);
485 }
486
487 return win;
488}
489
Mathias Agopian13127d82013-03-05 17:47:11 -0800490Rect Layer::computeBounds() const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700491 const Layer::State& s(getDrawingState());
Michael Lentine6c925ed2014-09-26 17:55:01 -0700492 return computeBounds(s.activeTransparentRegion);
493}
494
495Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
496 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800497 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700498
499 if (!s.crop.isEmpty()) {
500 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -0800501 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700502
503 Rect bounds = win;
Chia-I Wue41dbe62017-06-13 14:10:56 -0700504 const auto& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700505 if (p != nullptr) {
Robert Carrde9ec442017-02-08 17:43:36 -0800506 // Look in computeScreenBounds recursive call for explanation of
507 // why we pass false here.
508 bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700509 }
510
511 Transform t = getTransform();
512 if (p != nullptr) {
513 win = t.transform(win);
514 win.intersect(bounds, &win);
515 win = t.inverse().transform(win);
516 }
517
Mathias Agopian6c7f25a2013-05-09 20:37:10 -0700518 // subtract the transparent region and snap to the bounds
Michael Lentine6c925ed2014-09-26 17:55:01 -0700519 return reduce(win, activeTransparentRegion);
Mathias Agopian13127d82013-03-05 17:47:11 -0800520}
521
Robert Carr1f0a16a2016-10-24 16:27:39 -0700522Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
Robert Carrb5d3d262016-03-25 15:08:13 -0700523 // the crop is the area of the window that gets cropped, but not
Mathias Agopian13127d82013-03-05 17:47:11 -0800524 // scaled in any ways.
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700525 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800526
527 // apply the projection's clipping to the window crop in
528 // layerstack space, and convert-back to layer space.
Mathias Agopian6b442672013-07-09 21:24:52 -0700529 // if there are no window scaling involved, this operation will map to full
530 // pixels in the buffer.
531 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
532 // a viewport clipping and a window transform. we should use floating point to fix this.
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700533
534 Rect activeCrop(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700535 if (!s.crop.isEmpty()) {
Chia-I Wudf7867f2017-07-20 14:24:37 -0700536 activeCrop.intersect(s.crop, &activeCrop);
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700537 }
538
Robert Carr1f0a16a2016-10-24 16:27:39 -0700539 Transform t = getTransform();
540 activeCrop = t.transform(activeCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000541 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
542 activeCrop.clear();
543 }
Robert Carrb5d3d262016-03-25 15:08:13 -0700544 if (!s.finalCrop.isEmpty()) {
545 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000546 activeCrop.clear();
547 }
548 }
chaviwb1154d12017-10-31 14:15:36 -0700549
550 const auto& p = mDrawingParent.promote();
551 if (p != nullptr) {
552 auto parentCrop = p->computeInitialCrop(hw);
553 activeCrop.intersect(parentCrop, &activeCrop);
554 }
555
Robert Carr1f0a16a2016-10-24 16:27:39 -0700556 return activeCrop;
557}
558
Dan Stoza5a423ea2017-02-16 14:10:39 -0800559FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
Robert Carr1f0a16a2016-10-24 16:27:39 -0700560 // the content crop is the area of the content that gets scaled to the
561 // layer's size. This is in buffer space.
Dan Stoza5a423ea2017-02-16 14:10:39 -0800562 FloatRect crop = getContentCrop().toFloatRect();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700563
564 // In addition there is a WM-specified crop we pull from our drawing state.
565 const State& s(getDrawingState());
566
567 // Screen space to make reduction to parent crop clearer.
568 Rect activeCrop = computeInitialCrop(hw);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700569 Transform t = getTransform();
570 // Back to layer space to work with the content crop.
571 activeCrop = t.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800572
Michael Lentine28ea2172014-11-19 18:32:37 -0800573 // This needs to be here as transform.transform(Rect) computes the
574 // transformed rect and then takes the bounding box of the result before
575 // returning. This means
576 // transform.inverse().transform(transform.transform(Rect)) != Rect
577 // in which case we need to make sure the final rect is clipped to the
578 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000579 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
580 activeCrop.clear();
581 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800582
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700583 // subtract the transparent region and snap to the bounds
584 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
585
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000586 // Transform the window crop to match the buffer coordinate system,
587 // which means using the inverse of the current transform set on the
588 // SurfaceFlingerConsumer.
589 uint32_t invTransform = mCurrentTransform;
Robert Carrcae605c2017-03-29 12:10:31 -0700590 if (getTransformToDisplayInverse()) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000591 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700592 * the code below applies the primary display's inverse transform to the
593 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000594 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700595 uint32_t invTransformOrient =
596 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000597 // calculate the inverse transform
598 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
599 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
600 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800601 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000602 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700603 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
604 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800605 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000606
607 int winWidth = s.active.w;
608 int winHeight = s.active.h;
609 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
610 // If the activeCrop has been rotate the ends are rotated but not
611 // the space itself so when transforming ends back we can't rely on
612 // a modification of the axes of rotation. To account for this we
613 // need to reorient the inverse rotation in terms of the current
614 // axes of rotation.
615 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
616 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
617 if (is_h_flipped == is_v_flipped) {
618 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
619 NATIVE_WINDOW_TRANSFORM_FLIP_H;
620 }
621 winWidth = s.active.h;
622 winHeight = s.active.w;
623 }
624 const Rect winCrop = activeCrop.transform(
625 invTransform, s.active.w, s.active.h);
626
627 // below, crop is intersected with winCrop expressed in crop's coordinate space
628 float xScale = crop.getWidth() / float(winWidth);
629 float yScale = crop.getHeight() / float(winHeight);
630
631 float insetL = winCrop.left * xScale;
632 float insetT = winCrop.top * yScale;
633 float insetR = (winWidth - winCrop.right ) * xScale;
634 float insetB = (winHeight - winCrop.bottom) * yScale;
635
636 crop.left += insetL;
637 crop.top += insetT;
638 crop.right -= insetR;
639 crop.bottom -= insetB;
640
Mathias Agopian13127d82013-03-05 17:47:11 -0800641 return crop;
642}
643
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000644#ifdef USE_HWC2
Robert Carrae060832016-11-28 10:51:00 -0800645void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000646#else
647void Layer::setGeometry(
648 const sp<const DisplayDevice>& hw,
649 HWComposer::HWCLayerInterface& layer)
650#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700651{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000652#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800653 const auto hwcId = displayDevice->getHwcDisplayId();
654 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000655#else
656 layer.setDefaultState();
657#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700658
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700659 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000660#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800661 hwcInfo.forceClientComposition = false;
662
663 if (isSecure() && !displayDevice->isSecure()) {
664 hwcInfo.forceClientComposition = true;
665 }
666
667 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000668#else
669 layer.setSkip(false);
670
671 if (isSecure() && !hw->isSecure()) {
672 layer.setSkip(true);
673 }
674#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700675
Mathias Agopian13127d82013-03-05 17:47:11 -0800676 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700677 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000678#ifdef USE_HWC2
David Revemanecf0fa52017-03-03 11:32:44 -0500679 auto blendMode = HWC2::BlendMode::None;
Robert Carr6452f122017-03-21 10:41:29 -0700680 if (!isOpaque(s) || getAlpha() != 1.0f) {
David Revemanecf0fa52017-03-03 11:32:44 -0500681 blendMode = mPremultipliedAlpha ?
Dan Stoza9e56aa02015-11-02 13:00:03 -0800682 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800683 }
David Revemanecf0fa52017-03-03 11:32:44 -0500684 auto error = hwcLayer->setBlendMode(blendMode);
685 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
686 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
687 to_string(error).c_str(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000688#else
chaviw13fdc492017-06-27 12:40:18 -0700689 if (!isOpaque(s) || getAlpha() != 1.0f) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000690 layer.setBlending(mPremultipliedAlpha ?
691 HWC_BLENDING_PREMULT :
692 HWC_BLENDING_COVERAGE);
693 }
694#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800695
696 // apply the layer's transform, followed by the display's global transform
697 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700698 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700699 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -0700700 if (!s.crop.isEmpty()) {
701 Rect activeCrop(s.crop);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700702 activeCrop = t.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000703#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000704 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000705#else
706 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
707#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000708 activeCrop.clear();
709 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700710 activeCrop = t.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800711 // This needs to be here as transform.transform(Rect) computes the
712 // transformed rect and then takes the bounding box of the result before
713 // returning. This means
714 // transform.inverse().transform(transform.transform(Rect)) != Rect
715 // in which case we need to make sure the final rect is clipped to the
716 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000717 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
718 activeCrop.clear();
719 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700720 // mark regions outside the crop as transparent
721 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
722 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
723 s.active.w, s.active.h));
724 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
725 activeCrop.left, activeCrop.bottom));
726 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
727 s.active.w, activeCrop.bottom));
728 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700729
730 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700731 if (!s.finalCrop.isEmpty()) {
732 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000733 frame.clear();
734 }
735 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000736#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000737 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
738 frame.clear();
739 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800740 const Transform& tr(displayDevice->getTransform());
741 Rect transformedFrame = tr.transform(frame);
David Revemanecf0fa52017-03-03 11:32:44 -0500742 error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700743 if (error != HWC2::Error::None) {
744 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
745 mName.string(), transformedFrame.left, transformedFrame.top,
746 transformedFrame.right, transformedFrame.bottom,
747 to_string(error).c_str(), static_cast<int32_t>(error));
748 } else {
749 hwcInfo.displayFrame = transformedFrame;
750 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800751
Dan Stoza5a423ea2017-02-16 14:10:39 -0800752 FloatRect sourceCrop = computeCrop(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800753 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700754 if (error != HWC2::Error::None) {
755 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
756 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
757 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
758 static_cast<int32_t>(error));
759 } else {
760 hwcInfo.sourceCrop = sourceCrop;
761 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800762
chaviw13fdc492017-06-27 12:40:18 -0700763 float alpha = static_cast<float>(getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -0700764 error = hwcLayer->setPlaneAlpha(alpha);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800765 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
Robert Carr6452f122017-03-21 10:41:29 -0700766 "%s (%d)", mName.string(), alpha, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800767 static_cast<int32_t>(error));
768
Robert Carrae060832016-11-28 10:51:00 -0800769 error = hwcLayer->setZOrder(z);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800770 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
Robert Carrae060832016-11-28 10:51:00 -0800771 mName.string(), z, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800772 static_cast<int32_t>(error));
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500773
Albert Chaulk2a589632017-05-04 16:59:44 -0400774 int type = s.type;
775 int appId = s.appId;
Chia-I Wue41dbe62017-06-13 14:10:56 -0700776 sp<Layer> parent = mDrawingParent.promote();
Albert Chaulk2a589632017-05-04 16:59:44 -0400777 if (parent.get()) {
778 auto& parentState = parent->getDrawingState();
779 type = parentState.type;
780 appId = parentState.appId;
781 }
782
783 error = hwcLayer->setInfo(type, appId);
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500784 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
785 mName.string(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000786#else
787 if (!frame.intersect(hw->getViewport(), &frame)) {
788 frame.clear();
789 }
790 const Transform& tr(hw->getTransform());
791 layer.setFrame(tr.transform(frame));
792 layer.setCrop(computeCrop(hw));
chaviw13fdc492017-06-27 12:40:18 -0700793 layer.setPlaneAlpha(static_cast<uint8_t>(std::round(255.0f*getAlpha())));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000794#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800795
Mathias Agopian29a367b2011-07-12 14:51:45 -0700796 /*
797 * Transformations are applied in this order:
798 * 1) buffer orientation/flip/mirror
799 * 2) state transformation (window manager)
800 * 3) layer orientation (screen orientation)
801 * (NOTE: the matrices are multiplied in reverse order)
802 */
803
804 const Transform bufferOrientation(mCurrentTransform);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700805 Transform transform(tr * t * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700806
Robert Carrcae605c2017-03-29 12:10:31 -0700807 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700808 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700809 * the code below applies the primary display's inverse transform to the
810 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700811 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700812 uint32_t invTransform =
813 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700814 // calculate the inverse transform
815 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
816 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
817 NATIVE_WINDOW_TRANSFORM_FLIP_H;
818 }
Robert Carrcae605c2017-03-29 12:10:31 -0700819
820 /*
821 * Here we cancel out the orientation component of the WM transform.
822 * The scaling and translate components are already included in our bounds
823 * computation so it's enough to just omit it in the composition.
824 * See comment in onDraw with ref to b/36727915 for why.
825 */
826 transform = Transform(invTransform) * tr * bufferOrientation;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700827 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700828
829 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800830 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000831#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800832 if (orientation & Transform::ROT_INVALID) {
833 // we can only handle simple transformation
834 hwcInfo.forceClientComposition = true;
835 } else {
836 auto transform = static_cast<HWC2::Transform>(orientation);
837 auto error = hwcLayer->setTransform(transform);
838 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
839 "%s (%d)", mName.string(), to_string(transform).c_str(),
840 to_string(error).c_str(), static_cast<int32_t>(error));
841 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000842#else
843 if (orientation & Transform::ROT_INVALID) {
844 // we can only handle simple transformation
845 layer.setSkip(true);
846 } else {
847 layer.setTransform(orientation);
848 }
849#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700850}
851
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000852#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800853void Layer::forceClientComposition(int32_t hwcId) {
854 if (mHwcLayers.count(hwcId) == 0) {
855 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
856 return;
857 }
858
859 mHwcLayers[hwcId].forceClientComposition = true;
860}
Dan Stoza9e56aa02015-11-02 13:00:03 -0800861
Dan Stoza9e56aa02015-11-02 13:00:03 -0800862void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
863 // Apply this display's projection's viewport to the visible region
864 // before giving it to the HWC HAL.
865 const Transform& tr = displayDevice->getTransform();
866 const auto& viewport = displayDevice->getViewport();
867 Region visible = tr.transform(visibleRegion.intersect(viewport));
868 auto hwcId = displayDevice->getHwcDisplayId();
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800869 auto& hwcInfo = mHwcLayers[hwcId];
870 auto& hwcLayer = hwcInfo.layer;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800871 auto error = hwcLayer->setVisibleRegion(visible);
872 if (error != HWC2::Error::None) {
873 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
874 to_string(error).c_str(), static_cast<int32_t>(error));
875 visible.dump(LOG_TAG);
876 }
877
878 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
879 if (error != HWC2::Error::None) {
880 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
881 to_string(error).c_str(), static_cast<int32_t>(error));
882 surfaceDamageRegion.dump(LOG_TAG);
883 }
884
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700885 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800886 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700887 setCompositionType(hwcId, HWC2::Composition::Sideband);
888 ALOGV("[%s] Requesting Sideband composition", mName.string());
889 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800890 if (error != HWC2::Error::None) {
891 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
892 mName.string(), mSidebandStream->handle(),
893 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700895 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800896 }
897
Dan Stoza0a21df72016-07-20 12:52:38 -0700898 // Client layers
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800899 if (hwcInfo.forceClientComposition ||
Dan Stoza0a21df72016-07-20 12:52:38 -0700900 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700901 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800902 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700903 return;
904 }
905
Dan Stoza0a21df72016-07-20 12:52:38 -0700906 // SolidColor layers
907 if (mActiveBuffer == nullptr) {
908 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700909
chaviw13fdc492017-06-27 12:40:18 -0700910 half4 color = getColor();
911 error = hwcLayer->setColor({static_cast<uint8_t>(std::round(255.0f*color.r)),
912 static_cast<uint8_t>(std::round(255.0f * color.g)),
913 static_cast<uint8_t>(std::round(255.0f * color.b)),
914 255});
Dan Stoza0a21df72016-07-20 12:52:38 -0700915 if (error != HWC2::Error::None) {
916 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
917 to_string(error).c_str(), static_cast<int32_t>(error));
918 }
Dan Stozac6c89542016-07-27 10:16:52 -0700919
920 // Clear out the transform, because it doesn't make sense absent a
921 // source buffer
922 error = hwcLayer->setTransform(HWC2::Transform::None);
923 if (error != HWC2::Error::None) {
924 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
925 to_string(error).c_str(), static_cast<int32_t>(error));
926 }
927
Dan Stoza0a21df72016-07-20 12:52:38 -0700928 return;
929 }
930
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700931 // Device or Cursor layers
932 if (mPotentialCursor) {
933 ALOGV("[%s] Requesting Cursor composition", mName.string());
934 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800935 } else {
936 ALOGV("[%s] Requesting Device composition", mName.string());
937 setCompositionType(hwcId, HWC2::Composition::Device);
938 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700939
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700940 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
941 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
942 if (error != HWC2::Error::None) {
943 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
944 mCurrentState.dataSpace, to_string(error).c_str(),
945 static_cast<int32_t>(error));
946 }
947
Chia-I Wu06d63de2017-01-04 14:58:51 +0800948 uint32_t hwcSlot = 0;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400949 sp<GraphicBuffer> hwcBuffer;
950 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
951 &hwcSlot, &hwcBuffer);
Chia-I Wu06d63de2017-01-04 14:58:51 +0800952
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700953 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400954 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700955 if (error != HWC2::Error::None) {
956 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
957 mActiveBuffer->handle, to_string(error).c_str(),
958 static_cast<int32_t>(error));
959 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800960}
Courtney Goeltzenleuchter9551fd32016-10-20 17:18:15 -0600961
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000962#else
963void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
964 HWComposer::HWCLayerInterface& layer) {
965 // we have to set the visible region on every frame because
966 // we currently free it during onLayerDisplayed(), which is called
967 // after HWComposer::commit() -- every frame.
968 // Apply this display's projection's viewport to the visible region
969 // before giving it to the HWC HAL.
970 const Transform& tr = hw->getTransform();
971 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
972 layer.setVisibleRegionScreen(visible);
973 layer.setSurfaceDamage(surfaceDamageRegion);
974 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700975
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000976 if (mSidebandStream.get()) {
977 layer.setSidebandStream(mSidebandStream);
978 } else {
979 // NOTE: buffer can be NULL if the client never drew into this
980 // layer yet, or if we ran out of memory
981 layer.setBuffer(mActiveBuffer);
982 }
983}
984#endif
985
986#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800987void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
988 auto hwcId = displayDevice->getHwcDisplayId();
989 if (mHwcLayers.count(hwcId) == 0 ||
990 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
991 return;
992 }
993
994 // This gives us only the "orientation" component of the transform
995 const State& s(getCurrentState());
996
997 // Apply the layer's transform, followed by the display's global transform
998 // Here we're guaranteed that the layer's transform preserves rects
999 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -07001000 if (!s.crop.isEmpty()) {
1001 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001002 }
1003 // Subtract the transparent region and snap to the bounds
1004 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001005 Rect frame(getTransform().transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -08001006 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -07001007 if (!s.finalCrop.isEmpty()) {
1008 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001009 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001010 auto& displayTransform(displayDevice->getTransform());
1011 auto position = displayTransform.transform(frame);
1012
1013 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
1014 position.top);
1015 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
1016 "to (%d, %d): %s (%d)", mName.string(), position.left,
1017 position.top, to_string(error).c_str(),
1018 static_cast<int32_t>(error));
1019}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001020#else
1021void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
1022 HWComposer::HWCLayerInterface& layer) {
1023 int fenceFd = -1;
1024
1025 // TODO: there is a possible optimization here: we only need to set the
1026 // acquire fence the first time a new buffer is acquired on EACH display.
1027
1028 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
1029 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
1030 if (fence->isValid()) {
1031 fenceFd = fence->dup();
1032 if (fenceFd == -1) {
1033 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
1034 }
1035 }
1036 }
1037 layer.setAcquireFenceFd(fenceFd);
1038}
1039
1040Rect Layer::getPosition(
1041 const sp<const DisplayDevice>& hw)
1042{
1043 // this gives us only the "orientation" component of the transform
1044 const State& s(getCurrentState());
1045
1046 // apply the layer's transform, followed by the display's global transform
1047 // here we're guaranteed that the layer's transform preserves rects
1048 Rect win(s.active.w, s.active.h);
1049 if (!s.crop.isEmpty()) {
1050 win.intersect(s.crop, &win);
1051 }
1052 // subtract the transparent region and snap to the bounds
1053 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001054 Rect frame(getTransform().transform(bounds));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001055 frame.intersect(hw->getViewport(), &frame);
1056 if (!s.finalCrop.isEmpty()) {
1057 frame.intersect(s.finalCrop, &frame);
1058 }
1059 const Transform& tr(hw->getTransform());
1060 return Rect(tr.transform(frame));
1061}
1062#endif
Riley Andrews03414a12014-07-01 14:22:59 -07001063
Mathias Agopian13127d82013-03-05 17:47:11 -08001064// ---------------------------------------------------------------------------
1065// drawing...
1066// ---------------------------------------------------------------------------
1067
chaviwa76b2712017-09-20 12:02:26 -07001068void Layer::draw(const RenderArea& renderArea, const Region& clip) const {
1069 onDraw(renderArea, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -08001070}
1071
chaviwa76b2712017-09-20 12:02:26 -07001072void Layer::draw(const RenderArea& renderArea, bool useIdentityTransform) const {
1073 onDraw(renderArea, Region(renderArea.getBounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001074}
1075
chaviwa76b2712017-09-20 12:02:26 -07001076void Layer::draw(const RenderArea& renderArea) const {
1077 onDraw(renderArea, Region(renderArea.getBounds()), false);
Dan Stozac7014012014-02-14 15:03:43 -08001078}
1079
Robert Carrcae605c2017-03-29 12:10:31 -07001080static constexpr mat4 inverseOrientation(uint32_t transform) {
1081 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1082 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1083 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1084 mat4 tr;
1085
1086 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1087 tr = tr * rot90;
1088 }
1089 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1090 tr = tr * flipH;
1091 }
1092 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1093 tr = tr * flipV;
1094 }
1095 return inverse(tr);
1096}
1097
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001098/*
1099 * onDraw will draw the current layer onto the presentable buffer
1100 */
chaviwa76b2712017-09-20 12:02:26 -07001101void Layer::onDraw(const RenderArea& renderArea, const Region& clip,
Dan Stozac7014012014-02-14 15:03:43 -08001102 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001103{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001104 ATRACE_CALL();
1105
Mathias Agopiana67932f2011-04-20 14:20:59 -07001106 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001107 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -07001108 // in fact never been drawn into. This happens frequently with
1109 // SurfaceView because the WindowManager can't know when the client
1110 // has drawn the first time.
1111
1112 // If there is nothing under us, we paint the screen in black, otherwise
1113 // we just skip this update.
1114
1115 // figure out if there is something below us
1116 Region under;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001117 bool finished = false;
Dan Stoza412903f2017-04-27 13:42:17 -07001118 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001119 if (finished || layer == static_cast<Layer const*>(this)) {
1120 finished = true;
1121 return;
1122 }
chaviwa76b2712017-09-20 12:02:26 -07001123 under.orSelf(renderArea.getTransform().transform(layer->visibleRegion));
Robert Carr1f0a16a2016-10-24 16:27:39 -07001124 });
Mathias Agopian179169e2010-05-06 20:21:45 -07001125 // if not everything below us is covered, we plug the holes!
1126 Region holes(clip.subtract(under));
1127 if (!holes.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07001128 clearWithOpenGL(renderArea, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -07001129 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001130 return;
1131 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001132
Andy McFadden97eba892012-12-11 15:21:45 -08001133 // Bind the current buffer to the GL texture, and wait for it to be
1134 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001135 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1136 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -08001137 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -07001138 // Go ahead and draw the buffer anyway; no matter what we do the screen
1139 // is probably going to have something visibly wrong.
1140 }
1141
chaviwa76b2712017-09-20 12:02:26 -07001142 bool blackOutLayer = isProtected() || (isSecure() && !renderArea.isSecure());
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001143
Mathias Agopian875d8e12013-06-07 15:35:48 -07001144 RenderEngine& engine(mFlinger->getRenderEngine());
1145
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001146 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -07001147 // TODO: we could be more subtle with isFixedSize()
chaviwa76b2712017-09-20 12:02:26 -07001148 const bool useFiltering = getFiltering() || needsFiltering(renderArea) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -07001149
1150 // Query the texture matrix given our current filtering mode.
1151 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001152 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1153 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -07001154
Robert Carrcae605c2017-03-29 12:10:31 -07001155 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001156
1157 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -07001158 * the code below applies the primary display's inverse transform to
1159 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001160 */
Pablo Ceballos021623b2016-04-15 17:31:51 -07001161 uint32_t transform =
1162 DisplayDevice::getPrimaryDisplayOrientationTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001163 mat4 tr = inverseOrientation(transform);
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001164
Robert Carrcae605c2017-03-29 12:10:31 -07001165 /**
1166 * TODO(b/36727915): This is basically a hack.
1167 *
1168 * Ensure that regardless of the parent transformation,
1169 * this buffer is always transformed from native display
1170 * orientation to display orientation. For example, in the case
1171 * of a camera where the buffer remains in native orientation,
1172 * we want the pixels to always be upright.
1173 */
Chia-I Wue41dbe62017-06-13 14:10:56 -07001174 sp<Layer> p = mDrawingParent.promote();
1175 if (p != nullptr) {
1176 const auto parentTransform = p->getTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001177 tr = tr * inverseOrientation(parentTransform.getOrientation());
1178 }
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001179
1180 // and finally apply it to the original texture matrix
1181 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1182 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1183 }
1184
Jamie Genniscbb1a952012-05-08 17:05:52 -07001185 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -07001186 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1187 mTexture.setFiltering(useFiltering);
1188 mTexture.setMatrix(textureMatrix);
1189
1190 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -07001191 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001192 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -07001193 }
chaviwa76b2712017-09-20 12:02:26 -07001194 drawWithOpenGL(renderArea, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001195 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001196}
1197
Mathias Agopian13127d82013-03-05 17:47:11 -08001198
chaviwa76b2712017-09-20 12:02:26 -07001199void Layer::clearWithOpenGL(const RenderArea& renderArea,
Fabien Sanglard17487192016-12-07 13:03:32 -08001200 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -08001201 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001202{
Mathias Agopian19733a32013-08-28 18:13:56 -07001203 RenderEngine& engine(mFlinger->getRenderEngine());
chaviwa76b2712017-09-20 12:02:26 -07001204 computeGeometry(renderArea, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -07001205 engine.setupFillWithColor(red, green, blue, alpha);
1206 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -08001207}
1208
chaviwa76b2712017-09-20 12:02:26 -07001209void Layer::clearWithOpenGL(const RenderArea& renderArea) const {
1210 clearWithOpenGL(renderArea, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001211}
1212
chaviwa76b2712017-09-20 12:02:26 -07001213void Layer::drawWithOpenGL(const RenderArea& renderArea, bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001214 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001215
chaviwa76b2712017-09-20 12:02:26 -07001216 computeGeometry(renderArea, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001217
Mathias Agopian13127d82013-03-05 17:47:11 -08001218 /*
1219 * NOTE: the way we compute the texture coordinates here produces
1220 * different results than when we take the HWC path -- in the later case
1221 * the "source crop" is rounded to texel boundaries.
1222 * This can produce significantly different results when the texture
1223 * is scaled by a large amount.
1224 *
1225 * The GL code below is more logical (imho), and the difference with
1226 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001227 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001228 * GL composition when a buffer scaling is applied (maybe with some
1229 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1230 * like more of a hack.
1231 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001232 Rect win(computeBounds());
1233
Robert Carr1f0a16a2016-10-24 16:27:39 -07001234 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -07001235 if (!s.finalCrop.isEmpty()) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001236 win = t.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001237 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001238 win.clear();
1239 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001240 win = t.inverse().transform(win);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001241 if (!win.intersect(computeBounds(), &win)) {
1242 win.clear();
1243 }
1244 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001245
Mathias Agopian3f844832013-08-07 21:24:32 -07001246 float left = float(win.left) / float(s.active.w);
1247 float top = float(win.top) / float(s.active.h);
1248 float right = float(win.right) / float(s.active.w);
1249 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001250
Mathias Agopian875d8e12013-06-07 15:35:48 -07001251 // TODO: we probably want to generate the texture coords with the mesh
1252 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001253 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1254 texCoords[0] = vec2(left, 1.0f - top);
1255 texCoords[1] = vec2(left, 1.0f - bottom);
1256 texCoords[2] = vec2(right, 1.0f - bottom);
1257 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001258
Mathias Agopian875d8e12013-06-07 15:35:48 -07001259 RenderEngine& engine(mFlinger->getRenderEngine());
chaviw13fdc492017-06-27 12:40:18 -07001260 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s),
1261 false /* disableTexture */, getColor());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001262#ifdef USE_HWC2
1263 engine.setSourceDataSpace(mCurrentState.dataSpace);
1264#endif
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001265 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001266 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001267}
1268
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001269#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001270void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1271 bool callIntoHwc) {
1272 if (mHwcLayers.count(hwcId) == 0) {
1273 ALOGE("setCompositionType called without a valid HWC layer");
1274 return;
1275 }
1276 auto& hwcInfo = mHwcLayers[hwcId];
1277 auto& hwcLayer = hwcInfo.layer;
1278 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1279 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1280 if (hwcInfo.compositionType != type) {
1281 ALOGV(" actually setting");
1282 hwcInfo.compositionType = type;
1283 if (callIntoHwc) {
1284 auto error = hwcLayer->setCompositionType(type);
1285 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1286 "composition type %s: %s (%d)", mName.string(),
1287 to_string(type).c_str(), to_string(error).c_str(),
1288 static_cast<int32_t>(error));
1289 }
1290 }
1291}
1292
1293HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001294 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1295 // If we're querying the composition type for a display that does not
1296 // have a HWC counterpart, then it will always be Client
1297 return HWC2::Composition::Client;
1298 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001299 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001300 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001301 return HWC2::Composition::Invalid;
1302 }
1303 return mHwcLayers.at(hwcId).compositionType;
1304}
1305
1306void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1307 if (mHwcLayers.count(hwcId) == 0) {
1308 ALOGE("setClearClientTarget called without a valid HWC layer");
1309 return;
1310 }
1311 mHwcLayers[hwcId].clearClientTarget = clear;
1312}
1313
1314bool Layer::getClearClientTarget(int32_t hwcId) const {
1315 if (mHwcLayers.count(hwcId) == 0) {
1316 ALOGE("getClearClientTarget called without a valid HWC layer");
1317 return false;
1318 }
1319 return mHwcLayers.at(hwcId).clearClientTarget;
1320}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001321#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001322
Ruben Brunk1681d952014-06-27 15:51:55 -07001323uint32_t Layer::getProducerStickyTransform() const {
1324 int producerStickyTransform = 0;
1325 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1326 if (ret != OK) {
1327 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1328 strerror(-ret), ret);
1329 return 0;
1330 }
1331 return static_cast<uint32_t>(producerStickyTransform);
1332}
1333
Dan Stozac5da2712016-07-20 15:38:12 -07001334bool Layer::latchUnsignaledBuffers() {
1335 static bool propertyLoaded = false;
1336 static bool latch = false;
1337 static std::mutex mutex;
1338 std::lock_guard<std::mutex> lock(mutex);
1339 if (!propertyLoaded) {
1340 char value[PROPERTY_VALUE_MAX] = {};
1341 property_get("debug.sf.latch_unsignaled", value, "0");
1342 latch = atoi(value);
1343 propertyLoaded = true;
1344 }
1345 return latch;
1346}
1347
Dan Stozacac35382016-01-27 12:21:06 -08001348uint64_t Layer::getHeadFrameNumber() const {
1349 Mutex::Autolock lock(mQueueItemLock);
1350 if (!mQueueItems.empty()) {
1351 return mQueueItems[0].mFrameNumber;
1352 } else {
1353 return mCurrentFrameNumber;
1354 }
1355}
1356
Dan Stoza1ce65812016-06-15 16:26:27 -07001357bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001358#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001359 if (latchUnsignaledBuffers()) {
1360 return true;
1361 }
1362
Dan Stoza1ce65812016-06-15 16:26:27 -07001363 Mutex::Autolock lock(mQueueItemLock);
1364 if (mQueueItems.empty()) {
1365 return true;
1366 }
1367 if (mQueueItems[0].mIsDroppable) {
1368 // Even though this buffer's fence may not have signaled yet, it could
1369 // be replaced by another buffer before it has a chance to, which means
1370 // that it's possible to get into a situation where a buffer is never
1371 // able to be latched. To avoid this, grab this buffer anyway.
1372 return true;
1373 }
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001374 return mQueueItems[0].mFenceTime->getSignalTime() !=
1375 Fence::SIGNAL_TIME_PENDING;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001376#else
1377 return true;
1378#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001379}
1380
Dan Stozacac35382016-01-27 12:21:06 -08001381bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1382 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1383 // Don't bother with a SyncPoint, since we've already latched the
1384 // relevant frame
1385 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001386 }
1387
Dan Stozacac35382016-01-27 12:21:06 -08001388 Mutex::Autolock lock(mLocalSyncPointMutex);
1389 mLocalSyncPoints.push_back(point);
1390 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001391}
1392
Mathias Agopian13127d82013-03-05 17:47:11 -08001393void Layer::setFiltering(bool filtering) {
1394 mFiltering = filtering;
1395}
1396
1397bool Layer::getFiltering() const {
1398 return mFiltering;
1399}
1400
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001401// As documented in libhardware header, formats in the range
1402// 0x100 - 0x1FF are specific to the HAL implementation, and
1403// are known to have no alpha channel
1404// TODO: move definition for device-specific range into
1405// hardware.h, instead of using hard-coded values here.
1406#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1407
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001408bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001409 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1410 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001411 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001412 switch (format) {
1413 case HAL_PIXEL_FORMAT_RGBA_8888:
1414 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001415 case HAL_PIXEL_FORMAT_RGBA_FP16:
Romain Guy541f2262017-02-10 18:50:17 -08001416 case HAL_PIXEL_FORMAT_RGBA_1010102:
Mathias Agopiandd533712013-07-26 15:31:39 -07001417 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001418 }
1419 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001420 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001421}
1422
Mathias Agopian13127d82013-03-05 17:47:11 -08001423// ----------------------------------------------------------------------------
1424// local state
1425// ----------------------------------------------------------------------------
1426
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001427static void boundPoint(vec2* point, const Rect& crop) {
1428 if (point->x < crop.left) {
1429 point->x = crop.left;
1430 }
1431 if (point->x > crop.right) {
1432 point->x = crop.right;
1433 }
1434 if (point->y < crop.top) {
1435 point->y = crop.top;
1436 }
1437 if (point->y > crop.bottom) {
1438 point->y = crop.bottom;
1439 }
1440}
1441
chaviwa76b2712017-09-20 12:02:26 -07001442void Layer::computeGeometry(const RenderArea& renderArea, Mesh& mesh,
1443 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001444 const Layer::State& s(getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07001445 const Transform renderAreaTransform(renderArea.getTransform());
1446 const uint32_t height = renderArea.getHeight();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001447 Rect win = computeBounds();
Mathias Agopian3f844832013-08-07 21:24:32 -07001448
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001449 vec2 lt = vec2(win.left, win.top);
1450 vec2 lb = vec2(win.left, win.bottom);
1451 vec2 rb = vec2(win.right, win.bottom);
1452 vec2 rt = vec2(win.right, win.top);
1453
Robert Carr1f0a16a2016-10-24 16:27:39 -07001454 Transform layerTransform = getTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001455 if (!useIdentityTransform) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001456 lt = layerTransform.transform(lt);
1457 lb = layerTransform.transform(lb);
1458 rb = layerTransform.transform(rb);
1459 rt = layerTransform.transform(rt);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001460 }
1461
Robert Carrb5d3d262016-03-25 15:08:13 -07001462 if (!s.finalCrop.isEmpty()) {
1463 boundPoint(&lt, s.finalCrop);
1464 boundPoint(&lb, s.finalCrop);
1465 boundPoint(&rb, s.finalCrop);
1466 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001467 }
1468
Mathias Agopianff2ed702013-09-01 21:36:12 -07001469 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
chaviwa76b2712017-09-20 12:02:26 -07001470 position[0] = renderAreaTransform.transform(lt);
1471 position[1] = renderAreaTransform.transform(lb);
1472 position[2] = renderAreaTransform.transform(rb);
1473 position[3] = renderAreaTransform.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001474 for (size_t i=0 ; i<4 ; i++) {
chaviwa76b2712017-09-20 12:02:26 -07001475 position[i].y = height - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001476 }
1477}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001478
Andy McFadden4125a4f2014-01-29 17:17:11 -08001479bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001480{
neo.hee6fd41d2017-02-17 14:35:33 +08001481 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
Mathias Agopiana67932f2011-04-20 14:20:59 -07001482 // layer's opaque flag.
neo.hee6fd41d2017-02-17 14:35:33 +08001483 if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001484 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001485 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001486
1487 // if the layer has the opaque flag, then we're always opaque,
1488 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001489 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001490}
1491
Dan Stoza23116082015-06-18 14:58:39 -07001492bool Layer::isSecure() const
1493{
1494 const Layer::State& s(mDrawingState);
1495 return (s.flags & layer_state_t::eLayerSecure);
1496}
1497
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001498bool Layer::isProtected() const
1499{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001500 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001501 return (activeBuffer != 0) &&
1502 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1503}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001504
Mathias Agopian13127d82013-03-05 17:47:11 -08001505bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001506 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001507}
1508
1509bool Layer::isCropped() const {
1510 return !mCurrentCrop.isEmpty();
1511}
1512
chaviwa76b2712017-09-20 12:02:26 -07001513bool Layer::needsFiltering(const RenderArea& renderArea) const {
1514 return mNeedsFiltering || renderArea.needsFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -08001515}
1516
1517void Layer::setVisibleRegion(const Region& visibleRegion) {
1518 // always called from main thread
1519 this->visibleRegion = visibleRegion;
1520}
1521
1522void Layer::setCoveredRegion(const Region& coveredRegion) {
1523 // always called from main thread
1524 this->coveredRegion = coveredRegion;
1525}
1526
1527void Layer::setVisibleNonTransparentRegion(const Region&
1528 setVisibleNonTransparentRegion) {
1529 // always called from main thread
1530 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1531}
1532
1533// ----------------------------------------------------------------------------
1534// transaction
1535// ----------------------------------------------------------------------------
1536
Dan Stoza7dde5992015-05-22 09:51:44 -07001537void Layer::pushPendingState() {
1538 if (!mCurrentState.modified) {
1539 return;
1540 }
1541
Dan Stoza7dde5992015-05-22 09:51:44 -07001542 // If this transaction is waiting on the receipt of a frame, generate a sync
1543 // point and send it to the remote layer.
Robert Carr0d480722017-01-10 16:42:54 -08001544 if (mCurrentState.barrierLayer != nullptr) {
1545 sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1546 if (barrierLayer == nullptr) {
1547 ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
Dan Stoza7dde5992015-05-22 09:51:44 -07001548 // If we can't promote the layer we are intended to wait on,
1549 // then it is expired or otherwise invalid. Allow this transaction
1550 // to be applied as per normal (no synchronization).
Robert Carr0d480722017-01-10 16:42:54 -08001551 mCurrentState.barrierLayer = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001552 } else {
1553 auto syncPoint = std::make_shared<SyncPoint>(
1554 mCurrentState.frameNumber);
Robert Carr0d480722017-01-10 16:42:54 -08001555 if (barrierLayer->addSyncPoint(syncPoint)) {
Dan Stozacac35382016-01-27 12:21:06 -08001556 mRemoteSyncPoints.push_back(std::move(syncPoint));
1557 } else {
1558 // We already missed the frame we're supposed to synchronize
1559 // on, so go ahead and apply the state update
Robert Carr0d480722017-01-10 16:42:54 -08001560 mCurrentState.barrierLayer = nullptr;
Dan Stozacac35382016-01-27 12:21:06 -08001561 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001562 }
1563
Dan Stoza7dde5992015-05-22 09:51:44 -07001564 // Wake us up to check if the frame has been received
1565 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001566 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001567 }
1568 mPendingStates.push_back(mCurrentState);
Dan Stozaf7ba41a2017-05-10 15:11:11 -07001569 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
Dan Stoza7dde5992015-05-22 09:51:44 -07001570}
1571
Pablo Ceballos05289c22016-04-14 15:49:55 -07001572void Layer::popPendingState(State* stateToCommit) {
1573 auto oldFlags = stateToCommit->flags;
1574 *stateToCommit = mPendingStates[0];
1575 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1576 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001577
1578 mPendingStates.removeAt(0);
Dan Stozaf7ba41a2017-05-10 15:11:11 -07001579 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
Dan Stoza7dde5992015-05-22 09:51:44 -07001580}
1581
Pablo Ceballos05289c22016-04-14 15:49:55 -07001582bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001583 bool stateUpdateAvailable = false;
1584 while (!mPendingStates.empty()) {
Robert Carr0d480722017-01-10 16:42:54 -08001585 if (mPendingStates[0].barrierLayer != nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001586 if (mRemoteSyncPoints.empty()) {
1587 // If we don't have a sync point for this, apply it anyway. It
1588 // will be visually wrong, but it should keep us from getting
1589 // into too much trouble.
1590 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001591 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001592 stateUpdateAvailable = true;
1593 continue;
1594 }
1595
Dan Stozacac35382016-01-27 12:21:06 -08001596 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1597 mPendingStates[0].frameNumber) {
1598 ALOGE("[%s] Unexpected sync point frame number found",
1599 mName.string());
1600
1601 // Signal our end of the sync point and then dispose of it
1602 mRemoteSyncPoints.front()->setTransactionApplied();
1603 mRemoteSyncPoints.pop_front();
1604 continue;
1605 }
1606
Dan Stoza7dde5992015-05-22 09:51:44 -07001607 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1608 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001609 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001610 stateUpdateAvailable = true;
1611
1612 // Signal our end of the sync point and then dispose of it
1613 mRemoteSyncPoints.front()->setTransactionApplied();
1614 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001615 } else {
1616 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001617 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001618 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001619 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001620 stateUpdateAvailable = true;
1621 }
1622 }
1623
1624 // If we still have pending updates, wake SurfaceFlinger back up and point
1625 // it at this layer so we can process them
1626 if (!mPendingStates.empty()) {
1627 setTransactionFlags(eTransactionNeeded);
1628 mFlinger->setTransactionFlags(eTraversalNeeded);
1629 }
1630
1631 mCurrentState.modified = false;
1632 return stateUpdateAvailable;
1633}
1634
1635void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001636 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001637 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001638 Mutex::Autolock lock(mLocalSyncPointMutex);
1639 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001640 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001641 point->setFrameAvailable();
1642 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001643 }
1644}
1645
Mathias Agopian13127d82013-03-05 17:47:11 -08001646uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001647 ATRACE_CALL();
1648
Dan Stoza7dde5992015-05-22 09:51:44 -07001649 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001650 Layer::State c = getCurrentState();
1651 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001652 return 0;
1653 }
1654
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001655 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001656
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001657 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1658 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001659
1660 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001661 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001662 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001663 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001664 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001665 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001666 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001667 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001668 this, getName().string(), mCurrentTransform,
1669 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001670 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001671 c.crop.left,
1672 c.crop.top,
1673 c.crop.right,
1674 c.crop.bottom,
1675 c.crop.getWidth(),
1676 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001677 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001678 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001679 s.crop.left,
1680 s.crop.top,
1681 s.crop.right,
1682 s.crop.bottom,
1683 s.crop.getWidth(),
1684 s.crop.getHeight(),
1685 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001686
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001687 // record the new size, form this point on, when the client request
1688 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001689 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001690 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001691 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001692
Robert Carre392b552017-09-19 12:16:05 -07001693 // Don't let Layer::doTransaction update the drawing state
1694 // if we have a pending resize, unless we are in fixed-size mode.
1695 // the drawing state will be updated only once we receive a buffer
1696 // with the correct size.
1697 //
1698 // In particular, we want to make sure the clip (which is part
1699 // of the geometry state) is latched together with the size but is
1700 // latched immediately when no resizing is involved.
1701 //
1702 // If a sideband stream is attached, however, we want to skip this
1703 // optimization so that transactions aren't missed when a buffer
1704 // never arrives
1705 //
1706 // In the case that we don't have a buffer we ignore other factors
1707 // and avoid entering the resizePending state. At a high level the
1708 // resizePending state is to avoid applying the state of the new buffer
1709 // to the old buffer. However in the state where we don't have an old buffer
1710 // there is no such concern but we may still be being used as a parent layer.
1711 const bool resizePending = ((c.requested.w != c.active.w) ||
1712 (c.requested.h != c.active.h)) && (mActiveBuffer != nullptr);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001713 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001714 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001715 flags |= eDontUpdateGeometryState;
1716 }
1717 }
1718
Robert Carr7bf247e2017-05-18 14:02:49 -07001719 // Here we apply various requested geometry states, depending on our
1720 // latching configuration. See Layer.h for a detailed discussion of
1721 // how geometry latching is controlled.
1722 if (!(flags & eDontUpdateGeometryState)) {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001723 Layer::State& editCurrentState(getCurrentState());
Robert Carr7bf247e2017-05-18 14:02:49 -07001724
1725 // If mFreezeGeometryUpdates is true we are in the setGeometryAppliesWithResize
1726 // mode, which causes attributes which normally latch regardless of scaling mode,
1727 // to be delayed. We copy the requested state to the active state making sure
1728 // to respect these rules (again see Layer.h for a detailed discussion).
1729 //
1730 // There is an awkward asymmetry in the handling of the crop states in the position
1731 // states, as can be seen below. Largely this arises from position and transform
1732 // being stored in the same data structure while having different latching rules.
1733 // b/38182305
1734 //
1735 // Careful that "c" and editCurrentState may not begin as equivalent due to
1736 // applyPendingStates in the presence of deferred transactions.
1737 if (mFreezeGeometryUpdates) {
Robert Carr82364e32016-05-15 11:27:47 -07001738 float tx = c.active.transform.tx();
1739 float ty = c.active.transform.ty();
1740 c.active = c.requested;
1741 c.active.transform.set(tx, ty);
1742 editCurrentState.active = c.active;
1743 } else {
1744 editCurrentState.active = editCurrentState.requested;
1745 c.active = c.requested;
1746 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001747 }
1748
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001749 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001750 // invalidate and recompute the visible regions if needed
1751 flags |= Layer::eVisibleRegion;
1752 }
1753
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001754 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001755 // invalidate and recompute the visible regions if needed
1756 flags |= eVisibleRegion;
1757 this->contentDirty = true;
1758
1759 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001760 const uint8_t type = c.active.transform.getType();
1761 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001762 (type >= Transform::SCALE));
1763 }
1764
Dan Stozac8145172016-04-28 16:29:06 -07001765 // If the layer is hidden, signal and clear out all local sync points so
1766 // that transactions for layers depending on this layer's frames becoming
1767 // visible are not blocked
1768 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001769 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001770 }
1771
Mathias Agopian13127d82013-03-05 17:47:11 -08001772 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001773 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001774 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001775}
1776
Pablo Ceballos05289c22016-04-14 15:49:55 -07001777void Layer::commitTransaction(const State& stateToCommit) {
1778 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001779}
1780
Mathias Agopian13127d82013-03-05 17:47:11 -08001781uint32_t Layer::getTransactionFlags(uint32_t flags) {
1782 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1783}
1784
1785uint32_t Layer::setTransactionFlags(uint32_t flags) {
1786 return android_atomic_or(flags, &mTransactionFlags);
1787}
1788
Robert Carr82364e32016-05-15 11:27:47 -07001789bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001790 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001791 return false;
1792 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001793
1794 // We update the requested and active position simultaneously because
1795 // we want to apply the position portion of the transform matrix immediately,
1796 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001797 mCurrentState.requested.transform.set(x, y);
Robert Carr7bf247e2017-05-18 14:02:49 -07001798 if (immediate && !mFreezeGeometryUpdates) {
1799 // Here we directly update the active state
1800 // unlike other setters, because we store it within
1801 // the transform, but use different latching rules.
1802 // b/38182305
Robert Carr82364e32016-05-15 11:27:47 -07001803 mCurrentState.active.transform.set(x, y);
1804 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001805 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001806
Dan Stoza7dde5992015-05-22 09:51:44 -07001807 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001808 setTransactionFlags(eTransactionNeeded);
1809 return true;
1810}
Robert Carr82364e32016-05-15 11:27:47 -07001811
Robert Carr1f0a16a2016-10-24 16:27:39 -07001812bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1813 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1814 if (idx < 0) {
1815 return false;
1816 }
1817 if (childLayer->setLayer(z)) {
1818 mCurrentChildren.removeAt(idx);
1819 mCurrentChildren.add(childLayer);
1820 }
1821 return true;
1822}
1823
Robert Carrae060832016-11-28 10:51:00 -08001824bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001825 if (mCurrentState.z == z)
1826 return false;
1827 mCurrentState.sequence++;
1828 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001829 mCurrentState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001830
1831 // Discard all relative layering.
1832 if (mCurrentState.zOrderRelativeOf != nullptr) {
1833 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1834 if (strongRelative != nullptr) {
1835 strongRelative->removeZOrderRelative(this);
1836 }
1837 mCurrentState.zOrderRelativeOf = nullptr;
1838 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001839 setTransactionFlags(eTransactionNeeded);
1840 return true;
1841}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001842
Robert Carrdb66e622017-04-10 16:55:57 -07001843void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1844 mCurrentState.zOrderRelatives.remove(relative);
1845 mCurrentState.sequence++;
1846 mCurrentState.modified = true;
1847 setTransactionFlags(eTransactionNeeded);
1848}
1849
1850void Layer::addZOrderRelative(const wp<Layer>& relative) {
1851 mCurrentState.zOrderRelatives.add(relative);
1852 mCurrentState.modified = true;
1853 mCurrentState.sequence++;
1854 setTransactionFlags(eTransactionNeeded);
1855}
1856
1857bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1858 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1859 if (handle == nullptr) {
1860 return false;
1861 }
1862 sp<Layer> relative = handle->owner.promote();
1863 if (relative == nullptr) {
1864 return false;
1865 }
1866
1867 mCurrentState.sequence++;
1868 mCurrentState.modified = true;
1869 mCurrentState.z = z;
1870
1871 mCurrentState.zOrderRelativeOf = relative;
1872 relative->addZOrderRelative(this);
1873
1874 setTransactionFlags(eTransactionNeeded);
1875
1876 return true;
1877}
1878
Mathias Agopian13127d82013-03-05 17:47:11 -08001879bool Layer::setSize(uint32_t w, uint32_t h) {
1880 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1881 return false;
1882 mCurrentState.requested.w = w;
1883 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001884 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001885 setTransactionFlags(eTransactionNeeded);
1886 return true;
1887}
Dan Stoza9e56aa02015-11-02 13:00:03 -08001888bool Layer::setAlpha(float alpha) {
chaviw13fdc492017-06-27 12:40:18 -07001889 if (mCurrentState.color.a == alpha)
Mathias Agopian13127d82013-03-05 17:47:11 -08001890 return false;
1891 mCurrentState.sequence++;
chaviw13fdc492017-06-27 12:40:18 -07001892 mCurrentState.color.a = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001893 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001894 setTransactionFlags(eTransactionNeeded);
1895 return true;
1896}
chaviw13fdc492017-06-27 12:40:18 -07001897
1898bool Layer::setColor(const half3& color) {
1899 if (color.r == mCurrentState.color.r && color.g == mCurrentState.color.g
1900 && color.b == mCurrentState.color.b)
1901 return false;
1902
1903 mCurrentState.sequence++;
1904 mCurrentState.color.r = color.r;
1905 mCurrentState.color.g = color.g;
1906 mCurrentState.color.b = color.b;
1907 mCurrentState.modified = true;
1908 setTransactionFlags(eTransactionNeeded);
1909 return true;
1910}
1911
Mathias Agopian13127d82013-03-05 17:47:11 -08001912bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1913 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001914 mCurrentState.requested.transform.set(
Robert Carrcb6e1e32017-02-21 19:48:26 -08001915 matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001916 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001917 setTransactionFlags(eTransactionNeeded);
1918 return true;
1919}
1920bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001921 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001922 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001923 setTransactionFlags(eTransactionNeeded);
1924 return true;
1925}
1926bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1927 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1928 if (mCurrentState.flags == newFlags)
1929 return false;
1930 mCurrentState.sequence++;
1931 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001932 mCurrentState.mask = mask;
1933 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001934 setTransactionFlags(eTransactionNeeded);
1935 return true;
1936}
Robert Carr99e27f02016-06-16 15:18:02 -07001937
1938bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001939 if (mCurrentState.requestedCrop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001940 return false;
1941 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001942 mCurrentState.requestedCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001943 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr99e27f02016-06-16 15:18:02 -07001944 mCurrentState.crop = crop;
1945 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001946 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1947
Dan Stoza7dde5992015-05-22 09:51:44 -07001948 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001949 setTransactionFlags(eTransactionNeeded);
1950 return true;
1951}
Robert Carr8d5227b2017-03-16 15:41:03 -07001952
1953bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001954 if (mCurrentState.requestedFinalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001955 return false;
1956 mCurrentState.sequence++;
Robert Carr8d5227b2017-03-16 15:41:03 -07001957 mCurrentState.requestedFinalCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001958 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr8d5227b2017-03-16 15:41:03 -07001959 mCurrentState.finalCrop = crop;
1960 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001961 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1962
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001963 mCurrentState.modified = true;
1964 setTransactionFlags(eTransactionNeeded);
1965 return true;
1966}
Mathias Agopian13127d82013-03-05 17:47:11 -08001967
Robert Carrc3574f72016-03-24 12:19:32 -07001968bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1969 if (scalingMode == mOverrideScalingMode)
1970 return false;
1971 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001972 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001973 return true;
1974}
1975
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001976void Layer::setInfo(uint32_t type, uint32_t appId) {
1977 mCurrentState.appId = appId;
1978 mCurrentState.type = type;
1979 mCurrentState.modified = true;
1980 setTransactionFlags(eTransactionNeeded);
1981}
1982
Robert Carrc3574f72016-03-24 12:19:32 -07001983uint32_t Layer::getEffectiveScalingMode() const {
1984 if (mOverrideScalingMode >= 0) {
1985 return mOverrideScalingMode;
1986 }
1987 return mCurrentScalingMode;
1988}
1989
Mathias Agopian13127d82013-03-05 17:47:11 -08001990bool Layer::setLayerStack(uint32_t layerStack) {
1991 if (mCurrentState.layerStack == layerStack)
1992 return false;
1993 mCurrentState.sequence++;
1994 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001995 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001996 setTransactionFlags(eTransactionNeeded);
1997 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001998}
1999
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002000bool Layer::setDataSpace(android_dataspace dataSpace) {
2001 if (mCurrentState.dataSpace == dataSpace)
2002 return false;
2003 mCurrentState.sequence++;
2004 mCurrentState.dataSpace = dataSpace;
2005 mCurrentState.modified = true;
2006 setTransactionFlags(eTransactionNeeded);
2007 return true;
2008}
2009
Courtney Goeltzenleuchter532b2632017-05-05 16:34:38 -06002010android_dataspace Layer::getDataSpace() const {
2011 return mCurrentState.dataSpace;
2012}
2013
Robert Carr1f0a16a2016-10-24 16:27:39 -07002014uint32_t Layer::getLayerStack() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002015 auto p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002016 if (p == nullptr) {
2017 return getDrawingState().layerStack;
2018 }
2019 return p->getLayerStack();
2020}
2021
Robert Carr0d480722017-01-10 16:42:54 -08002022void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
Dan Stoza7dde5992015-05-22 09:51:44 -07002023 uint64_t frameNumber) {
Robert Carr0d480722017-01-10 16:42:54 -08002024 mCurrentState.barrierLayer = barrierLayer;
Dan Stoza7dde5992015-05-22 09:51:44 -07002025 mCurrentState.frameNumber = frameNumber;
2026 // We don't set eTransactionNeeded, because just receiving a deferral
2027 // request without any other state updates shouldn't actually induce a delay
2028 mCurrentState.modified = true;
2029 pushPendingState();
Robert Carr0d480722017-01-10 16:42:54 -08002030 mCurrentState.barrierLayer = nullptr;
Dan Stoza792e5292016-02-11 11:43:58 -08002031 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07002032 mCurrentState.modified = false;
Robert Carr0d480722017-01-10 16:42:54 -08002033}
2034
2035void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
2036 uint64_t frameNumber) {
2037 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
2038 deferTransactionUntil(handle->owner.promote(), frameNumber);
Dan Stoza7dde5992015-05-22 09:51:44 -07002039}
2040
Dan Stozaee44edd2015-03-23 15:50:23 -07002041void Layer::useSurfaceDamage() {
2042 if (mFlinger->mForceFullDamage) {
2043 surfaceDamageRegion = Region::INVALID_REGION;
2044 } else {
2045 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
2046 }
2047}
2048
2049void Layer::useEmptyDamage() {
2050 surfaceDamageRegion.clear();
2051}
2052
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002053// ----------------------------------------------------------------------------
2054// pageflip handling...
2055// ----------------------------------------------------------------------------
2056
Dan Stoza6b9454d2014-11-07 16:00:59 -08002057bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08002058 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07002059 return true;
2060 }
2061
Dan Stoza6b9454d2014-11-07 16:00:59 -08002062 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07002063 if (mQueueItems.empty()) {
2064 return false;
2065 }
2066 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002067 nsecs_t expectedPresent =
2068 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07002069
2070 // Ignore timestamps more than a second in the future
2071 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
2072 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
2073 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
2074 expectedPresent);
2075
2076 bool isDue = timestamp < expectedPresent;
2077 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002078}
2079
Brian Andersond6927fb2016-07-23 23:37:30 -07002080bool Layer::onPreComposition(nsecs_t refreshStartTime) {
2081 if (mBufferLatched) {
2082 Mutex::Autolock lock(mFrameEventHistoryMutex);
2083 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
2084 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08002085 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08002086 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002087}
2088
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002089bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
Brian Anderson3d4039d2016-09-23 16:31:30 -07002090 const std::shared_ptr<FenceTime>& presentFence,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002091 const CompositorTiming& compositorTiming) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002092 // mFrameLatencyNeeded is true when a new frame was latched for the
2093 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08002094 if (!mFrameLatencyNeeded)
2095 return false;
2096
Fabien Sanglard28e98082016-12-05 10:19:46 -08002097 // Update mFrameEventHistory.
2098 {
2099 Mutex::Autolock lock(mFrameEventHistoryMutex);
2100 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002101 glDoneFence, presentFence, compositorTiming);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002102 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08002103
2104 // Update mFrameTracker.
2105 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
2106 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
2107
Brian Anderson3d4039d2016-09-23 16:31:30 -07002108 std::shared_ptr<FenceTime> frameReadyFence =
2109 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08002110 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002111 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002112 } else {
2113 // There was no fence for this frame, so assume that it was ready
2114 // to be presented at the desired present time.
2115 mFrameTracker.setFrameReadyTime(desiredPresentTime);
2116 }
2117
Brian Anderson3d4039d2016-09-23 16:31:30 -07002118 if (presentFence->isValid()) {
2119 mFrameTracker.setActualPresentFence(
2120 std::shared_ptr<FenceTime>(presentFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002121 } else {
2122 // The HWC doesn't support present fences, so use the refresh
2123 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002124 mFrameTracker.setActualPresentTime(
2125 mFlinger->getHwComposer().getRefreshTimestamp(
2126 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002127 }
2128
2129 mFrameTracker.advanceFrame();
2130 mFrameLatencyNeeded = false;
2131 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002132}
2133
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002134#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07002135void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Brian Anderson5ea5e592016-12-01 16:54:33 -08002136 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2137 return;
2138 }
2139
Brian Anderson3d4039d2016-09-23 16:31:30 -07002140 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002141 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002142 mReleaseTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002143 mReleaseTimeline.push(releaseFenceTime);
2144
2145 Mutex::Autolock lock(mFrameEventHistoryMutex);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002146 if (mPreviousFrameNumber != 0) {
2147 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2148 dequeueReadyTime, std::move(releaseFenceTime));
2149 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002150}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002151#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002152
Robert Carr1f0a16a2016-10-24 16:27:39 -07002153bool Layer::isHiddenByPolicy() const {
2154 const Layer::State& s(mDrawingState);
Chia-I Wue41dbe62017-06-13 14:10:56 -07002155 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002156 if (parent != nullptr && parent->isHiddenByPolicy()) {
2157 return true;
2158 }
2159 return s.flags & layer_state_t::eLayerHidden;
2160}
2161
Mathias Agopianda27af92012-09-13 18:17:13 -07002162bool Layer::isVisible() const {
Robert Carr6452f122017-03-21 10:41:29 -07002163 return !(isHiddenByPolicy()) && getAlpha() > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08002164 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Mathias Agopianda27af92012-09-13 18:17:13 -07002165}
2166
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002167bool Layer::allTransactionsSignaled() {
2168 auto headFrameNumber = getHeadFrameNumber();
2169 bool matchingFramesFound = false;
2170 bool allTransactionsApplied = true;
2171 Mutex::Autolock lock(mLocalSyncPointMutex);
2172
2173 for (auto& point : mLocalSyncPoints) {
2174 if (point->getFrameNumber() > headFrameNumber) {
2175 break;
2176 }
2177 matchingFramesFound = true;
2178
2179 if (!point->frameIsAvailable()) {
2180 // We haven't notified the remote layer that the frame for
2181 // this point is available yet. Notify it now, and then
2182 // abort this attempt to latch.
2183 point->setFrameAvailable();
2184 allTransactionsApplied = false;
2185 break;
2186 }
2187
2188 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2189 }
2190 return !matchingFramesFound || allTransactionsApplied;
2191}
2192
Brian Andersond6927fb2016-07-23 23:37:30 -07002193Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002194{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08002195 ATRACE_CALL();
2196
Jesse Hall399184a2014-03-03 15:42:54 -08002197 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2198 // mSidebandStreamChanged was true
2199 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07002200 if (mSidebandStream != NULL) {
2201 setTransactionFlags(eTransactionNeeded);
2202 mFlinger->setTransactionFlags(eTraversalNeeded);
2203 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07002204 recomputeVisibleRegions = true;
2205
2206 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07002207 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08002208 }
2209
Mathias Agopian4fec8732012-06-29 14:12:52 -07002210 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07002211 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2212 return outDirtyRegion;
2213 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002214
Fabien Sanglard223eb912016-10-13 10:15:06 -07002215 // if we've already called updateTexImage() without going through
2216 // a composition step, we have to skip this layer at this point
2217 // because we cannot call updateTeximage() without a corresponding
2218 // compositionComplete() call.
2219 // we'll trigger an update in onPreComposition().
2220 if (mRefreshPending) {
2221 return outDirtyRegion;
2222 }
2223
2224 // If the head buffer's acquire fence hasn't signaled yet, return and
2225 // try again later
2226 if (!headFenceHasSignaled()) {
2227 mFlinger->signalLayerUpdate();
2228 return outDirtyRegion;
2229 }
2230
2231 // Capture the old state of the layer for comparisons later
2232 const State& s(getDrawingState());
2233 const bool oldOpacity = isOpaque(s);
2234 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2235
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002236 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002237 mFlinger->signalLayerUpdate();
2238 return outDirtyRegion;
2239 }
2240
2241 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2242 // of the buffer queue isn't modified when the buffer queue is returning
2243 // BufferItem's that weren't actually queued. This can happen in shared
2244 // buffer mode.
2245 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002246 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2247 getProducerStickyTransform() != 0, mName.string(),
Robert Carr7bf247e2017-05-18 14:02:49 -07002248 mOverrideScalingMode, mFreezeGeometryUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002249 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2250 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2251 mLastFrameNumberReceived);
2252 if (updateResult == BufferQueue::PRESENT_LATER) {
2253 // Producer doesn't want buffer to be displayed yet. Signal a
2254 // layer update so we check again at the next opportunity.
2255 mFlinger->signalLayerUpdate();
2256 return outDirtyRegion;
2257 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2258 // If the buffer has been rejected, remove it from the shadow queue
2259 // and return early
2260 if (queuedBuffer) {
2261 Mutex::Autolock lock(mQueueItemLock);
2262 mQueueItems.removeAt(0);
2263 android_atomic_dec(&mQueuedFrames);
2264 }
2265 return outDirtyRegion;
2266 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2267 // This can occur if something goes wrong when trying to create the
2268 // EGLImage for this buffer. If this happens, the buffer has already
2269 // been released, so we need to clean up the queue and bug out
2270 // early.
2271 if (queuedBuffer) {
2272 Mutex::Autolock lock(mQueueItemLock);
2273 mQueueItems.clear();
2274 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002275 }
2276
Fabien Sanglard223eb912016-10-13 10:15:06 -07002277 // Once we have hit this state, the shadow queue may no longer
2278 // correctly reflect the incoming BufferQueue's contents, so even if
2279 // updateTexImage starts working, the only safe course of action is
2280 // to continue to ignore updates.
2281 mUpdateTexImageFailed = true;
2282
2283 return outDirtyRegion;
2284 }
2285
2286 if (queuedBuffer) {
2287 // Autolock scope
2288 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2289
2290 Mutex::Autolock lock(mQueueItemLock);
2291
2292 // Remove any stale buffers that have been dropped during
2293 // updateTexImage
2294 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2295 mQueueItems.removeAt(0);
2296 android_atomic_dec(&mQueuedFrames);
2297 }
2298
2299 mQueueItems.removeAt(0);
2300 }
2301
2302
2303 // Decrement the queued-frames count. Signal another event if we
2304 // have more frames pending.
2305 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2306 || mAutoRefresh) {
2307 mFlinger->signalLayerUpdate();
2308 }
2309
Fabien Sanglard223eb912016-10-13 10:15:06 -07002310 // update the active buffer
Chia-I Wu06d63de2017-01-04 14:58:51 +08002311 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2312 &mActiveBufferSlot);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002313 if (mActiveBuffer == NULL) {
2314 // this can only happen if the very first buffer was rejected.
2315 return outDirtyRegion;
2316 }
2317
Brian Andersond6927fb2016-07-23 23:37:30 -07002318 mBufferLatched = true;
2319 mPreviousFrameNumber = mCurrentFrameNumber;
2320 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2321
2322 {
2323 Mutex::Autolock lock(mFrameEventHistoryMutex);
2324 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2325#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002326 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002327 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002328 mReleaseTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002329 mReleaseTimeline.push(releaseFenceTime);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002330 if (mPreviousFrameNumber != 0) {
2331 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2332 latchTime, std::move(releaseFenceTime));
2333 }
Brian Andersond6927fb2016-07-23 23:37:30 -07002334#endif
2335 }
2336
Fabien Sanglard223eb912016-10-13 10:15:06 -07002337 mRefreshPending = true;
2338 mFrameLatencyNeeded = true;
2339 if (oldActiveBuffer == NULL) {
2340 // the first time we receive a buffer, we need to trigger a
2341 // geometry invalidation.
2342 recomputeVisibleRegions = true;
2343 }
2344
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002345 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2346
Fabien Sanglard223eb912016-10-13 10:15:06 -07002347 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2348 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2349 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2350 if ((crop != mCurrentCrop) ||
2351 (transform != mCurrentTransform) ||
2352 (scalingMode != mCurrentScalingMode))
2353 {
2354 mCurrentCrop = crop;
2355 mCurrentTransform = transform;
2356 mCurrentScalingMode = scalingMode;
2357 recomputeVisibleRegions = true;
2358 }
2359
2360 if (oldActiveBuffer != NULL) {
2361 uint32_t bufWidth = mActiveBuffer->getWidth();
2362 uint32_t bufHeight = mActiveBuffer->getHeight();
2363 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2364 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002365 recomputeVisibleRegions = true;
2366 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002367 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002368
Fabien Sanglard223eb912016-10-13 10:15:06 -07002369 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2370 if (oldOpacity != isOpaque(s)) {
2371 recomputeVisibleRegions = true;
2372 }
Dan Stozacac35382016-01-27 12:21:06 -08002373
Fabien Sanglard223eb912016-10-13 10:15:06 -07002374 // Remove any sync points corresponding to the buffer which was just
2375 // latched
2376 {
2377 Mutex::Autolock lock(mLocalSyncPointMutex);
2378 auto point = mLocalSyncPoints.begin();
2379 while (point != mLocalSyncPoints.end()) {
2380 if (!(*point)->frameIsAvailable() ||
2381 !(*point)->transactionIsApplied()) {
2382 // This sync point must have been added since we started
2383 // latching. Don't drop it yet.
2384 ++point;
2385 continue;
2386 }
2387
2388 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2389 point = mLocalSyncPoints.erase(point);
2390 } else {
2391 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002392 }
2393 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002394 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002395
2396 // FIXME: postedRegion should be dirty & bounds
2397 Region dirtyRegion(Rect(s.active.w, s.active.h));
2398
2399 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002400 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002401
Mathias Agopian4fec8732012-06-29 14:12:52 -07002402 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002403}
2404
Mathias Agopiana67932f2011-04-20 14:20:59 -07002405uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002406{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002407 // TODO: should we do something special if mSecure is set?
2408 if (mProtectedByApp) {
2409 // need a hardware-protected path to external video sink
2410 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002411 }
Riley Andrews03414a12014-07-01 14:22:59 -07002412 if (mPotentialCursor) {
2413 usage |= GraphicBuffer::USAGE_CURSOR;
2414 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002415 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002416 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002417}
2418
Mathias Agopian84300952012-11-21 16:02:13 -08002419void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002420 uint32_t orientation = 0;
2421 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002422 // The transform hint is used to improve performance, but we can
2423 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002424 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002425 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002426 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002427 if (orientation & Transform::ROT_INVALID) {
2428 orientation = 0;
2429 }
2430 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002431 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002432}
2433
Mathias Agopian13127d82013-03-05 17:47:11 -08002434// ----------------------------------------------------------------------------
2435// debugging
2436// ----------------------------------------------------------------------------
2437
Kalle Raitaa099a242017-01-11 11:17:29 -08002438LayerDebugInfo Layer::getLayerDebugInfo() const {
2439 LayerDebugInfo info;
2440 const Layer::State& ds = getDrawingState();
2441 info.mName = getName();
chaviw1acbec72017-07-27 15:28:26 -07002442 sp<Layer> parent = getParent();
Kalle Raitaa099a242017-01-11 11:17:29 -08002443 info.mParentName = (parent == nullptr ? std::string("none") : parent->getName().string());
2444 info.mType = String8(getTypeId());
2445 info.mTransparentRegion = ds.activeTransparentRegion;
2446 info.mVisibleRegion = visibleRegion;
2447 info.mSurfaceDamageRegion = surfaceDamageRegion;
2448 info.mLayerStack = getLayerStack();
2449 info.mX = ds.active.transform.tx();
2450 info.mY = ds.active.transform.ty();
2451 info.mZ = ds.z;
2452 info.mWidth = ds.active.w;
2453 info.mHeight = ds.active.h;
2454 info.mCrop = ds.crop;
2455 info.mFinalCrop = ds.finalCrop;
chaviw13fdc492017-06-27 12:40:18 -07002456 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08002457 info.mFlags = ds.flags;
2458 info.mPixelFormat = getPixelFormat();
2459 info.mDataSpace = getDataSpace();
2460 info.mMatrix[0][0] = ds.active.transform[0][0];
2461 info.mMatrix[0][1] = ds.active.transform[0][1];
2462 info.mMatrix[1][0] = ds.active.transform[1][0];
2463 info.mMatrix[1][1] = ds.active.transform[1][1];
2464 {
2465 sp<const GraphicBuffer> activeBuffer = getActiveBuffer();
2466 if (activeBuffer != 0) {
2467 info.mActiveBufferWidth = activeBuffer->getWidth();
2468 info.mActiveBufferHeight = activeBuffer->getHeight();
2469 info.mActiveBufferStride = activeBuffer->getStride();
2470 info.mActiveBufferFormat = activeBuffer->format;
2471 } else {
2472 info.mActiveBufferWidth = 0;
2473 info.mActiveBufferHeight = 0;
2474 info.mActiveBufferStride = 0;
2475 info.mActiveBufferFormat = 0;
2476 }
Mathias Agopian13127d82013-03-05 17:47:11 -08002477 }
Kalle Raitaa099a242017-01-11 11:17:29 -08002478 info.mNumQueuedFrames = getQueuedFrameCount();
2479 info.mRefreshPending = isBufferLatched();
2480 info.mIsOpaque = isOpaque(ds);
2481 info.mContentDirty = contentDirty;
2482 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08002483}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002484#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002485void Layer::miniDumpHeader(String8& result) {
2486 result.append("----------------------------------------");
2487 result.append("---------------------------------------\n");
2488 result.append(" Layer name\n");
2489 result.append(" Z | ");
2490 result.append(" Comp Type | ");
2491 result.append(" Disp Frame (LTRB) | ");
2492 result.append(" Source Crop (LTRB)\n");
2493 result.append("----------------------------------------");
2494 result.append("---------------------------------------\n");
2495}
2496
2497void Layer::miniDump(String8& result, int32_t hwcId) const {
2498 if (mHwcLayers.count(hwcId) == 0) {
2499 return;
2500 }
2501
2502 String8 name;
2503 if (mName.length() > 77) {
2504 std::string shortened;
2505 shortened.append(mName.string(), 36);
2506 shortened.append("[...]");
2507 shortened.append(mName.string() + (mName.length() - 36), 36);
2508 name = shortened.c_str();
2509 } else {
2510 name = mName;
2511 }
2512
2513 result.appendFormat(" %s\n", name.string());
2514
2515 const Layer::State& layerState(getDrawingState());
2516 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
John Reck8c3b6ac2017-08-24 10:25:42 -07002517 result.appendFormat(" %10d | ", layerState.z);
Dan Stozae22aec72016-08-01 13:20:59 -07002518 result.appendFormat("%10s | ",
2519 to_string(getCompositionType(hwcId)).c_str());
2520 const Rect& frame = hwcInfo.displayFrame;
2521 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2522 frame.right, frame.bottom);
Dan Stoza5a423ea2017-02-16 14:10:39 -08002523 const FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002524 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2525 crop.right, crop.bottom);
2526
2527 result.append("- - - - - - - - - - - - - - - - - - - - ");
2528 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2529}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002530#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002531
Svetoslavd85084b2014-03-20 10:28:31 -07002532void Layer::dumpFrameStats(String8& result) const {
2533 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002534}
2535
Svetoslavd85084b2014-03-20 10:28:31 -07002536void Layer::clearFrameStats() {
2537 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002538}
2539
Jamie Gennis6547ff42013-07-16 20:12:42 -07002540void Layer::logFrameStats() {
2541 mFrameTracker.logAndResetStats(mName);
2542}
2543
Svetoslavd85084b2014-03-20 10:28:31 -07002544void Layer::getFrameStats(FrameStats* outStats) const {
2545 mFrameTracker.getStats(outStats);
2546}
2547
Brian Andersond6927fb2016-07-23 23:37:30 -07002548void Layer::dumpFrameEvents(String8& result) {
2549 result.appendFormat("- Layer %s (%s, %p)\n",
2550 getName().string(), getTypeId(), this);
2551 Mutex::Autolock lock(mFrameEventHistoryMutex);
2552 mFrameEventHistory.checkFencesForCompletion();
2553 mFrameEventHistory.dump(result);
2554}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002555
Brian Anderson5ea5e592016-12-01 16:54:33 -08002556void Layer::onDisconnect() {
2557 Mutex::Autolock lock(mFrameEventHistoryMutex);
2558 mFrameEventHistory.onDisconnect();
2559}
2560
Brian Anderson3890c392016-07-25 12:48:08 -07002561void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2562 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002563 Mutex::Autolock lock(mFrameEventHistoryMutex);
2564 if (newTimestamps) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002565 // If there are any unsignaled fences in the aquire timeline at this
2566 // point, the previously queued frame hasn't been latched yet. Go ahead
2567 // and try to get the signal time here so the syscall is taken out of
2568 // the main thread's critical path.
2569 mAcquireTimeline.updateSignalTimes();
2570 // Push the new fence after updating since it's likely still pending.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002571 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002572 mFrameEventHistory.addQueue(*newTimestamps);
2573 }
2574
Brian Anderson3890c392016-07-25 12:48:08 -07002575 if (outDelta) {
2576 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002577 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002578}
Dan Stozae77c7662016-05-13 11:37:28 -07002579
2580std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2581 bool forceFlush) {
2582 std::vector<OccupancyTracker::Segment> history;
2583 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2584 &history);
2585 if (result != NO_ERROR) {
2586 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2587 result);
2588 return {};
2589 }
2590 return history;
2591}
2592
Robert Carr367c5682016-06-20 11:55:28 -07002593bool Layer::getTransformToDisplayInverse() const {
2594 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2595}
2596
Chia-I Wu98f1c102017-05-30 14:54:08 -07002597size_t Layer::getChildrenCount() const {
2598 size_t count = 0;
2599 for (const sp<Layer>& child : mCurrentChildren) {
2600 count += 1 + child->getChildrenCount();
2601 }
2602 return count;
2603}
2604
Robert Carr1f0a16a2016-10-24 16:27:39 -07002605void Layer::addChild(const sp<Layer>& layer) {
2606 mCurrentChildren.add(layer);
2607 layer->setParent(this);
2608}
2609
2610ssize_t Layer::removeChild(const sp<Layer>& layer) {
2611 layer->setParent(nullptr);
2612 return mCurrentChildren.remove(layer);
2613}
2614
Robert Carr1db73f62016-12-21 12:58:51 -08002615bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2616 sp<Handle> handle = nullptr;
2617 sp<Layer> newParent = nullptr;
2618 if (newParentHandle == nullptr) {
2619 return false;
2620 }
2621 handle = static_cast<Handle*>(newParentHandle.get());
2622 newParent = handle->owner.promote();
2623 if (newParent == nullptr) {
2624 ALOGE("Unable to promote Layer handle");
2625 return false;
2626 }
2627
2628 for (const sp<Layer>& child : mCurrentChildren) {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002629 newParent->addChild(child);
Robert Carr1db73f62016-12-21 12:58:51 -08002630
2631 sp<Client> client(child->mClientRef.promote());
2632 if (client != nullptr) {
2633 client->setParentLayer(newParent);
2634 }
2635 }
2636 mCurrentChildren.clear();
2637
2638 return true;
2639}
2640
chaviwf1961f72017-09-18 16:41:07 -07002641bool Layer::reparent(const sp<IBinder>& newParentHandle) {
2642 if (newParentHandle == nullptr) {
chaviw06178942017-07-27 10:25:59 -07002643 return false;
2644 }
2645
2646 auto handle = static_cast<Handle*>(newParentHandle.get());
2647 sp<Layer> newParent = handle->owner.promote();
2648 if (newParent == nullptr) {
2649 ALOGE("Unable to promote Layer handle");
2650 return false;
2651 }
2652
chaviwf1961f72017-09-18 16:41:07 -07002653 sp<Layer> parent = getParent();
2654 if (parent != nullptr) {
2655 parent->removeChild(this);
chaviw06178942017-07-27 10:25:59 -07002656 }
chaviwf1961f72017-09-18 16:41:07 -07002657 newParent->addChild(this);
chaviw06178942017-07-27 10:25:59 -07002658
chaviwf1961f72017-09-18 16:41:07 -07002659 sp<Client> client(mClientRef.promote());
chaviw06178942017-07-27 10:25:59 -07002660 sp<Client> newParentClient(newParent->mClientRef.promote());
2661
chaviwf1961f72017-09-18 16:41:07 -07002662 if (client != newParentClient) {
2663 client->setParentLayer(newParent);
chaviw06178942017-07-27 10:25:59 -07002664 }
2665
chaviw06178942017-07-27 10:25:59 -07002666 return true;
2667}
2668
Robert Carr9524cb32017-02-13 11:32:32 -08002669bool Layer::detachChildren() {
Dan Stoza412903f2017-04-27 13:42:17 -07002670 traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
Robert Carr9524cb32017-02-13 11:32:32 -08002671 if (child == this) {
2672 return;
2673 }
2674
chaviw161410b02017-07-27 10:46:08 -07002675 sp<Client> parentClient = mClientRef.promote();
Robert Carr9524cb32017-02-13 11:32:32 -08002676 sp<Client> client(child->mClientRef.promote());
chaviw161410b02017-07-27 10:46:08 -07002677 if (client != nullptr && parentClient != client) {
Robert Carr9524cb32017-02-13 11:32:32 -08002678 client->detachLayer(child);
2679 }
2680 });
2681
2682 return true;
2683}
2684
Robert Carr1f0a16a2016-10-24 16:27:39 -07002685void Layer::setParent(const sp<Layer>& layer) {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002686 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002687}
2688
2689void Layer::clearSyncPoints() {
2690 for (const auto& child : mCurrentChildren) {
2691 child->clearSyncPoints();
2692 }
2693
2694 Mutex::Autolock lock(mLocalSyncPointMutex);
2695 for (auto& point : mLocalSyncPoints) {
2696 point->setFrameAvailable();
2697 }
2698 mLocalSyncPoints.clear();
2699}
2700
2701int32_t Layer::getZ() const {
2702 return mDrawingState.z;
2703}
2704
Ivan Lozano80de6f32017-10-30 11:24:08 -07002705__attribute__((no_sanitize("unsigned-integer-overflow")))
Dan Stoza412903f2017-04-27 13:42:17 -07002706LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2707 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2708 "makeTraversalList received invalid stateSet");
2709 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2710 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2711 const State& state = useDrawing ? mDrawingState : mCurrentState;
2712
2713 if (state.zOrderRelatives.size() == 0) {
2714 return children;
Robert Carrdb66e622017-04-10 16:55:57 -07002715 }
2716 LayerVector traverse;
2717
Dan Stoza412903f2017-04-27 13:42:17 -07002718 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07002719 sp<Layer> strongRelative = weakRelative.promote();
2720 if (strongRelative != nullptr) {
2721 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07002722 }
2723 }
2724
Dan Stoza412903f2017-04-27 13:42:17 -07002725 for (const sp<Layer>& child : children) {
Robert Carrdb66e622017-04-10 16:55:57 -07002726 traverse.add(child);
2727 }
2728
2729 return traverse;
2730}
2731
Robert Carr1f0a16a2016-10-24 16:27:39 -07002732/**
Robert Carrdb66e622017-04-10 16:55:57 -07002733 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002734 */
Dan Stoza412903f2017-04-27 13:42:17 -07002735void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2736 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002737
Robert Carr1f0a16a2016-10-24 16:27:39 -07002738 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002739 for (; i < list.size(); i++) {
2740 const auto& relative = list[i];
2741 if (relative->getZ() >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002742 break;
Robert Carrdb66e622017-04-10 16:55:57 -07002743 }
Dan Stoza412903f2017-04-27 13:42:17 -07002744 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002745 }
Dan Stoza412903f2017-04-27 13:42:17 -07002746 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07002747 for (; i < list.size(); i++) {
2748 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002749 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002750 }
2751}
2752
2753/**
Robert Carrdb66e622017-04-10 16:55:57 -07002754 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002755 */
Dan Stoza412903f2017-04-27 13:42:17 -07002756void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2757 const LayerVector::Visitor& visitor) {
2758 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002759
Robert Carr1f0a16a2016-10-24 16:27:39 -07002760 int32_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002761 for (i = list.size()-1; i>=0; i--) {
2762 const auto& relative = list[i];
2763 if (relative->getZ() < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002764 break;
2765 }
Dan Stoza412903f2017-04-27 13:42:17 -07002766 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002767 }
Dan Stoza412903f2017-04-27 13:42:17 -07002768 visitor(this);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002769 for (; i>=0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002770 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002771 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002772 }
2773}
2774
chaviwa76b2712017-09-20 12:02:26 -07002775/**
2776 * Traverse only children in z order, ignoring relative layers.
2777 */
2778void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2779 const LayerVector::Visitor& visitor) {
2780 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2781 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2782
2783 size_t i = 0;
2784 for (; i < children.size(); i++) {
2785 const auto& relative = children[i];
2786 if (relative->getZ() >= 0) {
2787 break;
2788 }
2789 relative->traverseChildrenInZOrder(stateSet, visitor);
2790 }
2791 visitor(this);
2792 for (; i < children.size(); i++) {
2793 const auto& relative = children[i];
2794 relative->traverseChildrenInZOrder(stateSet, visitor);
2795 }
2796}
2797
Robert Carr1f0a16a2016-10-24 16:27:39 -07002798Transform Layer::getTransform() const {
2799 Transform t;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002800 const auto& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002801 if (p != nullptr) {
2802 t = p->getTransform();
Robert Carr9b429f42017-04-17 14:56:57 -07002803
2804 // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2805 // it isFixedSize) then there may be additional scaling not accounted
2806 // for in the transform. We need to mirror this scaling in child surfaces
2807 // or we will break the contract where WM can treat child surfaces as
2808 // pixels in the parent surface.
Chia-I Wu0a68b462017-07-18 11:30:05 -07002809 if (p->isFixedSize() && p->mActiveBuffer != nullptr) {
Robert Carr1725eee2017-04-26 18:32:15 -07002810 int bufferWidth;
2811 int bufferHeight;
2812 if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2813 bufferWidth = p->mActiveBuffer->getWidth();
2814 bufferHeight = p->mActiveBuffer->getHeight();
2815 } else {
2816 bufferHeight = p->mActiveBuffer->getWidth();
2817 bufferWidth = p->mActiveBuffer->getHeight();
2818 }
Robert Carr9b429f42017-04-17 14:56:57 -07002819 float sx = p->getDrawingState().active.w /
Robert Carr1725eee2017-04-26 18:32:15 -07002820 static_cast<float>(bufferWidth);
Robert Carr9b429f42017-04-17 14:56:57 -07002821 float sy = p->getDrawingState().active.h /
Robert Carr1725eee2017-04-26 18:32:15 -07002822 static_cast<float>(bufferHeight);
Robert Carr9b429f42017-04-17 14:56:57 -07002823 Transform extraParentScaling;
2824 extraParentScaling.set(sx, 0, 0, sy);
2825 t = t * extraParentScaling;
2826 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002827 }
2828 return t * getDrawingState().active.transform;
2829}
2830
chaviw13fdc492017-06-27 12:40:18 -07002831half Layer::getAlpha() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002832 const auto& p = mDrawingParent.promote();
Robert Carr6452f122017-03-21 10:41:29 -07002833
chaviw13fdc492017-06-27 12:40:18 -07002834 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2835 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002836}
Robert Carr6452f122017-03-21 10:41:29 -07002837
chaviw13fdc492017-06-27 12:40:18 -07002838half4 Layer::getColor() const {
2839 const half4 color(getDrawingState().color);
2840 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002841}
Robert Carr6452f122017-03-21 10:41:29 -07002842
Robert Carr1f0a16a2016-10-24 16:27:39 -07002843void Layer::commitChildList() {
2844 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2845 const auto& child = mCurrentChildren[i];
2846 child->commitChildList();
2847 }
2848 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002849 mDrawingParent = mCurrentParent;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002850}
2851
chaviw1d044282017-09-27 12:19:28 -07002852void Layer::writeToProto(LayerProto* layerInfo, LayerVector::StateSet stateSet) {
2853 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2854 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2855 const State& state = useDrawing ? mDrawingState : mCurrentState;
2856
2857 Transform requestedTransform = state.active.transform;
2858 Transform transform = getTransform();
2859
2860 layerInfo->set_id(sequence);
2861 layerInfo->set_name(getName().c_str());
2862 layerInfo->set_type(String8(getTypeId()));
2863
2864 for (const auto& child : children) {
2865 layerInfo->add_children(child->sequence);
2866 }
2867
2868 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2869 sp<Layer> strongRelative = weakRelative.promote();
2870 if (strongRelative != nullptr) {
2871 layerInfo->add_relatives(strongRelative->sequence);
2872 }
2873 }
2874
2875 LayerProtoHelper::writeToProto(state.activeTransparentRegion,
2876 layerInfo->mutable_transparent_region());
2877 LayerProtoHelper::writeToProto(visibleRegion, layerInfo->mutable_visible_region());
2878 LayerProtoHelper::writeToProto(surfaceDamageRegion, layerInfo->mutable_damage_region());
2879
2880 layerInfo->set_layer_stack(getLayerStack());
2881 layerInfo->set_z(state.z);
2882
2883 PositionProto* position = layerInfo->mutable_position();
2884 position->set_x(transform.tx());
2885 position->set_y(transform.ty());
2886
2887 PositionProto* requestedPosition = layerInfo->mutable_requested_position();
2888 requestedPosition->set_x(requestedTransform.tx());
2889 requestedPosition->set_y(requestedTransform.ty());
2890
2891 SizeProto* size = layerInfo->mutable_size();
2892 size->set_w(state.active.w);
2893 size->set_h(state.active.h);
2894
2895 LayerProtoHelper::writeToProto(state.crop, layerInfo->mutable_crop());
2896 LayerProtoHelper::writeToProto(state.finalCrop, layerInfo->mutable_final_crop());
2897
2898 layerInfo->set_is_opaque(isOpaque(state));
2899 layerInfo->set_invalidate(contentDirty);
2900 layerInfo->set_dataspace(dataspaceDetails(getDataSpace()));
2901 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2902 LayerProtoHelper::writeToProto(getColor(), layerInfo->mutable_color());
2903 LayerProtoHelper::writeToProto(state.color, layerInfo->mutable_requested_color());
2904 layerInfo->set_flags(state.flags);
2905
2906 LayerProtoHelper::writeToProto(transform, layerInfo->mutable_transform());
2907 LayerProtoHelper::writeToProto(requestedTransform, layerInfo->mutable_requested_transform());
2908
2909 auto parent = getParent();
2910 if (parent != nullptr) {
2911 layerInfo->set_parent(parent->sequence);
2912 }
2913
2914 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2915 if (zOrderRelativeOf != nullptr) {
2916 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2917 }
2918
2919 auto activeBuffer = getActiveBuffer();
2920 if (activeBuffer != nullptr) {
2921 LayerProtoHelper::writeToProto(activeBuffer, layerInfo->mutable_active_buffer());
2922 }
2923
2924 layerInfo->set_queued_frames(getQueuedFrameCount());
2925 layerInfo->set_refresh_pending(isBufferLatched());
2926}
2927
Mathias Agopian13127d82013-03-05 17:47:11 -08002928// ---------------------------------------------------------------------------
2929
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002930}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002931
2932#if defined(__gl_h_)
2933#error "don't include gl/gl.h in this file"
2934#endif
2935
2936#if defined(__gl2_h_)
2937#error "don't include gl2/gl2.h in this file"
2938#endif