blob: ae731f7123ad18838c89b4b2809702b168eca4e7 [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),
107 mFreezePositionUpdates(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;
129
130 mCurrentState.active.w = w;
131 mCurrentState.active.h = h;
Robert Carr3dcabfa2016-03-01 18:36:58 -0800132 mCurrentState.active.transform.set(0, 0);
Robert Carrb5d3d262016-03-25 15:08:13 -0700133 mCurrentState.crop.makeInvalid();
134 mCurrentState.finalCrop.makeInvalid();
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700135 mCurrentState.z = 0;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000136#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800137 mCurrentState.alpha = 1.0f;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000138#else
139 mCurrentState.alpha = 0xFF;
140#endif
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700141 mCurrentState.layerStack = 0;
142 mCurrentState.flags = layerFlags;
143 mCurrentState.sequence = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700144 mCurrentState.requested = mCurrentState.active;
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700145 mCurrentState.dataSpace = HAL_DATASPACE_UNKNOWN;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500146 mCurrentState.appId = 0;
147 mCurrentState.type = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700148
149 // drawing state & current state are identical
150 mDrawingState = mCurrentState;
Jamie Gennis6547ff42013-07-16 20:12:42 -0700151
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000152#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800153 const auto& hwc = flinger->getHwComposer();
154 const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
155 nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000156#else
157 nsecs_t displayPeriod =
158 flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
159#endif
Jamie Gennis6547ff42013-07-16 20:12:42 -0700160 mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -0800161
162 CompositorTiming compositorTiming;
163 flinger->getCompositorTiming(&compositorTiming);
164 mFrameEventHistory.initializeCompositorTiming(compositorTiming);
Jamie Gennise8696a42012-01-15 18:54:57 -0800165}
166
Mathias Agopian3f844832013-08-07 21:24:32 -0700167void Layer::onFirstRef() {
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800168 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
Dan Stozab3d0bdf2014-04-07 16:33:59 -0700169 sp<IGraphicBufferProducer> producer;
170 sp<IGraphicBufferConsumer> consumer;
Mathias Agopian0556d792017-03-22 15:49:32 -0700171 BufferQueue::createBufferQueue(&producer, &consumer, true);
Robert Carr1db73f62016-12-21 12:58:51 -0800172 mProducer = new MonitoredProducer(producer, mFlinger, this);
Irvel468051e2016-06-13 16:44:44 -0700173 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800174 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Jesse Hall399184a2014-03-03 15:42:54 -0800175 mSurfaceFlingerConsumer->setContentsChangedListener(this);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700176 mSurfaceFlingerConsumer->setName(mName);
Daniel Lamb2675792012-02-23 14:35:13 -0800177
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800178 if (mFlinger->isLayerTripleBufferingDisabled()) {
179 mProducer->setMaxDequeuedBufferCount(2);
180 }
Andy McFadden69052052012-09-14 16:10:11 -0700181
Mathias Agopian84300952012-11-21 16:02:13 -0800182 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
183 updateTransformHint(hw);
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700184}
185
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700186Layer::~Layer() {
Pablo Ceballos8ea4e7b2016-03-03 15:20:02 -0800187 sp<Client> c(mClientRef.promote());
188 if (c != 0) {
189 c->detachLayer(this);
190 }
191
Dan Stozacac35382016-01-27 12:21:06 -0800192 for (auto& point : mRemoteSyncPoints) {
193 point->setTransactionApplied();
194 }
Dan Stozac8145172016-04-28 16:29:06 -0700195 for (auto& point : mLocalSyncPoints) {
196 point->setFrameAvailable();
197 }
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700198 mFlinger->deleteTextureAsync(mTextureName);
Jamie Gennis6547ff42013-07-16 20:12:42 -0700199 mFrameTracker.logAndResetStats(mName);
Mathias Agopian96f08192010-06-02 23:28:45 -0700200}
201
Mathias Agopian13127d82013-03-05 17:47:11 -0800202// ---------------------------------------------------------------------------
203// callbacks
204// ---------------------------------------------------------------------------
205
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000206#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800207void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
208 if (mHwcLayers.empty()) {
209 return;
210 }
211 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();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700300 for (const auto& child : mCurrentChildren) {
301 child->onRemoved();
302 }
Mathias Agopian48d819a2009-09-10 19:41:18 -0700303}
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700304
Mathias Agopian13127d82013-03-05 17:47:11 -0800305// ---------------------------------------------------------------------------
306// set-up
307// ---------------------------------------------------------------------------
308
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700309const String8& Layer::getName() const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800310 return mName;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800311}
312
Mathias Agopianf9d93272009-06-19 17:00:27 -0700313status_t Layer::setBuffers( uint32_t w, uint32_t h,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800314 PixelFormat format, uint32_t flags)
315{
Mathias Agopianca99fb82010-04-14 16:43:44 -0700316 uint32_t const maxSurfaceDims = min(
Mathias Agopiana4912602012-07-12 14:25:33 -0700317 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
Mathias Agopianca99fb82010-04-14 16:43:44 -0700318
319 // never allow a surface larger than what our underlying GL implementation
320 // can handle.
321 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
Mathias Agopianff615cc2012-02-24 14:58:36 -0800322 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700323 return BAD_VALUE;
324 }
325
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700326 mFormat = format;
Mathias Agopianeff062c2010-08-25 14:59:15 -0700327
Riley Andrews03414a12014-07-01 14:22:59 -0700328 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
Mathias Agopian3165cc22012-08-08 19:42:09 -0700329 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700330 mCurrentOpacity = getOpacityForFormat(format);
331
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800332 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
333 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
334 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700335
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800336 return NO_ERROR;
337}
338
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700339sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800340 Mutex::Autolock _l(mLock);
341
342 LOG_ALWAYS_FATAL_IF(mHasSurface,
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700343 "Layer::getHandle() has already been called");
Mathias Agopian13127d82013-03-05 17:47:11 -0800344
345 mHasSurface = true;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700346
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700347 return new Handle(mFlinger, this);
Mathias Agopian13127d82013-03-05 17:47:11 -0800348}
349
Dan Stozab9b08832014-03-13 11:55:57 -0700350sp<IGraphicBufferProducer> Layer::getProducer() const {
351 return mProducer;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700352}
353
Mathias Agopian13127d82013-03-05 17:47:11 -0800354// ---------------------------------------------------------------------------
355// h/w composer set-up
356// ---------------------------------------------------------------------------
357
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800358Rect Layer::getContentCrop() const {
359 // this is the crop rectangle that applies to the buffer
360 // itself (as opposed to the window)
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700361 Rect crop;
362 if (!mCurrentCrop.isEmpty()) {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800363 // if the buffer crop is defined, we use that
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700364 crop = mCurrentCrop;
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800365 } else if (mActiveBuffer != NULL) {
366 // otherwise we use the whole buffer
367 crop = mActiveBuffer->getBounds();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700368 } else {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800369 // if we don't have a buffer yet, we use an empty/invalid crop
Mathias Agopian4fec8732012-06-29 14:12:52 -0700370 crop.makeInvalid();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700371 }
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700372 return crop;
373}
374
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700375static Rect reduce(const Rect& win, const Region& exclude) {
376 if (CC_LIKELY(exclude.isEmpty())) {
377 return win;
378 }
379 if (exclude.isRect()) {
380 return win.reduce(exclude.getBounds());
381 }
382 return Region(win).subtract(exclude).getBounds();
383}
384
Robert Carr1f0a16a2016-10-24 16:27:39 -0700385Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
386 const Layer::State& s(getDrawingState());
387 Rect win(s.active.w, s.active.h);
388
389 if (!s.crop.isEmpty()) {
390 win.intersect(s.crop, &win);
391 }
392
393 Transform t = getTransform();
394 win = t.transform(win);
395
396 const sp<Layer>& p = getParent();
397 // Now we need to calculate the parent bounds, so we can clip ourselves to those.
398 // When calculating the parent bounds for purposes of clipping,
399 // we don't need to constrain the parent to its transparent region.
400 // The transparent region is an optimization based on the
401 // buffer contents of the layer, but does not affect the space allocated to
402 // it by policy, and thus children should be allowed to extend into the
403 // parent's transparent region. In fact one of the main uses, is to reduce
404 // buffer allocation size in cases where a child window sits behind a main window
405 // (by marking the hole in the parent window as a transparent region)
406 if (p != nullptr) {
407 Rect bounds = p->computeScreenBounds(false);
408 bounds.intersect(win, &win);
409 }
410
411 if (reduceTransparentRegion) {
412 auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
413 win = reduce(win, screenTransparentRegion);
414 }
415
416 return win;
417}
418
Mathias Agopian13127d82013-03-05 17:47:11 -0800419Rect Layer::computeBounds() const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700420 const Layer::State& s(getDrawingState());
Michael Lentine6c925ed2014-09-26 17:55:01 -0700421 return computeBounds(s.activeTransparentRegion);
422}
423
424Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
425 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800426 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700427
428 if (!s.crop.isEmpty()) {
429 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -0800430 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700431
432 Rect bounds = win;
433 const auto& p = getParent();
434 if (p != nullptr) {
Robert Carrde9ec442017-02-08 17:43:36 -0800435 // Look in computeScreenBounds recursive call for explanation of
436 // why we pass false here.
437 bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700438 }
439
440 Transform t = getTransform();
441 if (p != nullptr) {
442 win = t.transform(win);
443 win.intersect(bounds, &win);
444 win = t.inverse().transform(win);
445 }
446
Mathias Agopian6c7f25a2013-05-09 20:37:10 -0700447 // subtract the transparent region and snap to the bounds
Michael Lentine6c925ed2014-09-26 17:55:01 -0700448 return reduce(win, activeTransparentRegion);
Mathias Agopian13127d82013-03-05 17:47:11 -0800449}
450
Robert Carr1f0a16a2016-10-24 16:27:39 -0700451Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
Robert Carrb5d3d262016-03-25 15:08:13 -0700452 // the crop is the area of the window that gets cropped, but not
Mathias Agopian13127d82013-03-05 17:47:11 -0800453 // scaled in any ways.
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700454 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800455
456 // apply the projection's clipping to the window crop in
457 // layerstack space, and convert-back to layer space.
Mathias Agopian6b442672013-07-09 21:24:52 -0700458 // if there are no window scaling involved, this operation will map to full
459 // pixels in the buffer.
460 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
461 // a viewport clipping and a window transform. we should use floating point to fix this.
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700462
463 Rect activeCrop(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700464 if (!s.crop.isEmpty()) {
465 activeCrop = s.crop;
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700466 }
467
Robert Carr1f0a16a2016-10-24 16:27:39 -0700468 Transform t = getTransform();
469 activeCrop = t.transform(activeCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000470 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
471 activeCrop.clear();
472 }
Robert Carrb5d3d262016-03-25 15:08:13 -0700473 if (!s.finalCrop.isEmpty()) {
474 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000475 activeCrop.clear();
476 }
477 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700478 return activeCrop;
479}
480
Dan Stoza5a423ea2017-02-16 14:10:39 -0800481FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
Robert Carr1f0a16a2016-10-24 16:27:39 -0700482 // the content crop is the area of the content that gets scaled to the
483 // layer's size. This is in buffer space.
Dan Stoza5a423ea2017-02-16 14:10:39 -0800484 FloatRect crop = getContentCrop().toFloatRect();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700485
486 // In addition there is a WM-specified crop we pull from our drawing state.
487 const State& s(getDrawingState());
488
489 // Screen space to make reduction to parent crop clearer.
490 Rect activeCrop = computeInitialCrop(hw);
491 const auto& p = getParent();
492 if (p != nullptr) {
493 auto parentCrop = p->computeInitialCrop(hw);
494 activeCrop.intersect(parentCrop, &activeCrop);
495 }
496 Transform t = getTransform();
497 // Back to layer space to work with the content crop.
498 activeCrop = t.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800499
Michael Lentine28ea2172014-11-19 18:32:37 -0800500 // This needs to be here as transform.transform(Rect) computes the
501 // transformed rect and then takes the bounding box of the result before
502 // returning. This means
503 // transform.inverse().transform(transform.transform(Rect)) != Rect
504 // in which case we need to make sure the final rect is clipped to the
505 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000506 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
507 activeCrop.clear();
508 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800509
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700510 // subtract the transparent region and snap to the bounds
511 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
512
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000513 // Transform the window crop to match the buffer coordinate system,
514 // which means using the inverse of the current transform set on the
515 // SurfaceFlingerConsumer.
516 uint32_t invTransform = mCurrentTransform;
Robert Carrcae605c2017-03-29 12:10:31 -0700517 if (getTransformToDisplayInverse()) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000518 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700519 * the code below applies the primary display's inverse transform to the
520 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000521 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700522 uint32_t invTransformOrient =
523 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000524 // calculate the inverse transform
525 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
526 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
527 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800528 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000529 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700530 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
531 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800532 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000533
534 int winWidth = s.active.w;
535 int winHeight = s.active.h;
536 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
537 // If the activeCrop has been rotate the ends are rotated but not
538 // the space itself so when transforming ends back we can't rely on
539 // a modification of the axes of rotation. To account for this we
540 // need to reorient the inverse rotation in terms of the current
541 // axes of rotation.
542 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
543 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
544 if (is_h_flipped == is_v_flipped) {
545 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
546 NATIVE_WINDOW_TRANSFORM_FLIP_H;
547 }
548 winWidth = s.active.h;
549 winHeight = s.active.w;
550 }
551 const Rect winCrop = activeCrop.transform(
552 invTransform, s.active.w, s.active.h);
553
554 // below, crop is intersected with winCrop expressed in crop's coordinate space
555 float xScale = crop.getWidth() / float(winWidth);
556 float yScale = crop.getHeight() / float(winHeight);
557
558 float insetL = winCrop.left * xScale;
559 float insetT = winCrop.top * yScale;
560 float insetR = (winWidth - winCrop.right ) * xScale;
561 float insetB = (winHeight - winCrop.bottom) * yScale;
562
563 crop.left += insetL;
564 crop.top += insetT;
565 crop.right -= insetR;
566 crop.bottom -= insetB;
567
Mathias Agopian13127d82013-03-05 17:47:11 -0800568 return crop;
569}
570
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000571#ifdef USE_HWC2
Robert Carrae060832016-11-28 10:51:00 -0800572void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000573#else
574void Layer::setGeometry(
575 const sp<const DisplayDevice>& hw,
576 HWComposer::HWCLayerInterface& layer)
577#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700578{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000579#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800580 const auto hwcId = displayDevice->getHwcDisplayId();
581 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000582#else
583 layer.setDefaultState();
584#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700585
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700586 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000587#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800588 hwcInfo.forceClientComposition = false;
589
590 if (isSecure() && !displayDevice->isSecure()) {
591 hwcInfo.forceClientComposition = true;
592 }
593
594 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000595#else
596 layer.setSkip(false);
597
598 if (isSecure() && !hw->isSecure()) {
599 layer.setSkip(true);
600 }
601#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700602
Mathias Agopian13127d82013-03-05 17:47:11 -0800603 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700604 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000605#ifdef USE_HWC2
David Revemanecf0fa52017-03-03 11:32:44 -0500606 auto blendMode = HWC2::BlendMode::None;
Robert Carr6452f122017-03-21 10:41:29 -0700607 if (!isOpaque(s) || getAlpha() != 1.0f) {
David Revemanecf0fa52017-03-03 11:32:44 -0500608 blendMode = mPremultipliedAlpha ?
Dan Stoza9e56aa02015-11-02 13:00:03 -0800609 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800610 }
David Revemanecf0fa52017-03-03 11:32:44 -0500611 auto error = hwcLayer->setBlendMode(blendMode);
612 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
613 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
614 to_string(error).c_str(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000615#else
Robert Carr6452f122017-03-21 10:41:29 -0700616 if (!isOpaque(s) || getAlpha() != 0xFF) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000617 layer.setBlending(mPremultipliedAlpha ?
618 HWC_BLENDING_PREMULT :
619 HWC_BLENDING_COVERAGE);
620 }
621#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800622
623 // apply the layer's transform, followed by the display's global transform
624 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700625 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700626 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -0700627 if (!s.crop.isEmpty()) {
628 Rect activeCrop(s.crop);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700629 activeCrop = t.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000630#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000631 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000632#else
633 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
634#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000635 activeCrop.clear();
636 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700637 activeCrop = t.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800638 // This needs to be here as transform.transform(Rect) computes the
639 // transformed rect and then takes the bounding box of the result before
640 // returning. This means
641 // transform.inverse().transform(transform.transform(Rect)) != Rect
642 // in which case we need to make sure the final rect is clipped to the
643 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000644 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
645 activeCrop.clear();
646 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700647 // mark regions outside the crop as transparent
648 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
649 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
650 s.active.w, s.active.h));
651 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
652 activeCrop.left, activeCrop.bottom));
653 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
654 s.active.w, activeCrop.bottom));
655 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700656
657 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700658 if (!s.finalCrop.isEmpty()) {
659 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000660 frame.clear();
661 }
662 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000663#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000664 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
665 frame.clear();
666 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800667 const Transform& tr(displayDevice->getTransform());
668 Rect transformedFrame = tr.transform(frame);
David Revemanecf0fa52017-03-03 11:32:44 -0500669 error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700670 if (error != HWC2::Error::None) {
671 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
672 mName.string(), transformedFrame.left, transformedFrame.top,
673 transformedFrame.right, transformedFrame.bottom,
674 to_string(error).c_str(), static_cast<int32_t>(error));
675 } else {
676 hwcInfo.displayFrame = transformedFrame;
677 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800678
Dan Stoza5a423ea2017-02-16 14:10:39 -0800679 FloatRect sourceCrop = computeCrop(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800680 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700681 if (error != HWC2::Error::None) {
682 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
683 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
684 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
685 static_cast<int32_t>(error));
686 } else {
687 hwcInfo.sourceCrop = sourceCrop;
688 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800689
Robert Carr6452f122017-03-21 10:41:29 -0700690 float alpha = getAlpha();
691 error = hwcLayer->setPlaneAlpha(alpha);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800692 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
Robert Carr6452f122017-03-21 10:41:29 -0700693 "%s (%d)", mName.string(), alpha, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800694 static_cast<int32_t>(error));
695
Robert Carrae060832016-11-28 10:51:00 -0800696 error = hwcLayer->setZOrder(z);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800697 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
Robert Carrae060832016-11-28 10:51:00 -0800698 mName.string(), z, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800699 static_cast<int32_t>(error));
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500700
701 error = hwcLayer->setInfo(s.type, s.appId);
702 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
703 mName.string(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000704#else
705 if (!frame.intersect(hw->getViewport(), &frame)) {
706 frame.clear();
707 }
708 const Transform& tr(hw->getTransform());
709 layer.setFrame(tr.transform(frame));
710 layer.setCrop(computeCrop(hw));
Robert Carr6452f122017-03-21 10:41:29 -0700711 layer.setPlaneAlpha(getAlpha());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000712#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800713
Mathias Agopian29a367b2011-07-12 14:51:45 -0700714 /*
715 * Transformations are applied in this order:
716 * 1) buffer orientation/flip/mirror
717 * 2) state transformation (window manager)
718 * 3) layer orientation (screen orientation)
719 * (NOTE: the matrices are multiplied in reverse order)
720 */
721
722 const Transform bufferOrientation(mCurrentTransform);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700723 Transform transform(tr * t * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700724
Robert Carrcae605c2017-03-29 12:10:31 -0700725 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700726 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700727 * the code below applies the primary display's inverse transform to the
728 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700729 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700730 uint32_t invTransform =
731 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700732 // calculate the inverse transform
733 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
734 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
735 NATIVE_WINDOW_TRANSFORM_FLIP_H;
736 }
Robert Carrcae605c2017-03-29 12:10:31 -0700737
738 /*
739 * Here we cancel out the orientation component of the WM transform.
740 * The scaling and translate components are already included in our bounds
741 * computation so it's enough to just omit it in the composition.
742 * See comment in onDraw with ref to b/36727915 for why.
743 */
744 transform = Transform(invTransform) * tr * bufferOrientation;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700745 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700746
747 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800748 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000749#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800750 if (orientation & Transform::ROT_INVALID) {
751 // we can only handle simple transformation
752 hwcInfo.forceClientComposition = true;
753 } else {
754 auto transform = static_cast<HWC2::Transform>(orientation);
755 auto error = hwcLayer->setTransform(transform);
756 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
757 "%s (%d)", mName.string(), to_string(transform).c_str(),
758 to_string(error).c_str(), static_cast<int32_t>(error));
759 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000760#else
761 if (orientation & Transform::ROT_INVALID) {
762 // we can only handle simple transformation
763 layer.setSkip(true);
764 } else {
765 layer.setTransform(orientation);
766 }
767#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700768}
769
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000770#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800771void Layer::forceClientComposition(int32_t hwcId) {
772 if (mHwcLayers.count(hwcId) == 0) {
773 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
774 return;
775 }
776
777 mHwcLayers[hwcId].forceClientComposition = true;
778}
Dan Stoza9e56aa02015-11-02 13:00:03 -0800779
Dan Stoza9e56aa02015-11-02 13:00:03 -0800780void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
781 // Apply this display's projection's viewport to the visible region
782 // before giving it to the HWC HAL.
783 const Transform& tr = displayDevice->getTransform();
784 const auto& viewport = displayDevice->getViewport();
785 Region visible = tr.transform(visibleRegion.intersect(viewport));
786 auto hwcId = displayDevice->getHwcDisplayId();
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800787 auto& hwcInfo = mHwcLayers[hwcId];
788 auto& hwcLayer = hwcInfo.layer;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800789 auto error = hwcLayer->setVisibleRegion(visible);
790 if (error != HWC2::Error::None) {
791 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
792 to_string(error).c_str(), static_cast<int32_t>(error));
793 visible.dump(LOG_TAG);
794 }
795
796 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
797 if (error != HWC2::Error::None) {
798 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
799 to_string(error).c_str(), static_cast<int32_t>(error));
800 surfaceDamageRegion.dump(LOG_TAG);
801 }
802
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700803 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800804 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700805 setCompositionType(hwcId, HWC2::Composition::Sideband);
806 ALOGV("[%s] Requesting Sideband composition", mName.string());
807 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800808 if (error != HWC2::Error::None) {
809 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
810 mName.string(), mSidebandStream->handle(),
811 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800812 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700813 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800814 }
815
Dan Stoza0a21df72016-07-20 12:52:38 -0700816 // Client layers
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800817 if (hwcInfo.forceClientComposition ||
Dan Stoza0a21df72016-07-20 12:52:38 -0700818 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700819 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800820 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700821 return;
822 }
823
Dan Stoza0a21df72016-07-20 12:52:38 -0700824 // SolidColor layers
825 if (mActiveBuffer == nullptr) {
826 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700827
828 // For now, we only support black for DimLayer
Dan Stoza0a21df72016-07-20 12:52:38 -0700829 error = hwcLayer->setColor({0, 0, 0, 255});
830 if (error != HWC2::Error::None) {
831 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
832 to_string(error).c_str(), static_cast<int32_t>(error));
833 }
Dan Stozac6c89542016-07-27 10:16:52 -0700834
835 // Clear out the transform, because it doesn't make sense absent a
836 // source buffer
837 error = hwcLayer->setTransform(HWC2::Transform::None);
838 if (error != HWC2::Error::None) {
839 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
840 to_string(error).c_str(), static_cast<int32_t>(error));
841 }
842
Dan Stoza0a21df72016-07-20 12:52:38 -0700843 return;
844 }
845
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700846 // Device or Cursor layers
847 if (mPotentialCursor) {
848 ALOGV("[%s] Requesting Cursor composition", mName.string());
849 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800850 } else {
851 ALOGV("[%s] Requesting Device composition", mName.string());
852 setCompositionType(hwcId, HWC2::Composition::Device);
853 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700854
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700855 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
856 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
857 if (error != HWC2::Error::None) {
858 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
859 mCurrentState.dataSpace, to_string(error).c_str(),
860 static_cast<int32_t>(error));
861 }
862
Chia-I Wu06d63de2017-01-04 14:58:51 +0800863 uint32_t hwcSlot = 0;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400864 sp<GraphicBuffer> hwcBuffer;
865 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
866 &hwcSlot, &hwcBuffer);
Chia-I Wu06d63de2017-01-04 14:58:51 +0800867
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700868 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400869 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700870 if (error != HWC2::Error::None) {
871 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
872 mActiveBuffer->handle, to_string(error).c_str(),
873 static_cast<int32_t>(error));
874 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800875}
Courtney Goeltzenleuchter9551fd32016-10-20 17:18:15 -0600876
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000877#else
878void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
879 HWComposer::HWCLayerInterface& layer) {
880 // we have to set the visible region on every frame because
881 // we currently free it during onLayerDisplayed(), which is called
882 // after HWComposer::commit() -- every frame.
883 // Apply this display's projection's viewport to the visible region
884 // before giving it to the HWC HAL.
885 const Transform& tr = hw->getTransform();
886 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
887 layer.setVisibleRegionScreen(visible);
888 layer.setSurfaceDamage(surfaceDamageRegion);
889 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700890
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000891 if (mSidebandStream.get()) {
892 layer.setSidebandStream(mSidebandStream);
893 } else {
894 // NOTE: buffer can be NULL if the client never drew into this
895 // layer yet, or if we ran out of memory
896 layer.setBuffer(mActiveBuffer);
897 }
898}
899#endif
900
901#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800902void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
903 auto hwcId = displayDevice->getHwcDisplayId();
904 if (mHwcLayers.count(hwcId) == 0 ||
905 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
906 return;
907 }
908
909 // This gives us only the "orientation" component of the transform
910 const State& s(getCurrentState());
911
912 // Apply the layer's transform, followed by the display's global transform
913 // Here we're guaranteed that the layer's transform preserves rects
914 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700915 if (!s.crop.isEmpty()) {
916 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800917 }
918 // Subtract the transparent region and snap to the bounds
919 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700920 Rect frame(getTransform().transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800921 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -0700922 if (!s.finalCrop.isEmpty()) {
923 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000924 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800925 auto& displayTransform(displayDevice->getTransform());
926 auto position = displayTransform.transform(frame);
927
928 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
929 position.top);
930 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
931 "to (%d, %d): %s (%d)", mName.string(), position.left,
932 position.top, to_string(error).c_str(),
933 static_cast<int32_t>(error));
934}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000935#else
936void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
937 HWComposer::HWCLayerInterface& layer) {
938 int fenceFd = -1;
939
940 // TODO: there is a possible optimization here: we only need to set the
941 // acquire fence the first time a new buffer is acquired on EACH display.
942
943 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
944 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
945 if (fence->isValid()) {
946 fenceFd = fence->dup();
947 if (fenceFd == -1) {
948 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
949 }
950 }
951 }
952 layer.setAcquireFenceFd(fenceFd);
953}
954
955Rect Layer::getPosition(
956 const sp<const DisplayDevice>& hw)
957{
958 // this gives us only the "orientation" component of the transform
959 const State& s(getCurrentState());
960
961 // apply the layer's transform, followed by the display's global transform
962 // here we're guaranteed that the layer's transform preserves rects
963 Rect win(s.active.w, s.active.h);
964 if (!s.crop.isEmpty()) {
965 win.intersect(s.crop, &win);
966 }
967 // subtract the transparent region and snap to the bounds
968 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700969 Rect frame(getTransform().transform(bounds));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000970 frame.intersect(hw->getViewport(), &frame);
971 if (!s.finalCrop.isEmpty()) {
972 frame.intersect(s.finalCrop, &frame);
973 }
974 const Transform& tr(hw->getTransform());
975 return Rect(tr.transform(frame));
976}
977#endif
Riley Andrews03414a12014-07-01 14:22:59 -0700978
Mathias Agopian13127d82013-03-05 17:47:11 -0800979// ---------------------------------------------------------------------------
980// drawing...
981// ---------------------------------------------------------------------------
982
983void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -0800984 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -0800985}
986
Dan Stozac7014012014-02-14 15:03:43 -0800987void Layer::draw(const sp<const DisplayDevice>& hw,
988 bool useIdentityTransform) const {
989 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -0800990}
991
Dan Stozac7014012014-02-14 15:03:43 -0800992void Layer::draw(const sp<const DisplayDevice>& hw) const {
993 onDraw(hw, Region(hw->bounds()), false);
994}
995
Robert Carrcae605c2017-03-29 12:10:31 -0700996static constexpr mat4 inverseOrientation(uint32_t transform) {
997 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
998 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
999 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1000 mat4 tr;
1001
1002 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1003 tr = tr * rot90;
1004 }
1005 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1006 tr = tr * flipH;
1007 }
1008 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1009 tr = tr * flipV;
1010 }
1011 return inverse(tr);
1012}
1013
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001014/*
1015 * onDraw will draw the current layer onto the presentable buffer
1016 */
Dan Stozac7014012014-02-14 15:03:43 -08001017void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
1018 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001019{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001020 ATRACE_CALL();
1021
Mathias Agopiana67932f2011-04-20 14:20:59 -07001022 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001023 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -07001024 // in fact never been drawn into. This happens frequently with
1025 // SurfaceView because the WindowManager can't know when the client
1026 // has drawn the first time.
1027
1028 // If there is nothing under us, we paint the screen in black, otherwise
1029 // we just skip this update.
1030
1031 // figure out if there is something below us
1032 Region under;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001033 bool finished = false;
Dan Stoza412903f2017-04-27 13:42:17 -07001034 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001035 if (finished || layer == static_cast<Layer const*>(this)) {
1036 finished = true;
1037 return;
1038 }
Mathias Agopian42977342012-08-05 00:40:46 -07001039 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Robert Carr1f0a16a2016-10-24 16:27:39 -07001040 });
Mathias Agopian179169e2010-05-06 20:21:45 -07001041 // if not everything below us is covered, we plug the holes!
1042 Region holes(clip.subtract(under));
1043 if (!holes.isEmpty()) {
Fabien Sanglard17487192016-12-07 13:03:32 -08001044 clearWithOpenGL(hw, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -07001045 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001046 return;
1047 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001048
Andy McFadden97eba892012-12-11 15:21:45 -08001049 // Bind the current buffer to the GL texture, and wait for it to be
1050 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001051 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1052 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -08001053 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -07001054 // Go ahead and draw the buffer anyway; no matter what we do the screen
1055 // is probably going to have something visibly wrong.
1056 }
1057
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001058 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1059
Mathias Agopian875d8e12013-06-07 15:35:48 -07001060 RenderEngine& engine(mFlinger->getRenderEngine());
1061
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001062 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -07001063 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -07001064 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -07001065
1066 // Query the texture matrix given our current filtering mode.
1067 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001068 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1069 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -07001070
Robert Carrcae605c2017-03-29 12:10:31 -07001071 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001072
1073 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -07001074 * the code below applies the primary display's inverse transform to
1075 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001076 */
Pablo Ceballos021623b2016-04-15 17:31:51 -07001077 uint32_t transform =
1078 DisplayDevice::getPrimaryDisplayOrientationTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001079 mat4 tr = inverseOrientation(transform);
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001080
Robert Carrcae605c2017-03-29 12:10:31 -07001081 /**
1082 * TODO(b/36727915): This is basically a hack.
1083 *
1084 * Ensure that regardless of the parent transformation,
1085 * this buffer is always transformed from native display
1086 * orientation to display orientation. For example, in the case
1087 * of a camera where the buffer remains in native orientation,
1088 * we want the pixels to always be upright.
1089 */
1090 if (getParent() != nullptr) {
1091 const auto parentTransform = getParent()->getTransform();
1092 tr = tr * inverseOrientation(parentTransform.getOrientation());
1093 }
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001094
1095 // and finally apply it to the original texture matrix
1096 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1097 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1098 }
1099
Jamie Genniscbb1a952012-05-08 17:05:52 -07001100 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -07001101 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1102 mTexture.setFiltering(useFiltering);
1103 mTexture.setMatrix(textureMatrix);
1104
1105 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -07001106 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001107 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -07001108 }
Fabien Sanglard85789802016-12-07 13:08:24 -08001109 drawWithOpenGL(hw, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001110 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001111}
1112
Mathias Agopian13127d82013-03-05 17:47:11 -08001113
Dan Stozac7014012014-02-14 15:03:43 -08001114void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard17487192016-12-07 13:03:32 -08001115 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -08001116 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001117{
Mathias Agopian19733a32013-08-28 18:13:56 -07001118 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -08001119 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -07001120 engine.setupFillWithColor(red, green, blue, alpha);
1121 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -08001122}
1123
1124void Layer::clearWithOpenGL(
Fabien Sanglard17487192016-12-07 13:03:32 -08001125 const sp<const DisplayDevice>& hw) const {
1126 clearWithOpenGL(hw, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001127}
1128
Dan Stozac7014012014-02-14 15:03:43 -08001129void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard85789802016-12-07 13:08:24 -08001130 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001131 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001132
Dan Stozac7014012014-02-14 15:03:43 -08001133 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001134
Mathias Agopian13127d82013-03-05 17:47:11 -08001135 /*
1136 * NOTE: the way we compute the texture coordinates here produces
1137 * different results than when we take the HWC path -- in the later case
1138 * the "source crop" is rounded to texel boundaries.
1139 * This can produce significantly different results when the texture
1140 * is scaled by a large amount.
1141 *
1142 * The GL code below is more logical (imho), and the difference with
1143 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001144 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001145 * GL composition when a buffer scaling is applied (maybe with some
1146 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1147 * like more of a hack.
1148 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001149 Rect win(computeBounds());
1150
Robert Carr1f0a16a2016-10-24 16:27:39 -07001151 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -07001152 if (!s.finalCrop.isEmpty()) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001153 win = t.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001154 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001155 win.clear();
1156 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001157 win = t.inverse().transform(win);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001158 if (!win.intersect(computeBounds(), &win)) {
1159 win.clear();
1160 }
1161 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001162
Mathias Agopian3f844832013-08-07 21:24:32 -07001163 float left = float(win.left) / float(s.active.w);
1164 float top = float(win.top) / float(s.active.h);
1165 float right = float(win.right) / float(s.active.w);
1166 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001167
Mathias Agopian875d8e12013-06-07 15:35:48 -07001168 // TODO: we probably want to generate the texture coords with the mesh
1169 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001170 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1171 texCoords[0] = vec2(left, 1.0f - top);
1172 texCoords[1] = vec2(left, 1.0f - bottom);
1173 texCoords[2] = vec2(right, 1.0f - bottom);
1174 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001175
Mathias Agopian875d8e12013-06-07 15:35:48 -07001176 RenderEngine& engine(mFlinger->getRenderEngine());
Robert Carr6452f122017-03-21 10:41:29 -07001177 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), getAlpha());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001178#ifdef USE_HWC2
1179 engine.setSourceDataSpace(mCurrentState.dataSpace);
1180#endif
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001181 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001182 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001183}
1184
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001185#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001186void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1187 bool callIntoHwc) {
1188 if (mHwcLayers.count(hwcId) == 0) {
1189 ALOGE("setCompositionType called without a valid HWC layer");
1190 return;
1191 }
1192 auto& hwcInfo = mHwcLayers[hwcId];
1193 auto& hwcLayer = hwcInfo.layer;
1194 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1195 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1196 if (hwcInfo.compositionType != type) {
1197 ALOGV(" actually setting");
1198 hwcInfo.compositionType = type;
1199 if (callIntoHwc) {
1200 auto error = hwcLayer->setCompositionType(type);
1201 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1202 "composition type %s: %s (%d)", mName.string(),
1203 to_string(type).c_str(), to_string(error).c_str(),
1204 static_cast<int32_t>(error));
1205 }
1206 }
1207}
1208
1209HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001210 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1211 // If we're querying the composition type for a display that does not
1212 // have a HWC counterpart, then it will always be Client
1213 return HWC2::Composition::Client;
1214 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001215 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001216 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001217 return HWC2::Composition::Invalid;
1218 }
1219 return mHwcLayers.at(hwcId).compositionType;
1220}
1221
1222void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1223 if (mHwcLayers.count(hwcId) == 0) {
1224 ALOGE("setClearClientTarget called without a valid HWC layer");
1225 return;
1226 }
1227 mHwcLayers[hwcId].clearClientTarget = clear;
1228}
1229
1230bool Layer::getClearClientTarget(int32_t hwcId) const {
1231 if (mHwcLayers.count(hwcId) == 0) {
1232 ALOGE("getClearClientTarget called without a valid HWC layer");
1233 return false;
1234 }
1235 return mHwcLayers.at(hwcId).clearClientTarget;
1236}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001237#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001238
Ruben Brunk1681d952014-06-27 15:51:55 -07001239uint32_t Layer::getProducerStickyTransform() const {
1240 int producerStickyTransform = 0;
1241 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1242 if (ret != OK) {
1243 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1244 strerror(-ret), ret);
1245 return 0;
1246 }
1247 return static_cast<uint32_t>(producerStickyTransform);
1248}
1249
Dan Stozac5da2712016-07-20 15:38:12 -07001250bool Layer::latchUnsignaledBuffers() {
1251 static bool propertyLoaded = false;
1252 static bool latch = false;
1253 static std::mutex mutex;
1254 std::lock_guard<std::mutex> lock(mutex);
1255 if (!propertyLoaded) {
1256 char value[PROPERTY_VALUE_MAX] = {};
1257 property_get("debug.sf.latch_unsignaled", value, "0");
1258 latch = atoi(value);
1259 propertyLoaded = true;
1260 }
1261 return latch;
1262}
1263
Dan Stozacac35382016-01-27 12:21:06 -08001264uint64_t Layer::getHeadFrameNumber() const {
1265 Mutex::Autolock lock(mQueueItemLock);
1266 if (!mQueueItems.empty()) {
1267 return mQueueItems[0].mFrameNumber;
1268 } else {
1269 return mCurrentFrameNumber;
1270 }
1271}
1272
Dan Stoza1ce65812016-06-15 16:26:27 -07001273bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001274#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001275 if (latchUnsignaledBuffers()) {
1276 return true;
1277 }
1278
Dan Stoza1ce65812016-06-15 16:26:27 -07001279 Mutex::Autolock lock(mQueueItemLock);
1280 if (mQueueItems.empty()) {
1281 return true;
1282 }
1283 if (mQueueItems[0].mIsDroppable) {
1284 // Even though this buffer's fence may not have signaled yet, it could
1285 // be replaced by another buffer before it has a chance to, which means
1286 // that it's possible to get into a situation where a buffer is never
1287 // able to be latched. To avoid this, grab this buffer anyway.
1288 return true;
1289 }
1290 return mQueueItems[0].mFence->getSignalTime() != INT64_MAX;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001291#else
1292 return true;
1293#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001294}
1295
Dan Stozacac35382016-01-27 12:21:06 -08001296bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1297 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1298 // Don't bother with a SyncPoint, since we've already latched the
1299 // relevant frame
1300 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001301 }
1302
Dan Stozacac35382016-01-27 12:21:06 -08001303 Mutex::Autolock lock(mLocalSyncPointMutex);
1304 mLocalSyncPoints.push_back(point);
1305 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001306}
1307
Mathias Agopian13127d82013-03-05 17:47:11 -08001308void Layer::setFiltering(bool filtering) {
1309 mFiltering = filtering;
1310}
1311
1312bool Layer::getFiltering() const {
1313 return mFiltering;
1314}
1315
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001316// As documented in libhardware header, formats in the range
1317// 0x100 - 0x1FF are specific to the HAL implementation, and
1318// are known to have no alpha channel
1319// TODO: move definition for device-specific range into
1320// hardware.h, instead of using hard-coded values here.
1321#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1322
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001323bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001324 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1325 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001326 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001327 switch (format) {
1328 case HAL_PIXEL_FORMAT_RGBA_8888:
1329 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001330 case HAL_PIXEL_FORMAT_RGBA_FP16:
Romain Guy541f2262017-02-10 18:50:17 -08001331 case HAL_PIXEL_FORMAT_RGBA_1010102:
Mathias Agopiandd533712013-07-26 15:31:39 -07001332 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001333 }
1334 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001335 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001336}
1337
Mathias Agopian13127d82013-03-05 17:47:11 -08001338// ----------------------------------------------------------------------------
1339// local state
1340// ----------------------------------------------------------------------------
1341
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001342static void boundPoint(vec2* point, const Rect& crop) {
1343 if (point->x < crop.left) {
1344 point->x = crop.left;
1345 }
1346 if (point->x > crop.right) {
1347 point->x = crop.right;
1348 }
1349 if (point->y < crop.top) {
1350 point->y = crop.top;
1351 }
1352 if (point->y > crop.bottom) {
1353 point->y = crop.bottom;
1354 }
1355}
1356
Dan Stozac7014012014-02-14 15:03:43 -08001357void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1358 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001359{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001360 const Layer::State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001361 const Transform hwTransform(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001362 const uint32_t hw_h = hw->getHeight();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001363 Rect win = computeBounds();
Mathias Agopian3f844832013-08-07 21:24:32 -07001364
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001365 vec2 lt = vec2(win.left, win.top);
1366 vec2 lb = vec2(win.left, win.bottom);
1367 vec2 rb = vec2(win.right, win.bottom);
1368 vec2 rt = vec2(win.right, win.top);
1369
Robert Carr1f0a16a2016-10-24 16:27:39 -07001370 Transform layerTransform = getTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001371 if (!useIdentityTransform) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001372 lt = layerTransform.transform(lt);
1373 lb = layerTransform.transform(lb);
1374 rb = layerTransform.transform(rb);
1375 rt = layerTransform.transform(rt);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001376 }
1377
Robert Carrb5d3d262016-03-25 15:08:13 -07001378 if (!s.finalCrop.isEmpty()) {
1379 boundPoint(&lt, s.finalCrop);
1380 boundPoint(&lb, s.finalCrop);
1381 boundPoint(&rb, s.finalCrop);
1382 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001383 }
1384
Mathias Agopianff2ed702013-09-01 21:36:12 -07001385 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001386 position[0] = hwTransform.transform(lt);
1387 position[1] = hwTransform.transform(lb);
1388 position[2] = hwTransform.transform(rb);
1389 position[3] = hwTransform.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001390 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001391 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001392 }
1393}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001394
Andy McFadden4125a4f2014-01-29 17:17:11 -08001395bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001396{
neo.hee6fd41d2017-02-17 14:35:33 +08001397 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
Mathias Agopiana67932f2011-04-20 14:20:59 -07001398 // layer's opaque flag.
neo.hee6fd41d2017-02-17 14:35:33 +08001399 if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001400 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001401 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001402
1403 // if the layer has the opaque flag, then we're always opaque,
1404 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001405 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001406}
1407
Dan Stoza23116082015-06-18 14:58:39 -07001408bool Layer::isSecure() const
1409{
1410 const Layer::State& s(mDrawingState);
1411 return (s.flags & layer_state_t::eLayerSecure);
1412}
1413
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001414bool Layer::isProtected() const
1415{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001416 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001417 return (activeBuffer != 0) &&
1418 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1419}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001420
Mathias Agopian13127d82013-03-05 17:47:11 -08001421bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001422 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001423}
1424
1425bool Layer::isCropped() const {
1426 return !mCurrentCrop.isEmpty();
1427}
1428
1429bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1430 return mNeedsFiltering || hw->needsFiltering();
1431}
1432
1433void Layer::setVisibleRegion(const Region& visibleRegion) {
1434 // always called from main thread
1435 this->visibleRegion = visibleRegion;
1436}
1437
1438void Layer::setCoveredRegion(const Region& coveredRegion) {
1439 // always called from main thread
1440 this->coveredRegion = coveredRegion;
1441}
1442
1443void Layer::setVisibleNonTransparentRegion(const Region&
1444 setVisibleNonTransparentRegion) {
1445 // always called from main thread
1446 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1447}
1448
1449// ----------------------------------------------------------------------------
1450// transaction
1451// ----------------------------------------------------------------------------
1452
Dan Stoza7dde5992015-05-22 09:51:44 -07001453void Layer::pushPendingState() {
1454 if (!mCurrentState.modified) {
1455 return;
1456 }
1457
Dan Stoza7dde5992015-05-22 09:51:44 -07001458 // If this transaction is waiting on the receipt of a frame, generate a sync
1459 // point and send it to the remote layer.
Robert Carr0d480722017-01-10 16:42:54 -08001460 if (mCurrentState.barrierLayer != nullptr) {
1461 sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1462 if (barrierLayer == nullptr) {
1463 ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
Dan Stoza7dde5992015-05-22 09:51:44 -07001464 // If we can't promote the layer we are intended to wait on,
1465 // then it is expired or otherwise invalid. Allow this transaction
1466 // to be applied as per normal (no synchronization).
Robert Carr0d480722017-01-10 16:42:54 -08001467 mCurrentState.barrierLayer = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001468 } else {
1469 auto syncPoint = std::make_shared<SyncPoint>(
1470 mCurrentState.frameNumber);
Robert Carr0d480722017-01-10 16:42:54 -08001471 if (barrierLayer->addSyncPoint(syncPoint)) {
Dan Stozacac35382016-01-27 12:21:06 -08001472 mRemoteSyncPoints.push_back(std::move(syncPoint));
1473 } else {
1474 // We already missed the frame we're supposed to synchronize
1475 // on, so go ahead and apply the state update
Robert Carr0d480722017-01-10 16:42:54 -08001476 mCurrentState.barrierLayer = nullptr;
Dan Stozacac35382016-01-27 12:21:06 -08001477 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001478 }
1479
Dan Stoza7dde5992015-05-22 09:51:44 -07001480 // Wake us up to check if the frame has been received
1481 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001482 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001483 }
1484 mPendingStates.push_back(mCurrentState);
1485}
1486
Pablo Ceballos05289c22016-04-14 15:49:55 -07001487void Layer::popPendingState(State* stateToCommit) {
1488 auto oldFlags = stateToCommit->flags;
1489 *stateToCommit = mPendingStates[0];
1490 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1491 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001492
1493 mPendingStates.removeAt(0);
1494}
1495
Pablo Ceballos05289c22016-04-14 15:49:55 -07001496bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001497 bool stateUpdateAvailable = false;
1498 while (!mPendingStates.empty()) {
Robert Carr0d480722017-01-10 16:42:54 -08001499 if (mPendingStates[0].barrierLayer != nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001500 if (mRemoteSyncPoints.empty()) {
1501 // If we don't have a sync point for this, apply it anyway. It
1502 // will be visually wrong, but it should keep us from getting
1503 // into too much trouble.
1504 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001505 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001506 stateUpdateAvailable = true;
1507 continue;
1508 }
1509
Dan Stozacac35382016-01-27 12:21:06 -08001510 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1511 mPendingStates[0].frameNumber) {
1512 ALOGE("[%s] Unexpected sync point frame number found",
1513 mName.string());
1514
1515 // Signal our end of the sync point and then dispose of it
1516 mRemoteSyncPoints.front()->setTransactionApplied();
1517 mRemoteSyncPoints.pop_front();
1518 continue;
1519 }
1520
Dan Stoza7dde5992015-05-22 09:51:44 -07001521 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1522 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001523 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001524 stateUpdateAvailable = true;
1525
1526 // Signal our end of the sync point and then dispose of it
1527 mRemoteSyncPoints.front()->setTransactionApplied();
1528 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001529 } else {
1530 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001531 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001532 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001533 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001534 stateUpdateAvailable = true;
1535 }
1536 }
1537
1538 // If we still have pending updates, wake SurfaceFlinger back up and point
1539 // it at this layer so we can process them
1540 if (!mPendingStates.empty()) {
1541 setTransactionFlags(eTransactionNeeded);
1542 mFlinger->setTransactionFlags(eTraversalNeeded);
1543 }
1544
1545 mCurrentState.modified = false;
1546 return stateUpdateAvailable;
1547}
1548
1549void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001550 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001551 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001552 Mutex::Autolock lock(mLocalSyncPointMutex);
1553 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001554 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001555 point->setFrameAvailable();
1556 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001557 }
1558}
1559
Mathias Agopian13127d82013-03-05 17:47:11 -08001560uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001561 ATRACE_CALL();
1562
Dan Stoza7dde5992015-05-22 09:51:44 -07001563 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001564 Layer::State c = getCurrentState();
1565 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001566 return 0;
1567 }
1568
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001569 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001570
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001571 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1572 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001573
1574 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001575 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001576 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001577 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001578 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001579 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001580 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001581 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001582 this, getName().string(), mCurrentTransform,
1583 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001584 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001585 c.crop.left,
1586 c.crop.top,
1587 c.crop.right,
1588 c.crop.bottom,
1589 c.crop.getWidth(),
1590 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001591 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001592 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001593 s.crop.left,
1594 s.crop.top,
1595 s.crop.right,
1596 s.crop.bottom,
1597 s.crop.getWidth(),
1598 s.crop.getHeight(),
1599 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001600
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001601 // record the new size, form this point on, when the client request
1602 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001603 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001604 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001605 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001606
Robert Carr82364e32016-05-15 11:27:47 -07001607 const bool resizePending = (c.requested.w != c.active.w) ||
1608 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001609 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001610 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001611 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001612 // if we have a pending resize, unless we are in fixed-size mode.
1613 // the drawing state will be updated only once we receive a buffer
1614 // with the correct size.
1615 //
1616 // in particular, we want to make sure the clip (which is part
1617 // of the geometry state) is latched together with the size but is
1618 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001619 //
1620 // If a sideband stream is attached, however, we want to skip this
1621 // optimization so that transactions aren't missed when a buffer
1622 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001623
1624 flags |= eDontUpdateGeometryState;
1625 }
1626 }
1627
Mathias Agopian13127d82013-03-05 17:47:11 -08001628 // always set active to requested, unless we're asked not to
1629 // this is used by Layer, which special cases resizes.
1630 if (flags & eDontUpdateGeometryState) {
1631 } else {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001632 Layer::State& editCurrentState(getCurrentState());
Robert Carr82364e32016-05-15 11:27:47 -07001633 if (mFreezePositionUpdates) {
1634 float tx = c.active.transform.tx();
1635 float ty = c.active.transform.ty();
1636 c.active = c.requested;
1637 c.active.transform.set(tx, ty);
1638 editCurrentState.active = c.active;
1639 } else {
1640 editCurrentState.active = editCurrentState.requested;
1641 c.active = c.requested;
1642 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001643 }
1644
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001645 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001646 // invalidate and recompute the visible regions if needed
1647 flags |= Layer::eVisibleRegion;
1648 }
1649
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001650 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001651 // invalidate and recompute the visible regions if needed
1652 flags |= eVisibleRegion;
1653 this->contentDirty = true;
1654
1655 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001656 const uint8_t type = c.active.transform.getType();
1657 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001658 (type >= Transform::SCALE));
1659 }
1660
Dan Stozac8145172016-04-28 16:29:06 -07001661 // If the layer is hidden, signal and clear out all local sync points so
1662 // that transactions for layers depending on this layer's frames becoming
1663 // visible are not blocked
1664 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001665 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001666 }
1667
Mathias Agopian13127d82013-03-05 17:47:11 -08001668 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001669 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001670 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001671}
1672
Pablo Ceballos05289c22016-04-14 15:49:55 -07001673void Layer::commitTransaction(const State& stateToCommit) {
1674 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001675}
1676
Mathias Agopian13127d82013-03-05 17:47:11 -08001677uint32_t Layer::getTransactionFlags(uint32_t flags) {
1678 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1679}
1680
1681uint32_t Layer::setTransactionFlags(uint32_t flags) {
1682 return android_atomic_or(flags, &mTransactionFlags);
1683}
1684
Robert Carr82364e32016-05-15 11:27:47 -07001685bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001686 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001687 return false;
1688 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001689
1690 // We update the requested and active position simultaneously because
1691 // we want to apply the position portion of the transform matrix immediately,
1692 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001693 mCurrentState.requested.transform.set(x, y);
Robert Carr82364e32016-05-15 11:27:47 -07001694 if (immediate && !mFreezePositionUpdates) {
1695 mCurrentState.active.transform.set(x, y);
1696 }
1697 mFreezePositionUpdates = mFreezePositionUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001698
Dan Stoza7dde5992015-05-22 09:51:44 -07001699 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001700 setTransactionFlags(eTransactionNeeded);
1701 return true;
1702}
Robert Carr82364e32016-05-15 11:27:47 -07001703
Robert Carr1f0a16a2016-10-24 16:27:39 -07001704bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1705 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1706 if (idx < 0) {
1707 return false;
1708 }
1709 if (childLayer->setLayer(z)) {
1710 mCurrentChildren.removeAt(idx);
1711 mCurrentChildren.add(childLayer);
1712 }
1713 return true;
1714}
1715
Robert Carrae060832016-11-28 10:51:00 -08001716bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001717 if (mCurrentState.z == z)
1718 return false;
1719 mCurrentState.sequence++;
1720 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001721 mCurrentState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001722
1723 // Discard all relative layering.
1724 if (mCurrentState.zOrderRelativeOf != nullptr) {
1725 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1726 if (strongRelative != nullptr) {
1727 strongRelative->removeZOrderRelative(this);
1728 }
1729 mCurrentState.zOrderRelativeOf = nullptr;
1730 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001731 setTransactionFlags(eTransactionNeeded);
1732 return true;
1733}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001734
Robert Carrdb66e622017-04-10 16:55:57 -07001735void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1736 mCurrentState.zOrderRelatives.remove(relative);
1737 mCurrentState.sequence++;
1738 mCurrentState.modified = true;
1739 setTransactionFlags(eTransactionNeeded);
1740}
1741
1742void Layer::addZOrderRelative(const wp<Layer>& relative) {
1743 mCurrentState.zOrderRelatives.add(relative);
1744 mCurrentState.modified = true;
1745 mCurrentState.sequence++;
1746 setTransactionFlags(eTransactionNeeded);
1747}
1748
1749bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1750 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1751 if (handle == nullptr) {
1752 return false;
1753 }
1754 sp<Layer> relative = handle->owner.promote();
1755 if (relative == nullptr) {
1756 return false;
1757 }
1758
1759 mCurrentState.sequence++;
1760 mCurrentState.modified = true;
1761 mCurrentState.z = z;
1762
1763 mCurrentState.zOrderRelativeOf = relative;
1764 relative->addZOrderRelative(this);
1765
1766 setTransactionFlags(eTransactionNeeded);
1767
1768 return true;
1769}
1770
Mathias Agopian13127d82013-03-05 17:47:11 -08001771bool Layer::setSize(uint32_t w, uint32_t h) {
1772 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1773 return false;
1774 mCurrentState.requested.w = w;
1775 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001776 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001777 setTransactionFlags(eTransactionNeeded);
1778 return true;
1779}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001780#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001781bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001782#else
1783bool Layer::setAlpha(uint8_t alpha) {
1784#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001785 if (mCurrentState.alpha == alpha)
1786 return false;
1787 mCurrentState.sequence++;
1788 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001789 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001790 setTransactionFlags(eTransactionNeeded);
1791 return true;
1792}
1793bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1794 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001795 mCurrentState.requested.transform.set(
Robert Carrcb6e1e32017-02-21 19:48:26 -08001796 matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001797 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001798 setTransactionFlags(eTransactionNeeded);
1799 return true;
1800}
1801bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001802 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001803 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001804 setTransactionFlags(eTransactionNeeded);
1805 return true;
1806}
1807bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1808 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1809 if (mCurrentState.flags == newFlags)
1810 return false;
1811 mCurrentState.sequence++;
1812 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001813 mCurrentState.mask = mask;
1814 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001815 setTransactionFlags(eTransactionNeeded);
1816 return true;
1817}
Robert Carr99e27f02016-06-16 15:18:02 -07001818
1819bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001820 if (mCurrentState.crop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001821 return false;
1822 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001823 mCurrentState.requestedCrop = crop;
1824 if (immediate) {
1825 mCurrentState.crop = crop;
1826 }
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}
Robert Carr8d5227b2017-03-16 15:41:03 -07001831
1832bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001833 if (mCurrentState.finalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001834 return false;
1835 mCurrentState.sequence++;
Robert Carr8d5227b2017-03-16 15:41:03 -07001836 mCurrentState.requestedFinalCrop = crop;
1837 if (immediate) {
1838 mCurrentState.finalCrop = crop;
1839 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001840 mCurrentState.modified = true;
1841 setTransactionFlags(eTransactionNeeded);
1842 return true;
1843}
Mathias Agopian13127d82013-03-05 17:47:11 -08001844
Robert Carrc3574f72016-03-24 12:19:32 -07001845bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1846 if (scalingMode == mOverrideScalingMode)
1847 return false;
1848 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001849 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001850 return true;
1851}
1852
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001853void Layer::setInfo(uint32_t type, uint32_t appId) {
1854 mCurrentState.appId = appId;
1855 mCurrentState.type = type;
1856 mCurrentState.modified = true;
1857 setTransactionFlags(eTransactionNeeded);
1858}
1859
Robert Carrc3574f72016-03-24 12:19:32 -07001860uint32_t Layer::getEffectiveScalingMode() const {
1861 if (mOverrideScalingMode >= 0) {
1862 return mOverrideScalingMode;
1863 }
1864 return mCurrentScalingMode;
1865}
1866
Mathias Agopian13127d82013-03-05 17:47:11 -08001867bool Layer::setLayerStack(uint32_t layerStack) {
1868 if (mCurrentState.layerStack == layerStack)
1869 return false;
1870 mCurrentState.sequence++;
1871 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001872 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001873 setTransactionFlags(eTransactionNeeded);
1874 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001875}
1876
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07001877bool Layer::setDataSpace(android_dataspace dataSpace) {
1878 if (mCurrentState.dataSpace == dataSpace)
1879 return false;
1880 mCurrentState.sequence++;
1881 mCurrentState.dataSpace = dataSpace;
1882 mCurrentState.modified = true;
1883 setTransactionFlags(eTransactionNeeded);
1884 return true;
1885}
1886
Courtney Goeltzenleuchter532b2632017-05-05 16:34:38 -06001887android_dataspace Layer::getDataSpace() const {
1888 return mCurrentState.dataSpace;
1889}
1890
Robert Carr1f0a16a2016-10-24 16:27:39 -07001891uint32_t Layer::getLayerStack() const {
1892 auto p = getParent();
1893 if (p == nullptr) {
1894 return getDrawingState().layerStack;
1895 }
1896 return p->getLayerStack();
1897}
1898
Robert Carr0d480722017-01-10 16:42:54 -08001899void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
Dan Stoza7dde5992015-05-22 09:51:44 -07001900 uint64_t frameNumber) {
Robert Carr0d480722017-01-10 16:42:54 -08001901 mCurrentState.barrierLayer = barrierLayer;
Dan Stoza7dde5992015-05-22 09:51:44 -07001902 mCurrentState.frameNumber = frameNumber;
1903 // We don't set eTransactionNeeded, because just receiving a deferral
1904 // request without any other state updates shouldn't actually induce a delay
1905 mCurrentState.modified = true;
1906 pushPendingState();
Robert Carr0d480722017-01-10 16:42:54 -08001907 mCurrentState.barrierLayer = nullptr;
Dan Stoza792e5292016-02-11 11:43:58 -08001908 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07001909 mCurrentState.modified = false;
Robert Carr0d480722017-01-10 16:42:54 -08001910 ALOGE("Deferred transaction");
1911}
1912
1913void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
1914 uint64_t frameNumber) {
1915 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
1916 deferTransactionUntil(handle->owner.promote(), frameNumber);
Dan Stoza7dde5992015-05-22 09:51:44 -07001917}
1918
Dan Stozaee44edd2015-03-23 15:50:23 -07001919void Layer::useSurfaceDamage() {
1920 if (mFlinger->mForceFullDamage) {
1921 surfaceDamageRegion = Region::INVALID_REGION;
1922 } else {
1923 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1924 }
1925}
1926
1927void Layer::useEmptyDamage() {
1928 surfaceDamageRegion.clear();
1929}
1930
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001931// ----------------------------------------------------------------------------
1932// pageflip handling...
1933// ----------------------------------------------------------------------------
1934
Dan Stoza6b9454d2014-11-07 16:00:59 -08001935bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001936 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07001937 return true;
1938 }
1939
Dan Stoza6b9454d2014-11-07 16:00:59 -08001940 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001941 if (mQueueItems.empty()) {
1942 return false;
1943 }
1944 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001945 nsecs_t expectedPresent =
1946 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001947
1948 // Ignore timestamps more than a second in the future
1949 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1950 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1951 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1952 expectedPresent);
1953
1954 bool isDue = timestamp < expectedPresent;
1955 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001956}
1957
Brian Andersond6927fb2016-07-23 23:37:30 -07001958bool Layer::onPreComposition(nsecs_t refreshStartTime) {
1959 if (mBufferLatched) {
1960 Mutex::Autolock lock(mFrameEventHistoryMutex);
1961 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
1962 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08001963 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001964 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001965}
1966
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001967bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
Brian Anderson3d4039d2016-09-23 16:31:30 -07001968 const std::shared_ptr<FenceTime>& presentFence,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001969 const CompositorTiming& compositorTiming) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001970 mAcquireTimeline.updateSignalTimes();
1971 mReleaseTimeline.updateSignalTimes();
1972
Brian Andersond6927fb2016-07-23 23:37:30 -07001973 // mFrameLatencyNeeded is true when a new frame was latched for the
1974 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08001975 if (!mFrameLatencyNeeded)
1976 return false;
1977
Fabien Sanglard28e98082016-12-05 10:19:46 -08001978 // Update mFrameEventHistory.
1979 {
1980 Mutex::Autolock lock(mFrameEventHistoryMutex);
1981 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001982 glDoneFence, presentFence, compositorTiming);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001983 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08001984
1985 // Update mFrameTracker.
1986 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1987 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1988
Brian Anderson3d4039d2016-09-23 16:31:30 -07001989 std::shared_ptr<FenceTime> frameReadyFence =
1990 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08001991 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001992 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001993 } else {
1994 // There was no fence for this frame, so assume that it was ready
1995 // to be presented at the desired present time.
1996 mFrameTracker.setFrameReadyTime(desiredPresentTime);
1997 }
1998
Brian Anderson3d4039d2016-09-23 16:31:30 -07001999 if (presentFence->isValid()) {
2000 mFrameTracker.setActualPresentFence(
2001 std::shared_ptr<FenceTime>(presentFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002002 } else {
2003 // The HWC doesn't support present fences, so use the refresh
2004 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002005 mFrameTracker.setActualPresentTime(
2006 mFlinger->getHwComposer().getRefreshTimestamp(
2007 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002008 }
2009
2010 mFrameTracker.advanceFrame();
2011 mFrameLatencyNeeded = false;
2012 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002013}
2014
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002015#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07002016void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Brian Anderson5ea5e592016-12-01 16:54:33 -08002017 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2018 return;
2019 }
2020
Brian Anderson3d4039d2016-09-23 16:31:30 -07002021 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002022 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002023 mReleaseTimeline.push(releaseFenceTime);
2024
2025 Mutex::Autolock lock(mFrameEventHistoryMutex);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002026 if (mPreviousFrameNumber != 0) {
2027 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2028 dequeueReadyTime, std::move(releaseFenceTime));
2029 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002030}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002031#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002032
Robert Carr1f0a16a2016-10-24 16:27:39 -07002033bool Layer::isHiddenByPolicy() const {
2034 const Layer::State& s(mDrawingState);
2035 const auto& parent = getParent();
2036 if (parent != nullptr && parent->isHiddenByPolicy()) {
2037 return true;
2038 }
2039 return s.flags & layer_state_t::eLayerHidden;
2040}
2041
Mathias Agopianda27af92012-09-13 18:17:13 -07002042bool Layer::isVisible() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002043#ifdef USE_HWC2
Robert Carr6452f122017-03-21 10:41:29 -07002044 return !(isHiddenByPolicy()) && getAlpha() > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08002045 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002046#else
Robert Carr6452f122017-03-21 10:41:29 -07002047 return !(isHiddenByPolicy()) && getAlpha()
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002048 && (mActiveBuffer != NULL || mSidebandStream != NULL);
2049#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07002050}
2051
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002052bool Layer::allTransactionsSignaled() {
2053 auto headFrameNumber = getHeadFrameNumber();
2054 bool matchingFramesFound = false;
2055 bool allTransactionsApplied = true;
2056 Mutex::Autolock lock(mLocalSyncPointMutex);
2057
2058 for (auto& point : mLocalSyncPoints) {
2059 if (point->getFrameNumber() > headFrameNumber) {
2060 break;
2061 }
2062 matchingFramesFound = true;
2063
2064 if (!point->frameIsAvailable()) {
2065 // We haven't notified the remote layer that the frame for
2066 // this point is available yet. Notify it now, and then
2067 // abort this attempt to latch.
2068 point->setFrameAvailable();
2069 allTransactionsApplied = false;
2070 break;
2071 }
2072
2073 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2074 }
2075 return !matchingFramesFound || allTransactionsApplied;
2076}
2077
Brian Andersond6927fb2016-07-23 23:37:30 -07002078Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002079{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08002080 ATRACE_CALL();
2081
Jesse Hall399184a2014-03-03 15:42:54 -08002082 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2083 // mSidebandStreamChanged was true
2084 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07002085 if (mSidebandStream != NULL) {
2086 setTransactionFlags(eTransactionNeeded);
2087 mFlinger->setTransactionFlags(eTraversalNeeded);
2088 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07002089 recomputeVisibleRegions = true;
2090
2091 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07002092 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08002093 }
2094
Mathias Agopian4fec8732012-06-29 14:12:52 -07002095 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07002096 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2097 return outDirtyRegion;
2098 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002099
Fabien Sanglard223eb912016-10-13 10:15:06 -07002100 // if we've already called updateTexImage() without going through
2101 // a composition step, we have to skip this layer at this point
2102 // because we cannot call updateTeximage() without a corresponding
2103 // compositionComplete() call.
2104 // we'll trigger an update in onPreComposition().
2105 if (mRefreshPending) {
2106 return outDirtyRegion;
2107 }
2108
2109 // If the head buffer's acquire fence hasn't signaled yet, return and
2110 // try again later
2111 if (!headFenceHasSignaled()) {
2112 mFlinger->signalLayerUpdate();
2113 return outDirtyRegion;
2114 }
2115
2116 // Capture the old state of the layer for comparisons later
2117 const State& s(getDrawingState());
2118 const bool oldOpacity = isOpaque(s);
2119 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2120
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002121 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002122 mFlinger->signalLayerUpdate();
2123 return outDirtyRegion;
2124 }
2125
2126 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2127 // of the buffer queue isn't modified when the buffer queue is returning
2128 // BufferItem's that weren't actually queued. This can happen in shared
2129 // buffer mode.
2130 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002131 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2132 getProducerStickyTransform() != 0, mName.string(),
2133 mOverrideScalingMode, mFreezePositionUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002134 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2135 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2136 mLastFrameNumberReceived);
2137 if (updateResult == BufferQueue::PRESENT_LATER) {
2138 // Producer doesn't want buffer to be displayed yet. Signal a
2139 // layer update so we check again at the next opportunity.
2140 mFlinger->signalLayerUpdate();
2141 return outDirtyRegion;
2142 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2143 // If the buffer has been rejected, remove it from the shadow queue
2144 // and return early
2145 if (queuedBuffer) {
2146 Mutex::Autolock lock(mQueueItemLock);
2147 mQueueItems.removeAt(0);
2148 android_atomic_dec(&mQueuedFrames);
2149 }
2150 return outDirtyRegion;
2151 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2152 // This can occur if something goes wrong when trying to create the
2153 // EGLImage for this buffer. If this happens, the buffer has already
2154 // been released, so we need to clean up the queue and bug out
2155 // early.
2156 if (queuedBuffer) {
2157 Mutex::Autolock lock(mQueueItemLock);
2158 mQueueItems.clear();
2159 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002160 }
2161
Fabien Sanglard223eb912016-10-13 10:15:06 -07002162 // Once we have hit this state, the shadow queue may no longer
2163 // correctly reflect the incoming BufferQueue's contents, so even if
2164 // updateTexImage starts working, the only safe course of action is
2165 // to continue to ignore updates.
2166 mUpdateTexImageFailed = true;
2167
2168 return outDirtyRegion;
2169 }
2170
2171 if (queuedBuffer) {
2172 // Autolock scope
2173 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2174
2175 Mutex::Autolock lock(mQueueItemLock);
2176
2177 // Remove any stale buffers that have been dropped during
2178 // updateTexImage
2179 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2180 mQueueItems.removeAt(0);
2181 android_atomic_dec(&mQueuedFrames);
2182 }
2183
2184 mQueueItems.removeAt(0);
2185 }
2186
2187
2188 // Decrement the queued-frames count. Signal another event if we
2189 // have more frames pending.
2190 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2191 || mAutoRefresh) {
2192 mFlinger->signalLayerUpdate();
2193 }
2194
Fabien Sanglard223eb912016-10-13 10:15:06 -07002195 // update the active buffer
Chia-I Wu06d63de2017-01-04 14:58:51 +08002196 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2197 &mActiveBufferSlot);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002198 if (mActiveBuffer == NULL) {
2199 // this can only happen if the very first buffer was rejected.
2200 return outDirtyRegion;
2201 }
2202
Brian Andersond6927fb2016-07-23 23:37:30 -07002203 mBufferLatched = true;
2204 mPreviousFrameNumber = mCurrentFrameNumber;
2205 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2206
2207 {
2208 Mutex::Autolock lock(mFrameEventHistoryMutex);
2209 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2210#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002211 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002212 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002213 mReleaseTimeline.push(releaseFenceTime);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002214 if (mPreviousFrameNumber != 0) {
2215 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2216 latchTime, std::move(releaseFenceTime));
2217 }
Brian Andersond6927fb2016-07-23 23:37:30 -07002218#endif
2219 }
2220
Fabien Sanglard223eb912016-10-13 10:15:06 -07002221 mRefreshPending = true;
2222 mFrameLatencyNeeded = true;
2223 if (oldActiveBuffer == NULL) {
2224 // the first time we receive a buffer, we need to trigger a
2225 // geometry invalidation.
2226 recomputeVisibleRegions = true;
2227 }
2228
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002229 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2230
Fabien Sanglard223eb912016-10-13 10:15:06 -07002231 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2232 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2233 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2234 if ((crop != mCurrentCrop) ||
2235 (transform != mCurrentTransform) ||
2236 (scalingMode != mCurrentScalingMode))
2237 {
2238 mCurrentCrop = crop;
2239 mCurrentTransform = transform;
2240 mCurrentScalingMode = scalingMode;
2241 recomputeVisibleRegions = true;
2242 }
2243
2244 if (oldActiveBuffer != NULL) {
2245 uint32_t bufWidth = mActiveBuffer->getWidth();
2246 uint32_t bufHeight = mActiveBuffer->getHeight();
2247 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2248 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002249 recomputeVisibleRegions = true;
2250 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002251 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002252
Fabien Sanglard223eb912016-10-13 10:15:06 -07002253 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2254 if (oldOpacity != isOpaque(s)) {
2255 recomputeVisibleRegions = true;
2256 }
Dan Stozacac35382016-01-27 12:21:06 -08002257
Fabien Sanglard223eb912016-10-13 10:15:06 -07002258 // Remove any sync points corresponding to the buffer which was just
2259 // latched
2260 {
2261 Mutex::Autolock lock(mLocalSyncPointMutex);
2262 auto point = mLocalSyncPoints.begin();
2263 while (point != mLocalSyncPoints.end()) {
2264 if (!(*point)->frameIsAvailable() ||
2265 !(*point)->transactionIsApplied()) {
2266 // This sync point must have been added since we started
2267 // latching. Don't drop it yet.
2268 ++point;
2269 continue;
2270 }
2271
2272 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2273 point = mLocalSyncPoints.erase(point);
2274 } else {
2275 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002276 }
2277 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002278 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002279
2280 // FIXME: postedRegion should be dirty & bounds
2281 Region dirtyRegion(Rect(s.active.w, s.active.h));
2282
2283 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002284 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002285
Mathias Agopian4fec8732012-06-29 14:12:52 -07002286 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002287}
2288
Mathias Agopiana67932f2011-04-20 14:20:59 -07002289uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002290{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002291 // TODO: should we do something special if mSecure is set?
2292 if (mProtectedByApp) {
2293 // need a hardware-protected path to external video sink
2294 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002295 }
Riley Andrews03414a12014-07-01 14:22:59 -07002296 if (mPotentialCursor) {
2297 usage |= GraphicBuffer::USAGE_CURSOR;
2298 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002299 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002300 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002301}
2302
Mathias Agopian84300952012-11-21 16:02:13 -08002303void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002304 uint32_t orientation = 0;
2305 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002306 // The transform hint is used to improve performance, but we can
2307 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002308 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002309 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002310 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002311 if (orientation & Transform::ROT_INVALID) {
2312 orientation = 0;
2313 }
2314 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002315 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002316}
2317
Mathias Agopian13127d82013-03-05 17:47:11 -08002318// ----------------------------------------------------------------------------
2319// debugging
2320// ----------------------------------------------------------------------------
2321
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002322void Layer::dump(String8& result, Colorizer& colorizer) const
Mathias Agopian13127d82013-03-05 17:47:11 -08002323{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002324 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08002325
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002326 colorizer.colorize(result, Colorizer::GREEN);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002327 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002328 "+ %s %p (%s)\n",
2329 getTypeId(), this, getName().string());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002330 colorizer.reset(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002331
Mathias Agopian2ca79392013-04-02 18:30:32 -07002332 s.activeTransparentRegion.dump(result, "transparentRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002333 visibleRegion.dump(result, "visibleRegion");
Dan Stozaee44edd2015-03-23 15:50:23 -07002334 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002335 sp<Client> client(mClientRef.promote());
Courtney Goeltzenleuchter36c44dc2017-04-14 09:33:16 -06002336 PixelFormat pf = PIXEL_FORMAT_UNKNOWN;
2337 const sp<GraphicBuffer>& buffer(getActiveBuffer());
2338 if (buffer != NULL) {
2339 pf = buffer->getPixelFormat();
2340 }
Mathias Agopian13127d82013-03-05 17:47:11 -08002341
Mathias Agopian74d211a2013-04-22 16:55:35 +02002342 result.appendFormat( " "
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002343 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2344 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
Mathias Agopian13127d82013-03-05 17:47:11 -08002345 "isOpaque=%1d, invalidate=%1d, "
Courtney Goeltzenleuchter36c44dc2017-04-14 09:33:16 -06002346 "dataspace=%s, pixelformat=%s "
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002347#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08002348 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002349#else
2350 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2351#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08002352 " client=%p\n",
Robert Carr1f0a16a2016-10-24 16:27:39 -07002353 getLayerStack(), s.z,
2354 s.active.transform.tx(), s.active.transform.ty(),
2355 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07002356 s.crop.left, s.crop.top,
2357 s.crop.right, s.crop.bottom,
2358 s.finalCrop.left, s.finalCrop.top,
2359 s.finalCrop.right, s.finalCrop.bottom,
Andy McFadden4125a4f2014-01-29 17:17:11 -08002360 isOpaque(s), contentDirty,
Courtney Goeltzenleuchter36c44dc2017-04-14 09:33:16 -06002361 dataspaceDetails(getDataSpace()).c_str(), decodePixelFormat(pf).c_str(),
Mathias Agopian13127d82013-03-05 17:47:11 -08002362 s.alpha, s.flags,
Robert Carr3dcabfa2016-03-01 18:36:58 -08002363 s.active.transform[0][0], s.active.transform[0][1],
2364 s.active.transform[1][0], s.active.transform[1][1],
Mathias Agopian13127d82013-03-05 17:47:11 -08002365 client.get());
Mathias Agopian13127d82013-03-05 17:47:11 -08002366
2367 sp<const GraphicBuffer> buf0(mActiveBuffer);
2368 uint32_t w0=0, h0=0, s0=0, f0=0;
2369 if (buf0 != 0) {
2370 w0 = buf0->getWidth();
2371 h0 = buf0->getHeight();
2372 s0 = buf0->getStride();
2373 f0 = buf0->format;
2374 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02002375 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002376 " "
2377 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2378 " queued-frames=%d, mRefreshPending=%d\n",
2379 mFormat, w0, h0, s0,f0,
2380 mQueuedFrames, mRefreshPending);
2381
Mathias Agopian13127d82013-03-05 17:47:11 -08002382 if (mSurfaceFlingerConsumer != 0) {
Colin Cross3d1d2802016-09-26 18:10:16 -07002383 mSurfaceFlingerConsumer->dumpState(result, " ");
Mathias Agopian13127d82013-03-05 17:47:11 -08002384 }
2385}
2386
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002387#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002388void Layer::miniDumpHeader(String8& result) {
2389 result.append("----------------------------------------");
2390 result.append("---------------------------------------\n");
2391 result.append(" Layer name\n");
2392 result.append(" Z | ");
2393 result.append(" Comp Type | ");
2394 result.append(" Disp Frame (LTRB) | ");
2395 result.append(" Source Crop (LTRB)\n");
2396 result.append("----------------------------------------");
2397 result.append("---------------------------------------\n");
2398}
2399
2400void Layer::miniDump(String8& result, int32_t hwcId) const {
2401 if (mHwcLayers.count(hwcId) == 0) {
2402 return;
2403 }
2404
2405 String8 name;
2406 if (mName.length() > 77) {
2407 std::string shortened;
2408 shortened.append(mName.string(), 36);
2409 shortened.append("[...]");
2410 shortened.append(mName.string() + (mName.length() - 36), 36);
2411 name = shortened.c_str();
2412 } else {
2413 name = mName;
2414 }
2415
2416 result.appendFormat(" %s\n", name.string());
2417
2418 const Layer::State& layerState(getDrawingState());
2419 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2420 result.appendFormat(" %10u | ", layerState.z);
2421 result.appendFormat("%10s | ",
2422 to_string(getCompositionType(hwcId)).c_str());
2423 const Rect& frame = hwcInfo.displayFrame;
2424 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2425 frame.right, frame.bottom);
Dan Stoza5a423ea2017-02-16 14:10:39 -08002426 const FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002427 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2428 crop.right, crop.bottom);
2429
2430 result.append("- - - - - - - - - - - - - - - - - - - - ");
2431 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2432}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002433#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002434
Svetoslavd85084b2014-03-20 10:28:31 -07002435void Layer::dumpFrameStats(String8& result) const {
2436 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002437}
2438
Svetoslavd85084b2014-03-20 10:28:31 -07002439void Layer::clearFrameStats() {
2440 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002441}
2442
Jamie Gennis6547ff42013-07-16 20:12:42 -07002443void Layer::logFrameStats() {
2444 mFrameTracker.logAndResetStats(mName);
2445}
2446
Svetoslavd85084b2014-03-20 10:28:31 -07002447void Layer::getFrameStats(FrameStats* outStats) const {
2448 mFrameTracker.getStats(outStats);
2449}
2450
Brian Andersond6927fb2016-07-23 23:37:30 -07002451void Layer::dumpFrameEvents(String8& result) {
2452 result.appendFormat("- Layer %s (%s, %p)\n",
2453 getName().string(), getTypeId(), this);
2454 Mutex::Autolock lock(mFrameEventHistoryMutex);
2455 mFrameEventHistory.checkFencesForCompletion();
2456 mFrameEventHistory.dump(result);
2457}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002458
Brian Anderson5ea5e592016-12-01 16:54:33 -08002459void Layer::onDisconnect() {
2460 Mutex::Autolock lock(mFrameEventHistoryMutex);
2461 mFrameEventHistory.onDisconnect();
2462}
2463
Brian Anderson3890c392016-07-25 12:48:08 -07002464void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2465 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002466 Mutex::Autolock lock(mFrameEventHistoryMutex);
2467 if (newTimestamps) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002468 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002469 mFrameEventHistory.addQueue(*newTimestamps);
2470 }
2471
Brian Anderson3890c392016-07-25 12:48:08 -07002472 if (outDelta) {
2473 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002474 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002475}
Dan Stozae77c7662016-05-13 11:37:28 -07002476
2477std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2478 bool forceFlush) {
2479 std::vector<OccupancyTracker::Segment> history;
2480 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2481 &history);
2482 if (result != NO_ERROR) {
2483 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2484 result);
2485 return {};
2486 }
2487 return history;
2488}
2489
Robert Carr367c5682016-06-20 11:55:28 -07002490bool Layer::getTransformToDisplayInverse() const {
2491 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2492}
2493
Robert Carr1f0a16a2016-10-24 16:27:39 -07002494void Layer::addChild(const sp<Layer>& layer) {
2495 mCurrentChildren.add(layer);
2496 layer->setParent(this);
2497}
2498
2499ssize_t Layer::removeChild(const sp<Layer>& layer) {
2500 layer->setParent(nullptr);
2501 return mCurrentChildren.remove(layer);
2502}
2503
Robert Carr1db73f62016-12-21 12:58:51 -08002504bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2505 sp<Handle> handle = nullptr;
2506 sp<Layer> newParent = nullptr;
2507 if (newParentHandle == nullptr) {
2508 return false;
2509 }
2510 handle = static_cast<Handle*>(newParentHandle.get());
2511 newParent = handle->owner.promote();
2512 if (newParent == nullptr) {
2513 ALOGE("Unable to promote Layer handle");
2514 return false;
2515 }
2516
2517 for (const sp<Layer>& child : mCurrentChildren) {
2518 newParent->addChild(child);
2519
2520 sp<Client> client(child->mClientRef.promote());
2521 if (client != nullptr) {
2522 client->setParentLayer(newParent);
2523 }
2524 }
2525 mCurrentChildren.clear();
2526
2527 return true;
2528}
2529
Robert Carr9524cb32017-02-13 11:32:32 -08002530bool Layer::detachChildren() {
Dan Stoza412903f2017-04-27 13:42:17 -07002531 traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
Robert Carr9524cb32017-02-13 11:32:32 -08002532 if (child == this) {
2533 return;
2534 }
2535
2536 sp<Client> client(child->mClientRef.promote());
2537 if (client != nullptr) {
2538 client->detachLayer(child);
2539 }
2540 });
2541
2542 return true;
2543}
2544
Robert Carr1f0a16a2016-10-24 16:27:39 -07002545void Layer::setParent(const sp<Layer>& layer) {
2546 mParent = layer;
2547}
2548
2549void Layer::clearSyncPoints() {
2550 for (const auto& child : mCurrentChildren) {
2551 child->clearSyncPoints();
2552 }
2553
2554 Mutex::Autolock lock(mLocalSyncPointMutex);
2555 for (auto& point : mLocalSyncPoints) {
2556 point->setFrameAvailable();
2557 }
2558 mLocalSyncPoints.clear();
2559}
2560
2561int32_t Layer::getZ() const {
2562 return mDrawingState.z;
2563}
2564
Dan Stoza412903f2017-04-27 13:42:17 -07002565LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2566 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2567 "makeTraversalList received invalid stateSet");
2568 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2569 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2570 const State& state = useDrawing ? mDrawingState : mCurrentState;
2571
2572 if (state.zOrderRelatives.size() == 0) {
2573 return children;
Robert Carrdb66e622017-04-10 16:55:57 -07002574 }
2575 LayerVector traverse;
2576
Dan Stoza412903f2017-04-27 13:42:17 -07002577 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07002578 sp<Layer> strongRelative = weakRelative.promote();
2579 if (strongRelative != nullptr) {
2580 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07002581 }
2582 }
2583
Dan Stoza412903f2017-04-27 13:42:17 -07002584 for (const sp<Layer>& child : children) {
Robert Carrdb66e622017-04-10 16:55:57 -07002585 traverse.add(child);
2586 }
2587
2588 return traverse;
2589}
2590
Robert Carr1f0a16a2016-10-24 16:27:39 -07002591/**
Robert Carrdb66e622017-04-10 16:55:57 -07002592 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002593 */
Dan Stoza412903f2017-04-27 13:42:17 -07002594void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2595 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002596
Robert Carr1f0a16a2016-10-24 16:27:39 -07002597 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002598 for (; i < list.size(); i++) {
2599 const auto& relative = list[i];
2600 if (relative->getZ() >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002601 break;
Robert Carrdb66e622017-04-10 16:55:57 -07002602 }
Dan Stoza412903f2017-04-27 13:42:17 -07002603 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002604 }
Dan Stoza412903f2017-04-27 13:42:17 -07002605 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07002606 for (; i < list.size(); i++) {
2607 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002608 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002609 }
2610}
2611
2612/**
Robert Carrdb66e622017-04-10 16:55:57 -07002613 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002614 */
Dan Stoza412903f2017-04-27 13:42:17 -07002615void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2616 const LayerVector::Visitor& visitor) {
2617 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002618
Robert Carr1f0a16a2016-10-24 16:27:39 -07002619 int32_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002620 for (i = list.size()-1; i>=0; i--) {
2621 const auto& relative = list[i];
2622 if (relative->getZ() < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002623 break;
2624 }
Dan Stoza412903f2017-04-27 13:42:17 -07002625 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002626 }
Dan Stoza412903f2017-04-27 13:42:17 -07002627 visitor(this);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002628 for (; i>=0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002629 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002630 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002631 }
2632}
2633
2634Transform Layer::getTransform() const {
2635 Transform t;
2636 const auto& p = getParent();
2637 if (p != nullptr) {
2638 t = p->getTransform();
Robert Carr9b429f42017-04-17 14:56:57 -07002639
2640 // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2641 // it isFixedSize) then there may be additional scaling not accounted
2642 // for in the transform. We need to mirror this scaling in child surfaces
2643 // or we will break the contract where WM can treat child surfaces as
2644 // pixels in the parent surface.
2645 if (p->isFixedSize()) {
Robert Carr1725eee2017-04-26 18:32:15 -07002646 int bufferWidth;
2647 int bufferHeight;
2648 if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2649 bufferWidth = p->mActiveBuffer->getWidth();
2650 bufferHeight = p->mActiveBuffer->getHeight();
2651 } else {
2652 bufferHeight = p->mActiveBuffer->getWidth();
2653 bufferWidth = p->mActiveBuffer->getHeight();
2654 }
Robert Carr9b429f42017-04-17 14:56:57 -07002655 float sx = p->getDrawingState().active.w /
Robert Carr1725eee2017-04-26 18:32:15 -07002656 static_cast<float>(bufferWidth);
Robert Carr9b429f42017-04-17 14:56:57 -07002657 float sy = p->getDrawingState().active.h /
Robert Carr1725eee2017-04-26 18:32:15 -07002658 static_cast<float>(bufferHeight);
Robert Carr9b429f42017-04-17 14:56:57 -07002659 Transform extraParentScaling;
2660 extraParentScaling.set(sx, 0, 0, sy);
2661 t = t * extraParentScaling;
2662 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002663 }
2664 return t * getDrawingState().active.transform;
2665}
2666
Robert Carr6452f122017-03-21 10:41:29 -07002667#ifdef USE_HWC2
2668float Layer::getAlpha() const {
2669 const auto& p = getParent();
2670
2671 float parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0;
2672 return parentAlpha * getDrawingState().alpha;
2673}
2674#else
2675uint8_t Layer::getAlpha() const {
2676 const auto& p = getParent();
2677
2678 float parentAlpha = (p != nullptr) ? (p->getAlpha() / 255.0f) : 1.0;
2679 float drawingAlpha = getDrawingState().alpha / 255.0f;
2680 drawingAlpha = drawingAlpha * parentAlpha;
2681 return static_cast<uint8_t>(std::round(drawingAlpha * 255));
2682}
2683#endif
2684
Robert Carr1f0a16a2016-10-24 16:27:39 -07002685void Layer::commitChildList() {
2686 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2687 const auto& child = mCurrentChildren[i];
2688 child->commitChildList();
2689 }
2690 mDrawingChildren = mCurrentChildren;
2691}
2692
Mathias Agopian13127d82013-03-05 17:47:11 -08002693// ---------------------------------------------------------------------------
2694
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002695}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002696
2697#if defined(__gl_h_)
2698#error "don't include gl/gl.h in this file"
2699#endif
2700
2701#if defined(__gl2_h_)
2702#error "don't include gl2/gl2.h in this file"
2703#endif