blob: dbace322b604677301c0c4b121bfcb6268a35f1b [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 }
chaviwb1154d12017-10-31 14:15:36 -0700549
550 const auto& p = mDrawingParent.promote();
551 if (p != nullptr) {
552 auto parentCrop = p->computeInitialCrop(hw);
553 activeCrop.intersect(parentCrop, &activeCrop);
554 }
555
Robert Carr1f0a16a2016-10-24 16:27:39 -0700556 return activeCrop;
557}
558
Dan Stoza5a423ea2017-02-16 14:10:39 -0800559FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
Robert Carr1f0a16a2016-10-24 16:27:39 -0700560 // the content crop is the area of the content that gets scaled to the
561 // layer's size. This is in buffer space.
Dan Stoza5a423ea2017-02-16 14:10:39 -0800562 FloatRect crop = getContentCrop().toFloatRect();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700563
564 // In addition there is a WM-specified crop we pull from our drawing state.
565 const State& s(getDrawingState());
566
567 // Screen space to make reduction to parent crop clearer.
568 Rect activeCrop = computeInitialCrop(hw);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700569 Transform t = getTransform();
570 // Back to layer space to work with the content crop.
571 activeCrop = t.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800572
Michael Lentine28ea2172014-11-19 18:32:37 -0800573 // This needs to be here as transform.transform(Rect) computes the
574 // transformed rect and then takes the bounding box of the result before
575 // returning. This means
576 // transform.inverse().transform(transform.transform(Rect)) != Rect
577 // in which case we need to make sure the final rect is clipped to the
578 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000579 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
580 activeCrop.clear();
581 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800582
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700583 // subtract the transparent region and snap to the bounds
584 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
585
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000586 // Transform the window crop to match the buffer coordinate system,
587 // which means using the inverse of the current transform set on the
588 // SurfaceFlingerConsumer.
589 uint32_t invTransform = mCurrentTransform;
Robert Carrcae605c2017-03-29 12:10:31 -0700590 if (getTransformToDisplayInverse()) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000591 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700592 * the code below applies the primary display's inverse transform to the
593 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000594 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700595 uint32_t invTransformOrient =
596 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000597 // calculate the inverse transform
598 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
599 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
600 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800601 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000602 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700603 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
604 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800605 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000606
607 int winWidth = s.active.w;
608 int winHeight = s.active.h;
609 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
610 // If the activeCrop has been rotate the ends are rotated but not
611 // the space itself so when transforming ends back we can't rely on
612 // a modification of the axes of rotation. To account for this we
613 // need to reorient the inverse rotation in terms of the current
614 // axes of rotation.
615 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
616 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
617 if (is_h_flipped == is_v_flipped) {
618 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
619 NATIVE_WINDOW_TRANSFORM_FLIP_H;
620 }
621 winWidth = s.active.h;
622 winHeight = s.active.w;
623 }
624 const Rect winCrop = activeCrop.transform(
625 invTransform, s.active.w, s.active.h);
626
627 // below, crop is intersected with winCrop expressed in crop's coordinate space
628 float xScale = crop.getWidth() / float(winWidth);
629 float yScale = crop.getHeight() / float(winHeight);
630
631 float insetL = winCrop.left * xScale;
632 float insetT = winCrop.top * yScale;
633 float insetR = (winWidth - winCrop.right ) * xScale;
634 float insetB = (winHeight - winCrop.bottom) * yScale;
635
636 crop.left += insetL;
637 crop.top += insetT;
638 crop.right -= insetR;
639 crop.bottom -= insetB;
640
Mathias Agopian13127d82013-03-05 17:47:11 -0800641 return crop;
642}
643
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000644#ifdef USE_HWC2
Robert Carrae060832016-11-28 10:51:00 -0800645void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000646#else
647void Layer::setGeometry(
648 const sp<const DisplayDevice>& hw,
649 HWComposer::HWCLayerInterface& layer)
650#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700651{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000652#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800653 const auto hwcId = displayDevice->getHwcDisplayId();
654 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000655#else
656 layer.setDefaultState();
657#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700658
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700659 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000660#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800661 hwcInfo.forceClientComposition = false;
662
663 if (isSecure() && !displayDevice->isSecure()) {
664 hwcInfo.forceClientComposition = true;
665 }
666
667 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000668#else
669 layer.setSkip(false);
670
671 if (isSecure() && !hw->isSecure()) {
672 layer.setSkip(true);
673 }
674#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700675
Mathias Agopian13127d82013-03-05 17:47:11 -0800676 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700677 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000678#ifdef USE_HWC2
David Revemanecf0fa52017-03-03 11:32:44 -0500679 auto blendMode = HWC2::BlendMode::None;
Robert Carr6452f122017-03-21 10:41:29 -0700680 if (!isOpaque(s) || getAlpha() != 1.0f) {
David Revemanecf0fa52017-03-03 11:32:44 -0500681 blendMode = mPremultipliedAlpha ?
Dan Stoza9e56aa02015-11-02 13:00:03 -0800682 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800683 }
David Revemanecf0fa52017-03-03 11:32:44 -0500684 auto error = hwcLayer->setBlendMode(blendMode);
685 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
686 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
687 to_string(error).c_str(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000688#else
chaviw13fdc492017-06-27 12:40:18 -0700689 if (!isOpaque(s) || getAlpha() != 1.0f) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000690 layer.setBlending(mPremultipliedAlpha ?
691 HWC_BLENDING_PREMULT :
692 HWC_BLENDING_COVERAGE);
693 }
694#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800695
696 // apply the layer's transform, followed by the display's global transform
697 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700698 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700699 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -0700700 if (!s.crop.isEmpty()) {
701 Rect activeCrop(s.crop);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700702 activeCrop = t.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000703#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000704 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000705#else
706 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
707#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000708 activeCrop.clear();
709 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700710 activeCrop = t.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800711 // This needs to be here as transform.transform(Rect) computes the
712 // transformed rect and then takes the bounding box of the result before
713 // returning. This means
714 // transform.inverse().transform(transform.transform(Rect)) != Rect
715 // in which case we need to make sure the final rect is clipped to the
716 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000717 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
718 activeCrop.clear();
719 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700720 // mark regions outside the crop as transparent
721 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
722 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
723 s.active.w, s.active.h));
724 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
725 activeCrop.left, activeCrop.bottom));
726 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
727 s.active.w, activeCrop.bottom));
728 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700729
730 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700731 if (!s.finalCrop.isEmpty()) {
732 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000733 frame.clear();
734 }
735 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000736#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000737 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
738 frame.clear();
739 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800740 const Transform& tr(displayDevice->getTransform());
741 Rect transformedFrame = tr.transform(frame);
David Revemanecf0fa52017-03-03 11:32:44 -0500742 error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700743 if (error != HWC2::Error::None) {
744 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
745 mName.string(), transformedFrame.left, transformedFrame.top,
746 transformedFrame.right, transformedFrame.bottom,
747 to_string(error).c_str(), static_cast<int32_t>(error));
748 } else {
749 hwcInfo.displayFrame = transformedFrame;
750 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800751
Dan Stoza5a423ea2017-02-16 14:10:39 -0800752 FloatRect sourceCrop = computeCrop(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800753 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700754 if (error != HWC2::Error::None) {
755 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
756 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
757 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
758 static_cast<int32_t>(error));
759 } else {
760 hwcInfo.sourceCrop = sourceCrop;
761 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800762
chaviw13fdc492017-06-27 12:40:18 -0700763 float alpha = static_cast<float>(getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -0700764 error = hwcLayer->setPlaneAlpha(alpha);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800765 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
Robert Carr6452f122017-03-21 10:41:29 -0700766 "%s (%d)", mName.string(), alpha, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800767 static_cast<int32_t>(error));
768
Robert Carrae060832016-11-28 10:51:00 -0800769 error = hwcLayer->setZOrder(z);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800770 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
Robert Carrae060832016-11-28 10:51:00 -0800771 mName.string(), z, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800772 static_cast<int32_t>(error));
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500773
Albert Chaulk2a589632017-05-04 16:59:44 -0400774 int type = s.type;
775 int appId = s.appId;
Chia-I Wue41dbe62017-06-13 14:10:56 -0700776 sp<Layer> parent = mDrawingParent.promote();
Albert Chaulk2a589632017-05-04 16:59:44 -0400777 if (parent.get()) {
778 auto& parentState = parent->getDrawingState();
779 type = parentState.type;
780 appId = parentState.appId;
781 }
782
783 error = hwcLayer->setInfo(type, appId);
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500784 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
785 mName.string(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000786#else
787 if (!frame.intersect(hw->getViewport(), &frame)) {
788 frame.clear();
789 }
790 const Transform& tr(hw->getTransform());
791 layer.setFrame(tr.transform(frame));
792 layer.setCrop(computeCrop(hw));
chaviw13fdc492017-06-27 12:40:18 -0700793 layer.setPlaneAlpha(static_cast<uint8_t>(std::round(255.0f*getAlpha())));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000794#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800795
Mathias Agopian29a367b2011-07-12 14:51:45 -0700796 /*
797 * Transformations are applied in this order:
798 * 1) buffer orientation/flip/mirror
799 * 2) state transformation (window manager)
800 * 3) layer orientation (screen orientation)
801 * (NOTE: the matrices are multiplied in reverse order)
802 */
803
804 const Transform bufferOrientation(mCurrentTransform);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700805 Transform transform(tr * t * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700806
Robert Carrcae605c2017-03-29 12:10:31 -0700807 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700808 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700809 * the code below applies the primary display's inverse transform to the
810 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700811 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700812 uint32_t invTransform =
813 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700814 // calculate the inverse transform
815 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
816 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
817 NATIVE_WINDOW_TRANSFORM_FLIP_H;
818 }
Robert Carrcae605c2017-03-29 12:10:31 -0700819
820 /*
821 * Here we cancel out the orientation component of the WM transform.
822 * The scaling and translate components are already included in our bounds
823 * computation so it's enough to just omit it in the composition.
824 * See comment in onDraw with ref to b/36727915 for why.
825 */
826 transform = Transform(invTransform) * tr * bufferOrientation;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700827 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700828
829 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800830 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000831#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800832 if (orientation & Transform::ROT_INVALID) {
833 // we can only handle simple transformation
834 hwcInfo.forceClientComposition = true;
835 } else {
836 auto transform = static_cast<HWC2::Transform>(orientation);
837 auto error = hwcLayer->setTransform(transform);
838 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
839 "%s (%d)", mName.string(), to_string(transform).c_str(),
840 to_string(error).c_str(), static_cast<int32_t>(error));
841 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000842#else
843 if (orientation & Transform::ROT_INVALID) {
844 // we can only handle simple transformation
845 layer.setSkip(true);
846 } else {
847 layer.setTransform(orientation);
848 }
849#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700850}
851
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000852#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800853void Layer::forceClientComposition(int32_t hwcId) {
854 if (mHwcLayers.count(hwcId) == 0) {
855 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
856 return;
857 }
858
859 mHwcLayers[hwcId].forceClientComposition = true;
860}
Dan Stoza9e56aa02015-11-02 13:00:03 -0800861
Dan Stoza9e56aa02015-11-02 13:00:03 -0800862void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
863 // Apply this display's projection's viewport to the visible region
864 // before giving it to the HWC HAL.
865 const Transform& tr = displayDevice->getTransform();
866 const auto& viewport = displayDevice->getViewport();
867 Region visible = tr.transform(visibleRegion.intersect(viewport));
868 auto hwcId = displayDevice->getHwcDisplayId();
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800869 auto& hwcInfo = mHwcLayers[hwcId];
870 auto& hwcLayer = hwcInfo.layer;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800871 auto error = hwcLayer->setVisibleRegion(visible);
872 if (error != HWC2::Error::None) {
873 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
874 to_string(error).c_str(), static_cast<int32_t>(error));
875 visible.dump(LOG_TAG);
876 }
877
878 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
879 if (error != HWC2::Error::None) {
880 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
881 to_string(error).c_str(), static_cast<int32_t>(error));
882 surfaceDamageRegion.dump(LOG_TAG);
883 }
884
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700885 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800886 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700887 setCompositionType(hwcId, HWC2::Composition::Sideband);
888 ALOGV("[%s] Requesting Sideband composition", mName.string());
889 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800890 if (error != HWC2::Error::None) {
891 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
892 mName.string(), mSidebandStream->handle(),
893 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700895 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800896 }
897
Dan Stoza0a21df72016-07-20 12:52:38 -0700898 // Client layers
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800899 if (hwcInfo.forceClientComposition ||
Dan Stoza0a21df72016-07-20 12:52:38 -0700900 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700901 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800902 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700903 return;
904 }
905
Dan Stoza0a21df72016-07-20 12:52:38 -0700906 // SolidColor layers
907 if (mActiveBuffer == nullptr) {
908 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700909
chaviw13fdc492017-06-27 12:40:18 -0700910 half4 color = getColor();
911 error = hwcLayer->setColor({static_cast<uint8_t>(std::round(255.0f*color.r)),
912 static_cast<uint8_t>(std::round(255.0f * color.g)),
913 static_cast<uint8_t>(std::round(255.0f * color.b)),
914 255});
Dan Stoza0a21df72016-07-20 12:52:38 -0700915 if (error != HWC2::Error::None) {
916 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
917 to_string(error).c_str(), static_cast<int32_t>(error));
918 }
Dan Stozac6c89542016-07-27 10:16:52 -0700919
920 // Clear out the transform, because it doesn't make sense absent a
921 // source buffer
922 error = hwcLayer->setTransform(HWC2::Transform::None);
923 if (error != HWC2::Error::None) {
924 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
925 to_string(error).c_str(), static_cast<int32_t>(error));
926 }
927
Dan Stoza0a21df72016-07-20 12:52:38 -0700928 return;
929 }
930
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700931 // Device or Cursor layers
932 if (mPotentialCursor) {
933 ALOGV("[%s] Requesting Cursor composition", mName.string());
934 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800935 } else {
936 ALOGV("[%s] Requesting Device composition", mName.string());
937 setCompositionType(hwcId, HWC2::Composition::Device);
938 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700939
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700940 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
941 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
942 if (error != HWC2::Error::None) {
943 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
944 mCurrentState.dataSpace, to_string(error).c_str(),
945 static_cast<int32_t>(error));
946 }
947
Chia-I Wu06d63de2017-01-04 14:58:51 +0800948 uint32_t hwcSlot = 0;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400949 sp<GraphicBuffer> hwcBuffer;
950 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
951 &hwcSlot, &hwcBuffer);
Chia-I Wu06d63de2017-01-04 14:58:51 +0800952
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700953 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400954 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700955 if (error != HWC2::Error::None) {
956 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
957 mActiveBuffer->handle, to_string(error).c_str(),
958 static_cast<int32_t>(error));
959 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800960}
Courtney Goeltzenleuchter9551fd32016-10-20 17:18:15 -0600961
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000962#else
963void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
964 HWComposer::HWCLayerInterface& layer) {
965 // we have to set the visible region on every frame because
966 // we currently free it during onLayerDisplayed(), which is called
967 // after HWComposer::commit() -- every frame.
968 // Apply this display's projection's viewport to the visible region
969 // before giving it to the HWC HAL.
970 const Transform& tr = hw->getTransform();
971 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
972 layer.setVisibleRegionScreen(visible);
973 layer.setSurfaceDamage(surfaceDamageRegion);
974 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700975
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000976 if (mSidebandStream.get()) {
977 layer.setSidebandStream(mSidebandStream);
978 } else {
979 // NOTE: buffer can be NULL if the client never drew into this
980 // layer yet, or if we ran out of memory
981 layer.setBuffer(mActiveBuffer);
982 }
983}
984#endif
985
986#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800987void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
988 auto hwcId = displayDevice->getHwcDisplayId();
989 if (mHwcLayers.count(hwcId) == 0 ||
990 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
991 return;
992 }
993
994 // This gives us only the "orientation" component of the transform
995 const State& s(getCurrentState());
996
997 // Apply the layer's transform, followed by the display's global transform
998 // Here we're guaranteed that the layer's transform preserves rects
999 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -07001000 if (!s.crop.isEmpty()) {
1001 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001002 }
1003 // Subtract the transparent region and snap to the bounds
1004 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001005 Rect frame(getTransform().transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -08001006 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -07001007 if (!s.finalCrop.isEmpty()) {
1008 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001009 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001010 auto& displayTransform(displayDevice->getTransform());
1011 auto position = displayTransform.transform(frame);
1012
1013 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
1014 position.top);
1015 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
1016 "to (%d, %d): %s (%d)", mName.string(), position.left,
1017 position.top, to_string(error).c_str(),
1018 static_cast<int32_t>(error));
1019}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001020#else
1021void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
1022 HWComposer::HWCLayerInterface& layer) {
1023 int fenceFd = -1;
1024
1025 // TODO: there is a possible optimization here: we only need to set the
1026 // acquire fence the first time a new buffer is acquired on EACH display.
1027
1028 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
1029 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
1030 if (fence->isValid()) {
1031 fenceFd = fence->dup();
1032 if (fenceFd == -1) {
1033 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
1034 }
1035 }
1036 }
1037 layer.setAcquireFenceFd(fenceFd);
1038}
1039
1040Rect Layer::getPosition(
1041 const sp<const DisplayDevice>& hw)
1042{
1043 // this gives us only the "orientation" component of the transform
1044 const State& s(getCurrentState());
1045
1046 // apply the layer's transform, followed by the display's global transform
1047 // here we're guaranteed that the layer's transform preserves rects
1048 Rect win(s.active.w, s.active.h);
1049 if (!s.crop.isEmpty()) {
1050 win.intersect(s.crop, &win);
1051 }
1052 // subtract the transparent region and snap to the bounds
1053 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001054 Rect frame(getTransform().transform(bounds));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001055 frame.intersect(hw->getViewport(), &frame);
1056 if (!s.finalCrop.isEmpty()) {
1057 frame.intersect(s.finalCrop, &frame);
1058 }
1059 const Transform& tr(hw->getTransform());
1060 return Rect(tr.transform(frame));
1061}
1062#endif
Riley Andrews03414a12014-07-01 14:22:59 -07001063
Mathias Agopian13127d82013-03-05 17:47:11 -08001064// ---------------------------------------------------------------------------
1065// drawing...
1066// ---------------------------------------------------------------------------
1067
1068void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -08001069 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -08001070}
1071
Dan Stozac7014012014-02-14 15:03:43 -08001072void Layer::draw(const sp<const DisplayDevice>& hw,
1073 bool useIdentityTransform) const {
1074 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001075}
1076
Dan Stozac7014012014-02-14 15:03:43 -08001077void Layer::draw(const sp<const DisplayDevice>& hw) const {
1078 onDraw(hw, Region(hw->bounds()), false);
1079}
1080
Robert Carrcae605c2017-03-29 12:10:31 -07001081static constexpr mat4 inverseOrientation(uint32_t transform) {
1082 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1083 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1084 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1085 mat4 tr;
1086
1087 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1088 tr = tr * rot90;
1089 }
1090 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1091 tr = tr * flipH;
1092 }
1093 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1094 tr = tr * flipV;
1095 }
1096 return inverse(tr);
1097}
1098
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001099/*
1100 * onDraw will draw the current layer onto the presentable buffer
1101 */
Dan Stozac7014012014-02-14 15:03:43 -08001102void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
1103 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001104{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001105 ATRACE_CALL();
1106
Mathias Agopiana67932f2011-04-20 14:20:59 -07001107 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001108 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -07001109 // in fact never been drawn into. This happens frequently with
1110 // SurfaceView because the WindowManager can't know when the client
1111 // has drawn the first time.
1112
1113 // If there is nothing under us, we paint the screen in black, otherwise
1114 // we just skip this update.
1115
1116 // figure out if there is something below us
1117 Region under;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001118 bool finished = false;
Dan Stoza412903f2017-04-27 13:42:17 -07001119 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001120 if (finished || layer == static_cast<Layer const*>(this)) {
1121 finished = true;
1122 return;
1123 }
Mathias Agopian42977342012-08-05 00:40:46 -07001124 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Robert Carr1f0a16a2016-10-24 16:27:39 -07001125 });
Mathias Agopian179169e2010-05-06 20:21:45 -07001126 // if not everything below us is covered, we plug the holes!
1127 Region holes(clip.subtract(under));
1128 if (!holes.isEmpty()) {
Fabien Sanglard17487192016-12-07 13:03:32 -08001129 clearWithOpenGL(hw, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -07001130 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001131 return;
1132 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001133
Andy McFadden97eba892012-12-11 15:21:45 -08001134 // Bind the current buffer to the GL texture, and wait for it to be
1135 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001136 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1137 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -08001138 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -07001139 // Go ahead and draw the buffer anyway; no matter what we do the screen
1140 // is probably going to have something visibly wrong.
1141 }
1142
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001143 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1144
Mathias Agopian875d8e12013-06-07 15:35:48 -07001145 RenderEngine& engine(mFlinger->getRenderEngine());
1146
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001147 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -07001148 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -07001149 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -07001150
1151 // Query the texture matrix given our current filtering mode.
1152 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001153 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1154 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -07001155
Robert Carrcae605c2017-03-29 12:10:31 -07001156 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001157
1158 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -07001159 * the code below applies the primary display's inverse transform to
1160 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001161 */
Pablo Ceballos021623b2016-04-15 17:31:51 -07001162 uint32_t transform =
1163 DisplayDevice::getPrimaryDisplayOrientationTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001164 mat4 tr = inverseOrientation(transform);
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001165
Robert Carrcae605c2017-03-29 12:10:31 -07001166 /**
1167 * TODO(b/36727915): This is basically a hack.
1168 *
1169 * Ensure that regardless of the parent transformation,
1170 * this buffer is always transformed from native display
1171 * orientation to display orientation. For example, in the case
1172 * of a camera where the buffer remains in native orientation,
1173 * we want the pixels to always be upright.
1174 */
Chia-I Wue41dbe62017-06-13 14:10:56 -07001175 sp<Layer> p = mDrawingParent.promote();
1176 if (p != nullptr) {
1177 const auto parentTransform = p->getTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001178 tr = tr * inverseOrientation(parentTransform.getOrientation());
1179 }
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001180
1181 // and finally apply it to the original texture matrix
1182 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1183 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1184 }
1185
Jamie Genniscbb1a952012-05-08 17:05:52 -07001186 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -07001187 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1188 mTexture.setFiltering(useFiltering);
1189 mTexture.setMatrix(textureMatrix);
1190
1191 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -07001192 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001193 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -07001194 }
Fabien Sanglard85789802016-12-07 13:08:24 -08001195 drawWithOpenGL(hw, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001196 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001197}
1198
Mathias Agopian13127d82013-03-05 17:47:11 -08001199
Dan Stozac7014012014-02-14 15:03:43 -08001200void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard17487192016-12-07 13:03:32 -08001201 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -08001202 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001203{
Mathias Agopian19733a32013-08-28 18:13:56 -07001204 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -08001205 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -07001206 engine.setupFillWithColor(red, green, blue, alpha);
1207 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -08001208}
1209
1210void Layer::clearWithOpenGL(
Fabien Sanglard17487192016-12-07 13:03:32 -08001211 const sp<const DisplayDevice>& hw) const {
1212 clearWithOpenGL(hw, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001213}
1214
Dan Stozac7014012014-02-14 15:03:43 -08001215void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard85789802016-12-07 13:08:24 -08001216 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001217 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001218
Dan Stozac7014012014-02-14 15:03:43 -08001219 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001220
Mathias Agopian13127d82013-03-05 17:47:11 -08001221 /*
1222 * NOTE: the way we compute the texture coordinates here produces
1223 * different results than when we take the HWC path -- in the later case
1224 * the "source crop" is rounded to texel boundaries.
1225 * This can produce significantly different results when the texture
1226 * is scaled by a large amount.
1227 *
1228 * The GL code below is more logical (imho), and the difference with
1229 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001230 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001231 * GL composition when a buffer scaling is applied (maybe with some
1232 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1233 * like more of a hack.
1234 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001235 Rect win(computeBounds());
1236
Robert Carr1f0a16a2016-10-24 16:27:39 -07001237 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -07001238 if (!s.finalCrop.isEmpty()) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001239 win = t.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001240 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001241 win.clear();
1242 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001243 win = t.inverse().transform(win);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001244 if (!win.intersect(computeBounds(), &win)) {
1245 win.clear();
1246 }
1247 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001248
Mathias Agopian3f844832013-08-07 21:24:32 -07001249 float left = float(win.left) / float(s.active.w);
1250 float top = float(win.top) / float(s.active.h);
1251 float right = float(win.right) / float(s.active.w);
1252 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001253
Mathias Agopian875d8e12013-06-07 15:35:48 -07001254 // TODO: we probably want to generate the texture coords with the mesh
1255 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001256 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1257 texCoords[0] = vec2(left, 1.0f - top);
1258 texCoords[1] = vec2(left, 1.0f - bottom);
1259 texCoords[2] = vec2(right, 1.0f - bottom);
1260 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001261
Mathias Agopian875d8e12013-06-07 15:35:48 -07001262 RenderEngine& engine(mFlinger->getRenderEngine());
chaviw13fdc492017-06-27 12:40:18 -07001263 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s),
1264 false /* disableTexture */, getColor());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001265#ifdef USE_HWC2
1266 engine.setSourceDataSpace(mCurrentState.dataSpace);
1267#endif
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001268 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001269 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001270}
1271
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001272#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001273void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1274 bool callIntoHwc) {
1275 if (mHwcLayers.count(hwcId) == 0) {
1276 ALOGE("setCompositionType called without a valid HWC layer");
1277 return;
1278 }
1279 auto& hwcInfo = mHwcLayers[hwcId];
1280 auto& hwcLayer = hwcInfo.layer;
1281 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1282 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1283 if (hwcInfo.compositionType != type) {
1284 ALOGV(" actually setting");
1285 hwcInfo.compositionType = type;
1286 if (callIntoHwc) {
1287 auto error = hwcLayer->setCompositionType(type);
1288 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1289 "composition type %s: %s (%d)", mName.string(),
1290 to_string(type).c_str(), to_string(error).c_str(),
1291 static_cast<int32_t>(error));
1292 }
1293 }
1294}
1295
1296HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001297 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1298 // If we're querying the composition type for a display that does not
1299 // have a HWC counterpart, then it will always be Client
1300 return HWC2::Composition::Client;
1301 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001302 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001303 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001304 return HWC2::Composition::Invalid;
1305 }
1306 return mHwcLayers.at(hwcId).compositionType;
1307}
1308
1309void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1310 if (mHwcLayers.count(hwcId) == 0) {
1311 ALOGE("setClearClientTarget called without a valid HWC layer");
1312 return;
1313 }
1314 mHwcLayers[hwcId].clearClientTarget = clear;
1315}
1316
1317bool Layer::getClearClientTarget(int32_t hwcId) const {
1318 if (mHwcLayers.count(hwcId) == 0) {
1319 ALOGE("getClearClientTarget called without a valid HWC layer");
1320 return false;
1321 }
1322 return mHwcLayers.at(hwcId).clearClientTarget;
1323}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001324#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001325
Ruben Brunk1681d952014-06-27 15:51:55 -07001326uint32_t Layer::getProducerStickyTransform() const {
1327 int producerStickyTransform = 0;
1328 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1329 if (ret != OK) {
1330 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1331 strerror(-ret), ret);
1332 return 0;
1333 }
1334 return static_cast<uint32_t>(producerStickyTransform);
1335}
1336
Dan Stozac5da2712016-07-20 15:38:12 -07001337bool Layer::latchUnsignaledBuffers() {
1338 static bool propertyLoaded = false;
1339 static bool latch = false;
1340 static std::mutex mutex;
1341 std::lock_guard<std::mutex> lock(mutex);
1342 if (!propertyLoaded) {
1343 char value[PROPERTY_VALUE_MAX] = {};
1344 property_get("debug.sf.latch_unsignaled", value, "0");
1345 latch = atoi(value);
1346 propertyLoaded = true;
1347 }
1348 return latch;
1349}
1350
Dan Stozacac35382016-01-27 12:21:06 -08001351uint64_t Layer::getHeadFrameNumber() const {
1352 Mutex::Autolock lock(mQueueItemLock);
1353 if (!mQueueItems.empty()) {
1354 return mQueueItems[0].mFrameNumber;
1355 } else {
1356 return mCurrentFrameNumber;
1357 }
1358}
1359
Dan Stoza1ce65812016-06-15 16:26:27 -07001360bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001361#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001362 if (latchUnsignaledBuffers()) {
1363 return true;
1364 }
1365
Dan Stoza1ce65812016-06-15 16:26:27 -07001366 Mutex::Autolock lock(mQueueItemLock);
1367 if (mQueueItems.empty()) {
1368 return true;
1369 }
1370 if (mQueueItems[0].mIsDroppable) {
1371 // Even though this buffer's fence may not have signaled yet, it could
1372 // be replaced by another buffer before it has a chance to, which means
1373 // that it's possible to get into a situation where a buffer is never
1374 // able to be latched. To avoid this, grab this buffer anyway.
1375 return true;
1376 }
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001377 return mQueueItems[0].mFenceTime->getSignalTime() !=
1378 Fence::SIGNAL_TIME_PENDING;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001379#else
1380 return true;
1381#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001382}
1383
Dan Stozacac35382016-01-27 12:21:06 -08001384bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1385 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1386 // Don't bother with a SyncPoint, since we've already latched the
1387 // relevant frame
1388 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001389 }
1390
Dan Stozacac35382016-01-27 12:21:06 -08001391 Mutex::Autolock lock(mLocalSyncPointMutex);
1392 mLocalSyncPoints.push_back(point);
1393 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001394}
1395
Mathias Agopian13127d82013-03-05 17:47:11 -08001396void Layer::setFiltering(bool filtering) {
1397 mFiltering = filtering;
1398}
1399
1400bool Layer::getFiltering() const {
1401 return mFiltering;
1402}
1403
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001404// As documented in libhardware header, formats in the range
1405// 0x100 - 0x1FF are specific to the HAL implementation, and
1406// are known to have no alpha channel
1407// TODO: move definition for device-specific range into
1408// hardware.h, instead of using hard-coded values here.
1409#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1410
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001411bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001412 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1413 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001414 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001415 switch (format) {
1416 case HAL_PIXEL_FORMAT_RGBA_8888:
1417 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001418 case HAL_PIXEL_FORMAT_RGBA_FP16:
Romain Guy541f2262017-02-10 18:50:17 -08001419 case HAL_PIXEL_FORMAT_RGBA_1010102:
Mathias Agopiandd533712013-07-26 15:31:39 -07001420 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001421 }
1422 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001423 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001424}
1425
Mathias Agopian13127d82013-03-05 17:47:11 -08001426// ----------------------------------------------------------------------------
1427// local state
1428// ----------------------------------------------------------------------------
1429
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001430static void boundPoint(vec2* point, const Rect& crop) {
1431 if (point->x < crop.left) {
1432 point->x = crop.left;
1433 }
1434 if (point->x > crop.right) {
1435 point->x = crop.right;
1436 }
1437 if (point->y < crop.top) {
1438 point->y = crop.top;
1439 }
1440 if (point->y > crop.bottom) {
1441 point->y = crop.bottom;
1442 }
1443}
1444
Dan Stozac7014012014-02-14 15:03:43 -08001445void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1446 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001447{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001448 const Layer::State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001449 const Transform hwTransform(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001450 const uint32_t hw_h = hw->getHeight();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001451 Rect win = computeBounds();
Mathias Agopian3f844832013-08-07 21:24:32 -07001452
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001453 vec2 lt = vec2(win.left, win.top);
1454 vec2 lb = vec2(win.left, win.bottom);
1455 vec2 rb = vec2(win.right, win.bottom);
1456 vec2 rt = vec2(win.right, win.top);
1457
Robert Carr1f0a16a2016-10-24 16:27:39 -07001458 Transform layerTransform = getTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001459 if (!useIdentityTransform) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001460 lt = layerTransform.transform(lt);
1461 lb = layerTransform.transform(lb);
1462 rb = layerTransform.transform(rb);
1463 rt = layerTransform.transform(rt);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001464 }
1465
Robert Carrb5d3d262016-03-25 15:08:13 -07001466 if (!s.finalCrop.isEmpty()) {
1467 boundPoint(&lt, s.finalCrop);
1468 boundPoint(&lb, s.finalCrop);
1469 boundPoint(&rb, s.finalCrop);
1470 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001471 }
1472
Mathias Agopianff2ed702013-09-01 21:36:12 -07001473 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001474 position[0] = hwTransform.transform(lt);
1475 position[1] = hwTransform.transform(lb);
1476 position[2] = hwTransform.transform(rb);
1477 position[3] = hwTransform.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001478 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001479 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001480 }
1481}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001482
Andy McFadden4125a4f2014-01-29 17:17:11 -08001483bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001484{
neo.hee6fd41d2017-02-17 14:35:33 +08001485 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
Mathias Agopiana67932f2011-04-20 14:20:59 -07001486 // layer's opaque flag.
neo.hee6fd41d2017-02-17 14:35:33 +08001487 if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001488 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001489 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001490
1491 // if the layer has the opaque flag, then we're always opaque,
1492 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001493 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001494}
1495
Dan Stoza23116082015-06-18 14:58:39 -07001496bool Layer::isSecure() const
1497{
1498 const Layer::State& s(mDrawingState);
1499 return (s.flags & layer_state_t::eLayerSecure);
1500}
1501
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001502bool Layer::isProtected() const
1503{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001504 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001505 return (activeBuffer != 0) &&
1506 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1507}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001508
Mathias Agopian13127d82013-03-05 17:47:11 -08001509bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001510 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001511}
1512
1513bool Layer::isCropped() const {
1514 return !mCurrentCrop.isEmpty();
1515}
1516
1517bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1518 return mNeedsFiltering || hw->needsFiltering();
1519}
1520
1521void Layer::setVisibleRegion(const Region& visibleRegion) {
1522 // always called from main thread
1523 this->visibleRegion = visibleRegion;
1524}
1525
1526void Layer::setCoveredRegion(const Region& coveredRegion) {
1527 // always called from main thread
1528 this->coveredRegion = coveredRegion;
1529}
1530
1531void Layer::setVisibleNonTransparentRegion(const Region&
1532 setVisibleNonTransparentRegion) {
1533 // always called from main thread
1534 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1535}
1536
1537// ----------------------------------------------------------------------------
1538// transaction
1539// ----------------------------------------------------------------------------
1540
Dan Stoza7dde5992015-05-22 09:51:44 -07001541void Layer::pushPendingState() {
1542 if (!mCurrentState.modified) {
1543 return;
1544 }
1545
Dan Stoza7dde5992015-05-22 09:51:44 -07001546 // If this transaction is waiting on the receipt of a frame, generate a sync
1547 // point and send it to the remote layer.
Robert Carr0d480722017-01-10 16:42:54 -08001548 if (mCurrentState.barrierLayer != nullptr) {
1549 sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1550 if (barrierLayer == nullptr) {
1551 ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
Dan Stoza7dde5992015-05-22 09:51:44 -07001552 // If we can't promote the layer we are intended to wait on,
1553 // then it is expired or otherwise invalid. Allow this transaction
1554 // to be applied as per normal (no synchronization).
Robert Carr0d480722017-01-10 16:42:54 -08001555 mCurrentState.barrierLayer = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001556 } else {
1557 auto syncPoint = std::make_shared<SyncPoint>(
1558 mCurrentState.frameNumber);
Robert Carr0d480722017-01-10 16:42:54 -08001559 if (barrierLayer->addSyncPoint(syncPoint)) {
Dan Stozacac35382016-01-27 12:21:06 -08001560 mRemoteSyncPoints.push_back(std::move(syncPoint));
1561 } else {
1562 // We already missed the frame we're supposed to synchronize
1563 // on, so go ahead and apply the state update
Robert Carr0d480722017-01-10 16:42:54 -08001564 mCurrentState.barrierLayer = nullptr;
Dan Stozacac35382016-01-27 12:21:06 -08001565 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001566 }
1567
Dan Stoza7dde5992015-05-22 09:51:44 -07001568 // Wake us up to check if the frame has been received
1569 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001570 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001571 }
1572 mPendingStates.push_back(mCurrentState);
Dan Stozaf7ba41a2017-05-10 15:11:11 -07001573 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
Dan Stoza7dde5992015-05-22 09:51:44 -07001574}
1575
Pablo Ceballos05289c22016-04-14 15:49:55 -07001576void Layer::popPendingState(State* stateToCommit) {
1577 auto oldFlags = stateToCommit->flags;
1578 *stateToCommit = mPendingStates[0];
1579 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1580 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001581
1582 mPendingStates.removeAt(0);
Dan Stozaf7ba41a2017-05-10 15:11:11 -07001583 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
Dan Stoza7dde5992015-05-22 09:51:44 -07001584}
1585
Pablo Ceballos05289c22016-04-14 15:49:55 -07001586bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001587 bool stateUpdateAvailable = false;
1588 while (!mPendingStates.empty()) {
Robert Carr0d480722017-01-10 16:42:54 -08001589 if (mPendingStates[0].barrierLayer != nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001590 if (mRemoteSyncPoints.empty()) {
1591 // If we don't have a sync point for this, apply it anyway. It
1592 // will be visually wrong, but it should keep us from getting
1593 // into too much trouble.
1594 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001595 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001596 stateUpdateAvailable = true;
1597 continue;
1598 }
1599
Dan Stozacac35382016-01-27 12:21:06 -08001600 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1601 mPendingStates[0].frameNumber) {
1602 ALOGE("[%s] Unexpected sync point frame number found",
1603 mName.string());
1604
1605 // Signal our end of the sync point and then dispose of it
1606 mRemoteSyncPoints.front()->setTransactionApplied();
1607 mRemoteSyncPoints.pop_front();
1608 continue;
1609 }
1610
Dan Stoza7dde5992015-05-22 09:51:44 -07001611 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1612 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001613 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001614 stateUpdateAvailable = true;
1615
1616 // Signal our end of the sync point and then dispose of it
1617 mRemoteSyncPoints.front()->setTransactionApplied();
1618 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001619 } else {
1620 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001621 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001622 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001623 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001624 stateUpdateAvailable = true;
1625 }
1626 }
1627
1628 // If we still have pending updates, wake SurfaceFlinger back up and point
1629 // it at this layer so we can process them
1630 if (!mPendingStates.empty()) {
1631 setTransactionFlags(eTransactionNeeded);
1632 mFlinger->setTransactionFlags(eTraversalNeeded);
1633 }
1634
1635 mCurrentState.modified = false;
1636 return stateUpdateAvailable;
1637}
1638
1639void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001640 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001641 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001642 Mutex::Autolock lock(mLocalSyncPointMutex);
1643 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001644 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001645 point->setFrameAvailable();
1646 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001647 }
1648}
1649
Mathias Agopian13127d82013-03-05 17:47:11 -08001650uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001651 ATRACE_CALL();
1652
Dan Stoza7dde5992015-05-22 09:51:44 -07001653 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001654 Layer::State c = getCurrentState();
1655 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001656 return 0;
1657 }
1658
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001659 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001660
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001661 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1662 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001663
1664 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001665 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001666 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001667 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001668 " current={ 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"
Mathias Agopian419e1962012-05-23 14:34:07 -07001670 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001671 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001672 this, getName().string(), mCurrentTransform,
1673 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001674 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001675 c.crop.left,
1676 c.crop.top,
1677 c.crop.right,
1678 c.crop.bottom,
1679 c.crop.getWidth(),
1680 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001681 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001682 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001683 s.crop.left,
1684 s.crop.top,
1685 s.crop.right,
1686 s.crop.bottom,
1687 s.crop.getWidth(),
1688 s.crop.getHeight(),
1689 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001690
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001691 // record the new size, form this point on, when the client request
1692 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001693 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001694 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001695 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001696
Robert Carre392b552017-09-19 12:16:05 -07001697 // Don't let Layer::doTransaction update the drawing state
1698 // if we have a pending resize, unless we are in fixed-size mode.
1699 // the drawing state will be updated only once we receive a buffer
1700 // with the correct size.
1701 //
1702 // In particular, we want to make sure the clip (which is part
1703 // of the geometry state) is latched together with the size but is
1704 // latched immediately when no resizing is involved.
1705 //
1706 // If a sideband stream is attached, however, we want to skip this
1707 // optimization so that transactions aren't missed when a buffer
1708 // never arrives
1709 //
1710 // In the case that we don't have a buffer we ignore other factors
1711 // and avoid entering the resizePending state. At a high level the
1712 // resizePending state is to avoid applying the state of the new buffer
1713 // to the old buffer. However in the state where we don't have an old buffer
1714 // there is no such concern but we may still be being used as a parent layer.
1715 const bool resizePending = ((c.requested.w != c.active.w) ||
1716 (c.requested.h != c.active.h)) && (mActiveBuffer != nullptr);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001717 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001718 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001719 flags |= eDontUpdateGeometryState;
1720 }
1721 }
1722
Robert Carr7bf247e2017-05-18 14:02:49 -07001723 // Here we apply various requested geometry states, depending on our
1724 // latching configuration. See Layer.h for a detailed discussion of
1725 // how geometry latching is controlled.
1726 if (!(flags & eDontUpdateGeometryState)) {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001727 Layer::State& editCurrentState(getCurrentState());
Robert Carr7bf247e2017-05-18 14:02:49 -07001728
1729 // If mFreezeGeometryUpdates is true we are in the setGeometryAppliesWithResize
1730 // mode, which causes attributes which normally latch regardless of scaling mode,
1731 // to be delayed. We copy the requested state to the active state making sure
1732 // to respect these rules (again see Layer.h for a detailed discussion).
1733 //
1734 // There is an awkward asymmetry in the handling of the crop states in the position
1735 // states, as can be seen below. Largely this arises from position and transform
1736 // being stored in the same data structure while having different latching rules.
1737 // b/38182305
1738 //
1739 // Careful that "c" and editCurrentState may not begin as equivalent due to
1740 // applyPendingStates in the presence of deferred transactions.
1741 if (mFreezeGeometryUpdates) {
Robert Carr82364e32016-05-15 11:27:47 -07001742 float tx = c.active.transform.tx();
1743 float ty = c.active.transform.ty();
1744 c.active = c.requested;
1745 c.active.transform.set(tx, ty);
1746 editCurrentState.active = c.active;
1747 } else {
1748 editCurrentState.active = editCurrentState.requested;
1749 c.active = c.requested;
1750 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001751 }
1752
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001753 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001754 // invalidate and recompute the visible regions if needed
1755 flags |= Layer::eVisibleRegion;
1756 }
1757
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001758 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001759 // invalidate and recompute the visible regions if needed
1760 flags |= eVisibleRegion;
1761 this->contentDirty = true;
1762
1763 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001764 const uint8_t type = c.active.transform.getType();
1765 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001766 (type >= Transform::SCALE));
1767 }
1768
Dan Stozac8145172016-04-28 16:29:06 -07001769 // If the layer is hidden, signal and clear out all local sync points so
1770 // that transactions for layers depending on this layer's frames becoming
1771 // visible are not blocked
1772 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001773 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001774 }
1775
Mathias Agopian13127d82013-03-05 17:47:11 -08001776 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001777 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001778 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001779}
1780
Pablo Ceballos05289c22016-04-14 15:49:55 -07001781void Layer::commitTransaction(const State& stateToCommit) {
1782 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001783}
1784
Mathias Agopian13127d82013-03-05 17:47:11 -08001785uint32_t Layer::getTransactionFlags(uint32_t flags) {
1786 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1787}
1788
1789uint32_t Layer::setTransactionFlags(uint32_t flags) {
1790 return android_atomic_or(flags, &mTransactionFlags);
1791}
1792
Robert Carr82364e32016-05-15 11:27:47 -07001793bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001794 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001795 return false;
1796 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001797
1798 // We update the requested and active position simultaneously because
1799 // we want to apply the position portion of the transform matrix immediately,
1800 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001801 mCurrentState.requested.transform.set(x, y);
Robert Carr7bf247e2017-05-18 14:02:49 -07001802 if (immediate && !mFreezeGeometryUpdates) {
1803 // Here we directly update the active state
1804 // unlike other setters, because we store it within
1805 // the transform, but use different latching rules.
1806 // b/38182305
Robert Carr82364e32016-05-15 11:27:47 -07001807 mCurrentState.active.transform.set(x, y);
1808 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001809 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001810
Dan Stoza7dde5992015-05-22 09:51:44 -07001811 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001812 setTransactionFlags(eTransactionNeeded);
1813 return true;
1814}
Robert Carr82364e32016-05-15 11:27:47 -07001815
Robert Carr1f0a16a2016-10-24 16:27:39 -07001816bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1817 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1818 if (idx < 0) {
1819 return false;
1820 }
1821 if (childLayer->setLayer(z)) {
1822 mCurrentChildren.removeAt(idx);
1823 mCurrentChildren.add(childLayer);
1824 }
1825 return true;
1826}
1827
Robert Carrae060832016-11-28 10:51:00 -08001828bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001829 if (mCurrentState.z == z)
1830 return false;
1831 mCurrentState.sequence++;
1832 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001833 mCurrentState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001834
1835 // Discard all relative layering.
1836 if (mCurrentState.zOrderRelativeOf != nullptr) {
1837 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1838 if (strongRelative != nullptr) {
1839 strongRelative->removeZOrderRelative(this);
1840 }
1841 mCurrentState.zOrderRelativeOf = nullptr;
1842 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001843 setTransactionFlags(eTransactionNeeded);
1844 return true;
1845}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001846
Robert Carrdb66e622017-04-10 16:55:57 -07001847void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1848 mCurrentState.zOrderRelatives.remove(relative);
1849 mCurrentState.sequence++;
1850 mCurrentState.modified = true;
1851 setTransactionFlags(eTransactionNeeded);
1852}
1853
1854void Layer::addZOrderRelative(const wp<Layer>& relative) {
1855 mCurrentState.zOrderRelatives.add(relative);
1856 mCurrentState.modified = true;
1857 mCurrentState.sequence++;
1858 setTransactionFlags(eTransactionNeeded);
1859}
1860
1861bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1862 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1863 if (handle == nullptr) {
1864 return false;
1865 }
1866 sp<Layer> relative = handle->owner.promote();
1867 if (relative == nullptr) {
1868 return false;
1869 }
1870
1871 mCurrentState.sequence++;
1872 mCurrentState.modified = true;
1873 mCurrentState.z = z;
1874
1875 mCurrentState.zOrderRelativeOf = relative;
1876 relative->addZOrderRelative(this);
1877
1878 setTransactionFlags(eTransactionNeeded);
1879
1880 return true;
1881}
1882
Mathias Agopian13127d82013-03-05 17:47:11 -08001883bool Layer::setSize(uint32_t w, uint32_t h) {
1884 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1885 return false;
1886 mCurrentState.requested.w = w;
1887 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001888 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001889 setTransactionFlags(eTransactionNeeded);
1890 return true;
1891}
Dan Stoza9e56aa02015-11-02 13:00:03 -08001892bool Layer::setAlpha(float alpha) {
chaviw13fdc492017-06-27 12:40:18 -07001893 if (mCurrentState.color.a == alpha)
Mathias Agopian13127d82013-03-05 17:47:11 -08001894 return false;
1895 mCurrentState.sequence++;
chaviw13fdc492017-06-27 12:40:18 -07001896 mCurrentState.color.a = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001897 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001898 setTransactionFlags(eTransactionNeeded);
1899 return true;
1900}
chaviw13fdc492017-06-27 12:40:18 -07001901
1902bool Layer::setColor(const half3& color) {
1903 if (color.r == mCurrentState.color.r && color.g == mCurrentState.color.g
1904 && color.b == mCurrentState.color.b)
1905 return false;
1906
1907 mCurrentState.sequence++;
1908 mCurrentState.color.r = color.r;
1909 mCurrentState.color.g = color.g;
1910 mCurrentState.color.b = color.b;
1911 mCurrentState.modified = true;
1912 setTransactionFlags(eTransactionNeeded);
1913 return true;
1914}
1915
Mathias Agopian13127d82013-03-05 17:47:11 -08001916bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1917 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001918 mCurrentState.requested.transform.set(
Robert Carrcb6e1e32017-02-21 19:48:26 -08001919 matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001920 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001921 setTransactionFlags(eTransactionNeeded);
1922 return true;
1923}
1924bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001925 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001926 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001927 setTransactionFlags(eTransactionNeeded);
1928 return true;
1929}
1930bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1931 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1932 if (mCurrentState.flags == newFlags)
1933 return false;
1934 mCurrentState.sequence++;
1935 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001936 mCurrentState.mask = mask;
1937 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001938 setTransactionFlags(eTransactionNeeded);
1939 return true;
1940}
Robert Carr99e27f02016-06-16 15:18:02 -07001941
1942bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001943 if (mCurrentState.requestedCrop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001944 return false;
1945 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001946 mCurrentState.requestedCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001947 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr99e27f02016-06-16 15:18:02 -07001948 mCurrentState.crop = crop;
1949 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001950 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1951
Dan Stoza7dde5992015-05-22 09:51:44 -07001952 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001953 setTransactionFlags(eTransactionNeeded);
1954 return true;
1955}
Robert Carr8d5227b2017-03-16 15:41:03 -07001956
1957bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001958 if (mCurrentState.requestedFinalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001959 return false;
1960 mCurrentState.sequence++;
Robert Carr8d5227b2017-03-16 15:41:03 -07001961 mCurrentState.requestedFinalCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001962 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr8d5227b2017-03-16 15:41:03 -07001963 mCurrentState.finalCrop = crop;
1964 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001965 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1966
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001967 mCurrentState.modified = true;
1968 setTransactionFlags(eTransactionNeeded);
1969 return true;
1970}
Mathias Agopian13127d82013-03-05 17:47:11 -08001971
Robert Carrc3574f72016-03-24 12:19:32 -07001972bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1973 if (scalingMode == mOverrideScalingMode)
1974 return false;
1975 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001976 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001977 return true;
1978}
1979
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001980void Layer::setInfo(uint32_t type, uint32_t appId) {
1981 mCurrentState.appId = appId;
1982 mCurrentState.type = type;
1983 mCurrentState.modified = true;
1984 setTransactionFlags(eTransactionNeeded);
1985}
1986
Robert Carrc3574f72016-03-24 12:19:32 -07001987uint32_t Layer::getEffectiveScalingMode() const {
1988 if (mOverrideScalingMode >= 0) {
1989 return mOverrideScalingMode;
1990 }
1991 return mCurrentScalingMode;
1992}
1993
Mathias Agopian13127d82013-03-05 17:47:11 -08001994bool Layer::setLayerStack(uint32_t layerStack) {
1995 if (mCurrentState.layerStack == layerStack)
1996 return false;
1997 mCurrentState.sequence++;
1998 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001999 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08002000 setTransactionFlags(eTransactionNeeded);
2001 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002002}
2003
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002004bool Layer::setDataSpace(android_dataspace dataSpace) {
2005 if (mCurrentState.dataSpace == dataSpace)
2006 return false;
2007 mCurrentState.sequence++;
2008 mCurrentState.dataSpace = dataSpace;
2009 mCurrentState.modified = true;
2010 setTransactionFlags(eTransactionNeeded);
2011 return true;
2012}
2013
Courtney Goeltzenleuchter532b2632017-05-05 16:34:38 -06002014android_dataspace Layer::getDataSpace() const {
2015 return mCurrentState.dataSpace;
2016}
2017
Robert Carr1f0a16a2016-10-24 16:27:39 -07002018uint32_t Layer::getLayerStack() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002019 auto p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002020 if (p == nullptr) {
2021 return getDrawingState().layerStack;
2022 }
2023 return p->getLayerStack();
2024}
2025
Robert Carr0d480722017-01-10 16:42:54 -08002026void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
Dan Stoza7dde5992015-05-22 09:51:44 -07002027 uint64_t frameNumber) {
Robert Carr0d480722017-01-10 16:42:54 -08002028 mCurrentState.barrierLayer = barrierLayer;
Dan Stoza7dde5992015-05-22 09:51:44 -07002029 mCurrentState.frameNumber = frameNumber;
2030 // We don't set eTransactionNeeded, because just receiving a deferral
2031 // request without any other state updates shouldn't actually induce a delay
2032 mCurrentState.modified = true;
2033 pushPendingState();
Robert Carr0d480722017-01-10 16:42:54 -08002034 mCurrentState.barrierLayer = nullptr;
Dan Stoza792e5292016-02-11 11:43:58 -08002035 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07002036 mCurrentState.modified = false;
Robert Carr0d480722017-01-10 16:42:54 -08002037}
2038
2039void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
2040 uint64_t frameNumber) {
2041 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
2042 deferTransactionUntil(handle->owner.promote(), frameNumber);
Dan Stoza7dde5992015-05-22 09:51:44 -07002043}
2044
Dan Stozaee44edd2015-03-23 15:50:23 -07002045void Layer::useSurfaceDamage() {
2046 if (mFlinger->mForceFullDamage) {
2047 surfaceDamageRegion = Region::INVALID_REGION;
2048 } else {
2049 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
2050 }
2051}
2052
2053void Layer::useEmptyDamage() {
2054 surfaceDamageRegion.clear();
2055}
2056
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002057// ----------------------------------------------------------------------------
2058// pageflip handling...
2059// ----------------------------------------------------------------------------
2060
Dan Stoza6b9454d2014-11-07 16:00:59 -08002061bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08002062 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07002063 return true;
2064 }
2065
Dan Stoza6b9454d2014-11-07 16:00:59 -08002066 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07002067 if (mQueueItems.empty()) {
2068 return false;
2069 }
2070 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002071 nsecs_t expectedPresent =
2072 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07002073
2074 // Ignore timestamps more than a second in the future
2075 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
2076 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
2077 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
2078 expectedPresent);
2079
2080 bool isDue = timestamp < expectedPresent;
2081 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002082}
2083
Brian Andersond6927fb2016-07-23 23:37:30 -07002084bool Layer::onPreComposition(nsecs_t refreshStartTime) {
2085 if (mBufferLatched) {
2086 Mutex::Autolock lock(mFrameEventHistoryMutex);
2087 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
2088 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08002089 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08002090 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002091}
2092
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002093bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
Brian Anderson3d4039d2016-09-23 16:31:30 -07002094 const std::shared_ptr<FenceTime>& presentFence,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002095 const CompositorTiming& compositorTiming) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002096 // mFrameLatencyNeeded is true when a new frame was latched for the
2097 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08002098 if (!mFrameLatencyNeeded)
2099 return false;
2100
Fabien Sanglard28e98082016-12-05 10:19:46 -08002101 // Update mFrameEventHistory.
2102 {
2103 Mutex::Autolock lock(mFrameEventHistoryMutex);
2104 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002105 glDoneFence, presentFence, compositorTiming);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002106 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08002107
2108 // Update mFrameTracker.
2109 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
2110 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
2111
Brian Anderson3d4039d2016-09-23 16:31:30 -07002112 std::shared_ptr<FenceTime> frameReadyFence =
2113 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08002114 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002115 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002116 } else {
2117 // There was no fence for this frame, so assume that it was ready
2118 // to be presented at the desired present time.
2119 mFrameTracker.setFrameReadyTime(desiredPresentTime);
2120 }
2121
Brian Anderson3d4039d2016-09-23 16:31:30 -07002122 if (presentFence->isValid()) {
2123 mFrameTracker.setActualPresentFence(
2124 std::shared_ptr<FenceTime>(presentFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002125 } else {
2126 // The HWC doesn't support present fences, so use the refresh
2127 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002128 mFrameTracker.setActualPresentTime(
2129 mFlinger->getHwComposer().getRefreshTimestamp(
2130 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002131 }
2132
2133 mFrameTracker.advanceFrame();
2134 mFrameLatencyNeeded = false;
2135 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002136}
2137
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002138#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07002139void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Brian Anderson5ea5e592016-12-01 16:54:33 -08002140 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2141 return;
2142 }
2143
Brian Anderson3d4039d2016-09-23 16:31:30 -07002144 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002145 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002146 mReleaseTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002147 mReleaseTimeline.push(releaseFenceTime);
2148
2149 Mutex::Autolock lock(mFrameEventHistoryMutex);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002150 if (mPreviousFrameNumber != 0) {
2151 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2152 dequeueReadyTime, std::move(releaseFenceTime));
2153 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002154}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002155#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002156
Robert Carr1f0a16a2016-10-24 16:27:39 -07002157bool Layer::isHiddenByPolicy() const {
2158 const Layer::State& s(mDrawingState);
Chia-I Wue41dbe62017-06-13 14:10:56 -07002159 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002160 if (parent != nullptr && parent->isHiddenByPolicy()) {
2161 return true;
2162 }
2163 return s.flags & layer_state_t::eLayerHidden;
2164}
2165
Mathias Agopianda27af92012-09-13 18:17:13 -07002166bool Layer::isVisible() const {
Robert Carr6452f122017-03-21 10:41:29 -07002167 return !(isHiddenByPolicy()) && getAlpha() > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08002168 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Mathias Agopianda27af92012-09-13 18:17:13 -07002169}
2170
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002171bool Layer::allTransactionsSignaled() {
2172 auto headFrameNumber = getHeadFrameNumber();
2173 bool matchingFramesFound = false;
2174 bool allTransactionsApplied = true;
2175 Mutex::Autolock lock(mLocalSyncPointMutex);
2176
2177 for (auto& point : mLocalSyncPoints) {
2178 if (point->getFrameNumber() > headFrameNumber) {
2179 break;
2180 }
2181 matchingFramesFound = true;
2182
2183 if (!point->frameIsAvailable()) {
2184 // We haven't notified the remote layer that the frame for
2185 // this point is available yet. Notify it now, and then
2186 // abort this attempt to latch.
2187 point->setFrameAvailable();
2188 allTransactionsApplied = false;
2189 break;
2190 }
2191
2192 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2193 }
2194 return !matchingFramesFound || allTransactionsApplied;
2195}
2196
Brian Andersond6927fb2016-07-23 23:37:30 -07002197Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002198{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08002199 ATRACE_CALL();
2200
Jesse Hall399184a2014-03-03 15:42:54 -08002201 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2202 // mSidebandStreamChanged was true
2203 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07002204 if (mSidebandStream != NULL) {
2205 setTransactionFlags(eTransactionNeeded);
2206 mFlinger->setTransactionFlags(eTraversalNeeded);
2207 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07002208 recomputeVisibleRegions = true;
2209
2210 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07002211 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08002212 }
2213
Mathias Agopian4fec8732012-06-29 14:12:52 -07002214 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07002215 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2216 return outDirtyRegion;
2217 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002218
Fabien Sanglard223eb912016-10-13 10:15:06 -07002219 // if we've already called updateTexImage() without going through
2220 // a composition step, we have to skip this layer at this point
2221 // because we cannot call updateTeximage() without a corresponding
2222 // compositionComplete() call.
2223 // we'll trigger an update in onPreComposition().
2224 if (mRefreshPending) {
2225 return outDirtyRegion;
2226 }
2227
2228 // If the head buffer's acquire fence hasn't signaled yet, return and
2229 // try again later
2230 if (!headFenceHasSignaled()) {
2231 mFlinger->signalLayerUpdate();
2232 return outDirtyRegion;
2233 }
2234
2235 // Capture the old state of the layer for comparisons later
2236 const State& s(getDrawingState());
2237 const bool oldOpacity = isOpaque(s);
2238 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2239
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002240 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002241 mFlinger->signalLayerUpdate();
2242 return outDirtyRegion;
2243 }
2244
2245 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2246 // of the buffer queue isn't modified when the buffer queue is returning
2247 // BufferItem's that weren't actually queued. This can happen in shared
2248 // buffer mode.
2249 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002250 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2251 getProducerStickyTransform() != 0, mName.string(),
Robert Carr7bf247e2017-05-18 14:02:49 -07002252 mOverrideScalingMode, mFreezeGeometryUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002253 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2254 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2255 mLastFrameNumberReceived);
2256 if (updateResult == BufferQueue::PRESENT_LATER) {
2257 // Producer doesn't want buffer to be displayed yet. Signal a
2258 // layer update so we check again at the next opportunity.
2259 mFlinger->signalLayerUpdate();
2260 return outDirtyRegion;
2261 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2262 // If the buffer has been rejected, remove it from the shadow queue
2263 // and return early
2264 if (queuedBuffer) {
2265 Mutex::Autolock lock(mQueueItemLock);
2266 mQueueItems.removeAt(0);
2267 android_atomic_dec(&mQueuedFrames);
2268 }
2269 return outDirtyRegion;
2270 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2271 // This can occur if something goes wrong when trying to create the
2272 // EGLImage for this buffer. If this happens, the buffer has already
2273 // been released, so we need to clean up the queue and bug out
2274 // early.
2275 if (queuedBuffer) {
2276 Mutex::Autolock lock(mQueueItemLock);
2277 mQueueItems.clear();
2278 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002279 }
2280
Fabien Sanglard223eb912016-10-13 10:15:06 -07002281 // Once we have hit this state, the shadow queue may no longer
2282 // correctly reflect the incoming BufferQueue's contents, so even if
2283 // updateTexImage starts working, the only safe course of action is
2284 // to continue to ignore updates.
2285 mUpdateTexImageFailed = true;
2286
2287 return outDirtyRegion;
2288 }
2289
2290 if (queuedBuffer) {
2291 // Autolock scope
2292 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2293
2294 Mutex::Autolock lock(mQueueItemLock);
2295
2296 // Remove any stale buffers that have been dropped during
2297 // updateTexImage
2298 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2299 mQueueItems.removeAt(0);
2300 android_atomic_dec(&mQueuedFrames);
2301 }
2302
2303 mQueueItems.removeAt(0);
2304 }
2305
2306
2307 // Decrement the queued-frames count. Signal another event if we
2308 // have more frames pending.
2309 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2310 || mAutoRefresh) {
2311 mFlinger->signalLayerUpdate();
2312 }
2313
Fabien Sanglard223eb912016-10-13 10:15:06 -07002314 // update the active buffer
Chia-I Wu06d63de2017-01-04 14:58:51 +08002315 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2316 &mActiveBufferSlot);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002317 if (mActiveBuffer == NULL) {
2318 // this can only happen if the very first buffer was rejected.
2319 return outDirtyRegion;
2320 }
2321
Brian Andersond6927fb2016-07-23 23:37:30 -07002322 mBufferLatched = true;
2323 mPreviousFrameNumber = mCurrentFrameNumber;
2324 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2325
2326 {
2327 Mutex::Autolock lock(mFrameEventHistoryMutex);
2328 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2329#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002330 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002331 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002332 mReleaseTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002333 mReleaseTimeline.push(releaseFenceTime);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002334 if (mPreviousFrameNumber != 0) {
2335 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2336 latchTime, std::move(releaseFenceTime));
2337 }
Brian Andersond6927fb2016-07-23 23:37:30 -07002338#endif
2339 }
2340
Fabien Sanglard223eb912016-10-13 10:15:06 -07002341 mRefreshPending = true;
2342 mFrameLatencyNeeded = true;
2343 if (oldActiveBuffer == NULL) {
2344 // the first time we receive a buffer, we need to trigger a
2345 // geometry invalidation.
2346 recomputeVisibleRegions = true;
2347 }
2348
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002349 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2350
Fabien Sanglard223eb912016-10-13 10:15:06 -07002351 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2352 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2353 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2354 if ((crop != mCurrentCrop) ||
2355 (transform != mCurrentTransform) ||
2356 (scalingMode != mCurrentScalingMode))
2357 {
2358 mCurrentCrop = crop;
2359 mCurrentTransform = transform;
2360 mCurrentScalingMode = scalingMode;
2361 recomputeVisibleRegions = true;
2362 }
2363
2364 if (oldActiveBuffer != NULL) {
2365 uint32_t bufWidth = mActiveBuffer->getWidth();
2366 uint32_t bufHeight = mActiveBuffer->getHeight();
2367 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2368 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002369 recomputeVisibleRegions = true;
2370 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002371 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002372
Fabien Sanglard223eb912016-10-13 10:15:06 -07002373 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2374 if (oldOpacity != isOpaque(s)) {
2375 recomputeVisibleRegions = true;
2376 }
Dan Stozacac35382016-01-27 12:21:06 -08002377
Fabien Sanglard223eb912016-10-13 10:15:06 -07002378 // Remove any sync points corresponding to the buffer which was just
2379 // latched
2380 {
2381 Mutex::Autolock lock(mLocalSyncPointMutex);
2382 auto point = mLocalSyncPoints.begin();
2383 while (point != mLocalSyncPoints.end()) {
2384 if (!(*point)->frameIsAvailable() ||
2385 !(*point)->transactionIsApplied()) {
2386 // This sync point must have been added since we started
2387 // latching. Don't drop it yet.
2388 ++point;
2389 continue;
2390 }
2391
2392 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2393 point = mLocalSyncPoints.erase(point);
2394 } else {
2395 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002396 }
2397 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002398 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002399
2400 // FIXME: postedRegion should be dirty & bounds
2401 Region dirtyRegion(Rect(s.active.w, s.active.h));
2402
2403 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002404 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002405
Mathias Agopian4fec8732012-06-29 14:12:52 -07002406 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002407}
2408
Mathias Agopiana67932f2011-04-20 14:20:59 -07002409uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002410{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002411 // TODO: should we do something special if mSecure is set?
2412 if (mProtectedByApp) {
2413 // need a hardware-protected path to external video sink
2414 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002415 }
Riley Andrews03414a12014-07-01 14:22:59 -07002416 if (mPotentialCursor) {
2417 usage |= GraphicBuffer::USAGE_CURSOR;
2418 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002419 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002420 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002421}
2422
Mathias Agopian84300952012-11-21 16:02:13 -08002423void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002424 uint32_t orientation = 0;
2425 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002426 // The transform hint is used to improve performance, but we can
2427 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002428 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002429 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002430 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002431 if (orientation & Transform::ROT_INVALID) {
2432 orientation = 0;
2433 }
2434 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002435 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002436}
2437
Mathias Agopian13127d82013-03-05 17:47:11 -08002438// ----------------------------------------------------------------------------
2439// debugging
2440// ----------------------------------------------------------------------------
2441
Kalle Raitaa099a242017-01-11 11:17:29 -08002442LayerDebugInfo Layer::getLayerDebugInfo() const {
2443 LayerDebugInfo info;
2444 const Layer::State& ds = getDrawingState();
2445 info.mName = getName();
chaviw1acbec72017-07-27 15:28:26 -07002446 sp<Layer> parent = getParent();
Kalle Raitaa099a242017-01-11 11:17:29 -08002447 info.mParentName = (parent == nullptr ? std::string("none") : parent->getName().string());
2448 info.mType = String8(getTypeId());
2449 info.mTransparentRegion = ds.activeTransparentRegion;
2450 info.mVisibleRegion = visibleRegion;
2451 info.mSurfaceDamageRegion = surfaceDamageRegion;
2452 info.mLayerStack = getLayerStack();
2453 info.mX = ds.active.transform.tx();
2454 info.mY = ds.active.transform.ty();
2455 info.mZ = ds.z;
2456 info.mWidth = ds.active.w;
2457 info.mHeight = ds.active.h;
2458 info.mCrop = ds.crop;
2459 info.mFinalCrop = ds.finalCrop;
chaviw13fdc492017-06-27 12:40:18 -07002460 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08002461 info.mFlags = ds.flags;
2462 info.mPixelFormat = getPixelFormat();
2463 info.mDataSpace = getDataSpace();
2464 info.mMatrix[0][0] = ds.active.transform[0][0];
2465 info.mMatrix[0][1] = ds.active.transform[0][1];
2466 info.mMatrix[1][0] = ds.active.transform[1][0];
2467 info.mMatrix[1][1] = ds.active.transform[1][1];
2468 {
2469 sp<const GraphicBuffer> activeBuffer = getActiveBuffer();
2470 if (activeBuffer != 0) {
2471 info.mActiveBufferWidth = activeBuffer->getWidth();
2472 info.mActiveBufferHeight = activeBuffer->getHeight();
2473 info.mActiveBufferStride = activeBuffer->getStride();
2474 info.mActiveBufferFormat = activeBuffer->format;
2475 } else {
2476 info.mActiveBufferWidth = 0;
2477 info.mActiveBufferHeight = 0;
2478 info.mActiveBufferStride = 0;
2479 info.mActiveBufferFormat = 0;
2480 }
Mathias Agopian13127d82013-03-05 17:47:11 -08002481 }
Kalle Raitaa099a242017-01-11 11:17:29 -08002482 info.mNumQueuedFrames = getQueuedFrameCount();
2483 info.mRefreshPending = isBufferLatched();
2484 info.mIsOpaque = isOpaque(ds);
2485 info.mContentDirty = contentDirty;
2486 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08002487}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002488#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002489void Layer::miniDumpHeader(String8& result) {
2490 result.append("----------------------------------------");
2491 result.append("---------------------------------------\n");
2492 result.append(" Layer name\n");
2493 result.append(" Z | ");
2494 result.append(" Comp Type | ");
2495 result.append(" Disp Frame (LTRB) | ");
2496 result.append(" Source Crop (LTRB)\n");
2497 result.append("----------------------------------------");
2498 result.append("---------------------------------------\n");
2499}
2500
2501void Layer::miniDump(String8& result, int32_t hwcId) const {
2502 if (mHwcLayers.count(hwcId) == 0) {
2503 return;
2504 }
2505
2506 String8 name;
2507 if (mName.length() > 77) {
2508 std::string shortened;
2509 shortened.append(mName.string(), 36);
2510 shortened.append("[...]");
2511 shortened.append(mName.string() + (mName.length() - 36), 36);
2512 name = shortened.c_str();
2513 } else {
2514 name = mName;
2515 }
2516
2517 result.appendFormat(" %s\n", name.string());
2518
2519 const Layer::State& layerState(getDrawingState());
2520 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
John Reck8c3b6ac2017-08-24 10:25:42 -07002521 result.appendFormat(" %10d | ", layerState.z);
Dan Stozae22aec72016-08-01 13:20:59 -07002522 result.appendFormat("%10s | ",
2523 to_string(getCompositionType(hwcId)).c_str());
2524 const Rect& frame = hwcInfo.displayFrame;
2525 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2526 frame.right, frame.bottom);
Dan Stoza5a423ea2017-02-16 14:10:39 -08002527 const FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002528 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2529 crop.right, crop.bottom);
2530
2531 result.append("- - - - - - - - - - - - - - - - - - - - ");
2532 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2533}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002534#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002535
Svetoslavd85084b2014-03-20 10:28:31 -07002536void Layer::dumpFrameStats(String8& result) const {
2537 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002538}
2539
Svetoslavd85084b2014-03-20 10:28:31 -07002540void Layer::clearFrameStats() {
2541 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002542}
2543
Jamie Gennis6547ff42013-07-16 20:12:42 -07002544void Layer::logFrameStats() {
2545 mFrameTracker.logAndResetStats(mName);
2546}
2547
Svetoslavd85084b2014-03-20 10:28:31 -07002548void Layer::getFrameStats(FrameStats* outStats) const {
2549 mFrameTracker.getStats(outStats);
2550}
2551
Brian Andersond6927fb2016-07-23 23:37:30 -07002552void Layer::dumpFrameEvents(String8& result) {
2553 result.appendFormat("- Layer %s (%s, %p)\n",
2554 getName().string(), getTypeId(), this);
2555 Mutex::Autolock lock(mFrameEventHistoryMutex);
2556 mFrameEventHistory.checkFencesForCompletion();
2557 mFrameEventHistory.dump(result);
2558}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002559
Brian Anderson5ea5e592016-12-01 16:54:33 -08002560void Layer::onDisconnect() {
2561 Mutex::Autolock lock(mFrameEventHistoryMutex);
2562 mFrameEventHistory.onDisconnect();
2563}
2564
Brian Anderson3890c392016-07-25 12:48:08 -07002565void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2566 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002567 Mutex::Autolock lock(mFrameEventHistoryMutex);
2568 if (newTimestamps) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002569 // If there are any unsignaled fences in the aquire timeline at this
2570 // point, the previously queued frame hasn't been latched yet. Go ahead
2571 // and try to get the signal time here so the syscall is taken out of
2572 // the main thread's critical path.
2573 mAcquireTimeline.updateSignalTimes();
2574 // Push the new fence after updating since it's likely still pending.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002575 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002576 mFrameEventHistory.addQueue(*newTimestamps);
2577 }
2578
Brian Anderson3890c392016-07-25 12:48:08 -07002579 if (outDelta) {
2580 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002581 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002582}
Dan Stozae77c7662016-05-13 11:37:28 -07002583
2584std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2585 bool forceFlush) {
2586 std::vector<OccupancyTracker::Segment> history;
2587 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2588 &history);
2589 if (result != NO_ERROR) {
2590 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2591 result);
2592 return {};
2593 }
2594 return history;
2595}
2596
Robert Carr367c5682016-06-20 11:55:28 -07002597bool Layer::getTransformToDisplayInverse() const {
2598 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2599}
2600
Chia-I Wu98f1c102017-05-30 14:54:08 -07002601size_t Layer::getChildrenCount() const {
2602 size_t count = 0;
2603 for (const sp<Layer>& child : mCurrentChildren) {
2604 count += 1 + child->getChildrenCount();
2605 }
2606 return count;
2607}
2608
Robert Carr1f0a16a2016-10-24 16:27:39 -07002609void Layer::addChild(const sp<Layer>& layer) {
2610 mCurrentChildren.add(layer);
2611 layer->setParent(this);
2612}
2613
2614ssize_t Layer::removeChild(const sp<Layer>& layer) {
2615 layer->setParent(nullptr);
2616 return mCurrentChildren.remove(layer);
2617}
2618
Robert Carr1db73f62016-12-21 12:58:51 -08002619bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2620 sp<Handle> handle = nullptr;
2621 sp<Layer> newParent = nullptr;
2622 if (newParentHandle == nullptr) {
2623 return false;
2624 }
2625 handle = static_cast<Handle*>(newParentHandle.get());
2626 newParent = handle->owner.promote();
2627 if (newParent == nullptr) {
2628 ALOGE("Unable to promote Layer handle");
2629 return false;
2630 }
2631
2632 for (const sp<Layer>& child : mCurrentChildren) {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002633 newParent->addChild(child);
Robert Carr1db73f62016-12-21 12:58:51 -08002634
2635 sp<Client> client(child->mClientRef.promote());
2636 if (client != nullptr) {
2637 client->setParentLayer(newParent);
2638 }
2639 }
2640 mCurrentChildren.clear();
2641
2642 return true;
2643}
2644
chaviwf1961f72017-09-18 16:41:07 -07002645bool Layer::reparent(const sp<IBinder>& newParentHandle) {
2646 if (newParentHandle == nullptr) {
chaviw06178942017-07-27 10:25:59 -07002647 return false;
2648 }
2649
2650 auto handle = static_cast<Handle*>(newParentHandle.get());
2651 sp<Layer> newParent = handle->owner.promote();
2652 if (newParent == nullptr) {
2653 ALOGE("Unable to promote Layer handle");
2654 return false;
2655 }
2656
chaviwf1961f72017-09-18 16:41:07 -07002657 sp<Layer> parent = getParent();
2658 if (parent != nullptr) {
2659 parent->removeChild(this);
chaviw06178942017-07-27 10:25:59 -07002660 }
chaviwf1961f72017-09-18 16:41:07 -07002661 newParent->addChild(this);
chaviw06178942017-07-27 10:25:59 -07002662
chaviwf1961f72017-09-18 16:41:07 -07002663 sp<Client> client(mClientRef.promote());
chaviw06178942017-07-27 10:25:59 -07002664 sp<Client> newParentClient(newParent->mClientRef.promote());
2665
chaviwf1961f72017-09-18 16:41:07 -07002666 if (client != newParentClient) {
2667 client->setParentLayer(newParent);
chaviw06178942017-07-27 10:25:59 -07002668 }
2669
chaviw06178942017-07-27 10:25:59 -07002670 return true;
2671}
2672
Robert Carr9524cb32017-02-13 11:32:32 -08002673bool Layer::detachChildren() {
Dan Stoza412903f2017-04-27 13:42:17 -07002674 traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
Robert Carr9524cb32017-02-13 11:32:32 -08002675 if (child == this) {
2676 return;
2677 }
2678
chaviw161410b02017-07-27 10:46:08 -07002679 sp<Client> parentClient = mClientRef.promote();
Robert Carr9524cb32017-02-13 11:32:32 -08002680 sp<Client> client(child->mClientRef.promote());
chaviw161410b02017-07-27 10:46:08 -07002681 if (client != nullptr && parentClient != client) {
Robert Carr9524cb32017-02-13 11:32:32 -08002682 client->detachLayer(child);
2683 }
2684 });
2685
2686 return true;
2687}
2688
Robert Carr1f0a16a2016-10-24 16:27:39 -07002689void Layer::setParent(const sp<Layer>& layer) {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002690 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002691}
2692
2693void Layer::clearSyncPoints() {
2694 for (const auto& child : mCurrentChildren) {
2695 child->clearSyncPoints();
2696 }
2697
2698 Mutex::Autolock lock(mLocalSyncPointMutex);
2699 for (auto& point : mLocalSyncPoints) {
2700 point->setFrameAvailable();
2701 }
2702 mLocalSyncPoints.clear();
2703}
2704
2705int32_t Layer::getZ() const {
2706 return mDrawingState.z;
2707}
2708
Dan Stoza412903f2017-04-27 13:42:17 -07002709LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2710 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2711 "makeTraversalList received invalid stateSet");
2712 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2713 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2714 const State& state = useDrawing ? mDrawingState : mCurrentState;
2715
2716 if (state.zOrderRelatives.size() == 0) {
2717 return children;
Robert Carrdb66e622017-04-10 16:55:57 -07002718 }
2719 LayerVector traverse;
2720
Dan Stoza412903f2017-04-27 13:42:17 -07002721 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07002722 sp<Layer> strongRelative = weakRelative.promote();
2723 if (strongRelative != nullptr) {
2724 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07002725 }
2726 }
2727
Dan Stoza412903f2017-04-27 13:42:17 -07002728 for (const sp<Layer>& child : children) {
Robert Carrdb66e622017-04-10 16:55:57 -07002729 traverse.add(child);
2730 }
2731
2732 return traverse;
2733}
2734
Robert Carr1f0a16a2016-10-24 16:27:39 -07002735/**
Robert Carrdb66e622017-04-10 16:55:57 -07002736 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002737 */
Dan Stoza412903f2017-04-27 13:42:17 -07002738void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2739 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002740
Robert Carr1f0a16a2016-10-24 16:27:39 -07002741 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002742 for (; i < list.size(); i++) {
2743 const auto& relative = list[i];
2744 if (relative->getZ() >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002745 break;
Robert Carrdb66e622017-04-10 16:55:57 -07002746 }
Dan Stoza412903f2017-04-27 13:42:17 -07002747 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002748 }
Dan Stoza412903f2017-04-27 13:42:17 -07002749 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07002750 for (; i < list.size(); i++) {
2751 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002752 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002753 }
2754}
2755
2756/**
Robert Carrdb66e622017-04-10 16:55:57 -07002757 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002758 */
Dan Stoza412903f2017-04-27 13:42:17 -07002759void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2760 const LayerVector::Visitor& visitor) {
2761 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002762
Robert Carr1f0a16a2016-10-24 16:27:39 -07002763 int32_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002764 for (i = list.size()-1; i>=0; i--) {
2765 const auto& relative = list[i];
2766 if (relative->getZ() < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002767 break;
2768 }
Dan Stoza412903f2017-04-27 13:42:17 -07002769 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002770 }
Dan Stoza412903f2017-04-27 13:42:17 -07002771 visitor(this);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002772 for (; i>=0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002773 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002774 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002775 }
2776}
2777
2778Transform Layer::getTransform() const {
2779 Transform t;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002780 const auto& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002781 if (p != nullptr) {
2782 t = p->getTransform();
Robert Carr9b429f42017-04-17 14:56:57 -07002783
2784 // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2785 // it isFixedSize) then there may be additional scaling not accounted
2786 // for in the transform. We need to mirror this scaling in child surfaces
2787 // or we will break the contract where WM can treat child surfaces as
2788 // pixels in the parent surface.
Chia-I Wu0a68b462017-07-18 11:30:05 -07002789 if (p->isFixedSize() && p->mActiveBuffer != nullptr) {
Robert Carr1725eee2017-04-26 18:32:15 -07002790 int bufferWidth;
2791 int bufferHeight;
2792 if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2793 bufferWidth = p->mActiveBuffer->getWidth();
2794 bufferHeight = p->mActiveBuffer->getHeight();
2795 } else {
2796 bufferHeight = p->mActiveBuffer->getWidth();
2797 bufferWidth = p->mActiveBuffer->getHeight();
2798 }
Robert Carr9b429f42017-04-17 14:56:57 -07002799 float sx = p->getDrawingState().active.w /
Robert Carr1725eee2017-04-26 18:32:15 -07002800 static_cast<float>(bufferWidth);
Robert Carr9b429f42017-04-17 14:56:57 -07002801 float sy = p->getDrawingState().active.h /
Robert Carr1725eee2017-04-26 18:32:15 -07002802 static_cast<float>(bufferHeight);
Robert Carr9b429f42017-04-17 14:56:57 -07002803 Transform extraParentScaling;
2804 extraParentScaling.set(sx, 0, 0, sy);
2805 t = t * extraParentScaling;
2806 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002807 }
2808 return t * getDrawingState().active.transform;
2809}
2810
chaviw13fdc492017-06-27 12:40:18 -07002811half Layer::getAlpha() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002812 const auto& p = mDrawingParent.promote();
Robert Carr6452f122017-03-21 10:41:29 -07002813
chaviw13fdc492017-06-27 12:40:18 -07002814 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2815 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002816}
Robert Carr6452f122017-03-21 10:41:29 -07002817
chaviw13fdc492017-06-27 12:40:18 -07002818half4 Layer::getColor() const {
2819 const half4 color(getDrawingState().color);
2820 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002821}
Robert Carr6452f122017-03-21 10:41:29 -07002822
Robert Carr1f0a16a2016-10-24 16:27:39 -07002823void Layer::commitChildList() {
2824 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2825 const auto& child = mCurrentChildren[i];
2826 child->commitChildList();
2827 }
2828 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002829 mDrawingParent = mCurrentParent;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002830}
2831
chaviw1d044282017-09-27 12:19:28 -07002832void Layer::writeToProto(LayerProto* layerInfo, LayerVector::StateSet stateSet) {
2833 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2834 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2835 const State& state = useDrawing ? mDrawingState : mCurrentState;
2836
2837 Transform requestedTransform = state.active.transform;
2838 Transform transform = getTransform();
2839
2840 layerInfo->set_id(sequence);
2841 layerInfo->set_name(getName().c_str());
2842 layerInfo->set_type(String8(getTypeId()));
2843
2844 for (const auto& child : children) {
2845 layerInfo->add_children(child->sequence);
2846 }
2847
2848 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2849 sp<Layer> strongRelative = weakRelative.promote();
2850 if (strongRelative != nullptr) {
2851 layerInfo->add_relatives(strongRelative->sequence);
2852 }
2853 }
2854
2855 LayerProtoHelper::writeToProto(state.activeTransparentRegion,
2856 layerInfo->mutable_transparent_region());
2857 LayerProtoHelper::writeToProto(visibleRegion, layerInfo->mutable_visible_region());
2858 LayerProtoHelper::writeToProto(surfaceDamageRegion, layerInfo->mutable_damage_region());
2859
2860 layerInfo->set_layer_stack(getLayerStack());
2861 layerInfo->set_z(state.z);
2862
2863 PositionProto* position = layerInfo->mutable_position();
2864 position->set_x(transform.tx());
2865 position->set_y(transform.ty());
2866
2867 PositionProto* requestedPosition = layerInfo->mutable_requested_position();
2868 requestedPosition->set_x(requestedTransform.tx());
2869 requestedPosition->set_y(requestedTransform.ty());
2870
2871 SizeProto* size = layerInfo->mutable_size();
2872 size->set_w(state.active.w);
2873 size->set_h(state.active.h);
2874
2875 LayerProtoHelper::writeToProto(state.crop, layerInfo->mutable_crop());
2876 LayerProtoHelper::writeToProto(state.finalCrop, layerInfo->mutable_final_crop());
2877
2878 layerInfo->set_is_opaque(isOpaque(state));
2879 layerInfo->set_invalidate(contentDirty);
2880 layerInfo->set_dataspace(dataspaceDetails(getDataSpace()));
2881 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2882 LayerProtoHelper::writeToProto(getColor(), layerInfo->mutable_color());
2883 LayerProtoHelper::writeToProto(state.color, layerInfo->mutable_requested_color());
2884 layerInfo->set_flags(state.flags);
2885
2886 LayerProtoHelper::writeToProto(transform, layerInfo->mutable_transform());
2887 LayerProtoHelper::writeToProto(requestedTransform, layerInfo->mutable_requested_transform());
2888
2889 auto parent = getParent();
2890 if (parent != nullptr) {
2891 layerInfo->set_parent(parent->sequence);
2892 }
2893
2894 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2895 if (zOrderRelativeOf != nullptr) {
2896 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2897 }
2898
2899 auto activeBuffer = getActiveBuffer();
2900 if (activeBuffer != nullptr) {
2901 LayerProtoHelper::writeToProto(activeBuffer, layerInfo->mutable_active_buffer());
2902 }
2903
2904 layerInfo->set_queued_frames(getQueuedFrameCount());
2905 layerInfo->set_refresh_pending(isBufferLatched());
2906}
2907
Mathias Agopian13127d82013-03-05 17:47:11 -08002908// ---------------------------------------------------------------------------
2909
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002910}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002911
2912#if defined(__gl_h_)
2913#error "don't include gl/gl.h in this file"
2914#endif
2915
2916#if defined(__gl2_h_)
2917#error "don't include gl2/gl2.h in this file"
2918#endif