blob: 56328c9b3d43045ae456aa162650b81c3e653279 [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),
Mathias Agopiana67932f2011-04-20 14:20:59 -070074 mTextureName(-1U),
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 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700549 return activeCrop;
550}
551
Dan Stoza5a423ea2017-02-16 14:10:39 -0800552FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
Robert Carr1f0a16a2016-10-24 16:27:39 -0700553 // the content crop is the area of the content that gets scaled to the
554 // layer's size. This is in buffer space.
Dan Stoza5a423ea2017-02-16 14:10:39 -0800555 FloatRect crop = getContentCrop().toFloatRect();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700556
557 // In addition there is a WM-specified crop we pull from our drawing state.
558 const State& s(getDrawingState());
559
560 // Screen space to make reduction to parent crop clearer.
561 Rect activeCrop = computeInitialCrop(hw);
Chia-I Wue41dbe62017-06-13 14:10:56 -0700562 const auto& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700563 if (p != nullptr) {
564 auto parentCrop = p->computeInitialCrop(hw);
565 activeCrop.intersect(parentCrop, &activeCrop);
566 }
567 Transform t = getTransform();
568 // Back to layer space to work with the content crop.
569 activeCrop = t.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800570
Michael Lentine28ea2172014-11-19 18:32:37 -0800571 // This needs to be here as transform.transform(Rect) computes the
572 // transformed rect and then takes the bounding box of the result before
573 // returning. This means
574 // transform.inverse().transform(transform.transform(Rect)) != Rect
575 // in which case we need to make sure the final rect is clipped to the
576 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000577 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
578 activeCrop.clear();
579 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800580
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700581 // subtract the transparent region and snap to the bounds
582 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
583
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000584 // Transform the window crop to match the buffer coordinate system,
585 // which means using the inverse of the current transform set on the
586 // SurfaceFlingerConsumer.
587 uint32_t invTransform = mCurrentTransform;
Robert Carrcae605c2017-03-29 12:10:31 -0700588 if (getTransformToDisplayInverse()) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000589 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700590 * the code below applies the primary display's inverse transform to the
591 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000592 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700593 uint32_t invTransformOrient =
594 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000595 // calculate the inverse transform
596 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
597 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
598 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800599 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000600 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700601 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
602 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800603 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000604
605 int winWidth = s.active.w;
606 int winHeight = s.active.h;
607 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
608 // If the activeCrop has been rotate the ends are rotated but not
609 // the space itself so when transforming ends back we can't rely on
610 // a modification of the axes of rotation. To account for this we
611 // need to reorient the inverse rotation in terms of the current
612 // axes of rotation.
613 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
614 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
615 if (is_h_flipped == is_v_flipped) {
616 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
617 NATIVE_WINDOW_TRANSFORM_FLIP_H;
618 }
619 winWidth = s.active.h;
620 winHeight = s.active.w;
621 }
622 const Rect winCrop = activeCrop.transform(
623 invTransform, s.active.w, s.active.h);
624
625 // below, crop is intersected with winCrop expressed in crop's coordinate space
626 float xScale = crop.getWidth() / float(winWidth);
627 float yScale = crop.getHeight() / float(winHeight);
628
629 float insetL = winCrop.left * xScale;
630 float insetT = winCrop.top * yScale;
631 float insetR = (winWidth - winCrop.right ) * xScale;
632 float insetB = (winHeight - winCrop.bottom) * yScale;
633
634 crop.left += insetL;
635 crop.top += insetT;
636 crop.right -= insetR;
637 crop.bottom -= insetB;
638
Mathias Agopian13127d82013-03-05 17:47:11 -0800639 return crop;
640}
641
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000642#ifdef USE_HWC2
Robert Carrae060832016-11-28 10:51:00 -0800643void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000644#else
645void Layer::setGeometry(
646 const sp<const DisplayDevice>& hw,
647 HWComposer::HWCLayerInterface& layer)
648#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700649{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000650#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800651 const auto hwcId = displayDevice->getHwcDisplayId();
652 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000653#else
654 layer.setDefaultState();
655#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700656
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700657 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000658#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800659 hwcInfo.forceClientComposition = false;
660
661 if (isSecure() && !displayDevice->isSecure()) {
662 hwcInfo.forceClientComposition = true;
663 }
664
665 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000666#else
667 layer.setSkip(false);
668
669 if (isSecure() && !hw->isSecure()) {
670 layer.setSkip(true);
671 }
672#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700673
Mathias Agopian13127d82013-03-05 17:47:11 -0800674 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700675 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000676#ifdef USE_HWC2
David Revemanecf0fa52017-03-03 11:32:44 -0500677 auto blendMode = HWC2::BlendMode::None;
Robert Carr6452f122017-03-21 10:41:29 -0700678 if (!isOpaque(s) || getAlpha() != 1.0f) {
David Revemanecf0fa52017-03-03 11:32:44 -0500679 blendMode = mPremultipliedAlpha ?
Dan Stoza9e56aa02015-11-02 13:00:03 -0800680 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800681 }
David Revemanecf0fa52017-03-03 11:32:44 -0500682 auto error = hwcLayer->setBlendMode(blendMode);
683 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
684 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
685 to_string(error).c_str(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000686#else
chaviw13fdc492017-06-27 12:40:18 -0700687 if (!isOpaque(s) || getAlpha() != 1.0f) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000688 layer.setBlending(mPremultipliedAlpha ?
689 HWC_BLENDING_PREMULT :
690 HWC_BLENDING_COVERAGE);
691 }
692#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800693
694 // apply the layer's transform, followed by the display's global transform
695 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700696 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700697 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -0700698 if (!s.crop.isEmpty()) {
699 Rect activeCrop(s.crop);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700700 activeCrop = t.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000701#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000702 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000703#else
704 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
705#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000706 activeCrop.clear();
707 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700708 activeCrop = t.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800709 // This needs to be here as transform.transform(Rect) computes the
710 // transformed rect and then takes the bounding box of the result before
711 // returning. This means
712 // transform.inverse().transform(transform.transform(Rect)) != Rect
713 // in which case we need to make sure the final rect is clipped to the
714 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000715 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
716 activeCrop.clear();
717 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700718 // mark regions outside the crop as transparent
719 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
720 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
721 s.active.w, s.active.h));
722 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
723 activeCrop.left, activeCrop.bottom));
724 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
725 s.active.w, activeCrop.bottom));
726 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700727
728 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700729 if (!s.finalCrop.isEmpty()) {
730 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000731 frame.clear();
732 }
733 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000734#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000735 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
736 frame.clear();
737 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800738 const Transform& tr(displayDevice->getTransform());
739 Rect transformedFrame = tr.transform(frame);
David Revemanecf0fa52017-03-03 11:32:44 -0500740 error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700741 if (error != HWC2::Error::None) {
742 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
743 mName.string(), transformedFrame.left, transformedFrame.top,
744 transformedFrame.right, transformedFrame.bottom,
745 to_string(error).c_str(), static_cast<int32_t>(error));
746 } else {
747 hwcInfo.displayFrame = transformedFrame;
748 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800749
Dan Stoza5a423ea2017-02-16 14:10:39 -0800750 FloatRect sourceCrop = computeCrop(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800751 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700752 if (error != HWC2::Error::None) {
753 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
754 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
755 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
756 static_cast<int32_t>(error));
757 } else {
758 hwcInfo.sourceCrop = sourceCrop;
759 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800760
chaviw13fdc492017-06-27 12:40:18 -0700761 float alpha = static_cast<float>(getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -0700762 error = hwcLayer->setPlaneAlpha(alpha);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800763 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
Robert Carr6452f122017-03-21 10:41:29 -0700764 "%s (%d)", mName.string(), alpha, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800765 static_cast<int32_t>(error));
766
Robert Carrae060832016-11-28 10:51:00 -0800767 error = hwcLayer->setZOrder(z);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800768 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
Robert Carrae060832016-11-28 10:51:00 -0800769 mName.string(), z, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800770 static_cast<int32_t>(error));
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500771
Albert Chaulk2a589632017-05-04 16:59:44 -0400772 int type = s.type;
773 int appId = s.appId;
Chia-I Wue41dbe62017-06-13 14:10:56 -0700774 sp<Layer> parent = mDrawingParent.promote();
Albert Chaulk2a589632017-05-04 16:59:44 -0400775 if (parent.get()) {
776 auto& parentState = parent->getDrawingState();
777 type = parentState.type;
778 appId = parentState.appId;
779 }
780
781 error = hwcLayer->setInfo(type, appId);
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500782 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
783 mName.string(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000784#else
785 if (!frame.intersect(hw->getViewport(), &frame)) {
786 frame.clear();
787 }
788 const Transform& tr(hw->getTransform());
789 layer.setFrame(tr.transform(frame));
790 layer.setCrop(computeCrop(hw));
chaviw13fdc492017-06-27 12:40:18 -0700791 layer.setPlaneAlpha(static_cast<uint8_t>(std::round(255.0f*getAlpha())));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000792#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800793
Mathias Agopian29a367b2011-07-12 14:51:45 -0700794 /*
795 * Transformations are applied in this order:
796 * 1) buffer orientation/flip/mirror
797 * 2) state transformation (window manager)
798 * 3) layer orientation (screen orientation)
799 * (NOTE: the matrices are multiplied in reverse order)
800 */
801
802 const Transform bufferOrientation(mCurrentTransform);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700803 Transform transform(tr * t * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700804
Robert Carrcae605c2017-03-29 12:10:31 -0700805 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700806 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700807 * the code below applies the primary display's inverse transform to the
808 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700809 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700810 uint32_t invTransform =
811 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700812 // calculate the inverse transform
813 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
814 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
815 NATIVE_WINDOW_TRANSFORM_FLIP_H;
816 }
Robert Carrcae605c2017-03-29 12:10:31 -0700817
818 /*
819 * Here we cancel out the orientation component of the WM transform.
820 * The scaling and translate components are already included in our bounds
821 * computation so it's enough to just omit it in the composition.
822 * See comment in onDraw with ref to b/36727915 for why.
823 */
824 transform = Transform(invTransform) * tr * bufferOrientation;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700825 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700826
827 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800828 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000829#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800830 if (orientation & Transform::ROT_INVALID) {
831 // we can only handle simple transformation
832 hwcInfo.forceClientComposition = true;
833 } else {
834 auto transform = static_cast<HWC2::Transform>(orientation);
835 auto error = hwcLayer->setTransform(transform);
836 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
837 "%s (%d)", mName.string(), to_string(transform).c_str(),
838 to_string(error).c_str(), static_cast<int32_t>(error));
839 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000840#else
841 if (orientation & Transform::ROT_INVALID) {
842 // we can only handle simple transformation
843 layer.setSkip(true);
844 } else {
845 layer.setTransform(orientation);
846 }
847#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700848}
849
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000850#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800851void Layer::forceClientComposition(int32_t hwcId) {
852 if (mHwcLayers.count(hwcId) == 0) {
853 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
854 return;
855 }
856
857 mHwcLayers[hwcId].forceClientComposition = true;
858}
Dan Stoza9e56aa02015-11-02 13:00:03 -0800859
Dan Stoza9e56aa02015-11-02 13:00:03 -0800860void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
861 // Apply this display's projection's viewport to the visible region
862 // before giving it to the HWC HAL.
863 const Transform& tr = displayDevice->getTransform();
864 const auto& viewport = displayDevice->getViewport();
865 Region visible = tr.transform(visibleRegion.intersect(viewport));
866 auto hwcId = displayDevice->getHwcDisplayId();
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800867 auto& hwcInfo = mHwcLayers[hwcId];
868 auto& hwcLayer = hwcInfo.layer;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800869 auto error = hwcLayer->setVisibleRegion(visible);
870 if (error != HWC2::Error::None) {
871 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
872 to_string(error).c_str(), static_cast<int32_t>(error));
873 visible.dump(LOG_TAG);
874 }
875
876 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
877 if (error != HWC2::Error::None) {
878 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
879 to_string(error).c_str(), static_cast<int32_t>(error));
880 surfaceDamageRegion.dump(LOG_TAG);
881 }
882
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700883 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800884 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700885 setCompositionType(hwcId, HWC2::Composition::Sideband);
886 ALOGV("[%s] Requesting Sideband composition", mName.string());
887 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800888 if (error != HWC2::Error::None) {
889 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
890 mName.string(), mSidebandStream->handle(),
891 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800892 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700893 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894 }
895
Dan Stoza0a21df72016-07-20 12:52:38 -0700896 // Client layers
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800897 if (hwcInfo.forceClientComposition ||
Dan Stoza0a21df72016-07-20 12:52:38 -0700898 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700899 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800900 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700901 return;
902 }
903
Dan Stoza0a21df72016-07-20 12:52:38 -0700904 // SolidColor layers
905 if (mActiveBuffer == nullptr) {
906 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700907
chaviw13fdc492017-06-27 12:40:18 -0700908 half4 color = getColor();
909 error = hwcLayer->setColor({static_cast<uint8_t>(std::round(255.0f*color.r)),
910 static_cast<uint8_t>(std::round(255.0f * color.g)),
911 static_cast<uint8_t>(std::round(255.0f * color.b)),
912 255});
Dan Stoza0a21df72016-07-20 12:52:38 -0700913 if (error != HWC2::Error::None) {
914 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
915 to_string(error).c_str(), static_cast<int32_t>(error));
916 }
Dan Stozac6c89542016-07-27 10:16:52 -0700917
918 // Clear out the transform, because it doesn't make sense absent a
919 // source buffer
920 error = hwcLayer->setTransform(HWC2::Transform::None);
921 if (error != HWC2::Error::None) {
922 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
923 to_string(error).c_str(), static_cast<int32_t>(error));
924 }
925
Dan Stoza0a21df72016-07-20 12:52:38 -0700926 return;
927 }
928
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700929 // Device or Cursor layers
930 if (mPotentialCursor) {
931 ALOGV("[%s] Requesting Cursor composition", mName.string());
932 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800933 } else {
934 ALOGV("[%s] Requesting Device composition", mName.string());
935 setCompositionType(hwcId, HWC2::Composition::Device);
936 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700937
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700938 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
939 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
940 if (error != HWC2::Error::None) {
941 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
942 mCurrentState.dataSpace, to_string(error).c_str(),
943 static_cast<int32_t>(error));
944 }
945
Chia-I Wu06d63de2017-01-04 14:58:51 +0800946 uint32_t hwcSlot = 0;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400947 sp<GraphicBuffer> hwcBuffer;
948 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
949 &hwcSlot, &hwcBuffer);
Chia-I Wu06d63de2017-01-04 14:58:51 +0800950
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700951 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400952 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700953 if (error != HWC2::Error::None) {
954 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
955 mActiveBuffer->handle, to_string(error).c_str(),
956 static_cast<int32_t>(error));
957 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800958}
Courtney Goeltzenleuchter9551fd32016-10-20 17:18:15 -0600959
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000960#else
961void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
962 HWComposer::HWCLayerInterface& layer) {
963 // we have to set the visible region on every frame because
964 // we currently free it during onLayerDisplayed(), which is called
965 // after HWComposer::commit() -- every frame.
966 // Apply this display's projection's viewport to the visible region
967 // before giving it to the HWC HAL.
968 const Transform& tr = hw->getTransform();
969 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
970 layer.setVisibleRegionScreen(visible);
971 layer.setSurfaceDamage(surfaceDamageRegion);
972 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700973
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000974 if (mSidebandStream.get()) {
975 layer.setSidebandStream(mSidebandStream);
976 } else {
977 // NOTE: buffer can be NULL if the client never drew into this
978 // layer yet, or if we ran out of memory
979 layer.setBuffer(mActiveBuffer);
980 }
981}
982#endif
983
984#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800985void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
986 auto hwcId = displayDevice->getHwcDisplayId();
987 if (mHwcLayers.count(hwcId) == 0 ||
988 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
989 return;
990 }
991
992 // This gives us only the "orientation" component of the transform
993 const State& s(getCurrentState());
994
995 // Apply the layer's transform, followed by the display's global transform
996 // Here we're guaranteed that the layer's transform preserves rects
997 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700998 if (!s.crop.isEmpty()) {
999 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001000 }
1001 // Subtract the transparent region and snap to the bounds
1002 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001003 Rect frame(getTransform().transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -08001004 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -07001005 if (!s.finalCrop.isEmpty()) {
1006 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001007 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001008 auto& displayTransform(displayDevice->getTransform());
1009 auto position = displayTransform.transform(frame);
1010
1011 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
1012 position.top);
1013 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
1014 "to (%d, %d): %s (%d)", mName.string(), position.left,
1015 position.top, to_string(error).c_str(),
1016 static_cast<int32_t>(error));
1017}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001018#else
1019void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
1020 HWComposer::HWCLayerInterface& layer) {
1021 int fenceFd = -1;
1022
1023 // TODO: there is a possible optimization here: we only need to set the
1024 // acquire fence the first time a new buffer is acquired on EACH display.
1025
1026 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
1027 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
1028 if (fence->isValid()) {
1029 fenceFd = fence->dup();
1030 if (fenceFd == -1) {
1031 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
1032 }
1033 }
1034 }
1035 layer.setAcquireFenceFd(fenceFd);
1036}
1037
1038Rect Layer::getPosition(
1039 const sp<const DisplayDevice>& hw)
1040{
1041 // this gives us only the "orientation" component of the transform
1042 const State& s(getCurrentState());
1043
1044 // apply the layer's transform, followed by the display's global transform
1045 // here we're guaranteed that the layer's transform preserves rects
1046 Rect win(s.active.w, s.active.h);
1047 if (!s.crop.isEmpty()) {
1048 win.intersect(s.crop, &win);
1049 }
1050 // subtract the transparent region and snap to the bounds
1051 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001052 Rect frame(getTransform().transform(bounds));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001053 frame.intersect(hw->getViewport(), &frame);
1054 if (!s.finalCrop.isEmpty()) {
1055 frame.intersect(s.finalCrop, &frame);
1056 }
1057 const Transform& tr(hw->getTransform());
1058 return Rect(tr.transform(frame));
1059}
1060#endif
Riley Andrews03414a12014-07-01 14:22:59 -07001061
Mathias Agopian13127d82013-03-05 17:47:11 -08001062// ---------------------------------------------------------------------------
1063// drawing...
1064// ---------------------------------------------------------------------------
1065
chaviwa76b2712017-09-20 12:02:26 -07001066void Layer::draw(const RenderArea& renderArea, const Region& clip) const {
1067 onDraw(renderArea, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -08001068}
1069
chaviwa76b2712017-09-20 12:02:26 -07001070void Layer::draw(const RenderArea& renderArea, bool useIdentityTransform) const {
1071 onDraw(renderArea, Region(renderArea.getBounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001072}
1073
chaviwa76b2712017-09-20 12:02:26 -07001074void Layer::draw(const RenderArea& renderArea) const {
1075 onDraw(renderArea, Region(renderArea.getBounds()), false);
Dan Stozac7014012014-02-14 15:03:43 -08001076}
1077
Robert Carrcae605c2017-03-29 12:10:31 -07001078static constexpr mat4 inverseOrientation(uint32_t transform) {
1079 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1080 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1081 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1082 mat4 tr;
1083
1084 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1085 tr = tr * rot90;
1086 }
1087 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1088 tr = tr * flipH;
1089 }
1090 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1091 tr = tr * flipV;
1092 }
1093 return inverse(tr);
1094}
1095
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001096/*
1097 * onDraw will draw the current layer onto the presentable buffer
1098 */
chaviwa76b2712017-09-20 12:02:26 -07001099void Layer::onDraw(const RenderArea& renderArea, const Region& clip,
Dan Stozac7014012014-02-14 15:03:43 -08001100 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001101{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001102 ATRACE_CALL();
1103
Mathias Agopiana67932f2011-04-20 14:20:59 -07001104 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001105 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -07001106 // in fact never been drawn into. This happens frequently with
1107 // SurfaceView because the WindowManager can't know when the client
1108 // has drawn the first time.
1109
1110 // If there is nothing under us, we paint the screen in black, otherwise
1111 // we just skip this update.
1112
1113 // figure out if there is something below us
1114 Region under;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001115 bool finished = false;
Dan Stoza412903f2017-04-27 13:42:17 -07001116 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001117 if (finished || layer == static_cast<Layer const*>(this)) {
1118 finished = true;
1119 return;
1120 }
chaviwa76b2712017-09-20 12:02:26 -07001121 under.orSelf(renderArea.getTransform().transform(layer->visibleRegion));
Robert Carr1f0a16a2016-10-24 16:27:39 -07001122 });
Mathias Agopian179169e2010-05-06 20:21:45 -07001123 // if not everything below us is covered, we plug the holes!
1124 Region holes(clip.subtract(under));
1125 if (!holes.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07001126 clearWithOpenGL(renderArea, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -07001127 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001128 return;
1129 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001130
Andy McFadden97eba892012-12-11 15:21:45 -08001131 // Bind the current buffer to the GL texture, and wait for it to be
1132 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001133 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1134 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -08001135 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -07001136 // Go ahead and draw the buffer anyway; no matter what we do the screen
1137 // is probably going to have something visibly wrong.
1138 }
1139
chaviwa76b2712017-09-20 12:02:26 -07001140 bool blackOutLayer = isProtected() || (isSecure() && !renderArea.isSecure());
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001141
Mathias Agopian875d8e12013-06-07 15:35:48 -07001142 RenderEngine& engine(mFlinger->getRenderEngine());
1143
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001144 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -07001145 // TODO: we could be more subtle with isFixedSize()
chaviwa76b2712017-09-20 12:02:26 -07001146 const bool useFiltering = getFiltering() || needsFiltering(renderArea) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -07001147
1148 // Query the texture matrix given our current filtering mode.
1149 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001150 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1151 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -07001152
Robert Carrcae605c2017-03-29 12:10:31 -07001153 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001154
1155 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -07001156 * the code below applies the primary display's inverse transform to
1157 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001158 */
Pablo Ceballos021623b2016-04-15 17:31:51 -07001159 uint32_t transform =
1160 DisplayDevice::getPrimaryDisplayOrientationTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001161 mat4 tr = inverseOrientation(transform);
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001162
Robert Carrcae605c2017-03-29 12:10:31 -07001163 /**
1164 * TODO(b/36727915): This is basically a hack.
1165 *
1166 * Ensure that regardless of the parent transformation,
1167 * this buffer is always transformed from native display
1168 * orientation to display orientation. For example, in the case
1169 * of a camera where the buffer remains in native orientation,
1170 * we want the pixels to always be upright.
1171 */
Chia-I Wue41dbe62017-06-13 14:10:56 -07001172 sp<Layer> p = mDrawingParent.promote();
1173 if (p != nullptr) {
1174 const auto parentTransform = p->getTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001175 tr = tr * inverseOrientation(parentTransform.getOrientation());
1176 }
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001177
1178 // and finally apply it to the original texture matrix
1179 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1180 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1181 }
1182
Jamie Genniscbb1a952012-05-08 17:05:52 -07001183 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -07001184 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1185 mTexture.setFiltering(useFiltering);
1186 mTexture.setMatrix(textureMatrix);
1187
1188 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -07001189 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001190 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -07001191 }
chaviwa76b2712017-09-20 12:02:26 -07001192 drawWithOpenGL(renderArea, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001193 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001194}
1195
Mathias Agopian13127d82013-03-05 17:47:11 -08001196
chaviwa76b2712017-09-20 12:02:26 -07001197void Layer::clearWithOpenGL(const RenderArea& renderArea,
Fabien Sanglard17487192016-12-07 13:03:32 -08001198 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -08001199 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001200{
Mathias Agopian19733a32013-08-28 18:13:56 -07001201 RenderEngine& engine(mFlinger->getRenderEngine());
chaviwa76b2712017-09-20 12:02:26 -07001202 computeGeometry(renderArea, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -07001203 engine.setupFillWithColor(red, green, blue, alpha);
1204 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -08001205}
1206
chaviwa76b2712017-09-20 12:02:26 -07001207void Layer::clearWithOpenGL(const RenderArea& renderArea) const {
1208 clearWithOpenGL(renderArea, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001209}
1210
chaviwa76b2712017-09-20 12:02:26 -07001211void Layer::drawWithOpenGL(const RenderArea& renderArea, bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001212 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001213
chaviwa76b2712017-09-20 12:02:26 -07001214 computeGeometry(renderArea, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001215
Mathias Agopian13127d82013-03-05 17:47:11 -08001216 /*
1217 * NOTE: the way we compute the texture coordinates here produces
1218 * different results than when we take the HWC path -- in the later case
1219 * the "source crop" is rounded to texel boundaries.
1220 * This can produce significantly different results when the texture
1221 * is scaled by a large amount.
1222 *
1223 * The GL code below is more logical (imho), and the difference with
1224 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001225 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001226 * GL composition when a buffer scaling is applied (maybe with some
1227 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1228 * like more of a hack.
1229 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001230 Rect win(computeBounds());
1231
Robert Carr1f0a16a2016-10-24 16:27:39 -07001232 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -07001233 if (!s.finalCrop.isEmpty()) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001234 win = t.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001235 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001236 win.clear();
1237 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001238 win = t.inverse().transform(win);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001239 if (!win.intersect(computeBounds(), &win)) {
1240 win.clear();
1241 }
1242 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001243
Mathias Agopian3f844832013-08-07 21:24:32 -07001244 float left = float(win.left) / float(s.active.w);
1245 float top = float(win.top) / float(s.active.h);
1246 float right = float(win.right) / float(s.active.w);
1247 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001248
Mathias Agopian875d8e12013-06-07 15:35:48 -07001249 // TODO: we probably want to generate the texture coords with the mesh
1250 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001251 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1252 texCoords[0] = vec2(left, 1.0f - top);
1253 texCoords[1] = vec2(left, 1.0f - bottom);
1254 texCoords[2] = vec2(right, 1.0f - bottom);
1255 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001256
Mathias Agopian875d8e12013-06-07 15:35:48 -07001257 RenderEngine& engine(mFlinger->getRenderEngine());
chaviw13fdc492017-06-27 12:40:18 -07001258 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s),
1259 false /* disableTexture */, getColor());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001260#ifdef USE_HWC2
1261 engine.setSourceDataSpace(mCurrentState.dataSpace);
1262#endif
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001263 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001264 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001265}
1266
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001267#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001268void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1269 bool callIntoHwc) {
1270 if (mHwcLayers.count(hwcId) == 0) {
1271 ALOGE("setCompositionType called without a valid HWC layer");
1272 return;
1273 }
1274 auto& hwcInfo = mHwcLayers[hwcId];
1275 auto& hwcLayer = hwcInfo.layer;
1276 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1277 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1278 if (hwcInfo.compositionType != type) {
1279 ALOGV(" actually setting");
1280 hwcInfo.compositionType = type;
1281 if (callIntoHwc) {
1282 auto error = hwcLayer->setCompositionType(type);
1283 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1284 "composition type %s: %s (%d)", mName.string(),
1285 to_string(type).c_str(), to_string(error).c_str(),
1286 static_cast<int32_t>(error));
1287 }
1288 }
1289}
1290
1291HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001292 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1293 // If we're querying the composition type for a display that does not
1294 // have a HWC counterpart, then it will always be Client
1295 return HWC2::Composition::Client;
1296 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001297 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001298 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001299 return HWC2::Composition::Invalid;
1300 }
1301 return mHwcLayers.at(hwcId).compositionType;
1302}
1303
1304void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1305 if (mHwcLayers.count(hwcId) == 0) {
1306 ALOGE("setClearClientTarget called without a valid HWC layer");
1307 return;
1308 }
1309 mHwcLayers[hwcId].clearClientTarget = clear;
1310}
1311
1312bool Layer::getClearClientTarget(int32_t hwcId) const {
1313 if (mHwcLayers.count(hwcId) == 0) {
1314 ALOGE("getClearClientTarget called without a valid HWC layer");
1315 return false;
1316 }
1317 return mHwcLayers.at(hwcId).clearClientTarget;
1318}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001319#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001320
Ruben Brunk1681d952014-06-27 15:51:55 -07001321uint32_t Layer::getProducerStickyTransform() const {
1322 int producerStickyTransform = 0;
1323 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1324 if (ret != OK) {
1325 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1326 strerror(-ret), ret);
1327 return 0;
1328 }
1329 return static_cast<uint32_t>(producerStickyTransform);
1330}
1331
Dan Stozac5da2712016-07-20 15:38:12 -07001332bool Layer::latchUnsignaledBuffers() {
1333 static bool propertyLoaded = false;
1334 static bool latch = false;
1335 static std::mutex mutex;
1336 std::lock_guard<std::mutex> lock(mutex);
1337 if (!propertyLoaded) {
1338 char value[PROPERTY_VALUE_MAX] = {};
1339 property_get("debug.sf.latch_unsignaled", value, "0");
1340 latch = atoi(value);
1341 propertyLoaded = true;
1342 }
1343 return latch;
1344}
1345
Dan Stozacac35382016-01-27 12:21:06 -08001346uint64_t Layer::getHeadFrameNumber() const {
1347 Mutex::Autolock lock(mQueueItemLock);
1348 if (!mQueueItems.empty()) {
1349 return mQueueItems[0].mFrameNumber;
1350 } else {
1351 return mCurrentFrameNumber;
1352 }
1353}
1354
Dan Stoza1ce65812016-06-15 16:26:27 -07001355bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001356#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001357 if (latchUnsignaledBuffers()) {
1358 return true;
1359 }
1360
Dan Stoza1ce65812016-06-15 16:26:27 -07001361 Mutex::Autolock lock(mQueueItemLock);
1362 if (mQueueItems.empty()) {
1363 return true;
1364 }
1365 if (mQueueItems[0].mIsDroppable) {
1366 // Even though this buffer's fence may not have signaled yet, it could
1367 // be replaced by another buffer before it has a chance to, which means
1368 // that it's possible to get into a situation where a buffer is never
1369 // able to be latched. To avoid this, grab this buffer anyway.
1370 return true;
1371 }
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001372 return mQueueItems[0].mFenceTime->getSignalTime() !=
1373 Fence::SIGNAL_TIME_PENDING;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001374#else
1375 return true;
1376#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001377}
1378
Dan Stozacac35382016-01-27 12:21:06 -08001379bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1380 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1381 // Don't bother with a SyncPoint, since we've already latched the
1382 // relevant frame
1383 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001384 }
1385
Dan Stozacac35382016-01-27 12:21:06 -08001386 Mutex::Autolock lock(mLocalSyncPointMutex);
1387 mLocalSyncPoints.push_back(point);
1388 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001389}
1390
Mathias Agopian13127d82013-03-05 17:47:11 -08001391void Layer::setFiltering(bool filtering) {
1392 mFiltering = filtering;
1393}
1394
1395bool Layer::getFiltering() const {
1396 return mFiltering;
1397}
1398
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001399// As documented in libhardware header, formats in the range
1400// 0x100 - 0x1FF are specific to the HAL implementation, and
1401// are known to have no alpha channel
1402// TODO: move definition for device-specific range into
1403// hardware.h, instead of using hard-coded values here.
1404#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1405
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001406bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001407 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1408 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001409 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001410 switch (format) {
1411 case HAL_PIXEL_FORMAT_RGBA_8888:
1412 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001413 case HAL_PIXEL_FORMAT_RGBA_FP16:
Romain Guy541f2262017-02-10 18:50:17 -08001414 case HAL_PIXEL_FORMAT_RGBA_1010102:
Mathias Agopiandd533712013-07-26 15:31:39 -07001415 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001416 }
1417 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001418 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001419}
1420
Mathias Agopian13127d82013-03-05 17:47:11 -08001421// ----------------------------------------------------------------------------
1422// local state
1423// ----------------------------------------------------------------------------
1424
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001425static void boundPoint(vec2* point, const Rect& crop) {
1426 if (point->x < crop.left) {
1427 point->x = crop.left;
1428 }
1429 if (point->x > crop.right) {
1430 point->x = crop.right;
1431 }
1432 if (point->y < crop.top) {
1433 point->y = crop.top;
1434 }
1435 if (point->y > crop.bottom) {
1436 point->y = crop.bottom;
1437 }
1438}
1439
chaviwa76b2712017-09-20 12:02:26 -07001440void Layer::computeGeometry(const RenderArea& renderArea, Mesh& mesh,
1441 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001442 const Layer::State& s(getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07001443 const Transform renderAreaTransform(renderArea.getTransform());
1444 const uint32_t height = renderArea.getHeight();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001445 Rect win = computeBounds();
Mathias Agopian3f844832013-08-07 21:24:32 -07001446
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001447 vec2 lt = vec2(win.left, win.top);
1448 vec2 lb = vec2(win.left, win.bottom);
1449 vec2 rb = vec2(win.right, win.bottom);
1450 vec2 rt = vec2(win.right, win.top);
1451
Robert Carr1f0a16a2016-10-24 16:27:39 -07001452 Transform layerTransform = getTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001453 if (!useIdentityTransform) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001454 lt = layerTransform.transform(lt);
1455 lb = layerTransform.transform(lb);
1456 rb = layerTransform.transform(rb);
1457 rt = layerTransform.transform(rt);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001458 }
1459
Robert Carrb5d3d262016-03-25 15:08:13 -07001460 if (!s.finalCrop.isEmpty()) {
1461 boundPoint(&lt, s.finalCrop);
1462 boundPoint(&lb, s.finalCrop);
1463 boundPoint(&rb, s.finalCrop);
1464 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001465 }
1466
Mathias Agopianff2ed702013-09-01 21:36:12 -07001467 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
chaviwa76b2712017-09-20 12:02:26 -07001468 position[0] = renderAreaTransform.transform(lt);
1469 position[1] = renderAreaTransform.transform(lb);
1470 position[2] = renderAreaTransform.transform(rb);
1471 position[3] = renderAreaTransform.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001472 for (size_t i=0 ; i<4 ; i++) {
chaviwa76b2712017-09-20 12:02:26 -07001473 position[i].y = height - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001474 }
1475}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001476
Andy McFadden4125a4f2014-01-29 17:17:11 -08001477bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001478{
neo.hee6fd41d2017-02-17 14:35:33 +08001479 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
Mathias Agopiana67932f2011-04-20 14:20:59 -07001480 // layer's opaque flag.
neo.hee6fd41d2017-02-17 14:35:33 +08001481 if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001482 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001483 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001484
1485 // if the layer has the opaque flag, then we're always opaque,
1486 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001487 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001488}
1489
Dan Stoza23116082015-06-18 14:58:39 -07001490bool Layer::isSecure() const
1491{
1492 const Layer::State& s(mDrawingState);
1493 return (s.flags & layer_state_t::eLayerSecure);
1494}
1495
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001496bool Layer::isProtected() const
1497{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001498 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001499 return (activeBuffer != 0) &&
1500 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1501}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001502
Mathias Agopian13127d82013-03-05 17:47:11 -08001503bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001504 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001505}
1506
1507bool Layer::isCropped() const {
1508 return !mCurrentCrop.isEmpty();
1509}
1510
chaviwa76b2712017-09-20 12:02:26 -07001511bool Layer::needsFiltering(const RenderArea& renderArea) const {
1512 return mNeedsFiltering || renderArea.needsFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -08001513}
1514
1515void Layer::setVisibleRegion(const Region& visibleRegion) {
1516 // always called from main thread
1517 this->visibleRegion = visibleRegion;
1518}
1519
1520void Layer::setCoveredRegion(const Region& coveredRegion) {
1521 // always called from main thread
1522 this->coveredRegion = coveredRegion;
1523}
1524
1525void Layer::setVisibleNonTransparentRegion(const Region&
1526 setVisibleNonTransparentRegion) {
1527 // always called from main thread
1528 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1529}
1530
1531// ----------------------------------------------------------------------------
1532// transaction
1533// ----------------------------------------------------------------------------
1534
Dan Stoza7dde5992015-05-22 09:51:44 -07001535void Layer::pushPendingState() {
1536 if (!mCurrentState.modified) {
1537 return;
1538 }
1539
Dan Stoza7dde5992015-05-22 09:51:44 -07001540 // If this transaction is waiting on the receipt of a frame, generate a sync
1541 // point and send it to the remote layer.
Robert Carr0d480722017-01-10 16:42:54 -08001542 if (mCurrentState.barrierLayer != nullptr) {
1543 sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1544 if (barrierLayer == nullptr) {
1545 ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
Dan Stoza7dde5992015-05-22 09:51:44 -07001546 // If we can't promote the layer we are intended to wait on,
1547 // then it is expired or otherwise invalid. Allow this transaction
1548 // to be applied as per normal (no synchronization).
Robert Carr0d480722017-01-10 16:42:54 -08001549 mCurrentState.barrierLayer = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001550 } else {
1551 auto syncPoint = std::make_shared<SyncPoint>(
1552 mCurrentState.frameNumber);
Robert Carr0d480722017-01-10 16:42:54 -08001553 if (barrierLayer->addSyncPoint(syncPoint)) {
Dan Stozacac35382016-01-27 12:21:06 -08001554 mRemoteSyncPoints.push_back(std::move(syncPoint));
1555 } else {
1556 // We already missed the frame we're supposed to synchronize
1557 // on, so go ahead and apply the state update
Robert Carr0d480722017-01-10 16:42:54 -08001558 mCurrentState.barrierLayer = nullptr;
Dan Stozacac35382016-01-27 12:21:06 -08001559 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001560 }
1561
Dan Stoza7dde5992015-05-22 09:51:44 -07001562 // Wake us up to check if the frame has been received
1563 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001564 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001565 }
1566 mPendingStates.push_back(mCurrentState);
Dan Stozaf7ba41a2017-05-10 15:11:11 -07001567 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
Dan Stoza7dde5992015-05-22 09:51:44 -07001568}
1569
Pablo Ceballos05289c22016-04-14 15:49:55 -07001570void Layer::popPendingState(State* stateToCommit) {
1571 auto oldFlags = stateToCommit->flags;
1572 *stateToCommit = mPendingStates[0];
1573 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1574 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001575
1576 mPendingStates.removeAt(0);
Dan Stozaf7ba41a2017-05-10 15:11:11 -07001577 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
Dan Stoza7dde5992015-05-22 09:51:44 -07001578}
1579
Pablo Ceballos05289c22016-04-14 15:49:55 -07001580bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001581 bool stateUpdateAvailable = false;
1582 while (!mPendingStates.empty()) {
Robert Carr0d480722017-01-10 16:42:54 -08001583 if (mPendingStates[0].barrierLayer != nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001584 if (mRemoteSyncPoints.empty()) {
1585 // If we don't have a sync point for this, apply it anyway. It
1586 // will be visually wrong, but it should keep us from getting
1587 // into too much trouble.
1588 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001589 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001590 stateUpdateAvailable = true;
1591 continue;
1592 }
1593
Dan Stozacac35382016-01-27 12:21:06 -08001594 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1595 mPendingStates[0].frameNumber) {
1596 ALOGE("[%s] Unexpected sync point frame number found",
1597 mName.string());
1598
1599 // Signal our end of the sync point and then dispose of it
1600 mRemoteSyncPoints.front()->setTransactionApplied();
1601 mRemoteSyncPoints.pop_front();
1602 continue;
1603 }
1604
Dan Stoza7dde5992015-05-22 09:51:44 -07001605 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1606 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001607 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001608 stateUpdateAvailable = true;
1609
1610 // Signal our end of the sync point and then dispose of it
1611 mRemoteSyncPoints.front()->setTransactionApplied();
1612 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001613 } else {
1614 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001615 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001616 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001617 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001618 stateUpdateAvailable = true;
1619 }
1620 }
1621
1622 // If we still have pending updates, wake SurfaceFlinger back up and point
1623 // it at this layer so we can process them
1624 if (!mPendingStates.empty()) {
1625 setTransactionFlags(eTransactionNeeded);
1626 mFlinger->setTransactionFlags(eTraversalNeeded);
1627 }
1628
1629 mCurrentState.modified = false;
1630 return stateUpdateAvailable;
1631}
1632
1633void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001634 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001635 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001636 Mutex::Autolock lock(mLocalSyncPointMutex);
1637 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001638 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001639 point->setFrameAvailable();
1640 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001641 }
1642}
1643
Mathias Agopian13127d82013-03-05 17:47:11 -08001644uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001645 ATRACE_CALL();
1646
Dan Stoza7dde5992015-05-22 09:51:44 -07001647 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001648 Layer::State c = getCurrentState();
1649 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001650 return 0;
1651 }
1652
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001653 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001654
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001655 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1656 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001657
1658 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001659 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001660 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001661 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001662 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001663 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001664 " drawing={ 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",
Robert Carrc3574f72016-03-24 12:19:32 -07001666 this, getName().string(), mCurrentTransform,
1667 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001668 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001669 c.crop.left,
1670 c.crop.top,
1671 c.crop.right,
1672 c.crop.bottom,
1673 c.crop.getWidth(),
1674 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001675 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001676 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001677 s.crop.left,
1678 s.crop.top,
1679 s.crop.right,
1680 s.crop.bottom,
1681 s.crop.getWidth(),
1682 s.crop.getHeight(),
1683 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001684
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001685 // record the new size, form this point on, when the client request
1686 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001687 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001688 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001689 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001690
Robert Carre392b552017-09-19 12:16:05 -07001691 // Don't let Layer::doTransaction update the drawing state
1692 // if we have a pending resize, unless we are in fixed-size mode.
1693 // the drawing state will be updated only once we receive a buffer
1694 // with the correct size.
1695 //
1696 // In particular, we want to make sure the clip (which is part
1697 // of the geometry state) is latched together with the size but is
1698 // latched immediately when no resizing is involved.
1699 //
1700 // If a sideband stream is attached, however, we want to skip this
1701 // optimization so that transactions aren't missed when a buffer
1702 // never arrives
1703 //
1704 // In the case that we don't have a buffer we ignore other factors
1705 // and avoid entering the resizePending state. At a high level the
1706 // resizePending state is to avoid applying the state of the new buffer
1707 // to the old buffer. However in the state where we don't have an old buffer
1708 // there is no such concern but we may still be being used as a parent layer.
1709 const bool resizePending = ((c.requested.w != c.active.w) ||
1710 (c.requested.h != c.active.h)) && (mActiveBuffer != nullptr);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001711 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001712 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001713 flags |= eDontUpdateGeometryState;
1714 }
1715 }
1716
Robert Carr7bf247e2017-05-18 14:02:49 -07001717 // Here we apply various requested geometry states, depending on our
1718 // latching configuration. See Layer.h for a detailed discussion of
1719 // how geometry latching is controlled.
1720 if (!(flags & eDontUpdateGeometryState)) {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001721 Layer::State& editCurrentState(getCurrentState());
Robert Carr7bf247e2017-05-18 14:02:49 -07001722
1723 // If mFreezeGeometryUpdates is true we are in the setGeometryAppliesWithResize
1724 // mode, which causes attributes which normally latch regardless of scaling mode,
1725 // to be delayed. We copy the requested state to the active state making sure
1726 // to respect these rules (again see Layer.h for a detailed discussion).
1727 //
1728 // There is an awkward asymmetry in the handling of the crop states in the position
1729 // states, as can be seen below. Largely this arises from position and transform
1730 // being stored in the same data structure while having different latching rules.
1731 // b/38182305
1732 //
1733 // Careful that "c" and editCurrentState may not begin as equivalent due to
1734 // applyPendingStates in the presence of deferred transactions.
1735 if (mFreezeGeometryUpdates) {
Robert Carr82364e32016-05-15 11:27:47 -07001736 float tx = c.active.transform.tx();
1737 float ty = c.active.transform.ty();
1738 c.active = c.requested;
1739 c.active.transform.set(tx, ty);
1740 editCurrentState.active = c.active;
1741 } else {
1742 editCurrentState.active = editCurrentState.requested;
1743 c.active = c.requested;
1744 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001745 }
1746
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001747 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001748 // invalidate and recompute the visible regions if needed
1749 flags |= Layer::eVisibleRegion;
1750 }
1751
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001752 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001753 // invalidate and recompute the visible regions if needed
1754 flags |= eVisibleRegion;
1755 this->contentDirty = true;
1756
1757 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001758 const uint8_t type = c.active.transform.getType();
1759 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001760 (type >= Transform::SCALE));
1761 }
1762
Dan Stozac8145172016-04-28 16:29:06 -07001763 // If the layer is hidden, signal and clear out all local sync points so
1764 // that transactions for layers depending on this layer's frames becoming
1765 // visible are not blocked
1766 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001767 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001768 }
1769
Mathias Agopian13127d82013-03-05 17:47:11 -08001770 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001771 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001772 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001773}
1774
Pablo Ceballos05289c22016-04-14 15:49:55 -07001775void Layer::commitTransaction(const State& stateToCommit) {
1776 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001777}
1778
Mathias Agopian13127d82013-03-05 17:47:11 -08001779uint32_t Layer::getTransactionFlags(uint32_t flags) {
1780 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1781}
1782
1783uint32_t Layer::setTransactionFlags(uint32_t flags) {
1784 return android_atomic_or(flags, &mTransactionFlags);
1785}
1786
Robert Carr82364e32016-05-15 11:27:47 -07001787bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001788 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001789 return false;
1790 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001791
1792 // We update the requested and active position simultaneously because
1793 // we want to apply the position portion of the transform matrix immediately,
1794 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001795 mCurrentState.requested.transform.set(x, y);
Robert Carr7bf247e2017-05-18 14:02:49 -07001796 if (immediate && !mFreezeGeometryUpdates) {
1797 // Here we directly update the active state
1798 // unlike other setters, because we store it within
1799 // the transform, but use different latching rules.
1800 // b/38182305
Robert Carr82364e32016-05-15 11:27:47 -07001801 mCurrentState.active.transform.set(x, y);
1802 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001803 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001804
Dan Stoza7dde5992015-05-22 09:51:44 -07001805 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001806 setTransactionFlags(eTransactionNeeded);
1807 return true;
1808}
Robert Carr82364e32016-05-15 11:27:47 -07001809
Robert Carr1f0a16a2016-10-24 16:27:39 -07001810bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1811 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1812 if (idx < 0) {
1813 return false;
1814 }
1815 if (childLayer->setLayer(z)) {
1816 mCurrentChildren.removeAt(idx);
1817 mCurrentChildren.add(childLayer);
1818 }
1819 return true;
1820}
1821
Robert Carrae060832016-11-28 10:51:00 -08001822bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001823 if (mCurrentState.z == z)
1824 return false;
1825 mCurrentState.sequence++;
1826 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001827 mCurrentState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001828
1829 // Discard all relative layering.
1830 if (mCurrentState.zOrderRelativeOf != nullptr) {
1831 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1832 if (strongRelative != nullptr) {
1833 strongRelative->removeZOrderRelative(this);
1834 }
1835 mCurrentState.zOrderRelativeOf = nullptr;
1836 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001837 setTransactionFlags(eTransactionNeeded);
1838 return true;
1839}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001840
Robert Carrdb66e622017-04-10 16:55:57 -07001841void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1842 mCurrentState.zOrderRelatives.remove(relative);
1843 mCurrentState.sequence++;
1844 mCurrentState.modified = true;
1845 setTransactionFlags(eTransactionNeeded);
1846}
1847
1848void Layer::addZOrderRelative(const wp<Layer>& relative) {
1849 mCurrentState.zOrderRelatives.add(relative);
1850 mCurrentState.modified = true;
1851 mCurrentState.sequence++;
1852 setTransactionFlags(eTransactionNeeded);
1853}
1854
1855bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1856 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1857 if (handle == nullptr) {
1858 return false;
1859 }
1860 sp<Layer> relative = handle->owner.promote();
1861 if (relative == nullptr) {
1862 return false;
1863 }
1864
1865 mCurrentState.sequence++;
1866 mCurrentState.modified = true;
1867 mCurrentState.z = z;
1868
1869 mCurrentState.zOrderRelativeOf = relative;
1870 relative->addZOrderRelative(this);
1871
1872 setTransactionFlags(eTransactionNeeded);
1873
1874 return true;
1875}
1876
Mathias Agopian13127d82013-03-05 17:47:11 -08001877bool Layer::setSize(uint32_t w, uint32_t h) {
1878 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1879 return false;
1880 mCurrentState.requested.w = w;
1881 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001882 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001883 setTransactionFlags(eTransactionNeeded);
1884 return true;
1885}
Dan Stoza9e56aa02015-11-02 13:00:03 -08001886bool Layer::setAlpha(float alpha) {
chaviw13fdc492017-06-27 12:40:18 -07001887 if (mCurrentState.color.a == alpha)
Mathias Agopian13127d82013-03-05 17:47:11 -08001888 return false;
1889 mCurrentState.sequence++;
chaviw13fdc492017-06-27 12:40:18 -07001890 mCurrentState.color.a = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001891 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001892 setTransactionFlags(eTransactionNeeded);
1893 return true;
1894}
chaviw13fdc492017-06-27 12:40:18 -07001895
1896bool Layer::setColor(const half3& color) {
1897 if (color.r == mCurrentState.color.r && color.g == mCurrentState.color.g
1898 && color.b == mCurrentState.color.b)
1899 return false;
1900
1901 mCurrentState.sequence++;
1902 mCurrentState.color.r = color.r;
1903 mCurrentState.color.g = color.g;
1904 mCurrentState.color.b = color.b;
1905 mCurrentState.modified = true;
1906 setTransactionFlags(eTransactionNeeded);
1907 return true;
1908}
1909
Mathias Agopian13127d82013-03-05 17:47:11 -08001910bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1911 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001912 mCurrentState.requested.transform.set(
Robert Carrcb6e1e32017-02-21 19:48:26 -08001913 matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001914 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001915 setTransactionFlags(eTransactionNeeded);
1916 return true;
1917}
1918bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001919 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001920 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001921 setTransactionFlags(eTransactionNeeded);
1922 return true;
1923}
1924bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1925 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1926 if (mCurrentState.flags == newFlags)
1927 return false;
1928 mCurrentState.sequence++;
1929 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001930 mCurrentState.mask = mask;
1931 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001932 setTransactionFlags(eTransactionNeeded);
1933 return true;
1934}
Robert Carr99e27f02016-06-16 15:18:02 -07001935
1936bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001937 if (mCurrentState.requestedCrop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001938 return false;
1939 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001940 mCurrentState.requestedCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001941 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr99e27f02016-06-16 15:18:02 -07001942 mCurrentState.crop = crop;
1943 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001944 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1945
Dan Stoza7dde5992015-05-22 09:51:44 -07001946 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001947 setTransactionFlags(eTransactionNeeded);
1948 return true;
1949}
Robert Carr8d5227b2017-03-16 15:41:03 -07001950
1951bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001952 if (mCurrentState.requestedFinalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001953 return false;
1954 mCurrentState.sequence++;
Robert Carr8d5227b2017-03-16 15:41:03 -07001955 mCurrentState.requestedFinalCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001956 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr8d5227b2017-03-16 15:41:03 -07001957 mCurrentState.finalCrop = crop;
1958 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001959 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1960
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001961 mCurrentState.modified = true;
1962 setTransactionFlags(eTransactionNeeded);
1963 return true;
1964}
Mathias Agopian13127d82013-03-05 17:47:11 -08001965
Robert Carrc3574f72016-03-24 12:19:32 -07001966bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1967 if (scalingMode == mOverrideScalingMode)
1968 return false;
1969 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001970 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001971 return true;
1972}
1973
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001974void Layer::setInfo(uint32_t type, uint32_t appId) {
1975 mCurrentState.appId = appId;
1976 mCurrentState.type = type;
1977 mCurrentState.modified = true;
1978 setTransactionFlags(eTransactionNeeded);
1979}
1980
Robert Carrc3574f72016-03-24 12:19:32 -07001981uint32_t Layer::getEffectiveScalingMode() const {
1982 if (mOverrideScalingMode >= 0) {
1983 return mOverrideScalingMode;
1984 }
1985 return mCurrentScalingMode;
1986}
1987
Mathias Agopian13127d82013-03-05 17:47:11 -08001988bool Layer::setLayerStack(uint32_t layerStack) {
1989 if (mCurrentState.layerStack == layerStack)
1990 return false;
1991 mCurrentState.sequence++;
1992 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001993 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001994 setTransactionFlags(eTransactionNeeded);
1995 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001996}
1997
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07001998bool Layer::setDataSpace(android_dataspace dataSpace) {
1999 if (mCurrentState.dataSpace == dataSpace)
2000 return false;
2001 mCurrentState.sequence++;
2002 mCurrentState.dataSpace = dataSpace;
2003 mCurrentState.modified = true;
2004 setTransactionFlags(eTransactionNeeded);
2005 return true;
2006}
2007
Courtney Goeltzenleuchter532b2632017-05-05 16:34:38 -06002008android_dataspace Layer::getDataSpace() const {
2009 return mCurrentState.dataSpace;
2010}
2011
Robert Carr1f0a16a2016-10-24 16:27:39 -07002012uint32_t Layer::getLayerStack() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002013 auto p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002014 if (p == nullptr) {
2015 return getDrawingState().layerStack;
2016 }
2017 return p->getLayerStack();
2018}
2019
Robert Carr0d480722017-01-10 16:42:54 -08002020void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
Dan Stoza7dde5992015-05-22 09:51:44 -07002021 uint64_t frameNumber) {
Robert Carr0d480722017-01-10 16:42:54 -08002022 mCurrentState.barrierLayer = barrierLayer;
Dan Stoza7dde5992015-05-22 09:51:44 -07002023 mCurrentState.frameNumber = frameNumber;
2024 // We don't set eTransactionNeeded, because just receiving a deferral
2025 // request without any other state updates shouldn't actually induce a delay
2026 mCurrentState.modified = true;
2027 pushPendingState();
Robert Carr0d480722017-01-10 16:42:54 -08002028 mCurrentState.barrierLayer = nullptr;
Dan Stoza792e5292016-02-11 11:43:58 -08002029 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07002030 mCurrentState.modified = false;
Robert Carr0d480722017-01-10 16:42:54 -08002031}
2032
2033void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
2034 uint64_t frameNumber) {
2035 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
2036 deferTransactionUntil(handle->owner.promote(), frameNumber);
Dan Stoza7dde5992015-05-22 09:51:44 -07002037}
2038
Dan Stozaee44edd2015-03-23 15:50:23 -07002039void Layer::useSurfaceDamage() {
2040 if (mFlinger->mForceFullDamage) {
2041 surfaceDamageRegion = Region::INVALID_REGION;
2042 } else {
2043 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
2044 }
2045}
2046
2047void Layer::useEmptyDamage() {
2048 surfaceDamageRegion.clear();
2049}
2050
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002051// ----------------------------------------------------------------------------
2052// pageflip handling...
2053// ----------------------------------------------------------------------------
2054
Dan Stoza6b9454d2014-11-07 16:00:59 -08002055bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08002056 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07002057 return true;
2058 }
2059
Dan Stoza6b9454d2014-11-07 16:00:59 -08002060 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07002061 if (mQueueItems.empty()) {
2062 return false;
2063 }
2064 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002065 nsecs_t expectedPresent =
2066 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07002067
2068 // Ignore timestamps more than a second in the future
2069 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
2070 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
2071 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
2072 expectedPresent);
2073
2074 bool isDue = timestamp < expectedPresent;
2075 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002076}
2077
Brian Andersond6927fb2016-07-23 23:37:30 -07002078bool Layer::onPreComposition(nsecs_t refreshStartTime) {
2079 if (mBufferLatched) {
2080 Mutex::Autolock lock(mFrameEventHistoryMutex);
2081 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
2082 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08002083 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08002084 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002085}
2086
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002087bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
Brian Anderson3d4039d2016-09-23 16:31:30 -07002088 const std::shared_ptr<FenceTime>& presentFence,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002089 const CompositorTiming& compositorTiming) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002090 // mFrameLatencyNeeded is true when a new frame was latched for the
2091 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08002092 if (!mFrameLatencyNeeded)
2093 return false;
2094
Fabien Sanglard28e98082016-12-05 10:19:46 -08002095 // Update mFrameEventHistory.
2096 {
2097 Mutex::Autolock lock(mFrameEventHistoryMutex);
2098 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002099 glDoneFence, presentFence, compositorTiming);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002100 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08002101
2102 // Update mFrameTracker.
2103 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
2104 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
2105
Brian Anderson3d4039d2016-09-23 16:31:30 -07002106 std::shared_ptr<FenceTime> frameReadyFence =
2107 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08002108 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002109 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002110 } else {
2111 // There was no fence for this frame, so assume that it was ready
2112 // to be presented at the desired present time.
2113 mFrameTracker.setFrameReadyTime(desiredPresentTime);
2114 }
2115
Brian Anderson3d4039d2016-09-23 16:31:30 -07002116 if (presentFence->isValid()) {
2117 mFrameTracker.setActualPresentFence(
2118 std::shared_ptr<FenceTime>(presentFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002119 } else {
2120 // The HWC doesn't support present fences, so use the refresh
2121 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002122 mFrameTracker.setActualPresentTime(
2123 mFlinger->getHwComposer().getRefreshTimestamp(
2124 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002125 }
2126
2127 mFrameTracker.advanceFrame();
2128 mFrameLatencyNeeded = false;
2129 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002130}
2131
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002132#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07002133void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Brian Anderson5ea5e592016-12-01 16:54:33 -08002134 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2135 return;
2136 }
2137
Brian Anderson3d4039d2016-09-23 16:31:30 -07002138 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002139 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002140 mReleaseTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002141 mReleaseTimeline.push(releaseFenceTime);
2142
2143 Mutex::Autolock lock(mFrameEventHistoryMutex);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002144 if (mPreviousFrameNumber != 0) {
2145 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2146 dequeueReadyTime, std::move(releaseFenceTime));
2147 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002148}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002149#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002150
Robert Carr1f0a16a2016-10-24 16:27:39 -07002151bool Layer::isHiddenByPolicy() const {
2152 const Layer::State& s(mDrawingState);
Chia-I Wue41dbe62017-06-13 14:10:56 -07002153 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002154 if (parent != nullptr && parent->isHiddenByPolicy()) {
2155 return true;
2156 }
2157 return s.flags & layer_state_t::eLayerHidden;
2158}
2159
Mathias Agopianda27af92012-09-13 18:17:13 -07002160bool Layer::isVisible() const {
Robert Carr6452f122017-03-21 10:41:29 -07002161 return !(isHiddenByPolicy()) && getAlpha() > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08002162 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Mathias Agopianda27af92012-09-13 18:17:13 -07002163}
2164
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002165bool Layer::allTransactionsSignaled() {
2166 auto headFrameNumber = getHeadFrameNumber();
2167 bool matchingFramesFound = false;
2168 bool allTransactionsApplied = true;
2169 Mutex::Autolock lock(mLocalSyncPointMutex);
2170
2171 for (auto& point : mLocalSyncPoints) {
2172 if (point->getFrameNumber() > headFrameNumber) {
2173 break;
2174 }
2175 matchingFramesFound = true;
2176
2177 if (!point->frameIsAvailable()) {
2178 // We haven't notified the remote layer that the frame for
2179 // this point is available yet. Notify it now, and then
2180 // abort this attempt to latch.
2181 point->setFrameAvailable();
2182 allTransactionsApplied = false;
2183 break;
2184 }
2185
2186 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2187 }
2188 return !matchingFramesFound || allTransactionsApplied;
2189}
2190
Brian Andersond6927fb2016-07-23 23:37:30 -07002191Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002192{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08002193 ATRACE_CALL();
2194
Jesse Hall399184a2014-03-03 15:42:54 -08002195 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2196 // mSidebandStreamChanged was true
2197 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07002198 if (mSidebandStream != NULL) {
2199 setTransactionFlags(eTransactionNeeded);
2200 mFlinger->setTransactionFlags(eTraversalNeeded);
2201 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07002202 recomputeVisibleRegions = true;
2203
2204 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07002205 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08002206 }
2207
Mathias Agopian4fec8732012-06-29 14:12:52 -07002208 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07002209 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2210 return outDirtyRegion;
2211 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002212
Fabien Sanglard223eb912016-10-13 10:15:06 -07002213 // if we've already called updateTexImage() without going through
2214 // a composition step, we have to skip this layer at this point
2215 // because we cannot call updateTeximage() without a corresponding
2216 // compositionComplete() call.
2217 // we'll trigger an update in onPreComposition().
2218 if (mRefreshPending) {
2219 return outDirtyRegion;
2220 }
2221
2222 // If the head buffer's acquire fence hasn't signaled yet, return and
2223 // try again later
2224 if (!headFenceHasSignaled()) {
2225 mFlinger->signalLayerUpdate();
2226 return outDirtyRegion;
2227 }
2228
2229 // Capture the old state of the layer for comparisons later
2230 const State& s(getDrawingState());
2231 const bool oldOpacity = isOpaque(s);
2232 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2233
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002234 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002235 mFlinger->signalLayerUpdate();
2236 return outDirtyRegion;
2237 }
2238
2239 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2240 // of the buffer queue isn't modified when the buffer queue is returning
2241 // BufferItem's that weren't actually queued. This can happen in shared
2242 // buffer mode.
2243 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002244 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2245 getProducerStickyTransform() != 0, mName.string(),
Robert Carr7bf247e2017-05-18 14:02:49 -07002246 mOverrideScalingMode, mFreezeGeometryUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002247 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2248 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2249 mLastFrameNumberReceived);
2250 if (updateResult == BufferQueue::PRESENT_LATER) {
2251 // Producer doesn't want buffer to be displayed yet. Signal a
2252 // layer update so we check again at the next opportunity.
2253 mFlinger->signalLayerUpdate();
2254 return outDirtyRegion;
2255 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2256 // If the buffer has been rejected, remove it from the shadow queue
2257 // and return early
2258 if (queuedBuffer) {
2259 Mutex::Autolock lock(mQueueItemLock);
2260 mQueueItems.removeAt(0);
2261 android_atomic_dec(&mQueuedFrames);
2262 }
2263 return outDirtyRegion;
2264 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2265 // This can occur if something goes wrong when trying to create the
2266 // EGLImage for this buffer. If this happens, the buffer has already
2267 // been released, so we need to clean up the queue and bug out
2268 // early.
2269 if (queuedBuffer) {
2270 Mutex::Autolock lock(mQueueItemLock);
2271 mQueueItems.clear();
2272 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002273 }
2274
Fabien Sanglard223eb912016-10-13 10:15:06 -07002275 // Once we have hit this state, the shadow queue may no longer
2276 // correctly reflect the incoming BufferQueue's contents, so even if
2277 // updateTexImage starts working, the only safe course of action is
2278 // to continue to ignore updates.
2279 mUpdateTexImageFailed = true;
2280
2281 return outDirtyRegion;
2282 }
2283
2284 if (queuedBuffer) {
2285 // Autolock scope
2286 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2287
2288 Mutex::Autolock lock(mQueueItemLock);
2289
2290 // Remove any stale buffers that have been dropped during
2291 // updateTexImage
2292 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2293 mQueueItems.removeAt(0);
2294 android_atomic_dec(&mQueuedFrames);
2295 }
2296
2297 mQueueItems.removeAt(0);
2298 }
2299
2300
2301 // Decrement the queued-frames count. Signal another event if we
2302 // have more frames pending.
2303 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2304 || mAutoRefresh) {
2305 mFlinger->signalLayerUpdate();
2306 }
2307
Fabien Sanglard223eb912016-10-13 10:15:06 -07002308 // update the active buffer
Chia-I Wu06d63de2017-01-04 14:58:51 +08002309 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2310 &mActiveBufferSlot);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002311 if (mActiveBuffer == NULL) {
2312 // this can only happen if the very first buffer was rejected.
2313 return outDirtyRegion;
2314 }
2315
Brian Andersond6927fb2016-07-23 23:37:30 -07002316 mBufferLatched = true;
2317 mPreviousFrameNumber = mCurrentFrameNumber;
2318 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2319
2320 {
2321 Mutex::Autolock lock(mFrameEventHistoryMutex);
2322 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2323#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002324 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002325 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002326 mReleaseTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002327 mReleaseTimeline.push(releaseFenceTime);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002328 if (mPreviousFrameNumber != 0) {
2329 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2330 latchTime, std::move(releaseFenceTime));
2331 }
Brian Andersond6927fb2016-07-23 23:37:30 -07002332#endif
2333 }
2334
Fabien Sanglard223eb912016-10-13 10:15:06 -07002335 mRefreshPending = true;
2336 mFrameLatencyNeeded = true;
2337 if (oldActiveBuffer == NULL) {
2338 // the first time we receive a buffer, we need to trigger a
2339 // geometry invalidation.
2340 recomputeVisibleRegions = true;
2341 }
2342
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002343 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2344
Fabien Sanglard223eb912016-10-13 10:15:06 -07002345 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2346 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2347 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2348 if ((crop != mCurrentCrop) ||
2349 (transform != mCurrentTransform) ||
2350 (scalingMode != mCurrentScalingMode))
2351 {
2352 mCurrentCrop = crop;
2353 mCurrentTransform = transform;
2354 mCurrentScalingMode = scalingMode;
2355 recomputeVisibleRegions = true;
2356 }
2357
2358 if (oldActiveBuffer != NULL) {
2359 uint32_t bufWidth = mActiveBuffer->getWidth();
2360 uint32_t bufHeight = mActiveBuffer->getHeight();
2361 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2362 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002363 recomputeVisibleRegions = true;
2364 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002365 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002366
Fabien Sanglard223eb912016-10-13 10:15:06 -07002367 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2368 if (oldOpacity != isOpaque(s)) {
2369 recomputeVisibleRegions = true;
2370 }
Dan Stozacac35382016-01-27 12:21:06 -08002371
Fabien Sanglard223eb912016-10-13 10:15:06 -07002372 // Remove any sync points corresponding to the buffer which was just
2373 // latched
2374 {
2375 Mutex::Autolock lock(mLocalSyncPointMutex);
2376 auto point = mLocalSyncPoints.begin();
2377 while (point != mLocalSyncPoints.end()) {
2378 if (!(*point)->frameIsAvailable() ||
2379 !(*point)->transactionIsApplied()) {
2380 // This sync point must have been added since we started
2381 // latching. Don't drop it yet.
2382 ++point;
2383 continue;
2384 }
2385
2386 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2387 point = mLocalSyncPoints.erase(point);
2388 } else {
2389 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002390 }
2391 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002392 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002393
2394 // FIXME: postedRegion should be dirty & bounds
2395 Region dirtyRegion(Rect(s.active.w, s.active.h));
2396
2397 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002398 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002399
Mathias Agopian4fec8732012-06-29 14:12:52 -07002400 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002401}
2402
Mathias Agopiana67932f2011-04-20 14:20:59 -07002403uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002404{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002405 // TODO: should we do something special if mSecure is set?
2406 if (mProtectedByApp) {
2407 // need a hardware-protected path to external video sink
2408 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002409 }
Riley Andrews03414a12014-07-01 14:22:59 -07002410 if (mPotentialCursor) {
2411 usage |= GraphicBuffer::USAGE_CURSOR;
2412 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002413 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002414 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002415}
2416
Mathias Agopian84300952012-11-21 16:02:13 -08002417void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002418 uint32_t orientation = 0;
2419 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002420 // The transform hint is used to improve performance, but we can
2421 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002422 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002423 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002424 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002425 if (orientation & Transform::ROT_INVALID) {
2426 orientation = 0;
2427 }
2428 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002429 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002430}
2431
Mathias Agopian13127d82013-03-05 17:47:11 -08002432// ----------------------------------------------------------------------------
2433// debugging
2434// ----------------------------------------------------------------------------
2435
Kalle Raitaa099a242017-01-11 11:17:29 -08002436LayerDebugInfo Layer::getLayerDebugInfo() const {
2437 LayerDebugInfo info;
2438 const Layer::State& ds = getDrawingState();
2439 info.mName = getName();
chaviw1acbec72017-07-27 15:28:26 -07002440 sp<Layer> parent = getParent();
Kalle Raitaa099a242017-01-11 11:17:29 -08002441 info.mParentName = (parent == nullptr ? std::string("none") : parent->getName().string());
2442 info.mType = String8(getTypeId());
2443 info.mTransparentRegion = ds.activeTransparentRegion;
2444 info.mVisibleRegion = visibleRegion;
2445 info.mSurfaceDamageRegion = surfaceDamageRegion;
2446 info.mLayerStack = getLayerStack();
2447 info.mX = ds.active.transform.tx();
2448 info.mY = ds.active.transform.ty();
2449 info.mZ = ds.z;
2450 info.mWidth = ds.active.w;
2451 info.mHeight = ds.active.h;
2452 info.mCrop = ds.crop;
2453 info.mFinalCrop = ds.finalCrop;
chaviw13fdc492017-06-27 12:40:18 -07002454 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08002455 info.mFlags = ds.flags;
2456 info.mPixelFormat = getPixelFormat();
2457 info.mDataSpace = getDataSpace();
2458 info.mMatrix[0][0] = ds.active.transform[0][0];
2459 info.mMatrix[0][1] = ds.active.transform[0][1];
2460 info.mMatrix[1][0] = ds.active.transform[1][0];
2461 info.mMatrix[1][1] = ds.active.transform[1][1];
2462 {
2463 sp<const GraphicBuffer> activeBuffer = getActiveBuffer();
2464 if (activeBuffer != 0) {
2465 info.mActiveBufferWidth = activeBuffer->getWidth();
2466 info.mActiveBufferHeight = activeBuffer->getHeight();
2467 info.mActiveBufferStride = activeBuffer->getStride();
2468 info.mActiveBufferFormat = activeBuffer->format;
2469 } else {
2470 info.mActiveBufferWidth = 0;
2471 info.mActiveBufferHeight = 0;
2472 info.mActiveBufferStride = 0;
2473 info.mActiveBufferFormat = 0;
2474 }
Mathias Agopian13127d82013-03-05 17:47:11 -08002475 }
Kalle Raitaa099a242017-01-11 11:17:29 -08002476 info.mNumQueuedFrames = getQueuedFrameCount();
2477 info.mRefreshPending = isBufferLatched();
2478 info.mIsOpaque = isOpaque(ds);
2479 info.mContentDirty = contentDirty;
2480 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08002481}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002482#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002483void Layer::miniDumpHeader(String8& result) {
2484 result.append("----------------------------------------");
2485 result.append("---------------------------------------\n");
2486 result.append(" Layer name\n");
2487 result.append(" Z | ");
2488 result.append(" Comp Type | ");
2489 result.append(" Disp Frame (LTRB) | ");
2490 result.append(" Source Crop (LTRB)\n");
2491 result.append("----------------------------------------");
2492 result.append("---------------------------------------\n");
2493}
2494
2495void Layer::miniDump(String8& result, int32_t hwcId) const {
2496 if (mHwcLayers.count(hwcId) == 0) {
2497 return;
2498 }
2499
2500 String8 name;
2501 if (mName.length() > 77) {
2502 std::string shortened;
2503 shortened.append(mName.string(), 36);
2504 shortened.append("[...]");
2505 shortened.append(mName.string() + (mName.length() - 36), 36);
2506 name = shortened.c_str();
2507 } else {
2508 name = mName;
2509 }
2510
2511 result.appendFormat(" %s\n", name.string());
2512
2513 const Layer::State& layerState(getDrawingState());
2514 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
John Reck8c3b6ac2017-08-24 10:25:42 -07002515 result.appendFormat(" %10d | ", layerState.z);
Dan Stozae22aec72016-08-01 13:20:59 -07002516 result.appendFormat("%10s | ",
2517 to_string(getCompositionType(hwcId)).c_str());
2518 const Rect& frame = hwcInfo.displayFrame;
2519 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2520 frame.right, frame.bottom);
Dan Stoza5a423ea2017-02-16 14:10:39 -08002521 const FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002522 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2523 crop.right, crop.bottom);
2524
2525 result.append("- - - - - - - - - - - - - - - - - - - - ");
2526 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2527}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002528#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002529
Svetoslavd85084b2014-03-20 10:28:31 -07002530void Layer::dumpFrameStats(String8& result) const {
2531 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002532}
2533
Svetoslavd85084b2014-03-20 10:28:31 -07002534void Layer::clearFrameStats() {
2535 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002536}
2537
Jamie Gennis6547ff42013-07-16 20:12:42 -07002538void Layer::logFrameStats() {
2539 mFrameTracker.logAndResetStats(mName);
2540}
2541
Svetoslavd85084b2014-03-20 10:28:31 -07002542void Layer::getFrameStats(FrameStats* outStats) const {
2543 mFrameTracker.getStats(outStats);
2544}
2545
Brian Andersond6927fb2016-07-23 23:37:30 -07002546void Layer::dumpFrameEvents(String8& result) {
2547 result.appendFormat("- Layer %s (%s, %p)\n",
2548 getName().string(), getTypeId(), this);
2549 Mutex::Autolock lock(mFrameEventHistoryMutex);
2550 mFrameEventHistory.checkFencesForCompletion();
2551 mFrameEventHistory.dump(result);
2552}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002553
Brian Anderson5ea5e592016-12-01 16:54:33 -08002554void Layer::onDisconnect() {
2555 Mutex::Autolock lock(mFrameEventHistoryMutex);
2556 mFrameEventHistory.onDisconnect();
2557}
2558
Brian Anderson3890c392016-07-25 12:48:08 -07002559void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2560 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002561 Mutex::Autolock lock(mFrameEventHistoryMutex);
2562 if (newTimestamps) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002563 // If there are any unsignaled fences in the aquire timeline at this
2564 // point, the previously queued frame hasn't been latched yet. Go ahead
2565 // and try to get the signal time here so the syscall is taken out of
2566 // the main thread's critical path.
2567 mAcquireTimeline.updateSignalTimes();
2568 // Push the new fence after updating since it's likely still pending.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002569 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002570 mFrameEventHistory.addQueue(*newTimestamps);
2571 }
2572
Brian Anderson3890c392016-07-25 12:48:08 -07002573 if (outDelta) {
2574 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002575 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002576}
Dan Stozae77c7662016-05-13 11:37:28 -07002577
2578std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2579 bool forceFlush) {
2580 std::vector<OccupancyTracker::Segment> history;
2581 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2582 &history);
2583 if (result != NO_ERROR) {
2584 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2585 result);
2586 return {};
2587 }
2588 return history;
2589}
2590
Robert Carr367c5682016-06-20 11:55:28 -07002591bool Layer::getTransformToDisplayInverse() const {
2592 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2593}
2594
Chia-I Wu98f1c102017-05-30 14:54:08 -07002595size_t Layer::getChildrenCount() const {
2596 size_t count = 0;
2597 for (const sp<Layer>& child : mCurrentChildren) {
2598 count += 1 + child->getChildrenCount();
2599 }
2600 return count;
2601}
2602
Robert Carr1f0a16a2016-10-24 16:27:39 -07002603void Layer::addChild(const sp<Layer>& layer) {
2604 mCurrentChildren.add(layer);
2605 layer->setParent(this);
2606}
2607
2608ssize_t Layer::removeChild(const sp<Layer>& layer) {
2609 layer->setParent(nullptr);
2610 return mCurrentChildren.remove(layer);
2611}
2612
Robert Carr1db73f62016-12-21 12:58:51 -08002613bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2614 sp<Handle> handle = nullptr;
2615 sp<Layer> newParent = nullptr;
2616 if (newParentHandle == nullptr) {
2617 return false;
2618 }
2619 handle = static_cast<Handle*>(newParentHandle.get());
2620 newParent = handle->owner.promote();
2621 if (newParent == nullptr) {
2622 ALOGE("Unable to promote Layer handle");
2623 return false;
2624 }
2625
2626 for (const sp<Layer>& child : mCurrentChildren) {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002627 newParent->addChild(child);
Robert Carr1db73f62016-12-21 12:58:51 -08002628
2629 sp<Client> client(child->mClientRef.promote());
2630 if (client != nullptr) {
2631 client->setParentLayer(newParent);
2632 }
2633 }
2634 mCurrentChildren.clear();
2635
2636 return true;
2637}
2638
chaviwf1961f72017-09-18 16:41:07 -07002639bool Layer::reparent(const sp<IBinder>& newParentHandle) {
2640 if (newParentHandle == nullptr) {
chaviw06178942017-07-27 10:25:59 -07002641 return false;
2642 }
2643
2644 auto handle = static_cast<Handle*>(newParentHandle.get());
2645 sp<Layer> newParent = handle->owner.promote();
2646 if (newParent == nullptr) {
2647 ALOGE("Unable to promote Layer handle");
2648 return false;
2649 }
2650
chaviwf1961f72017-09-18 16:41:07 -07002651 sp<Layer> parent = getParent();
2652 if (parent != nullptr) {
2653 parent->removeChild(this);
chaviw06178942017-07-27 10:25:59 -07002654 }
chaviwf1961f72017-09-18 16:41:07 -07002655 newParent->addChild(this);
chaviw06178942017-07-27 10:25:59 -07002656
chaviwf1961f72017-09-18 16:41:07 -07002657 sp<Client> client(mClientRef.promote());
chaviw06178942017-07-27 10:25:59 -07002658 sp<Client> newParentClient(newParent->mClientRef.promote());
2659
chaviwf1961f72017-09-18 16:41:07 -07002660 if (client != newParentClient) {
2661 client->setParentLayer(newParent);
chaviw06178942017-07-27 10:25:59 -07002662 }
2663
chaviw06178942017-07-27 10:25:59 -07002664 return true;
2665}
2666
Robert Carr9524cb32017-02-13 11:32:32 -08002667bool Layer::detachChildren() {
Dan Stoza412903f2017-04-27 13:42:17 -07002668 traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
Robert Carr9524cb32017-02-13 11:32:32 -08002669 if (child == this) {
2670 return;
2671 }
2672
chaviw161410b02017-07-27 10:46:08 -07002673 sp<Client> parentClient = mClientRef.promote();
Robert Carr9524cb32017-02-13 11:32:32 -08002674 sp<Client> client(child->mClientRef.promote());
chaviw161410b02017-07-27 10:46:08 -07002675 if (client != nullptr && parentClient != client) {
Robert Carr9524cb32017-02-13 11:32:32 -08002676 client->detachLayer(child);
2677 }
2678 });
2679
2680 return true;
2681}
2682
Robert Carr1f0a16a2016-10-24 16:27:39 -07002683void Layer::setParent(const sp<Layer>& layer) {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002684 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002685}
2686
2687void Layer::clearSyncPoints() {
2688 for (const auto& child : mCurrentChildren) {
2689 child->clearSyncPoints();
2690 }
2691
2692 Mutex::Autolock lock(mLocalSyncPointMutex);
2693 for (auto& point : mLocalSyncPoints) {
2694 point->setFrameAvailable();
2695 }
2696 mLocalSyncPoints.clear();
2697}
2698
2699int32_t Layer::getZ() const {
2700 return mDrawingState.z;
2701}
2702
Dan Stoza412903f2017-04-27 13:42:17 -07002703LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2704 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2705 "makeTraversalList received invalid stateSet");
2706 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2707 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2708 const State& state = useDrawing ? mDrawingState : mCurrentState;
2709
2710 if (state.zOrderRelatives.size() == 0) {
2711 return children;
Robert Carrdb66e622017-04-10 16:55:57 -07002712 }
2713 LayerVector traverse;
2714
Dan Stoza412903f2017-04-27 13:42:17 -07002715 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07002716 sp<Layer> strongRelative = weakRelative.promote();
2717 if (strongRelative != nullptr) {
2718 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07002719 }
2720 }
2721
Dan Stoza412903f2017-04-27 13:42:17 -07002722 for (const sp<Layer>& child : children) {
Robert Carrdb66e622017-04-10 16:55:57 -07002723 traverse.add(child);
2724 }
2725
2726 return traverse;
2727}
2728
Robert Carr1f0a16a2016-10-24 16:27:39 -07002729/**
Robert Carrdb66e622017-04-10 16:55:57 -07002730 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002731 */
Dan Stoza412903f2017-04-27 13:42:17 -07002732void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2733 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002734
Robert Carr1f0a16a2016-10-24 16:27:39 -07002735 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002736 for (; i < list.size(); i++) {
2737 const auto& relative = list[i];
2738 if (relative->getZ() >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002739 break;
Robert Carrdb66e622017-04-10 16:55:57 -07002740 }
Dan Stoza412903f2017-04-27 13:42:17 -07002741 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002742 }
Dan Stoza412903f2017-04-27 13:42:17 -07002743 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07002744 for (; i < list.size(); i++) {
2745 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002746 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002747 }
2748}
2749
2750/**
Robert Carrdb66e622017-04-10 16:55:57 -07002751 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002752 */
Dan Stoza412903f2017-04-27 13:42:17 -07002753void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2754 const LayerVector::Visitor& visitor) {
2755 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002756
Robert Carr1f0a16a2016-10-24 16:27:39 -07002757 int32_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002758 for (i = list.size()-1; i>=0; i--) {
2759 const auto& relative = list[i];
2760 if (relative->getZ() < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002761 break;
2762 }
Dan Stoza412903f2017-04-27 13:42:17 -07002763 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002764 }
Dan Stoza412903f2017-04-27 13:42:17 -07002765 visitor(this);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002766 for (; i>=0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002767 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002768 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002769 }
2770}
2771
chaviwa76b2712017-09-20 12:02:26 -07002772/**
2773 * Traverse only children in z order, ignoring relative layers.
2774 */
2775void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2776 const LayerVector::Visitor& visitor) {
2777 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2778 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2779
2780 size_t i = 0;
2781 for (; i < children.size(); i++) {
2782 const auto& relative = children[i];
2783 if (relative->getZ() >= 0) {
2784 break;
2785 }
2786 relative->traverseChildrenInZOrder(stateSet, visitor);
2787 }
2788 visitor(this);
2789 for (; i < children.size(); i++) {
2790 const auto& relative = children[i];
2791 relative->traverseChildrenInZOrder(stateSet, visitor);
2792 }
2793}
2794
Robert Carr1f0a16a2016-10-24 16:27:39 -07002795Transform Layer::getTransform() const {
2796 Transform t;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002797 const auto& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002798 if (p != nullptr) {
2799 t = p->getTransform();
Robert Carr9b429f42017-04-17 14:56:57 -07002800
2801 // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2802 // it isFixedSize) then there may be additional scaling not accounted
2803 // for in the transform. We need to mirror this scaling in child surfaces
2804 // or we will break the contract where WM can treat child surfaces as
2805 // pixels in the parent surface.
Chia-I Wu0a68b462017-07-18 11:30:05 -07002806 if (p->isFixedSize() && p->mActiveBuffer != nullptr) {
Robert Carr1725eee2017-04-26 18:32:15 -07002807 int bufferWidth;
2808 int bufferHeight;
2809 if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2810 bufferWidth = p->mActiveBuffer->getWidth();
2811 bufferHeight = p->mActiveBuffer->getHeight();
2812 } else {
2813 bufferHeight = p->mActiveBuffer->getWidth();
2814 bufferWidth = p->mActiveBuffer->getHeight();
2815 }
Robert Carr9b429f42017-04-17 14:56:57 -07002816 float sx = p->getDrawingState().active.w /
Robert Carr1725eee2017-04-26 18:32:15 -07002817 static_cast<float>(bufferWidth);
Robert Carr9b429f42017-04-17 14:56:57 -07002818 float sy = p->getDrawingState().active.h /
Robert Carr1725eee2017-04-26 18:32:15 -07002819 static_cast<float>(bufferHeight);
Robert Carr9b429f42017-04-17 14:56:57 -07002820 Transform extraParentScaling;
2821 extraParentScaling.set(sx, 0, 0, sy);
2822 t = t * extraParentScaling;
2823 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002824 }
2825 return t * getDrawingState().active.transform;
2826}
2827
chaviw13fdc492017-06-27 12:40:18 -07002828half Layer::getAlpha() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002829 const auto& p = mDrawingParent.promote();
Robert Carr6452f122017-03-21 10:41:29 -07002830
chaviw13fdc492017-06-27 12:40:18 -07002831 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2832 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002833}
Robert Carr6452f122017-03-21 10:41:29 -07002834
chaviw13fdc492017-06-27 12:40:18 -07002835half4 Layer::getColor() const {
2836 const half4 color(getDrawingState().color);
2837 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002838}
Robert Carr6452f122017-03-21 10:41:29 -07002839
Robert Carr1f0a16a2016-10-24 16:27:39 -07002840void Layer::commitChildList() {
2841 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2842 const auto& child = mCurrentChildren[i];
2843 child->commitChildList();
2844 }
2845 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002846 mDrawingParent = mCurrentParent;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002847}
2848
chaviw1d044282017-09-27 12:19:28 -07002849void Layer::writeToProto(LayerProto* layerInfo, LayerVector::StateSet stateSet) {
2850 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2851 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2852 const State& state = useDrawing ? mDrawingState : mCurrentState;
2853
2854 Transform requestedTransform = state.active.transform;
2855 Transform transform = getTransform();
2856
2857 layerInfo->set_id(sequence);
2858 layerInfo->set_name(getName().c_str());
2859 layerInfo->set_type(String8(getTypeId()));
2860
2861 for (const auto& child : children) {
2862 layerInfo->add_children(child->sequence);
2863 }
2864
2865 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2866 sp<Layer> strongRelative = weakRelative.promote();
2867 if (strongRelative != nullptr) {
2868 layerInfo->add_relatives(strongRelative->sequence);
2869 }
2870 }
2871
2872 LayerProtoHelper::writeToProto(state.activeTransparentRegion,
2873 layerInfo->mutable_transparent_region());
2874 LayerProtoHelper::writeToProto(visibleRegion, layerInfo->mutable_visible_region());
2875 LayerProtoHelper::writeToProto(surfaceDamageRegion, layerInfo->mutable_damage_region());
2876
2877 layerInfo->set_layer_stack(getLayerStack());
2878 layerInfo->set_z(state.z);
2879
2880 PositionProto* position = layerInfo->mutable_position();
2881 position->set_x(transform.tx());
2882 position->set_y(transform.ty());
2883
2884 PositionProto* requestedPosition = layerInfo->mutable_requested_position();
2885 requestedPosition->set_x(requestedTransform.tx());
2886 requestedPosition->set_y(requestedTransform.ty());
2887
2888 SizeProto* size = layerInfo->mutable_size();
2889 size->set_w(state.active.w);
2890 size->set_h(state.active.h);
2891
2892 LayerProtoHelper::writeToProto(state.crop, layerInfo->mutable_crop());
2893 LayerProtoHelper::writeToProto(state.finalCrop, layerInfo->mutable_final_crop());
2894
2895 layerInfo->set_is_opaque(isOpaque(state));
2896 layerInfo->set_invalidate(contentDirty);
2897 layerInfo->set_dataspace(dataspaceDetails(getDataSpace()));
2898 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2899 LayerProtoHelper::writeToProto(getColor(), layerInfo->mutable_color());
2900 LayerProtoHelper::writeToProto(state.color, layerInfo->mutable_requested_color());
2901 layerInfo->set_flags(state.flags);
2902
2903 LayerProtoHelper::writeToProto(transform, layerInfo->mutable_transform());
2904 LayerProtoHelper::writeToProto(requestedTransform, layerInfo->mutable_requested_transform());
2905
2906 auto parent = getParent();
2907 if (parent != nullptr) {
2908 layerInfo->set_parent(parent->sequence);
2909 }
2910
2911 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2912 if (zOrderRelativeOf != nullptr) {
2913 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2914 }
2915
2916 auto activeBuffer = getActiveBuffer();
2917 if (activeBuffer != nullptr) {
2918 LayerProtoHelper::writeToProto(activeBuffer, layerInfo->mutable_active_buffer());
2919 }
2920
2921 layerInfo->set_queued_frames(getQueuedFrameCount());
2922 layerInfo->set_refresh_pending(isBufferLatched());
2923}
2924
Mathias Agopian13127d82013-03-05 17:47:11 -08002925// ---------------------------------------------------------------------------
2926
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002927}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002928
2929#if defined(__gl_h_)
2930#error "don't include gl/gl.h in this file"
2931#endif
2932
2933#if defined(__gl2_h_)
2934#error "don't include gl2/gl2.h in this file"
2935#endif