blob: 5f4856b59c71daff43ef8fab519df72b0b95db9e [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
877android_dataspace Layer::getDataSpace() const {
878 return mCurrentState.dataSpace;
879}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000880#else
881void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
882 HWComposer::HWCLayerInterface& layer) {
883 // we have to set the visible region on every frame because
884 // we currently free it during onLayerDisplayed(), which is called
885 // after HWComposer::commit() -- every frame.
886 // Apply this display's projection's viewport to the visible region
887 // before giving it to the HWC HAL.
888 const Transform& tr = hw->getTransform();
889 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
890 layer.setVisibleRegionScreen(visible);
891 layer.setSurfaceDamage(surfaceDamageRegion);
892 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700893
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000894 if (mSidebandStream.get()) {
895 layer.setSidebandStream(mSidebandStream);
896 } else {
897 // NOTE: buffer can be NULL if the client never drew into this
898 // layer yet, or if we ran out of memory
899 layer.setBuffer(mActiveBuffer);
900 }
901}
902#endif
903
904#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800905void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
906 auto hwcId = displayDevice->getHwcDisplayId();
907 if (mHwcLayers.count(hwcId) == 0 ||
908 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
909 return;
910 }
911
912 // This gives us only the "orientation" component of the transform
913 const State& s(getCurrentState());
914
915 // Apply the layer's transform, followed by the display's global transform
916 // Here we're guaranteed that the layer's transform preserves rects
917 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700918 if (!s.crop.isEmpty()) {
919 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800920 }
921 // Subtract the transparent region and snap to the bounds
922 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700923 Rect frame(getTransform().transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800924 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -0700925 if (!s.finalCrop.isEmpty()) {
926 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000927 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800928 auto& displayTransform(displayDevice->getTransform());
929 auto position = displayTransform.transform(frame);
930
931 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
932 position.top);
933 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
934 "to (%d, %d): %s (%d)", mName.string(), position.left,
935 position.top, to_string(error).c_str(),
936 static_cast<int32_t>(error));
937}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000938#else
939void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
940 HWComposer::HWCLayerInterface& layer) {
941 int fenceFd = -1;
942
943 // TODO: there is a possible optimization here: we only need to set the
944 // acquire fence the first time a new buffer is acquired on EACH display.
945
946 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
947 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
948 if (fence->isValid()) {
949 fenceFd = fence->dup();
950 if (fenceFd == -1) {
951 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
952 }
953 }
954 }
955 layer.setAcquireFenceFd(fenceFd);
956}
957
958Rect Layer::getPosition(
959 const sp<const DisplayDevice>& hw)
960{
961 // this gives us only the "orientation" component of the transform
962 const State& s(getCurrentState());
963
964 // apply the layer's transform, followed by the display's global transform
965 // here we're guaranteed that the layer's transform preserves rects
966 Rect win(s.active.w, s.active.h);
967 if (!s.crop.isEmpty()) {
968 win.intersect(s.crop, &win);
969 }
970 // subtract the transparent region and snap to the bounds
971 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700972 Rect frame(getTransform().transform(bounds));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000973 frame.intersect(hw->getViewport(), &frame);
974 if (!s.finalCrop.isEmpty()) {
975 frame.intersect(s.finalCrop, &frame);
976 }
977 const Transform& tr(hw->getTransform());
978 return Rect(tr.transform(frame));
979}
980#endif
Riley Andrews03414a12014-07-01 14:22:59 -0700981
Mathias Agopian13127d82013-03-05 17:47:11 -0800982// ---------------------------------------------------------------------------
983// drawing...
984// ---------------------------------------------------------------------------
985
986void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -0800987 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -0800988}
989
Dan Stozac7014012014-02-14 15:03:43 -0800990void Layer::draw(const sp<const DisplayDevice>& hw,
991 bool useIdentityTransform) const {
992 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -0800993}
994
Dan Stozac7014012014-02-14 15:03:43 -0800995void Layer::draw(const sp<const DisplayDevice>& hw) const {
996 onDraw(hw, Region(hw->bounds()), false);
997}
998
Robert Carrcae605c2017-03-29 12:10:31 -0700999static constexpr mat4 inverseOrientation(uint32_t transform) {
1000 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1001 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1002 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1003 mat4 tr;
1004
1005 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1006 tr = tr * rot90;
1007 }
1008 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1009 tr = tr * flipH;
1010 }
1011 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1012 tr = tr * flipV;
1013 }
1014 return inverse(tr);
1015}
1016
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001017/*
1018 * onDraw will draw the current layer onto the presentable buffer
1019 */
Dan Stozac7014012014-02-14 15:03:43 -08001020void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
1021 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001022{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001023 ATRACE_CALL();
1024
Mathias Agopiana67932f2011-04-20 14:20:59 -07001025 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001026 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -07001027 // in fact never been drawn into. This happens frequently with
1028 // SurfaceView because the WindowManager can't know when the client
1029 // has drawn the first time.
1030
1031 // If there is nothing under us, we paint the screen in black, otherwise
1032 // we just skip this update.
1033
1034 // figure out if there is something below us
1035 Region under;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001036 bool finished = false;
Dan Stoza412903f2017-04-27 13:42:17 -07001037 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001038 if (finished || layer == static_cast<Layer const*>(this)) {
1039 finished = true;
1040 return;
1041 }
Mathias Agopian42977342012-08-05 00:40:46 -07001042 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Robert Carr1f0a16a2016-10-24 16:27:39 -07001043 });
Mathias Agopian179169e2010-05-06 20:21:45 -07001044 // if not everything below us is covered, we plug the holes!
1045 Region holes(clip.subtract(under));
1046 if (!holes.isEmpty()) {
Fabien Sanglard17487192016-12-07 13:03:32 -08001047 clearWithOpenGL(hw, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -07001048 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001049 return;
1050 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001051
Andy McFadden97eba892012-12-11 15:21:45 -08001052 // Bind the current buffer to the GL texture, and wait for it to be
1053 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001054 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1055 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -08001056 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -07001057 // Go ahead and draw the buffer anyway; no matter what we do the screen
1058 // is probably going to have something visibly wrong.
1059 }
1060
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001061 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1062
Mathias Agopian875d8e12013-06-07 15:35:48 -07001063 RenderEngine& engine(mFlinger->getRenderEngine());
1064
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001065 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -07001066 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -07001067 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -07001068
1069 // Query the texture matrix given our current filtering mode.
1070 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001071 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1072 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -07001073
Robert Carrcae605c2017-03-29 12:10:31 -07001074 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001075
1076 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -07001077 * the code below applies the primary display's inverse transform to
1078 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001079 */
Pablo Ceballos021623b2016-04-15 17:31:51 -07001080 uint32_t transform =
1081 DisplayDevice::getPrimaryDisplayOrientationTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001082 mat4 tr = inverseOrientation(transform);
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001083
Robert Carrcae605c2017-03-29 12:10:31 -07001084 /**
1085 * TODO(b/36727915): This is basically a hack.
1086 *
1087 * Ensure that regardless of the parent transformation,
1088 * this buffer is always transformed from native display
1089 * orientation to display orientation. For example, in the case
1090 * of a camera where the buffer remains in native orientation,
1091 * we want the pixels to always be upright.
1092 */
1093 if (getParent() != nullptr) {
1094 const auto parentTransform = getParent()->getTransform();
1095 tr = tr * inverseOrientation(parentTransform.getOrientation());
1096 }
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001097
1098 // and finally apply it to the original texture matrix
1099 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1100 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1101 }
1102
Jamie Genniscbb1a952012-05-08 17:05:52 -07001103 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -07001104 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1105 mTexture.setFiltering(useFiltering);
1106 mTexture.setMatrix(textureMatrix);
1107
1108 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -07001109 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001110 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -07001111 }
Fabien Sanglard85789802016-12-07 13:08:24 -08001112 drawWithOpenGL(hw, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001113 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001114}
1115
Mathias Agopian13127d82013-03-05 17:47:11 -08001116
Dan Stozac7014012014-02-14 15:03:43 -08001117void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard17487192016-12-07 13:03:32 -08001118 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -08001119 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001120{
Mathias Agopian19733a32013-08-28 18:13:56 -07001121 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -08001122 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -07001123 engine.setupFillWithColor(red, green, blue, alpha);
1124 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -08001125}
1126
1127void Layer::clearWithOpenGL(
Fabien Sanglard17487192016-12-07 13:03:32 -08001128 const sp<const DisplayDevice>& hw) const {
1129 clearWithOpenGL(hw, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001130}
1131
Dan Stozac7014012014-02-14 15:03:43 -08001132void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard85789802016-12-07 13:08:24 -08001133 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001134 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001135
Dan Stozac7014012014-02-14 15:03:43 -08001136 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001137
Mathias Agopian13127d82013-03-05 17:47:11 -08001138 /*
1139 * NOTE: the way we compute the texture coordinates here produces
1140 * different results than when we take the HWC path -- in the later case
1141 * the "source crop" is rounded to texel boundaries.
1142 * This can produce significantly different results when the texture
1143 * is scaled by a large amount.
1144 *
1145 * The GL code below is more logical (imho), and the difference with
1146 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001147 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001148 * GL composition when a buffer scaling is applied (maybe with some
1149 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1150 * like more of a hack.
1151 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001152 Rect win(computeBounds());
1153
Robert Carr1f0a16a2016-10-24 16:27:39 -07001154 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -07001155 if (!s.finalCrop.isEmpty()) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001156 win = t.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001157 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001158 win.clear();
1159 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001160 win = t.inverse().transform(win);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001161 if (!win.intersect(computeBounds(), &win)) {
1162 win.clear();
1163 }
1164 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001165
Mathias Agopian3f844832013-08-07 21:24:32 -07001166 float left = float(win.left) / float(s.active.w);
1167 float top = float(win.top) / float(s.active.h);
1168 float right = float(win.right) / float(s.active.w);
1169 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001170
Mathias Agopian875d8e12013-06-07 15:35:48 -07001171 // TODO: we probably want to generate the texture coords with the mesh
1172 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001173 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1174 texCoords[0] = vec2(left, 1.0f - top);
1175 texCoords[1] = vec2(left, 1.0f - bottom);
1176 texCoords[2] = vec2(right, 1.0f - bottom);
1177 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001178
Mathias Agopian875d8e12013-06-07 15:35:48 -07001179 RenderEngine& engine(mFlinger->getRenderEngine());
Robert Carr6452f122017-03-21 10:41:29 -07001180 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), getAlpha());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001181#ifdef USE_HWC2
1182 engine.setSourceDataSpace(mCurrentState.dataSpace);
1183#endif
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001184 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001185 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001186}
1187
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001188#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001189void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1190 bool callIntoHwc) {
1191 if (mHwcLayers.count(hwcId) == 0) {
1192 ALOGE("setCompositionType called without a valid HWC layer");
1193 return;
1194 }
1195 auto& hwcInfo = mHwcLayers[hwcId];
1196 auto& hwcLayer = hwcInfo.layer;
1197 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1198 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1199 if (hwcInfo.compositionType != type) {
1200 ALOGV(" actually setting");
1201 hwcInfo.compositionType = type;
1202 if (callIntoHwc) {
1203 auto error = hwcLayer->setCompositionType(type);
1204 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1205 "composition type %s: %s (%d)", mName.string(),
1206 to_string(type).c_str(), to_string(error).c_str(),
1207 static_cast<int32_t>(error));
1208 }
1209 }
1210}
1211
1212HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001213 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1214 // If we're querying the composition type for a display that does not
1215 // have a HWC counterpart, then it will always be Client
1216 return HWC2::Composition::Client;
1217 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001218 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001219 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001220 return HWC2::Composition::Invalid;
1221 }
1222 return mHwcLayers.at(hwcId).compositionType;
1223}
1224
1225void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1226 if (mHwcLayers.count(hwcId) == 0) {
1227 ALOGE("setClearClientTarget called without a valid HWC layer");
1228 return;
1229 }
1230 mHwcLayers[hwcId].clearClientTarget = clear;
1231}
1232
1233bool Layer::getClearClientTarget(int32_t hwcId) const {
1234 if (mHwcLayers.count(hwcId) == 0) {
1235 ALOGE("getClearClientTarget called without a valid HWC layer");
1236 return false;
1237 }
1238 return mHwcLayers.at(hwcId).clearClientTarget;
1239}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001240#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001241
Ruben Brunk1681d952014-06-27 15:51:55 -07001242uint32_t Layer::getProducerStickyTransform() const {
1243 int producerStickyTransform = 0;
1244 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1245 if (ret != OK) {
1246 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1247 strerror(-ret), ret);
1248 return 0;
1249 }
1250 return static_cast<uint32_t>(producerStickyTransform);
1251}
1252
Dan Stozac5da2712016-07-20 15:38:12 -07001253bool Layer::latchUnsignaledBuffers() {
1254 static bool propertyLoaded = false;
1255 static bool latch = false;
1256 static std::mutex mutex;
1257 std::lock_guard<std::mutex> lock(mutex);
1258 if (!propertyLoaded) {
1259 char value[PROPERTY_VALUE_MAX] = {};
1260 property_get("debug.sf.latch_unsignaled", value, "0");
1261 latch = atoi(value);
1262 propertyLoaded = true;
1263 }
1264 return latch;
1265}
1266
Dan Stozacac35382016-01-27 12:21:06 -08001267uint64_t Layer::getHeadFrameNumber() const {
1268 Mutex::Autolock lock(mQueueItemLock);
1269 if (!mQueueItems.empty()) {
1270 return mQueueItems[0].mFrameNumber;
1271 } else {
1272 return mCurrentFrameNumber;
1273 }
1274}
1275
Dan Stoza1ce65812016-06-15 16:26:27 -07001276bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001277#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001278 if (latchUnsignaledBuffers()) {
1279 return true;
1280 }
1281
Dan Stoza1ce65812016-06-15 16:26:27 -07001282 Mutex::Autolock lock(mQueueItemLock);
1283 if (mQueueItems.empty()) {
1284 return true;
1285 }
1286 if (mQueueItems[0].mIsDroppable) {
1287 // Even though this buffer's fence may not have signaled yet, it could
1288 // be replaced by another buffer before it has a chance to, which means
1289 // that it's possible to get into a situation where a buffer is never
1290 // able to be latched. To avoid this, grab this buffer anyway.
1291 return true;
1292 }
1293 return mQueueItems[0].mFence->getSignalTime() != INT64_MAX;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001294#else
1295 return true;
1296#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001297}
1298
Dan Stozacac35382016-01-27 12:21:06 -08001299bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1300 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1301 // Don't bother with a SyncPoint, since we've already latched the
1302 // relevant frame
1303 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001304 }
1305
Dan Stozacac35382016-01-27 12:21:06 -08001306 Mutex::Autolock lock(mLocalSyncPointMutex);
1307 mLocalSyncPoints.push_back(point);
1308 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001309}
1310
Mathias Agopian13127d82013-03-05 17:47:11 -08001311void Layer::setFiltering(bool filtering) {
1312 mFiltering = filtering;
1313}
1314
1315bool Layer::getFiltering() const {
1316 return mFiltering;
1317}
1318
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001319// As documented in libhardware header, formats in the range
1320// 0x100 - 0x1FF are specific to the HAL implementation, and
1321// are known to have no alpha channel
1322// TODO: move definition for device-specific range into
1323// hardware.h, instead of using hard-coded values here.
1324#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1325
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001326bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001327 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1328 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001329 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001330 switch (format) {
1331 case HAL_PIXEL_FORMAT_RGBA_8888:
1332 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001333 case HAL_PIXEL_FORMAT_RGBA_FP16:
Romain Guy541f2262017-02-10 18:50:17 -08001334 case HAL_PIXEL_FORMAT_RGBA_1010102:
Mathias Agopiandd533712013-07-26 15:31:39 -07001335 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001336 }
1337 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001338 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001339}
1340
Mathias Agopian13127d82013-03-05 17:47:11 -08001341// ----------------------------------------------------------------------------
1342// local state
1343// ----------------------------------------------------------------------------
1344
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001345static void boundPoint(vec2* point, const Rect& crop) {
1346 if (point->x < crop.left) {
1347 point->x = crop.left;
1348 }
1349 if (point->x > crop.right) {
1350 point->x = crop.right;
1351 }
1352 if (point->y < crop.top) {
1353 point->y = crop.top;
1354 }
1355 if (point->y > crop.bottom) {
1356 point->y = crop.bottom;
1357 }
1358}
1359
Dan Stozac7014012014-02-14 15:03:43 -08001360void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1361 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001362{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001363 const Layer::State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001364 const Transform hwTransform(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001365 const uint32_t hw_h = hw->getHeight();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001366 Rect win = computeBounds();
Mathias Agopian3f844832013-08-07 21:24:32 -07001367
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001368 vec2 lt = vec2(win.left, win.top);
1369 vec2 lb = vec2(win.left, win.bottom);
1370 vec2 rb = vec2(win.right, win.bottom);
1371 vec2 rt = vec2(win.right, win.top);
1372
Robert Carr1f0a16a2016-10-24 16:27:39 -07001373 Transform layerTransform = getTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001374 if (!useIdentityTransform) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001375 lt = layerTransform.transform(lt);
1376 lb = layerTransform.transform(lb);
1377 rb = layerTransform.transform(rb);
1378 rt = layerTransform.transform(rt);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001379 }
1380
Robert Carrb5d3d262016-03-25 15:08:13 -07001381 if (!s.finalCrop.isEmpty()) {
1382 boundPoint(&lt, s.finalCrop);
1383 boundPoint(&lb, s.finalCrop);
1384 boundPoint(&rb, s.finalCrop);
1385 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001386 }
1387
Mathias Agopianff2ed702013-09-01 21:36:12 -07001388 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001389 position[0] = hwTransform.transform(lt);
1390 position[1] = hwTransform.transform(lb);
1391 position[2] = hwTransform.transform(rb);
1392 position[3] = hwTransform.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001393 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001394 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001395 }
1396}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001397
Andy McFadden4125a4f2014-01-29 17:17:11 -08001398bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001399{
neo.hee6fd41d2017-02-17 14:35:33 +08001400 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
Mathias Agopiana67932f2011-04-20 14:20:59 -07001401 // layer's opaque flag.
neo.hee6fd41d2017-02-17 14:35:33 +08001402 if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001403 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001404 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001405
1406 // if the layer has the opaque flag, then we're always opaque,
1407 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001408 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001409}
1410
Dan Stoza23116082015-06-18 14:58:39 -07001411bool Layer::isSecure() const
1412{
1413 const Layer::State& s(mDrawingState);
1414 return (s.flags & layer_state_t::eLayerSecure);
1415}
1416
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001417bool Layer::isProtected() const
1418{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001419 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001420 return (activeBuffer != 0) &&
1421 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1422}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001423
Mathias Agopian13127d82013-03-05 17:47:11 -08001424bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001425 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001426}
1427
1428bool Layer::isCropped() const {
1429 return !mCurrentCrop.isEmpty();
1430}
1431
1432bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1433 return mNeedsFiltering || hw->needsFiltering();
1434}
1435
1436void Layer::setVisibleRegion(const Region& visibleRegion) {
1437 // always called from main thread
1438 this->visibleRegion = visibleRegion;
1439}
1440
1441void Layer::setCoveredRegion(const Region& coveredRegion) {
1442 // always called from main thread
1443 this->coveredRegion = coveredRegion;
1444}
1445
1446void Layer::setVisibleNonTransparentRegion(const Region&
1447 setVisibleNonTransparentRegion) {
1448 // always called from main thread
1449 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1450}
1451
1452// ----------------------------------------------------------------------------
1453// transaction
1454// ----------------------------------------------------------------------------
1455
Dan Stoza7dde5992015-05-22 09:51:44 -07001456void Layer::pushPendingState() {
1457 if (!mCurrentState.modified) {
1458 return;
1459 }
1460
Dan Stoza7dde5992015-05-22 09:51:44 -07001461 // If this transaction is waiting on the receipt of a frame, generate a sync
1462 // point and send it to the remote layer.
Robert Carr0d480722017-01-10 16:42:54 -08001463 if (mCurrentState.barrierLayer != nullptr) {
1464 sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1465 if (barrierLayer == nullptr) {
1466 ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
Dan Stoza7dde5992015-05-22 09:51:44 -07001467 // If we can't promote the layer we are intended to wait on,
1468 // then it is expired or otherwise invalid. Allow this transaction
1469 // to be applied as per normal (no synchronization).
Robert Carr0d480722017-01-10 16:42:54 -08001470 mCurrentState.barrierLayer = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001471 } else {
1472 auto syncPoint = std::make_shared<SyncPoint>(
1473 mCurrentState.frameNumber);
Robert Carr0d480722017-01-10 16:42:54 -08001474 if (barrierLayer->addSyncPoint(syncPoint)) {
Dan Stozacac35382016-01-27 12:21:06 -08001475 mRemoteSyncPoints.push_back(std::move(syncPoint));
1476 } else {
1477 // We already missed the frame we're supposed to synchronize
1478 // on, so go ahead and apply the state update
Robert Carr0d480722017-01-10 16:42:54 -08001479 mCurrentState.barrierLayer = nullptr;
Dan Stozacac35382016-01-27 12:21:06 -08001480 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001481 }
1482
Dan Stoza7dde5992015-05-22 09:51:44 -07001483 // Wake us up to check if the frame has been received
1484 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001485 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001486 }
1487 mPendingStates.push_back(mCurrentState);
1488}
1489
Pablo Ceballos05289c22016-04-14 15:49:55 -07001490void Layer::popPendingState(State* stateToCommit) {
1491 auto oldFlags = stateToCommit->flags;
1492 *stateToCommit = mPendingStates[0];
1493 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1494 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001495
1496 mPendingStates.removeAt(0);
1497}
1498
Pablo Ceballos05289c22016-04-14 15:49:55 -07001499bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001500 bool stateUpdateAvailable = false;
1501 while (!mPendingStates.empty()) {
Robert Carr0d480722017-01-10 16:42:54 -08001502 if (mPendingStates[0].barrierLayer != nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001503 if (mRemoteSyncPoints.empty()) {
1504 // If we don't have a sync point for this, apply it anyway. It
1505 // will be visually wrong, but it should keep us from getting
1506 // into too much trouble.
1507 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001508 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001509 stateUpdateAvailable = true;
1510 continue;
1511 }
1512
Dan Stozacac35382016-01-27 12:21:06 -08001513 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1514 mPendingStates[0].frameNumber) {
1515 ALOGE("[%s] Unexpected sync point frame number found",
1516 mName.string());
1517
1518 // Signal our end of the sync point and then dispose of it
1519 mRemoteSyncPoints.front()->setTransactionApplied();
1520 mRemoteSyncPoints.pop_front();
1521 continue;
1522 }
1523
Dan Stoza7dde5992015-05-22 09:51:44 -07001524 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1525 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001526 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001527 stateUpdateAvailable = true;
1528
1529 // Signal our end of the sync point and then dispose of it
1530 mRemoteSyncPoints.front()->setTransactionApplied();
1531 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001532 } else {
1533 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001534 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001535 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001536 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001537 stateUpdateAvailable = true;
1538 }
1539 }
1540
1541 // If we still have pending updates, wake SurfaceFlinger back up and point
1542 // it at this layer so we can process them
1543 if (!mPendingStates.empty()) {
1544 setTransactionFlags(eTransactionNeeded);
1545 mFlinger->setTransactionFlags(eTraversalNeeded);
1546 }
1547
1548 mCurrentState.modified = false;
1549 return stateUpdateAvailable;
1550}
1551
1552void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001553 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001554 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001555 Mutex::Autolock lock(mLocalSyncPointMutex);
1556 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001557 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001558 point->setFrameAvailable();
1559 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001560 }
1561}
1562
Mathias Agopian13127d82013-03-05 17:47:11 -08001563uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001564 ATRACE_CALL();
1565
Dan Stoza7dde5992015-05-22 09:51:44 -07001566 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001567 Layer::State c = getCurrentState();
1568 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001569 return 0;
1570 }
1571
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001572 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001573
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001574 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1575 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001576
1577 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001578 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001579 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001580 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001581 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001582 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001583 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001584 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001585 this, getName().string(), mCurrentTransform,
1586 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001587 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001588 c.crop.left,
1589 c.crop.top,
1590 c.crop.right,
1591 c.crop.bottom,
1592 c.crop.getWidth(),
1593 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001594 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001595 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001596 s.crop.left,
1597 s.crop.top,
1598 s.crop.right,
1599 s.crop.bottom,
1600 s.crop.getWidth(),
1601 s.crop.getHeight(),
1602 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001603
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001604 // record the new size, form this point on, when the client request
1605 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001606 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001607 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001608 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001609
Robert Carr82364e32016-05-15 11:27:47 -07001610 const bool resizePending = (c.requested.w != c.active.w) ||
1611 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001612 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001613 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001614 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001615 // if we have a pending resize, unless we are in fixed-size mode.
1616 // the drawing state will be updated only once we receive a buffer
1617 // with the correct size.
1618 //
1619 // in particular, we want to make sure the clip (which is part
1620 // of the geometry state) is latched together with the size but is
1621 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001622 //
1623 // If a sideband stream is attached, however, we want to skip this
1624 // optimization so that transactions aren't missed when a buffer
1625 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001626
1627 flags |= eDontUpdateGeometryState;
1628 }
1629 }
1630
Mathias Agopian13127d82013-03-05 17:47:11 -08001631 // always set active to requested, unless we're asked not to
1632 // this is used by Layer, which special cases resizes.
1633 if (flags & eDontUpdateGeometryState) {
1634 } else {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001635 Layer::State& editCurrentState(getCurrentState());
Robert Carr82364e32016-05-15 11:27:47 -07001636 if (mFreezePositionUpdates) {
1637 float tx = c.active.transform.tx();
1638 float ty = c.active.transform.ty();
1639 c.active = c.requested;
1640 c.active.transform.set(tx, ty);
1641 editCurrentState.active = c.active;
1642 } else {
1643 editCurrentState.active = editCurrentState.requested;
1644 c.active = c.requested;
1645 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001646 }
1647
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001648 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001649 // invalidate and recompute the visible regions if needed
1650 flags |= Layer::eVisibleRegion;
1651 }
1652
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001653 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001654 // invalidate and recompute the visible regions if needed
1655 flags |= eVisibleRegion;
1656 this->contentDirty = true;
1657
1658 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001659 const uint8_t type = c.active.transform.getType();
1660 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001661 (type >= Transform::SCALE));
1662 }
1663
Dan Stozac8145172016-04-28 16:29:06 -07001664 // If the layer is hidden, signal and clear out all local sync points so
1665 // that transactions for layers depending on this layer's frames becoming
1666 // visible are not blocked
1667 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001668 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001669 }
1670
Mathias Agopian13127d82013-03-05 17:47:11 -08001671 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001672 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001673 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001674}
1675
Pablo Ceballos05289c22016-04-14 15:49:55 -07001676void Layer::commitTransaction(const State& stateToCommit) {
1677 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001678}
1679
Mathias Agopian13127d82013-03-05 17:47:11 -08001680uint32_t Layer::getTransactionFlags(uint32_t flags) {
1681 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1682}
1683
1684uint32_t Layer::setTransactionFlags(uint32_t flags) {
1685 return android_atomic_or(flags, &mTransactionFlags);
1686}
1687
Robert Carr82364e32016-05-15 11:27:47 -07001688bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001689 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001690 return false;
1691 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001692
1693 // We update the requested and active position simultaneously because
1694 // we want to apply the position portion of the transform matrix immediately,
1695 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001696 mCurrentState.requested.transform.set(x, y);
Robert Carr82364e32016-05-15 11:27:47 -07001697 if (immediate && !mFreezePositionUpdates) {
1698 mCurrentState.active.transform.set(x, y);
1699 }
1700 mFreezePositionUpdates = mFreezePositionUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001701
Dan Stoza7dde5992015-05-22 09:51:44 -07001702 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001703 setTransactionFlags(eTransactionNeeded);
1704 return true;
1705}
Robert Carr82364e32016-05-15 11:27:47 -07001706
Robert Carr1f0a16a2016-10-24 16:27:39 -07001707bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1708 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1709 if (idx < 0) {
1710 return false;
1711 }
1712 if (childLayer->setLayer(z)) {
1713 mCurrentChildren.removeAt(idx);
1714 mCurrentChildren.add(childLayer);
1715 }
1716 return true;
1717}
1718
Robert Carrae060832016-11-28 10:51:00 -08001719bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001720 if (mCurrentState.z == z)
1721 return false;
1722 mCurrentState.sequence++;
1723 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001724 mCurrentState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001725
1726 // Discard all relative layering.
1727 if (mCurrentState.zOrderRelativeOf != nullptr) {
1728 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1729 if (strongRelative != nullptr) {
1730 strongRelative->removeZOrderRelative(this);
1731 }
1732 mCurrentState.zOrderRelativeOf = nullptr;
1733 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001734 setTransactionFlags(eTransactionNeeded);
1735 return true;
1736}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001737
Robert Carrdb66e622017-04-10 16:55:57 -07001738void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1739 mCurrentState.zOrderRelatives.remove(relative);
1740 mCurrentState.sequence++;
1741 mCurrentState.modified = true;
1742 setTransactionFlags(eTransactionNeeded);
1743}
1744
1745void Layer::addZOrderRelative(const wp<Layer>& relative) {
1746 mCurrentState.zOrderRelatives.add(relative);
1747 mCurrentState.modified = true;
1748 mCurrentState.sequence++;
1749 setTransactionFlags(eTransactionNeeded);
1750}
1751
1752bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1753 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1754 if (handle == nullptr) {
1755 return false;
1756 }
1757 sp<Layer> relative = handle->owner.promote();
1758 if (relative == nullptr) {
1759 return false;
1760 }
1761
1762 mCurrentState.sequence++;
1763 mCurrentState.modified = true;
1764 mCurrentState.z = z;
1765
1766 mCurrentState.zOrderRelativeOf = relative;
1767 relative->addZOrderRelative(this);
1768
1769 setTransactionFlags(eTransactionNeeded);
1770
1771 return true;
1772}
1773
Mathias Agopian13127d82013-03-05 17:47:11 -08001774bool Layer::setSize(uint32_t w, uint32_t h) {
1775 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1776 return false;
1777 mCurrentState.requested.w = w;
1778 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001779 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001780 setTransactionFlags(eTransactionNeeded);
1781 return true;
1782}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001783#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001784bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001785#else
1786bool Layer::setAlpha(uint8_t alpha) {
1787#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001788 if (mCurrentState.alpha == alpha)
1789 return false;
1790 mCurrentState.sequence++;
1791 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001792 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001793 setTransactionFlags(eTransactionNeeded);
1794 return true;
1795}
1796bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1797 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001798 mCurrentState.requested.transform.set(
Robert Carrcb6e1e32017-02-21 19:48:26 -08001799 matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001800 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001801 setTransactionFlags(eTransactionNeeded);
1802 return true;
1803}
1804bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001805 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001806 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001807 setTransactionFlags(eTransactionNeeded);
1808 return true;
1809}
1810bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1811 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1812 if (mCurrentState.flags == newFlags)
1813 return false;
1814 mCurrentState.sequence++;
1815 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001816 mCurrentState.mask = mask;
1817 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001818 setTransactionFlags(eTransactionNeeded);
1819 return true;
1820}
Robert Carr99e27f02016-06-16 15:18:02 -07001821
1822bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001823 if (mCurrentState.crop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001824 return false;
1825 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001826 mCurrentState.requestedCrop = crop;
1827 if (immediate) {
1828 mCurrentState.crop = crop;
1829 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001830 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001831 setTransactionFlags(eTransactionNeeded);
1832 return true;
1833}
Robert Carr8d5227b2017-03-16 15:41:03 -07001834
1835bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001836 if (mCurrentState.finalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001837 return false;
1838 mCurrentState.sequence++;
Robert Carr8d5227b2017-03-16 15:41:03 -07001839 mCurrentState.requestedFinalCrop = crop;
1840 if (immediate) {
1841 mCurrentState.finalCrop = crop;
1842 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001843 mCurrentState.modified = true;
1844 setTransactionFlags(eTransactionNeeded);
1845 return true;
1846}
Mathias Agopian13127d82013-03-05 17:47:11 -08001847
Robert Carrc3574f72016-03-24 12:19:32 -07001848bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1849 if (scalingMode == mOverrideScalingMode)
1850 return false;
1851 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001852 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001853 return true;
1854}
1855
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001856void Layer::setInfo(uint32_t type, uint32_t appId) {
1857 mCurrentState.appId = appId;
1858 mCurrentState.type = type;
1859 mCurrentState.modified = true;
1860 setTransactionFlags(eTransactionNeeded);
1861}
1862
Robert Carrc3574f72016-03-24 12:19:32 -07001863uint32_t Layer::getEffectiveScalingMode() const {
1864 if (mOverrideScalingMode >= 0) {
1865 return mOverrideScalingMode;
1866 }
1867 return mCurrentScalingMode;
1868}
1869
Mathias Agopian13127d82013-03-05 17:47:11 -08001870bool Layer::setLayerStack(uint32_t layerStack) {
1871 if (mCurrentState.layerStack == layerStack)
1872 return false;
1873 mCurrentState.sequence++;
1874 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001875 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001876 setTransactionFlags(eTransactionNeeded);
1877 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001878}
1879
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07001880bool Layer::setDataSpace(android_dataspace dataSpace) {
1881 if (mCurrentState.dataSpace == dataSpace)
1882 return false;
1883 mCurrentState.sequence++;
1884 mCurrentState.dataSpace = dataSpace;
1885 mCurrentState.modified = true;
1886 setTransactionFlags(eTransactionNeeded);
1887 return true;
1888}
1889
Robert Carr1f0a16a2016-10-24 16:27:39 -07001890uint32_t Layer::getLayerStack() const {
1891 auto p = getParent();
1892 if (p == nullptr) {
1893 return getDrawingState().layerStack;
1894 }
1895 return p->getLayerStack();
1896}
1897
Robert Carr0d480722017-01-10 16:42:54 -08001898void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
Dan Stoza7dde5992015-05-22 09:51:44 -07001899 uint64_t frameNumber) {
Robert Carr0d480722017-01-10 16:42:54 -08001900 mCurrentState.barrierLayer = barrierLayer;
Dan Stoza7dde5992015-05-22 09:51:44 -07001901 mCurrentState.frameNumber = frameNumber;
1902 // We don't set eTransactionNeeded, because just receiving a deferral
1903 // request without any other state updates shouldn't actually induce a delay
1904 mCurrentState.modified = true;
1905 pushPendingState();
Robert Carr0d480722017-01-10 16:42:54 -08001906 mCurrentState.barrierLayer = nullptr;
Dan Stoza792e5292016-02-11 11:43:58 -08001907 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07001908 mCurrentState.modified = false;
Robert Carr0d480722017-01-10 16:42:54 -08001909 ALOGE("Deferred transaction");
1910}
1911
1912void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
1913 uint64_t frameNumber) {
1914 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
1915 deferTransactionUntil(handle->owner.promote(), frameNumber);
Dan Stoza7dde5992015-05-22 09:51:44 -07001916}
1917
Dan Stozaee44edd2015-03-23 15:50:23 -07001918void Layer::useSurfaceDamage() {
1919 if (mFlinger->mForceFullDamage) {
1920 surfaceDamageRegion = Region::INVALID_REGION;
1921 } else {
1922 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1923 }
1924}
1925
1926void Layer::useEmptyDamage() {
1927 surfaceDamageRegion.clear();
1928}
1929
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001930// ----------------------------------------------------------------------------
1931// pageflip handling...
1932// ----------------------------------------------------------------------------
1933
Dan Stoza6b9454d2014-11-07 16:00:59 -08001934bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001935 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07001936 return true;
1937 }
1938
Dan Stoza6b9454d2014-11-07 16:00:59 -08001939 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001940 if (mQueueItems.empty()) {
1941 return false;
1942 }
1943 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001944 nsecs_t expectedPresent =
1945 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001946
1947 // Ignore timestamps more than a second in the future
1948 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1949 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1950 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1951 expectedPresent);
1952
1953 bool isDue = timestamp < expectedPresent;
1954 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001955}
1956
Brian Andersond6927fb2016-07-23 23:37:30 -07001957bool Layer::onPreComposition(nsecs_t refreshStartTime) {
1958 if (mBufferLatched) {
1959 Mutex::Autolock lock(mFrameEventHistoryMutex);
1960 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
1961 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08001962 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001963 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001964}
1965
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001966bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
Brian Anderson3d4039d2016-09-23 16:31:30 -07001967 const std::shared_ptr<FenceTime>& presentFence,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001968 const CompositorTiming& compositorTiming) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001969 mAcquireTimeline.updateSignalTimes();
1970 mReleaseTimeline.updateSignalTimes();
1971
Brian Andersond6927fb2016-07-23 23:37:30 -07001972 // mFrameLatencyNeeded is true when a new frame was latched for the
1973 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08001974 if (!mFrameLatencyNeeded)
1975 return false;
1976
Fabien Sanglard28e98082016-12-05 10:19:46 -08001977 // Update mFrameEventHistory.
1978 {
1979 Mutex::Autolock lock(mFrameEventHistoryMutex);
1980 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001981 glDoneFence, presentFence, compositorTiming);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001982 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08001983
1984 // Update mFrameTracker.
1985 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1986 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1987
Brian Anderson3d4039d2016-09-23 16:31:30 -07001988 std::shared_ptr<FenceTime> frameReadyFence =
1989 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08001990 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001991 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001992 } else {
1993 // There was no fence for this frame, so assume that it was ready
1994 // to be presented at the desired present time.
1995 mFrameTracker.setFrameReadyTime(desiredPresentTime);
1996 }
1997
Brian Anderson3d4039d2016-09-23 16:31:30 -07001998 if (presentFence->isValid()) {
1999 mFrameTracker.setActualPresentFence(
2000 std::shared_ptr<FenceTime>(presentFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002001 } else {
2002 // The HWC doesn't support present fences, so use the refresh
2003 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002004 mFrameTracker.setActualPresentTime(
2005 mFlinger->getHwComposer().getRefreshTimestamp(
2006 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002007 }
2008
2009 mFrameTracker.advanceFrame();
2010 mFrameLatencyNeeded = false;
2011 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002012}
2013
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002014#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07002015void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Brian Anderson5ea5e592016-12-01 16:54:33 -08002016 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2017 return;
2018 }
2019
Brian Anderson3d4039d2016-09-23 16:31:30 -07002020 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002021 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002022 mReleaseTimeline.push(releaseFenceTime);
2023
2024 Mutex::Autolock lock(mFrameEventHistoryMutex);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002025 if (mPreviousFrameNumber != 0) {
2026 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2027 dequeueReadyTime, std::move(releaseFenceTime));
2028 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002029}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002030#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002031
Robert Carr1f0a16a2016-10-24 16:27:39 -07002032bool Layer::isHiddenByPolicy() const {
2033 const Layer::State& s(mDrawingState);
2034 const auto& parent = getParent();
2035 if (parent != nullptr && parent->isHiddenByPolicy()) {
2036 return true;
2037 }
2038 return s.flags & layer_state_t::eLayerHidden;
2039}
2040
Mathias Agopianda27af92012-09-13 18:17:13 -07002041bool Layer::isVisible() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002042#ifdef USE_HWC2
Robert Carr6452f122017-03-21 10:41:29 -07002043 return !(isHiddenByPolicy()) && getAlpha() > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08002044 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002045#else
Robert Carr6452f122017-03-21 10:41:29 -07002046 return !(isHiddenByPolicy()) && getAlpha()
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002047 && (mActiveBuffer != NULL || mSidebandStream != NULL);
2048#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07002049}
2050
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002051bool Layer::allTransactionsSignaled() {
2052 auto headFrameNumber = getHeadFrameNumber();
2053 bool matchingFramesFound = false;
2054 bool allTransactionsApplied = true;
2055 Mutex::Autolock lock(mLocalSyncPointMutex);
2056
2057 for (auto& point : mLocalSyncPoints) {
2058 if (point->getFrameNumber() > headFrameNumber) {
2059 break;
2060 }
2061 matchingFramesFound = true;
2062
2063 if (!point->frameIsAvailable()) {
2064 // We haven't notified the remote layer that the frame for
2065 // this point is available yet. Notify it now, and then
2066 // abort this attempt to latch.
2067 point->setFrameAvailable();
2068 allTransactionsApplied = false;
2069 break;
2070 }
2071
2072 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2073 }
2074 return !matchingFramesFound || allTransactionsApplied;
2075}
2076
Brian Andersond6927fb2016-07-23 23:37:30 -07002077Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002078{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08002079 ATRACE_CALL();
2080
Jesse Hall399184a2014-03-03 15:42:54 -08002081 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2082 // mSidebandStreamChanged was true
2083 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07002084 if (mSidebandStream != NULL) {
2085 setTransactionFlags(eTransactionNeeded);
2086 mFlinger->setTransactionFlags(eTraversalNeeded);
2087 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07002088 recomputeVisibleRegions = true;
2089
2090 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07002091 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08002092 }
2093
Mathias Agopian4fec8732012-06-29 14:12:52 -07002094 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07002095 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2096 return outDirtyRegion;
2097 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002098
Fabien Sanglard223eb912016-10-13 10:15:06 -07002099 // if we've already called updateTexImage() without going through
2100 // a composition step, we have to skip this layer at this point
2101 // because we cannot call updateTeximage() without a corresponding
2102 // compositionComplete() call.
2103 // we'll trigger an update in onPreComposition().
2104 if (mRefreshPending) {
2105 return outDirtyRegion;
2106 }
2107
2108 // If the head buffer's acquire fence hasn't signaled yet, return and
2109 // try again later
2110 if (!headFenceHasSignaled()) {
2111 mFlinger->signalLayerUpdate();
2112 return outDirtyRegion;
2113 }
2114
2115 // Capture the old state of the layer for comparisons later
2116 const State& s(getDrawingState());
2117 const bool oldOpacity = isOpaque(s);
2118 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2119
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002120 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002121 mFlinger->signalLayerUpdate();
2122 return outDirtyRegion;
2123 }
2124
2125 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2126 // of the buffer queue isn't modified when the buffer queue is returning
2127 // BufferItem's that weren't actually queued. This can happen in shared
2128 // buffer mode.
2129 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002130 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2131 getProducerStickyTransform() != 0, mName.string(),
2132 mOverrideScalingMode, mFreezePositionUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002133 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2134 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2135 mLastFrameNumberReceived);
2136 if (updateResult == BufferQueue::PRESENT_LATER) {
2137 // Producer doesn't want buffer to be displayed yet. Signal a
2138 // layer update so we check again at the next opportunity.
2139 mFlinger->signalLayerUpdate();
2140 return outDirtyRegion;
2141 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2142 // If the buffer has been rejected, remove it from the shadow queue
2143 // and return early
2144 if (queuedBuffer) {
2145 Mutex::Autolock lock(mQueueItemLock);
2146 mQueueItems.removeAt(0);
2147 android_atomic_dec(&mQueuedFrames);
2148 }
2149 return outDirtyRegion;
2150 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2151 // This can occur if something goes wrong when trying to create the
2152 // EGLImage for this buffer. If this happens, the buffer has already
2153 // been released, so we need to clean up the queue and bug out
2154 // early.
2155 if (queuedBuffer) {
2156 Mutex::Autolock lock(mQueueItemLock);
2157 mQueueItems.clear();
2158 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002159 }
2160
Fabien Sanglard223eb912016-10-13 10:15:06 -07002161 // Once we have hit this state, the shadow queue may no longer
2162 // correctly reflect the incoming BufferQueue's contents, so even if
2163 // updateTexImage starts working, the only safe course of action is
2164 // to continue to ignore updates.
2165 mUpdateTexImageFailed = true;
2166
2167 return outDirtyRegion;
2168 }
2169
2170 if (queuedBuffer) {
2171 // Autolock scope
2172 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2173
2174 Mutex::Autolock lock(mQueueItemLock);
2175
2176 // Remove any stale buffers that have been dropped during
2177 // updateTexImage
2178 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2179 mQueueItems.removeAt(0);
2180 android_atomic_dec(&mQueuedFrames);
2181 }
2182
2183 mQueueItems.removeAt(0);
2184 }
2185
2186
2187 // Decrement the queued-frames count. Signal another event if we
2188 // have more frames pending.
2189 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2190 || mAutoRefresh) {
2191 mFlinger->signalLayerUpdate();
2192 }
2193
Fabien Sanglard223eb912016-10-13 10:15:06 -07002194 // update the active buffer
Chia-I Wu06d63de2017-01-04 14:58:51 +08002195 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2196 &mActiveBufferSlot);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002197 if (mActiveBuffer == NULL) {
2198 // this can only happen if the very first buffer was rejected.
2199 return outDirtyRegion;
2200 }
2201
Brian Andersond6927fb2016-07-23 23:37:30 -07002202 mBufferLatched = true;
2203 mPreviousFrameNumber = mCurrentFrameNumber;
2204 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2205
2206 {
2207 Mutex::Autolock lock(mFrameEventHistoryMutex);
2208 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2209#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002210 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002211 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002212 mReleaseTimeline.push(releaseFenceTime);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002213 if (mPreviousFrameNumber != 0) {
2214 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2215 latchTime, std::move(releaseFenceTime));
2216 }
Brian Andersond6927fb2016-07-23 23:37:30 -07002217#endif
2218 }
2219
Fabien Sanglard223eb912016-10-13 10:15:06 -07002220 mRefreshPending = true;
2221 mFrameLatencyNeeded = true;
2222 if (oldActiveBuffer == NULL) {
2223 // the first time we receive a buffer, we need to trigger a
2224 // geometry invalidation.
2225 recomputeVisibleRegions = true;
2226 }
2227
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002228 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2229
Fabien Sanglard223eb912016-10-13 10:15:06 -07002230 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2231 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2232 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2233 if ((crop != mCurrentCrop) ||
2234 (transform != mCurrentTransform) ||
2235 (scalingMode != mCurrentScalingMode))
2236 {
2237 mCurrentCrop = crop;
2238 mCurrentTransform = transform;
2239 mCurrentScalingMode = scalingMode;
2240 recomputeVisibleRegions = true;
2241 }
2242
2243 if (oldActiveBuffer != NULL) {
2244 uint32_t bufWidth = mActiveBuffer->getWidth();
2245 uint32_t bufHeight = mActiveBuffer->getHeight();
2246 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2247 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002248 recomputeVisibleRegions = true;
2249 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002250 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002251
Fabien Sanglard223eb912016-10-13 10:15:06 -07002252 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2253 if (oldOpacity != isOpaque(s)) {
2254 recomputeVisibleRegions = true;
2255 }
Dan Stozacac35382016-01-27 12:21:06 -08002256
Fabien Sanglard223eb912016-10-13 10:15:06 -07002257 // Remove any sync points corresponding to the buffer which was just
2258 // latched
2259 {
2260 Mutex::Autolock lock(mLocalSyncPointMutex);
2261 auto point = mLocalSyncPoints.begin();
2262 while (point != mLocalSyncPoints.end()) {
2263 if (!(*point)->frameIsAvailable() ||
2264 !(*point)->transactionIsApplied()) {
2265 // This sync point must have been added since we started
2266 // latching. Don't drop it yet.
2267 ++point;
2268 continue;
2269 }
2270
2271 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2272 point = mLocalSyncPoints.erase(point);
2273 } else {
2274 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002275 }
2276 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002277 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002278
2279 // FIXME: postedRegion should be dirty & bounds
2280 Region dirtyRegion(Rect(s.active.w, s.active.h));
2281
2282 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002283 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002284
Mathias Agopian4fec8732012-06-29 14:12:52 -07002285 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002286}
2287
Mathias Agopiana67932f2011-04-20 14:20:59 -07002288uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002289{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002290 // TODO: should we do something special if mSecure is set?
2291 if (mProtectedByApp) {
2292 // need a hardware-protected path to external video sink
2293 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002294 }
Riley Andrews03414a12014-07-01 14:22:59 -07002295 if (mPotentialCursor) {
2296 usage |= GraphicBuffer::USAGE_CURSOR;
2297 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002298 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002299 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002300}
2301
Mathias Agopian84300952012-11-21 16:02:13 -08002302void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002303 uint32_t orientation = 0;
2304 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002305 // The transform hint is used to improve performance, but we can
2306 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002307 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002308 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002309 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002310 if (orientation & Transform::ROT_INVALID) {
2311 orientation = 0;
2312 }
2313 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002314 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002315}
2316
Mathias Agopian13127d82013-03-05 17:47:11 -08002317// ----------------------------------------------------------------------------
2318// debugging
2319// ----------------------------------------------------------------------------
2320
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002321void Layer::dump(String8& result, Colorizer& colorizer) const
Mathias Agopian13127d82013-03-05 17:47:11 -08002322{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002323 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08002324
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002325 colorizer.colorize(result, Colorizer::GREEN);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002326 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002327 "+ %s %p (%s)\n",
2328 getTypeId(), this, getName().string());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002329 colorizer.reset(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002330
Mathias Agopian2ca79392013-04-02 18:30:32 -07002331 s.activeTransparentRegion.dump(result, "transparentRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002332 visibleRegion.dump(result, "visibleRegion");
Dan Stozaee44edd2015-03-23 15:50:23 -07002333 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002334 sp<Client> client(mClientRef.promote());
Courtney Goeltzenleuchter36c44dc2017-04-14 09:33:16 -06002335 PixelFormat pf = PIXEL_FORMAT_UNKNOWN;
2336 const sp<GraphicBuffer>& buffer(getActiveBuffer());
2337 if (buffer != NULL) {
2338 pf = buffer->getPixelFormat();
2339 }
Mathias Agopian13127d82013-03-05 17:47:11 -08002340
Mathias Agopian74d211a2013-04-22 16:55:35 +02002341 result.appendFormat( " "
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002342 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2343 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
Mathias Agopian13127d82013-03-05 17:47:11 -08002344 "isOpaque=%1d, invalidate=%1d, "
Courtney Goeltzenleuchter36c44dc2017-04-14 09:33:16 -06002345 "dataspace=%s, pixelformat=%s "
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002346#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08002347 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002348#else
2349 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2350#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08002351 " client=%p\n",
Robert Carr1f0a16a2016-10-24 16:27:39 -07002352 getLayerStack(), s.z,
2353 s.active.transform.tx(), s.active.transform.ty(),
2354 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07002355 s.crop.left, s.crop.top,
2356 s.crop.right, s.crop.bottom,
2357 s.finalCrop.left, s.finalCrop.top,
2358 s.finalCrop.right, s.finalCrop.bottom,
Andy McFadden4125a4f2014-01-29 17:17:11 -08002359 isOpaque(s), contentDirty,
Courtney Goeltzenleuchter36c44dc2017-04-14 09:33:16 -06002360 dataspaceDetails(getDataSpace()).c_str(), decodePixelFormat(pf).c_str(),
Mathias Agopian13127d82013-03-05 17:47:11 -08002361 s.alpha, s.flags,
Robert Carr3dcabfa2016-03-01 18:36:58 -08002362 s.active.transform[0][0], s.active.transform[0][1],
2363 s.active.transform[1][0], s.active.transform[1][1],
Mathias Agopian13127d82013-03-05 17:47:11 -08002364 client.get());
Mathias Agopian13127d82013-03-05 17:47:11 -08002365
2366 sp<const GraphicBuffer> buf0(mActiveBuffer);
2367 uint32_t w0=0, h0=0, s0=0, f0=0;
2368 if (buf0 != 0) {
2369 w0 = buf0->getWidth();
2370 h0 = buf0->getHeight();
2371 s0 = buf0->getStride();
2372 f0 = buf0->format;
2373 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02002374 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002375 " "
2376 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2377 " queued-frames=%d, mRefreshPending=%d\n",
2378 mFormat, w0, h0, s0,f0,
2379 mQueuedFrames, mRefreshPending);
2380
Mathias Agopian13127d82013-03-05 17:47:11 -08002381 if (mSurfaceFlingerConsumer != 0) {
Colin Cross3d1d2802016-09-26 18:10:16 -07002382 mSurfaceFlingerConsumer->dumpState(result, " ");
Mathias Agopian13127d82013-03-05 17:47:11 -08002383 }
2384}
2385
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002386#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002387void Layer::miniDumpHeader(String8& result) {
2388 result.append("----------------------------------------");
2389 result.append("---------------------------------------\n");
2390 result.append(" Layer name\n");
2391 result.append(" Z | ");
2392 result.append(" Comp Type | ");
2393 result.append(" Disp Frame (LTRB) | ");
2394 result.append(" Source Crop (LTRB)\n");
2395 result.append("----------------------------------------");
2396 result.append("---------------------------------------\n");
2397}
2398
2399void Layer::miniDump(String8& result, int32_t hwcId) const {
2400 if (mHwcLayers.count(hwcId) == 0) {
2401 return;
2402 }
2403
2404 String8 name;
2405 if (mName.length() > 77) {
2406 std::string shortened;
2407 shortened.append(mName.string(), 36);
2408 shortened.append("[...]");
2409 shortened.append(mName.string() + (mName.length() - 36), 36);
2410 name = shortened.c_str();
2411 } else {
2412 name = mName;
2413 }
2414
2415 result.appendFormat(" %s\n", name.string());
2416
2417 const Layer::State& layerState(getDrawingState());
2418 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2419 result.appendFormat(" %10u | ", layerState.z);
2420 result.appendFormat("%10s | ",
2421 to_string(getCompositionType(hwcId)).c_str());
2422 const Rect& frame = hwcInfo.displayFrame;
2423 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2424 frame.right, frame.bottom);
Dan Stoza5a423ea2017-02-16 14:10:39 -08002425 const FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002426 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2427 crop.right, crop.bottom);
2428
2429 result.append("- - - - - - - - - - - - - - - - - - - - ");
2430 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2431}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002432#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002433
Svetoslavd85084b2014-03-20 10:28:31 -07002434void Layer::dumpFrameStats(String8& result) const {
2435 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002436}
2437
Svetoslavd85084b2014-03-20 10:28:31 -07002438void Layer::clearFrameStats() {
2439 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002440}
2441
Jamie Gennis6547ff42013-07-16 20:12:42 -07002442void Layer::logFrameStats() {
2443 mFrameTracker.logAndResetStats(mName);
2444}
2445
Svetoslavd85084b2014-03-20 10:28:31 -07002446void Layer::getFrameStats(FrameStats* outStats) const {
2447 mFrameTracker.getStats(outStats);
2448}
2449
Brian Andersond6927fb2016-07-23 23:37:30 -07002450void Layer::dumpFrameEvents(String8& result) {
2451 result.appendFormat("- Layer %s (%s, %p)\n",
2452 getName().string(), getTypeId(), this);
2453 Mutex::Autolock lock(mFrameEventHistoryMutex);
2454 mFrameEventHistory.checkFencesForCompletion();
2455 mFrameEventHistory.dump(result);
2456}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002457
Brian Anderson5ea5e592016-12-01 16:54:33 -08002458void Layer::onDisconnect() {
2459 Mutex::Autolock lock(mFrameEventHistoryMutex);
2460 mFrameEventHistory.onDisconnect();
2461}
2462
Brian Anderson3890c392016-07-25 12:48:08 -07002463void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2464 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002465 Mutex::Autolock lock(mFrameEventHistoryMutex);
2466 if (newTimestamps) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002467 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002468 mFrameEventHistory.addQueue(*newTimestamps);
2469 }
2470
Brian Anderson3890c392016-07-25 12:48:08 -07002471 if (outDelta) {
2472 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002473 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002474}
Dan Stozae77c7662016-05-13 11:37:28 -07002475
2476std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2477 bool forceFlush) {
2478 std::vector<OccupancyTracker::Segment> history;
2479 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2480 &history);
2481 if (result != NO_ERROR) {
2482 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2483 result);
2484 return {};
2485 }
2486 return history;
2487}
2488
Robert Carr367c5682016-06-20 11:55:28 -07002489bool Layer::getTransformToDisplayInverse() const {
2490 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2491}
2492
Robert Carr1f0a16a2016-10-24 16:27:39 -07002493void Layer::addChild(const sp<Layer>& layer) {
2494 mCurrentChildren.add(layer);
2495 layer->setParent(this);
2496}
2497
2498ssize_t Layer::removeChild(const sp<Layer>& layer) {
2499 layer->setParent(nullptr);
2500 return mCurrentChildren.remove(layer);
2501}
2502
Robert Carr1db73f62016-12-21 12:58:51 -08002503bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2504 sp<Handle> handle = nullptr;
2505 sp<Layer> newParent = nullptr;
2506 if (newParentHandle == nullptr) {
2507 return false;
2508 }
2509 handle = static_cast<Handle*>(newParentHandle.get());
2510 newParent = handle->owner.promote();
2511 if (newParent == nullptr) {
2512 ALOGE("Unable to promote Layer handle");
2513 return false;
2514 }
2515
2516 for (const sp<Layer>& child : mCurrentChildren) {
2517 newParent->addChild(child);
2518
2519 sp<Client> client(child->mClientRef.promote());
2520 if (client != nullptr) {
2521 client->setParentLayer(newParent);
2522 }
2523 }
2524 mCurrentChildren.clear();
2525
2526 return true;
2527}
2528
Robert Carr9524cb32017-02-13 11:32:32 -08002529bool Layer::detachChildren() {
Dan Stoza412903f2017-04-27 13:42:17 -07002530 traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
Robert Carr9524cb32017-02-13 11:32:32 -08002531 if (child == this) {
2532 return;
2533 }
2534
2535 sp<Client> client(child->mClientRef.promote());
2536 if (client != nullptr) {
2537 client->detachLayer(child);
2538 }
2539 });
2540
2541 return true;
2542}
2543
Robert Carr1f0a16a2016-10-24 16:27:39 -07002544void Layer::setParent(const sp<Layer>& layer) {
2545 mParent = layer;
2546}
2547
2548void Layer::clearSyncPoints() {
2549 for (const auto& child : mCurrentChildren) {
2550 child->clearSyncPoints();
2551 }
2552
2553 Mutex::Autolock lock(mLocalSyncPointMutex);
2554 for (auto& point : mLocalSyncPoints) {
2555 point->setFrameAvailable();
2556 }
2557 mLocalSyncPoints.clear();
2558}
2559
2560int32_t Layer::getZ() const {
2561 return mDrawingState.z;
2562}
2563
Dan Stoza412903f2017-04-27 13:42:17 -07002564LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2565 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2566 "makeTraversalList received invalid stateSet");
2567 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2568 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2569 const State& state = useDrawing ? mDrawingState : mCurrentState;
2570
2571 if (state.zOrderRelatives.size() == 0) {
2572 return children;
Robert Carrdb66e622017-04-10 16:55:57 -07002573 }
2574 LayerVector traverse;
2575
Dan Stoza412903f2017-04-27 13:42:17 -07002576 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07002577 sp<Layer> strongRelative = weakRelative.promote();
2578 if (strongRelative != nullptr) {
2579 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07002580 }
2581 }
2582
Dan Stoza412903f2017-04-27 13:42:17 -07002583 for (const sp<Layer>& child : children) {
Robert Carrdb66e622017-04-10 16:55:57 -07002584 traverse.add(child);
2585 }
2586
2587 return traverse;
2588}
2589
Robert Carr1f0a16a2016-10-24 16:27:39 -07002590/**
Robert Carrdb66e622017-04-10 16:55:57 -07002591 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002592 */
Dan Stoza412903f2017-04-27 13:42:17 -07002593void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2594 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002595
Robert Carr1f0a16a2016-10-24 16:27:39 -07002596 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002597 for (; i < list.size(); i++) {
2598 const auto& relative = list[i];
2599 if (relative->getZ() >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002600 break;
Robert Carrdb66e622017-04-10 16:55:57 -07002601 }
Dan Stoza412903f2017-04-27 13:42:17 -07002602 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002603 }
Dan Stoza412903f2017-04-27 13:42:17 -07002604 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07002605 for (; i < list.size(); i++) {
2606 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002607 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002608 }
2609}
2610
2611/**
Robert Carrdb66e622017-04-10 16:55:57 -07002612 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002613 */
Dan Stoza412903f2017-04-27 13:42:17 -07002614void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2615 const LayerVector::Visitor& visitor) {
2616 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002617
Robert Carr1f0a16a2016-10-24 16:27:39 -07002618 int32_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002619 for (i = list.size()-1; i>=0; i--) {
2620 const auto& relative = list[i];
2621 if (relative->getZ() < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002622 break;
2623 }
Dan Stoza412903f2017-04-27 13:42:17 -07002624 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002625 }
Dan Stoza412903f2017-04-27 13:42:17 -07002626 visitor(this);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002627 for (; i>=0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002628 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002629 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002630 }
2631}
2632
2633Transform Layer::getTransform() const {
2634 Transform t;
2635 const auto& p = getParent();
2636 if (p != nullptr) {
2637 t = p->getTransform();
Robert Carr9b429f42017-04-17 14:56:57 -07002638
2639 // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2640 // it isFixedSize) then there may be additional scaling not accounted
2641 // for in the transform. We need to mirror this scaling in child surfaces
2642 // or we will break the contract where WM can treat child surfaces as
2643 // pixels in the parent surface.
2644 if (p->isFixedSize()) {
Robert Carr1725eee2017-04-26 18:32:15 -07002645 int bufferWidth;
2646 int bufferHeight;
2647 if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2648 bufferWidth = p->mActiveBuffer->getWidth();
2649 bufferHeight = p->mActiveBuffer->getHeight();
2650 } else {
2651 bufferHeight = p->mActiveBuffer->getWidth();
2652 bufferWidth = p->mActiveBuffer->getHeight();
2653 }
Robert Carr9b429f42017-04-17 14:56:57 -07002654 float sx = p->getDrawingState().active.w /
Robert Carr1725eee2017-04-26 18:32:15 -07002655 static_cast<float>(bufferWidth);
Robert Carr9b429f42017-04-17 14:56:57 -07002656 float sy = p->getDrawingState().active.h /
Robert Carr1725eee2017-04-26 18:32:15 -07002657 static_cast<float>(bufferHeight);
Robert Carr9b429f42017-04-17 14:56:57 -07002658 Transform extraParentScaling;
2659 extraParentScaling.set(sx, 0, 0, sy);
2660 t = t * extraParentScaling;
2661 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002662 }
2663 return t * getDrawingState().active.transform;
2664}
2665
Robert Carr6452f122017-03-21 10:41:29 -07002666#ifdef USE_HWC2
2667float Layer::getAlpha() const {
2668 const auto& p = getParent();
2669
2670 float parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0;
2671 return parentAlpha * getDrawingState().alpha;
2672}
2673#else
2674uint8_t Layer::getAlpha() const {
2675 const auto& p = getParent();
2676
2677 float parentAlpha = (p != nullptr) ? (p->getAlpha() / 255.0f) : 1.0;
2678 float drawingAlpha = getDrawingState().alpha / 255.0f;
2679 drawingAlpha = drawingAlpha * parentAlpha;
2680 return static_cast<uint8_t>(std::round(drawingAlpha * 255));
2681}
2682#endif
2683
Robert Carr1f0a16a2016-10-24 16:27:39 -07002684void Layer::commitChildList() {
2685 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2686 const auto& child = mCurrentChildren[i];
2687 child->commitChildList();
2688 }
2689 mDrawingChildren = mCurrentChildren;
2690}
2691
Mathias Agopian13127d82013-03-05 17:47:11 -08002692// ---------------------------------------------------------------------------
2693
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002694}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002695
2696#if defined(__gl_h_)
2697#error "don't include gl/gl.h in this file"
2698#endif
2699
2700#if defined(__gl2_h_)
2701#error "don't include gl2/gl2.h in this file"
2702#endif