blob: 1fa3faa8a4c13567e17c6449fe1cd5f69fdca684 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017//#define LOG_NDEBUG 0
18#undef LOG_TAG
19#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080020#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <stdlib.h>
23#include <stdint.h>
24#include <sys/types.h>
Mathias Agopian13127d82013-03-05 17:47:11 -080025#include <math.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080026
Mathias Agopiana67932f2011-04-20 14:20:59 -070027#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070028#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070029#include <cutils/properties.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
31#include <utils/Errors.h>
32#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080033#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080034#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080035#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080036
Courtney Goeltzenleuchter36c44dc2017-04-14 09:33:16 -060037#include <ui/DebugUtils.h>
Mathias Agopian3330b202009-10-05 17:07:12 -070038#include <ui/GraphicBuffer.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080039#include <ui/PixelFormat.h>
Mathias Agopian9cce3252010-02-09 17:46:37 -080040
Dan Stoza6b9454d2014-11-07 16:00:59 -080041#include <gui/BufferItem.h>
Mathias Agopiana9347642017-02-13 16:42:28 -080042#include <gui/BufferQueue.h>
Mathias Agopian90ac7992012-02-25 18:48:35 -080043#include <gui/Surface.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080044
45#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020046#include "Colorizer.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070047#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080048#include "Layer.h"
Fabien Sanglard7b1563a2016-10-13 12:05:28 -070049#include "LayerRejecter.h"
Dan Stozab9b08832014-03-13 11:55:57 -070050#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080051#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080052
Mathias Agopian1b031492012-06-20 17:51:20 -070053#include "DisplayHardware/HWComposer.h"
54
Mathias Agopian875d8e12013-06-07 15:35:48 -070055#include "RenderEngine/RenderEngine.h"
56
Dan Stozac5da2712016-07-20 15:38:12 -070057#include <mutex>
58
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059#define DEBUG_RESIZE 0
60
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061namespace android {
62
63// ---------------------------------------------------------------------------
64
Mathias Agopian13127d82013-03-05 17:47:11 -080065int32_t Layer::sSequence = 1;
66
Mathias Agopian4d9b8222013-03-12 17:11:48 -070067Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
68 const String8& name, uint32_t w, uint32_t h, uint32_t flags)
Mathias Agopian13127d82013-03-05 17:47:11 -080069 : contentDirty(false),
70 sequence(uint32_t(android_atomic_inc(&sSequence))),
71 mFlinger(flinger),
Mathias Agopiana67932f2011-04-20 14:20:59 -070072 mTextureName(-1U),
Mathias Agopian13127d82013-03-05 17:47:11 -080073 mPremultipliedAlpha(true),
74 mName("unnamed"),
Mathias Agopian13127d82013-03-05 17:47:11 -080075 mFormat(PIXEL_FORMAT_NONE),
Mathias Agopian13127d82013-03-05 17:47:11 -080076 mTransactionFlags(0),
Dan Stoza7dde5992015-05-22 09:51:44 -070077 mPendingStateMutex(),
78 mPendingStates(),
Mathias Agopiana67932f2011-04-20 14:20:59 -070079 mQueuedFrames(0),
Jesse Hall399184a2014-03-03 15:42:54 -080080 mSidebandStreamChanged(false),
Mathias Agopiana9347642017-02-13 16:42:28 -080081 mActiveBufferSlot(BufferQueue::INVALID_BUFFER_SLOT),
Mathias Agopiana67932f2011-04-20 14:20:59 -070082 mCurrentTransform(0),
Mathias Agopian933389f2011-07-18 16:15:08 -070083 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
Robert Carrc3574f72016-03-24 12:19:32 -070084 mOverrideScalingMode(-1),
Mathias Agopiana67932f2011-04-20 14:20:59 -070085 mCurrentOpacity(true),
Brian Andersond6927fb2016-07-23 23:37:30 -070086 mBufferLatched(false),
Dan Stozacac35382016-01-27 12:21:06 -080087 mCurrentFrameNumber(0),
Brian Anderson8cc8b102016-10-21 12:43:09 -070088 mPreviousFrameNumber(0),
Mathias Agopian4d143ee2012-02-23 20:05:39 -080089 mRefreshPending(false),
Mathias Agopian82d7ab62012-01-19 18:34:40 -080090 mFrameLatencyNeeded(false),
Mathias Agopian13127d82013-03-05 17:47:11 -080091 mFiltering(false),
92 mNeedsFiltering(false),
Mathias Agopian5cdc8992013-08-13 20:51:23 -070093 mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
Fabien Sanglard9d96de42016-10-11 00:15:18 +000094#ifndef USE_HWC2
95 mIsGlesComposition(false),
96#endif
Mathias Agopian13127d82013-03-05 17:47:11 -080097 mProtectedByApp(false),
98 mHasSurface(false),
Riley Andrews03414a12014-07-01 14:22:59 -070099 mClientRef(client),
Dan Stozaa4650a52015-05-12 12:56:16 -0700100 mPotentialCursor(false),
101 mQueueItemLock(),
102 mQueueItemCondition(),
103 mQueueItems(),
Dan Stoza65476f32015-05-14 09:27:25 -0700104 mLastFrameNumberReceived(0),
Pablo Ceballos04839ab2015-11-13 13:39:23 -0800105 mUpdateTexImageFailed(false),
Robert Carr82364e32016-05-15 11:27:47 -0700106 mAutoRefresh(false),
Robert Carr7bf247e2017-05-18 14:02:49 -0700107 mFreezeGeometryUpdates(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800108{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000109#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800110 ALOGV("Creating Layer %s", name.string());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000111#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -0800112
Mathias Agopiana67932f2011-04-20 14:20:59 -0700113 mCurrentCrop.makeInvalid();
Mathias Agopian3f844832013-08-07 21:24:32 -0700114 mFlinger->getRenderEngine().genTextures(1, &mTextureName);
Mathias Agopian49457ac2013-08-14 18:20:17 -0700115 mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700116
117 uint32_t layerFlags = 0;
118 if (flags & ISurfaceComposerClient::eHidden)
Andy McFadden4125a4f2014-01-29 17:17:11 -0800119 layerFlags |= layer_state_t::eLayerHidden;
120 if (flags & ISurfaceComposerClient::eOpaque)
121 layerFlags |= layer_state_t::eLayerOpaque;
Dan Stoza23116082015-06-18 14:58:39 -0700122 if (flags & ISurfaceComposerClient::eSecure)
123 layerFlags |= layer_state_t::eLayerSecure;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700124
125 if (flags & ISurfaceComposerClient::eNonPremultiplied)
126 mPremultipliedAlpha = false;
127
128 mName = name;
Dan Stozaf7ba41a2017-05-10 15:11:11 -0700129 mTransactionName = String8("TX - ") + mName;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700130
131 mCurrentState.active.w = w;
132 mCurrentState.active.h = h;
Robert Carr3dcabfa2016-03-01 18:36:58 -0800133 mCurrentState.active.transform.set(0, 0);
Robert Carrb5d3d262016-03-25 15:08:13 -0700134 mCurrentState.crop.makeInvalid();
135 mCurrentState.finalCrop.makeInvalid();
Robert Carr7bf247e2017-05-18 14:02:49 -0700136 mCurrentState.requestedFinalCrop = mCurrentState.finalCrop;
137 mCurrentState.requestedCrop = mCurrentState.crop;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700138 mCurrentState.z = 0;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000139#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800140 mCurrentState.alpha = 1.0f;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000141#else
142 mCurrentState.alpha = 0xFF;
143#endif
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700144 mCurrentState.layerStack = 0;
145 mCurrentState.flags = layerFlags;
146 mCurrentState.sequence = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700147 mCurrentState.requested = mCurrentState.active;
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700148 mCurrentState.dataSpace = HAL_DATASPACE_UNKNOWN;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500149 mCurrentState.appId = 0;
150 mCurrentState.type = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700151
152 // drawing state & current state are identical
153 mDrawingState = mCurrentState;
Jamie Gennis6547ff42013-07-16 20:12:42 -0700154
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000155#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800156 const auto& hwc = flinger->getHwComposer();
157 const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
158 nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000159#else
160 nsecs_t displayPeriod =
161 flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
162#endif
Jamie Gennis6547ff42013-07-16 20:12:42 -0700163 mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -0800164
165 CompositorTiming compositorTiming;
166 flinger->getCompositorTiming(&compositorTiming);
167 mFrameEventHistory.initializeCompositorTiming(compositorTiming);
Jamie Gennise8696a42012-01-15 18:54:57 -0800168}
169
Mathias Agopian3f844832013-08-07 21:24:32 -0700170void Layer::onFirstRef() {
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800171 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
Dan Stozab3d0bdf2014-04-07 16:33:59 -0700172 sp<IGraphicBufferProducer> producer;
173 sp<IGraphicBufferConsumer> consumer;
Mathias Agopian0556d792017-03-22 15:49:32 -0700174 BufferQueue::createBufferQueue(&producer, &consumer, true);
Robert Carr1db73f62016-12-21 12:58:51 -0800175 mProducer = new MonitoredProducer(producer, mFlinger, this);
Irvel468051e2016-06-13 16:44:44 -0700176 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800177 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Jesse Hall399184a2014-03-03 15:42:54 -0800178 mSurfaceFlingerConsumer->setContentsChangedListener(this);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700179 mSurfaceFlingerConsumer->setName(mName);
Daniel Lamb2675792012-02-23 14:35:13 -0800180
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800181 if (mFlinger->isLayerTripleBufferingDisabled()) {
182 mProducer->setMaxDequeuedBufferCount(2);
183 }
Andy McFadden69052052012-09-14 16:10:11 -0700184
Mathias Agopian84300952012-11-21 16:02:13 -0800185 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
186 updateTransformHint(hw);
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700187}
188
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700189Layer::~Layer() {
Pablo Ceballos8ea4e7b2016-03-03 15:20:02 -0800190 sp<Client> c(mClientRef.promote());
191 if (c != 0) {
192 c->detachLayer(this);
193 }
194
Dan Stozacac35382016-01-27 12:21:06 -0800195 for (auto& point : mRemoteSyncPoints) {
196 point->setTransactionApplied();
197 }
Dan Stozac8145172016-04-28 16:29:06 -0700198 for (auto& point : mLocalSyncPoints) {
199 point->setFrameAvailable();
200 }
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700201 mFlinger->deleteTextureAsync(mTextureName);
Jamie Gennis6547ff42013-07-16 20:12:42 -0700202 mFrameTracker.logAndResetStats(mName);
Mathias Agopian96f08192010-06-02 23:28:45 -0700203}
204
Mathias Agopian13127d82013-03-05 17:47:11 -0800205// ---------------------------------------------------------------------------
206// callbacks
207// ---------------------------------------------------------------------------
208
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000209#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800210void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800211 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
212}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000213#else
214void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
215 HWComposer::HWCLayerInterface* layer) {
216 if (layer) {
217 layer->onDisplayed();
218 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
219 }
220}
221#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800222
Dan Stoza6b9454d2014-11-07 16:00:59 -0800223void Layer::onFrameAvailable(const BufferItem& item) {
224 // Add this buffer from our internal queue tracker
225 { // Autolock scope
226 Mutex::Autolock lock(mQueueItemLock);
Irvel468051e2016-06-13 16:44:44 -0700227 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
228 item.mGraphicBuffer->getHeight(), item.mFrameNumber);
Dan Stozaa4650a52015-05-12 12:56:16 -0700229 // Reset the frame number tracker when we receive the first buffer after
230 // a frame number reset
231 if (item.mFrameNumber == 1) {
232 mLastFrameNumberReceived = 0;
233 }
234
235 // Ensure that callbacks are handled in order
236 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
237 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
238 ms2ns(500));
239 if (result != NO_ERROR) {
240 ALOGE("[%s] Timed out waiting on callback", mName.string());
241 }
242 }
243
Dan Stoza6b9454d2014-11-07 16:00:59 -0800244 mQueueItems.push_back(item);
Dan Stozaecc50402015-04-28 14:42:06 -0700245 android_atomic_inc(&mQueuedFrames);
Dan Stozaa4650a52015-05-12 12:56:16 -0700246
247 // Wake up any pending callbacks
248 mLastFrameNumberReceived = item.mFrameNumber;
249 mQueueItemCondition.broadcast();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800250 }
251
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800252 mFlinger->signalLayerUpdate();
Mathias Agopian579b3f82010-06-08 19:54:15 -0700253}
254
Dan Stoza6b9454d2014-11-07 16:00:59 -0800255void Layer::onFrameReplaced(const BufferItem& item) {
Dan Stoza7dde5992015-05-22 09:51:44 -0700256 { // Autolock scope
257 Mutex::Autolock lock(mQueueItemLock);
Dan Stozaa4650a52015-05-12 12:56:16 -0700258
Dan Stoza7dde5992015-05-22 09:51:44 -0700259 // Ensure that callbacks are handled in order
260 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
261 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
262 ms2ns(500));
263 if (result != NO_ERROR) {
264 ALOGE("[%s] Timed out waiting on callback", mName.string());
265 }
Dan Stozaa4650a52015-05-12 12:56:16 -0700266 }
Dan Stoza7dde5992015-05-22 09:51:44 -0700267
268 if (mQueueItems.empty()) {
269 ALOGE("Can't replace a frame on an empty queue");
270 return;
271 }
Pablo Ceballos4d85da42016-04-19 20:11:56 -0700272 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
Dan Stoza7dde5992015-05-22 09:51:44 -0700273
274 // Wake up any pending callbacks
275 mLastFrameNumberReceived = item.mFrameNumber;
276 mQueueItemCondition.broadcast();
Dan Stozaa4650a52015-05-12 12:56:16 -0700277 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800278}
279
Jesse Hall399184a2014-03-03 15:42:54 -0800280void Layer::onSidebandStreamChanged() {
281 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
282 // mSidebandStreamChanged was false
283 mFlinger->signalLayerUpdate();
284 }
285}
286
Mathias Agopian67106042013-03-14 19:18:13 -0700287// called with SurfaceFlinger::mStateLock from the drawing thread after
288// the layer has been remove from the current state list (and just before
289// it's removed from the drawing state list)
Mathias Agopian13127d82013-03-05 17:47:11 -0800290void Layer::onRemoved() {
Robert Carr5edb1ad2017-04-25 10:54:24 -0700291 if (mCurrentState.zOrderRelativeOf != nullptr) {
292 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
293 if (strongRelative != nullptr) {
294 strongRelative->removeZOrderRelative(this);
295 }
296 mCurrentState.zOrderRelativeOf = nullptr;
297 }
298
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800299 mSurfaceFlingerConsumer->abandon();
Chia-I Wu38512252017-05-17 14:36:16 -0700300
301#ifdef USE_HWC2
302 clearHwcLayers();
303#endif
304
Robert Carr1f0a16a2016-10-24 16:27:39 -0700305 for (const auto& child : mCurrentChildren) {
306 child->onRemoved();
307 }
Mathias Agopian48d819a2009-09-10 19:41:18 -0700308}
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700309
Mathias Agopian13127d82013-03-05 17:47:11 -0800310// ---------------------------------------------------------------------------
311// set-up
312// ---------------------------------------------------------------------------
313
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700314const String8& Layer::getName() const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800315 return mName;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800316}
317
Mathias Agopianf9d93272009-06-19 17:00:27 -0700318status_t Layer::setBuffers( uint32_t w, uint32_t h,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800319 PixelFormat format, uint32_t flags)
320{
Mathias Agopianca99fb82010-04-14 16:43:44 -0700321 uint32_t const maxSurfaceDims = min(
Mathias Agopiana4912602012-07-12 14:25:33 -0700322 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
Mathias Agopianca99fb82010-04-14 16:43:44 -0700323
324 // never allow a surface larger than what our underlying GL implementation
325 // can handle.
326 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
Mathias Agopianff615cc2012-02-24 14:58:36 -0800327 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700328 return BAD_VALUE;
329 }
330
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700331 mFormat = format;
Mathias Agopianeff062c2010-08-25 14:59:15 -0700332
Riley Andrews03414a12014-07-01 14:22:59 -0700333 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
Mathias Agopian3165cc22012-08-08 19:42:09 -0700334 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700335 mCurrentOpacity = getOpacityForFormat(format);
336
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800337 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
338 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
339 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700340
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800341 return NO_ERROR;
342}
343
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700344sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800345 Mutex::Autolock _l(mLock);
346
347 LOG_ALWAYS_FATAL_IF(mHasSurface,
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700348 "Layer::getHandle() has already been called");
Mathias Agopian13127d82013-03-05 17:47:11 -0800349
350 mHasSurface = true;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700351
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700352 return new Handle(mFlinger, this);
Mathias Agopian13127d82013-03-05 17:47:11 -0800353}
354
Dan Stozab9b08832014-03-13 11:55:57 -0700355sp<IGraphicBufferProducer> Layer::getProducer() const {
356 return mProducer;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700357}
358
Mathias Agopian13127d82013-03-05 17:47:11 -0800359// ---------------------------------------------------------------------------
360// h/w composer set-up
361// ---------------------------------------------------------------------------
362
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800363Rect Layer::getContentCrop() const {
364 // this is the crop rectangle that applies to the buffer
365 // itself (as opposed to the window)
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700366 Rect crop;
367 if (!mCurrentCrop.isEmpty()) {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800368 // if the buffer crop is defined, we use that
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700369 crop = mCurrentCrop;
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800370 } else if (mActiveBuffer != NULL) {
371 // otherwise we use the whole buffer
372 crop = mActiveBuffer->getBounds();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700373 } else {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800374 // if we don't have a buffer yet, we use an empty/invalid crop
Mathias Agopian4fec8732012-06-29 14:12:52 -0700375 crop.makeInvalid();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700376 }
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700377 return crop;
378}
379
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700380static Rect reduce(const Rect& win, const Region& exclude) {
381 if (CC_LIKELY(exclude.isEmpty())) {
382 return win;
383 }
384 if (exclude.isRect()) {
385 return win.reduce(exclude.getBounds());
386 }
387 return Region(win).subtract(exclude).getBounds();
388}
389
Robert Carr1f0a16a2016-10-24 16:27:39 -0700390Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
391 const Layer::State& s(getDrawingState());
392 Rect win(s.active.w, s.active.h);
393
394 if (!s.crop.isEmpty()) {
395 win.intersect(s.crop, &win);
396 }
397
398 Transform t = getTransform();
399 win = t.transform(win);
400
Robert Carr41b08b52017-06-01 16:11:34 -0700401 if (!s.finalCrop.isEmpty()) {
402 win.intersect(s.finalCrop, &win);
403 }
404
Chia-I Wue41dbe62017-06-13 14:10:56 -0700405 const sp<Layer>& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700406 // Now we need to calculate the parent bounds, so we can clip ourselves to those.
407 // When calculating the parent bounds for purposes of clipping,
408 // we don't need to constrain the parent to its transparent region.
409 // The transparent region is an optimization based on the
410 // buffer contents of the layer, but does not affect the space allocated to
411 // it by policy, and thus children should be allowed to extend into the
412 // parent's transparent region. In fact one of the main uses, is to reduce
413 // buffer allocation size in cases where a child window sits behind a main window
414 // (by marking the hole in the parent window as a transparent region)
415 if (p != nullptr) {
416 Rect bounds = p->computeScreenBounds(false);
417 bounds.intersect(win, &win);
418 }
419
420 if (reduceTransparentRegion) {
421 auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
422 win = reduce(win, screenTransparentRegion);
423 }
424
425 return win;
426}
427
Mathias Agopian13127d82013-03-05 17:47:11 -0800428Rect Layer::computeBounds() const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700429 const Layer::State& s(getDrawingState());
Michael Lentine6c925ed2014-09-26 17:55:01 -0700430 return computeBounds(s.activeTransparentRegion);
431}
432
433Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
434 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800435 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700436
437 if (!s.crop.isEmpty()) {
438 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -0800439 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700440
441 Rect bounds = win;
Chia-I Wue41dbe62017-06-13 14:10:56 -0700442 const auto& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700443 if (p != nullptr) {
Robert Carrde9ec442017-02-08 17:43:36 -0800444 // Look in computeScreenBounds recursive call for explanation of
445 // why we pass false here.
446 bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700447 }
448
449 Transform t = getTransform();
450 if (p != nullptr) {
451 win = t.transform(win);
452 win.intersect(bounds, &win);
453 win = t.inverse().transform(win);
454 }
455
Mathias Agopian6c7f25a2013-05-09 20:37:10 -0700456 // subtract the transparent region and snap to the bounds
Michael Lentine6c925ed2014-09-26 17:55:01 -0700457 return reduce(win, activeTransparentRegion);
Mathias Agopian13127d82013-03-05 17:47:11 -0800458}
459
Robert Carr1f0a16a2016-10-24 16:27:39 -0700460Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
Robert Carrb5d3d262016-03-25 15:08:13 -0700461 // the crop is the area of the window that gets cropped, but not
Mathias Agopian13127d82013-03-05 17:47:11 -0800462 // scaled in any ways.
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700463 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800464
465 // apply the projection's clipping to the window crop in
466 // layerstack space, and convert-back to layer space.
Mathias Agopian6b442672013-07-09 21:24:52 -0700467 // if there are no window scaling involved, this operation will map to full
468 // pixels in the buffer.
469 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
470 // a viewport clipping and a window transform. we should use floating point to fix this.
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700471
472 Rect activeCrop(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700473 if (!s.crop.isEmpty()) {
Chia-I Wudf7867f2017-07-20 14:24:37 -0700474 activeCrop.intersect(s.crop, &activeCrop);
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700475 }
476
Robert Carr1f0a16a2016-10-24 16:27:39 -0700477 Transform t = getTransform();
478 activeCrop = t.transform(activeCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000479 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
480 activeCrop.clear();
481 }
Robert Carrb5d3d262016-03-25 15:08:13 -0700482 if (!s.finalCrop.isEmpty()) {
483 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000484 activeCrop.clear();
485 }
486 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700487 return activeCrop;
488}
489
Dan Stoza5a423ea2017-02-16 14:10:39 -0800490FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
Robert Carr1f0a16a2016-10-24 16:27:39 -0700491 // the content crop is the area of the content that gets scaled to the
492 // layer's size. This is in buffer space.
Dan Stoza5a423ea2017-02-16 14:10:39 -0800493 FloatRect crop = getContentCrop().toFloatRect();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700494
495 // In addition there is a WM-specified crop we pull from our drawing state.
496 const State& s(getDrawingState());
497
498 // Screen space to make reduction to parent crop clearer.
499 Rect activeCrop = computeInitialCrop(hw);
Chia-I Wue41dbe62017-06-13 14:10:56 -0700500 const auto& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700501 if (p != nullptr) {
502 auto parentCrop = p->computeInitialCrop(hw);
503 activeCrop.intersect(parentCrop, &activeCrop);
504 }
505 Transform t = getTransform();
506 // Back to layer space to work with the content crop.
507 activeCrop = t.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800508
Michael Lentine28ea2172014-11-19 18:32:37 -0800509 // This needs to be here as transform.transform(Rect) computes the
510 // transformed rect and then takes the bounding box of the result before
511 // returning. This means
512 // transform.inverse().transform(transform.transform(Rect)) != Rect
513 // in which case we need to make sure the final rect is clipped to the
514 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000515 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
516 activeCrop.clear();
517 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800518
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700519 // subtract the transparent region and snap to the bounds
520 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
521
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000522 // Transform the window crop to match the buffer coordinate system,
523 // which means using the inverse of the current transform set on the
524 // SurfaceFlingerConsumer.
525 uint32_t invTransform = mCurrentTransform;
Robert Carrcae605c2017-03-29 12:10:31 -0700526 if (getTransformToDisplayInverse()) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000527 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700528 * the code below applies the primary display's inverse transform to the
529 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000530 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700531 uint32_t invTransformOrient =
532 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000533 // calculate the inverse transform
534 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
535 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
536 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800537 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000538 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700539 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
540 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800541 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000542
543 int winWidth = s.active.w;
544 int winHeight = s.active.h;
545 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
546 // If the activeCrop has been rotate the ends are rotated but not
547 // the space itself so when transforming ends back we can't rely on
548 // a modification of the axes of rotation. To account for this we
549 // need to reorient the inverse rotation in terms of the current
550 // axes of rotation.
551 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
552 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
553 if (is_h_flipped == is_v_flipped) {
554 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
555 NATIVE_WINDOW_TRANSFORM_FLIP_H;
556 }
557 winWidth = s.active.h;
558 winHeight = s.active.w;
559 }
560 const Rect winCrop = activeCrop.transform(
561 invTransform, s.active.w, s.active.h);
562
563 // below, crop is intersected with winCrop expressed in crop's coordinate space
564 float xScale = crop.getWidth() / float(winWidth);
565 float yScale = crop.getHeight() / float(winHeight);
566
567 float insetL = winCrop.left * xScale;
568 float insetT = winCrop.top * yScale;
569 float insetR = (winWidth - winCrop.right ) * xScale;
570 float insetB = (winHeight - winCrop.bottom) * yScale;
571
572 crop.left += insetL;
573 crop.top += insetT;
574 crop.right -= insetR;
575 crop.bottom -= insetB;
576
Mathias Agopian13127d82013-03-05 17:47:11 -0800577 return crop;
578}
579
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000580#ifdef USE_HWC2
Robert Carrae060832016-11-28 10:51:00 -0800581void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000582#else
583void Layer::setGeometry(
584 const sp<const DisplayDevice>& hw,
585 HWComposer::HWCLayerInterface& layer)
586#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700587{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000588#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800589 const auto hwcId = displayDevice->getHwcDisplayId();
590 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000591#else
592 layer.setDefaultState();
593#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700594
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700595 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000596#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800597 hwcInfo.forceClientComposition = false;
598
599 if (isSecure() && !displayDevice->isSecure()) {
600 hwcInfo.forceClientComposition = true;
601 }
602
603 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000604#else
605 layer.setSkip(false);
606
607 if (isSecure() && !hw->isSecure()) {
608 layer.setSkip(true);
609 }
610#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700611
Mathias Agopian13127d82013-03-05 17:47:11 -0800612 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700613 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000614#ifdef USE_HWC2
David Revemanecf0fa52017-03-03 11:32:44 -0500615 auto blendMode = HWC2::BlendMode::None;
Robert Carr6452f122017-03-21 10:41:29 -0700616 if (!isOpaque(s) || getAlpha() != 1.0f) {
David Revemanecf0fa52017-03-03 11:32:44 -0500617 blendMode = mPremultipliedAlpha ?
Dan Stoza9e56aa02015-11-02 13:00:03 -0800618 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800619 }
David Revemanecf0fa52017-03-03 11:32:44 -0500620 auto error = hwcLayer->setBlendMode(blendMode);
621 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
622 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
623 to_string(error).c_str(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000624#else
Robert Carr6452f122017-03-21 10:41:29 -0700625 if (!isOpaque(s) || getAlpha() != 0xFF) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000626 layer.setBlending(mPremultipliedAlpha ?
627 HWC_BLENDING_PREMULT :
628 HWC_BLENDING_COVERAGE);
629 }
630#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800631
632 // apply the layer's transform, followed by the display's global transform
633 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700634 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700635 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -0700636 if (!s.crop.isEmpty()) {
637 Rect activeCrop(s.crop);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700638 activeCrop = t.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000639#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000640 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000641#else
642 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
643#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000644 activeCrop.clear();
645 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700646 activeCrop = t.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800647 // This needs to be here as transform.transform(Rect) computes the
648 // transformed rect and then takes the bounding box of the result before
649 // returning. This means
650 // transform.inverse().transform(transform.transform(Rect)) != Rect
651 // in which case we need to make sure the final rect is clipped to the
652 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000653 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
654 activeCrop.clear();
655 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700656 // mark regions outside the crop as transparent
657 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
658 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
659 s.active.w, s.active.h));
660 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
661 activeCrop.left, activeCrop.bottom));
662 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
663 s.active.w, activeCrop.bottom));
664 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700665
666 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700667 if (!s.finalCrop.isEmpty()) {
668 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000669 frame.clear();
670 }
671 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000672#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000673 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
674 frame.clear();
675 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800676 const Transform& tr(displayDevice->getTransform());
677 Rect transformedFrame = tr.transform(frame);
David Revemanecf0fa52017-03-03 11:32:44 -0500678 error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700679 if (error != HWC2::Error::None) {
680 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
681 mName.string(), transformedFrame.left, transformedFrame.top,
682 transformedFrame.right, transformedFrame.bottom,
683 to_string(error).c_str(), static_cast<int32_t>(error));
684 } else {
685 hwcInfo.displayFrame = transformedFrame;
686 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800687
Dan Stoza5a423ea2017-02-16 14:10:39 -0800688 FloatRect sourceCrop = computeCrop(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800689 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700690 if (error != HWC2::Error::None) {
691 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
692 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
693 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
694 static_cast<int32_t>(error));
695 } else {
696 hwcInfo.sourceCrop = sourceCrop;
697 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800698
Robert Carr6452f122017-03-21 10:41:29 -0700699 float alpha = getAlpha();
700 error = hwcLayer->setPlaneAlpha(alpha);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800701 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
Robert Carr6452f122017-03-21 10:41:29 -0700702 "%s (%d)", mName.string(), alpha, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800703 static_cast<int32_t>(error));
704
Robert Carrae060832016-11-28 10:51:00 -0800705 error = hwcLayer->setZOrder(z);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800706 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
Robert Carrae060832016-11-28 10:51:00 -0800707 mName.string(), z, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800708 static_cast<int32_t>(error));
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500709
Albert Chaulk2a589632017-05-04 16:59:44 -0400710 int type = s.type;
711 int appId = s.appId;
Chia-I Wue41dbe62017-06-13 14:10:56 -0700712 sp<Layer> parent = mDrawingParent.promote();
Albert Chaulk2a589632017-05-04 16:59:44 -0400713 if (parent.get()) {
714 auto& parentState = parent->getDrawingState();
715 type = parentState.type;
716 appId = parentState.appId;
717 }
718
719 error = hwcLayer->setInfo(type, appId);
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500720 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
721 mName.string(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000722#else
723 if (!frame.intersect(hw->getViewport(), &frame)) {
724 frame.clear();
725 }
726 const Transform& tr(hw->getTransform());
727 layer.setFrame(tr.transform(frame));
728 layer.setCrop(computeCrop(hw));
Robert Carr6452f122017-03-21 10:41:29 -0700729 layer.setPlaneAlpha(getAlpha());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000730#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800731
Mathias Agopian29a367b2011-07-12 14:51:45 -0700732 /*
733 * Transformations are applied in this order:
734 * 1) buffer orientation/flip/mirror
735 * 2) state transformation (window manager)
736 * 3) layer orientation (screen orientation)
737 * (NOTE: the matrices are multiplied in reverse order)
738 */
739
740 const Transform bufferOrientation(mCurrentTransform);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700741 Transform transform(tr * t * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700742
Robert Carrcae605c2017-03-29 12:10:31 -0700743 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700744 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700745 * the code below applies the primary display's inverse transform to the
746 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700747 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700748 uint32_t invTransform =
749 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700750 // calculate the inverse transform
751 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
752 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
753 NATIVE_WINDOW_TRANSFORM_FLIP_H;
754 }
Robert Carrcae605c2017-03-29 12:10:31 -0700755
756 /*
757 * Here we cancel out the orientation component of the WM transform.
758 * The scaling and translate components are already included in our bounds
759 * computation so it's enough to just omit it in the composition.
760 * See comment in onDraw with ref to b/36727915 for why.
761 */
762 transform = Transform(invTransform) * tr * bufferOrientation;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700763 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700764
765 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800766 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000767#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800768 if (orientation & Transform::ROT_INVALID) {
769 // we can only handle simple transformation
770 hwcInfo.forceClientComposition = true;
771 } else {
772 auto transform = static_cast<HWC2::Transform>(orientation);
773 auto error = hwcLayer->setTransform(transform);
774 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
775 "%s (%d)", mName.string(), to_string(transform).c_str(),
776 to_string(error).c_str(), static_cast<int32_t>(error));
777 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000778#else
779 if (orientation & Transform::ROT_INVALID) {
780 // we can only handle simple transformation
781 layer.setSkip(true);
782 } else {
783 layer.setTransform(orientation);
784 }
785#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700786}
787
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000788#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800789void Layer::forceClientComposition(int32_t hwcId) {
790 if (mHwcLayers.count(hwcId) == 0) {
791 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
792 return;
793 }
794
795 mHwcLayers[hwcId].forceClientComposition = true;
796}
Dan Stoza9e56aa02015-11-02 13:00:03 -0800797
Dan Stoza9e56aa02015-11-02 13:00:03 -0800798void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
799 // Apply this display's projection's viewport to the visible region
800 // before giving it to the HWC HAL.
801 const Transform& tr = displayDevice->getTransform();
802 const auto& viewport = displayDevice->getViewport();
803 Region visible = tr.transform(visibleRegion.intersect(viewport));
804 auto hwcId = displayDevice->getHwcDisplayId();
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800805 auto& hwcInfo = mHwcLayers[hwcId];
806 auto& hwcLayer = hwcInfo.layer;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800807 auto error = hwcLayer->setVisibleRegion(visible);
808 if (error != HWC2::Error::None) {
809 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
810 to_string(error).c_str(), static_cast<int32_t>(error));
811 visible.dump(LOG_TAG);
812 }
813
814 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
815 if (error != HWC2::Error::None) {
816 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
817 to_string(error).c_str(), static_cast<int32_t>(error));
818 surfaceDamageRegion.dump(LOG_TAG);
819 }
820
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700821 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800822 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700823 setCompositionType(hwcId, HWC2::Composition::Sideband);
824 ALOGV("[%s] Requesting Sideband composition", mName.string());
825 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800826 if (error != HWC2::Error::None) {
827 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
828 mName.string(), mSidebandStream->handle(),
829 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800830 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700831 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800832 }
833
Dan Stoza0a21df72016-07-20 12:52:38 -0700834 // Client layers
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800835 if (hwcInfo.forceClientComposition ||
Dan Stoza0a21df72016-07-20 12:52:38 -0700836 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700837 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800838 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700839 return;
840 }
841
Dan Stoza0a21df72016-07-20 12:52:38 -0700842 // SolidColor layers
843 if (mActiveBuffer == nullptr) {
844 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700845
846 // For now, we only support black for DimLayer
Dan Stoza0a21df72016-07-20 12:52:38 -0700847 error = hwcLayer->setColor({0, 0, 0, 255});
848 if (error != HWC2::Error::None) {
849 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
850 to_string(error).c_str(), static_cast<int32_t>(error));
851 }
Dan Stozac6c89542016-07-27 10:16:52 -0700852
853 // Clear out the transform, because it doesn't make sense absent a
854 // source buffer
855 error = hwcLayer->setTransform(HWC2::Transform::None);
856 if (error != HWC2::Error::None) {
857 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
858 to_string(error).c_str(), static_cast<int32_t>(error));
859 }
860
Dan Stoza0a21df72016-07-20 12:52:38 -0700861 return;
862 }
863
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700864 // Device or Cursor layers
865 if (mPotentialCursor) {
866 ALOGV("[%s] Requesting Cursor composition", mName.string());
867 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800868 } else {
869 ALOGV("[%s] Requesting Device composition", mName.string());
870 setCompositionType(hwcId, HWC2::Composition::Device);
871 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700872
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700873 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
874 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
875 if (error != HWC2::Error::None) {
876 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
877 mCurrentState.dataSpace, to_string(error).c_str(),
878 static_cast<int32_t>(error));
879 }
880
Chia-I Wu06d63de2017-01-04 14:58:51 +0800881 uint32_t hwcSlot = 0;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400882 sp<GraphicBuffer> hwcBuffer;
883 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
884 &hwcSlot, &hwcBuffer);
Chia-I Wu06d63de2017-01-04 14:58:51 +0800885
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700886 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400887 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700888 if (error != HWC2::Error::None) {
889 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
890 mActiveBuffer->handle, to_string(error).c_str(),
891 static_cast<int32_t>(error));
892 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800893}
Courtney Goeltzenleuchter9551fd32016-10-20 17:18:15 -0600894
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000895#else
896void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
897 HWComposer::HWCLayerInterface& layer) {
898 // we have to set the visible region on every frame because
899 // we currently free it during onLayerDisplayed(), which is called
900 // after HWComposer::commit() -- every frame.
901 // Apply this display's projection's viewport to the visible region
902 // before giving it to the HWC HAL.
903 const Transform& tr = hw->getTransform();
904 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
905 layer.setVisibleRegionScreen(visible);
906 layer.setSurfaceDamage(surfaceDamageRegion);
907 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700908
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000909 if (mSidebandStream.get()) {
910 layer.setSidebandStream(mSidebandStream);
911 } else {
912 // NOTE: buffer can be NULL if the client never drew into this
913 // layer yet, or if we ran out of memory
914 layer.setBuffer(mActiveBuffer);
915 }
916}
917#endif
918
919#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800920void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
921 auto hwcId = displayDevice->getHwcDisplayId();
922 if (mHwcLayers.count(hwcId) == 0 ||
923 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
924 return;
925 }
926
927 // This gives us only the "orientation" component of the transform
928 const State& s(getCurrentState());
929
930 // Apply the layer's transform, followed by the display's global transform
931 // Here we're guaranteed that the layer's transform preserves rects
932 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700933 if (!s.crop.isEmpty()) {
934 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800935 }
936 // Subtract the transparent region and snap to the bounds
937 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700938 Rect frame(getTransform().transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800939 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -0700940 if (!s.finalCrop.isEmpty()) {
941 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000942 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800943 auto& displayTransform(displayDevice->getTransform());
944 auto position = displayTransform.transform(frame);
945
946 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
947 position.top);
948 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
949 "to (%d, %d): %s (%d)", mName.string(), position.left,
950 position.top, to_string(error).c_str(),
951 static_cast<int32_t>(error));
952}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000953#else
954void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
955 HWComposer::HWCLayerInterface& layer) {
956 int fenceFd = -1;
957
958 // TODO: there is a possible optimization here: we only need to set the
959 // acquire fence the first time a new buffer is acquired on EACH display.
960
961 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
962 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
963 if (fence->isValid()) {
964 fenceFd = fence->dup();
965 if (fenceFd == -1) {
966 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
967 }
968 }
969 }
970 layer.setAcquireFenceFd(fenceFd);
971}
972
973Rect Layer::getPosition(
974 const sp<const DisplayDevice>& hw)
975{
976 // this gives us only the "orientation" component of the transform
977 const State& s(getCurrentState());
978
979 // apply the layer's transform, followed by the display's global transform
980 // here we're guaranteed that the layer's transform preserves rects
981 Rect win(s.active.w, s.active.h);
982 if (!s.crop.isEmpty()) {
983 win.intersect(s.crop, &win);
984 }
985 // subtract the transparent region and snap to the bounds
986 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700987 Rect frame(getTransform().transform(bounds));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000988 frame.intersect(hw->getViewport(), &frame);
989 if (!s.finalCrop.isEmpty()) {
990 frame.intersect(s.finalCrop, &frame);
991 }
992 const Transform& tr(hw->getTransform());
993 return Rect(tr.transform(frame));
994}
995#endif
Riley Andrews03414a12014-07-01 14:22:59 -0700996
Mathias Agopian13127d82013-03-05 17:47:11 -0800997// ---------------------------------------------------------------------------
998// drawing...
999// ---------------------------------------------------------------------------
1000
1001void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -08001002 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -08001003}
1004
Dan Stozac7014012014-02-14 15:03:43 -08001005void Layer::draw(const sp<const DisplayDevice>& hw,
1006 bool useIdentityTransform) const {
1007 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001008}
1009
Dan Stozac7014012014-02-14 15:03:43 -08001010void Layer::draw(const sp<const DisplayDevice>& hw) const {
1011 onDraw(hw, Region(hw->bounds()), false);
1012}
1013
Robert Carrcae605c2017-03-29 12:10:31 -07001014static constexpr mat4 inverseOrientation(uint32_t transform) {
1015 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1016 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1017 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1018 mat4 tr;
1019
1020 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1021 tr = tr * rot90;
1022 }
1023 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1024 tr = tr * flipH;
1025 }
1026 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1027 tr = tr * flipV;
1028 }
1029 return inverse(tr);
1030}
1031
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001032/*
1033 * onDraw will draw the current layer onto the presentable buffer
1034 */
Dan Stozac7014012014-02-14 15:03:43 -08001035void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
1036 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001037{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001038 ATRACE_CALL();
1039
Mathias Agopiana67932f2011-04-20 14:20:59 -07001040 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001041 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -07001042 // in fact never been drawn into. This happens frequently with
1043 // SurfaceView because the WindowManager can't know when the client
1044 // has drawn the first time.
1045
1046 // If there is nothing under us, we paint the screen in black, otherwise
1047 // we just skip this update.
1048
1049 // figure out if there is something below us
1050 Region under;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001051 bool finished = false;
Dan Stoza412903f2017-04-27 13:42:17 -07001052 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001053 if (finished || layer == static_cast<Layer const*>(this)) {
1054 finished = true;
1055 return;
1056 }
Mathias Agopian42977342012-08-05 00:40:46 -07001057 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Robert Carr1f0a16a2016-10-24 16:27:39 -07001058 });
Mathias Agopian179169e2010-05-06 20:21:45 -07001059 // if not everything below us is covered, we plug the holes!
1060 Region holes(clip.subtract(under));
1061 if (!holes.isEmpty()) {
Fabien Sanglard17487192016-12-07 13:03:32 -08001062 clearWithOpenGL(hw, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -07001063 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001064 return;
1065 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001066
Andy McFadden97eba892012-12-11 15:21:45 -08001067 // Bind the current buffer to the GL texture, and wait for it to be
1068 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001069 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1070 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -08001071 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -07001072 // Go ahead and draw the buffer anyway; no matter what we do the screen
1073 // is probably going to have something visibly wrong.
1074 }
1075
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001076 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1077
Mathias Agopian875d8e12013-06-07 15:35:48 -07001078 RenderEngine& engine(mFlinger->getRenderEngine());
1079
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001080 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -07001081 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -07001082 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -07001083
1084 // Query the texture matrix given our current filtering mode.
1085 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001086 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1087 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -07001088
Robert Carrcae605c2017-03-29 12:10:31 -07001089 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001090
1091 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -07001092 * the code below applies the primary display's inverse transform to
1093 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001094 */
Pablo Ceballos021623b2016-04-15 17:31:51 -07001095 uint32_t transform =
1096 DisplayDevice::getPrimaryDisplayOrientationTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001097 mat4 tr = inverseOrientation(transform);
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001098
Robert Carrcae605c2017-03-29 12:10:31 -07001099 /**
1100 * TODO(b/36727915): This is basically a hack.
1101 *
1102 * Ensure that regardless of the parent transformation,
1103 * this buffer is always transformed from native display
1104 * orientation to display orientation. For example, in the case
1105 * of a camera where the buffer remains in native orientation,
1106 * we want the pixels to always be upright.
1107 */
Chia-I Wue41dbe62017-06-13 14:10:56 -07001108 sp<Layer> p = mDrawingParent.promote();
1109 if (p != nullptr) {
1110 const auto parentTransform = p->getTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001111 tr = tr * inverseOrientation(parentTransform.getOrientation());
1112 }
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001113
1114 // and finally apply it to the original texture matrix
1115 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1116 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1117 }
1118
Jamie Genniscbb1a952012-05-08 17:05:52 -07001119 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -07001120 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1121 mTexture.setFiltering(useFiltering);
1122 mTexture.setMatrix(textureMatrix);
1123
1124 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -07001125 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001126 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -07001127 }
Fabien Sanglard85789802016-12-07 13:08:24 -08001128 drawWithOpenGL(hw, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001129 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001130}
1131
Mathias Agopian13127d82013-03-05 17:47:11 -08001132
Dan Stozac7014012014-02-14 15:03:43 -08001133void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard17487192016-12-07 13:03:32 -08001134 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -08001135 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001136{
Mathias Agopian19733a32013-08-28 18:13:56 -07001137 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -08001138 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -07001139 engine.setupFillWithColor(red, green, blue, alpha);
1140 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -08001141}
1142
1143void Layer::clearWithOpenGL(
Fabien Sanglard17487192016-12-07 13:03:32 -08001144 const sp<const DisplayDevice>& hw) const {
1145 clearWithOpenGL(hw, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001146}
1147
Dan Stozac7014012014-02-14 15:03:43 -08001148void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard85789802016-12-07 13:08:24 -08001149 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001150 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001151
Dan Stozac7014012014-02-14 15:03:43 -08001152 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001153
Mathias Agopian13127d82013-03-05 17:47:11 -08001154 /*
1155 * NOTE: the way we compute the texture coordinates here produces
1156 * different results than when we take the HWC path -- in the later case
1157 * the "source crop" is rounded to texel boundaries.
1158 * This can produce significantly different results when the texture
1159 * is scaled by a large amount.
1160 *
1161 * The GL code below is more logical (imho), and the difference with
1162 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001163 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001164 * GL composition when a buffer scaling is applied (maybe with some
1165 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1166 * like more of a hack.
1167 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001168 Rect win(computeBounds());
1169
Robert Carr1f0a16a2016-10-24 16:27:39 -07001170 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -07001171 if (!s.finalCrop.isEmpty()) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001172 win = t.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001173 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001174 win.clear();
1175 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001176 win = t.inverse().transform(win);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001177 if (!win.intersect(computeBounds(), &win)) {
1178 win.clear();
1179 }
1180 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001181
Mathias Agopian3f844832013-08-07 21:24:32 -07001182 float left = float(win.left) / float(s.active.w);
1183 float top = float(win.top) / float(s.active.h);
1184 float right = float(win.right) / float(s.active.w);
1185 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001186
Mathias Agopian875d8e12013-06-07 15:35:48 -07001187 // TODO: we probably want to generate the texture coords with the mesh
1188 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001189 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1190 texCoords[0] = vec2(left, 1.0f - top);
1191 texCoords[1] = vec2(left, 1.0f - bottom);
1192 texCoords[2] = vec2(right, 1.0f - bottom);
1193 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001194
Mathias Agopian875d8e12013-06-07 15:35:48 -07001195 RenderEngine& engine(mFlinger->getRenderEngine());
Robert Carr6452f122017-03-21 10:41:29 -07001196 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), getAlpha());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001197#ifdef USE_HWC2
1198 engine.setSourceDataSpace(mCurrentState.dataSpace);
1199#endif
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001200 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001201 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001202}
1203
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001204#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001205void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1206 bool callIntoHwc) {
1207 if (mHwcLayers.count(hwcId) == 0) {
1208 ALOGE("setCompositionType called without a valid HWC layer");
1209 return;
1210 }
1211 auto& hwcInfo = mHwcLayers[hwcId];
1212 auto& hwcLayer = hwcInfo.layer;
1213 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1214 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1215 if (hwcInfo.compositionType != type) {
1216 ALOGV(" actually setting");
1217 hwcInfo.compositionType = type;
1218 if (callIntoHwc) {
1219 auto error = hwcLayer->setCompositionType(type);
1220 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1221 "composition type %s: %s (%d)", mName.string(),
1222 to_string(type).c_str(), to_string(error).c_str(),
1223 static_cast<int32_t>(error));
1224 }
1225 }
1226}
1227
1228HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001229 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1230 // If we're querying the composition type for a display that does not
1231 // have a HWC counterpart, then it will always be Client
1232 return HWC2::Composition::Client;
1233 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001234 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001235 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001236 return HWC2::Composition::Invalid;
1237 }
1238 return mHwcLayers.at(hwcId).compositionType;
1239}
1240
1241void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1242 if (mHwcLayers.count(hwcId) == 0) {
1243 ALOGE("setClearClientTarget called without a valid HWC layer");
1244 return;
1245 }
1246 mHwcLayers[hwcId].clearClientTarget = clear;
1247}
1248
1249bool Layer::getClearClientTarget(int32_t hwcId) const {
1250 if (mHwcLayers.count(hwcId) == 0) {
1251 ALOGE("getClearClientTarget called without a valid HWC layer");
1252 return false;
1253 }
1254 return mHwcLayers.at(hwcId).clearClientTarget;
1255}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001256#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001257
Ruben Brunk1681d952014-06-27 15:51:55 -07001258uint32_t Layer::getProducerStickyTransform() const {
1259 int producerStickyTransform = 0;
1260 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1261 if (ret != OK) {
1262 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1263 strerror(-ret), ret);
1264 return 0;
1265 }
1266 return static_cast<uint32_t>(producerStickyTransform);
1267}
1268
Dan Stozac5da2712016-07-20 15:38:12 -07001269bool Layer::latchUnsignaledBuffers() {
1270 static bool propertyLoaded = false;
1271 static bool latch = false;
1272 static std::mutex mutex;
1273 std::lock_guard<std::mutex> lock(mutex);
1274 if (!propertyLoaded) {
1275 char value[PROPERTY_VALUE_MAX] = {};
1276 property_get("debug.sf.latch_unsignaled", value, "0");
1277 latch = atoi(value);
1278 propertyLoaded = true;
1279 }
1280 return latch;
1281}
1282
Dan Stozacac35382016-01-27 12:21:06 -08001283uint64_t Layer::getHeadFrameNumber() const {
1284 Mutex::Autolock lock(mQueueItemLock);
1285 if (!mQueueItems.empty()) {
1286 return mQueueItems[0].mFrameNumber;
1287 } else {
1288 return mCurrentFrameNumber;
1289 }
1290}
1291
Dan Stoza1ce65812016-06-15 16:26:27 -07001292bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001293#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001294 if (latchUnsignaledBuffers()) {
1295 return true;
1296 }
1297
Dan Stoza1ce65812016-06-15 16:26:27 -07001298 Mutex::Autolock lock(mQueueItemLock);
1299 if (mQueueItems.empty()) {
1300 return true;
1301 }
1302 if (mQueueItems[0].mIsDroppable) {
1303 // Even though this buffer's fence may not have signaled yet, it could
1304 // be replaced by another buffer before it has a chance to, which means
1305 // that it's possible to get into a situation where a buffer is never
1306 // able to be latched. To avoid this, grab this buffer anyway.
1307 return true;
1308 }
1309 return mQueueItems[0].mFence->getSignalTime() != INT64_MAX;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001310#else
1311 return true;
1312#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001313}
1314
Dan Stozacac35382016-01-27 12:21:06 -08001315bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1316 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1317 // Don't bother with a SyncPoint, since we've already latched the
1318 // relevant frame
1319 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001320 }
1321
Dan Stozacac35382016-01-27 12:21:06 -08001322 Mutex::Autolock lock(mLocalSyncPointMutex);
1323 mLocalSyncPoints.push_back(point);
1324 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001325}
1326
Mathias Agopian13127d82013-03-05 17:47:11 -08001327void Layer::setFiltering(bool filtering) {
1328 mFiltering = filtering;
1329}
1330
1331bool Layer::getFiltering() const {
1332 return mFiltering;
1333}
1334
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001335// As documented in libhardware header, formats in the range
1336// 0x100 - 0x1FF are specific to the HAL implementation, and
1337// are known to have no alpha channel
1338// TODO: move definition for device-specific range into
1339// hardware.h, instead of using hard-coded values here.
1340#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1341
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001342bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001343 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1344 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001345 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001346 switch (format) {
1347 case HAL_PIXEL_FORMAT_RGBA_8888:
1348 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001349 case HAL_PIXEL_FORMAT_RGBA_FP16:
Romain Guy541f2262017-02-10 18:50:17 -08001350 case HAL_PIXEL_FORMAT_RGBA_1010102:
Mathias Agopiandd533712013-07-26 15:31:39 -07001351 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001352 }
1353 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001354 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001355}
1356
Mathias Agopian13127d82013-03-05 17:47:11 -08001357// ----------------------------------------------------------------------------
1358// local state
1359// ----------------------------------------------------------------------------
1360
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001361static void boundPoint(vec2* point, const Rect& crop) {
1362 if (point->x < crop.left) {
1363 point->x = crop.left;
1364 }
1365 if (point->x > crop.right) {
1366 point->x = crop.right;
1367 }
1368 if (point->y < crop.top) {
1369 point->y = crop.top;
1370 }
1371 if (point->y > crop.bottom) {
1372 point->y = crop.bottom;
1373 }
1374}
1375
Dan Stozac7014012014-02-14 15:03:43 -08001376void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1377 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001378{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001379 const Layer::State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001380 const Transform hwTransform(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001381 const uint32_t hw_h = hw->getHeight();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001382 Rect win = computeBounds();
Mathias Agopian3f844832013-08-07 21:24:32 -07001383
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001384 vec2 lt = vec2(win.left, win.top);
1385 vec2 lb = vec2(win.left, win.bottom);
1386 vec2 rb = vec2(win.right, win.bottom);
1387 vec2 rt = vec2(win.right, win.top);
1388
Robert Carr1f0a16a2016-10-24 16:27:39 -07001389 Transform layerTransform = getTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001390 if (!useIdentityTransform) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001391 lt = layerTransform.transform(lt);
1392 lb = layerTransform.transform(lb);
1393 rb = layerTransform.transform(rb);
1394 rt = layerTransform.transform(rt);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001395 }
1396
Robert Carrb5d3d262016-03-25 15:08:13 -07001397 if (!s.finalCrop.isEmpty()) {
1398 boundPoint(&lt, s.finalCrop);
1399 boundPoint(&lb, s.finalCrop);
1400 boundPoint(&rb, s.finalCrop);
1401 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001402 }
1403
Mathias Agopianff2ed702013-09-01 21:36:12 -07001404 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001405 position[0] = hwTransform.transform(lt);
1406 position[1] = hwTransform.transform(lb);
1407 position[2] = hwTransform.transform(rb);
1408 position[3] = hwTransform.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001409 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001410 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001411 }
1412}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001413
Andy McFadden4125a4f2014-01-29 17:17:11 -08001414bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001415{
neo.hee6fd41d2017-02-17 14:35:33 +08001416 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
Mathias Agopiana67932f2011-04-20 14:20:59 -07001417 // layer's opaque flag.
neo.hee6fd41d2017-02-17 14:35:33 +08001418 if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001419 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001420 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001421
1422 // if the layer has the opaque flag, then we're always opaque,
1423 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001424 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001425}
1426
Dan Stoza23116082015-06-18 14:58:39 -07001427bool Layer::isSecure() const
1428{
1429 const Layer::State& s(mDrawingState);
1430 return (s.flags & layer_state_t::eLayerSecure);
1431}
1432
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001433bool Layer::isProtected() const
1434{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001435 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001436 return (activeBuffer != 0) &&
1437 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1438}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001439
Mathias Agopian13127d82013-03-05 17:47:11 -08001440bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001441 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001442}
1443
1444bool Layer::isCropped() const {
1445 return !mCurrentCrop.isEmpty();
1446}
1447
1448bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1449 return mNeedsFiltering || hw->needsFiltering();
1450}
1451
1452void Layer::setVisibleRegion(const Region& visibleRegion) {
1453 // always called from main thread
1454 this->visibleRegion = visibleRegion;
1455}
1456
1457void Layer::setCoveredRegion(const Region& coveredRegion) {
1458 // always called from main thread
1459 this->coveredRegion = coveredRegion;
1460}
1461
1462void Layer::setVisibleNonTransparentRegion(const Region&
1463 setVisibleNonTransparentRegion) {
1464 // always called from main thread
1465 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1466}
1467
1468// ----------------------------------------------------------------------------
1469// transaction
1470// ----------------------------------------------------------------------------
1471
Dan Stoza7dde5992015-05-22 09:51:44 -07001472void Layer::pushPendingState() {
1473 if (!mCurrentState.modified) {
1474 return;
1475 }
1476
Dan Stoza7dde5992015-05-22 09:51:44 -07001477 // If this transaction is waiting on the receipt of a frame, generate a sync
1478 // point and send it to the remote layer.
Robert Carr0d480722017-01-10 16:42:54 -08001479 if (mCurrentState.barrierLayer != nullptr) {
1480 sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1481 if (barrierLayer == nullptr) {
1482 ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
Dan Stoza7dde5992015-05-22 09:51:44 -07001483 // If we can't promote the layer we are intended to wait on,
1484 // then it is expired or otherwise invalid. Allow this transaction
1485 // to be applied as per normal (no synchronization).
Robert Carr0d480722017-01-10 16:42:54 -08001486 mCurrentState.barrierLayer = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001487 } else {
1488 auto syncPoint = std::make_shared<SyncPoint>(
1489 mCurrentState.frameNumber);
Robert Carr0d480722017-01-10 16:42:54 -08001490 if (barrierLayer->addSyncPoint(syncPoint)) {
Dan Stozacac35382016-01-27 12:21:06 -08001491 mRemoteSyncPoints.push_back(std::move(syncPoint));
1492 } else {
1493 // We already missed the frame we're supposed to synchronize
1494 // on, so go ahead and apply the state update
Robert Carr0d480722017-01-10 16:42:54 -08001495 mCurrentState.barrierLayer = nullptr;
Dan Stozacac35382016-01-27 12:21:06 -08001496 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001497 }
1498
Dan Stoza7dde5992015-05-22 09:51:44 -07001499 // Wake us up to check if the frame has been received
1500 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001501 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001502 }
1503 mPendingStates.push_back(mCurrentState);
Dan Stozaf7ba41a2017-05-10 15:11:11 -07001504 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
Dan Stoza7dde5992015-05-22 09:51:44 -07001505}
1506
Pablo Ceballos05289c22016-04-14 15:49:55 -07001507void Layer::popPendingState(State* stateToCommit) {
1508 auto oldFlags = stateToCommit->flags;
1509 *stateToCommit = mPendingStates[0];
1510 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1511 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001512
1513 mPendingStates.removeAt(0);
Dan Stozaf7ba41a2017-05-10 15:11:11 -07001514 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
Dan Stoza7dde5992015-05-22 09:51:44 -07001515}
1516
Pablo Ceballos05289c22016-04-14 15:49:55 -07001517bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001518 bool stateUpdateAvailable = false;
1519 while (!mPendingStates.empty()) {
Robert Carr0d480722017-01-10 16:42:54 -08001520 if (mPendingStates[0].barrierLayer != nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001521 if (mRemoteSyncPoints.empty()) {
1522 // If we don't have a sync point for this, apply it anyway. It
1523 // will be visually wrong, but it should keep us from getting
1524 // into too much trouble.
1525 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001526 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001527 stateUpdateAvailable = true;
1528 continue;
1529 }
1530
Dan Stozacac35382016-01-27 12:21:06 -08001531 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1532 mPendingStates[0].frameNumber) {
1533 ALOGE("[%s] Unexpected sync point frame number found",
1534 mName.string());
1535
1536 // Signal our end of the sync point and then dispose of it
1537 mRemoteSyncPoints.front()->setTransactionApplied();
1538 mRemoteSyncPoints.pop_front();
1539 continue;
1540 }
1541
Dan Stoza7dde5992015-05-22 09:51:44 -07001542 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1543 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001544 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001545 stateUpdateAvailable = true;
1546
1547 // Signal our end of the sync point and then dispose of it
1548 mRemoteSyncPoints.front()->setTransactionApplied();
1549 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001550 } else {
1551 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001552 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001553 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001554 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001555 stateUpdateAvailable = true;
1556 }
1557 }
1558
1559 // If we still have pending updates, wake SurfaceFlinger back up and point
1560 // it at this layer so we can process them
1561 if (!mPendingStates.empty()) {
1562 setTransactionFlags(eTransactionNeeded);
1563 mFlinger->setTransactionFlags(eTraversalNeeded);
1564 }
1565
1566 mCurrentState.modified = false;
1567 return stateUpdateAvailable;
1568}
1569
1570void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001571 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001572 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001573 Mutex::Autolock lock(mLocalSyncPointMutex);
1574 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001575 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001576 point->setFrameAvailable();
1577 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001578 }
1579}
1580
Mathias Agopian13127d82013-03-05 17:47:11 -08001581uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001582 ATRACE_CALL();
1583
Dan Stoza7dde5992015-05-22 09:51:44 -07001584 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001585 Layer::State c = getCurrentState();
1586 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001587 return 0;
1588 }
1589
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001590 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001591
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001592 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1593 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001594
1595 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001596 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001597 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001598 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001599 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001600 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001601 " drawing={ 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",
Robert Carrc3574f72016-03-24 12:19:32 -07001603 this, getName().string(), mCurrentTransform,
1604 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001605 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001606 c.crop.left,
1607 c.crop.top,
1608 c.crop.right,
1609 c.crop.bottom,
1610 c.crop.getWidth(),
1611 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001612 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001613 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001614 s.crop.left,
1615 s.crop.top,
1616 s.crop.right,
1617 s.crop.bottom,
1618 s.crop.getWidth(),
1619 s.crop.getHeight(),
1620 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001621
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001622 // record the new size, form this point on, when the client request
1623 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001624 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001625 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001626 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001627
Robert Carr82364e32016-05-15 11:27:47 -07001628 const bool resizePending = (c.requested.w != c.active.w) ||
1629 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001630 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001631 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001632 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001633 // if we have a pending resize, unless we are in fixed-size mode.
1634 // the drawing state will be updated only once we receive a buffer
1635 // with the correct size.
1636 //
1637 // in particular, we want to make sure the clip (which is part
1638 // of the geometry state) is latched together with the size but is
1639 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001640 //
1641 // If a sideband stream is attached, however, we want to skip this
1642 // optimization so that transactions aren't missed when a buffer
1643 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001644
1645 flags |= eDontUpdateGeometryState;
1646 }
1647 }
1648
Robert Carr7bf247e2017-05-18 14:02:49 -07001649 // Here we apply various requested geometry states, depending on our
1650 // latching configuration. See Layer.h for a detailed discussion of
1651 // how geometry latching is controlled.
1652 if (!(flags & eDontUpdateGeometryState)) {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001653 Layer::State& editCurrentState(getCurrentState());
Robert Carr7bf247e2017-05-18 14:02:49 -07001654
1655 // If mFreezeGeometryUpdates is true we are in the setGeometryAppliesWithResize
1656 // mode, which causes attributes which normally latch regardless of scaling mode,
1657 // to be delayed. We copy the requested state to the active state making sure
1658 // to respect these rules (again see Layer.h for a detailed discussion).
1659 //
1660 // There is an awkward asymmetry in the handling of the crop states in the position
1661 // states, as can be seen below. Largely this arises from position and transform
1662 // being stored in the same data structure while having different latching rules.
1663 // b/38182305
1664 //
1665 // Careful that "c" and editCurrentState may not begin as equivalent due to
1666 // applyPendingStates in the presence of deferred transactions.
1667 if (mFreezeGeometryUpdates) {
Robert Carr82364e32016-05-15 11:27:47 -07001668 float tx = c.active.transform.tx();
1669 float ty = c.active.transform.ty();
1670 c.active = c.requested;
1671 c.active.transform.set(tx, ty);
1672 editCurrentState.active = c.active;
1673 } else {
1674 editCurrentState.active = editCurrentState.requested;
1675 c.active = c.requested;
1676 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001677 }
1678
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001679 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001680 // invalidate and recompute the visible regions if needed
1681 flags |= Layer::eVisibleRegion;
1682 }
1683
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001684 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001685 // invalidate and recompute the visible regions if needed
1686 flags |= eVisibleRegion;
1687 this->contentDirty = true;
1688
1689 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001690 const uint8_t type = c.active.transform.getType();
1691 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001692 (type >= Transform::SCALE));
1693 }
1694
Dan Stozac8145172016-04-28 16:29:06 -07001695 // If the layer is hidden, signal and clear out all local sync points so
1696 // that transactions for layers depending on this layer's frames becoming
1697 // visible are not blocked
1698 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001699 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001700 }
1701
Mathias Agopian13127d82013-03-05 17:47:11 -08001702 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001703 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001704 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001705}
1706
Pablo Ceballos05289c22016-04-14 15:49:55 -07001707void Layer::commitTransaction(const State& stateToCommit) {
1708 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001709}
1710
Mathias Agopian13127d82013-03-05 17:47:11 -08001711uint32_t Layer::getTransactionFlags(uint32_t flags) {
1712 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1713}
1714
1715uint32_t Layer::setTransactionFlags(uint32_t flags) {
1716 return android_atomic_or(flags, &mTransactionFlags);
1717}
1718
Robert Carr82364e32016-05-15 11:27:47 -07001719bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001720 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001721 return false;
1722 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001723
1724 // We update the requested and active position simultaneously because
1725 // we want to apply the position portion of the transform matrix immediately,
1726 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001727 mCurrentState.requested.transform.set(x, y);
Robert Carr7bf247e2017-05-18 14:02:49 -07001728 if (immediate && !mFreezeGeometryUpdates) {
1729 // Here we directly update the active state
1730 // unlike other setters, because we store it within
1731 // the transform, but use different latching rules.
1732 // b/38182305
Robert Carr82364e32016-05-15 11:27:47 -07001733 mCurrentState.active.transform.set(x, y);
1734 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001735 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001736
Dan Stoza7dde5992015-05-22 09:51:44 -07001737 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001738 setTransactionFlags(eTransactionNeeded);
1739 return true;
1740}
Robert Carr82364e32016-05-15 11:27:47 -07001741
Robert Carr1f0a16a2016-10-24 16:27:39 -07001742bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1743 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1744 if (idx < 0) {
1745 return false;
1746 }
1747 if (childLayer->setLayer(z)) {
1748 mCurrentChildren.removeAt(idx);
1749 mCurrentChildren.add(childLayer);
1750 }
1751 return true;
1752}
1753
Robert Carrae060832016-11-28 10:51:00 -08001754bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001755 if (mCurrentState.z == z)
1756 return false;
1757 mCurrentState.sequence++;
1758 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001759 mCurrentState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001760
1761 // Discard all relative layering.
1762 if (mCurrentState.zOrderRelativeOf != nullptr) {
1763 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1764 if (strongRelative != nullptr) {
1765 strongRelative->removeZOrderRelative(this);
1766 }
1767 mCurrentState.zOrderRelativeOf = nullptr;
1768 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001769 setTransactionFlags(eTransactionNeeded);
1770 return true;
1771}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001772
Robert Carrdb66e622017-04-10 16:55:57 -07001773void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1774 mCurrentState.zOrderRelatives.remove(relative);
1775 mCurrentState.sequence++;
1776 mCurrentState.modified = true;
1777 setTransactionFlags(eTransactionNeeded);
1778}
1779
1780void Layer::addZOrderRelative(const wp<Layer>& relative) {
1781 mCurrentState.zOrderRelatives.add(relative);
1782 mCurrentState.modified = true;
1783 mCurrentState.sequence++;
1784 setTransactionFlags(eTransactionNeeded);
1785}
1786
1787bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1788 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1789 if (handle == nullptr) {
1790 return false;
1791 }
1792 sp<Layer> relative = handle->owner.promote();
1793 if (relative == nullptr) {
1794 return false;
1795 }
1796
1797 mCurrentState.sequence++;
1798 mCurrentState.modified = true;
1799 mCurrentState.z = z;
1800
1801 mCurrentState.zOrderRelativeOf = relative;
1802 relative->addZOrderRelative(this);
1803
1804 setTransactionFlags(eTransactionNeeded);
1805
1806 return true;
1807}
1808
Mathias Agopian13127d82013-03-05 17:47:11 -08001809bool Layer::setSize(uint32_t w, uint32_t h) {
1810 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1811 return false;
1812 mCurrentState.requested.w = w;
1813 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001814 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001815 setTransactionFlags(eTransactionNeeded);
1816 return true;
1817}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001818#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001819bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001820#else
1821bool Layer::setAlpha(uint8_t alpha) {
1822#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001823 if (mCurrentState.alpha == alpha)
1824 return false;
1825 mCurrentState.sequence++;
1826 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001827 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001828 setTransactionFlags(eTransactionNeeded);
1829 return true;
1830}
1831bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1832 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001833 mCurrentState.requested.transform.set(
Robert Carrcb6e1e32017-02-21 19:48:26 -08001834 matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001835 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001836 setTransactionFlags(eTransactionNeeded);
1837 return true;
1838}
1839bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001840 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001841 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001842 setTransactionFlags(eTransactionNeeded);
1843 return true;
1844}
1845bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1846 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1847 if (mCurrentState.flags == newFlags)
1848 return false;
1849 mCurrentState.sequence++;
1850 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001851 mCurrentState.mask = mask;
1852 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001853 setTransactionFlags(eTransactionNeeded);
1854 return true;
1855}
Robert Carr99e27f02016-06-16 15:18:02 -07001856
1857bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001858 if (mCurrentState.requestedCrop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001859 return false;
1860 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001861 mCurrentState.requestedCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001862 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr99e27f02016-06-16 15:18:02 -07001863 mCurrentState.crop = crop;
1864 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001865 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1866
Dan Stoza7dde5992015-05-22 09:51:44 -07001867 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001868 setTransactionFlags(eTransactionNeeded);
1869 return true;
1870}
Robert Carr8d5227b2017-03-16 15:41:03 -07001871
1872bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001873 if (mCurrentState.requestedFinalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001874 return false;
1875 mCurrentState.sequence++;
Robert Carr8d5227b2017-03-16 15:41:03 -07001876 mCurrentState.requestedFinalCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001877 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr8d5227b2017-03-16 15:41:03 -07001878 mCurrentState.finalCrop = crop;
1879 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001880 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1881
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001882 mCurrentState.modified = true;
1883 setTransactionFlags(eTransactionNeeded);
1884 return true;
1885}
Mathias Agopian13127d82013-03-05 17:47:11 -08001886
Robert Carrc3574f72016-03-24 12:19:32 -07001887bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1888 if (scalingMode == mOverrideScalingMode)
1889 return false;
1890 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001891 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001892 return true;
1893}
1894
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001895void Layer::setInfo(uint32_t type, uint32_t appId) {
1896 mCurrentState.appId = appId;
1897 mCurrentState.type = type;
1898 mCurrentState.modified = true;
1899 setTransactionFlags(eTransactionNeeded);
1900}
1901
Robert Carrc3574f72016-03-24 12:19:32 -07001902uint32_t Layer::getEffectiveScalingMode() const {
1903 if (mOverrideScalingMode >= 0) {
1904 return mOverrideScalingMode;
1905 }
1906 return mCurrentScalingMode;
1907}
1908
Mathias Agopian13127d82013-03-05 17:47:11 -08001909bool Layer::setLayerStack(uint32_t layerStack) {
1910 if (mCurrentState.layerStack == layerStack)
1911 return false;
1912 mCurrentState.sequence++;
1913 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001914 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001915 setTransactionFlags(eTransactionNeeded);
1916 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001917}
1918
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07001919bool Layer::setDataSpace(android_dataspace dataSpace) {
1920 if (mCurrentState.dataSpace == dataSpace)
1921 return false;
1922 mCurrentState.sequence++;
1923 mCurrentState.dataSpace = dataSpace;
1924 mCurrentState.modified = true;
1925 setTransactionFlags(eTransactionNeeded);
1926 return true;
1927}
1928
Courtney Goeltzenleuchter532b2632017-05-05 16:34:38 -06001929android_dataspace Layer::getDataSpace() const {
1930 return mCurrentState.dataSpace;
1931}
1932
Robert Carr1f0a16a2016-10-24 16:27:39 -07001933uint32_t Layer::getLayerStack() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07001934 auto p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001935 if (p == nullptr) {
1936 return getDrawingState().layerStack;
1937 }
1938 return p->getLayerStack();
1939}
1940
Robert Carr0d480722017-01-10 16:42:54 -08001941void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
Dan Stoza7dde5992015-05-22 09:51:44 -07001942 uint64_t frameNumber) {
Robert Carr0d480722017-01-10 16:42:54 -08001943 mCurrentState.barrierLayer = barrierLayer;
Dan Stoza7dde5992015-05-22 09:51:44 -07001944 mCurrentState.frameNumber = frameNumber;
1945 // We don't set eTransactionNeeded, because just receiving a deferral
1946 // request without any other state updates shouldn't actually induce a delay
1947 mCurrentState.modified = true;
1948 pushPendingState();
Robert Carr0d480722017-01-10 16:42:54 -08001949 mCurrentState.barrierLayer = nullptr;
Dan Stoza792e5292016-02-11 11:43:58 -08001950 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07001951 mCurrentState.modified = false;
Robert Carr0d480722017-01-10 16:42:54 -08001952}
1953
1954void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
1955 uint64_t frameNumber) {
1956 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
1957 deferTransactionUntil(handle->owner.promote(), frameNumber);
Dan Stoza7dde5992015-05-22 09:51:44 -07001958}
1959
Dan Stozaee44edd2015-03-23 15:50:23 -07001960void Layer::useSurfaceDamage() {
1961 if (mFlinger->mForceFullDamage) {
1962 surfaceDamageRegion = Region::INVALID_REGION;
1963 } else {
1964 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1965 }
1966}
1967
1968void Layer::useEmptyDamage() {
1969 surfaceDamageRegion.clear();
1970}
1971
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001972// ----------------------------------------------------------------------------
1973// pageflip handling...
1974// ----------------------------------------------------------------------------
1975
Dan Stoza6b9454d2014-11-07 16:00:59 -08001976bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001977 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07001978 return true;
1979 }
1980
Dan Stoza6b9454d2014-11-07 16:00:59 -08001981 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001982 if (mQueueItems.empty()) {
1983 return false;
1984 }
1985 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001986 nsecs_t expectedPresent =
1987 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001988
1989 // Ignore timestamps more than a second in the future
1990 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1991 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1992 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1993 expectedPresent);
1994
1995 bool isDue = timestamp < expectedPresent;
1996 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001997}
1998
Brian Andersond6927fb2016-07-23 23:37:30 -07001999bool Layer::onPreComposition(nsecs_t refreshStartTime) {
2000 if (mBufferLatched) {
2001 Mutex::Autolock lock(mFrameEventHistoryMutex);
2002 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
2003 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08002004 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08002005 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002006}
2007
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002008bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
Brian Anderson3d4039d2016-09-23 16:31:30 -07002009 const std::shared_ptr<FenceTime>& presentFence,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002010 const CompositorTiming& compositorTiming) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002011 mAcquireTimeline.updateSignalTimes();
2012 mReleaseTimeline.updateSignalTimes();
2013
Brian Andersond6927fb2016-07-23 23:37:30 -07002014 // mFrameLatencyNeeded is true when a new frame was latched for the
2015 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08002016 if (!mFrameLatencyNeeded)
2017 return false;
2018
Fabien Sanglard28e98082016-12-05 10:19:46 -08002019 // Update mFrameEventHistory.
2020 {
2021 Mutex::Autolock lock(mFrameEventHistoryMutex);
2022 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002023 glDoneFence, presentFence, compositorTiming);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002024 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08002025
2026 // Update mFrameTracker.
2027 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
2028 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
2029
Brian Anderson3d4039d2016-09-23 16:31:30 -07002030 std::shared_ptr<FenceTime> frameReadyFence =
2031 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08002032 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002033 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002034 } else {
2035 // There was no fence for this frame, so assume that it was ready
2036 // to be presented at the desired present time.
2037 mFrameTracker.setFrameReadyTime(desiredPresentTime);
2038 }
2039
Brian Anderson3d4039d2016-09-23 16:31:30 -07002040 if (presentFence->isValid()) {
2041 mFrameTracker.setActualPresentFence(
2042 std::shared_ptr<FenceTime>(presentFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002043 } else {
2044 // The HWC doesn't support present fences, so use the refresh
2045 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002046 mFrameTracker.setActualPresentTime(
2047 mFlinger->getHwComposer().getRefreshTimestamp(
2048 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002049 }
2050
2051 mFrameTracker.advanceFrame();
2052 mFrameLatencyNeeded = false;
2053 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002054}
2055
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002056#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07002057void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Brian Anderson5ea5e592016-12-01 16:54:33 -08002058 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2059 return;
2060 }
2061
Brian Anderson3d4039d2016-09-23 16:31:30 -07002062 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002063 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002064 mReleaseTimeline.push(releaseFenceTime);
2065
2066 Mutex::Autolock lock(mFrameEventHistoryMutex);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002067 if (mPreviousFrameNumber != 0) {
2068 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2069 dequeueReadyTime, std::move(releaseFenceTime));
2070 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002071}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002072#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002073
Robert Carr1f0a16a2016-10-24 16:27:39 -07002074bool Layer::isHiddenByPolicy() const {
2075 const Layer::State& s(mDrawingState);
Chia-I Wue41dbe62017-06-13 14:10:56 -07002076 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002077 if (parent != nullptr && parent->isHiddenByPolicy()) {
2078 return true;
2079 }
2080 return s.flags & layer_state_t::eLayerHidden;
2081}
2082
Mathias Agopianda27af92012-09-13 18:17:13 -07002083bool Layer::isVisible() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002084#ifdef USE_HWC2
Robert Carr6452f122017-03-21 10:41:29 -07002085 return !(isHiddenByPolicy()) && getAlpha() > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08002086 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002087#else
Robert Carr6452f122017-03-21 10:41:29 -07002088 return !(isHiddenByPolicy()) && getAlpha()
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002089 && (mActiveBuffer != NULL || mSidebandStream != NULL);
2090#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07002091}
2092
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002093bool Layer::allTransactionsSignaled() {
2094 auto headFrameNumber = getHeadFrameNumber();
2095 bool matchingFramesFound = false;
2096 bool allTransactionsApplied = true;
2097 Mutex::Autolock lock(mLocalSyncPointMutex);
2098
2099 for (auto& point : mLocalSyncPoints) {
2100 if (point->getFrameNumber() > headFrameNumber) {
2101 break;
2102 }
2103 matchingFramesFound = true;
2104
2105 if (!point->frameIsAvailable()) {
2106 // We haven't notified the remote layer that the frame for
2107 // this point is available yet. Notify it now, and then
2108 // abort this attempt to latch.
2109 point->setFrameAvailable();
2110 allTransactionsApplied = false;
2111 break;
2112 }
2113
2114 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2115 }
2116 return !matchingFramesFound || allTransactionsApplied;
2117}
2118
Brian Andersond6927fb2016-07-23 23:37:30 -07002119Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002120{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08002121 ATRACE_CALL();
2122
Jesse Hall399184a2014-03-03 15:42:54 -08002123 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2124 // mSidebandStreamChanged was true
2125 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07002126 if (mSidebandStream != NULL) {
2127 setTransactionFlags(eTransactionNeeded);
2128 mFlinger->setTransactionFlags(eTraversalNeeded);
2129 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07002130 recomputeVisibleRegions = true;
2131
2132 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07002133 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08002134 }
2135
Mathias Agopian4fec8732012-06-29 14:12:52 -07002136 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07002137 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2138 return outDirtyRegion;
2139 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002140
Fabien Sanglard223eb912016-10-13 10:15:06 -07002141 // if we've already called updateTexImage() without going through
2142 // a composition step, we have to skip this layer at this point
2143 // because we cannot call updateTeximage() without a corresponding
2144 // compositionComplete() call.
2145 // we'll trigger an update in onPreComposition().
2146 if (mRefreshPending) {
2147 return outDirtyRegion;
2148 }
2149
2150 // If the head buffer's acquire fence hasn't signaled yet, return and
2151 // try again later
2152 if (!headFenceHasSignaled()) {
2153 mFlinger->signalLayerUpdate();
2154 return outDirtyRegion;
2155 }
2156
2157 // Capture the old state of the layer for comparisons later
2158 const State& s(getDrawingState());
2159 const bool oldOpacity = isOpaque(s);
2160 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2161
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002162 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002163 mFlinger->signalLayerUpdate();
2164 return outDirtyRegion;
2165 }
2166
2167 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2168 // of the buffer queue isn't modified when the buffer queue is returning
2169 // BufferItem's that weren't actually queued. This can happen in shared
2170 // buffer mode.
2171 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002172 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2173 getProducerStickyTransform() != 0, mName.string(),
Robert Carr7bf247e2017-05-18 14:02:49 -07002174 mOverrideScalingMode, mFreezeGeometryUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002175 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2176 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2177 mLastFrameNumberReceived);
2178 if (updateResult == BufferQueue::PRESENT_LATER) {
2179 // Producer doesn't want buffer to be displayed yet. Signal a
2180 // layer update so we check again at the next opportunity.
2181 mFlinger->signalLayerUpdate();
2182 return outDirtyRegion;
2183 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2184 // If the buffer has been rejected, remove it from the shadow queue
2185 // and return early
2186 if (queuedBuffer) {
2187 Mutex::Autolock lock(mQueueItemLock);
2188 mQueueItems.removeAt(0);
2189 android_atomic_dec(&mQueuedFrames);
2190 }
2191 return outDirtyRegion;
2192 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2193 // This can occur if something goes wrong when trying to create the
2194 // EGLImage for this buffer. If this happens, the buffer has already
2195 // been released, so we need to clean up the queue and bug out
2196 // early.
2197 if (queuedBuffer) {
2198 Mutex::Autolock lock(mQueueItemLock);
2199 mQueueItems.clear();
2200 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002201 }
2202
Fabien Sanglard223eb912016-10-13 10:15:06 -07002203 // Once we have hit this state, the shadow queue may no longer
2204 // correctly reflect the incoming BufferQueue's contents, so even if
2205 // updateTexImage starts working, the only safe course of action is
2206 // to continue to ignore updates.
2207 mUpdateTexImageFailed = true;
2208
2209 return outDirtyRegion;
2210 }
2211
2212 if (queuedBuffer) {
2213 // Autolock scope
2214 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2215
2216 Mutex::Autolock lock(mQueueItemLock);
2217
2218 // Remove any stale buffers that have been dropped during
2219 // updateTexImage
2220 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2221 mQueueItems.removeAt(0);
2222 android_atomic_dec(&mQueuedFrames);
2223 }
2224
2225 mQueueItems.removeAt(0);
2226 }
2227
2228
2229 // Decrement the queued-frames count. Signal another event if we
2230 // have more frames pending.
2231 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2232 || mAutoRefresh) {
2233 mFlinger->signalLayerUpdate();
2234 }
2235
Fabien Sanglard223eb912016-10-13 10:15:06 -07002236 // update the active buffer
Chia-I Wu06d63de2017-01-04 14:58:51 +08002237 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2238 &mActiveBufferSlot);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002239 if (mActiveBuffer == NULL) {
2240 // this can only happen if the very first buffer was rejected.
2241 return outDirtyRegion;
2242 }
2243
Brian Andersond6927fb2016-07-23 23:37:30 -07002244 mBufferLatched = true;
2245 mPreviousFrameNumber = mCurrentFrameNumber;
2246 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2247
2248 {
2249 Mutex::Autolock lock(mFrameEventHistoryMutex);
2250 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2251#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002252 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002253 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002254 mReleaseTimeline.push(releaseFenceTime);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002255 if (mPreviousFrameNumber != 0) {
2256 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2257 latchTime, std::move(releaseFenceTime));
2258 }
Brian Andersond6927fb2016-07-23 23:37:30 -07002259#endif
2260 }
2261
Fabien Sanglard223eb912016-10-13 10:15:06 -07002262 mRefreshPending = true;
2263 mFrameLatencyNeeded = true;
2264 if (oldActiveBuffer == NULL) {
2265 // the first time we receive a buffer, we need to trigger a
2266 // geometry invalidation.
2267 recomputeVisibleRegions = true;
2268 }
2269
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002270 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2271
Fabien Sanglard223eb912016-10-13 10:15:06 -07002272 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2273 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2274 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2275 if ((crop != mCurrentCrop) ||
2276 (transform != mCurrentTransform) ||
2277 (scalingMode != mCurrentScalingMode))
2278 {
2279 mCurrentCrop = crop;
2280 mCurrentTransform = transform;
2281 mCurrentScalingMode = scalingMode;
2282 recomputeVisibleRegions = true;
2283 }
2284
2285 if (oldActiveBuffer != NULL) {
2286 uint32_t bufWidth = mActiveBuffer->getWidth();
2287 uint32_t bufHeight = mActiveBuffer->getHeight();
2288 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2289 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002290 recomputeVisibleRegions = true;
2291 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002292 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002293
Fabien Sanglard223eb912016-10-13 10:15:06 -07002294 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2295 if (oldOpacity != isOpaque(s)) {
2296 recomputeVisibleRegions = true;
2297 }
Dan Stozacac35382016-01-27 12:21:06 -08002298
Fabien Sanglard223eb912016-10-13 10:15:06 -07002299 // Remove any sync points corresponding to the buffer which was just
2300 // latched
2301 {
2302 Mutex::Autolock lock(mLocalSyncPointMutex);
2303 auto point = mLocalSyncPoints.begin();
2304 while (point != mLocalSyncPoints.end()) {
2305 if (!(*point)->frameIsAvailable() ||
2306 !(*point)->transactionIsApplied()) {
2307 // This sync point must have been added since we started
2308 // latching. Don't drop it yet.
2309 ++point;
2310 continue;
2311 }
2312
2313 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2314 point = mLocalSyncPoints.erase(point);
2315 } else {
2316 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002317 }
2318 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002319 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002320
2321 // FIXME: postedRegion should be dirty & bounds
2322 Region dirtyRegion(Rect(s.active.w, s.active.h));
2323
2324 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002325 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002326
Mathias Agopian4fec8732012-06-29 14:12:52 -07002327 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002328}
2329
Mathias Agopiana67932f2011-04-20 14:20:59 -07002330uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002331{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002332 // TODO: should we do something special if mSecure is set?
2333 if (mProtectedByApp) {
2334 // need a hardware-protected path to external video sink
2335 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002336 }
Riley Andrews03414a12014-07-01 14:22:59 -07002337 if (mPotentialCursor) {
2338 usage |= GraphicBuffer::USAGE_CURSOR;
2339 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002340 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002341 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002342}
2343
Mathias Agopian84300952012-11-21 16:02:13 -08002344void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002345 uint32_t orientation = 0;
2346 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002347 // The transform hint is used to improve performance, but we can
2348 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002349 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002350 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002351 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002352 if (orientation & Transform::ROT_INVALID) {
2353 orientation = 0;
2354 }
2355 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002356 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002357}
2358
Mathias Agopian13127d82013-03-05 17:47:11 -08002359// ----------------------------------------------------------------------------
2360// debugging
2361// ----------------------------------------------------------------------------
2362
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002363void Layer::dump(String8& result, Colorizer& colorizer) const
Mathias Agopian13127d82013-03-05 17:47:11 -08002364{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002365 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08002366
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002367 colorizer.colorize(result, Colorizer::GREEN);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002368 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002369 "+ %s %p (%s)\n",
2370 getTypeId(), this, getName().string());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002371 colorizer.reset(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002372
Mathias Agopian2ca79392013-04-02 18:30:32 -07002373 s.activeTransparentRegion.dump(result, "transparentRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002374 visibleRegion.dump(result, "visibleRegion");
Dan Stozaee44edd2015-03-23 15:50:23 -07002375 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002376 sp<Client> client(mClientRef.promote());
Courtney Goeltzenleuchter36c44dc2017-04-14 09:33:16 -06002377 PixelFormat pf = PIXEL_FORMAT_UNKNOWN;
2378 const sp<GraphicBuffer>& buffer(getActiveBuffer());
2379 if (buffer != NULL) {
2380 pf = buffer->getPixelFormat();
2381 }
Mathias Agopian13127d82013-03-05 17:47:11 -08002382
Mathias Agopian74d211a2013-04-22 16:55:35 +02002383 result.appendFormat( " "
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002384 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2385 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
Mathias Agopian13127d82013-03-05 17:47:11 -08002386 "isOpaque=%1d, invalidate=%1d, "
Courtney Goeltzenleuchter36c44dc2017-04-14 09:33:16 -06002387 "dataspace=%s, pixelformat=%s "
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002388#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08002389 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002390#else
2391 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2392#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08002393 " client=%p\n",
Robert Carr1f0a16a2016-10-24 16:27:39 -07002394 getLayerStack(), s.z,
2395 s.active.transform.tx(), s.active.transform.ty(),
2396 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07002397 s.crop.left, s.crop.top,
2398 s.crop.right, s.crop.bottom,
2399 s.finalCrop.left, s.finalCrop.top,
2400 s.finalCrop.right, s.finalCrop.bottom,
Andy McFadden4125a4f2014-01-29 17:17:11 -08002401 isOpaque(s), contentDirty,
Courtney Goeltzenleuchter36c44dc2017-04-14 09:33:16 -06002402 dataspaceDetails(getDataSpace()).c_str(), decodePixelFormat(pf).c_str(),
Mathias Agopian13127d82013-03-05 17:47:11 -08002403 s.alpha, s.flags,
Robert Carr3dcabfa2016-03-01 18:36:58 -08002404 s.active.transform[0][0], s.active.transform[0][1],
2405 s.active.transform[1][0], s.active.transform[1][1],
Mathias Agopian13127d82013-03-05 17:47:11 -08002406 client.get());
Mathias Agopian13127d82013-03-05 17:47:11 -08002407
2408 sp<const GraphicBuffer> buf0(mActiveBuffer);
2409 uint32_t w0=0, h0=0, s0=0, f0=0;
2410 if (buf0 != 0) {
2411 w0 = buf0->getWidth();
2412 h0 = buf0->getHeight();
2413 s0 = buf0->getStride();
2414 f0 = buf0->format;
2415 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02002416 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002417 " "
2418 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2419 " queued-frames=%d, mRefreshPending=%d\n",
2420 mFormat, w0, h0, s0,f0,
2421 mQueuedFrames, mRefreshPending);
2422
Mathias Agopian13127d82013-03-05 17:47:11 -08002423 if (mSurfaceFlingerConsumer != 0) {
Colin Cross3d1d2802016-09-26 18:10:16 -07002424 mSurfaceFlingerConsumer->dumpState(result, " ");
Mathias Agopian13127d82013-03-05 17:47:11 -08002425 }
2426}
2427
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002428#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002429void Layer::miniDumpHeader(String8& result) {
2430 result.append("----------------------------------------");
2431 result.append("---------------------------------------\n");
2432 result.append(" Layer name\n");
2433 result.append(" Z | ");
2434 result.append(" Comp Type | ");
2435 result.append(" Disp Frame (LTRB) | ");
2436 result.append(" Source Crop (LTRB)\n");
2437 result.append("----------------------------------------");
2438 result.append("---------------------------------------\n");
2439}
2440
2441void Layer::miniDump(String8& result, int32_t hwcId) const {
2442 if (mHwcLayers.count(hwcId) == 0) {
2443 return;
2444 }
2445
2446 String8 name;
2447 if (mName.length() > 77) {
2448 std::string shortened;
2449 shortened.append(mName.string(), 36);
2450 shortened.append("[...]");
2451 shortened.append(mName.string() + (mName.length() - 36), 36);
2452 name = shortened.c_str();
2453 } else {
2454 name = mName;
2455 }
2456
2457 result.appendFormat(" %s\n", name.string());
2458
2459 const Layer::State& layerState(getDrawingState());
2460 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2461 result.appendFormat(" %10u | ", layerState.z);
2462 result.appendFormat("%10s | ",
2463 to_string(getCompositionType(hwcId)).c_str());
2464 const Rect& frame = hwcInfo.displayFrame;
2465 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2466 frame.right, frame.bottom);
Dan Stoza5a423ea2017-02-16 14:10:39 -08002467 const FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002468 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2469 crop.right, crop.bottom);
2470
2471 result.append("- - - - - - - - - - - - - - - - - - - - ");
2472 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2473}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002474#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002475
Svetoslavd85084b2014-03-20 10:28:31 -07002476void Layer::dumpFrameStats(String8& result) const {
2477 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002478}
2479
Svetoslavd85084b2014-03-20 10:28:31 -07002480void Layer::clearFrameStats() {
2481 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002482}
2483
Jamie Gennis6547ff42013-07-16 20:12:42 -07002484void Layer::logFrameStats() {
2485 mFrameTracker.logAndResetStats(mName);
2486}
2487
Svetoslavd85084b2014-03-20 10:28:31 -07002488void Layer::getFrameStats(FrameStats* outStats) const {
2489 mFrameTracker.getStats(outStats);
2490}
2491
Brian Andersond6927fb2016-07-23 23:37:30 -07002492void Layer::dumpFrameEvents(String8& result) {
2493 result.appendFormat("- Layer %s (%s, %p)\n",
2494 getName().string(), getTypeId(), this);
2495 Mutex::Autolock lock(mFrameEventHistoryMutex);
2496 mFrameEventHistory.checkFencesForCompletion();
2497 mFrameEventHistory.dump(result);
2498}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002499
Brian Anderson5ea5e592016-12-01 16:54:33 -08002500void Layer::onDisconnect() {
2501 Mutex::Autolock lock(mFrameEventHistoryMutex);
2502 mFrameEventHistory.onDisconnect();
2503}
2504
Brian Anderson3890c392016-07-25 12:48:08 -07002505void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2506 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002507 Mutex::Autolock lock(mFrameEventHistoryMutex);
2508 if (newTimestamps) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002509 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002510 mFrameEventHistory.addQueue(*newTimestamps);
2511 }
2512
Brian Anderson3890c392016-07-25 12:48:08 -07002513 if (outDelta) {
2514 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002515 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002516}
Dan Stozae77c7662016-05-13 11:37:28 -07002517
2518std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2519 bool forceFlush) {
2520 std::vector<OccupancyTracker::Segment> history;
2521 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2522 &history);
2523 if (result != NO_ERROR) {
2524 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2525 result);
2526 return {};
2527 }
2528 return history;
2529}
2530
Robert Carr367c5682016-06-20 11:55:28 -07002531bool Layer::getTransformToDisplayInverse() const {
2532 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2533}
2534
Chia-I Wu98f1c102017-05-30 14:54:08 -07002535size_t Layer::getChildrenCount() const {
2536 size_t count = 0;
2537 for (const sp<Layer>& child : mCurrentChildren) {
2538 count += 1 + child->getChildrenCount();
2539 }
2540 return count;
2541}
2542
Robert Carr1f0a16a2016-10-24 16:27:39 -07002543void Layer::addChild(const sp<Layer>& layer) {
2544 mCurrentChildren.add(layer);
2545 layer->setParent(this);
2546}
2547
2548ssize_t Layer::removeChild(const sp<Layer>& layer) {
2549 layer->setParent(nullptr);
2550 return mCurrentChildren.remove(layer);
2551}
2552
Robert Carr1db73f62016-12-21 12:58:51 -08002553bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2554 sp<Handle> handle = nullptr;
2555 sp<Layer> newParent = nullptr;
2556 if (newParentHandle == nullptr) {
2557 return false;
2558 }
2559 handle = static_cast<Handle*>(newParentHandle.get());
2560 newParent = handle->owner.promote();
2561 if (newParent == nullptr) {
2562 ALOGE("Unable to promote Layer handle");
2563 return false;
2564 }
2565
2566 for (const sp<Layer>& child : mCurrentChildren) {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002567 newParent->addChild(child);
Robert Carr1db73f62016-12-21 12:58:51 -08002568
2569 sp<Client> client(child->mClientRef.promote());
2570 if (client != nullptr) {
2571 client->setParentLayer(newParent);
2572 }
2573 }
2574 mCurrentChildren.clear();
2575
2576 return true;
2577}
2578
Robert Carr9524cb32017-02-13 11:32:32 -08002579bool Layer::detachChildren() {
Dan Stoza412903f2017-04-27 13:42:17 -07002580 traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
Robert Carr9524cb32017-02-13 11:32:32 -08002581 if (child == this) {
2582 return;
2583 }
2584
2585 sp<Client> client(child->mClientRef.promote());
2586 if (client != nullptr) {
2587 client->detachLayer(child);
2588 }
2589 });
2590
2591 return true;
2592}
2593
Robert Carr1f0a16a2016-10-24 16:27:39 -07002594void Layer::setParent(const sp<Layer>& layer) {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002595 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002596}
2597
2598void Layer::clearSyncPoints() {
2599 for (const auto& child : mCurrentChildren) {
2600 child->clearSyncPoints();
2601 }
2602
2603 Mutex::Autolock lock(mLocalSyncPointMutex);
2604 for (auto& point : mLocalSyncPoints) {
2605 point->setFrameAvailable();
2606 }
2607 mLocalSyncPoints.clear();
2608}
2609
2610int32_t Layer::getZ() const {
2611 return mDrawingState.z;
2612}
2613
Dan Stoza412903f2017-04-27 13:42:17 -07002614LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2615 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2616 "makeTraversalList received invalid stateSet");
2617 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2618 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2619 const State& state = useDrawing ? mDrawingState : mCurrentState;
2620
2621 if (state.zOrderRelatives.size() == 0) {
2622 return children;
Robert Carrdb66e622017-04-10 16:55:57 -07002623 }
2624 LayerVector traverse;
2625
Dan Stoza412903f2017-04-27 13:42:17 -07002626 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07002627 sp<Layer> strongRelative = weakRelative.promote();
2628 if (strongRelative != nullptr) {
2629 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07002630 }
2631 }
2632
Dan Stoza412903f2017-04-27 13:42:17 -07002633 for (const sp<Layer>& child : children) {
Robert Carrdb66e622017-04-10 16:55:57 -07002634 traverse.add(child);
2635 }
2636
2637 return traverse;
2638}
2639
Robert Carr1f0a16a2016-10-24 16:27:39 -07002640/**
Robert Carrdb66e622017-04-10 16:55:57 -07002641 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002642 */
Dan Stoza412903f2017-04-27 13:42:17 -07002643void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2644 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002645
Robert Carr1f0a16a2016-10-24 16:27:39 -07002646 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002647 for (; i < list.size(); i++) {
2648 const auto& relative = list[i];
2649 if (relative->getZ() >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002650 break;
Robert Carrdb66e622017-04-10 16:55:57 -07002651 }
Dan Stoza412903f2017-04-27 13:42:17 -07002652 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002653 }
Dan Stoza412903f2017-04-27 13:42:17 -07002654 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07002655 for (; i < list.size(); i++) {
2656 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002657 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002658 }
2659}
2660
2661/**
Robert Carrdb66e622017-04-10 16:55:57 -07002662 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002663 */
Dan Stoza412903f2017-04-27 13:42:17 -07002664void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2665 const LayerVector::Visitor& visitor) {
2666 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002667
Robert Carr1f0a16a2016-10-24 16:27:39 -07002668 int32_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002669 for (i = list.size()-1; i>=0; i--) {
2670 const auto& relative = list[i];
2671 if (relative->getZ() < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002672 break;
2673 }
Dan Stoza412903f2017-04-27 13:42:17 -07002674 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002675 }
Dan Stoza412903f2017-04-27 13:42:17 -07002676 visitor(this);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002677 for (; i>=0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002678 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002679 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002680 }
2681}
2682
2683Transform Layer::getTransform() const {
2684 Transform t;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002685 const auto& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002686 if (p != nullptr) {
2687 t = p->getTransform();
Robert Carr9b429f42017-04-17 14:56:57 -07002688
2689 // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2690 // it isFixedSize) then there may be additional scaling not accounted
2691 // for in the transform. We need to mirror this scaling in child surfaces
2692 // or we will break the contract where WM can treat child surfaces as
2693 // pixels in the parent surface.
Chia-I Wu0a68b462017-07-18 11:30:05 -07002694 if (p->isFixedSize() && p->mActiveBuffer != nullptr) {
Robert Carr1725eee2017-04-26 18:32:15 -07002695 int bufferWidth;
2696 int bufferHeight;
2697 if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2698 bufferWidth = p->mActiveBuffer->getWidth();
2699 bufferHeight = p->mActiveBuffer->getHeight();
2700 } else {
2701 bufferHeight = p->mActiveBuffer->getWidth();
2702 bufferWidth = p->mActiveBuffer->getHeight();
2703 }
Robert Carr9b429f42017-04-17 14:56:57 -07002704 float sx = p->getDrawingState().active.w /
Robert Carr1725eee2017-04-26 18:32:15 -07002705 static_cast<float>(bufferWidth);
Robert Carr9b429f42017-04-17 14:56:57 -07002706 float sy = p->getDrawingState().active.h /
Robert Carr1725eee2017-04-26 18:32:15 -07002707 static_cast<float>(bufferHeight);
Robert Carr9b429f42017-04-17 14:56:57 -07002708 Transform extraParentScaling;
2709 extraParentScaling.set(sx, 0, 0, sy);
2710 t = t * extraParentScaling;
2711 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002712 }
2713 return t * getDrawingState().active.transform;
2714}
2715
Robert Carr6452f122017-03-21 10:41:29 -07002716#ifdef USE_HWC2
2717float Layer::getAlpha() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002718 const auto& p = mDrawingParent.promote();
Robert Carr6452f122017-03-21 10:41:29 -07002719
2720 float parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0;
2721 return parentAlpha * getDrawingState().alpha;
2722}
2723#else
2724uint8_t Layer::getAlpha() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002725 const auto& p = mDrawingParent.promote();
Robert Carr6452f122017-03-21 10:41:29 -07002726
2727 float parentAlpha = (p != nullptr) ? (p->getAlpha() / 255.0f) : 1.0;
2728 float drawingAlpha = getDrawingState().alpha / 255.0f;
2729 drawingAlpha = drawingAlpha * parentAlpha;
2730 return static_cast<uint8_t>(std::round(drawingAlpha * 255));
2731}
2732#endif
2733
Robert Carr1f0a16a2016-10-24 16:27:39 -07002734void Layer::commitChildList() {
2735 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2736 const auto& child = mCurrentChildren[i];
2737 child->commitChildList();
2738 }
2739 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002740 mDrawingParent = mCurrentParent;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002741}
2742
Mathias Agopian13127d82013-03-05 17:47:11 -08002743// ---------------------------------------------------------------------------
2744
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002745}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002746
2747#if defined(__gl_h_)
2748#error "don't include gl/gl.h in this file"
2749#endif
2750
2751#if defined(__gl2_h_)
2752#error "don't include gl2/gl2.h in this file"
2753#endif