blob: 8eb406747a03670ee58cb680d62fd8e5d13f7145 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017//#define LOG_NDEBUG 0
18#undef LOG_TAG
19#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080020#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <stdlib.h>
23#include <stdint.h>
24#include <sys/types.h>
Mathias Agopian13127d82013-03-05 17:47:11 -080025#include <math.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080026
Mathias Agopiana67932f2011-04-20 14:20:59 -070027#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070028#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070029#include <cutils/properties.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
31#include <utils/Errors.h>
32#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080033#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080034#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080035#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080036
Courtney Goeltzenleuchter36c44dc2017-04-14 09:33:16 -060037#include <ui/DebugUtils.h>
Mathias Agopian3330b202009-10-05 17:07:12 -070038#include <ui/GraphicBuffer.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080039#include <ui/PixelFormat.h>
Mathias Agopian9cce3252010-02-09 17:46:37 -080040
Dan Stoza6b9454d2014-11-07 16:00:59 -080041#include <gui/BufferItem.h>
Mathias Agopiana9347642017-02-13 16:42:28 -080042#include <gui/BufferQueue.h>
Mathias Agopian90ac7992012-02-25 18:48:35 -080043#include <gui/Surface.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080044
45#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020046#include "Colorizer.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070047#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080048#include "Layer.h"
Fabien Sanglard7b1563a2016-10-13 12:05:28 -070049#include "LayerRejecter.h"
Dan Stozab9b08832014-03-13 11:55:57 -070050#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080051#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080052
Mathias Agopian1b031492012-06-20 17:51:20 -070053#include "DisplayHardware/HWComposer.h"
54
Mathias Agopian875d8e12013-06-07 15:35:48 -070055#include "RenderEngine/RenderEngine.h"
56
Dan Stozac5da2712016-07-20 15:38:12 -070057#include <mutex>
58
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059#define DEBUG_RESIZE 0
60
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061namespace android {
62
63// ---------------------------------------------------------------------------
64
Mathias Agopian13127d82013-03-05 17:47:11 -080065int32_t Layer::sSequence = 1;
66
Mathias Agopian4d9b8222013-03-12 17:11:48 -070067Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
68 const String8& name, uint32_t w, uint32_t h, uint32_t flags)
Mathias Agopian13127d82013-03-05 17:47:11 -080069 : contentDirty(false),
70 sequence(uint32_t(android_atomic_inc(&sSequence))),
71 mFlinger(flinger),
Mathias Agopiana67932f2011-04-20 14:20:59 -070072 mTextureName(-1U),
Mathias Agopian13127d82013-03-05 17:47:11 -080073 mPremultipliedAlpha(true),
74 mName("unnamed"),
Mathias Agopian13127d82013-03-05 17:47:11 -080075 mFormat(PIXEL_FORMAT_NONE),
Mathias Agopian13127d82013-03-05 17:47:11 -080076 mTransactionFlags(0),
Dan Stoza7dde5992015-05-22 09:51:44 -070077 mPendingStateMutex(),
78 mPendingStates(),
Mathias Agopiana67932f2011-04-20 14:20:59 -070079 mQueuedFrames(0),
Jesse Hall399184a2014-03-03 15:42:54 -080080 mSidebandStreamChanged(false),
Mathias Agopiana9347642017-02-13 16:42:28 -080081 mActiveBufferSlot(BufferQueue::INVALID_BUFFER_SLOT),
Mathias Agopiana67932f2011-04-20 14:20:59 -070082 mCurrentTransform(0),
Mathias Agopian933389f2011-07-18 16:15:08 -070083 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
Robert Carrc3574f72016-03-24 12:19:32 -070084 mOverrideScalingMode(-1),
Mathias Agopiana67932f2011-04-20 14:20:59 -070085 mCurrentOpacity(true),
Brian Andersond6927fb2016-07-23 23:37:30 -070086 mBufferLatched(false),
Dan Stozacac35382016-01-27 12:21:06 -080087 mCurrentFrameNumber(0),
Brian Anderson8cc8b102016-10-21 12:43:09 -070088 mPreviousFrameNumber(0),
Mathias Agopian4d143ee2012-02-23 20:05:39 -080089 mRefreshPending(false),
Mathias Agopian82d7ab62012-01-19 18:34:40 -080090 mFrameLatencyNeeded(false),
Mathias Agopian13127d82013-03-05 17:47:11 -080091 mFiltering(false),
92 mNeedsFiltering(false),
Mathias Agopian5cdc8992013-08-13 20:51:23 -070093 mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
Fabien Sanglard9d96de42016-10-11 00:15:18 +000094#ifndef USE_HWC2
95 mIsGlesComposition(false),
96#endif
Mathias Agopian13127d82013-03-05 17:47:11 -080097 mProtectedByApp(false),
98 mHasSurface(false),
Riley Andrews03414a12014-07-01 14:22:59 -070099 mClientRef(client),
Dan Stozaa4650a52015-05-12 12:56:16 -0700100 mPotentialCursor(false),
101 mQueueItemLock(),
102 mQueueItemCondition(),
103 mQueueItems(),
Dan Stoza65476f32015-05-14 09:27:25 -0700104 mLastFrameNumberReceived(0),
Pablo Ceballos04839ab2015-11-13 13:39:23 -0800105 mUpdateTexImageFailed(false),
Robert Carr82364e32016-05-15 11:27:47 -0700106 mAutoRefresh(false),
Robert Carr7bf247e2017-05-18 14:02:49 -0700107 mFreezeGeometryUpdates(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800108{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000109#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800110 ALOGV("Creating Layer %s", name.string());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000111#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -0800112
Mathias Agopiana67932f2011-04-20 14:20:59 -0700113 mCurrentCrop.makeInvalid();
Mathias Agopian3f844832013-08-07 21:24:32 -0700114 mFlinger->getRenderEngine().genTextures(1, &mTextureName);
Mathias Agopian49457ac2013-08-14 18:20:17 -0700115 mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700116
117 uint32_t layerFlags = 0;
118 if (flags & ISurfaceComposerClient::eHidden)
Andy McFadden4125a4f2014-01-29 17:17:11 -0800119 layerFlags |= layer_state_t::eLayerHidden;
120 if (flags & ISurfaceComposerClient::eOpaque)
121 layerFlags |= layer_state_t::eLayerOpaque;
Dan Stoza23116082015-06-18 14:58:39 -0700122 if (flags & ISurfaceComposerClient::eSecure)
123 layerFlags |= layer_state_t::eLayerSecure;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700124
125 if (flags & ISurfaceComposerClient::eNonPremultiplied)
126 mPremultipliedAlpha = false;
127
128 mName = name;
Dan Stozaf7ba41a2017-05-10 15:11:11 -0700129 mTransactionName = String8("TX - ") + mName;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700130
131 mCurrentState.active.w = w;
132 mCurrentState.active.h = h;
Robert Carr3dcabfa2016-03-01 18:36:58 -0800133 mCurrentState.active.transform.set(0, 0);
Robert Carrb5d3d262016-03-25 15:08:13 -0700134 mCurrentState.crop.makeInvalid();
135 mCurrentState.finalCrop.makeInvalid();
Robert Carr7bf247e2017-05-18 14:02:49 -0700136 mCurrentState.requestedFinalCrop = mCurrentState.finalCrop;
137 mCurrentState.requestedCrop = mCurrentState.crop;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700138 mCurrentState.z = 0;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000139#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800140 mCurrentState.alpha = 1.0f;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000141#else
142 mCurrentState.alpha = 0xFF;
143#endif
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700144 mCurrentState.layerStack = 0;
145 mCurrentState.flags = layerFlags;
146 mCurrentState.sequence = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700147 mCurrentState.requested = mCurrentState.active;
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700148 mCurrentState.dataSpace = HAL_DATASPACE_UNKNOWN;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500149 mCurrentState.appId = 0;
150 mCurrentState.type = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700151
152 // drawing state & current state are identical
153 mDrawingState = mCurrentState;
Jamie Gennis6547ff42013-07-16 20:12:42 -0700154
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000155#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800156 const auto& hwc = flinger->getHwComposer();
157 const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
158 nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000159#else
160 nsecs_t displayPeriod =
161 flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
162#endif
Jamie Gennis6547ff42013-07-16 20:12:42 -0700163 mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -0800164
165 CompositorTiming compositorTiming;
166 flinger->getCompositorTiming(&compositorTiming);
167 mFrameEventHistory.initializeCompositorTiming(compositorTiming);
Jamie Gennise8696a42012-01-15 18:54:57 -0800168}
169
Mathias Agopian3f844832013-08-07 21:24:32 -0700170void Layer::onFirstRef() {
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800171 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
Dan Stozab3d0bdf2014-04-07 16:33:59 -0700172 sp<IGraphicBufferProducer> producer;
173 sp<IGraphicBufferConsumer> consumer;
Mathias Agopian0556d792017-03-22 15:49:32 -0700174 BufferQueue::createBufferQueue(&producer, &consumer, true);
Robert Carr1db73f62016-12-21 12:58:51 -0800175 mProducer = new MonitoredProducer(producer, mFlinger, this);
Irvel468051e2016-06-13 16:44:44 -0700176 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800177 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Jesse Hall399184a2014-03-03 15:42:54 -0800178 mSurfaceFlingerConsumer->setContentsChangedListener(this);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700179 mSurfaceFlingerConsumer->setName(mName);
Daniel Lamb2675792012-02-23 14:35:13 -0800180
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800181 if (mFlinger->isLayerTripleBufferingDisabled()) {
182 mProducer->setMaxDequeuedBufferCount(2);
183 }
Andy McFadden69052052012-09-14 16:10:11 -0700184
Mathias Agopian84300952012-11-21 16:02:13 -0800185 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
186 updateTransformHint(hw);
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700187}
188
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700189Layer::~Layer() {
Pablo Ceballos8ea4e7b2016-03-03 15:20:02 -0800190 sp<Client> c(mClientRef.promote());
191 if (c != 0) {
192 c->detachLayer(this);
193 }
194
Dan Stozacac35382016-01-27 12:21:06 -0800195 for (auto& point : mRemoteSyncPoints) {
196 point->setTransactionApplied();
197 }
Dan Stozac8145172016-04-28 16:29:06 -0700198 for (auto& point : mLocalSyncPoints) {
199 point->setFrameAvailable();
200 }
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700201 mFlinger->deleteTextureAsync(mTextureName);
Jamie Gennis6547ff42013-07-16 20:12:42 -0700202 mFrameTracker.logAndResetStats(mName);
Mathias Agopian96f08192010-06-02 23:28:45 -0700203}
204
Mathias Agopian13127d82013-03-05 17:47:11 -0800205// ---------------------------------------------------------------------------
206// callbacks
207// ---------------------------------------------------------------------------
208
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000209#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800210void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
211 if (mHwcLayers.empty()) {
212 return;
213 }
214 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
215}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000216#else
217void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
218 HWComposer::HWCLayerInterface* layer) {
219 if (layer) {
220 layer->onDisplayed();
221 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
222 }
223}
224#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800225
Dan Stoza6b9454d2014-11-07 16:00:59 -0800226void Layer::onFrameAvailable(const BufferItem& item) {
227 // Add this buffer from our internal queue tracker
228 { // Autolock scope
229 Mutex::Autolock lock(mQueueItemLock);
Irvel468051e2016-06-13 16:44:44 -0700230 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
231 item.mGraphicBuffer->getHeight(), item.mFrameNumber);
Dan Stozaa4650a52015-05-12 12:56:16 -0700232 // Reset the frame number tracker when we receive the first buffer after
233 // a frame number reset
234 if (item.mFrameNumber == 1) {
235 mLastFrameNumberReceived = 0;
236 }
237
238 // Ensure that callbacks are handled in order
239 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
240 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
241 ms2ns(500));
242 if (result != NO_ERROR) {
243 ALOGE("[%s] Timed out waiting on callback", mName.string());
244 }
245 }
246
Dan Stoza6b9454d2014-11-07 16:00:59 -0800247 mQueueItems.push_back(item);
Dan Stozaecc50402015-04-28 14:42:06 -0700248 android_atomic_inc(&mQueuedFrames);
Dan Stozaa4650a52015-05-12 12:56:16 -0700249
250 // Wake up any pending callbacks
251 mLastFrameNumberReceived = item.mFrameNumber;
252 mQueueItemCondition.broadcast();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800253 }
254
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800255 mFlinger->signalLayerUpdate();
Mathias Agopian579b3f82010-06-08 19:54:15 -0700256}
257
Dan Stoza6b9454d2014-11-07 16:00:59 -0800258void Layer::onFrameReplaced(const BufferItem& item) {
Dan Stoza7dde5992015-05-22 09:51:44 -0700259 { // Autolock scope
260 Mutex::Autolock lock(mQueueItemLock);
Dan Stozaa4650a52015-05-12 12:56:16 -0700261
Dan Stoza7dde5992015-05-22 09:51:44 -0700262 // Ensure that callbacks are handled in order
263 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
264 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
265 ms2ns(500));
266 if (result != NO_ERROR) {
267 ALOGE("[%s] Timed out waiting on callback", mName.string());
268 }
Dan Stozaa4650a52015-05-12 12:56:16 -0700269 }
Dan Stoza7dde5992015-05-22 09:51:44 -0700270
271 if (mQueueItems.empty()) {
272 ALOGE("Can't replace a frame on an empty queue");
273 return;
274 }
Pablo Ceballos4d85da42016-04-19 20:11:56 -0700275 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
Dan Stoza7dde5992015-05-22 09:51:44 -0700276
277 // Wake up any pending callbacks
278 mLastFrameNumberReceived = item.mFrameNumber;
279 mQueueItemCondition.broadcast();
Dan Stozaa4650a52015-05-12 12:56:16 -0700280 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800281}
282
Jesse Hall399184a2014-03-03 15:42:54 -0800283void Layer::onSidebandStreamChanged() {
284 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
285 // mSidebandStreamChanged was false
286 mFlinger->signalLayerUpdate();
287 }
288}
289
Mathias Agopian67106042013-03-14 19:18:13 -0700290// called with SurfaceFlinger::mStateLock from the drawing thread after
291// the layer has been remove from the current state list (and just before
292// it's removed from the drawing state list)
Mathias Agopian13127d82013-03-05 17:47:11 -0800293void Layer::onRemoved() {
Robert Carr5edb1ad2017-04-25 10:54:24 -0700294 if (mCurrentState.zOrderRelativeOf != nullptr) {
295 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
296 if (strongRelative != nullptr) {
297 strongRelative->removeZOrderRelative(this);
298 }
299 mCurrentState.zOrderRelativeOf = nullptr;
300 }
301
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800302 mSurfaceFlingerConsumer->abandon();
Chia-I Wu38512252017-05-17 14:36:16 -0700303
304#ifdef USE_HWC2
305 clearHwcLayers();
306#endif
307
Robert Carr1f0a16a2016-10-24 16:27:39 -0700308 for (const auto& child : mCurrentChildren) {
309 child->onRemoved();
310 }
Mathias Agopian48d819a2009-09-10 19:41:18 -0700311}
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700312
Mathias Agopian13127d82013-03-05 17:47:11 -0800313// ---------------------------------------------------------------------------
314// set-up
315// ---------------------------------------------------------------------------
316
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700317const String8& Layer::getName() const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800318 return mName;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800319}
320
Mathias Agopianf9d93272009-06-19 17:00:27 -0700321status_t Layer::setBuffers( uint32_t w, uint32_t h,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800322 PixelFormat format, uint32_t flags)
323{
Mathias Agopianca99fb82010-04-14 16:43:44 -0700324 uint32_t const maxSurfaceDims = min(
Mathias Agopiana4912602012-07-12 14:25:33 -0700325 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
Mathias Agopianca99fb82010-04-14 16:43:44 -0700326
327 // never allow a surface larger than what our underlying GL implementation
328 // can handle.
329 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
Mathias Agopianff615cc2012-02-24 14:58:36 -0800330 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700331 return BAD_VALUE;
332 }
333
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700334 mFormat = format;
Mathias Agopianeff062c2010-08-25 14:59:15 -0700335
Riley Andrews03414a12014-07-01 14:22:59 -0700336 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
Mathias Agopian3165cc22012-08-08 19:42:09 -0700337 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700338 mCurrentOpacity = getOpacityForFormat(format);
339
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800340 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
341 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
342 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700343
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800344 return NO_ERROR;
345}
346
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700347sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800348 Mutex::Autolock _l(mLock);
349
350 LOG_ALWAYS_FATAL_IF(mHasSurface,
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700351 "Layer::getHandle() has already been called");
Mathias Agopian13127d82013-03-05 17:47:11 -0800352
353 mHasSurface = true;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700354
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700355 return new Handle(mFlinger, this);
Mathias Agopian13127d82013-03-05 17:47:11 -0800356}
357
Dan Stozab9b08832014-03-13 11:55:57 -0700358sp<IGraphicBufferProducer> Layer::getProducer() const {
359 return mProducer;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700360}
361
Mathias Agopian13127d82013-03-05 17:47:11 -0800362// ---------------------------------------------------------------------------
363// h/w composer set-up
364// ---------------------------------------------------------------------------
365
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800366Rect Layer::getContentCrop() const {
367 // this is the crop rectangle that applies to the buffer
368 // itself (as opposed to the window)
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700369 Rect crop;
370 if (!mCurrentCrop.isEmpty()) {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800371 // if the buffer crop is defined, we use that
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700372 crop = mCurrentCrop;
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800373 } else if (mActiveBuffer != NULL) {
374 // otherwise we use the whole buffer
375 crop = mActiveBuffer->getBounds();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700376 } else {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800377 // if we don't have a buffer yet, we use an empty/invalid crop
Mathias Agopian4fec8732012-06-29 14:12:52 -0700378 crop.makeInvalid();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700379 }
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700380 return crop;
381}
382
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700383static Rect reduce(const Rect& win, const Region& exclude) {
384 if (CC_LIKELY(exclude.isEmpty())) {
385 return win;
386 }
387 if (exclude.isRect()) {
388 return win.reduce(exclude.getBounds());
389 }
390 return Region(win).subtract(exclude).getBounds();
391}
392
Robert Carr1f0a16a2016-10-24 16:27:39 -0700393Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
394 const Layer::State& s(getDrawingState());
395 Rect win(s.active.w, s.active.h);
396
397 if (!s.crop.isEmpty()) {
398 win.intersect(s.crop, &win);
399 }
400
401 Transform t = getTransform();
402 win = t.transform(win);
403
Robert Carr41b08b52017-06-01 16:11:34 -0700404 if (!s.finalCrop.isEmpty()) {
405 win.intersect(s.finalCrop, &win);
406 }
407
Chia-I Wue41dbe62017-06-13 14:10:56 -0700408 const sp<Layer>& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700409 // Now we need to calculate the parent bounds, so we can clip ourselves to those.
410 // When calculating the parent bounds for purposes of clipping,
411 // we don't need to constrain the parent to its transparent region.
412 // The transparent region is an optimization based on the
413 // buffer contents of the layer, but does not affect the space allocated to
414 // it by policy, and thus children should be allowed to extend into the
415 // parent's transparent region. In fact one of the main uses, is to reduce
416 // buffer allocation size in cases where a child window sits behind a main window
417 // (by marking the hole in the parent window as a transparent region)
418 if (p != nullptr) {
419 Rect bounds = p->computeScreenBounds(false);
420 bounds.intersect(win, &win);
421 }
422
423 if (reduceTransparentRegion) {
424 auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
425 win = reduce(win, screenTransparentRegion);
426 }
427
428 return win;
429}
430
Mathias Agopian13127d82013-03-05 17:47:11 -0800431Rect Layer::computeBounds() const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700432 const Layer::State& s(getDrawingState());
Michael Lentine6c925ed2014-09-26 17:55:01 -0700433 return computeBounds(s.activeTransparentRegion);
434}
435
436Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
437 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800438 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700439
440 if (!s.crop.isEmpty()) {
441 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -0800442 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700443
444 Rect bounds = win;
Chia-I Wue41dbe62017-06-13 14:10:56 -0700445 const auto& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700446 if (p != nullptr) {
Robert Carrde9ec442017-02-08 17:43:36 -0800447 // Look in computeScreenBounds recursive call for explanation of
448 // why we pass false here.
449 bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700450 }
451
452 Transform t = getTransform();
453 if (p != nullptr) {
454 win = t.transform(win);
455 win.intersect(bounds, &win);
456 win = t.inverse().transform(win);
457 }
458
Mathias Agopian6c7f25a2013-05-09 20:37:10 -0700459 // subtract the transparent region and snap to the bounds
Michael Lentine6c925ed2014-09-26 17:55:01 -0700460 return reduce(win, activeTransparentRegion);
Mathias Agopian13127d82013-03-05 17:47:11 -0800461}
462
Robert Carr1f0a16a2016-10-24 16:27:39 -0700463Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
Robert Carrb5d3d262016-03-25 15:08:13 -0700464 // the crop is the area of the window that gets cropped, but not
Mathias Agopian13127d82013-03-05 17:47:11 -0800465 // scaled in any ways.
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700466 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800467
468 // apply the projection's clipping to the window crop in
469 // layerstack space, and convert-back to layer space.
Mathias Agopian6b442672013-07-09 21:24:52 -0700470 // if there are no window scaling involved, this operation will map to full
471 // pixels in the buffer.
472 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
473 // a viewport clipping and a window transform. we should use floating point to fix this.
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700474
475 Rect activeCrop(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700476 if (!s.crop.isEmpty()) {
Chia-I Wudf7867f2017-07-20 14:24:37 -0700477 activeCrop.intersect(s.crop, &activeCrop);
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700478 }
479
Robert Carr1f0a16a2016-10-24 16:27:39 -0700480 Transform t = getTransform();
481 activeCrop = t.transform(activeCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000482 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
483 activeCrop.clear();
484 }
Robert Carrb5d3d262016-03-25 15:08:13 -0700485 if (!s.finalCrop.isEmpty()) {
486 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000487 activeCrop.clear();
488 }
489 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700490 return activeCrop;
491}
492
Dan Stoza5a423ea2017-02-16 14:10:39 -0800493FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
Robert Carr1f0a16a2016-10-24 16:27:39 -0700494 // the content crop is the area of the content that gets scaled to the
495 // layer's size. This is in buffer space.
Dan Stoza5a423ea2017-02-16 14:10:39 -0800496 FloatRect crop = getContentCrop().toFloatRect();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700497
498 // In addition there is a WM-specified crop we pull from our drawing state.
499 const State& s(getDrawingState());
500
501 // Screen space to make reduction to parent crop clearer.
502 Rect activeCrop = computeInitialCrop(hw);
Chia-I Wue41dbe62017-06-13 14:10:56 -0700503 const auto& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700504 if (p != nullptr) {
505 auto parentCrop = p->computeInitialCrop(hw);
506 activeCrop.intersect(parentCrop, &activeCrop);
507 }
508 Transform t = getTransform();
509 // Back to layer space to work with the content crop.
510 activeCrop = t.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800511
Michael Lentine28ea2172014-11-19 18:32:37 -0800512 // This needs to be here as transform.transform(Rect) computes the
513 // transformed rect and then takes the bounding box of the result before
514 // returning. This means
515 // transform.inverse().transform(transform.transform(Rect)) != Rect
516 // in which case we need to make sure the final rect is clipped to the
517 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000518 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
519 activeCrop.clear();
520 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800521
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700522 // subtract the transparent region and snap to the bounds
523 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
524
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000525 // Transform the window crop to match the buffer coordinate system,
526 // which means using the inverse of the current transform set on the
527 // SurfaceFlingerConsumer.
528 uint32_t invTransform = mCurrentTransform;
Robert Carrcae605c2017-03-29 12:10:31 -0700529 if (getTransformToDisplayInverse()) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000530 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700531 * the code below applies the primary display's inverse transform to the
532 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000533 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700534 uint32_t invTransformOrient =
535 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000536 // calculate the inverse transform
537 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
538 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
539 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800540 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000541 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700542 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
543 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800544 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000545
546 int winWidth = s.active.w;
547 int winHeight = s.active.h;
548 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
549 // If the activeCrop has been rotate the ends are rotated but not
550 // the space itself so when transforming ends back we can't rely on
551 // a modification of the axes of rotation. To account for this we
552 // need to reorient the inverse rotation in terms of the current
553 // axes of rotation.
554 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
555 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
556 if (is_h_flipped == is_v_flipped) {
557 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
558 NATIVE_WINDOW_TRANSFORM_FLIP_H;
559 }
560 winWidth = s.active.h;
561 winHeight = s.active.w;
562 }
563 const Rect winCrop = activeCrop.transform(
564 invTransform, s.active.w, s.active.h);
565
566 // below, crop is intersected with winCrop expressed in crop's coordinate space
567 float xScale = crop.getWidth() / float(winWidth);
568 float yScale = crop.getHeight() / float(winHeight);
569
570 float insetL = winCrop.left * xScale;
571 float insetT = winCrop.top * yScale;
572 float insetR = (winWidth - winCrop.right ) * xScale;
573 float insetB = (winHeight - winCrop.bottom) * yScale;
574
575 crop.left += insetL;
576 crop.top += insetT;
577 crop.right -= insetR;
578 crop.bottom -= insetB;
579
Mathias Agopian13127d82013-03-05 17:47:11 -0800580 return crop;
581}
582
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000583#ifdef USE_HWC2
Robert Carrae060832016-11-28 10:51:00 -0800584void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000585#else
586void Layer::setGeometry(
587 const sp<const DisplayDevice>& hw,
588 HWComposer::HWCLayerInterface& layer)
589#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700590{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000591#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800592 const auto hwcId = displayDevice->getHwcDisplayId();
593 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000594#else
595 layer.setDefaultState();
596#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700597
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700598 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000599#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800600 hwcInfo.forceClientComposition = false;
601
602 if (isSecure() && !displayDevice->isSecure()) {
603 hwcInfo.forceClientComposition = true;
604 }
605
606 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000607#else
608 layer.setSkip(false);
609
610 if (isSecure() && !hw->isSecure()) {
611 layer.setSkip(true);
612 }
613#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700614
Mathias Agopian13127d82013-03-05 17:47:11 -0800615 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700616 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000617#ifdef USE_HWC2
David Revemanecf0fa52017-03-03 11:32:44 -0500618 auto blendMode = HWC2::BlendMode::None;
Robert Carr6452f122017-03-21 10:41:29 -0700619 if (!isOpaque(s) || getAlpha() != 1.0f) {
David Revemanecf0fa52017-03-03 11:32:44 -0500620 blendMode = mPremultipliedAlpha ?
Dan Stoza9e56aa02015-11-02 13:00:03 -0800621 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800622 }
David Revemanecf0fa52017-03-03 11:32:44 -0500623 auto error = hwcLayer->setBlendMode(blendMode);
624 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
625 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
626 to_string(error).c_str(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000627#else
Robert Carr6452f122017-03-21 10:41:29 -0700628 if (!isOpaque(s) || getAlpha() != 0xFF) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000629 layer.setBlending(mPremultipliedAlpha ?
630 HWC_BLENDING_PREMULT :
631 HWC_BLENDING_COVERAGE);
632 }
633#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800634
635 // apply the layer's transform, followed by the display's global transform
636 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700637 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700638 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -0700639 if (!s.crop.isEmpty()) {
640 Rect activeCrop(s.crop);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700641 activeCrop = t.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000642#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000643 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000644#else
645 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
646#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000647 activeCrop.clear();
648 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700649 activeCrop = t.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800650 // This needs to be here as transform.transform(Rect) computes the
651 // transformed rect and then takes the bounding box of the result before
652 // returning. This means
653 // transform.inverse().transform(transform.transform(Rect)) != Rect
654 // in which case we need to make sure the final rect is clipped to the
655 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000656 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
657 activeCrop.clear();
658 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700659 // mark regions outside the crop as transparent
660 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
661 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
662 s.active.w, s.active.h));
663 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
664 activeCrop.left, activeCrop.bottom));
665 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
666 s.active.w, activeCrop.bottom));
667 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700668
669 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700670 if (!s.finalCrop.isEmpty()) {
671 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000672 frame.clear();
673 }
674 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000675#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000676 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
677 frame.clear();
678 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800679 const Transform& tr(displayDevice->getTransform());
680 Rect transformedFrame = tr.transform(frame);
David Revemanecf0fa52017-03-03 11:32:44 -0500681 error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700682 if (error != HWC2::Error::None) {
683 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
684 mName.string(), transformedFrame.left, transformedFrame.top,
685 transformedFrame.right, transformedFrame.bottom,
686 to_string(error).c_str(), static_cast<int32_t>(error));
687 } else {
688 hwcInfo.displayFrame = transformedFrame;
689 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800690
Dan Stoza5a423ea2017-02-16 14:10:39 -0800691 FloatRect sourceCrop = computeCrop(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800692 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700693 if (error != HWC2::Error::None) {
694 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
695 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
696 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
697 static_cast<int32_t>(error));
698 } else {
699 hwcInfo.sourceCrop = sourceCrop;
700 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800701
Robert Carr6452f122017-03-21 10:41:29 -0700702 float alpha = getAlpha();
703 error = hwcLayer->setPlaneAlpha(alpha);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800704 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
Robert Carr6452f122017-03-21 10:41:29 -0700705 "%s (%d)", mName.string(), alpha, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800706 static_cast<int32_t>(error));
707
Robert Carrae060832016-11-28 10:51:00 -0800708 error = hwcLayer->setZOrder(z);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800709 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
Robert Carrae060832016-11-28 10:51:00 -0800710 mName.string(), z, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800711 static_cast<int32_t>(error));
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500712
Albert Chaulk2a589632017-05-04 16:59:44 -0400713 int type = s.type;
714 int appId = s.appId;
Chia-I Wue41dbe62017-06-13 14:10:56 -0700715 sp<Layer> parent = mDrawingParent.promote();
Albert Chaulk2a589632017-05-04 16:59:44 -0400716 if (parent.get()) {
717 auto& parentState = parent->getDrawingState();
718 type = parentState.type;
719 appId = parentState.appId;
720 }
721
722 error = hwcLayer->setInfo(type, appId);
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500723 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
724 mName.string(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000725#else
726 if (!frame.intersect(hw->getViewport(), &frame)) {
727 frame.clear();
728 }
729 const Transform& tr(hw->getTransform());
730 layer.setFrame(tr.transform(frame));
731 layer.setCrop(computeCrop(hw));
Robert Carr6452f122017-03-21 10:41:29 -0700732 layer.setPlaneAlpha(getAlpha());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000733#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800734
Mathias Agopian29a367b2011-07-12 14:51:45 -0700735 /*
736 * Transformations are applied in this order:
737 * 1) buffer orientation/flip/mirror
738 * 2) state transformation (window manager)
739 * 3) layer orientation (screen orientation)
740 * (NOTE: the matrices are multiplied in reverse order)
741 */
742
743 const Transform bufferOrientation(mCurrentTransform);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700744 Transform transform(tr * t * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700745
Robert Carrcae605c2017-03-29 12:10:31 -0700746 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700747 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700748 * the code below applies the primary display's inverse transform to the
749 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700750 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700751 uint32_t invTransform =
752 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700753 // calculate the inverse transform
754 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
755 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
756 NATIVE_WINDOW_TRANSFORM_FLIP_H;
757 }
Robert Carrcae605c2017-03-29 12:10:31 -0700758
759 /*
760 * Here we cancel out the orientation component of the WM transform.
761 * The scaling and translate components are already included in our bounds
762 * computation so it's enough to just omit it in the composition.
763 * See comment in onDraw with ref to b/36727915 for why.
764 */
765 transform = Transform(invTransform) * tr * bufferOrientation;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700766 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700767
768 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800769 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000770#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800771 if (orientation & Transform::ROT_INVALID) {
772 // we can only handle simple transformation
773 hwcInfo.forceClientComposition = true;
774 } else {
775 auto transform = static_cast<HWC2::Transform>(orientation);
776 auto error = hwcLayer->setTransform(transform);
777 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
778 "%s (%d)", mName.string(), to_string(transform).c_str(),
779 to_string(error).c_str(), static_cast<int32_t>(error));
780 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000781#else
782 if (orientation & Transform::ROT_INVALID) {
783 // we can only handle simple transformation
784 layer.setSkip(true);
785 } else {
786 layer.setTransform(orientation);
787 }
788#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700789}
790
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000791#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800792void Layer::forceClientComposition(int32_t hwcId) {
793 if (mHwcLayers.count(hwcId) == 0) {
794 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
795 return;
796 }
797
798 mHwcLayers[hwcId].forceClientComposition = true;
799}
Dan Stoza9e56aa02015-11-02 13:00:03 -0800800
Dan Stoza9e56aa02015-11-02 13:00:03 -0800801void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
802 // Apply this display's projection's viewport to the visible region
803 // before giving it to the HWC HAL.
804 const Transform& tr = displayDevice->getTransform();
805 const auto& viewport = displayDevice->getViewport();
806 Region visible = tr.transform(visibleRegion.intersect(viewport));
807 auto hwcId = displayDevice->getHwcDisplayId();
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800808 auto& hwcInfo = mHwcLayers[hwcId];
809 auto& hwcLayer = hwcInfo.layer;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800810 auto error = hwcLayer->setVisibleRegion(visible);
811 if (error != HWC2::Error::None) {
812 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
813 to_string(error).c_str(), static_cast<int32_t>(error));
814 visible.dump(LOG_TAG);
815 }
816
817 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
818 if (error != HWC2::Error::None) {
819 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
820 to_string(error).c_str(), static_cast<int32_t>(error));
821 surfaceDamageRegion.dump(LOG_TAG);
822 }
823
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700824 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800825 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700826 setCompositionType(hwcId, HWC2::Composition::Sideband);
827 ALOGV("[%s] Requesting Sideband composition", mName.string());
828 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800829 if (error != HWC2::Error::None) {
830 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
831 mName.string(), mSidebandStream->handle(),
832 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800833 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700834 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800835 }
836
Dan Stoza0a21df72016-07-20 12:52:38 -0700837 // Client layers
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800838 if (hwcInfo.forceClientComposition ||
Dan Stoza0a21df72016-07-20 12:52:38 -0700839 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700840 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800841 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700842 return;
843 }
844
Dan Stoza0a21df72016-07-20 12:52:38 -0700845 // SolidColor layers
846 if (mActiveBuffer == nullptr) {
847 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700848
849 // For now, we only support black for DimLayer
Dan Stoza0a21df72016-07-20 12:52:38 -0700850 error = hwcLayer->setColor({0, 0, 0, 255});
851 if (error != HWC2::Error::None) {
852 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
853 to_string(error).c_str(), static_cast<int32_t>(error));
854 }
Dan Stozac6c89542016-07-27 10:16:52 -0700855
856 // Clear out the transform, because it doesn't make sense absent a
857 // source buffer
858 error = hwcLayer->setTransform(HWC2::Transform::None);
859 if (error != HWC2::Error::None) {
860 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
861 to_string(error).c_str(), static_cast<int32_t>(error));
862 }
863
Dan Stoza0a21df72016-07-20 12:52:38 -0700864 return;
865 }
866
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700867 // Device or Cursor layers
868 if (mPotentialCursor) {
869 ALOGV("[%s] Requesting Cursor composition", mName.string());
870 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800871 } else {
872 ALOGV("[%s] Requesting Device composition", mName.string());
873 setCompositionType(hwcId, HWC2::Composition::Device);
874 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700875
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700876 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
877 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
878 if (error != HWC2::Error::None) {
879 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
880 mCurrentState.dataSpace, to_string(error).c_str(),
881 static_cast<int32_t>(error));
882 }
883
Chia-I Wu06d63de2017-01-04 14:58:51 +0800884 uint32_t hwcSlot = 0;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400885 sp<GraphicBuffer> hwcBuffer;
886 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
887 &hwcSlot, &hwcBuffer);
Chia-I Wu06d63de2017-01-04 14:58:51 +0800888
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700889 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400890 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700891 if (error != HWC2::Error::None) {
892 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
893 mActiveBuffer->handle, to_string(error).c_str(),
894 static_cast<int32_t>(error));
895 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800896}
Courtney Goeltzenleuchter9551fd32016-10-20 17:18:15 -0600897
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000898#else
899void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
900 HWComposer::HWCLayerInterface& layer) {
901 // we have to set the visible region on every frame because
902 // we currently free it during onLayerDisplayed(), which is called
903 // after HWComposer::commit() -- every frame.
904 // Apply this display's projection's viewport to the visible region
905 // before giving it to the HWC HAL.
906 const Transform& tr = hw->getTransform();
907 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
908 layer.setVisibleRegionScreen(visible);
909 layer.setSurfaceDamage(surfaceDamageRegion);
910 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700911
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000912 if (mSidebandStream.get()) {
913 layer.setSidebandStream(mSidebandStream);
914 } else {
915 // NOTE: buffer can be NULL if the client never drew into this
916 // layer yet, or if we ran out of memory
917 layer.setBuffer(mActiveBuffer);
918 }
919}
920#endif
921
922#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800923void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
924 auto hwcId = displayDevice->getHwcDisplayId();
925 if (mHwcLayers.count(hwcId) == 0 ||
926 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
927 return;
928 }
929
930 // This gives us only the "orientation" component of the transform
931 const State& s(getCurrentState());
932
933 // Apply the layer's transform, followed by the display's global transform
934 // Here we're guaranteed that the layer's transform preserves rects
935 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700936 if (!s.crop.isEmpty()) {
937 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800938 }
939 // Subtract the transparent region and snap to the bounds
940 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700941 Rect frame(getTransform().transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800942 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -0700943 if (!s.finalCrop.isEmpty()) {
944 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000945 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800946 auto& displayTransform(displayDevice->getTransform());
947 auto position = displayTransform.transform(frame);
948
949 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
950 position.top);
951 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
952 "to (%d, %d): %s (%d)", mName.string(), position.left,
953 position.top, to_string(error).c_str(),
954 static_cast<int32_t>(error));
955}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000956#else
957void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
958 HWComposer::HWCLayerInterface& layer) {
959 int fenceFd = -1;
960
961 // TODO: there is a possible optimization here: we only need to set the
962 // acquire fence the first time a new buffer is acquired on EACH display.
963
964 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
965 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
966 if (fence->isValid()) {
967 fenceFd = fence->dup();
968 if (fenceFd == -1) {
969 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
970 }
971 }
972 }
973 layer.setAcquireFenceFd(fenceFd);
974}
975
976Rect Layer::getPosition(
977 const sp<const DisplayDevice>& hw)
978{
979 // this gives us only the "orientation" component of the transform
980 const State& s(getCurrentState());
981
982 // apply the layer's transform, followed by the display's global transform
983 // here we're guaranteed that the layer's transform preserves rects
984 Rect win(s.active.w, s.active.h);
985 if (!s.crop.isEmpty()) {
986 win.intersect(s.crop, &win);
987 }
988 // subtract the transparent region and snap to the bounds
989 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700990 Rect frame(getTransform().transform(bounds));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000991 frame.intersect(hw->getViewport(), &frame);
992 if (!s.finalCrop.isEmpty()) {
993 frame.intersect(s.finalCrop, &frame);
994 }
995 const Transform& tr(hw->getTransform());
996 return Rect(tr.transform(frame));
997}
998#endif
Riley Andrews03414a12014-07-01 14:22:59 -0700999
Mathias Agopian13127d82013-03-05 17:47:11 -08001000// ---------------------------------------------------------------------------
1001// drawing...
1002// ---------------------------------------------------------------------------
1003
1004void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -08001005 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -08001006}
1007
Dan Stozac7014012014-02-14 15:03:43 -08001008void Layer::draw(const sp<const DisplayDevice>& hw,
1009 bool useIdentityTransform) const {
1010 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001011}
1012
Dan Stozac7014012014-02-14 15:03:43 -08001013void Layer::draw(const sp<const DisplayDevice>& hw) const {
1014 onDraw(hw, Region(hw->bounds()), false);
1015}
1016
Robert Carrcae605c2017-03-29 12:10:31 -07001017static constexpr mat4 inverseOrientation(uint32_t transform) {
1018 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1019 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1020 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1021 mat4 tr;
1022
1023 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1024 tr = tr * rot90;
1025 }
1026 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1027 tr = tr * flipH;
1028 }
1029 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1030 tr = tr * flipV;
1031 }
1032 return inverse(tr);
1033}
1034
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001035/*
1036 * onDraw will draw the current layer onto the presentable buffer
1037 */
Dan Stozac7014012014-02-14 15:03:43 -08001038void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
1039 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001040{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001041 ATRACE_CALL();
1042
Mathias Agopiana67932f2011-04-20 14:20:59 -07001043 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001044 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -07001045 // in fact never been drawn into. This happens frequently with
1046 // SurfaceView because the WindowManager can't know when the client
1047 // has drawn the first time.
1048
1049 // If there is nothing under us, we paint the screen in black, otherwise
1050 // we just skip this update.
1051
1052 // figure out if there is something below us
1053 Region under;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001054 bool finished = false;
Dan Stoza412903f2017-04-27 13:42:17 -07001055 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001056 if (finished || layer == static_cast<Layer const*>(this)) {
1057 finished = true;
1058 return;
1059 }
Mathias Agopian42977342012-08-05 00:40:46 -07001060 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Robert Carr1f0a16a2016-10-24 16:27:39 -07001061 });
Mathias Agopian179169e2010-05-06 20:21:45 -07001062 // if not everything below us is covered, we plug the holes!
1063 Region holes(clip.subtract(under));
1064 if (!holes.isEmpty()) {
Fabien Sanglard17487192016-12-07 13:03:32 -08001065 clearWithOpenGL(hw, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -07001066 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001067 return;
1068 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001069
Andy McFadden97eba892012-12-11 15:21:45 -08001070 // Bind the current buffer to the GL texture, and wait for it to be
1071 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001072 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1073 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -08001074 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -07001075 // Go ahead and draw the buffer anyway; no matter what we do the screen
1076 // is probably going to have something visibly wrong.
1077 }
1078
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001079 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1080
Mathias Agopian875d8e12013-06-07 15:35:48 -07001081 RenderEngine& engine(mFlinger->getRenderEngine());
1082
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001083 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -07001084 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -07001085 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -07001086
1087 // Query the texture matrix given our current filtering mode.
1088 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001089 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1090 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -07001091
Robert Carrcae605c2017-03-29 12:10:31 -07001092 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001093
1094 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -07001095 * the code below applies the primary display's inverse transform to
1096 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001097 */
Pablo Ceballos021623b2016-04-15 17:31:51 -07001098 uint32_t transform =
1099 DisplayDevice::getPrimaryDisplayOrientationTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001100 mat4 tr = inverseOrientation(transform);
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001101
Robert Carrcae605c2017-03-29 12:10:31 -07001102 /**
1103 * TODO(b/36727915): This is basically a hack.
1104 *
1105 * Ensure that regardless of the parent transformation,
1106 * this buffer is always transformed from native display
1107 * orientation to display orientation. For example, in the case
1108 * of a camera where the buffer remains in native orientation,
1109 * we want the pixels to always be upright.
1110 */
Chia-I Wue41dbe62017-06-13 14:10:56 -07001111 sp<Layer> p = mDrawingParent.promote();
1112 if (p != nullptr) {
1113 const auto parentTransform = p->getTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001114 tr = tr * inverseOrientation(parentTransform.getOrientation());
1115 }
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001116
1117 // and finally apply it to the original texture matrix
1118 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1119 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1120 }
1121
Jamie Genniscbb1a952012-05-08 17:05:52 -07001122 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -07001123 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1124 mTexture.setFiltering(useFiltering);
1125 mTexture.setMatrix(textureMatrix);
1126
1127 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -07001128 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001129 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -07001130 }
Fabien Sanglard85789802016-12-07 13:08:24 -08001131 drawWithOpenGL(hw, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001132 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001133}
1134
Mathias Agopian13127d82013-03-05 17:47:11 -08001135
Dan Stozac7014012014-02-14 15:03:43 -08001136void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard17487192016-12-07 13:03:32 -08001137 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -08001138 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001139{
Mathias Agopian19733a32013-08-28 18:13:56 -07001140 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -08001141 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -07001142 engine.setupFillWithColor(red, green, blue, alpha);
1143 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -08001144}
1145
1146void Layer::clearWithOpenGL(
Fabien Sanglard17487192016-12-07 13:03:32 -08001147 const sp<const DisplayDevice>& hw) const {
1148 clearWithOpenGL(hw, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001149}
1150
Dan Stozac7014012014-02-14 15:03:43 -08001151void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard85789802016-12-07 13:08:24 -08001152 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001153 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001154
Dan Stozac7014012014-02-14 15:03:43 -08001155 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001156
Mathias Agopian13127d82013-03-05 17:47:11 -08001157 /*
1158 * NOTE: the way we compute the texture coordinates here produces
1159 * different results than when we take the HWC path -- in the later case
1160 * the "source crop" is rounded to texel boundaries.
1161 * This can produce significantly different results when the texture
1162 * is scaled by a large amount.
1163 *
1164 * The GL code below is more logical (imho), and the difference with
1165 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001166 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001167 * GL composition when a buffer scaling is applied (maybe with some
1168 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1169 * like more of a hack.
1170 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001171 Rect win(computeBounds());
1172
Robert Carr1f0a16a2016-10-24 16:27:39 -07001173 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -07001174 if (!s.finalCrop.isEmpty()) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001175 win = t.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001176 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001177 win.clear();
1178 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001179 win = t.inverse().transform(win);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001180 if (!win.intersect(computeBounds(), &win)) {
1181 win.clear();
1182 }
1183 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001184
Mathias Agopian3f844832013-08-07 21:24:32 -07001185 float left = float(win.left) / float(s.active.w);
1186 float top = float(win.top) / float(s.active.h);
1187 float right = float(win.right) / float(s.active.w);
1188 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001189
Mathias Agopian875d8e12013-06-07 15:35:48 -07001190 // TODO: we probably want to generate the texture coords with the mesh
1191 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001192 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1193 texCoords[0] = vec2(left, 1.0f - top);
1194 texCoords[1] = vec2(left, 1.0f - bottom);
1195 texCoords[2] = vec2(right, 1.0f - bottom);
1196 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001197
Mathias Agopian875d8e12013-06-07 15:35:48 -07001198 RenderEngine& engine(mFlinger->getRenderEngine());
Robert Carr6452f122017-03-21 10:41:29 -07001199 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), getAlpha());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001200#ifdef USE_HWC2
1201 engine.setSourceDataSpace(mCurrentState.dataSpace);
1202#endif
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001203 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001204 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001205}
1206
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001207#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001208void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1209 bool callIntoHwc) {
1210 if (mHwcLayers.count(hwcId) == 0) {
1211 ALOGE("setCompositionType called without a valid HWC layer");
1212 return;
1213 }
1214 auto& hwcInfo = mHwcLayers[hwcId];
1215 auto& hwcLayer = hwcInfo.layer;
1216 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1217 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1218 if (hwcInfo.compositionType != type) {
1219 ALOGV(" actually setting");
1220 hwcInfo.compositionType = type;
1221 if (callIntoHwc) {
1222 auto error = hwcLayer->setCompositionType(type);
1223 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1224 "composition type %s: %s (%d)", mName.string(),
1225 to_string(type).c_str(), to_string(error).c_str(),
1226 static_cast<int32_t>(error));
1227 }
1228 }
1229}
1230
1231HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001232 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1233 // If we're querying the composition type for a display that does not
1234 // have a HWC counterpart, then it will always be Client
1235 return HWC2::Composition::Client;
1236 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001237 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001238 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001239 return HWC2::Composition::Invalid;
1240 }
1241 return mHwcLayers.at(hwcId).compositionType;
1242}
1243
1244void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1245 if (mHwcLayers.count(hwcId) == 0) {
1246 ALOGE("setClearClientTarget called without a valid HWC layer");
1247 return;
1248 }
1249 mHwcLayers[hwcId].clearClientTarget = clear;
1250}
1251
1252bool Layer::getClearClientTarget(int32_t hwcId) const {
1253 if (mHwcLayers.count(hwcId) == 0) {
1254 ALOGE("getClearClientTarget called without a valid HWC layer");
1255 return false;
1256 }
1257 return mHwcLayers.at(hwcId).clearClientTarget;
1258}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001259#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001260
Ruben Brunk1681d952014-06-27 15:51:55 -07001261uint32_t Layer::getProducerStickyTransform() const {
1262 int producerStickyTransform = 0;
1263 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1264 if (ret != OK) {
1265 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1266 strerror(-ret), ret);
1267 return 0;
1268 }
1269 return static_cast<uint32_t>(producerStickyTransform);
1270}
1271
Dan Stozac5da2712016-07-20 15:38:12 -07001272bool Layer::latchUnsignaledBuffers() {
1273 static bool propertyLoaded = false;
1274 static bool latch = false;
1275 static std::mutex mutex;
1276 std::lock_guard<std::mutex> lock(mutex);
1277 if (!propertyLoaded) {
1278 char value[PROPERTY_VALUE_MAX] = {};
1279 property_get("debug.sf.latch_unsignaled", value, "0");
1280 latch = atoi(value);
1281 propertyLoaded = true;
1282 }
1283 return latch;
1284}
1285
Dan Stozacac35382016-01-27 12:21:06 -08001286uint64_t Layer::getHeadFrameNumber() const {
1287 Mutex::Autolock lock(mQueueItemLock);
1288 if (!mQueueItems.empty()) {
1289 return mQueueItems[0].mFrameNumber;
1290 } else {
1291 return mCurrentFrameNumber;
1292 }
1293}
1294
Dan Stoza1ce65812016-06-15 16:26:27 -07001295bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001296#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001297 if (latchUnsignaledBuffers()) {
1298 return true;
1299 }
1300
Dan Stoza1ce65812016-06-15 16:26:27 -07001301 Mutex::Autolock lock(mQueueItemLock);
1302 if (mQueueItems.empty()) {
1303 return true;
1304 }
1305 if (mQueueItems[0].mIsDroppable) {
1306 // Even though this buffer's fence may not have signaled yet, it could
1307 // be replaced by another buffer before it has a chance to, which means
1308 // that it's possible to get into a situation where a buffer is never
1309 // able to be latched. To avoid this, grab this buffer anyway.
1310 return true;
1311 }
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001312 return mQueueItems[0].mFenceTime->getSignalTime() !=
1313 Fence::SIGNAL_TIME_PENDING;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001314#else
1315 return true;
1316#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001317}
1318
Dan Stozacac35382016-01-27 12:21:06 -08001319bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1320 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1321 // Don't bother with a SyncPoint, since we've already latched the
1322 // relevant frame
1323 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001324 }
1325
Dan Stozacac35382016-01-27 12:21:06 -08001326 Mutex::Autolock lock(mLocalSyncPointMutex);
1327 mLocalSyncPoints.push_back(point);
1328 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001329}
1330
Mathias Agopian13127d82013-03-05 17:47:11 -08001331void Layer::setFiltering(bool filtering) {
1332 mFiltering = filtering;
1333}
1334
1335bool Layer::getFiltering() const {
1336 return mFiltering;
1337}
1338
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001339// As documented in libhardware header, formats in the range
1340// 0x100 - 0x1FF are specific to the HAL implementation, and
1341// are known to have no alpha channel
1342// TODO: move definition for device-specific range into
1343// hardware.h, instead of using hard-coded values here.
1344#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1345
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001346bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001347 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1348 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001349 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001350 switch (format) {
1351 case HAL_PIXEL_FORMAT_RGBA_8888:
1352 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001353 case HAL_PIXEL_FORMAT_RGBA_FP16:
Romain Guy541f2262017-02-10 18:50:17 -08001354 case HAL_PIXEL_FORMAT_RGBA_1010102:
Mathias Agopiandd533712013-07-26 15:31:39 -07001355 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001356 }
1357 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001358 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001359}
1360
Mathias Agopian13127d82013-03-05 17:47:11 -08001361// ----------------------------------------------------------------------------
1362// local state
1363// ----------------------------------------------------------------------------
1364
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001365static void boundPoint(vec2* point, const Rect& crop) {
1366 if (point->x < crop.left) {
1367 point->x = crop.left;
1368 }
1369 if (point->x > crop.right) {
1370 point->x = crop.right;
1371 }
1372 if (point->y < crop.top) {
1373 point->y = crop.top;
1374 }
1375 if (point->y > crop.bottom) {
1376 point->y = crop.bottom;
1377 }
1378}
1379
Dan Stozac7014012014-02-14 15:03:43 -08001380void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1381 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001382{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001383 const Layer::State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001384 const Transform hwTransform(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001385 const uint32_t hw_h = hw->getHeight();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001386 Rect win = computeBounds();
Mathias Agopian3f844832013-08-07 21:24:32 -07001387
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001388 vec2 lt = vec2(win.left, win.top);
1389 vec2 lb = vec2(win.left, win.bottom);
1390 vec2 rb = vec2(win.right, win.bottom);
1391 vec2 rt = vec2(win.right, win.top);
1392
Robert Carr1f0a16a2016-10-24 16:27:39 -07001393 Transform layerTransform = getTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001394 if (!useIdentityTransform) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001395 lt = layerTransform.transform(lt);
1396 lb = layerTransform.transform(lb);
1397 rb = layerTransform.transform(rb);
1398 rt = layerTransform.transform(rt);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001399 }
1400
Robert Carrb5d3d262016-03-25 15:08:13 -07001401 if (!s.finalCrop.isEmpty()) {
1402 boundPoint(&lt, s.finalCrop);
1403 boundPoint(&lb, s.finalCrop);
1404 boundPoint(&rb, s.finalCrop);
1405 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001406 }
1407
Mathias Agopianff2ed702013-09-01 21:36:12 -07001408 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001409 position[0] = hwTransform.transform(lt);
1410 position[1] = hwTransform.transform(lb);
1411 position[2] = hwTransform.transform(rb);
1412 position[3] = hwTransform.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001413 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001414 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001415 }
1416}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001417
Andy McFadden4125a4f2014-01-29 17:17:11 -08001418bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001419{
neo.hee6fd41d2017-02-17 14:35:33 +08001420 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
Mathias Agopiana67932f2011-04-20 14:20:59 -07001421 // layer's opaque flag.
neo.hee6fd41d2017-02-17 14:35:33 +08001422 if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001423 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001424 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001425
1426 // if the layer has the opaque flag, then we're always opaque,
1427 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001428 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001429}
1430
Dan Stoza23116082015-06-18 14:58:39 -07001431bool Layer::isSecure() const
1432{
1433 const Layer::State& s(mDrawingState);
1434 return (s.flags & layer_state_t::eLayerSecure);
1435}
1436
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001437bool Layer::isProtected() const
1438{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001439 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001440 return (activeBuffer != 0) &&
1441 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1442}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001443
Mathias Agopian13127d82013-03-05 17:47:11 -08001444bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001445 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001446}
1447
1448bool Layer::isCropped() const {
1449 return !mCurrentCrop.isEmpty();
1450}
1451
1452bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1453 return mNeedsFiltering || hw->needsFiltering();
1454}
1455
1456void Layer::setVisibleRegion(const Region& visibleRegion) {
1457 // always called from main thread
1458 this->visibleRegion = visibleRegion;
1459}
1460
1461void Layer::setCoveredRegion(const Region& coveredRegion) {
1462 // always called from main thread
1463 this->coveredRegion = coveredRegion;
1464}
1465
1466void Layer::setVisibleNonTransparentRegion(const Region&
1467 setVisibleNonTransparentRegion) {
1468 // always called from main thread
1469 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1470}
1471
1472// ----------------------------------------------------------------------------
1473// transaction
1474// ----------------------------------------------------------------------------
1475
Dan Stoza7dde5992015-05-22 09:51:44 -07001476void Layer::pushPendingState() {
1477 if (!mCurrentState.modified) {
1478 return;
1479 }
1480
Dan Stoza7dde5992015-05-22 09:51:44 -07001481 // If this transaction is waiting on the receipt of a frame, generate a sync
1482 // point and send it to the remote layer.
Robert Carr0d480722017-01-10 16:42:54 -08001483 if (mCurrentState.barrierLayer != nullptr) {
1484 sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1485 if (barrierLayer == nullptr) {
1486 ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
Dan Stoza7dde5992015-05-22 09:51:44 -07001487 // If we can't promote the layer we are intended to wait on,
1488 // then it is expired or otherwise invalid. Allow this transaction
1489 // to be applied as per normal (no synchronization).
Robert Carr0d480722017-01-10 16:42:54 -08001490 mCurrentState.barrierLayer = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001491 } else {
1492 auto syncPoint = std::make_shared<SyncPoint>(
1493 mCurrentState.frameNumber);
Robert Carr0d480722017-01-10 16:42:54 -08001494 if (barrierLayer->addSyncPoint(syncPoint)) {
Dan Stozacac35382016-01-27 12:21:06 -08001495 mRemoteSyncPoints.push_back(std::move(syncPoint));
1496 } else {
1497 // We already missed the frame we're supposed to synchronize
1498 // on, so go ahead and apply the state update
Robert Carr0d480722017-01-10 16:42:54 -08001499 mCurrentState.barrierLayer = nullptr;
Dan Stozacac35382016-01-27 12:21:06 -08001500 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001501 }
1502
Dan Stoza7dde5992015-05-22 09:51:44 -07001503 // Wake us up to check if the frame has been received
1504 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001505 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001506 }
1507 mPendingStates.push_back(mCurrentState);
Dan Stozaf7ba41a2017-05-10 15:11:11 -07001508 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
Dan Stoza7dde5992015-05-22 09:51:44 -07001509}
1510
Pablo Ceballos05289c22016-04-14 15:49:55 -07001511void Layer::popPendingState(State* stateToCommit) {
1512 auto oldFlags = stateToCommit->flags;
1513 *stateToCommit = mPendingStates[0];
1514 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1515 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001516
1517 mPendingStates.removeAt(0);
Dan Stozaf7ba41a2017-05-10 15:11:11 -07001518 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
Dan Stoza7dde5992015-05-22 09:51:44 -07001519}
1520
Pablo Ceballos05289c22016-04-14 15:49:55 -07001521bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001522 bool stateUpdateAvailable = false;
1523 while (!mPendingStates.empty()) {
Robert Carr0d480722017-01-10 16:42:54 -08001524 if (mPendingStates[0].barrierLayer != nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001525 if (mRemoteSyncPoints.empty()) {
1526 // If we don't have a sync point for this, apply it anyway. It
1527 // will be visually wrong, but it should keep us from getting
1528 // into too much trouble.
1529 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001530 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001531 stateUpdateAvailable = true;
1532 continue;
1533 }
1534
Dan Stozacac35382016-01-27 12:21:06 -08001535 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1536 mPendingStates[0].frameNumber) {
1537 ALOGE("[%s] Unexpected sync point frame number found",
1538 mName.string());
1539
1540 // Signal our end of the sync point and then dispose of it
1541 mRemoteSyncPoints.front()->setTransactionApplied();
1542 mRemoteSyncPoints.pop_front();
1543 continue;
1544 }
1545
Dan Stoza7dde5992015-05-22 09:51:44 -07001546 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1547 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001548 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001549 stateUpdateAvailable = true;
1550
1551 // Signal our end of the sync point and then dispose of it
1552 mRemoteSyncPoints.front()->setTransactionApplied();
1553 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001554 } else {
1555 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001556 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001557 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001558 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001559 stateUpdateAvailable = true;
1560 }
1561 }
1562
1563 // If we still have pending updates, wake SurfaceFlinger back up and point
1564 // it at this layer so we can process them
1565 if (!mPendingStates.empty()) {
1566 setTransactionFlags(eTransactionNeeded);
1567 mFlinger->setTransactionFlags(eTraversalNeeded);
1568 }
1569
1570 mCurrentState.modified = false;
1571 return stateUpdateAvailable;
1572}
1573
1574void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001575 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001576 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001577 Mutex::Autolock lock(mLocalSyncPointMutex);
1578 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001579 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001580 point->setFrameAvailable();
1581 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001582 }
1583}
1584
Mathias Agopian13127d82013-03-05 17:47:11 -08001585uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001586 ATRACE_CALL();
1587
Dan Stoza7dde5992015-05-22 09:51:44 -07001588 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001589 Layer::State c = getCurrentState();
1590 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001591 return 0;
1592 }
1593
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001594 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001595
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001596 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1597 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001598
1599 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001600 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001601 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001602 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001603 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001604 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001605 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001606 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001607 this, getName().string(), mCurrentTransform,
1608 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001609 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001610 c.crop.left,
1611 c.crop.top,
1612 c.crop.right,
1613 c.crop.bottom,
1614 c.crop.getWidth(),
1615 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001616 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001617 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001618 s.crop.left,
1619 s.crop.top,
1620 s.crop.right,
1621 s.crop.bottom,
1622 s.crop.getWidth(),
1623 s.crop.getHeight(),
1624 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001625
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001626 // record the new size, form this point on, when the client request
1627 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001628 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001629 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001630 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001631
Robert Carr82364e32016-05-15 11:27:47 -07001632 const bool resizePending = (c.requested.w != c.active.w) ||
1633 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001634 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001635 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001636 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001637 // if we have a pending resize, unless we are in fixed-size mode.
1638 // the drawing state will be updated only once we receive a buffer
1639 // with the correct size.
1640 //
1641 // in particular, we want to make sure the clip (which is part
1642 // of the geometry state) is latched together with the size but is
1643 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001644 //
1645 // If a sideband stream is attached, however, we want to skip this
1646 // optimization so that transactions aren't missed when a buffer
1647 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001648
1649 flags |= eDontUpdateGeometryState;
1650 }
1651 }
1652
Robert Carr7bf247e2017-05-18 14:02:49 -07001653 // Here we apply various requested geometry states, depending on our
1654 // latching configuration. See Layer.h for a detailed discussion of
1655 // how geometry latching is controlled.
1656 if (!(flags & eDontUpdateGeometryState)) {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001657 Layer::State& editCurrentState(getCurrentState());
Robert Carr7bf247e2017-05-18 14:02:49 -07001658
1659 // If mFreezeGeometryUpdates is true we are in the setGeometryAppliesWithResize
1660 // mode, which causes attributes which normally latch regardless of scaling mode,
1661 // to be delayed. We copy the requested state to the active state making sure
1662 // to respect these rules (again see Layer.h for a detailed discussion).
1663 //
1664 // There is an awkward asymmetry in the handling of the crop states in the position
1665 // states, as can be seen below. Largely this arises from position and transform
1666 // being stored in the same data structure while having different latching rules.
1667 // b/38182305
1668 //
1669 // Careful that "c" and editCurrentState may not begin as equivalent due to
1670 // applyPendingStates in the presence of deferred transactions.
1671 if (mFreezeGeometryUpdates) {
Robert Carr82364e32016-05-15 11:27:47 -07001672 float tx = c.active.transform.tx();
1673 float ty = c.active.transform.ty();
1674 c.active = c.requested;
1675 c.active.transform.set(tx, ty);
1676 editCurrentState.active = c.active;
1677 } else {
1678 editCurrentState.active = editCurrentState.requested;
1679 c.active = c.requested;
1680 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001681 }
1682
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001683 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001684 // invalidate and recompute the visible regions if needed
1685 flags |= Layer::eVisibleRegion;
1686 }
1687
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001688 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001689 // invalidate and recompute the visible regions if needed
1690 flags |= eVisibleRegion;
1691 this->contentDirty = true;
1692
1693 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001694 const uint8_t type = c.active.transform.getType();
1695 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001696 (type >= Transform::SCALE));
1697 }
1698
Dan Stozac8145172016-04-28 16:29:06 -07001699 // If the layer is hidden, signal and clear out all local sync points so
1700 // that transactions for layers depending on this layer's frames becoming
1701 // visible are not blocked
1702 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001703 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001704 }
1705
Mathias Agopian13127d82013-03-05 17:47:11 -08001706 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001707 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001708 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001709}
1710
Pablo Ceballos05289c22016-04-14 15:49:55 -07001711void Layer::commitTransaction(const State& stateToCommit) {
1712 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001713}
1714
Mathias Agopian13127d82013-03-05 17:47:11 -08001715uint32_t Layer::getTransactionFlags(uint32_t flags) {
1716 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1717}
1718
1719uint32_t Layer::setTransactionFlags(uint32_t flags) {
1720 return android_atomic_or(flags, &mTransactionFlags);
1721}
1722
Robert Carr82364e32016-05-15 11:27:47 -07001723bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001724 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001725 return false;
1726 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001727
1728 // We update the requested and active position simultaneously because
1729 // we want to apply the position portion of the transform matrix immediately,
1730 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001731 mCurrentState.requested.transform.set(x, y);
Robert Carr7bf247e2017-05-18 14:02:49 -07001732 if (immediate && !mFreezeGeometryUpdates) {
1733 // Here we directly update the active state
1734 // unlike other setters, because we store it within
1735 // the transform, but use different latching rules.
1736 // b/38182305
Robert Carr82364e32016-05-15 11:27:47 -07001737 mCurrentState.active.transform.set(x, y);
1738 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001739 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001740
Dan Stoza7dde5992015-05-22 09:51:44 -07001741 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001742 setTransactionFlags(eTransactionNeeded);
1743 return true;
1744}
Robert Carr82364e32016-05-15 11:27:47 -07001745
Robert Carr1f0a16a2016-10-24 16:27:39 -07001746bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1747 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1748 if (idx < 0) {
1749 return false;
1750 }
1751 if (childLayer->setLayer(z)) {
1752 mCurrentChildren.removeAt(idx);
1753 mCurrentChildren.add(childLayer);
1754 }
1755 return true;
1756}
1757
Robert Carrae060832016-11-28 10:51:00 -08001758bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001759 if (mCurrentState.z == z)
1760 return false;
1761 mCurrentState.sequence++;
1762 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001763 mCurrentState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001764
1765 // Discard all relative layering.
1766 if (mCurrentState.zOrderRelativeOf != nullptr) {
1767 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1768 if (strongRelative != nullptr) {
1769 strongRelative->removeZOrderRelative(this);
1770 }
1771 mCurrentState.zOrderRelativeOf = nullptr;
1772 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001773 setTransactionFlags(eTransactionNeeded);
1774 return true;
1775}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001776
Robert Carrdb66e622017-04-10 16:55:57 -07001777void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1778 mCurrentState.zOrderRelatives.remove(relative);
1779 mCurrentState.sequence++;
1780 mCurrentState.modified = true;
1781 setTransactionFlags(eTransactionNeeded);
1782}
1783
1784void Layer::addZOrderRelative(const wp<Layer>& relative) {
1785 mCurrentState.zOrderRelatives.add(relative);
1786 mCurrentState.modified = true;
1787 mCurrentState.sequence++;
1788 setTransactionFlags(eTransactionNeeded);
1789}
1790
1791bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1792 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1793 if (handle == nullptr) {
1794 return false;
1795 }
1796 sp<Layer> relative = handle->owner.promote();
1797 if (relative == nullptr) {
1798 return false;
1799 }
1800
1801 mCurrentState.sequence++;
1802 mCurrentState.modified = true;
1803 mCurrentState.z = z;
1804
1805 mCurrentState.zOrderRelativeOf = relative;
1806 relative->addZOrderRelative(this);
1807
1808 setTransactionFlags(eTransactionNeeded);
1809
1810 return true;
1811}
1812
Mathias Agopian13127d82013-03-05 17:47:11 -08001813bool Layer::setSize(uint32_t w, uint32_t h) {
1814 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1815 return false;
1816 mCurrentState.requested.w = w;
1817 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001818 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001819 setTransactionFlags(eTransactionNeeded);
1820 return true;
1821}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001822#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001823bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001824#else
1825bool Layer::setAlpha(uint8_t alpha) {
1826#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001827 if (mCurrentState.alpha == alpha)
1828 return false;
1829 mCurrentState.sequence++;
1830 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001831 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001832 setTransactionFlags(eTransactionNeeded);
1833 return true;
1834}
1835bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1836 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001837 mCurrentState.requested.transform.set(
Robert Carrcb6e1e32017-02-21 19:48:26 -08001838 matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001839 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001840 setTransactionFlags(eTransactionNeeded);
1841 return true;
1842}
1843bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001844 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001845 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001846 setTransactionFlags(eTransactionNeeded);
1847 return true;
1848}
1849bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1850 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1851 if (mCurrentState.flags == newFlags)
1852 return false;
1853 mCurrentState.sequence++;
1854 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001855 mCurrentState.mask = mask;
1856 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001857 setTransactionFlags(eTransactionNeeded);
1858 return true;
1859}
Robert Carr99e27f02016-06-16 15:18:02 -07001860
1861bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001862 if (mCurrentState.requestedCrop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001863 return false;
1864 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001865 mCurrentState.requestedCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001866 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr99e27f02016-06-16 15:18:02 -07001867 mCurrentState.crop = crop;
1868 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001869 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1870
Dan Stoza7dde5992015-05-22 09:51:44 -07001871 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001872 setTransactionFlags(eTransactionNeeded);
1873 return true;
1874}
Robert Carr8d5227b2017-03-16 15:41:03 -07001875
1876bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001877 if (mCurrentState.requestedFinalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001878 return false;
1879 mCurrentState.sequence++;
Robert Carr8d5227b2017-03-16 15:41:03 -07001880 mCurrentState.requestedFinalCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001881 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr8d5227b2017-03-16 15:41:03 -07001882 mCurrentState.finalCrop = crop;
1883 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001884 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1885
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001886 mCurrentState.modified = true;
1887 setTransactionFlags(eTransactionNeeded);
1888 return true;
1889}
Mathias Agopian13127d82013-03-05 17:47:11 -08001890
Robert Carrc3574f72016-03-24 12:19:32 -07001891bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1892 if (scalingMode == mOverrideScalingMode)
1893 return false;
1894 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001895 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001896 return true;
1897}
1898
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001899void Layer::setInfo(uint32_t type, uint32_t appId) {
1900 mCurrentState.appId = appId;
1901 mCurrentState.type = type;
1902 mCurrentState.modified = true;
1903 setTransactionFlags(eTransactionNeeded);
1904}
1905
Robert Carrc3574f72016-03-24 12:19:32 -07001906uint32_t Layer::getEffectiveScalingMode() const {
1907 if (mOverrideScalingMode >= 0) {
1908 return mOverrideScalingMode;
1909 }
1910 return mCurrentScalingMode;
1911}
1912
Mathias Agopian13127d82013-03-05 17:47:11 -08001913bool Layer::setLayerStack(uint32_t layerStack) {
1914 if (mCurrentState.layerStack == layerStack)
1915 return false;
1916 mCurrentState.sequence++;
1917 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001918 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001919 setTransactionFlags(eTransactionNeeded);
1920 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001921}
1922
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07001923bool Layer::setDataSpace(android_dataspace dataSpace) {
1924 if (mCurrentState.dataSpace == dataSpace)
1925 return false;
1926 mCurrentState.sequence++;
1927 mCurrentState.dataSpace = dataSpace;
1928 mCurrentState.modified = true;
1929 setTransactionFlags(eTransactionNeeded);
1930 return true;
1931}
1932
Courtney Goeltzenleuchter532b2632017-05-05 16:34:38 -06001933android_dataspace Layer::getDataSpace() const {
1934 return mCurrentState.dataSpace;
1935}
1936
Robert Carr1f0a16a2016-10-24 16:27:39 -07001937uint32_t Layer::getLayerStack() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07001938 auto p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001939 if (p == nullptr) {
1940 return getDrawingState().layerStack;
1941 }
1942 return p->getLayerStack();
1943}
1944
Robert Carr0d480722017-01-10 16:42:54 -08001945void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
Dan Stoza7dde5992015-05-22 09:51:44 -07001946 uint64_t frameNumber) {
Robert Carr0d480722017-01-10 16:42:54 -08001947 mCurrentState.barrierLayer = barrierLayer;
Dan Stoza7dde5992015-05-22 09:51:44 -07001948 mCurrentState.frameNumber = frameNumber;
1949 // We don't set eTransactionNeeded, because just receiving a deferral
1950 // request without any other state updates shouldn't actually induce a delay
1951 mCurrentState.modified = true;
1952 pushPendingState();
Robert Carr0d480722017-01-10 16:42:54 -08001953 mCurrentState.barrierLayer = nullptr;
Dan Stoza792e5292016-02-11 11:43:58 -08001954 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07001955 mCurrentState.modified = false;
Robert Carr0d480722017-01-10 16:42:54 -08001956}
1957
1958void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
1959 uint64_t frameNumber) {
1960 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
1961 deferTransactionUntil(handle->owner.promote(), frameNumber);
Dan Stoza7dde5992015-05-22 09:51:44 -07001962}
1963
Dan Stozaee44edd2015-03-23 15:50:23 -07001964void Layer::useSurfaceDamage() {
1965 if (mFlinger->mForceFullDamage) {
1966 surfaceDamageRegion = Region::INVALID_REGION;
1967 } else {
1968 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1969 }
1970}
1971
1972void Layer::useEmptyDamage() {
1973 surfaceDamageRegion.clear();
1974}
1975
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001976// ----------------------------------------------------------------------------
1977// pageflip handling...
1978// ----------------------------------------------------------------------------
1979
Dan Stoza6b9454d2014-11-07 16:00:59 -08001980bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001981 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07001982 return true;
1983 }
1984
Dan Stoza6b9454d2014-11-07 16:00:59 -08001985 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001986 if (mQueueItems.empty()) {
1987 return false;
1988 }
1989 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001990 nsecs_t expectedPresent =
1991 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001992
1993 // Ignore timestamps more than a second in the future
1994 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1995 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1996 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1997 expectedPresent);
1998
1999 bool isDue = timestamp < expectedPresent;
2000 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002001}
2002
Brian Andersond6927fb2016-07-23 23:37:30 -07002003bool Layer::onPreComposition(nsecs_t refreshStartTime) {
2004 if (mBufferLatched) {
2005 Mutex::Autolock lock(mFrameEventHistoryMutex);
2006 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
2007 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08002008 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08002009 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002010}
2011
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002012bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
Brian Anderson3d4039d2016-09-23 16:31:30 -07002013 const std::shared_ptr<FenceTime>& presentFence,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002014 const CompositorTiming& compositorTiming) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002015 // mFrameLatencyNeeded is true when a new frame was latched for the
2016 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08002017 if (!mFrameLatencyNeeded)
2018 return false;
2019
Fabien Sanglard28e98082016-12-05 10:19:46 -08002020 // Update mFrameEventHistory.
2021 {
2022 Mutex::Autolock lock(mFrameEventHistoryMutex);
2023 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002024 glDoneFence, presentFence, compositorTiming);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002025 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08002026
2027 // Update mFrameTracker.
2028 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
2029 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
2030
Brian Anderson3d4039d2016-09-23 16:31:30 -07002031 std::shared_ptr<FenceTime> frameReadyFence =
2032 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08002033 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002034 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002035 } else {
2036 // There was no fence for this frame, so assume that it was ready
2037 // to be presented at the desired present time.
2038 mFrameTracker.setFrameReadyTime(desiredPresentTime);
2039 }
2040
Brian Anderson3d4039d2016-09-23 16:31:30 -07002041 if (presentFence->isValid()) {
2042 mFrameTracker.setActualPresentFence(
2043 std::shared_ptr<FenceTime>(presentFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002044 } else {
2045 // The HWC doesn't support present fences, so use the refresh
2046 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002047 mFrameTracker.setActualPresentTime(
2048 mFlinger->getHwComposer().getRefreshTimestamp(
2049 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002050 }
2051
2052 mFrameTracker.advanceFrame();
2053 mFrameLatencyNeeded = false;
2054 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002055}
2056
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002057#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07002058void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Brian Anderson5ea5e592016-12-01 16:54:33 -08002059 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2060 return;
2061 }
2062
Brian Anderson3d4039d2016-09-23 16:31:30 -07002063 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002064 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002065 mReleaseTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002066 mReleaseTimeline.push(releaseFenceTime);
2067
2068 Mutex::Autolock lock(mFrameEventHistoryMutex);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002069 if (mPreviousFrameNumber != 0) {
2070 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2071 dequeueReadyTime, std::move(releaseFenceTime));
2072 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002073}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002074#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002075
Robert Carr1f0a16a2016-10-24 16:27:39 -07002076bool Layer::isHiddenByPolicy() const {
2077 const Layer::State& s(mDrawingState);
Chia-I Wue41dbe62017-06-13 14:10:56 -07002078 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002079 if (parent != nullptr && parent->isHiddenByPolicy()) {
2080 return true;
2081 }
2082 return s.flags & layer_state_t::eLayerHidden;
2083}
2084
Mathias Agopianda27af92012-09-13 18:17:13 -07002085bool Layer::isVisible() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002086#ifdef USE_HWC2
Robert Carr6452f122017-03-21 10:41:29 -07002087 return !(isHiddenByPolicy()) && getAlpha() > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08002088 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002089#else
Robert Carr6452f122017-03-21 10:41:29 -07002090 return !(isHiddenByPolicy()) && getAlpha()
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002091 && (mActiveBuffer != NULL || mSidebandStream != NULL);
2092#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07002093}
2094
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002095bool Layer::allTransactionsSignaled() {
2096 auto headFrameNumber = getHeadFrameNumber();
2097 bool matchingFramesFound = false;
2098 bool allTransactionsApplied = true;
2099 Mutex::Autolock lock(mLocalSyncPointMutex);
2100
2101 for (auto& point : mLocalSyncPoints) {
2102 if (point->getFrameNumber() > headFrameNumber) {
2103 break;
2104 }
2105 matchingFramesFound = true;
2106
2107 if (!point->frameIsAvailable()) {
2108 // We haven't notified the remote layer that the frame for
2109 // this point is available yet. Notify it now, and then
2110 // abort this attempt to latch.
2111 point->setFrameAvailable();
2112 allTransactionsApplied = false;
2113 break;
2114 }
2115
2116 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2117 }
2118 return !matchingFramesFound || allTransactionsApplied;
2119}
2120
Brian Andersond6927fb2016-07-23 23:37:30 -07002121Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002122{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08002123 ATRACE_CALL();
2124
Jesse Hall399184a2014-03-03 15:42:54 -08002125 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2126 // mSidebandStreamChanged was true
2127 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07002128 if (mSidebandStream != NULL) {
2129 setTransactionFlags(eTransactionNeeded);
2130 mFlinger->setTransactionFlags(eTraversalNeeded);
2131 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07002132 recomputeVisibleRegions = true;
2133
2134 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07002135 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08002136 }
2137
Mathias Agopian4fec8732012-06-29 14:12:52 -07002138 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07002139 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2140 return outDirtyRegion;
2141 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002142
Fabien Sanglard223eb912016-10-13 10:15:06 -07002143 // if we've already called updateTexImage() without going through
2144 // a composition step, we have to skip this layer at this point
2145 // because we cannot call updateTeximage() without a corresponding
2146 // compositionComplete() call.
2147 // we'll trigger an update in onPreComposition().
2148 if (mRefreshPending) {
2149 return outDirtyRegion;
2150 }
2151
2152 // If the head buffer's acquire fence hasn't signaled yet, return and
2153 // try again later
2154 if (!headFenceHasSignaled()) {
2155 mFlinger->signalLayerUpdate();
2156 return outDirtyRegion;
2157 }
2158
2159 // Capture the old state of the layer for comparisons later
2160 const State& s(getDrawingState());
2161 const bool oldOpacity = isOpaque(s);
2162 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2163
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002164 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002165 mFlinger->signalLayerUpdate();
2166 return outDirtyRegion;
2167 }
2168
2169 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2170 // of the buffer queue isn't modified when the buffer queue is returning
2171 // BufferItem's that weren't actually queued. This can happen in shared
2172 // buffer mode.
2173 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002174 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2175 getProducerStickyTransform() != 0, mName.string(),
Robert Carr7bf247e2017-05-18 14:02:49 -07002176 mOverrideScalingMode, mFreezeGeometryUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002177 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2178 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2179 mLastFrameNumberReceived);
2180 if (updateResult == BufferQueue::PRESENT_LATER) {
2181 // Producer doesn't want buffer to be displayed yet. Signal a
2182 // layer update so we check again at the next opportunity.
2183 mFlinger->signalLayerUpdate();
2184 return outDirtyRegion;
2185 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2186 // If the buffer has been rejected, remove it from the shadow queue
2187 // and return early
2188 if (queuedBuffer) {
2189 Mutex::Autolock lock(mQueueItemLock);
2190 mQueueItems.removeAt(0);
2191 android_atomic_dec(&mQueuedFrames);
2192 }
2193 return outDirtyRegion;
2194 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2195 // This can occur if something goes wrong when trying to create the
2196 // EGLImage for this buffer. If this happens, the buffer has already
2197 // been released, so we need to clean up the queue and bug out
2198 // early.
2199 if (queuedBuffer) {
2200 Mutex::Autolock lock(mQueueItemLock);
2201 mQueueItems.clear();
2202 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002203 }
2204
Fabien Sanglard223eb912016-10-13 10:15:06 -07002205 // Once we have hit this state, the shadow queue may no longer
2206 // correctly reflect the incoming BufferQueue's contents, so even if
2207 // updateTexImage starts working, the only safe course of action is
2208 // to continue to ignore updates.
2209 mUpdateTexImageFailed = true;
2210
2211 return outDirtyRegion;
2212 }
2213
2214 if (queuedBuffer) {
2215 // Autolock scope
2216 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2217
2218 Mutex::Autolock lock(mQueueItemLock);
2219
2220 // Remove any stale buffers that have been dropped during
2221 // updateTexImage
2222 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2223 mQueueItems.removeAt(0);
2224 android_atomic_dec(&mQueuedFrames);
2225 }
2226
2227 mQueueItems.removeAt(0);
2228 }
2229
2230
2231 // Decrement the queued-frames count. Signal another event if we
2232 // have more frames pending.
2233 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2234 || mAutoRefresh) {
2235 mFlinger->signalLayerUpdate();
2236 }
2237
Fabien Sanglard223eb912016-10-13 10:15:06 -07002238 // update the active buffer
Chia-I Wu06d63de2017-01-04 14:58:51 +08002239 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2240 &mActiveBufferSlot);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002241 if (mActiveBuffer == NULL) {
2242 // this can only happen if the very first buffer was rejected.
2243 return outDirtyRegion;
2244 }
2245
Brian Andersond6927fb2016-07-23 23:37:30 -07002246 mBufferLatched = true;
2247 mPreviousFrameNumber = mCurrentFrameNumber;
2248 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2249
2250 {
2251 Mutex::Autolock lock(mFrameEventHistoryMutex);
2252 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2253#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002254 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002255 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002256 mReleaseTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002257 mReleaseTimeline.push(releaseFenceTime);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002258 if (mPreviousFrameNumber != 0) {
2259 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2260 latchTime, std::move(releaseFenceTime));
2261 }
Brian Andersond6927fb2016-07-23 23:37:30 -07002262#endif
2263 }
2264
Fabien Sanglard223eb912016-10-13 10:15:06 -07002265 mRefreshPending = true;
2266 mFrameLatencyNeeded = true;
2267 if (oldActiveBuffer == NULL) {
2268 // the first time we receive a buffer, we need to trigger a
2269 // geometry invalidation.
2270 recomputeVisibleRegions = true;
2271 }
2272
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002273 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2274
Fabien Sanglard223eb912016-10-13 10:15:06 -07002275 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2276 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2277 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2278 if ((crop != mCurrentCrop) ||
2279 (transform != mCurrentTransform) ||
2280 (scalingMode != mCurrentScalingMode))
2281 {
2282 mCurrentCrop = crop;
2283 mCurrentTransform = transform;
2284 mCurrentScalingMode = scalingMode;
2285 recomputeVisibleRegions = true;
2286 }
2287
2288 if (oldActiveBuffer != NULL) {
2289 uint32_t bufWidth = mActiveBuffer->getWidth();
2290 uint32_t bufHeight = mActiveBuffer->getHeight();
2291 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2292 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002293 recomputeVisibleRegions = true;
2294 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002295 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002296
Fabien Sanglard223eb912016-10-13 10:15:06 -07002297 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2298 if (oldOpacity != isOpaque(s)) {
2299 recomputeVisibleRegions = true;
2300 }
Dan Stozacac35382016-01-27 12:21:06 -08002301
Fabien Sanglard223eb912016-10-13 10:15:06 -07002302 // Remove any sync points corresponding to the buffer which was just
2303 // latched
2304 {
2305 Mutex::Autolock lock(mLocalSyncPointMutex);
2306 auto point = mLocalSyncPoints.begin();
2307 while (point != mLocalSyncPoints.end()) {
2308 if (!(*point)->frameIsAvailable() ||
2309 !(*point)->transactionIsApplied()) {
2310 // This sync point must have been added since we started
2311 // latching. Don't drop it yet.
2312 ++point;
2313 continue;
2314 }
2315
2316 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2317 point = mLocalSyncPoints.erase(point);
2318 } else {
2319 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002320 }
2321 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002322 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002323
2324 // FIXME: postedRegion should be dirty & bounds
2325 Region dirtyRegion(Rect(s.active.w, s.active.h));
2326
2327 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002328 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002329
Mathias Agopian4fec8732012-06-29 14:12:52 -07002330 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002331}
2332
Mathias Agopiana67932f2011-04-20 14:20:59 -07002333uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002334{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002335 // TODO: should we do something special if mSecure is set?
2336 if (mProtectedByApp) {
2337 // need a hardware-protected path to external video sink
2338 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002339 }
Riley Andrews03414a12014-07-01 14:22:59 -07002340 if (mPotentialCursor) {
2341 usage |= GraphicBuffer::USAGE_CURSOR;
2342 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002343 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002344 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002345}
2346
Mathias Agopian84300952012-11-21 16:02:13 -08002347void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002348 uint32_t orientation = 0;
2349 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002350 // The transform hint is used to improve performance, but we can
2351 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002352 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002353 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002354 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002355 if (orientation & Transform::ROT_INVALID) {
2356 orientation = 0;
2357 }
2358 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002359 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002360}
2361
Mathias Agopian13127d82013-03-05 17:47:11 -08002362// ----------------------------------------------------------------------------
2363// debugging
2364// ----------------------------------------------------------------------------
2365
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002366void Layer::dump(String8& result, Colorizer& colorizer) const
Mathias Agopian13127d82013-03-05 17:47:11 -08002367{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002368 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08002369
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002370 colorizer.colorize(result, Colorizer::GREEN);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002371 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002372 "+ %s %p (%s)\n",
2373 getTypeId(), this, getName().string());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002374 colorizer.reset(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002375
Mathias Agopian2ca79392013-04-02 18:30:32 -07002376 s.activeTransparentRegion.dump(result, "transparentRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002377 visibleRegion.dump(result, "visibleRegion");
Dan Stozaee44edd2015-03-23 15:50:23 -07002378 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002379 sp<Client> client(mClientRef.promote());
Courtney Goeltzenleuchter36c44dc2017-04-14 09:33:16 -06002380 PixelFormat pf = PIXEL_FORMAT_UNKNOWN;
2381 const sp<GraphicBuffer>& buffer(getActiveBuffer());
2382 if (buffer != NULL) {
2383 pf = buffer->getPixelFormat();
2384 }
Mathias Agopian13127d82013-03-05 17:47:11 -08002385
chaviw1acbec72017-07-27 15:28:26 -07002386 sp<Layer> parent = getParent();
2387
Mathias Agopian74d211a2013-04-22 16:55:35 +02002388 result.appendFormat( " "
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002389 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2390 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
Mathias Agopian13127d82013-03-05 17:47:11 -08002391 "isOpaque=%1d, invalidate=%1d, "
Courtney Goeltzenleuchter36c44dc2017-04-14 09:33:16 -06002392 "dataspace=%s, pixelformat=%s "
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002393#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08002394 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002395#else
2396 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2397#endif
chaviw1acbec72017-07-27 15:28:26 -07002398 " client=%p parent=%s\n",
Robert Carr1f0a16a2016-10-24 16:27:39 -07002399 getLayerStack(), s.z,
2400 s.active.transform.tx(), s.active.transform.ty(),
2401 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07002402 s.crop.left, s.crop.top,
2403 s.crop.right, s.crop.bottom,
2404 s.finalCrop.left, s.finalCrop.top,
2405 s.finalCrop.right, s.finalCrop.bottom,
Andy McFadden4125a4f2014-01-29 17:17:11 -08002406 isOpaque(s), contentDirty,
Courtney Goeltzenleuchter36c44dc2017-04-14 09:33:16 -06002407 dataspaceDetails(getDataSpace()).c_str(), decodePixelFormat(pf).c_str(),
Mathias Agopian13127d82013-03-05 17:47:11 -08002408 s.alpha, s.flags,
Robert Carr3dcabfa2016-03-01 18:36:58 -08002409 s.active.transform[0][0], s.active.transform[0][1],
2410 s.active.transform[1][0], s.active.transform[1][1],
chaviw1acbec72017-07-27 15:28:26 -07002411 client.get(), parent == nullptr ? "none" : parent->getName().string());
Mathias Agopian13127d82013-03-05 17:47:11 -08002412
2413 sp<const GraphicBuffer> buf0(mActiveBuffer);
2414 uint32_t w0=0, h0=0, s0=0, f0=0;
2415 if (buf0 != 0) {
2416 w0 = buf0->getWidth();
2417 h0 = buf0->getHeight();
2418 s0 = buf0->getStride();
2419 f0 = buf0->format;
2420 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02002421 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002422 " "
2423 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2424 " queued-frames=%d, mRefreshPending=%d\n",
2425 mFormat, w0, h0, s0,f0,
2426 mQueuedFrames, mRefreshPending);
2427
Mathias Agopian13127d82013-03-05 17:47:11 -08002428 if (mSurfaceFlingerConsumer != 0) {
Colin Cross3d1d2802016-09-26 18:10:16 -07002429 mSurfaceFlingerConsumer->dumpState(result, " ");
Mathias Agopian13127d82013-03-05 17:47:11 -08002430 }
2431}
2432
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002433#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002434void Layer::miniDumpHeader(String8& result) {
2435 result.append("----------------------------------------");
2436 result.append("---------------------------------------\n");
2437 result.append(" Layer name\n");
2438 result.append(" Z | ");
2439 result.append(" Comp Type | ");
2440 result.append(" Disp Frame (LTRB) | ");
2441 result.append(" Source Crop (LTRB)\n");
2442 result.append("----------------------------------------");
2443 result.append("---------------------------------------\n");
2444}
2445
2446void Layer::miniDump(String8& result, int32_t hwcId) const {
2447 if (mHwcLayers.count(hwcId) == 0) {
2448 return;
2449 }
2450
2451 String8 name;
2452 if (mName.length() > 77) {
2453 std::string shortened;
2454 shortened.append(mName.string(), 36);
2455 shortened.append("[...]");
2456 shortened.append(mName.string() + (mName.length() - 36), 36);
2457 name = shortened.c_str();
2458 } else {
2459 name = mName;
2460 }
2461
2462 result.appendFormat(" %s\n", name.string());
2463
2464 const Layer::State& layerState(getDrawingState());
2465 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2466 result.appendFormat(" %10u | ", layerState.z);
2467 result.appendFormat("%10s | ",
2468 to_string(getCompositionType(hwcId)).c_str());
2469 const Rect& frame = hwcInfo.displayFrame;
2470 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2471 frame.right, frame.bottom);
Dan Stoza5a423ea2017-02-16 14:10:39 -08002472 const FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002473 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2474 crop.right, crop.bottom);
2475
2476 result.append("- - - - - - - - - - - - - - - - - - - - ");
2477 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2478}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002479#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002480
Svetoslavd85084b2014-03-20 10:28:31 -07002481void Layer::dumpFrameStats(String8& result) const {
2482 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002483}
2484
Svetoslavd85084b2014-03-20 10:28:31 -07002485void Layer::clearFrameStats() {
2486 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002487}
2488
Jamie Gennis6547ff42013-07-16 20:12:42 -07002489void Layer::logFrameStats() {
2490 mFrameTracker.logAndResetStats(mName);
2491}
2492
Svetoslavd85084b2014-03-20 10:28:31 -07002493void Layer::getFrameStats(FrameStats* outStats) const {
2494 mFrameTracker.getStats(outStats);
2495}
2496
Brian Andersond6927fb2016-07-23 23:37:30 -07002497void Layer::dumpFrameEvents(String8& result) {
2498 result.appendFormat("- Layer %s (%s, %p)\n",
2499 getName().string(), getTypeId(), this);
2500 Mutex::Autolock lock(mFrameEventHistoryMutex);
2501 mFrameEventHistory.checkFencesForCompletion();
2502 mFrameEventHistory.dump(result);
2503}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002504
Brian Anderson5ea5e592016-12-01 16:54:33 -08002505void Layer::onDisconnect() {
2506 Mutex::Autolock lock(mFrameEventHistoryMutex);
2507 mFrameEventHistory.onDisconnect();
2508}
2509
Brian Anderson3890c392016-07-25 12:48:08 -07002510void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2511 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002512 Mutex::Autolock lock(mFrameEventHistoryMutex);
2513 if (newTimestamps) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002514 // If there are any unsignaled fences in the aquire timeline at this
2515 // point, the previously queued frame hasn't been latched yet. Go ahead
2516 // and try to get the signal time here so the syscall is taken out of
2517 // the main thread's critical path.
2518 mAcquireTimeline.updateSignalTimes();
2519 // Push the new fence after updating since it's likely still pending.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002520 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002521 mFrameEventHistory.addQueue(*newTimestamps);
2522 }
2523
Brian Anderson3890c392016-07-25 12:48:08 -07002524 if (outDelta) {
2525 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002526 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002527}
Dan Stozae77c7662016-05-13 11:37:28 -07002528
2529std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2530 bool forceFlush) {
2531 std::vector<OccupancyTracker::Segment> history;
2532 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2533 &history);
2534 if (result != NO_ERROR) {
2535 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2536 result);
2537 return {};
2538 }
2539 return history;
2540}
2541
Robert Carr367c5682016-06-20 11:55:28 -07002542bool Layer::getTransformToDisplayInverse() const {
2543 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2544}
2545
Chia-I Wu98f1c102017-05-30 14:54:08 -07002546size_t Layer::getChildrenCount() const {
2547 size_t count = 0;
2548 for (const sp<Layer>& child : mCurrentChildren) {
2549 count += 1 + child->getChildrenCount();
2550 }
2551 return count;
2552}
2553
Robert Carr1f0a16a2016-10-24 16:27:39 -07002554void Layer::addChild(const sp<Layer>& layer) {
2555 mCurrentChildren.add(layer);
2556 layer->setParent(this);
2557}
2558
2559ssize_t Layer::removeChild(const sp<Layer>& layer) {
2560 layer->setParent(nullptr);
2561 return mCurrentChildren.remove(layer);
2562}
2563
Robert Carr1db73f62016-12-21 12:58:51 -08002564bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2565 sp<Handle> handle = nullptr;
2566 sp<Layer> newParent = nullptr;
2567 if (newParentHandle == nullptr) {
2568 return false;
2569 }
2570 handle = static_cast<Handle*>(newParentHandle.get());
2571 newParent = handle->owner.promote();
2572 if (newParent == nullptr) {
2573 ALOGE("Unable to promote Layer handle");
2574 return false;
2575 }
2576
2577 for (const sp<Layer>& child : mCurrentChildren) {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002578 newParent->addChild(child);
Robert Carr1db73f62016-12-21 12:58:51 -08002579
2580 sp<Client> client(child->mClientRef.promote());
2581 if (client != nullptr) {
2582 client->setParentLayer(newParent);
2583 }
2584 }
2585 mCurrentChildren.clear();
2586
2587 return true;
2588}
2589
Robert Carr9524cb32017-02-13 11:32:32 -08002590bool Layer::detachChildren() {
Dan Stoza412903f2017-04-27 13:42:17 -07002591 traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
Robert Carr9524cb32017-02-13 11:32:32 -08002592 if (child == this) {
2593 return;
2594 }
2595
2596 sp<Client> client(child->mClientRef.promote());
2597 if (client != nullptr) {
2598 client->detachLayer(child);
2599 }
2600 });
2601
2602 return true;
2603}
2604
Robert Carr1f0a16a2016-10-24 16:27:39 -07002605void Layer::setParent(const sp<Layer>& layer) {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002606 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002607}
2608
2609void Layer::clearSyncPoints() {
2610 for (const auto& child : mCurrentChildren) {
2611 child->clearSyncPoints();
2612 }
2613
2614 Mutex::Autolock lock(mLocalSyncPointMutex);
2615 for (auto& point : mLocalSyncPoints) {
2616 point->setFrameAvailable();
2617 }
2618 mLocalSyncPoints.clear();
2619}
2620
2621int32_t Layer::getZ() const {
2622 return mDrawingState.z;
2623}
2624
Dan Stoza412903f2017-04-27 13:42:17 -07002625LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2626 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2627 "makeTraversalList received invalid stateSet");
2628 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2629 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2630 const State& state = useDrawing ? mDrawingState : mCurrentState;
2631
2632 if (state.zOrderRelatives.size() == 0) {
2633 return children;
Robert Carrdb66e622017-04-10 16:55:57 -07002634 }
2635 LayerVector traverse;
2636
Dan Stoza412903f2017-04-27 13:42:17 -07002637 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07002638 sp<Layer> strongRelative = weakRelative.promote();
2639 if (strongRelative != nullptr) {
2640 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07002641 }
2642 }
2643
Dan Stoza412903f2017-04-27 13:42:17 -07002644 for (const sp<Layer>& child : children) {
Robert Carrdb66e622017-04-10 16:55:57 -07002645 traverse.add(child);
2646 }
2647
2648 return traverse;
2649}
2650
Robert Carr1f0a16a2016-10-24 16:27:39 -07002651/**
Robert Carrdb66e622017-04-10 16:55:57 -07002652 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002653 */
Dan Stoza412903f2017-04-27 13:42:17 -07002654void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2655 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002656
Robert Carr1f0a16a2016-10-24 16:27:39 -07002657 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002658 for (; i < list.size(); i++) {
2659 const auto& relative = list[i];
2660 if (relative->getZ() >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002661 break;
Robert Carrdb66e622017-04-10 16:55:57 -07002662 }
Dan Stoza412903f2017-04-27 13:42:17 -07002663 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002664 }
Dan Stoza412903f2017-04-27 13:42:17 -07002665 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07002666 for (; i < list.size(); i++) {
2667 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002668 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002669 }
2670}
2671
2672/**
Robert Carrdb66e622017-04-10 16:55:57 -07002673 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002674 */
Dan Stoza412903f2017-04-27 13:42:17 -07002675void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2676 const LayerVector::Visitor& visitor) {
2677 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002678
Robert Carr1f0a16a2016-10-24 16:27:39 -07002679 int32_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002680 for (i = list.size()-1; i>=0; i--) {
2681 const auto& relative = list[i];
2682 if (relative->getZ() < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002683 break;
2684 }
Dan Stoza412903f2017-04-27 13:42:17 -07002685 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002686 }
Dan Stoza412903f2017-04-27 13:42:17 -07002687 visitor(this);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002688 for (; i>=0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002689 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002690 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002691 }
2692}
2693
2694Transform Layer::getTransform() const {
2695 Transform t;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002696 const auto& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002697 if (p != nullptr) {
2698 t = p->getTransform();
Robert Carr9b429f42017-04-17 14:56:57 -07002699
2700 // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2701 // it isFixedSize) then there may be additional scaling not accounted
2702 // for in the transform. We need to mirror this scaling in child surfaces
2703 // or we will break the contract where WM can treat child surfaces as
2704 // pixels in the parent surface.
Chia-I Wu0a68b462017-07-18 11:30:05 -07002705 if (p->isFixedSize() && p->mActiveBuffer != nullptr) {
Robert Carr1725eee2017-04-26 18:32:15 -07002706 int bufferWidth;
2707 int bufferHeight;
2708 if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2709 bufferWidth = p->mActiveBuffer->getWidth();
2710 bufferHeight = p->mActiveBuffer->getHeight();
2711 } else {
2712 bufferHeight = p->mActiveBuffer->getWidth();
2713 bufferWidth = p->mActiveBuffer->getHeight();
2714 }
Robert Carr9b429f42017-04-17 14:56:57 -07002715 float sx = p->getDrawingState().active.w /
Robert Carr1725eee2017-04-26 18:32:15 -07002716 static_cast<float>(bufferWidth);
Robert Carr9b429f42017-04-17 14:56:57 -07002717 float sy = p->getDrawingState().active.h /
Robert Carr1725eee2017-04-26 18:32:15 -07002718 static_cast<float>(bufferHeight);
Robert Carr9b429f42017-04-17 14:56:57 -07002719 Transform extraParentScaling;
2720 extraParentScaling.set(sx, 0, 0, sy);
2721 t = t * extraParentScaling;
2722 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002723 }
2724 return t * getDrawingState().active.transform;
2725}
2726
Robert Carr6452f122017-03-21 10:41:29 -07002727#ifdef USE_HWC2
2728float Layer::getAlpha() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002729 const auto& p = mDrawingParent.promote();
Robert Carr6452f122017-03-21 10:41:29 -07002730
2731 float parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0;
2732 return parentAlpha * getDrawingState().alpha;
2733}
2734#else
2735uint8_t Layer::getAlpha() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002736 const auto& p = mDrawingParent.promote();
Robert Carr6452f122017-03-21 10:41:29 -07002737
2738 float parentAlpha = (p != nullptr) ? (p->getAlpha() / 255.0f) : 1.0;
2739 float drawingAlpha = getDrawingState().alpha / 255.0f;
2740 drawingAlpha = drawingAlpha * parentAlpha;
2741 return static_cast<uint8_t>(std::round(drawingAlpha * 255));
2742}
2743#endif
2744
Robert Carr1f0a16a2016-10-24 16:27:39 -07002745void Layer::commitChildList() {
2746 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2747 const auto& child = mCurrentChildren[i];
2748 child->commitChildList();
2749 }
2750 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002751 mDrawingParent = mCurrentParent;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002752}
2753
Mathias Agopian13127d82013-03-05 17:47:11 -08002754// ---------------------------------------------------------------------------
2755
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002756}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002757
2758#if defined(__gl_h_)
2759#error "don't include gl/gl.h in this file"
2760#endif
2761
2762#if defined(__gl2_h_)
2763#error "don't include gl2/gl2.h in this file"
2764#endif