blob: 27739ce074c38fb28eedfa8b9cc5350353f342bf [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
1066void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -08001067 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -08001068}
1069
Dan Stozac7014012014-02-14 15:03:43 -08001070void Layer::draw(const sp<const DisplayDevice>& hw,
1071 bool useIdentityTransform) const {
1072 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001073}
1074
Dan Stozac7014012014-02-14 15:03:43 -08001075void Layer::draw(const sp<const DisplayDevice>& hw) const {
1076 onDraw(hw, Region(hw->bounds()), false);
1077}
1078
Robert Carrcae605c2017-03-29 12:10:31 -07001079static constexpr mat4 inverseOrientation(uint32_t transform) {
1080 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1081 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1082 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1083 mat4 tr;
1084
1085 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1086 tr = tr * rot90;
1087 }
1088 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1089 tr = tr * flipH;
1090 }
1091 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1092 tr = tr * flipV;
1093 }
1094 return inverse(tr);
1095}
1096
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001097/*
1098 * onDraw will draw the current layer onto the presentable buffer
1099 */
Dan Stozac7014012014-02-14 15:03:43 -08001100void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
1101 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001102{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001103 ATRACE_CALL();
1104
Mathias Agopiana67932f2011-04-20 14:20:59 -07001105 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001106 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -07001107 // in fact never been drawn into. This happens frequently with
1108 // SurfaceView because the WindowManager can't know when the client
1109 // has drawn the first time.
1110
1111 // If there is nothing under us, we paint the screen in black, otherwise
1112 // we just skip this update.
1113
1114 // figure out if there is something below us
1115 Region under;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001116 bool finished = false;
Dan Stoza412903f2017-04-27 13:42:17 -07001117 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001118 if (finished || layer == static_cast<Layer const*>(this)) {
1119 finished = true;
1120 return;
1121 }
Mathias Agopian42977342012-08-05 00:40:46 -07001122 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Robert Carr1f0a16a2016-10-24 16:27:39 -07001123 });
Mathias Agopian179169e2010-05-06 20:21:45 -07001124 // if not everything below us is covered, we plug the holes!
1125 Region holes(clip.subtract(under));
1126 if (!holes.isEmpty()) {
Fabien Sanglard17487192016-12-07 13:03:32 -08001127 clearWithOpenGL(hw, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -07001128 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001129 return;
1130 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001131
Andy McFadden97eba892012-12-11 15:21:45 -08001132 // Bind the current buffer to the GL texture, and wait for it to be
1133 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001134 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1135 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -08001136 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -07001137 // Go ahead and draw the buffer anyway; no matter what we do the screen
1138 // is probably going to have something visibly wrong.
1139 }
1140
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001141 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1142
Mathias Agopian875d8e12013-06-07 15:35:48 -07001143 RenderEngine& engine(mFlinger->getRenderEngine());
1144
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001145 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -07001146 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -07001147 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -07001148
1149 // Query the texture matrix given our current filtering mode.
1150 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001151 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1152 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -07001153
Robert Carrcae605c2017-03-29 12:10:31 -07001154 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001155
1156 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -07001157 * the code below applies the primary display's inverse transform to
1158 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001159 */
Pablo Ceballos021623b2016-04-15 17:31:51 -07001160 uint32_t transform =
1161 DisplayDevice::getPrimaryDisplayOrientationTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001162 mat4 tr = inverseOrientation(transform);
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001163
Robert Carrcae605c2017-03-29 12:10:31 -07001164 /**
1165 * TODO(b/36727915): This is basically a hack.
1166 *
1167 * Ensure that regardless of the parent transformation,
1168 * this buffer is always transformed from native display
1169 * orientation to display orientation. For example, in the case
1170 * of a camera where the buffer remains in native orientation,
1171 * we want the pixels to always be upright.
1172 */
Chia-I Wue41dbe62017-06-13 14:10:56 -07001173 sp<Layer> p = mDrawingParent.promote();
1174 if (p != nullptr) {
1175 const auto parentTransform = p->getTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001176 tr = tr * inverseOrientation(parentTransform.getOrientation());
1177 }
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001178
1179 // and finally apply it to the original texture matrix
1180 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1181 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1182 }
1183
Jamie Genniscbb1a952012-05-08 17:05:52 -07001184 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -07001185 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1186 mTexture.setFiltering(useFiltering);
1187 mTexture.setMatrix(textureMatrix);
1188
1189 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -07001190 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001191 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -07001192 }
Fabien Sanglard85789802016-12-07 13:08:24 -08001193 drawWithOpenGL(hw, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001194 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001195}
1196
Mathias Agopian13127d82013-03-05 17:47:11 -08001197
Dan Stozac7014012014-02-14 15:03:43 -08001198void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard17487192016-12-07 13:03:32 -08001199 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -08001200 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001201{
Mathias Agopian19733a32013-08-28 18:13:56 -07001202 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -08001203 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -07001204 engine.setupFillWithColor(red, green, blue, alpha);
1205 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -08001206}
1207
1208void Layer::clearWithOpenGL(
Fabien Sanglard17487192016-12-07 13:03:32 -08001209 const sp<const DisplayDevice>& hw) const {
1210 clearWithOpenGL(hw, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001211}
1212
Dan Stozac7014012014-02-14 15:03:43 -08001213void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard85789802016-12-07 13:08:24 -08001214 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001215 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001216
Dan Stozac7014012014-02-14 15:03:43 -08001217 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001218
Mathias Agopian13127d82013-03-05 17:47:11 -08001219 /*
1220 * NOTE: the way we compute the texture coordinates here produces
1221 * different results than when we take the HWC path -- in the later case
1222 * the "source crop" is rounded to texel boundaries.
1223 * This can produce significantly different results when the texture
1224 * is scaled by a large amount.
1225 *
1226 * The GL code below is more logical (imho), and the difference with
1227 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001228 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001229 * GL composition when a buffer scaling is applied (maybe with some
1230 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1231 * like more of a hack.
1232 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001233 Rect win(computeBounds());
1234
Robert Carr1f0a16a2016-10-24 16:27:39 -07001235 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -07001236 if (!s.finalCrop.isEmpty()) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001237 win = t.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001238 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001239 win.clear();
1240 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001241 win = t.inverse().transform(win);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001242 if (!win.intersect(computeBounds(), &win)) {
1243 win.clear();
1244 }
1245 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001246
Mathias Agopian3f844832013-08-07 21:24:32 -07001247 float left = float(win.left) / float(s.active.w);
1248 float top = float(win.top) / float(s.active.h);
1249 float right = float(win.right) / float(s.active.w);
1250 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001251
Mathias Agopian875d8e12013-06-07 15:35:48 -07001252 // TODO: we probably want to generate the texture coords with the mesh
1253 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001254 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1255 texCoords[0] = vec2(left, 1.0f - top);
1256 texCoords[1] = vec2(left, 1.0f - bottom);
1257 texCoords[2] = vec2(right, 1.0f - bottom);
1258 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001259
Mathias Agopian875d8e12013-06-07 15:35:48 -07001260 RenderEngine& engine(mFlinger->getRenderEngine());
chaviw13fdc492017-06-27 12:40:18 -07001261 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s),
1262 false /* disableTexture */, getColor());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001263#ifdef USE_HWC2
1264 engine.setSourceDataSpace(mCurrentState.dataSpace);
1265#endif
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001266 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001267 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001268}
1269
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001270#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001271void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1272 bool callIntoHwc) {
1273 if (mHwcLayers.count(hwcId) == 0) {
1274 ALOGE("setCompositionType called without a valid HWC layer");
1275 return;
1276 }
1277 auto& hwcInfo = mHwcLayers[hwcId];
1278 auto& hwcLayer = hwcInfo.layer;
1279 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1280 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1281 if (hwcInfo.compositionType != type) {
1282 ALOGV(" actually setting");
1283 hwcInfo.compositionType = type;
1284 if (callIntoHwc) {
1285 auto error = hwcLayer->setCompositionType(type);
1286 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1287 "composition type %s: %s (%d)", mName.string(),
1288 to_string(type).c_str(), to_string(error).c_str(),
1289 static_cast<int32_t>(error));
1290 }
1291 }
1292}
1293
1294HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001295 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1296 // If we're querying the composition type for a display that does not
1297 // have a HWC counterpart, then it will always be Client
1298 return HWC2::Composition::Client;
1299 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001300 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001301 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001302 return HWC2::Composition::Invalid;
1303 }
1304 return mHwcLayers.at(hwcId).compositionType;
1305}
1306
1307void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1308 if (mHwcLayers.count(hwcId) == 0) {
1309 ALOGE("setClearClientTarget called without a valid HWC layer");
1310 return;
1311 }
1312 mHwcLayers[hwcId].clearClientTarget = clear;
1313}
1314
1315bool Layer::getClearClientTarget(int32_t hwcId) const {
1316 if (mHwcLayers.count(hwcId) == 0) {
1317 ALOGE("getClearClientTarget called without a valid HWC layer");
1318 return false;
1319 }
1320 return mHwcLayers.at(hwcId).clearClientTarget;
1321}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001322#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001323
Ruben Brunk1681d952014-06-27 15:51:55 -07001324uint32_t Layer::getProducerStickyTransform() const {
1325 int producerStickyTransform = 0;
1326 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1327 if (ret != OK) {
1328 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1329 strerror(-ret), ret);
1330 return 0;
1331 }
1332 return static_cast<uint32_t>(producerStickyTransform);
1333}
1334
Dan Stozac5da2712016-07-20 15:38:12 -07001335bool Layer::latchUnsignaledBuffers() {
1336 static bool propertyLoaded = false;
1337 static bool latch = false;
1338 static std::mutex mutex;
1339 std::lock_guard<std::mutex> lock(mutex);
1340 if (!propertyLoaded) {
1341 char value[PROPERTY_VALUE_MAX] = {};
1342 property_get("debug.sf.latch_unsignaled", value, "0");
1343 latch = atoi(value);
1344 propertyLoaded = true;
1345 }
1346 return latch;
1347}
1348
Dan Stozacac35382016-01-27 12:21:06 -08001349uint64_t Layer::getHeadFrameNumber() const {
1350 Mutex::Autolock lock(mQueueItemLock);
1351 if (!mQueueItems.empty()) {
1352 return mQueueItems[0].mFrameNumber;
1353 } else {
1354 return mCurrentFrameNumber;
1355 }
1356}
1357
Dan Stoza1ce65812016-06-15 16:26:27 -07001358bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001359#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001360 if (latchUnsignaledBuffers()) {
1361 return true;
1362 }
1363
Dan Stoza1ce65812016-06-15 16:26:27 -07001364 Mutex::Autolock lock(mQueueItemLock);
1365 if (mQueueItems.empty()) {
1366 return true;
1367 }
1368 if (mQueueItems[0].mIsDroppable) {
1369 // Even though this buffer's fence may not have signaled yet, it could
1370 // be replaced by another buffer before it has a chance to, which means
1371 // that it's possible to get into a situation where a buffer is never
1372 // able to be latched. To avoid this, grab this buffer anyway.
1373 return true;
1374 }
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001375 return mQueueItems[0].mFenceTime->getSignalTime() !=
1376 Fence::SIGNAL_TIME_PENDING;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001377#else
1378 return true;
1379#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001380}
1381
Dan Stozacac35382016-01-27 12:21:06 -08001382bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1383 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1384 // Don't bother with a SyncPoint, since we've already latched the
1385 // relevant frame
1386 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001387 }
1388
Dan Stozacac35382016-01-27 12:21:06 -08001389 Mutex::Autolock lock(mLocalSyncPointMutex);
1390 mLocalSyncPoints.push_back(point);
1391 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001392}
1393
Mathias Agopian13127d82013-03-05 17:47:11 -08001394void Layer::setFiltering(bool filtering) {
1395 mFiltering = filtering;
1396}
1397
1398bool Layer::getFiltering() const {
1399 return mFiltering;
1400}
1401
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001402// As documented in libhardware header, formats in the range
1403// 0x100 - 0x1FF are specific to the HAL implementation, and
1404// are known to have no alpha channel
1405// TODO: move definition for device-specific range into
1406// hardware.h, instead of using hard-coded values here.
1407#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1408
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001409bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001410 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1411 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001412 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001413 switch (format) {
1414 case HAL_PIXEL_FORMAT_RGBA_8888:
1415 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001416 case HAL_PIXEL_FORMAT_RGBA_FP16:
Romain Guy541f2262017-02-10 18:50:17 -08001417 case HAL_PIXEL_FORMAT_RGBA_1010102:
Mathias Agopiandd533712013-07-26 15:31:39 -07001418 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001419 }
1420 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001421 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001422}
1423
Mathias Agopian13127d82013-03-05 17:47:11 -08001424// ----------------------------------------------------------------------------
1425// local state
1426// ----------------------------------------------------------------------------
1427
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001428static void boundPoint(vec2* point, const Rect& crop) {
1429 if (point->x < crop.left) {
1430 point->x = crop.left;
1431 }
1432 if (point->x > crop.right) {
1433 point->x = crop.right;
1434 }
1435 if (point->y < crop.top) {
1436 point->y = crop.top;
1437 }
1438 if (point->y > crop.bottom) {
1439 point->y = crop.bottom;
1440 }
1441}
1442
Dan Stozac7014012014-02-14 15:03:43 -08001443void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1444 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001445{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001446 const Layer::State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001447 const Transform hwTransform(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001448 const uint32_t hw_h = hw->getHeight();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001449 Rect win = computeBounds();
Mathias Agopian3f844832013-08-07 21:24:32 -07001450
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001451 vec2 lt = vec2(win.left, win.top);
1452 vec2 lb = vec2(win.left, win.bottom);
1453 vec2 rb = vec2(win.right, win.bottom);
1454 vec2 rt = vec2(win.right, win.top);
1455
Robert Carr1f0a16a2016-10-24 16:27:39 -07001456 Transform layerTransform = getTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001457 if (!useIdentityTransform) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001458 lt = layerTransform.transform(lt);
1459 lb = layerTransform.transform(lb);
1460 rb = layerTransform.transform(rb);
1461 rt = layerTransform.transform(rt);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001462 }
1463
Robert Carrb5d3d262016-03-25 15:08:13 -07001464 if (!s.finalCrop.isEmpty()) {
1465 boundPoint(&lt, s.finalCrop);
1466 boundPoint(&lb, s.finalCrop);
1467 boundPoint(&rb, s.finalCrop);
1468 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001469 }
1470
Mathias Agopianff2ed702013-09-01 21:36:12 -07001471 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001472 position[0] = hwTransform.transform(lt);
1473 position[1] = hwTransform.transform(lb);
1474 position[2] = hwTransform.transform(rb);
1475 position[3] = hwTransform.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001476 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001477 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001478 }
1479}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001480
Andy McFadden4125a4f2014-01-29 17:17:11 -08001481bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001482{
neo.hee6fd41d2017-02-17 14:35:33 +08001483 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
Mathias Agopiana67932f2011-04-20 14:20:59 -07001484 // layer's opaque flag.
neo.hee6fd41d2017-02-17 14:35:33 +08001485 if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001486 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001487 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001488
1489 // if the layer has the opaque flag, then we're always opaque,
1490 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001491 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001492}
1493
Dan Stoza23116082015-06-18 14:58:39 -07001494bool Layer::isSecure() const
1495{
1496 const Layer::State& s(mDrawingState);
1497 return (s.flags & layer_state_t::eLayerSecure);
1498}
1499
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001500bool Layer::isProtected() const
1501{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001502 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001503 return (activeBuffer != 0) &&
1504 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1505}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001506
Mathias Agopian13127d82013-03-05 17:47:11 -08001507bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001508 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001509}
1510
1511bool Layer::isCropped() const {
1512 return !mCurrentCrop.isEmpty();
1513}
1514
1515bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1516 return mNeedsFiltering || hw->needsFiltering();
1517}
1518
1519void Layer::setVisibleRegion(const Region& visibleRegion) {
1520 // always called from main thread
1521 this->visibleRegion = visibleRegion;
1522}
1523
1524void Layer::setCoveredRegion(const Region& coveredRegion) {
1525 // always called from main thread
1526 this->coveredRegion = coveredRegion;
1527}
1528
1529void Layer::setVisibleNonTransparentRegion(const Region&
1530 setVisibleNonTransparentRegion) {
1531 // always called from main thread
1532 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1533}
1534
1535// ----------------------------------------------------------------------------
1536// transaction
1537// ----------------------------------------------------------------------------
1538
Dan Stoza7dde5992015-05-22 09:51:44 -07001539void Layer::pushPendingState() {
1540 if (!mCurrentState.modified) {
1541 return;
1542 }
1543
Dan Stoza7dde5992015-05-22 09:51:44 -07001544 // If this transaction is waiting on the receipt of a frame, generate a sync
1545 // point and send it to the remote layer.
Robert Carr0d480722017-01-10 16:42:54 -08001546 if (mCurrentState.barrierLayer != nullptr) {
1547 sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1548 if (barrierLayer == nullptr) {
1549 ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
Dan Stoza7dde5992015-05-22 09:51:44 -07001550 // If we can't promote the layer we are intended to wait on,
1551 // then it is expired or otherwise invalid. Allow this transaction
1552 // to be applied as per normal (no synchronization).
Robert Carr0d480722017-01-10 16:42:54 -08001553 mCurrentState.barrierLayer = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001554 } else {
1555 auto syncPoint = std::make_shared<SyncPoint>(
1556 mCurrentState.frameNumber);
Robert Carr0d480722017-01-10 16:42:54 -08001557 if (barrierLayer->addSyncPoint(syncPoint)) {
Dan Stozacac35382016-01-27 12:21:06 -08001558 mRemoteSyncPoints.push_back(std::move(syncPoint));
1559 } else {
1560 // We already missed the frame we're supposed to synchronize
1561 // on, so go ahead and apply the state update
Robert Carr0d480722017-01-10 16:42:54 -08001562 mCurrentState.barrierLayer = nullptr;
Dan Stozacac35382016-01-27 12:21:06 -08001563 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001564 }
1565
Dan Stoza7dde5992015-05-22 09:51:44 -07001566 // Wake us up to check if the frame has been received
1567 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001568 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001569 }
1570 mPendingStates.push_back(mCurrentState);
Dan Stozaf7ba41a2017-05-10 15:11:11 -07001571 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
Dan Stoza7dde5992015-05-22 09:51:44 -07001572}
1573
Pablo Ceballos05289c22016-04-14 15:49:55 -07001574void Layer::popPendingState(State* stateToCommit) {
1575 auto oldFlags = stateToCommit->flags;
1576 *stateToCommit = mPendingStates[0];
1577 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1578 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001579
1580 mPendingStates.removeAt(0);
Dan Stozaf7ba41a2017-05-10 15:11:11 -07001581 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
Dan Stoza7dde5992015-05-22 09:51:44 -07001582}
1583
Pablo Ceballos05289c22016-04-14 15:49:55 -07001584bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001585 bool stateUpdateAvailable = false;
1586 while (!mPendingStates.empty()) {
Robert Carr0d480722017-01-10 16:42:54 -08001587 if (mPendingStates[0].barrierLayer != nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001588 if (mRemoteSyncPoints.empty()) {
1589 // If we don't have a sync point for this, apply it anyway. It
1590 // will be visually wrong, but it should keep us from getting
1591 // into too much trouble.
1592 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001593 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001594 stateUpdateAvailable = true;
1595 continue;
1596 }
1597
Dan Stozacac35382016-01-27 12:21:06 -08001598 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1599 mPendingStates[0].frameNumber) {
1600 ALOGE("[%s] Unexpected sync point frame number found",
1601 mName.string());
1602
1603 // Signal our end of the sync point and then dispose of it
1604 mRemoteSyncPoints.front()->setTransactionApplied();
1605 mRemoteSyncPoints.pop_front();
1606 continue;
1607 }
1608
Dan Stoza7dde5992015-05-22 09:51:44 -07001609 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1610 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001611 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001612 stateUpdateAvailable = true;
1613
1614 // Signal our end of the sync point and then dispose of it
1615 mRemoteSyncPoints.front()->setTransactionApplied();
1616 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001617 } else {
1618 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001619 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001620 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001621 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001622 stateUpdateAvailable = true;
1623 }
1624 }
1625
1626 // If we still have pending updates, wake SurfaceFlinger back up and point
1627 // it at this layer so we can process them
1628 if (!mPendingStates.empty()) {
1629 setTransactionFlags(eTransactionNeeded);
1630 mFlinger->setTransactionFlags(eTraversalNeeded);
1631 }
1632
1633 mCurrentState.modified = false;
1634 return stateUpdateAvailable;
1635}
1636
1637void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001638 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001639 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001640 Mutex::Autolock lock(mLocalSyncPointMutex);
1641 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001642 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001643 point->setFrameAvailable();
1644 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001645 }
1646}
1647
Mathias Agopian13127d82013-03-05 17:47:11 -08001648uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001649 ATRACE_CALL();
1650
Dan Stoza7dde5992015-05-22 09:51:44 -07001651 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001652 Layer::State c = getCurrentState();
1653 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001654 return 0;
1655 }
1656
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001657 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001658
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001659 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1660 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001661
1662 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001663 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001664 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001665 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001666 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001667 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001668 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001669 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001670 this, getName().string(), mCurrentTransform,
1671 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001672 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001673 c.crop.left,
1674 c.crop.top,
1675 c.crop.right,
1676 c.crop.bottom,
1677 c.crop.getWidth(),
1678 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001679 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001680 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001681 s.crop.left,
1682 s.crop.top,
1683 s.crop.right,
1684 s.crop.bottom,
1685 s.crop.getWidth(),
1686 s.crop.getHeight(),
1687 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001688
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001689 // record the new size, form this point on, when the client request
1690 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001691 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001692 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001693 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001694
Robert Carre392b552017-09-19 12:16:05 -07001695 // Don't let Layer::doTransaction update the drawing state
1696 // if we have a pending resize, unless we are in fixed-size mode.
1697 // the drawing state will be updated only once we receive a buffer
1698 // with the correct size.
1699 //
1700 // In particular, we want to make sure the clip (which is part
1701 // of the geometry state) is latched together with the size but is
1702 // latched immediately when no resizing is involved.
1703 //
1704 // If a sideband stream is attached, however, we want to skip this
1705 // optimization so that transactions aren't missed when a buffer
1706 // never arrives
1707 //
1708 // In the case that we don't have a buffer we ignore other factors
1709 // and avoid entering the resizePending state. At a high level the
1710 // resizePending state is to avoid applying the state of the new buffer
1711 // to the old buffer. However in the state where we don't have an old buffer
1712 // there is no such concern but we may still be being used as a parent layer.
1713 const bool resizePending = ((c.requested.w != c.active.w) ||
1714 (c.requested.h != c.active.h)) && (mActiveBuffer != nullptr);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001715 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001716 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001717 flags |= eDontUpdateGeometryState;
1718 }
1719 }
1720
Robert Carr7bf247e2017-05-18 14:02:49 -07001721 // Here we apply various requested geometry states, depending on our
1722 // latching configuration. See Layer.h for a detailed discussion of
1723 // how geometry latching is controlled.
1724 if (!(flags & eDontUpdateGeometryState)) {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001725 Layer::State& editCurrentState(getCurrentState());
Robert Carr7bf247e2017-05-18 14:02:49 -07001726
1727 // If mFreezeGeometryUpdates is true we are in the setGeometryAppliesWithResize
1728 // mode, which causes attributes which normally latch regardless of scaling mode,
1729 // to be delayed. We copy the requested state to the active state making sure
1730 // to respect these rules (again see Layer.h for a detailed discussion).
1731 //
1732 // There is an awkward asymmetry in the handling of the crop states in the position
1733 // states, as can be seen below. Largely this arises from position and transform
1734 // being stored in the same data structure while having different latching rules.
1735 // b/38182305
1736 //
1737 // Careful that "c" and editCurrentState may not begin as equivalent due to
1738 // applyPendingStates in the presence of deferred transactions.
1739 if (mFreezeGeometryUpdates) {
Robert Carr82364e32016-05-15 11:27:47 -07001740 float tx = c.active.transform.tx();
1741 float ty = c.active.transform.ty();
1742 c.active = c.requested;
1743 c.active.transform.set(tx, ty);
1744 editCurrentState.active = c.active;
1745 } else {
1746 editCurrentState.active = editCurrentState.requested;
1747 c.active = c.requested;
1748 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001749 }
1750
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001751 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001752 // invalidate and recompute the visible regions if needed
1753 flags |= Layer::eVisibleRegion;
1754 }
1755
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001756 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001757 // invalidate and recompute the visible regions if needed
1758 flags |= eVisibleRegion;
1759 this->contentDirty = true;
1760
1761 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001762 const uint8_t type = c.active.transform.getType();
1763 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001764 (type >= Transform::SCALE));
1765 }
1766
Dan Stozac8145172016-04-28 16:29:06 -07001767 // If the layer is hidden, signal and clear out all local sync points so
1768 // that transactions for layers depending on this layer's frames becoming
1769 // visible are not blocked
1770 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001771 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001772 }
1773
Mathias Agopian13127d82013-03-05 17:47:11 -08001774 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001775 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001776 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001777}
1778
Pablo Ceballos05289c22016-04-14 15:49:55 -07001779void Layer::commitTransaction(const State& stateToCommit) {
1780 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001781}
1782
Mathias Agopian13127d82013-03-05 17:47:11 -08001783uint32_t Layer::getTransactionFlags(uint32_t flags) {
1784 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1785}
1786
1787uint32_t Layer::setTransactionFlags(uint32_t flags) {
1788 return android_atomic_or(flags, &mTransactionFlags);
1789}
1790
Robert Carr82364e32016-05-15 11:27:47 -07001791bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001792 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001793 return false;
1794 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001795
1796 // We update the requested and active position simultaneously because
1797 // we want to apply the position portion of the transform matrix immediately,
1798 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001799 mCurrentState.requested.transform.set(x, y);
Robert Carr7bf247e2017-05-18 14:02:49 -07001800 if (immediate && !mFreezeGeometryUpdates) {
1801 // Here we directly update the active state
1802 // unlike other setters, because we store it within
1803 // the transform, but use different latching rules.
1804 // b/38182305
Robert Carr82364e32016-05-15 11:27:47 -07001805 mCurrentState.active.transform.set(x, y);
1806 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001807 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001808
Dan Stoza7dde5992015-05-22 09:51:44 -07001809 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001810 setTransactionFlags(eTransactionNeeded);
1811 return true;
1812}
Robert Carr82364e32016-05-15 11:27:47 -07001813
Robert Carr1f0a16a2016-10-24 16:27:39 -07001814bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1815 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1816 if (idx < 0) {
1817 return false;
1818 }
1819 if (childLayer->setLayer(z)) {
1820 mCurrentChildren.removeAt(idx);
1821 mCurrentChildren.add(childLayer);
1822 }
1823 return true;
1824}
1825
Robert Carrae060832016-11-28 10:51:00 -08001826bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001827 if (mCurrentState.z == z)
1828 return false;
1829 mCurrentState.sequence++;
1830 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001831 mCurrentState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001832
1833 // Discard all relative layering.
1834 if (mCurrentState.zOrderRelativeOf != nullptr) {
1835 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1836 if (strongRelative != nullptr) {
1837 strongRelative->removeZOrderRelative(this);
1838 }
1839 mCurrentState.zOrderRelativeOf = nullptr;
1840 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001841 setTransactionFlags(eTransactionNeeded);
1842 return true;
1843}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001844
Robert Carrdb66e622017-04-10 16:55:57 -07001845void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1846 mCurrentState.zOrderRelatives.remove(relative);
1847 mCurrentState.sequence++;
1848 mCurrentState.modified = true;
1849 setTransactionFlags(eTransactionNeeded);
1850}
1851
1852void Layer::addZOrderRelative(const wp<Layer>& relative) {
1853 mCurrentState.zOrderRelatives.add(relative);
1854 mCurrentState.modified = true;
1855 mCurrentState.sequence++;
1856 setTransactionFlags(eTransactionNeeded);
1857}
1858
1859bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1860 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1861 if (handle == nullptr) {
1862 return false;
1863 }
1864 sp<Layer> relative = handle->owner.promote();
1865 if (relative == nullptr) {
1866 return false;
1867 }
1868
1869 mCurrentState.sequence++;
1870 mCurrentState.modified = true;
1871 mCurrentState.z = z;
1872
1873 mCurrentState.zOrderRelativeOf = relative;
1874 relative->addZOrderRelative(this);
1875
1876 setTransactionFlags(eTransactionNeeded);
1877
1878 return true;
1879}
1880
Mathias Agopian13127d82013-03-05 17:47:11 -08001881bool Layer::setSize(uint32_t w, uint32_t h) {
1882 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1883 return false;
1884 mCurrentState.requested.w = w;
1885 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001886 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001887 setTransactionFlags(eTransactionNeeded);
1888 return true;
1889}
Dan Stoza9e56aa02015-11-02 13:00:03 -08001890bool Layer::setAlpha(float alpha) {
chaviw13fdc492017-06-27 12:40:18 -07001891 if (mCurrentState.color.a == alpha)
Mathias Agopian13127d82013-03-05 17:47:11 -08001892 return false;
1893 mCurrentState.sequence++;
chaviw13fdc492017-06-27 12:40:18 -07001894 mCurrentState.color.a = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001895 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001896 setTransactionFlags(eTransactionNeeded);
1897 return true;
1898}
chaviw13fdc492017-06-27 12:40:18 -07001899
1900bool Layer::setColor(const half3& color) {
1901 if (color.r == mCurrentState.color.r && color.g == mCurrentState.color.g
1902 && color.b == mCurrentState.color.b)
1903 return false;
1904
1905 mCurrentState.sequence++;
1906 mCurrentState.color.r = color.r;
1907 mCurrentState.color.g = color.g;
1908 mCurrentState.color.b = color.b;
1909 mCurrentState.modified = true;
1910 setTransactionFlags(eTransactionNeeded);
1911 return true;
1912}
1913
Mathias Agopian13127d82013-03-05 17:47:11 -08001914bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1915 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001916 mCurrentState.requested.transform.set(
Robert Carrcb6e1e32017-02-21 19:48:26 -08001917 matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001918 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001919 setTransactionFlags(eTransactionNeeded);
1920 return true;
1921}
1922bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001923 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001924 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001925 setTransactionFlags(eTransactionNeeded);
1926 return true;
1927}
1928bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1929 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1930 if (mCurrentState.flags == newFlags)
1931 return false;
1932 mCurrentState.sequence++;
1933 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001934 mCurrentState.mask = mask;
1935 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001936 setTransactionFlags(eTransactionNeeded);
1937 return true;
1938}
Robert Carr99e27f02016-06-16 15:18:02 -07001939
1940bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001941 if (mCurrentState.requestedCrop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001942 return false;
1943 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001944 mCurrentState.requestedCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001945 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr99e27f02016-06-16 15:18:02 -07001946 mCurrentState.crop = crop;
1947 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001948 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1949
Dan Stoza7dde5992015-05-22 09:51:44 -07001950 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001951 setTransactionFlags(eTransactionNeeded);
1952 return true;
1953}
Robert Carr8d5227b2017-03-16 15:41:03 -07001954
1955bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001956 if (mCurrentState.requestedFinalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001957 return false;
1958 mCurrentState.sequence++;
Robert Carr8d5227b2017-03-16 15:41:03 -07001959 mCurrentState.requestedFinalCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001960 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr8d5227b2017-03-16 15:41:03 -07001961 mCurrentState.finalCrop = crop;
1962 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001963 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1964
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001965 mCurrentState.modified = true;
1966 setTransactionFlags(eTransactionNeeded);
1967 return true;
1968}
Mathias Agopian13127d82013-03-05 17:47:11 -08001969
Robert Carrc3574f72016-03-24 12:19:32 -07001970bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1971 if (scalingMode == mOverrideScalingMode)
1972 return false;
1973 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001974 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001975 return true;
1976}
1977
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001978void Layer::setInfo(uint32_t type, uint32_t appId) {
1979 mCurrentState.appId = appId;
1980 mCurrentState.type = type;
1981 mCurrentState.modified = true;
1982 setTransactionFlags(eTransactionNeeded);
1983}
1984
Robert Carrc3574f72016-03-24 12:19:32 -07001985uint32_t Layer::getEffectiveScalingMode() const {
1986 if (mOverrideScalingMode >= 0) {
1987 return mOverrideScalingMode;
1988 }
1989 return mCurrentScalingMode;
1990}
1991
Mathias Agopian13127d82013-03-05 17:47:11 -08001992bool Layer::setLayerStack(uint32_t layerStack) {
1993 if (mCurrentState.layerStack == layerStack)
1994 return false;
1995 mCurrentState.sequence++;
1996 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001997 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001998 setTransactionFlags(eTransactionNeeded);
1999 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002000}
2001
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002002bool Layer::setDataSpace(android_dataspace dataSpace) {
2003 if (mCurrentState.dataSpace == dataSpace)
2004 return false;
2005 mCurrentState.sequence++;
2006 mCurrentState.dataSpace = dataSpace;
2007 mCurrentState.modified = true;
2008 setTransactionFlags(eTransactionNeeded);
2009 return true;
2010}
2011
Courtney Goeltzenleuchter532b2632017-05-05 16:34:38 -06002012android_dataspace Layer::getDataSpace() const {
2013 return mCurrentState.dataSpace;
2014}
2015
Robert Carr1f0a16a2016-10-24 16:27:39 -07002016uint32_t Layer::getLayerStack() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002017 auto p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002018 if (p == nullptr) {
2019 return getDrawingState().layerStack;
2020 }
2021 return p->getLayerStack();
2022}
2023
Robert Carr0d480722017-01-10 16:42:54 -08002024void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
Dan Stoza7dde5992015-05-22 09:51:44 -07002025 uint64_t frameNumber) {
Robert Carr0d480722017-01-10 16:42:54 -08002026 mCurrentState.barrierLayer = barrierLayer;
Dan Stoza7dde5992015-05-22 09:51:44 -07002027 mCurrentState.frameNumber = frameNumber;
2028 // We don't set eTransactionNeeded, because just receiving a deferral
2029 // request without any other state updates shouldn't actually induce a delay
2030 mCurrentState.modified = true;
2031 pushPendingState();
Robert Carr0d480722017-01-10 16:42:54 -08002032 mCurrentState.barrierLayer = nullptr;
Dan Stoza792e5292016-02-11 11:43:58 -08002033 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07002034 mCurrentState.modified = false;
Robert Carr0d480722017-01-10 16:42:54 -08002035}
2036
2037void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
2038 uint64_t frameNumber) {
2039 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
2040 deferTransactionUntil(handle->owner.promote(), frameNumber);
Dan Stoza7dde5992015-05-22 09:51:44 -07002041}
2042
Dan Stozaee44edd2015-03-23 15:50:23 -07002043void Layer::useSurfaceDamage() {
2044 if (mFlinger->mForceFullDamage) {
2045 surfaceDamageRegion = Region::INVALID_REGION;
2046 } else {
2047 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
2048 }
2049}
2050
2051void Layer::useEmptyDamage() {
2052 surfaceDamageRegion.clear();
2053}
2054
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002055// ----------------------------------------------------------------------------
2056// pageflip handling...
2057// ----------------------------------------------------------------------------
2058
Dan Stoza6b9454d2014-11-07 16:00:59 -08002059bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08002060 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07002061 return true;
2062 }
2063
Dan Stoza6b9454d2014-11-07 16:00:59 -08002064 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07002065 if (mQueueItems.empty()) {
2066 return false;
2067 }
2068 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002069 nsecs_t expectedPresent =
2070 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07002071
2072 // Ignore timestamps more than a second in the future
2073 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
2074 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
2075 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
2076 expectedPresent);
2077
2078 bool isDue = timestamp < expectedPresent;
2079 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002080}
2081
Brian Andersond6927fb2016-07-23 23:37:30 -07002082bool Layer::onPreComposition(nsecs_t refreshStartTime) {
2083 if (mBufferLatched) {
2084 Mutex::Autolock lock(mFrameEventHistoryMutex);
2085 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
2086 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08002087 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08002088 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002089}
2090
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002091bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
Brian Anderson3d4039d2016-09-23 16:31:30 -07002092 const std::shared_ptr<FenceTime>& presentFence,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002093 const CompositorTiming& compositorTiming) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002094 // mFrameLatencyNeeded is true when a new frame was latched for the
2095 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08002096 if (!mFrameLatencyNeeded)
2097 return false;
2098
Fabien Sanglard28e98082016-12-05 10:19:46 -08002099 // Update mFrameEventHistory.
2100 {
2101 Mutex::Autolock lock(mFrameEventHistoryMutex);
2102 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002103 glDoneFence, presentFence, compositorTiming);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002104 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08002105
2106 // Update mFrameTracker.
2107 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
2108 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
2109
Brian Anderson3d4039d2016-09-23 16:31:30 -07002110 std::shared_ptr<FenceTime> frameReadyFence =
2111 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08002112 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002113 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002114 } else {
2115 // There was no fence for this frame, so assume that it was ready
2116 // to be presented at the desired present time.
2117 mFrameTracker.setFrameReadyTime(desiredPresentTime);
2118 }
2119
Brian Anderson3d4039d2016-09-23 16:31:30 -07002120 if (presentFence->isValid()) {
2121 mFrameTracker.setActualPresentFence(
2122 std::shared_ptr<FenceTime>(presentFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002123 } else {
2124 // The HWC doesn't support present fences, so use the refresh
2125 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002126 mFrameTracker.setActualPresentTime(
2127 mFlinger->getHwComposer().getRefreshTimestamp(
2128 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002129 }
2130
2131 mFrameTracker.advanceFrame();
2132 mFrameLatencyNeeded = false;
2133 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002134}
2135
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002136#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07002137void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Brian Anderson5ea5e592016-12-01 16:54:33 -08002138 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2139 return;
2140 }
2141
Brian Anderson3d4039d2016-09-23 16:31:30 -07002142 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002143 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002144 mReleaseTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002145 mReleaseTimeline.push(releaseFenceTime);
2146
2147 Mutex::Autolock lock(mFrameEventHistoryMutex);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002148 if (mPreviousFrameNumber != 0) {
2149 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2150 dequeueReadyTime, std::move(releaseFenceTime));
2151 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002152}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002153#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002154
Robert Carr1f0a16a2016-10-24 16:27:39 -07002155bool Layer::isHiddenByPolicy() const {
2156 const Layer::State& s(mDrawingState);
Chia-I Wue41dbe62017-06-13 14:10:56 -07002157 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002158 if (parent != nullptr && parent->isHiddenByPolicy()) {
2159 return true;
2160 }
2161 return s.flags & layer_state_t::eLayerHidden;
2162}
2163
Mathias Agopianda27af92012-09-13 18:17:13 -07002164bool Layer::isVisible() const {
Robert Carr6452f122017-03-21 10:41:29 -07002165 return !(isHiddenByPolicy()) && getAlpha() > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08002166 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Mathias Agopianda27af92012-09-13 18:17:13 -07002167}
2168
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002169bool Layer::allTransactionsSignaled() {
2170 auto headFrameNumber = getHeadFrameNumber();
2171 bool matchingFramesFound = false;
2172 bool allTransactionsApplied = true;
2173 Mutex::Autolock lock(mLocalSyncPointMutex);
2174
2175 for (auto& point : mLocalSyncPoints) {
2176 if (point->getFrameNumber() > headFrameNumber) {
2177 break;
2178 }
2179 matchingFramesFound = true;
2180
2181 if (!point->frameIsAvailable()) {
2182 // We haven't notified the remote layer that the frame for
2183 // this point is available yet. Notify it now, and then
2184 // abort this attempt to latch.
2185 point->setFrameAvailable();
2186 allTransactionsApplied = false;
2187 break;
2188 }
2189
2190 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2191 }
2192 return !matchingFramesFound || allTransactionsApplied;
2193}
2194
Brian Andersond6927fb2016-07-23 23:37:30 -07002195Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002196{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08002197 ATRACE_CALL();
2198
Jesse Hall399184a2014-03-03 15:42:54 -08002199 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2200 // mSidebandStreamChanged was true
2201 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07002202 if (mSidebandStream != NULL) {
2203 setTransactionFlags(eTransactionNeeded);
2204 mFlinger->setTransactionFlags(eTraversalNeeded);
2205 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07002206 recomputeVisibleRegions = true;
2207
2208 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07002209 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08002210 }
2211
Mathias Agopian4fec8732012-06-29 14:12:52 -07002212 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07002213 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2214 return outDirtyRegion;
2215 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002216
Fabien Sanglard223eb912016-10-13 10:15:06 -07002217 // if we've already called updateTexImage() without going through
2218 // a composition step, we have to skip this layer at this point
2219 // because we cannot call updateTeximage() without a corresponding
2220 // compositionComplete() call.
2221 // we'll trigger an update in onPreComposition().
2222 if (mRefreshPending) {
2223 return outDirtyRegion;
2224 }
2225
2226 // If the head buffer's acquire fence hasn't signaled yet, return and
2227 // try again later
2228 if (!headFenceHasSignaled()) {
2229 mFlinger->signalLayerUpdate();
2230 return outDirtyRegion;
2231 }
2232
2233 // Capture the old state of the layer for comparisons later
2234 const State& s(getDrawingState());
2235 const bool oldOpacity = isOpaque(s);
2236 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2237
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002238 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002239 mFlinger->signalLayerUpdate();
2240 return outDirtyRegion;
2241 }
2242
2243 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2244 // of the buffer queue isn't modified when the buffer queue is returning
2245 // BufferItem's that weren't actually queued. This can happen in shared
2246 // buffer mode.
2247 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002248 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2249 getProducerStickyTransform() != 0, mName.string(),
Robert Carr7bf247e2017-05-18 14:02:49 -07002250 mOverrideScalingMode, mFreezeGeometryUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002251 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2252 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2253 mLastFrameNumberReceived);
2254 if (updateResult == BufferQueue::PRESENT_LATER) {
2255 // Producer doesn't want buffer to be displayed yet. Signal a
2256 // layer update so we check again at the next opportunity.
2257 mFlinger->signalLayerUpdate();
2258 return outDirtyRegion;
2259 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2260 // If the buffer has been rejected, remove it from the shadow queue
2261 // and return early
2262 if (queuedBuffer) {
2263 Mutex::Autolock lock(mQueueItemLock);
2264 mQueueItems.removeAt(0);
2265 android_atomic_dec(&mQueuedFrames);
2266 }
2267 return outDirtyRegion;
2268 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2269 // This can occur if something goes wrong when trying to create the
2270 // EGLImage for this buffer. If this happens, the buffer has already
2271 // been released, so we need to clean up the queue and bug out
2272 // early.
2273 if (queuedBuffer) {
2274 Mutex::Autolock lock(mQueueItemLock);
2275 mQueueItems.clear();
2276 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002277 }
2278
Fabien Sanglard223eb912016-10-13 10:15:06 -07002279 // Once we have hit this state, the shadow queue may no longer
2280 // correctly reflect the incoming BufferQueue's contents, so even if
2281 // updateTexImage starts working, the only safe course of action is
2282 // to continue to ignore updates.
2283 mUpdateTexImageFailed = true;
2284
2285 return outDirtyRegion;
2286 }
2287
2288 if (queuedBuffer) {
2289 // Autolock scope
2290 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2291
2292 Mutex::Autolock lock(mQueueItemLock);
2293
2294 // Remove any stale buffers that have been dropped during
2295 // updateTexImage
2296 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2297 mQueueItems.removeAt(0);
2298 android_atomic_dec(&mQueuedFrames);
2299 }
2300
2301 mQueueItems.removeAt(0);
2302 }
2303
2304
2305 // Decrement the queued-frames count. Signal another event if we
2306 // have more frames pending.
2307 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2308 || mAutoRefresh) {
2309 mFlinger->signalLayerUpdate();
2310 }
2311
Fabien Sanglard223eb912016-10-13 10:15:06 -07002312 // update the active buffer
Chia-I Wu06d63de2017-01-04 14:58:51 +08002313 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2314 &mActiveBufferSlot);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002315 if (mActiveBuffer == NULL) {
2316 // this can only happen if the very first buffer was rejected.
2317 return outDirtyRegion;
2318 }
2319
Brian Andersond6927fb2016-07-23 23:37:30 -07002320 mBufferLatched = true;
2321 mPreviousFrameNumber = mCurrentFrameNumber;
2322 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2323
2324 {
2325 Mutex::Autolock lock(mFrameEventHistoryMutex);
2326 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2327#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002328 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002329 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002330 mReleaseTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002331 mReleaseTimeline.push(releaseFenceTime);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002332 if (mPreviousFrameNumber != 0) {
2333 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2334 latchTime, std::move(releaseFenceTime));
2335 }
Brian Andersond6927fb2016-07-23 23:37:30 -07002336#endif
2337 }
2338
Fabien Sanglard223eb912016-10-13 10:15:06 -07002339 mRefreshPending = true;
2340 mFrameLatencyNeeded = true;
2341 if (oldActiveBuffer == NULL) {
2342 // the first time we receive a buffer, we need to trigger a
2343 // geometry invalidation.
2344 recomputeVisibleRegions = true;
2345 }
2346
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002347 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2348
Fabien Sanglard223eb912016-10-13 10:15:06 -07002349 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2350 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2351 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2352 if ((crop != mCurrentCrop) ||
2353 (transform != mCurrentTransform) ||
2354 (scalingMode != mCurrentScalingMode))
2355 {
2356 mCurrentCrop = crop;
2357 mCurrentTransform = transform;
2358 mCurrentScalingMode = scalingMode;
2359 recomputeVisibleRegions = true;
2360 }
2361
2362 if (oldActiveBuffer != NULL) {
2363 uint32_t bufWidth = mActiveBuffer->getWidth();
2364 uint32_t bufHeight = mActiveBuffer->getHeight();
2365 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2366 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002367 recomputeVisibleRegions = true;
2368 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002369 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002370
Fabien Sanglard223eb912016-10-13 10:15:06 -07002371 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2372 if (oldOpacity != isOpaque(s)) {
2373 recomputeVisibleRegions = true;
2374 }
Dan Stozacac35382016-01-27 12:21:06 -08002375
Fabien Sanglard223eb912016-10-13 10:15:06 -07002376 // Remove any sync points corresponding to the buffer which was just
2377 // latched
2378 {
2379 Mutex::Autolock lock(mLocalSyncPointMutex);
2380 auto point = mLocalSyncPoints.begin();
2381 while (point != mLocalSyncPoints.end()) {
2382 if (!(*point)->frameIsAvailable() ||
2383 !(*point)->transactionIsApplied()) {
2384 // This sync point must have been added since we started
2385 // latching. Don't drop it yet.
2386 ++point;
2387 continue;
2388 }
2389
2390 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2391 point = mLocalSyncPoints.erase(point);
2392 } else {
2393 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002394 }
2395 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002396 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002397
2398 // FIXME: postedRegion should be dirty & bounds
2399 Region dirtyRegion(Rect(s.active.w, s.active.h));
2400
2401 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002402 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002403
Mathias Agopian4fec8732012-06-29 14:12:52 -07002404 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002405}
2406
Mathias Agopiana67932f2011-04-20 14:20:59 -07002407uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002408{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002409 // TODO: should we do something special if mSecure is set?
2410 if (mProtectedByApp) {
2411 // need a hardware-protected path to external video sink
2412 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002413 }
Riley Andrews03414a12014-07-01 14:22:59 -07002414 if (mPotentialCursor) {
2415 usage |= GraphicBuffer::USAGE_CURSOR;
2416 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002417 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002418 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002419}
2420
Mathias Agopian84300952012-11-21 16:02:13 -08002421void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002422 uint32_t orientation = 0;
2423 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002424 // The transform hint is used to improve performance, but we can
2425 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002426 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002427 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002428 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002429 if (orientation & Transform::ROT_INVALID) {
2430 orientation = 0;
2431 }
2432 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002433 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002434}
2435
Mathias Agopian13127d82013-03-05 17:47:11 -08002436// ----------------------------------------------------------------------------
2437// debugging
2438// ----------------------------------------------------------------------------
2439
Kalle Raitaa099a242017-01-11 11:17:29 -08002440LayerDebugInfo Layer::getLayerDebugInfo() const {
2441 LayerDebugInfo info;
2442 const Layer::State& ds = getDrawingState();
2443 info.mName = getName();
chaviw1acbec72017-07-27 15:28:26 -07002444 sp<Layer> parent = getParent();
Kalle Raitaa099a242017-01-11 11:17:29 -08002445 info.mParentName = (parent == nullptr ? std::string("none") : parent->getName().string());
2446 info.mType = String8(getTypeId());
2447 info.mTransparentRegion = ds.activeTransparentRegion;
2448 info.mVisibleRegion = visibleRegion;
2449 info.mSurfaceDamageRegion = surfaceDamageRegion;
2450 info.mLayerStack = getLayerStack();
2451 info.mX = ds.active.transform.tx();
2452 info.mY = ds.active.transform.ty();
2453 info.mZ = ds.z;
2454 info.mWidth = ds.active.w;
2455 info.mHeight = ds.active.h;
2456 info.mCrop = ds.crop;
2457 info.mFinalCrop = ds.finalCrop;
chaviw13fdc492017-06-27 12:40:18 -07002458 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08002459 info.mFlags = ds.flags;
2460 info.mPixelFormat = getPixelFormat();
2461 info.mDataSpace = getDataSpace();
2462 info.mMatrix[0][0] = ds.active.transform[0][0];
2463 info.mMatrix[0][1] = ds.active.transform[0][1];
2464 info.mMatrix[1][0] = ds.active.transform[1][0];
2465 info.mMatrix[1][1] = ds.active.transform[1][1];
2466 {
2467 sp<const GraphicBuffer> activeBuffer = getActiveBuffer();
2468 if (activeBuffer != 0) {
2469 info.mActiveBufferWidth = activeBuffer->getWidth();
2470 info.mActiveBufferHeight = activeBuffer->getHeight();
2471 info.mActiveBufferStride = activeBuffer->getStride();
2472 info.mActiveBufferFormat = activeBuffer->format;
2473 } else {
2474 info.mActiveBufferWidth = 0;
2475 info.mActiveBufferHeight = 0;
2476 info.mActiveBufferStride = 0;
2477 info.mActiveBufferFormat = 0;
2478 }
Mathias Agopian13127d82013-03-05 17:47:11 -08002479 }
Kalle Raitaa099a242017-01-11 11:17:29 -08002480 info.mNumQueuedFrames = getQueuedFrameCount();
2481 info.mRefreshPending = isBufferLatched();
2482 info.mIsOpaque = isOpaque(ds);
2483 info.mContentDirty = contentDirty;
2484 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08002485}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002486#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002487void Layer::miniDumpHeader(String8& result) {
2488 result.append("----------------------------------------");
2489 result.append("---------------------------------------\n");
2490 result.append(" Layer name\n");
2491 result.append(" Z | ");
2492 result.append(" Comp Type | ");
2493 result.append(" Disp Frame (LTRB) | ");
2494 result.append(" Source Crop (LTRB)\n");
2495 result.append("----------------------------------------");
2496 result.append("---------------------------------------\n");
2497}
2498
2499void Layer::miniDump(String8& result, int32_t hwcId) const {
2500 if (mHwcLayers.count(hwcId) == 0) {
2501 return;
2502 }
2503
2504 String8 name;
2505 if (mName.length() > 77) {
2506 std::string shortened;
2507 shortened.append(mName.string(), 36);
2508 shortened.append("[...]");
2509 shortened.append(mName.string() + (mName.length() - 36), 36);
2510 name = shortened.c_str();
2511 } else {
2512 name = mName;
2513 }
2514
2515 result.appendFormat(" %s\n", name.string());
2516
2517 const Layer::State& layerState(getDrawingState());
2518 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
John Reck8c3b6ac2017-08-24 10:25:42 -07002519 result.appendFormat(" %10d | ", layerState.z);
Dan Stozae22aec72016-08-01 13:20:59 -07002520 result.appendFormat("%10s | ",
2521 to_string(getCompositionType(hwcId)).c_str());
2522 const Rect& frame = hwcInfo.displayFrame;
2523 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2524 frame.right, frame.bottom);
Dan Stoza5a423ea2017-02-16 14:10:39 -08002525 const FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002526 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2527 crop.right, crop.bottom);
2528
2529 result.append("- - - - - - - - - - - - - - - - - - - - ");
2530 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2531}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002532#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002533
Svetoslavd85084b2014-03-20 10:28:31 -07002534void Layer::dumpFrameStats(String8& result) const {
2535 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002536}
2537
Svetoslavd85084b2014-03-20 10:28:31 -07002538void Layer::clearFrameStats() {
2539 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002540}
2541
Jamie Gennis6547ff42013-07-16 20:12:42 -07002542void Layer::logFrameStats() {
2543 mFrameTracker.logAndResetStats(mName);
2544}
2545
Svetoslavd85084b2014-03-20 10:28:31 -07002546void Layer::getFrameStats(FrameStats* outStats) const {
2547 mFrameTracker.getStats(outStats);
2548}
2549
Brian Andersond6927fb2016-07-23 23:37:30 -07002550void Layer::dumpFrameEvents(String8& result) {
2551 result.appendFormat("- Layer %s (%s, %p)\n",
2552 getName().string(), getTypeId(), this);
2553 Mutex::Autolock lock(mFrameEventHistoryMutex);
2554 mFrameEventHistory.checkFencesForCompletion();
2555 mFrameEventHistory.dump(result);
2556}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002557
Brian Anderson5ea5e592016-12-01 16:54:33 -08002558void Layer::onDisconnect() {
2559 Mutex::Autolock lock(mFrameEventHistoryMutex);
2560 mFrameEventHistory.onDisconnect();
2561}
2562
Brian Anderson3890c392016-07-25 12:48:08 -07002563void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2564 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002565 Mutex::Autolock lock(mFrameEventHistoryMutex);
2566 if (newTimestamps) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002567 // If there are any unsignaled fences in the aquire timeline at this
2568 // point, the previously queued frame hasn't been latched yet. Go ahead
2569 // and try to get the signal time here so the syscall is taken out of
2570 // the main thread's critical path.
2571 mAcquireTimeline.updateSignalTimes();
2572 // Push the new fence after updating since it's likely still pending.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002573 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002574 mFrameEventHistory.addQueue(*newTimestamps);
2575 }
2576
Brian Anderson3890c392016-07-25 12:48:08 -07002577 if (outDelta) {
2578 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002579 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002580}
Dan Stozae77c7662016-05-13 11:37:28 -07002581
2582std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2583 bool forceFlush) {
2584 std::vector<OccupancyTracker::Segment> history;
2585 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2586 &history);
2587 if (result != NO_ERROR) {
2588 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2589 result);
2590 return {};
2591 }
2592 return history;
2593}
2594
Robert Carr367c5682016-06-20 11:55:28 -07002595bool Layer::getTransformToDisplayInverse() const {
2596 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2597}
2598
Chia-I Wu98f1c102017-05-30 14:54:08 -07002599size_t Layer::getChildrenCount() const {
2600 size_t count = 0;
2601 for (const sp<Layer>& child : mCurrentChildren) {
2602 count += 1 + child->getChildrenCount();
2603 }
2604 return count;
2605}
2606
Robert Carr1f0a16a2016-10-24 16:27:39 -07002607void Layer::addChild(const sp<Layer>& layer) {
2608 mCurrentChildren.add(layer);
2609 layer->setParent(this);
2610}
2611
2612ssize_t Layer::removeChild(const sp<Layer>& layer) {
2613 layer->setParent(nullptr);
2614 return mCurrentChildren.remove(layer);
2615}
2616
Robert Carr1db73f62016-12-21 12:58:51 -08002617bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2618 sp<Handle> handle = nullptr;
2619 sp<Layer> newParent = nullptr;
2620 if (newParentHandle == nullptr) {
2621 return false;
2622 }
2623 handle = static_cast<Handle*>(newParentHandle.get());
2624 newParent = handle->owner.promote();
2625 if (newParent == nullptr) {
2626 ALOGE("Unable to promote Layer handle");
2627 return false;
2628 }
2629
2630 for (const sp<Layer>& child : mCurrentChildren) {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002631 newParent->addChild(child);
Robert Carr1db73f62016-12-21 12:58:51 -08002632
2633 sp<Client> client(child->mClientRef.promote());
2634 if (client != nullptr) {
2635 client->setParentLayer(newParent);
2636 }
2637 }
2638 mCurrentChildren.clear();
2639
2640 return true;
2641}
2642
chaviwf1961f72017-09-18 16:41:07 -07002643bool Layer::reparent(const sp<IBinder>& newParentHandle) {
2644 if (newParentHandle == nullptr) {
chaviw06178942017-07-27 10:25:59 -07002645 return false;
2646 }
2647
2648 auto handle = static_cast<Handle*>(newParentHandle.get());
2649 sp<Layer> newParent = handle->owner.promote();
2650 if (newParent == nullptr) {
2651 ALOGE("Unable to promote Layer handle");
2652 return false;
2653 }
2654
chaviwf1961f72017-09-18 16:41:07 -07002655 sp<Layer> parent = getParent();
2656 if (parent != nullptr) {
2657 parent->removeChild(this);
chaviw06178942017-07-27 10:25:59 -07002658 }
chaviwf1961f72017-09-18 16:41:07 -07002659 newParent->addChild(this);
chaviw06178942017-07-27 10:25:59 -07002660
chaviwf1961f72017-09-18 16:41:07 -07002661 sp<Client> client(mClientRef.promote());
chaviw06178942017-07-27 10:25:59 -07002662 sp<Client> newParentClient(newParent->mClientRef.promote());
2663
chaviwf1961f72017-09-18 16:41:07 -07002664 if (client != newParentClient) {
2665 client->setParentLayer(newParent);
chaviw06178942017-07-27 10:25:59 -07002666 }
2667
chaviw06178942017-07-27 10:25:59 -07002668 return true;
2669}
2670
Robert Carr9524cb32017-02-13 11:32:32 -08002671bool Layer::detachChildren() {
Dan Stoza412903f2017-04-27 13:42:17 -07002672 traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
Robert Carr9524cb32017-02-13 11:32:32 -08002673 if (child == this) {
2674 return;
2675 }
2676
chaviw161410b02017-07-27 10:46:08 -07002677 sp<Client> parentClient = mClientRef.promote();
Robert Carr9524cb32017-02-13 11:32:32 -08002678 sp<Client> client(child->mClientRef.promote());
chaviw161410b02017-07-27 10:46:08 -07002679 if (client != nullptr && parentClient != client) {
Robert Carr9524cb32017-02-13 11:32:32 -08002680 client->detachLayer(child);
2681 }
2682 });
2683
2684 return true;
2685}
2686
Robert Carr1f0a16a2016-10-24 16:27:39 -07002687void Layer::setParent(const sp<Layer>& layer) {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002688 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002689}
2690
2691void Layer::clearSyncPoints() {
2692 for (const auto& child : mCurrentChildren) {
2693 child->clearSyncPoints();
2694 }
2695
2696 Mutex::Autolock lock(mLocalSyncPointMutex);
2697 for (auto& point : mLocalSyncPoints) {
2698 point->setFrameAvailable();
2699 }
2700 mLocalSyncPoints.clear();
2701}
2702
2703int32_t Layer::getZ() const {
2704 return mDrawingState.z;
2705}
2706
Dan Stoza412903f2017-04-27 13:42:17 -07002707LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2708 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2709 "makeTraversalList received invalid stateSet");
2710 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2711 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2712 const State& state = useDrawing ? mDrawingState : mCurrentState;
2713
2714 if (state.zOrderRelatives.size() == 0) {
2715 return children;
Robert Carrdb66e622017-04-10 16:55:57 -07002716 }
2717 LayerVector traverse;
2718
Dan Stoza412903f2017-04-27 13:42:17 -07002719 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07002720 sp<Layer> strongRelative = weakRelative.promote();
2721 if (strongRelative != nullptr) {
2722 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07002723 }
2724 }
2725
Dan Stoza412903f2017-04-27 13:42:17 -07002726 for (const sp<Layer>& child : children) {
Robert Carrdb66e622017-04-10 16:55:57 -07002727 traverse.add(child);
2728 }
2729
2730 return traverse;
2731}
2732
Robert Carr1f0a16a2016-10-24 16:27:39 -07002733/**
Robert Carrdb66e622017-04-10 16:55:57 -07002734 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002735 */
Dan Stoza412903f2017-04-27 13:42:17 -07002736void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2737 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002738
Robert Carr1f0a16a2016-10-24 16:27:39 -07002739 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002740 for (; i < list.size(); i++) {
2741 const auto& relative = list[i];
2742 if (relative->getZ() >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002743 break;
Robert Carrdb66e622017-04-10 16:55:57 -07002744 }
Dan Stoza412903f2017-04-27 13:42:17 -07002745 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002746 }
Dan Stoza412903f2017-04-27 13:42:17 -07002747 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07002748 for (; i < list.size(); i++) {
2749 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002750 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002751 }
2752}
2753
2754/**
Robert Carrdb66e622017-04-10 16:55:57 -07002755 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002756 */
Dan Stoza412903f2017-04-27 13:42:17 -07002757void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2758 const LayerVector::Visitor& visitor) {
2759 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002760
Robert Carr1f0a16a2016-10-24 16:27:39 -07002761 int32_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002762 for (i = list.size()-1; i>=0; i--) {
2763 const auto& relative = list[i];
2764 if (relative->getZ() < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002765 break;
2766 }
Dan Stoza412903f2017-04-27 13:42:17 -07002767 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002768 }
Dan Stoza412903f2017-04-27 13:42:17 -07002769 visitor(this);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002770 for (; i>=0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002771 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002772 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002773 }
2774}
2775
2776Transform Layer::getTransform() const {
2777 Transform t;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002778 const auto& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002779 if (p != nullptr) {
2780 t = p->getTransform();
Robert Carr9b429f42017-04-17 14:56:57 -07002781
2782 // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2783 // it isFixedSize) then there may be additional scaling not accounted
2784 // for in the transform. We need to mirror this scaling in child surfaces
2785 // or we will break the contract where WM can treat child surfaces as
2786 // pixels in the parent surface.
Chia-I Wu0a68b462017-07-18 11:30:05 -07002787 if (p->isFixedSize() && p->mActiveBuffer != nullptr) {
Robert Carr1725eee2017-04-26 18:32:15 -07002788 int bufferWidth;
2789 int bufferHeight;
2790 if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2791 bufferWidth = p->mActiveBuffer->getWidth();
2792 bufferHeight = p->mActiveBuffer->getHeight();
2793 } else {
2794 bufferHeight = p->mActiveBuffer->getWidth();
2795 bufferWidth = p->mActiveBuffer->getHeight();
2796 }
Robert Carr9b429f42017-04-17 14:56:57 -07002797 float sx = p->getDrawingState().active.w /
Robert Carr1725eee2017-04-26 18:32:15 -07002798 static_cast<float>(bufferWidth);
Robert Carr9b429f42017-04-17 14:56:57 -07002799 float sy = p->getDrawingState().active.h /
Robert Carr1725eee2017-04-26 18:32:15 -07002800 static_cast<float>(bufferHeight);
Robert Carr9b429f42017-04-17 14:56:57 -07002801 Transform extraParentScaling;
2802 extraParentScaling.set(sx, 0, 0, sy);
2803 t = t * extraParentScaling;
2804 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002805 }
2806 return t * getDrawingState().active.transform;
2807}
2808
chaviw13fdc492017-06-27 12:40:18 -07002809half Layer::getAlpha() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002810 const auto& p = mDrawingParent.promote();
Robert Carr6452f122017-03-21 10:41:29 -07002811
chaviw13fdc492017-06-27 12:40:18 -07002812 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2813 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002814}
Robert Carr6452f122017-03-21 10:41:29 -07002815
chaviw13fdc492017-06-27 12:40:18 -07002816half4 Layer::getColor() const {
2817 const half4 color(getDrawingState().color);
2818 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002819}
Robert Carr6452f122017-03-21 10:41:29 -07002820
Robert Carr1f0a16a2016-10-24 16:27:39 -07002821void Layer::commitChildList() {
2822 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2823 const auto& child = mCurrentChildren[i];
2824 child->commitChildList();
2825 }
2826 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002827 mDrawingParent = mCurrentParent;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002828}
2829
chaviw1d044282017-09-27 12:19:28 -07002830void Layer::writeToProto(LayerProto* layerInfo, LayerVector::StateSet stateSet) {
2831 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2832 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2833 const State& state = useDrawing ? mDrawingState : mCurrentState;
2834
2835 Transform requestedTransform = state.active.transform;
2836 Transform transform = getTransform();
2837
2838 layerInfo->set_id(sequence);
2839 layerInfo->set_name(getName().c_str());
2840 layerInfo->set_type(String8(getTypeId()));
2841
2842 for (const auto& child : children) {
2843 layerInfo->add_children(child->sequence);
2844 }
2845
2846 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2847 sp<Layer> strongRelative = weakRelative.promote();
2848 if (strongRelative != nullptr) {
2849 layerInfo->add_relatives(strongRelative->sequence);
2850 }
2851 }
2852
2853 LayerProtoHelper::writeToProto(state.activeTransparentRegion,
2854 layerInfo->mutable_transparent_region());
2855 LayerProtoHelper::writeToProto(visibleRegion, layerInfo->mutable_visible_region());
2856 LayerProtoHelper::writeToProto(surfaceDamageRegion, layerInfo->mutable_damage_region());
2857
2858 layerInfo->set_layer_stack(getLayerStack());
2859 layerInfo->set_z(state.z);
2860
2861 PositionProto* position = layerInfo->mutable_position();
2862 position->set_x(transform.tx());
2863 position->set_y(transform.ty());
2864
2865 PositionProto* requestedPosition = layerInfo->mutable_requested_position();
2866 requestedPosition->set_x(requestedTransform.tx());
2867 requestedPosition->set_y(requestedTransform.ty());
2868
2869 SizeProto* size = layerInfo->mutable_size();
2870 size->set_w(state.active.w);
2871 size->set_h(state.active.h);
2872
2873 LayerProtoHelper::writeToProto(state.crop, layerInfo->mutable_crop());
2874 LayerProtoHelper::writeToProto(state.finalCrop, layerInfo->mutable_final_crop());
2875
2876 layerInfo->set_is_opaque(isOpaque(state));
2877 layerInfo->set_invalidate(contentDirty);
2878 layerInfo->set_dataspace(dataspaceDetails(getDataSpace()));
2879 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2880 LayerProtoHelper::writeToProto(getColor(), layerInfo->mutable_color());
2881 LayerProtoHelper::writeToProto(state.color, layerInfo->mutable_requested_color());
2882 layerInfo->set_flags(state.flags);
2883
2884 LayerProtoHelper::writeToProto(transform, layerInfo->mutable_transform());
2885 LayerProtoHelper::writeToProto(requestedTransform, layerInfo->mutable_requested_transform());
2886
2887 auto parent = getParent();
2888 if (parent != nullptr) {
2889 layerInfo->set_parent(parent->sequence);
2890 }
2891
2892 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2893 if (zOrderRelativeOf != nullptr) {
2894 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2895 }
2896
2897 auto activeBuffer = getActiveBuffer();
2898 if (activeBuffer != nullptr) {
2899 LayerProtoHelper::writeToProto(activeBuffer, layerInfo->mutable_active_buffer());
2900 }
2901
2902 layerInfo->set_queued_frames(getQueuedFrameCount());
2903 layerInfo->set_refresh_pending(isBufferLatched());
2904}
2905
Mathias Agopian13127d82013-03-05 17:47:11 -08002906// ---------------------------------------------------------------------------
2907
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002908}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002909
2910#if defined(__gl_h_)
2911#error "don't include gl/gl.h in this file"
2912#endif
2913
2914#if defined(__gl2_h_)
2915#error "don't include gl2/gl2.h in this file"
2916#endif