blob: 022b41634dff3d4ba5c31729fd202b8bbd0ab932 [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
Mathias Agopian3330b202009-10-05 17:07:12 -070037#include <ui/GraphicBuffer.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080038#include <ui/PixelFormat.h>
Mathias Agopian9cce3252010-02-09 17:46:37 -080039
Dan Stoza6b9454d2014-11-07 16:00:59 -080040#include <gui/BufferItem.h>
Mathias Agopiana9347642017-02-13 16:42:28 -080041#include <gui/BufferQueue.h>
Mathias Agopian90ac7992012-02-25 18:48:35 -080042#include <gui/Surface.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080043
44#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020045#include "Colorizer.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070046#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080047#include "Layer.h"
Fabien Sanglard7b1563a2016-10-13 12:05:28 -070048#include "LayerRejecter.h"
Dan Stozab9b08832014-03-13 11:55:57 -070049#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080050#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080051
Mathias Agopian1b031492012-06-20 17:51:20 -070052#include "DisplayHardware/HWComposer.h"
53
Mathias Agopian875d8e12013-06-07 15:35:48 -070054#include "RenderEngine/RenderEngine.h"
55
Dan Stozac5da2712016-07-20 15:38:12 -070056#include <mutex>
57
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058#define DEBUG_RESIZE 0
59
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060namespace android {
61
62// ---------------------------------------------------------------------------
63
Mathias Agopian13127d82013-03-05 17:47:11 -080064int32_t Layer::sSequence = 1;
65
Mathias Agopian4d9b8222013-03-12 17:11:48 -070066Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
67 const String8& name, uint32_t w, uint32_t h, uint32_t flags)
Mathias Agopian13127d82013-03-05 17:47:11 -080068 : contentDirty(false),
69 sequence(uint32_t(android_atomic_inc(&sSequence))),
70 mFlinger(flinger),
Mathias Agopiana67932f2011-04-20 14:20:59 -070071 mTextureName(-1U),
Mathias Agopian13127d82013-03-05 17:47:11 -080072 mPremultipliedAlpha(true),
73 mName("unnamed"),
Mathias Agopian13127d82013-03-05 17:47:11 -080074 mFormat(PIXEL_FORMAT_NONE),
Mathias Agopian13127d82013-03-05 17:47:11 -080075 mTransactionFlags(0),
Dan Stoza7dde5992015-05-22 09:51:44 -070076 mPendingStateMutex(),
77 mPendingStates(),
Mathias Agopiana67932f2011-04-20 14:20:59 -070078 mQueuedFrames(0),
Jesse Hall399184a2014-03-03 15:42:54 -080079 mSidebandStreamChanged(false),
Mathias Agopiana9347642017-02-13 16:42:28 -080080 mActiveBufferSlot(BufferQueue::INVALID_BUFFER_SLOT),
Mathias Agopiana67932f2011-04-20 14:20:59 -070081 mCurrentTransform(0),
Mathias Agopian933389f2011-07-18 16:15:08 -070082 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
Robert Carrc3574f72016-03-24 12:19:32 -070083 mOverrideScalingMode(-1),
Mathias Agopiana67932f2011-04-20 14:20:59 -070084 mCurrentOpacity(true),
Brian Andersond6927fb2016-07-23 23:37:30 -070085 mBufferLatched(false),
Dan Stozacac35382016-01-27 12:21:06 -080086 mCurrentFrameNumber(0),
Brian Anderson8cc8b102016-10-21 12:43:09 -070087 mPreviousFrameNumber(0),
Mathias Agopian4d143ee2012-02-23 20:05:39 -080088 mRefreshPending(false),
Mathias Agopian82d7ab62012-01-19 18:34:40 -080089 mFrameLatencyNeeded(false),
Mathias Agopian13127d82013-03-05 17:47:11 -080090 mFiltering(false),
91 mNeedsFiltering(false),
Mathias Agopian5cdc8992013-08-13 20:51:23 -070092 mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
Fabien Sanglard9d96de42016-10-11 00:15:18 +000093#ifndef USE_HWC2
94 mIsGlesComposition(false),
95#endif
Mathias Agopian13127d82013-03-05 17:47:11 -080096 mProtectedByApp(false),
97 mHasSurface(false),
Riley Andrews03414a12014-07-01 14:22:59 -070098 mClientRef(client),
Dan Stozaa4650a52015-05-12 12:56:16 -070099 mPotentialCursor(false),
100 mQueueItemLock(),
101 mQueueItemCondition(),
102 mQueueItems(),
Dan Stoza65476f32015-05-14 09:27:25 -0700103 mLastFrameNumberReceived(0),
Pablo Ceballos04839ab2015-11-13 13:39:23 -0800104 mUpdateTexImageFailed(false),
Robert Carr82364e32016-05-15 11:27:47 -0700105 mAutoRefresh(false),
Robert Carr7bf247e2017-05-18 14:02:49 -0700106 mFreezeGeometryUpdates(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800107{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000108#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800109 ALOGV("Creating Layer %s", name.string());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000110#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -0800111
Mathias Agopiana67932f2011-04-20 14:20:59 -0700112 mCurrentCrop.makeInvalid();
Mathias Agopian3f844832013-08-07 21:24:32 -0700113 mFlinger->getRenderEngine().genTextures(1, &mTextureName);
Mathias Agopian49457ac2013-08-14 18:20:17 -0700114 mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700115
116 uint32_t layerFlags = 0;
117 if (flags & ISurfaceComposerClient::eHidden)
Andy McFadden4125a4f2014-01-29 17:17:11 -0800118 layerFlags |= layer_state_t::eLayerHidden;
119 if (flags & ISurfaceComposerClient::eOpaque)
120 layerFlags |= layer_state_t::eLayerOpaque;
Dan Stoza23116082015-06-18 14:58:39 -0700121 if (flags & ISurfaceComposerClient::eSecure)
122 layerFlags |= layer_state_t::eLayerSecure;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700123
124 if (flags & ISurfaceComposerClient::eNonPremultiplied)
125 mPremultipliedAlpha = false;
126
127 mName = name;
128
129 mCurrentState.active.w = w;
130 mCurrentState.active.h = h;
Robert Carr3dcabfa2016-03-01 18:36:58 -0800131 mCurrentState.active.transform.set(0, 0);
Robert Carrb5d3d262016-03-25 15:08:13 -0700132 mCurrentState.crop.makeInvalid();
133 mCurrentState.finalCrop.makeInvalid();
Robert Carr7bf247e2017-05-18 14:02:49 -0700134 mCurrentState.requestedFinalCrop = mCurrentState.finalCrop;
135 mCurrentState.requestedCrop = mCurrentState.crop;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700136 mCurrentState.z = 0;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000137#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800138 mCurrentState.alpha = 1.0f;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000139#else
140 mCurrentState.alpha = 0xFF;
141#endif
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700142 mCurrentState.layerStack = 0;
143 mCurrentState.flags = layerFlags;
144 mCurrentState.sequence = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700145 mCurrentState.requested = mCurrentState.active;
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700146 mCurrentState.dataSpace = HAL_DATASPACE_UNKNOWN;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500147 mCurrentState.appId = 0;
148 mCurrentState.type = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700149
150 // drawing state & current state are identical
151 mDrawingState = mCurrentState;
Jamie Gennis6547ff42013-07-16 20:12:42 -0700152
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000153#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800154 const auto& hwc = flinger->getHwComposer();
155 const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
156 nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000157#else
158 nsecs_t displayPeriod =
159 flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
160#endif
Jamie Gennis6547ff42013-07-16 20:12:42 -0700161 mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -0800162
163 CompositorTiming compositorTiming;
164 flinger->getCompositorTiming(&compositorTiming);
165 mFrameEventHistory.initializeCompositorTiming(compositorTiming);
Jamie Gennise8696a42012-01-15 18:54:57 -0800166}
167
Mathias Agopian3f844832013-08-07 21:24:32 -0700168void Layer::onFirstRef() {
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800169 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
Dan Stozab3d0bdf2014-04-07 16:33:59 -0700170 sp<IGraphicBufferProducer> producer;
171 sp<IGraphicBufferConsumer> consumer;
Mathias Agopian0556d792017-03-22 15:49:32 -0700172 BufferQueue::createBufferQueue(&producer, &consumer, true);
Robert Carr1db73f62016-12-21 12:58:51 -0800173 mProducer = new MonitoredProducer(producer, mFlinger, this);
Irvel468051e2016-06-13 16:44:44 -0700174 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800175 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Jesse Hall399184a2014-03-03 15:42:54 -0800176 mSurfaceFlingerConsumer->setContentsChangedListener(this);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700177 mSurfaceFlingerConsumer->setName(mName);
Daniel Lamb2675792012-02-23 14:35:13 -0800178
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800179 if (mFlinger->isLayerTripleBufferingDisabled()) {
180 mProducer->setMaxDequeuedBufferCount(2);
181 }
Andy McFadden69052052012-09-14 16:10:11 -0700182
Mathias Agopian84300952012-11-21 16:02:13 -0800183 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
184 updateTransformHint(hw);
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700185}
186
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700187Layer::~Layer() {
Pablo Ceballos8ea4e7b2016-03-03 15:20:02 -0800188 sp<Client> c(mClientRef.promote());
189 if (c != 0) {
190 c->detachLayer(this);
191 }
192
Dan Stozacac35382016-01-27 12:21:06 -0800193 for (auto& point : mRemoteSyncPoints) {
194 point->setTransactionApplied();
195 }
Dan Stozac8145172016-04-28 16:29:06 -0700196 for (auto& point : mLocalSyncPoints) {
197 point->setFrameAvailable();
198 }
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700199 mFlinger->deleteTextureAsync(mTextureName);
Jamie Gennis6547ff42013-07-16 20:12:42 -0700200 mFrameTracker.logAndResetStats(mName);
Mathias Agopian96f08192010-06-02 23:28:45 -0700201}
202
Mathias Agopian13127d82013-03-05 17:47:11 -0800203// ---------------------------------------------------------------------------
204// callbacks
205// ---------------------------------------------------------------------------
206
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000207#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800208void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
209 if (mHwcLayers.empty()) {
210 return;
211 }
212 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
213}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000214#else
215void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
216 HWComposer::HWCLayerInterface* layer) {
217 if (layer) {
218 layer->onDisplayed();
219 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
220 }
221}
222#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800223
Dan Stoza6b9454d2014-11-07 16:00:59 -0800224void Layer::onFrameAvailable(const BufferItem& item) {
225 // Add this buffer from our internal queue tracker
226 { // Autolock scope
227 Mutex::Autolock lock(mQueueItemLock);
Irvel468051e2016-06-13 16:44:44 -0700228 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
229 item.mGraphicBuffer->getHeight(), item.mFrameNumber);
Dan Stozaa4650a52015-05-12 12:56:16 -0700230 // Reset the frame number tracker when we receive the first buffer after
231 // a frame number reset
232 if (item.mFrameNumber == 1) {
233 mLastFrameNumberReceived = 0;
234 }
235
236 // Ensure that callbacks are handled in order
237 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
238 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
239 ms2ns(500));
240 if (result != NO_ERROR) {
241 ALOGE("[%s] Timed out waiting on callback", mName.string());
242 }
243 }
244
Dan Stoza6b9454d2014-11-07 16:00:59 -0800245 mQueueItems.push_back(item);
Dan Stozaecc50402015-04-28 14:42:06 -0700246 android_atomic_inc(&mQueuedFrames);
Dan Stozaa4650a52015-05-12 12:56:16 -0700247
248 // Wake up any pending callbacks
249 mLastFrameNumberReceived = item.mFrameNumber;
250 mQueueItemCondition.broadcast();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800251 }
252
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800253 mFlinger->signalLayerUpdate();
Mathias Agopian579b3f82010-06-08 19:54:15 -0700254}
255
Dan Stoza6b9454d2014-11-07 16:00:59 -0800256void Layer::onFrameReplaced(const BufferItem& item) {
Dan Stoza7dde5992015-05-22 09:51:44 -0700257 { // Autolock scope
258 Mutex::Autolock lock(mQueueItemLock);
Dan Stozaa4650a52015-05-12 12:56:16 -0700259
Dan Stoza7dde5992015-05-22 09:51:44 -0700260 // Ensure that callbacks are handled in order
261 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
262 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
263 ms2ns(500));
264 if (result != NO_ERROR) {
265 ALOGE("[%s] Timed out waiting on callback", mName.string());
266 }
Dan Stozaa4650a52015-05-12 12:56:16 -0700267 }
Dan Stoza7dde5992015-05-22 09:51:44 -0700268
269 if (mQueueItems.empty()) {
270 ALOGE("Can't replace a frame on an empty queue");
271 return;
272 }
Pablo Ceballos4d85da42016-04-19 20:11:56 -0700273 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
Dan Stoza7dde5992015-05-22 09:51:44 -0700274
275 // Wake up any pending callbacks
276 mLastFrameNumberReceived = item.mFrameNumber;
277 mQueueItemCondition.broadcast();
Dan Stozaa4650a52015-05-12 12:56:16 -0700278 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800279}
280
Jesse Hall399184a2014-03-03 15:42:54 -0800281void Layer::onSidebandStreamChanged() {
282 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
283 // mSidebandStreamChanged was false
284 mFlinger->signalLayerUpdate();
285 }
286}
287
Mathias Agopian67106042013-03-14 19:18:13 -0700288// called with SurfaceFlinger::mStateLock from the drawing thread after
289// the layer has been remove from the current state list (and just before
290// it's removed from the drawing state list)
Mathias Agopian13127d82013-03-05 17:47:11 -0800291void Layer::onRemoved() {
Robert Carr5edb1ad2017-04-25 10:54:24 -0700292 if (mCurrentState.zOrderRelativeOf != nullptr) {
293 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
294 if (strongRelative != nullptr) {
295 strongRelative->removeZOrderRelative(this);
296 }
297 mCurrentState.zOrderRelativeOf = nullptr;
298 }
299
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800300 mSurfaceFlingerConsumer->abandon();
Chia-I Wu38512252017-05-17 14:36:16 -0700301
302#ifdef USE_HWC2
303 clearHwcLayers();
304#endif
305
Robert Carr1f0a16a2016-10-24 16:27:39 -0700306 for (const auto& child : mCurrentChildren) {
307 child->onRemoved();
308 }
Mathias Agopian48d819a2009-09-10 19:41:18 -0700309}
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700310
Mathias Agopian13127d82013-03-05 17:47:11 -0800311// ---------------------------------------------------------------------------
312// set-up
313// ---------------------------------------------------------------------------
314
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700315const String8& Layer::getName() const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800316 return mName;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800317}
318
Mathias Agopianf9d93272009-06-19 17:00:27 -0700319status_t Layer::setBuffers( uint32_t w, uint32_t h,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800320 PixelFormat format, uint32_t flags)
321{
Mathias Agopianca99fb82010-04-14 16:43:44 -0700322 uint32_t const maxSurfaceDims = min(
Mathias Agopiana4912602012-07-12 14:25:33 -0700323 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
Mathias Agopianca99fb82010-04-14 16:43:44 -0700324
325 // never allow a surface larger than what our underlying GL implementation
326 // can handle.
327 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
Mathias Agopianff615cc2012-02-24 14:58:36 -0800328 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700329 return BAD_VALUE;
330 }
331
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700332 mFormat = format;
Mathias Agopianeff062c2010-08-25 14:59:15 -0700333
Riley Andrews03414a12014-07-01 14:22:59 -0700334 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
Mathias Agopian3165cc22012-08-08 19:42:09 -0700335 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700336 mCurrentOpacity = getOpacityForFormat(format);
337
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800338 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
339 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
340 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700341
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800342 return NO_ERROR;
343}
344
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700345sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800346 Mutex::Autolock _l(mLock);
347
348 LOG_ALWAYS_FATAL_IF(mHasSurface,
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700349 "Layer::getHandle() has already been called");
Mathias Agopian13127d82013-03-05 17:47:11 -0800350
351 mHasSurface = true;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700352
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700353 return new Handle(mFlinger, this);
Mathias Agopian13127d82013-03-05 17:47:11 -0800354}
355
Dan Stozab9b08832014-03-13 11:55:57 -0700356sp<IGraphicBufferProducer> Layer::getProducer() const {
357 return mProducer;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700358}
359
Mathias Agopian13127d82013-03-05 17:47:11 -0800360// ---------------------------------------------------------------------------
361// h/w composer set-up
362// ---------------------------------------------------------------------------
363
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800364Rect Layer::getContentCrop() const {
365 // this is the crop rectangle that applies to the buffer
366 // itself (as opposed to the window)
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700367 Rect crop;
368 if (!mCurrentCrop.isEmpty()) {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800369 // if the buffer crop is defined, we use that
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700370 crop = mCurrentCrop;
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800371 } else if (mActiveBuffer != NULL) {
372 // otherwise we use the whole buffer
373 crop = mActiveBuffer->getBounds();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700374 } else {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800375 // if we don't have a buffer yet, we use an empty/invalid crop
Mathias Agopian4fec8732012-06-29 14:12:52 -0700376 crop.makeInvalid();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700377 }
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700378 return crop;
379}
380
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700381static Rect reduce(const Rect& win, const Region& exclude) {
382 if (CC_LIKELY(exclude.isEmpty())) {
383 return win;
384 }
385 if (exclude.isRect()) {
386 return win.reduce(exclude.getBounds());
387 }
388 return Region(win).subtract(exclude).getBounds();
389}
390
Robert Carr1f0a16a2016-10-24 16:27:39 -0700391Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
392 const Layer::State& s(getDrawingState());
393 Rect win(s.active.w, s.active.h);
394
395 if (!s.crop.isEmpty()) {
396 win.intersect(s.crop, &win);
397 }
398
399 Transform t = getTransform();
400 win = t.transform(win);
401
Robert Carr41b08b52017-06-01 16:11:34 -0700402 if (!s.finalCrop.isEmpty()) {
403 win.intersect(s.finalCrop, &win);
404 }
405
Chia-I Wue41dbe62017-06-13 14:10:56 -0700406 const sp<Layer>& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700407 // Now we need to calculate the parent bounds, so we can clip ourselves to those.
408 // When calculating the parent bounds for purposes of clipping,
409 // we don't need to constrain the parent to its transparent region.
410 // The transparent region is an optimization based on the
411 // buffer contents of the layer, but does not affect the space allocated to
412 // it by policy, and thus children should be allowed to extend into the
413 // parent's transparent region. In fact one of the main uses, is to reduce
414 // buffer allocation size in cases where a child window sits behind a main window
415 // (by marking the hole in the parent window as a transparent region)
416 if (p != nullptr) {
417 Rect bounds = p->computeScreenBounds(false);
418 bounds.intersect(win, &win);
419 }
420
421 if (reduceTransparentRegion) {
422 auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
423 win = reduce(win, screenTransparentRegion);
424 }
425
426 return win;
427}
428
Mathias Agopian13127d82013-03-05 17:47:11 -0800429Rect Layer::computeBounds() const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700430 const Layer::State& s(getDrawingState());
Michael Lentine6c925ed2014-09-26 17:55:01 -0700431 return computeBounds(s.activeTransparentRegion);
432}
433
434Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
435 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800436 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700437
438 if (!s.crop.isEmpty()) {
439 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -0800440 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700441
442 Rect bounds = win;
Chia-I Wue41dbe62017-06-13 14:10:56 -0700443 const auto& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700444 if (p != nullptr) {
Robert Carrde9ec442017-02-08 17:43:36 -0800445 // Look in computeScreenBounds recursive call for explanation of
446 // why we pass false here.
447 bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700448 }
449
450 Transform t = getTransform();
451 if (p != nullptr) {
452 win = t.transform(win);
453 win.intersect(bounds, &win);
454 win = t.inverse().transform(win);
455 }
456
Mathias Agopian6c7f25a2013-05-09 20:37:10 -0700457 // subtract the transparent region and snap to the bounds
Michael Lentine6c925ed2014-09-26 17:55:01 -0700458 return reduce(win, activeTransparentRegion);
Mathias Agopian13127d82013-03-05 17:47:11 -0800459}
460
Robert Carr1f0a16a2016-10-24 16:27:39 -0700461Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
Robert Carrb5d3d262016-03-25 15:08:13 -0700462 // the crop is the area of the window that gets cropped, but not
Mathias Agopian13127d82013-03-05 17:47:11 -0800463 // scaled in any ways.
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700464 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800465
466 // apply the projection's clipping to the window crop in
467 // layerstack space, and convert-back to layer space.
Mathias Agopian6b442672013-07-09 21:24:52 -0700468 // if there are no window scaling involved, this operation will map to full
469 // pixels in the buffer.
470 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
471 // a viewport clipping and a window transform. we should use floating point to fix this.
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700472
473 Rect activeCrop(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700474 if (!s.crop.isEmpty()) {
475 activeCrop = s.crop;
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700476 }
477
Robert Carr1f0a16a2016-10-24 16:27:39 -0700478 Transform t = getTransform();
479 activeCrop = t.transform(activeCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000480 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
481 activeCrop.clear();
482 }
Robert Carrb5d3d262016-03-25 15:08:13 -0700483 if (!s.finalCrop.isEmpty()) {
484 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000485 activeCrop.clear();
486 }
487 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700488 return activeCrop;
489}
490
Dan Stoza5a423ea2017-02-16 14:10:39 -0800491FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
Robert Carr1f0a16a2016-10-24 16:27:39 -0700492 // the content crop is the area of the content that gets scaled to the
493 // layer's size. This is in buffer space.
Dan Stoza5a423ea2017-02-16 14:10:39 -0800494 FloatRect crop = getContentCrop().toFloatRect();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700495
496 // In addition there is a WM-specified crop we pull from our drawing state.
497 const State& s(getDrawingState());
498
499 // Screen space to make reduction to parent crop clearer.
500 Rect activeCrop = computeInitialCrop(hw);
Chia-I Wue41dbe62017-06-13 14:10:56 -0700501 const auto& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700502 if (p != nullptr) {
503 auto parentCrop = p->computeInitialCrop(hw);
504 activeCrop.intersect(parentCrop, &activeCrop);
505 }
506 Transform t = getTransform();
507 // Back to layer space to work with the content crop.
508 activeCrop = t.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800509
Michael Lentine28ea2172014-11-19 18:32:37 -0800510 // This needs to be here as transform.transform(Rect) computes the
511 // transformed rect and then takes the bounding box of the result before
512 // returning. This means
513 // transform.inverse().transform(transform.transform(Rect)) != Rect
514 // in which case we need to make sure the final rect is clipped to the
515 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000516 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
517 activeCrop.clear();
518 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800519
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700520 // subtract the transparent region and snap to the bounds
521 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
522
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000523 // Transform the window crop to match the buffer coordinate system,
524 // which means using the inverse of the current transform set on the
525 // SurfaceFlingerConsumer.
526 uint32_t invTransform = mCurrentTransform;
Robert Carrcae605c2017-03-29 12:10:31 -0700527 if (getTransformToDisplayInverse()) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000528 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700529 * the code below applies the primary display's inverse transform to the
530 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000531 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700532 uint32_t invTransformOrient =
533 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000534 // calculate the inverse transform
535 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
536 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
537 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800538 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000539 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700540 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
541 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800542 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000543
544 int winWidth = s.active.w;
545 int winHeight = s.active.h;
546 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
547 // If the activeCrop has been rotate the ends are rotated but not
548 // the space itself so when transforming ends back we can't rely on
549 // a modification of the axes of rotation. To account for this we
550 // need to reorient the inverse rotation in terms of the current
551 // axes of rotation.
552 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
553 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
554 if (is_h_flipped == is_v_flipped) {
555 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
556 NATIVE_WINDOW_TRANSFORM_FLIP_H;
557 }
558 winWidth = s.active.h;
559 winHeight = s.active.w;
560 }
561 const Rect winCrop = activeCrop.transform(
562 invTransform, s.active.w, s.active.h);
563
564 // below, crop is intersected with winCrop expressed in crop's coordinate space
565 float xScale = crop.getWidth() / float(winWidth);
566 float yScale = crop.getHeight() / float(winHeight);
567
568 float insetL = winCrop.left * xScale;
569 float insetT = winCrop.top * yScale;
570 float insetR = (winWidth - winCrop.right ) * xScale;
571 float insetB = (winHeight - winCrop.bottom) * yScale;
572
573 crop.left += insetL;
574 crop.top += insetT;
575 crop.right -= insetR;
576 crop.bottom -= insetB;
577
Mathias Agopian13127d82013-03-05 17:47:11 -0800578 return crop;
579}
580
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000581#ifdef USE_HWC2
Robert Carrae060832016-11-28 10:51:00 -0800582void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000583#else
584void Layer::setGeometry(
585 const sp<const DisplayDevice>& hw,
586 HWComposer::HWCLayerInterface& layer)
587#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700588{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000589#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800590 const auto hwcId = displayDevice->getHwcDisplayId();
591 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000592#else
593 layer.setDefaultState();
594#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700595
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700596 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000597#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800598 hwcInfo.forceClientComposition = false;
599
600 if (isSecure() && !displayDevice->isSecure()) {
601 hwcInfo.forceClientComposition = true;
602 }
603
604 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000605#else
606 layer.setSkip(false);
607
608 if (isSecure() && !hw->isSecure()) {
609 layer.setSkip(true);
610 }
611#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700612
Mathias Agopian13127d82013-03-05 17:47:11 -0800613 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700614 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000615#ifdef USE_HWC2
David Revemanecf0fa52017-03-03 11:32:44 -0500616 auto blendMode = HWC2::BlendMode::None;
Robert Carr6452f122017-03-21 10:41:29 -0700617 if (!isOpaque(s) || getAlpha() != 1.0f) {
David Revemanecf0fa52017-03-03 11:32:44 -0500618 blendMode = mPremultipliedAlpha ?
Dan Stoza9e56aa02015-11-02 13:00:03 -0800619 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800620 }
David Revemanecf0fa52017-03-03 11:32:44 -0500621 auto error = hwcLayer->setBlendMode(blendMode);
622 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
623 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
624 to_string(error).c_str(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000625#else
Robert Carr6452f122017-03-21 10:41:29 -0700626 if (!isOpaque(s) || getAlpha() != 0xFF) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000627 layer.setBlending(mPremultipliedAlpha ?
628 HWC_BLENDING_PREMULT :
629 HWC_BLENDING_COVERAGE);
630 }
631#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800632
633 // apply the layer's transform, followed by the display's global transform
634 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700635 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700636 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -0700637 if (!s.crop.isEmpty()) {
638 Rect activeCrop(s.crop);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700639 activeCrop = t.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000640#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000641 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000642#else
643 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
644#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000645 activeCrop.clear();
646 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700647 activeCrop = t.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800648 // This needs to be here as transform.transform(Rect) computes the
649 // transformed rect and then takes the bounding box of the result before
650 // returning. This means
651 // transform.inverse().transform(transform.transform(Rect)) != Rect
652 // in which case we need to make sure the final rect is clipped to the
653 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000654 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
655 activeCrop.clear();
656 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700657 // mark regions outside the crop as transparent
658 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
659 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
660 s.active.w, s.active.h));
661 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
662 activeCrop.left, activeCrop.bottom));
663 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
664 s.active.w, activeCrop.bottom));
665 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700666
667 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700668 if (!s.finalCrop.isEmpty()) {
669 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000670 frame.clear();
671 }
672 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000673#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000674 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
675 frame.clear();
676 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800677 const Transform& tr(displayDevice->getTransform());
678 Rect transformedFrame = tr.transform(frame);
David Revemanecf0fa52017-03-03 11:32:44 -0500679 error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700680 if (error != HWC2::Error::None) {
681 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
682 mName.string(), transformedFrame.left, transformedFrame.top,
683 transformedFrame.right, transformedFrame.bottom,
684 to_string(error).c_str(), static_cast<int32_t>(error));
685 } else {
686 hwcInfo.displayFrame = transformedFrame;
687 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800688
Dan Stoza5a423ea2017-02-16 14:10:39 -0800689 FloatRect sourceCrop = computeCrop(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800690 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700691 if (error != HWC2::Error::None) {
692 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
693 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
694 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
695 static_cast<int32_t>(error));
696 } else {
697 hwcInfo.sourceCrop = sourceCrop;
698 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800699
Robert Carr6452f122017-03-21 10:41:29 -0700700 float alpha = getAlpha();
701 error = hwcLayer->setPlaneAlpha(alpha);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800702 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
Robert Carr6452f122017-03-21 10:41:29 -0700703 "%s (%d)", mName.string(), alpha, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800704 static_cast<int32_t>(error));
705
Robert Carrae060832016-11-28 10:51:00 -0800706 error = hwcLayer->setZOrder(z);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800707 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
Robert Carrae060832016-11-28 10:51:00 -0800708 mName.string(), z, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800709 static_cast<int32_t>(error));
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500710
Albert Chaulk2a589632017-05-04 16:59:44 -0400711 int type = s.type;
712 int appId = s.appId;
Chia-I Wue41dbe62017-06-13 14:10:56 -0700713 sp<Layer> parent = mDrawingParent.promote();
Albert Chaulk2a589632017-05-04 16:59:44 -0400714 if (parent.get()) {
715 auto& parentState = parent->getDrawingState();
716 type = parentState.type;
717 appId = parentState.appId;
718 }
719
720 error = hwcLayer->setInfo(type, appId);
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500721 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
722 mName.string(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000723#else
724 if (!frame.intersect(hw->getViewport(), &frame)) {
725 frame.clear();
726 }
727 const Transform& tr(hw->getTransform());
728 layer.setFrame(tr.transform(frame));
729 layer.setCrop(computeCrop(hw));
Robert Carr6452f122017-03-21 10:41:29 -0700730 layer.setPlaneAlpha(getAlpha());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000731#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800732
Mathias Agopian29a367b2011-07-12 14:51:45 -0700733 /*
734 * Transformations are applied in this order:
735 * 1) buffer orientation/flip/mirror
736 * 2) state transformation (window manager)
737 * 3) layer orientation (screen orientation)
738 * (NOTE: the matrices are multiplied in reverse order)
739 */
740
741 const Transform bufferOrientation(mCurrentTransform);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700742 Transform transform(tr * t * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700743
Robert Carrcae605c2017-03-29 12:10:31 -0700744 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700745 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700746 * the code below applies the primary display's inverse transform to the
747 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700748 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700749 uint32_t invTransform =
750 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700751 // calculate the inverse transform
752 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
753 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
754 NATIVE_WINDOW_TRANSFORM_FLIP_H;
755 }
Robert Carrcae605c2017-03-29 12:10:31 -0700756
757 /*
758 * Here we cancel out the orientation component of the WM transform.
759 * The scaling and translate components are already included in our bounds
760 * computation so it's enough to just omit it in the composition.
761 * See comment in onDraw with ref to b/36727915 for why.
762 */
763 transform = Transform(invTransform) * tr * bufferOrientation;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700764 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700765
766 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800767 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000768#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800769 if (orientation & Transform::ROT_INVALID) {
770 // we can only handle simple transformation
771 hwcInfo.forceClientComposition = true;
772 } else {
773 auto transform = static_cast<HWC2::Transform>(orientation);
774 auto error = hwcLayer->setTransform(transform);
775 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
776 "%s (%d)", mName.string(), to_string(transform).c_str(),
777 to_string(error).c_str(), static_cast<int32_t>(error));
778 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000779#else
780 if (orientation & Transform::ROT_INVALID) {
781 // we can only handle simple transformation
782 layer.setSkip(true);
783 } else {
784 layer.setTransform(orientation);
785 }
786#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700787}
788
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000789#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800790void Layer::forceClientComposition(int32_t hwcId) {
791 if (mHwcLayers.count(hwcId) == 0) {
792 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
793 return;
794 }
795
796 mHwcLayers[hwcId].forceClientComposition = true;
797}
Dan Stoza9e56aa02015-11-02 13:00:03 -0800798
Dan Stoza9e56aa02015-11-02 13:00:03 -0800799void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
800 // Apply this display's projection's viewport to the visible region
801 // before giving it to the HWC HAL.
802 const Transform& tr = displayDevice->getTransform();
803 const auto& viewport = displayDevice->getViewport();
804 Region visible = tr.transform(visibleRegion.intersect(viewport));
805 auto hwcId = displayDevice->getHwcDisplayId();
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800806 auto& hwcInfo = mHwcLayers[hwcId];
807 auto& hwcLayer = hwcInfo.layer;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800808 auto error = hwcLayer->setVisibleRegion(visible);
809 if (error != HWC2::Error::None) {
810 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
811 to_string(error).c_str(), static_cast<int32_t>(error));
812 visible.dump(LOG_TAG);
813 }
814
815 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
816 if (error != HWC2::Error::None) {
817 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
818 to_string(error).c_str(), static_cast<int32_t>(error));
819 surfaceDamageRegion.dump(LOG_TAG);
820 }
821
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700822 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800823 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700824 setCompositionType(hwcId, HWC2::Composition::Sideband);
825 ALOGV("[%s] Requesting Sideband composition", mName.string());
826 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800827 if (error != HWC2::Error::None) {
828 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
829 mName.string(), mSidebandStream->handle(),
830 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800831 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700832 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800833 }
834
Dan Stoza0a21df72016-07-20 12:52:38 -0700835 // Client layers
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800836 if (hwcInfo.forceClientComposition ||
Dan Stoza0a21df72016-07-20 12:52:38 -0700837 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700838 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800839 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700840 return;
841 }
842
Dan Stoza0a21df72016-07-20 12:52:38 -0700843 // SolidColor layers
844 if (mActiveBuffer == nullptr) {
845 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700846
847 // For now, we only support black for DimLayer
Dan Stoza0a21df72016-07-20 12:52:38 -0700848 error = hwcLayer->setColor({0, 0, 0, 255});
849 if (error != HWC2::Error::None) {
850 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
851 to_string(error).c_str(), static_cast<int32_t>(error));
852 }
Dan Stozac6c89542016-07-27 10:16:52 -0700853
854 // Clear out the transform, because it doesn't make sense absent a
855 // source buffer
856 error = hwcLayer->setTransform(HWC2::Transform::None);
857 if (error != HWC2::Error::None) {
858 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
859 to_string(error).c_str(), static_cast<int32_t>(error));
860 }
861
Dan Stoza0a21df72016-07-20 12:52:38 -0700862 return;
863 }
864
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700865 // Device or Cursor layers
866 if (mPotentialCursor) {
867 ALOGV("[%s] Requesting Cursor composition", mName.string());
868 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800869 } else {
870 ALOGV("[%s] Requesting Device composition", mName.string());
871 setCompositionType(hwcId, HWC2::Composition::Device);
872 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700873
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700874 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
875 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
876 if (error != HWC2::Error::None) {
877 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
878 mCurrentState.dataSpace, to_string(error).c_str(),
879 static_cast<int32_t>(error));
880 }
881
Chia-I Wu06d63de2017-01-04 14:58:51 +0800882 uint32_t hwcSlot = 0;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400883 sp<GraphicBuffer> hwcBuffer;
884 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
885 &hwcSlot, &hwcBuffer);
Chia-I Wu06d63de2017-01-04 14:58:51 +0800886
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700887 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400888 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700889 if (error != HWC2::Error::None) {
890 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
891 mActiveBuffer->handle, to_string(error).c_str(),
892 static_cast<int32_t>(error));
893 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894}
Courtney Goeltzenleuchter9551fd32016-10-20 17:18:15 -0600895
896android_dataspace Layer::getDataSpace() const {
897 return mCurrentState.dataSpace;
898}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000899#else
900void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
901 HWComposer::HWCLayerInterface& layer) {
902 // we have to set the visible region on every frame because
903 // we currently free it during onLayerDisplayed(), which is called
904 // after HWComposer::commit() -- every frame.
905 // Apply this display's projection's viewport to the visible region
906 // before giving it to the HWC HAL.
907 const Transform& tr = hw->getTransform();
908 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
909 layer.setVisibleRegionScreen(visible);
910 layer.setSurfaceDamage(surfaceDamageRegion);
911 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700912
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000913 if (mSidebandStream.get()) {
914 layer.setSidebandStream(mSidebandStream);
915 } else {
916 // NOTE: buffer can be NULL if the client never drew into this
917 // layer yet, or if we ran out of memory
918 layer.setBuffer(mActiveBuffer);
919 }
920}
921#endif
922
923#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800924void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
925 auto hwcId = displayDevice->getHwcDisplayId();
926 if (mHwcLayers.count(hwcId) == 0 ||
927 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
928 return;
929 }
930
931 // This gives us only the "orientation" component of the transform
932 const State& s(getCurrentState());
933
934 // Apply the layer's transform, followed by the display's global transform
935 // Here we're guaranteed that the layer's transform preserves rects
936 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700937 if (!s.crop.isEmpty()) {
938 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800939 }
940 // Subtract the transparent region and snap to the bounds
941 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700942 Rect frame(getTransform().transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800943 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -0700944 if (!s.finalCrop.isEmpty()) {
945 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000946 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800947 auto& displayTransform(displayDevice->getTransform());
948 auto position = displayTransform.transform(frame);
949
950 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
951 position.top);
952 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
953 "to (%d, %d): %s (%d)", mName.string(), position.left,
954 position.top, to_string(error).c_str(),
955 static_cast<int32_t>(error));
956}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000957#else
958void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
959 HWComposer::HWCLayerInterface& layer) {
960 int fenceFd = -1;
961
962 // TODO: there is a possible optimization here: we only need to set the
963 // acquire fence the first time a new buffer is acquired on EACH display.
964
965 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
966 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
967 if (fence->isValid()) {
968 fenceFd = fence->dup();
969 if (fenceFd == -1) {
970 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
971 }
972 }
973 }
974 layer.setAcquireFenceFd(fenceFd);
975}
976
977Rect Layer::getPosition(
978 const sp<const DisplayDevice>& hw)
979{
980 // this gives us only the "orientation" component of the transform
981 const State& s(getCurrentState());
982
983 // apply the layer's transform, followed by the display's global transform
984 // here we're guaranteed that the layer's transform preserves rects
985 Rect win(s.active.w, s.active.h);
986 if (!s.crop.isEmpty()) {
987 win.intersect(s.crop, &win);
988 }
989 // subtract the transparent region and snap to the bounds
990 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700991 Rect frame(getTransform().transform(bounds));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000992 frame.intersect(hw->getViewport(), &frame);
993 if (!s.finalCrop.isEmpty()) {
994 frame.intersect(s.finalCrop, &frame);
995 }
996 const Transform& tr(hw->getTransform());
997 return Rect(tr.transform(frame));
998}
999#endif
Riley Andrews03414a12014-07-01 14:22:59 -07001000
Mathias Agopian13127d82013-03-05 17:47:11 -08001001// ---------------------------------------------------------------------------
1002// drawing...
1003// ---------------------------------------------------------------------------
1004
1005void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -08001006 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -08001007}
1008
Dan Stozac7014012014-02-14 15:03:43 -08001009void Layer::draw(const sp<const DisplayDevice>& hw,
1010 bool useIdentityTransform) const {
1011 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001012}
1013
Dan Stozac7014012014-02-14 15:03:43 -08001014void Layer::draw(const sp<const DisplayDevice>& hw) const {
1015 onDraw(hw, Region(hw->bounds()), false);
1016}
1017
Robert Carrcae605c2017-03-29 12:10:31 -07001018static constexpr mat4 inverseOrientation(uint32_t transform) {
1019 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1020 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1021 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1022 mat4 tr;
1023
1024 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1025 tr = tr * rot90;
1026 }
1027 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1028 tr = tr * flipH;
1029 }
1030 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1031 tr = tr * flipV;
1032 }
1033 return inverse(tr);
1034}
1035
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001036/*
1037 * onDraw will draw the current layer onto the presentable buffer
1038 */
Dan Stozac7014012014-02-14 15:03:43 -08001039void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
1040 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001041{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001042 ATRACE_CALL();
1043
Mathias Agopiana67932f2011-04-20 14:20:59 -07001044 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001045 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -07001046 // in fact never been drawn into. This happens frequently with
1047 // SurfaceView because the WindowManager can't know when the client
1048 // has drawn the first time.
1049
1050 // If there is nothing under us, we paint the screen in black, otherwise
1051 // we just skip this update.
1052
1053 // figure out if there is something below us
1054 Region under;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001055 bool finished = false;
Dan Stoza412903f2017-04-27 13:42:17 -07001056 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001057 if (finished || layer == static_cast<Layer const*>(this)) {
1058 finished = true;
1059 return;
1060 }
Mathias Agopian42977342012-08-05 00:40:46 -07001061 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Robert Carr1f0a16a2016-10-24 16:27:39 -07001062 });
Mathias Agopian179169e2010-05-06 20:21:45 -07001063 // if not everything below us is covered, we plug the holes!
1064 Region holes(clip.subtract(under));
1065 if (!holes.isEmpty()) {
Fabien Sanglard17487192016-12-07 13:03:32 -08001066 clearWithOpenGL(hw, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -07001067 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001068 return;
1069 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001070
Andy McFadden97eba892012-12-11 15:21:45 -08001071 // Bind the current buffer to the GL texture, and wait for it to be
1072 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001073 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1074 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -08001075 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -07001076 // Go ahead and draw the buffer anyway; no matter what we do the screen
1077 // is probably going to have something visibly wrong.
1078 }
1079
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001080 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1081
Mathias Agopian875d8e12013-06-07 15:35:48 -07001082 RenderEngine& engine(mFlinger->getRenderEngine());
1083
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001084 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -07001085 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -07001086 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -07001087
1088 // Query the texture matrix given our current filtering mode.
1089 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001090 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1091 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -07001092
Robert Carrcae605c2017-03-29 12:10:31 -07001093 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001094
1095 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -07001096 * the code below applies the primary display's inverse transform to
1097 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001098 */
Pablo Ceballos021623b2016-04-15 17:31:51 -07001099 uint32_t transform =
1100 DisplayDevice::getPrimaryDisplayOrientationTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001101 mat4 tr = inverseOrientation(transform);
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001102
Robert Carrcae605c2017-03-29 12:10:31 -07001103 /**
1104 * TODO(b/36727915): This is basically a hack.
1105 *
1106 * Ensure that regardless of the parent transformation,
1107 * this buffer is always transformed from native display
1108 * orientation to display orientation. For example, in the case
1109 * of a camera where the buffer remains in native orientation,
1110 * we want the pixels to always be upright.
1111 */
Chia-I Wue41dbe62017-06-13 14:10:56 -07001112 sp<Layer> p = mDrawingParent.promote();
1113 if (p != nullptr) {
1114 const auto parentTransform = p->getTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001115 tr = tr * inverseOrientation(parentTransform.getOrientation());
1116 }
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001117
1118 // and finally apply it to the original texture matrix
1119 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1120 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1121 }
1122
Jamie Genniscbb1a952012-05-08 17:05:52 -07001123 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -07001124 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1125 mTexture.setFiltering(useFiltering);
1126 mTexture.setMatrix(textureMatrix);
1127
1128 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -07001129 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001130 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -07001131 }
Fabien Sanglard85789802016-12-07 13:08:24 -08001132 drawWithOpenGL(hw, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001133 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001134}
1135
Mathias Agopian13127d82013-03-05 17:47:11 -08001136
Dan Stozac7014012014-02-14 15:03:43 -08001137void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard17487192016-12-07 13:03:32 -08001138 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -08001139 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001140{
Mathias Agopian19733a32013-08-28 18:13:56 -07001141 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -08001142 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -07001143 engine.setupFillWithColor(red, green, blue, alpha);
1144 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -08001145}
1146
1147void Layer::clearWithOpenGL(
Fabien Sanglard17487192016-12-07 13:03:32 -08001148 const sp<const DisplayDevice>& hw) const {
1149 clearWithOpenGL(hw, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001150}
1151
Dan Stozac7014012014-02-14 15:03:43 -08001152void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard85789802016-12-07 13:08:24 -08001153 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001154 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001155
Dan Stozac7014012014-02-14 15:03:43 -08001156 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001157
Mathias Agopian13127d82013-03-05 17:47:11 -08001158 /*
1159 * NOTE: the way we compute the texture coordinates here produces
1160 * different results than when we take the HWC path -- in the later case
1161 * the "source crop" is rounded to texel boundaries.
1162 * This can produce significantly different results when the texture
1163 * is scaled by a large amount.
1164 *
1165 * The GL code below is more logical (imho), and the difference with
1166 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001167 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001168 * GL composition when a buffer scaling is applied (maybe with some
1169 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1170 * like more of a hack.
1171 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001172 Rect win(computeBounds());
1173
Robert Carr1f0a16a2016-10-24 16:27:39 -07001174 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -07001175 if (!s.finalCrop.isEmpty()) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001176 win = t.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001177 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001178 win.clear();
1179 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001180 win = t.inverse().transform(win);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001181 if (!win.intersect(computeBounds(), &win)) {
1182 win.clear();
1183 }
1184 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001185
Mathias Agopian3f844832013-08-07 21:24:32 -07001186 float left = float(win.left) / float(s.active.w);
1187 float top = float(win.top) / float(s.active.h);
1188 float right = float(win.right) / float(s.active.w);
1189 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001190
Mathias Agopian875d8e12013-06-07 15:35:48 -07001191 // TODO: we probably want to generate the texture coords with the mesh
1192 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001193 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1194 texCoords[0] = vec2(left, 1.0f - top);
1195 texCoords[1] = vec2(left, 1.0f - bottom);
1196 texCoords[2] = vec2(right, 1.0f - bottom);
1197 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001198
Mathias Agopian875d8e12013-06-07 15:35:48 -07001199 RenderEngine& engine(mFlinger->getRenderEngine());
Robert Carr6452f122017-03-21 10:41:29 -07001200 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), getAlpha());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001201#ifdef USE_HWC2
1202 engine.setSourceDataSpace(mCurrentState.dataSpace);
1203#endif
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001204 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001205 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001206}
1207
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001208#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001209void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1210 bool callIntoHwc) {
1211 if (mHwcLayers.count(hwcId) == 0) {
1212 ALOGE("setCompositionType called without a valid HWC layer");
1213 return;
1214 }
1215 auto& hwcInfo = mHwcLayers[hwcId];
1216 auto& hwcLayer = hwcInfo.layer;
1217 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1218 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1219 if (hwcInfo.compositionType != type) {
1220 ALOGV(" actually setting");
1221 hwcInfo.compositionType = type;
1222 if (callIntoHwc) {
1223 auto error = hwcLayer->setCompositionType(type);
1224 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1225 "composition type %s: %s (%d)", mName.string(),
1226 to_string(type).c_str(), to_string(error).c_str(),
1227 static_cast<int32_t>(error));
1228 }
1229 }
1230}
1231
1232HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001233 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1234 // If we're querying the composition type for a display that does not
1235 // have a HWC counterpart, then it will always be Client
1236 return HWC2::Composition::Client;
1237 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001238 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001239 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001240 return HWC2::Composition::Invalid;
1241 }
1242 return mHwcLayers.at(hwcId).compositionType;
1243}
1244
1245void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1246 if (mHwcLayers.count(hwcId) == 0) {
1247 ALOGE("setClearClientTarget called without a valid HWC layer");
1248 return;
1249 }
1250 mHwcLayers[hwcId].clearClientTarget = clear;
1251}
1252
1253bool Layer::getClearClientTarget(int32_t hwcId) const {
1254 if (mHwcLayers.count(hwcId) == 0) {
1255 ALOGE("getClearClientTarget called without a valid HWC layer");
1256 return false;
1257 }
1258 return mHwcLayers.at(hwcId).clearClientTarget;
1259}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001260#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001261
Ruben Brunk1681d952014-06-27 15:51:55 -07001262uint32_t Layer::getProducerStickyTransform() const {
1263 int producerStickyTransform = 0;
1264 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1265 if (ret != OK) {
1266 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1267 strerror(-ret), ret);
1268 return 0;
1269 }
1270 return static_cast<uint32_t>(producerStickyTransform);
1271}
1272
Dan Stozac5da2712016-07-20 15:38:12 -07001273bool Layer::latchUnsignaledBuffers() {
1274 static bool propertyLoaded = false;
1275 static bool latch = false;
1276 static std::mutex mutex;
1277 std::lock_guard<std::mutex> lock(mutex);
1278 if (!propertyLoaded) {
1279 char value[PROPERTY_VALUE_MAX] = {};
1280 property_get("debug.sf.latch_unsignaled", value, "0");
1281 latch = atoi(value);
1282 propertyLoaded = true;
1283 }
1284 return latch;
1285}
1286
Dan Stozacac35382016-01-27 12:21:06 -08001287uint64_t Layer::getHeadFrameNumber() const {
1288 Mutex::Autolock lock(mQueueItemLock);
1289 if (!mQueueItems.empty()) {
1290 return mQueueItems[0].mFrameNumber;
1291 } else {
1292 return mCurrentFrameNumber;
1293 }
1294}
1295
Dan Stoza1ce65812016-06-15 16:26:27 -07001296bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001297#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001298 if (latchUnsignaledBuffers()) {
1299 return true;
1300 }
1301
Dan Stoza1ce65812016-06-15 16:26:27 -07001302 Mutex::Autolock lock(mQueueItemLock);
1303 if (mQueueItems.empty()) {
1304 return true;
1305 }
1306 if (mQueueItems[0].mIsDroppable) {
1307 // Even though this buffer's fence may not have signaled yet, it could
1308 // be replaced by another buffer before it has a chance to, which means
1309 // that it's possible to get into a situation where a buffer is never
1310 // able to be latched. To avoid this, grab this buffer anyway.
1311 return true;
1312 }
1313 return mQueueItems[0].mFence->getSignalTime() != INT64_MAX;
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{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001420 // if we don't have a buffer yet, we're translucent regardless of the
1421 // layer's opaque flag.
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001422 if (mActiveBuffer == 0) {
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);
1508}
1509
Pablo Ceballos05289c22016-04-14 15:49:55 -07001510void Layer::popPendingState(State* stateToCommit) {
1511 auto oldFlags = stateToCommit->flags;
1512 *stateToCommit = mPendingStates[0];
1513 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1514 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001515
1516 mPendingStates.removeAt(0);
1517}
1518
Pablo Ceballos05289c22016-04-14 15:49:55 -07001519bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001520 bool stateUpdateAvailable = false;
1521 while (!mPendingStates.empty()) {
Robert Carr0d480722017-01-10 16:42:54 -08001522 if (mPendingStates[0].barrierLayer != nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001523 if (mRemoteSyncPoints.empty()) {
1524 // If we don't have a sync point for this, apply it anyway. It
1525 // will be visually wrong, but it should keep us from getting
1526 // into too much trouble.
1527 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001528 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001529 stateUpdateAvailable = true;
1530 continue;
1531 }
1532
Dan Stozacac35382016-01-27 12:21:06 -08001533 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1534 mPendingStates[0].frameNumber) {
1535 ALOGE("[%s] Unexpected sync point frame number found",
1536 mName.string());
1537
1538 // Signal our end of the sync point and then dispose of it
1539 mRemoteSyncPoints.front()->setTransactionApplied();
1540 mRemoteSyncPoints.pop_front();
1541 continue;
1542 }
1543
Dan Stoza7dde5992015-05-22 09:51:44 -07001544 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1545 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001546 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001547 stateUpdateAvailable = true;
1548
1549 // Signal our end of the sync point and then dispose of it
1550 mRemoteSyncPoints.front()->setTransactionApplied();
1551 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001552 } else {
1553 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001554 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001555 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001556 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001557 stateUpdateAvailable = true;
1558 }
1559 }
1560
1561 // If we still have pending updates, wake SurfaceFlinger back up and point
1562 // it at this layer so we can process them
1563 if (!mPendingStates.empty()) {
1564 setTransactionFlags(eTransactionNeeded);
1565 mFlinger->setTransactionFlags(eTraversalNeeded);
1566 }
1567
1568 mCurrentState.modified = false;
1569 return stateUpdateAvailable;
1570}
1571
1572void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001573 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001574 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001575 Mutex::Autolock lock(mLocalSyncPointMutex);
1576 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001577 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001578 point->setFrameAvailable();
1579 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001580 }
1581}
1582
Mathias Agopian13127d82013-03-05 17:47:11 -08001583uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001584 ATRACE_CALL();
1585
Dan Stoza7dde5992015-05-22 09:51:44 -07001586 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001587 Layer::State c = getCurrentState();
1588 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001589 return 0;
1590 }
1591
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001592 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001593
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001594 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1595 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001596
1597 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001598 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001599 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001600 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001601 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001602 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001603 " drawing={ 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",
Robert Carrc3574f72016-03-24 12:19:32 -07001605 this, getName().string(), mCurrentTransform,
1606 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001607 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001608 c.crop.left,
1609 c.crop.top,
1610 c.crop.right,
1611 c.crop.bottom,
1612 c.crop.getWidth(),
1613 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001614 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001615 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001616 s.crop.left,
1617 s.crop.top,
1618 s.crop.right,
1619 s.crop.bottom,
1620 s.crop.getWidth(),
1621 s.crop.getHeight(),
1622 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001623
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001624 // record the new size, form this point on, when the client request
1625 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001626 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001627 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001628 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001629
Robert Carr82364e32016-05-15 11:27:47 -07001630 const bool resizePending = (c.requested.w != c.active.w) ||
1631 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001632 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001633 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001634 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001635 // if we have a pending resize, unless we are in fixed-size mode.
1636 // the drawing state will be updated only once we receive a buffer
1637 // with the correct size.
1638 //
1639 // in particular, we want to make sure the clip (which is part
1640 // of the geometry state) is latched together with the size but is
1641 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001642 //
1643 // If a sideband stream is attached, however, we want to skip this
1644 // optimization so that transactions aren't missed when a buffer
1645 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001646
1647 flags |= eDontUpdateGeometryState;
1648 }
1649 }
1650
Robert Carr7bf247e2017-05-18 14:02:49 -07001651 // Here we apply various requested geometry states, depending on our
1652 // latching configuration. See Layer.h for a detailed discussion of
1653 // how geometry latching is controlled.
1654 if (!(flags & eDontUpdateGeometryState)) {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001655 Layer::State& editCurrentState(getCurrentState());
Robert Carr7bf247e2017-05-18 14:02:49 -07001656
1657 // If mFreezeGeometryUpdates is true we are in the setGeometryAppliesWithResize
1658 // mode, which causes attributes which normally latch regardless of scaling mode,
1659 // to be delayed. We copy the requested state to the active state making sure
1660 // to respect these rules (again see Layer.h for a detailed discussion).
1661 //
1662 // There is an awkward asymmetry in the handling of the crop states in the position
1663 // states, as can be seen below. Largely this arises from position and transform
1664 // being stored in the same data structure while having different latching rules.
1665 // b/38182305
1666 //
1667 // Careful that "c" and editCurrentState may not begin as equivalent due to
1668 // applyPendingStates in the presence of deferred transactions.
1669 if (mFreezeGeometryUpdates) {
Robert Carr82364e32016-05-15 11:27:47 -07001670 float tx = c.active.transform.tx();
1671 float ty = c.active.transform.ty();
1672 c.active = c.requested;
1673 c.active.transform.set(tx, ty);
1674 editCurrentState.active = c.active;
1675 } else {
1676 editCurrentState.active = editCurrentState.requested;
1677 c.active = c.requested;
1678 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001679 }
1680
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001681 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001682 // invalidate and recompute the visible regions if needed
1683 flags |= Layer::eVisibleRegion;
1684 }
1685
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001686 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001687 // invalidate and recompute the visible regions if needed
1688 flags |= eVisibleRegion;
1689 this->contentDirty = true;
1690
1691 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001692 const uint8_t type = c.active.transform.getType();
1693 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001694 (type >= Transform::SCALE));
1695 }
1696
Dan Stozac8145172016-04-28 16:29:06 -07001697 // If the layer is hidden, signal and clear out all local sync points so
1698 // that transactions for layers depending on this layer's frames becoming
1699 // visible are not blocked
1700 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001701 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001702 }
1703
Mathias Agopian13127d82013-03-05 17:47:11 -08001704 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001705 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001706 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001707}
1708
Pablo Ceballos05289c22016-04-14 15:49:55 -07001709void Layer::commitTransaction(const State& stateToCommit) {
1710 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001711}
1712
Mathias Agopian13127d82013-03-05 17:47:11 -08001713uint32_t Layer::getTransactionFlags(uint32_t flags) {
1714 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1715}
1716
1717uint32_t Layer::setTransactionFlags(uint32_t flags) {
1718 return android_atomic_or(flags, &mTransactionFlags);
1719}
1720
Robert Carr82364e32016-05-15 11:27:47 -07001721bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001722 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001723 return false;
1724 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001725
1726 // We update the requested and active position simultaneously because
1727 // we want to apply the position portion of the transform matrix immediately,
1728 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001729 mCurrentState.requested.transform.set(x, y);
Robert Carr7bf247e2017-05-18 14:02:49 -07001730 if (immediate && !mFreezeGeometryUpdates) {
1731 // Here we directly update the active state
1732 // unlike other setters, because we store it within
1733 // the transform, but use different latching rules.
1734 // b/38182305
Robert Carr82364e32016-05-15 11:27:47 -07001735 mCurrentState.active.transform.set(x, y);
1736 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001737 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001738
Dan Stoza7dde5992015-05-22 09:51:44 -07001739 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001740 setTransactionFlags(eTransactionNeeded);
1741 return true;
1742}
Robert Carr82364e32016-05-15 11:27:47 -07001743
Robert Carr1f0a16a2016-10-24 16:27:39 -07001744bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1745 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1746 if (idx < 0) {
1747 return false;
1748 }
1749 if (childLayer->setLayer(z)) {
1750 mCurrentChildren.removeAt(idx);
1751 mCurrentChildren.add(childLayer);
1752 }
1753 return true;
1754}
1755
Robert Carrae060832016-11-28 10:51:00 -08001756bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001757 if (mCurrentState.z == z)
1758 return false;
1759 mCurrentState.sequence++;
1760 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001761 mCurrentState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001762
1763 // Discard all relative layering.
1764 if (mCurrentState.zOrderRelativeOf != nullptr) {
1765 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1766 if (strongRelative != nullptr) {
1767 strongRelative->removeZOrderRelative(this);
1768 }
1769 mCurrentState.zOrderRelativeOf = nullptr;
1770 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001771 setTransactionFlags(eTransactionNeeded);
1772 return true;
1773}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001774
Robert Carrdb66e622017-04-10 16:55:57 -07001775void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1776 mCurrentState.zOrderRelatives.remove(relative);
1777 mCurrentState.sequence++;
1778 mCurrentState.modified = true;
1779 setTransactionFlags(eTransactionNeeded);
1780}
1781
1782void Layer::addZOrderRelative(const wp<Layer>& relative) {
1783 mCurrentState.zOrderRelatives.add(relative);
1784 mCurrentState.modified = true;
1785 mCurrentState.sequence++;
1786 setTransactionFlags(eTransactionNeeded);
1787}
1788
1789bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1790 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1791 if (handle == nullptr) {
1792 return false;
1793 }
1794 sp<Layer> relative = handle->owner.promote();
1795 if (relative == nullptr) {
1796 return false;
1797 }
1798
1799 mCurrentState.sequence++;
1800 mCurrentState.modified = true;
1801 mCurrentState.z = z;
1802
1803 mCurrentState.zOrderRelativeOf = relative;
1804 relative->addZOrderRelative(this);
1805
1806 setTransactionFlags(eTransactionNeeded);
1807
1808 return true;
1809}
1810
Mathias Agopian13127d82013-03-05 17:47:11 -08001811bool Layer::setSize(uint32_t w, uint32_t h) {
1812 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1813 return false;
1814 mCurrentState.requested.w = w;
1815 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001816 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001817 setTransactionFlags(eTransactionNeeded);
1818 return true;
1819}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001820#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001821bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001822#else
1823bool Layer::setAlpha(uint8_t alpha) {
1824#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001825 if (mCurrentState.alpha == alpha)
1826 return false;
1827 mCurrentState.sequence++;
1828 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001829 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001830 setTransactionFlags(eTransactionNeeded);
1831 return true;
1832}
1833bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1834 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001835 mCurrentState.requested.transform.set(
Robert Carrcb6e1e32017-02-21 19:48:26 -08001836 matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001837 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001838 setTransactionFlags(eTransactionNeeded);
1839 return true;
1840}
1841bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001842 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001843 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001844 setTransactionFlags(eTransactionNeeded);
1845 return true;
1846}
1847bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1848 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1849 if (mCurrentState.flags == newFlags)
1850 return false;
1851 mCurrentState.sequence++;
1852 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001853 mCurrentState.mask = mask;
1854 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001855 setTransactionFlags(eTransactionNeeded);
1856 return true;
1857}
Robert Carr99e27f02016-06-16 15:18:02 -07001858
1859bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001860 if (mCurrentState.requestedCrop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001861 return false;
1862 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001863 mCurrentState.requestedCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001864 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr99e27f02016-06-16 15:18:02 -07001865 mCurrentState.crop = crop;
1866 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001867 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1868
Dan Stoza7dde5992015-05-22 09:51:44 -07001869 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001870 setTransactionFlags(eTransactionNeeded);
1871 return true;
1872}
Robert Carr8d5227b2017-03-16 15:41:03 -07001873
1874bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001875 if (mCurrentState.requestedFinalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001876 return false;
1877 mCurrentState.sequence++;
Robert Carr8d5227b2017-03-16 15:41:03 -07001878 mCurrentState.requestedFinalCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001879 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr8d5227b2017-03-16 15:41:03 -07001880 mCurrentState.finalCrop = crop;
1881 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001882 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1883
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001884 mCurrentState.modified = true;
1885 setTransactionFlags(eTransactionNeeded);
1886 return true;
1887}
Mathias Agopian13127d82013-03-05 17:47:11 -08001888
Robert Carrc3574f72016-03-24 12:19:32 -07001889bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1890 if (scalingMode == mOverrideScalingMode)
1891 return false;
1892 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001893 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001894 return true;
1895}
1896
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001897void Layer::setInfo(uint32_t type, uint32_t appId) {
1898 mCurrentState.appId = appId;
1899 mCurrentState.type = type;
1900 mCurrentState.modified = true;
1901 setTransactionFlags(eTransactionNeeded);
1902}
1903
Robert Carrc3574f72016-03-24 12:19:32 -07001904uint32_t Layer::getEffectiveScalingMode() const {
1905 if (mOverrideScalingMode >= 0) {
1906 return mOverrideScalingMode;
1907 }
1908 return mCurrentScalingMode;
1909}
1910
Mathias Agopian13127d82013-03-05 17:47:11 -08001911bool Layer::setLayerStack(uint32_t layerStack) {
1912 if (mCurrentState.layerStack == layerStack)
1913 return false;
1914 mCurrentState.sequence++;
1915 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001916 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001917 setTransactionFlags(eTransactionNeeded);
1918 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001919}
1920
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07001921bool Layer::setDataSpace(android_dataspace dataSpace) {
1922 if (mCurrentState.dataSpace == dataSpace)
1923 return false;
1924 mCurrentState.sequence++;
1925 mCurrentState.dataSpace = dataSpace;
1926 mCurrentState.modified = true;
1927 setTransactionFlags(eTransactionNeeded);
1928 return true;
1929}
1930
Robert Carr1f0a16a2016-10-24 16:27:39 -07001931uint32_t Layer::getLayerStack() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07001932 auto p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001933 if (p == nullptr) {
1934 return getDrawingState().layerStack;
1935 }
1936 return p->getLayerStack();
1937}
1938
Robert Carr0d480722017-01-10 16:42:54 -08001939void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
Dan Stoza7dde5992015-05-22 09:51:44 -07001940 uint64_t frameNumber) {
Robert Carr0d480722017-01-10 16:42:54 -08001941 mCurrentState.barrierLayer = barrierLayer;
Dan Stoza7dde5992015-05-22 09:51:44 -07001942 mCurrentState.frameNumber = frameNumber;
1943 // We don't set eTransactionNeeded, because just receiving a deferral
1944 // request without any other state updates shouldn't actually induce a delay
1945 mCurrentState.modified = true;
1946 pushPendingState();
Robert Carr0d480722017-01-10 16:42:54 -08001947 mCurrentState.barrierLayer = nullptr;
Dan Stoza792e5292016-02-11 11:43:58 -08001948 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07001949 mCurrentState.modified = false;
Robert Carr0d480722017-01-10 16:42:54 -08001950 ALOGE("Deferred transaction");
1951}
1952
1953void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
1954 uint64_t frameNumber) {
1955 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
1956 deferTransactionUntil(handle->owner.promote(), frameNumber);
Dan Stoza7dde5992015-05-22 09:51:44 -07001957}
1958
Dan Stozaee44edd2015-03-23 15:50:23 -07001959void Layer::useSurfaceDamage() {
1960 if (mFlinger->mForceFullDamage) {
1961 surfaceDamageRegion = Region::INVALID_REGION;
1962 } else {
1963 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1964 }
1965}
1966
1967void Layer::useEmptyDamage() {
1968 surfaceDamageRegion.clear();
1969}
1970
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001971// ----------------------------------------------------------------------------
1972// pageflip handling...
1973// ----------------------------------------------------------------------------
1974
Dan Stoza6b9454d2014-11-07 16:00:59 -08001975bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001976 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07001977 return true;
1978 }
1979
Dan Stoza6b9454d2014-11-07 16:00:59 -08001980 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001981 if (mQueueItems.empty()) {
1982 return false;
1983 }
1984 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001985 nsecs_t expectedPresent =
1986 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001987
1988 // Ignore timestamps more than a second in the future
1989 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1990 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1991 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1992 expectedPresent);
1993
1994 bool isDue = timestamp < expectedPresent;
1995 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001996}
1997
Brian Andersond6927fb2016-07-23 23:37:30 -07001998bool Layer::onPreComposition(nsecs_t refreshStartTime) {
1999 if (mBufferLatched) {
2000 Mutex::Autolock lock(mFrameEventHistoryMutex);
2001 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
2002 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08002003 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08002004 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002005}
2006
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002007bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
Brian Anderson3d4039d2016-09-23 16:31:30 -07002008 const std::shared_ptr<FenceTime>& presentFence,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002009 const CompositorTiming& compositorTiming) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002010 mAcquireTimeline.updateSignalTimes();
2011 mReleaseTimeline.updateSignalTimes();
2012
Brian Andersond6927fb2016-07-23 23:37:30 -07002013 // mFrameLatencyNeeded is true when a new frame was latched for the
2014 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08002015 if (!mFrameLatencyNeeded)
2016 return false;
2017
Fabien Sanglard28e98082016-12-05 10:19:46 -08002018 // Update mFrameEventHistory.
2019 {
2020 Mutex::Autolock lock(mFrameEventHistoryMutex);
2021 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002022 glDoneFence, presentFence, compositorTiming);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002023 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08002024
2025 // Update mFrameTracker.
2026 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
2027 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
2028
Brian Anderson3d4039d2016-09-23 16:31:30 -07002029 std::shared_ptr<FenceTime> frameReadyFence =
2030 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08002031 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002032 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002033 } else {
2034 // There was no fence for this frame, so assume that it was ready
2035 // to be presented at the desired present time.
2036 mFrameTracker.setFrameReadyTime(desiredPresentTime);
2037 }
2038
Brian Anderson3d4039d2016-09-23 16:31:30 -07002039 if (presentFence->isValid()) {
2040 mFrameTracker.setActualPresentFence(
2041 std::shared_ptr<FenceTime>(presentFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002042 } else {
2043 // The HWC doesn't support present fences, so use the refresh
2044 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002045 mFrameTracker.setActualPresentTime(
2046 mFlinger->getHwComposer().getRefreshTimestamp(
2047 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002048 }
2049
2050 mFrameTracker.advanceFrame();
2051 mFrameLatencyNeeded = false;
2052 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002053}
2054
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002055#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07002056void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Brian Anderson5ea5e592016-12-01 16:54:33 -08002057 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2058 return;
2059 }
2060
Brian Anderson3d4039d2016-09-23 16:31:30 -07002061 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002062 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002063 mReleaseTimeline.push(releaseFenceTime);
2064
2065 Mutex::Autolock lock(mFrameEventHistoryMutex);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002066 if (mPreviousFrameNumber != 0) {
2067 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2068 dequeueReadyTime, std::move(releaseFenceTime));
2069 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002070}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002071#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002072
Robert Carr1f0a16a2016-10-24 16:27:39 -07002073bool Layer::isHiddenByPolicy() const {
2074 const Layer::State& s(mDrawingState);
Chia-I Wue41dbe62017-06-13 14:10:56 -07002075 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002076 if (parent != nullptr && parent->isHiddenByPolicy()) {
2077 return true;
2078 }
2079 return s.flags & layer_state_t::eLayerHidden;
2080}
2081
Mathias Agopianda27af92012-09-13 18:17:13 -07002082bool Layer::isVisible() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002083#ifdef USE_HWC2
Robert Carr6452f122017-03-21 10:41:29 -07002084 return !(isHiddenByPolicy()) && getAlpha() > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08002085 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002086#else
Robert Carr6452f122017-03-21 10:41:29 -07002087 return !(isHiddenByPolicy()) && getAlpha()
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002088 && (mActiveBuffer != NULL || mSidebandStream != NULL);
2089#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07002090}
2091
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002092bool Layer::allTransactionsSignaled() {
2093 auto headFrameNumber = getHeadFrameNumber();
2094 bool matchingFramesFound = false;
2095 bool allTransactionsApplied = true;
2096 Mutex::Autolock lock(mLocalSyncPointMutex);
2097
2098 for (auto& point : mLocalSyncPoints) {
2099 if (point->getFrameNumber() > headFrameNumber) {
2100 break;
2101 }
2102 matchingFramesFound = true;
2103
2104 if (!point->frameIsAvailable()) {
2105 // We haven't notified the remote layer that the frame for
2106 // this point is available yet. Notify it now, and then
2107 // abort this attempt to latch.
2108 point->setFrameAvailable();
2109 allTransactionsApplied = false;
2110 break;
2111 }
2112
2113 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2114 }
2115 return !matchingFramesFound || allTransactionsApplied;
2116}
2117
Brian Andersond6927fb2016-07-23 23:37:30 -07002118Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002119{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08002120 ATRACE_CALL();
2121
Jesse Hall399184a2014-03-03 15:42:54 -08002122 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2123 // mSidebandStreamChanged was true
2124 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07002125 if (mSidebandStream != NULL) {
2126 setTransactionFlags(eTransactionNeeded);
2127 mFlinger->setTransactionFlags(eTraversalNeeded);
2128 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07002129 recomputeVisibleRegions = true;
2130
2131 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07002132 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08002133 }
2134
Mathias Agopian4fec8732012-06-29 14:12:52 -07002135 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07002136 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2137 return outDirtyRegion;
2138 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002139
Fabien Sanglard223eb912016-10-13 10:15:06 -07002140 // if we've already called updateTexImage() without going through
2141 // a composition step, we have to skip this layer at this point
2142 // because we cannot call updateTeximage() without a corresponding
2143 // compositionComplete() call.
2144 // we'll trigger an update in onPreComposition().
2145 if (mRefreshPending) {
2146 return outDirtyRegion;
2147 }
2148
2149 // If the head buffer's acquire fence hasn't signaled yet, return and
2150 // try again later
2151 if (!headFenceHasSignaled()) {
2152 mFlinger->signalLayerUpdate();
2153 return outDirtyRegion;
2154 }
2155
2156 // Capture the old state of the layer for comparisons later
2157 const State& s(getDrawingState());
2158 const bool oldOpacity = isOpaque(s);
2159 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2160
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002161 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002162 mFlinger->signalLayerUpdate();
2163 return outDirtyRegion;
2164 }
2165
2166 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2167 // of the buffer queue isn't modified when the buffer queue is returning
2168 // BufferItem's that weren't actually queued. This can happen in shared
2169 // buffer mode.
2170 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002171 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2172 getProducerStickyTransform() != 0, mName.string(),
Robert Carr7bf247e2017-05-18 14:02:49 -07002173 mOverrideScalingMode, mFreezeGeometryUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002174 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2175 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2176 mLastFrameNumberReceived);
2177 if (updateResult == BufferQueue::PRESENT_LATER) {
2178 // Producer doesn't want buffer to be displayed yet. Signal a
2179 // layer update so we check again at the next opportunity.
2180 mFlinger->signalLayerUpdate();
2181 return outDirtyRegion;
2182 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2183 // If the buffer has been rejected, remove it from the shadow queue
2184 // and return early
2185 if (queuedBuffer) {
2186 Mutex::Autolock lock(mQueueItemLock);
2187 mQueueItems.removeAt(0);
2188 android_atomic_dec(&mQueuedFrames);
2189 }
2190 return outDirtyRegion;
2191 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2192 // This can occur if something goes wrong when trying to create the
2193 // EGLImage for this buffer. If this happens, the buffer has already
2194 // been released, so we need to clean up the queue and bug out
2195 // early.
2196 if (queuedBuffer) {
2197 Mutex::Autolock lock(mQueueItemLock);
2198 mQueueItems.clear();
2199 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002200 }
2201
Fabien Sanglard223eb912016-10-13 10:15:06 -07002202 // Once we have hit this state, the shadow queue may no longer
2203 // correctly reflect the incoming BufferQueue's contents, so even if
2204 // updateTexImage starts working, the only safe course of action is
2205 // to continue to ignore updates.
2206 mUpdateTexImageFailed = true;
2207
2208 return outDirtyRegion;
2209 }
2210
2211 if (queuedBuffer) {
2212 // Autolock scope
2213 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2214
2215 Mutex::Autolock lock(mQueueItemLock);
2216
2217 // Remove any stale buffers that have been dropped during
2218 // updateTexImage
2219 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2220 mQueueItems.removeAt(0);
2221 android_atomic_dec(&mQueuedFrames);
2222 }
2223
2224 mQueueItems.removeAt(0);
2225 }
2226
2227
2228 // Decrement the queued-frames count. Signal another event if we
2229 // have more frames pending.
2230 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2231 || mAutoRefresh) {
2232 mFlinger->signalLayerUpdate();
2233 }
2234
Fabien Sanglard223eb912016-10-13 10:15:06 -07002235 // update the active buffer
Chia-I Wu06d63de2017-01-04 14:58:51 +08002236 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2237 &mActiveBufferSlot);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002238 if (mActiveBuffer == NULL) {
2239 // this can only happen if the very first buffer was rejected.
2240 return outDirtyRegion;
2241 }
2242
Brian Andersond6927fb2016-07-23 23:37:30 -07002243 mBufferLatched = true;
2244 mPreviousFrameNumber = mCurrentFrameNumber;
2245 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2246
2247 {
2248 Mutex::Autolock lock(mFrameEventHistoryMutex);
2249 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2250#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002251 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002252 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002253 mReleaseTimeline.push(releaseFenceTime);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002254 if (mPreviousFrameNumber != 0) {
2255 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2256 latchTime, std::move(releaseFenceTime));
2257 }
Brian Andersond6927fb2016-07-23 23:37:30 -07002258#endif
2259 }
2260
Fabien Sanglard223eb912016-10-13 10:15:06 -07002261 mRefreshPending = true;
2262 mFrameLatencyNeeded = true;
2263 if (oldActiveBuffer == NULL) {
2264 // the first time we receive a buffer, we need to trigger a
2265 // geometry invalidation.
2266 recomputeVisibleRegions = true;
2267 }
2268
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002269 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2270
Fabien Sanglard223eb912016-10-13 10:15:06 -07002271 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2272 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2273 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2274 if ((crop != mCurrentCrop) ||
2275 (transform != mCurrentTransform) ||
2276 (scalingMode != mCurrentScalingMode))
2277 {
2278 mCurrentCrop = crop;
2279 mCurrentTransform = transform;
2280 mCurrentScalingMode = scalingMode;
2281 recomputeVisibleRegions = true;
2282 }
2283
2284 if (oldActiveBuffer != NULL) {
2285 uint32_t bufWidth = mActiveBuffer->getWidth();
2286 uint32_t bufHeight = mActiveBuffer->getHeight();
2287 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2288 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002289 recomputeVisibleRegions = true;
2290 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002291 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002292
Fabien Sanglard223eb912016-10-13 10:15:06 -07002293 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2294 if (oldOpacity != isOpaque(s)) {
2295 recomputeVisibleRegions = true;
2296 }
Dan Stozacac35382016-01-27 12:21:06 -08002297
Fabien Sanglard223eb912016-10-13 10:15:06 -07002298 // Remove any sync points corresponding to the buffer which was just
2299 // latched
2300 {
2301 Mutex::Autolock lock(mLocalSyncPointMutex);
2302 auto point = mLocalSyncPoints.begin();
2303 while (point != mLocalSyncPoints.end()) {
2304 if (!(*point)->frameIsAvailable() ||
2305 !(*point)->transactionIsApplied()) {
2306 // This sync point must have been added since we started
2307 // latching. Don't drop it yet.
2308 ++point;
2309 continue;
2310 }
2311
2312 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2313 point = mLocalSyncPoints.erase(point);
2314 } else {
2315 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002316 }
2317 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002318 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002319
2320 // FIXME: postedRegion should be dirty & bounds
2321 Region dirtyRegion(Rect(s.active.w, s.active.h));
2322
2323 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002324 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002325
Mathias Agopian4fec8732012-06-29 14:12:52 -07002326 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002327}
2328
Mathias Agopiana67932f2011-04-20 14:20:59 -07002329uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002330{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002331 // TODO: should we do something special if mSecure is set?
2332 if (mProtectedByApp) {
2333 // need a hardware-protected path to external video sink
2334 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002335 }
Riley Andrews03414a12014-07-01 14:22:59 -07002336 if (mPotentialCursor) {
2337 usage |= GraphicBuffer::USAGE_CURSOR;
2338 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002339 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002340 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002341}
2342
Mathias Agopian84300952012-11-21 16:02:13 -08002343void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002344 uint32_t orientation = 0;
2345 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002346 // The transform hint is used to improve performance, but we can
2347 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002348 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002349 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002350 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002351 if (orientation & Transform::ROT_INVALID) {
2352 orientation = 0;
2353 }
2354 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002355 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002356}
2357
Mathias Agopian13127d82013-03-05 17:47:11 -08002358// ----------------------------------------------------------------------------
2359// debugging
2360// ----------------------------------------------------------------------------
2361
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002362void Layer::dump(String8& result, Colorizer& colorizer) const
Mathias Agopian13127d82013-03-05 17:47:11 -08002363{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002364 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08002365
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002366 colorizer.colorize(result, Colorizer::GREEN);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002367 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002368 "+ %s %p (%s)\n",
2369 getTypeId(), this, getName().string());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002370 colorizer.reset(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002371
Mathias Agopian2ca79392013-04-02 18:30:32 -07002372 s.activeTransparentRegion.dump(result, "transparentRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002373 visibleRegion.dump(result, "visibleRegion");
Dan Stozaee44edd2015-03-23 15:50:23 -07002374 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002375 sp<Client> client(mClientRef.promote());
2376
Mathias Agopian74d211a2013-04-22 16:55:35 +02002377 result.appendFormat( " "
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002378 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2379 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
Mathias Agopian13127d82013-03-05 17:47:11 -08002380 "isOpaque=%1d, invalidate=%1d, "
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002381#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08002382 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002383#else
2384 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2385#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08002386 " client=%p\n",
Robert Carr1f0a16a2016-10-24 16:27:39 -07002387 getLayerStack(), s.z,
2388 s.active.transform.tx(), s.active.transform.ty(),
2389 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07002390 s.crop.left, s.crop.top,
2391 s.crop.right, s.crop.bottom,
2392 s.finalCrop.left, s.finalCrop.top,
2393 s.finalCrop.right, s.finalCrop.bottom,
Andy McFadden4125a4f2014-01-29 17:17:11 -08002394 isOpaque(s), contentDirty,
Mathias Agopian13127d82013-03-05 17:47:11 -08002395 s.alpha, s.flags,
Robert Carr3dcabfa2016-03-01 18:36:58 -08002396 s.active.transform[0][0], s.active.transform[0][1],
2397 s.active.transform[1][0], s.active.transform[1][1],
Mathias Agopian13127d82013-03-05 17:47:11 -08002398 client.get());
Mathias Agopian13127d82013-03-05 17:47:11 -08002399
2400 sp<const GraphicBuffer> buf0(mActiveBuffer);
2401 uint32_t w0=0, h0=0, s0=0, f0=0;
2402 if (buf0 != 0) {
2403 w0 = buf0->getWidth();
2404 h0 = buf0->getHeight();
2405 s0 = buf0->getStride();
2406 f0 = buf0->format;
2407 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02002408 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002409 " "
2410 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2411 " queued-frames=%d, mRefreshPending=%d\n",
2412 mFormat, w0, h0, s0,f0,
2413 mQueuedFrames, mRefreshPending);
2414
Mathias Agopian13127d82013-03-05 17:47:11 -08002415 if (mSurfaceFlingerConsumer != 0) {
Colin Cross3d1d2802016-09-26 18:10:16 -07002416 mSurfaceFlingerConsumer->dumpState(result, " ");
Mathias Agopian13127d82013-03-05 17:47:11 -08002417 }
2418}
2419
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002420#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002421void Layer::miniDumpHeader(String8& result) {
2422 result.append("----------------------------------------");
2423 result.append("---------------------------------------\n");
2424 result.append(" Layer name\n");
2425 result.append(" Z | ");
2426 result.append(" Comp Type | ");
2427 result.append(" Disp Frame (LTRB) | ");
2428 result.append(" Source Crop (LTRB)\n");
2429 result.append("----------------------------------------");
2430 result.append("---------------------------------------\n");
2431}
2432
2433void Layer::miniDump(String8& result, int32_t hwcId) const {
2434 if (mHwcLayers.count(hwcId) == 0) {
2435 return;
2436 }
2437
2438 String8 name;
2439 if (mName.length() > 77) {
2440 std::string shortened;
2441 shortened.append(mName.string(), 36);
2442 shortened.append("[...]");
2443 shortened.append(mName.string() + (mName.length() - 36), 36);
2444 name = shortened.c_str();
2445 } else {
2446 name = mName;
2447 }
2448
2449 result.appendFormat(" %s\n", name.string());
2450
2451 const Layer::State& layerState(getDrawingState());
2452 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2453 result.appendFormat(" %10u | ", layerState.z);
2454 result.appendFormat("%10s | ",
2455 to_string(getCompositionType(hwcId)).c_str());
2456 const Rect& frame = hwcInfo.displayFrame;
2457 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2458 frame.right, frame.bottom);
Dan Stoza5a423ea2017-02-16 14:10:39 -08002459 const FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002460 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2461 crop.right, crop.bottom);
2462
2463 result.append("- - - - - - - - - - - - - - - - - - - - ");
2464 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2465}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002466#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002467
Svetoslavd85084b2014-03-20 10:28:31 -07002468void Layer::dumpFrameStats(String8& result) const {
2469 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002470}
2471
Svetoslavd85084b2014-03-20 10:28:31 -07002472void Layer::clearFrameStats() {
2473 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002474}
2475
Jamie Gennis6547ff42013-07-16 20:12:42 -07002476void Layer::logFrameStats() {
2477 mFrameTracker.logAndResetStats(mName);
2478}
2479
Svetoslavd85084b2014-03-20 10:28:31 -07002480void Layer::getFrameStats(FrameStats* outStats) const {
2481 mFrameTracker.getStats(outStats);
2482}
2483
Brian Andersond6927fb2016-07-23 23:37:30 -07002484void Layer::dumpFrameEvents(String8& result) {
2485 result.appendFormat("- Layer %s (%s, %p)\n",
2486 getName().string(), getTypeId(), this);
2487 Mutex::Autolock lock(mFrameEventHistoryMutex);
2488 mFrameEventHistory.checkFencesForCompletion();
2489 mFrameEventHistory.dump(result);
2490}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002491
Brian Anderson5ea5e592016-12-01 16:54:33 -08002492void Layer::onDisconnect() {
2493 Mutex::Autolock lock(mFrameEventHistoryMutex);
2494 mFrameEventHistory.onDisconnect();
2495}
2496
Brian Anderson3890c392016-07-25 12:48:08 -07002497void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2498 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002499 Mutex::Autolock lock(mFrameEventHistoryMutex);
2500 if (newTimestamps) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002501 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002502 mFrameEventHistory.addQueue(*newTimestamps);
2503 }
2504
Brian Anderson3890c392016-07-25 12:48:08 -07002505 if (outDelta) {
2506 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002507 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002508}
Dan Stozae77c7662016-05-13 11:37:28 -07002509
2510std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2511 bool forceFlush) {
2512 std::vector<OccupancyTracker::Segment> history;
2513 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2514 &history);
2515 if (result != NO_ERROR) {
2516 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2517 result);
2518 return {};
2519 }
2520 return history;
2521}
2522
Robert Carr367c5682016-06-20 11:55:28 -07002523bool Layer::getTransformToDisplayInverse() const {
2524 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2525}
2526
Chia-I Wue6b63e12017-05-30 14:54:08 -07002527size_t Layer::getChildrenCount() const {
2528 size_t count = 0;
2529 for (const sp<Layer>& child : mCurrentChildren) {
2530 count += 1 + child->getChildrenCount();
2531 }
2532 return count;
2533}
2534
Robert Carr1f0a16a2016-10-24 16:27:39 -07002535void Layer::addChild(const sp<Layer>& layer) {
2536 mCurrentChildren.add(layer);
2537 layer->setParent(this);
2538}
2539
2540ssize_t Layer::removeChild(const sp<Layer>& layer) {
2541 layer->setParent(nullptr);
2542 return mCurrentChildren.remove(layer);
2543}
2544
Robert Carr1db73f62016-12-21 12:58:51 -08002545bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2546 sp<Handle> handle = nullptr;
2547 sp<Layer> newParent = nullptr;
2548 if (newParentHandle == nullptr) {
2549 return false;
2550 }
2551 handle = static_cast<Handle*>(newParentHandle.get());
2552 newParent = handle->owner.promote();
2553 if (newParent == nullptr) {
2554 ALOGE("Unable to promote Layer handle");
2555 return false;
2556 }
2557
2558 for (const sp<Layer>& child : mCurrentChildren) {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002559 newParent->addChild(child);
Robert Carr1db73f62016-12-21 12:58:51 -08002560
2561 sp<Client> client(child->mClientRef.promote());
2562 if (client != nullptr) {
2563 client->setParentLayer(newParent);
2564 }
2565 }
2566 mCurrentChildren.clear();
2567
2568 return true;
2569}
2570
Robert Carr9524cb32017-02-13 11:32:32 -08002571bool Layer::detachChildren() {
Dan Stoza412903f2017-04-27 13:42:17 -07002572 traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
Robert Carr9524cb32017-02-13 11:32:32 -08002573 if (child == this) {
2574 return;
2575 }
2576
2577 sp<Client> client(child->mClientRef.promote());
2578 if (client != nullptr) {
2579 client->detachLayer(child);
2580 }
2581 });
2582
2583 return true;
2584}
2585
Robert Carr1f0a16a2016-10-24 16:27:39 -07002586void Layer::setParent(const sp<Layer>& layer) {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002587 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002588}
2589
2590void Layer::clearSyncPoints() {
2591 for (const auto& child : mCurrentChildren) {
2592 child->clearSyncPoints();
2593 }
2594
2595 Mutex::Autolock lock(mLocalSyncPointMutex);
2596 for (auto& point : mLocalSyncPoints) {
2597 point->setFrameAvailable();
2598 }
2599 mLocalSyncPoints.clear();
2600}
2601
2602int32_t Layer::getZ() const {
2603 return mDrawingState.z;
2604}
2605
Dan Stoza412903f2017-04-27 13:42:17 -07002606LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2607 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2608 "makeTraversalList received invalid stateSet");
2609 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2610 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2611 const State& state = useDrawing ? mDrawingState : mCurrentState;
2612
2613 if (state.zOrderRelatives.size() == 0) {
2614 return children;
Robert Carrdb66e622017-04-10 16:55:57 -07002615 }
2616 LayerVector traverse;
2617
Dan Stoza412903f2017-04-27 13:42:17 -07002618 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07002619 sp<Layer> strongRelative = weakRelative.promote();
2620 if (strongRelative != nullptr) {
2621 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07002622 }
2623 }
2624
Dan Stoza412903f2017-04-27 13:42:17 -07002625 for (const sp<Layer>& child : children) {
Robert Carrdb66e622017-04-10 16:55:57 -07002626 traverse.add(child);
2627 }
2628
2629 return traverse;
2630}
2631
Robert Carr1f0a16a2016-10-24 16:27:39 -07002632/**
Robert Carrdb66e622017-04-10 16:55:57 -07002633 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002634 */
Dan Stoza412903f2017-04-27 13:42:17 -07002635void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2636 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002637
Robert Carr1f0a16a2016-10-24 16:27:39 -07002638 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002639 for (; i < list.size(); i++) {
2640 const auto& relative = list[i];
2641 if (relative->getZ() >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002642 break;
Robert Carrdb66e622017-04-10 16:55:57 -07002643 }
Dan Stoza412903f2017-04-27 13:42:17 -07002644 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002645 }
Dan Stoza412903f2017-04-27 13:42:17 -07002646 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07002647 for (; i < list.size(); i++) {
2648 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002649 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002650 }
2651}
2652
2653/**
Robert Carrdb66e622017-04-10 16:55:57 -07002654 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002655 */
Dan Stoza412903f2017-04-27 13:42:17 -07002656void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2657 const LayerVector::Visitor& visitor) {
2658 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002659
Robert Carr1f0a16a2016-10-24 16:27:39 -07002660 int32_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002661 for (i = list.size()-1; i>=0; i--) {
2662 const auto& relative = list[i];
2663 if (relative->getZ() < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002664 break;
2665 }
Dan Stoza412903f2017-04-27 13:42:17 -07002666 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002667 }
Dan Stoza412903f2017-04-27 13:42:17 -07002668 visitor(this);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002669 for (; i>=0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002670 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002671 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002672 }
2673}
2674
2675Transform Layer::getTransform() const {
2676 Transform t;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002677 const auto& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002678 if (p != nullptr) {
2679 t = p->getTransform();
Robert Carr9b429f42017-04-17 14:56:57 -07002680
2681 // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2682 // it isFixedSize) then there may be additional scaling not accounted
2683 // for in the transform. We need to mirror this scaling in child surfaces
2684 // or we will break the contract where WM can treat child surfaces as
2685 // pixels in the parent surface.
2686 if (p->isFixedSize()) {
Robert Carr1725eee2017-04-26 18:32:15 -07002687 int bufferWidth;
2688 int bufferHeight;
2689 if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2690 bufferWidth = p->mActiveBuffer->getWidth();
2691 bufferHeight = p->mActiveBuffer->getHeight();
2692 } else {
2693 bufferHeight = p->mActiveBuffer->getWidth();
2694 bufferWidth = p->mActiveBuffer->getHeight();
2695 }
Robert Carr9b429f42017-04-17 14:56:57 -07002696 float sx = p->getDrawingState().active.w /
Robert Carr1725eee2017-04-26 18:32:15 -07002697 static_cast<float>(bufferWidth);
Robert Carr9b429f42017-04-17 14:56:57 -07002698 float sy = p->getDrawingState().active.h /
Robert Carr1725eee2017-04-26 18:32:15 -07002699 static_cast<float>(bufferHeight);
Robert Carr9b429f42017-04-17 14:56:57 -07002700 Transform extraParentScaling;
2701 extraParentScaling.set(sx, 0, 0, sy);
2702 t = t * extraParentScaling;
2703 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002704 }
2705 return t * getDrawingState().active.transform;
2706}
2707
Robert Carr6452f122017-03-21 10:41:29 -07002708#ifdef USE_HWC2
2709float Layer::getAlpha() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002710 const auto& p = mDrawingParent.promote();
Robert Carr6452f122017-03-21 10:41:29 -07002711
2712 float parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0;
2713 return parentAlpha * getDrawingState().alpha;
2714}
2715#else
2716uint8_t Layer::getAlpha() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002717 const auto& p = mDrawingParent.promote();
Robert Carr6452f122017-03-21 10:41:29 -07002718
2719 float parentAlpha = (p != nullptr) ? (p->getAlpha() / 255.0f) : 1.0;
2720 float drawingAlpha = getDrawingState().alpha / 255.0f;
2721 drawingAlpha = drawingAlpha * parentAlpha;
2722 return static_cast<uint8_t>(std::round(drawingAlpha * 255));
2723}
2724#endif
2725
Robert Carr1f0a16a2016-10-24 16:27:39 -07002726void Layer::commitChildList() {
2727 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2728 const auto& child = mCurrentChildren[i];
2729 child->commitChildList();
2730 }
2731 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002732 mDrawingParent = mCurrentParent;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002733}
2734
Mathias Agopian13127d82013-03-05 17:47:11 -08002735// ---------------------------------------------------------------------------
2736
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002737}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002738
2739#if defined(__gl_h_)
2740#error "don't include gl/gl.h in this file"
2741#endif
2742
2743#if defined(__gl2_h_)
2744#error "don't include gl2/gl2.h in this file"
2745#endif