blob: fe16b763c2eaa8e931f469dd22e8d37565d7eae0 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017//#define LOG_NDEBUG 0
18#undef LOG_TAG
19#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080020#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <stdlib.h>
23#include <stdint.h>
24#include <sys/types.h>
Mathias Agopian13127d82013-03-05 17:47:11 -080025#include <math.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080026
Mathias Agopiana67932f2011-04-20 14:20:59 -070027#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070028#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070029#include <cutils/properties.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
31#include <utils/Errors.h>
32#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080033#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080034#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080035#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080036
Mathias Agopian3330b202009-10-05 17:07:12 -070037#include <ui/GraphicBuffer.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080038#include <ui/PixelFormat.h>
Mathias Agopian9cce3252010-02-09 17:46:37 -080039
Dan Stoza6b9454d2014-11-07 16:00:59 -080040#include <gui/BufferItem.h>
Mathias Agopiana9347642017-02-13 16:42:28 -080041#include <gui/BufferQueue.h>
Mathias Agopian90ac7992012-02-25 18:48:35 -080042#include <gui/Surface.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080043
44#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020045#include "Colorizer.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070046#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080047#include "Layer.h"
Fabien Sanglard7b1563a2016-10-13 12:05:28 -070048#include "LayerRejecter.h"
Dan Stozab9b08832014-03-13 11:55:57 -070049#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080050#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080051
Mathias Agopian1b031492012-06-20 17:51:20 -070052#include "DisplayHardware/HWComposer.h"
53
Mathias Agopian875d8e12013-06-07 15:35:48 -070054#include "RenderEngine/RenderEngine.h"
55
Dan Stozac5da2712016-07-20 15:38:12 -070056#include <mutex>
57
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058#define DEBUG_RESIZE 0
59
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060namespace android {
61
62// ---------------------------------------------------------------------------
63
Mathias Agopian13127d82013-03-05 17:47:11 -080064int32_t Layer::sSequence = 1;
65
Mathias Agopian4d9b8222013-03-12 17:11:48 -070066Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
67 const String8& name, uint32_t w, uint32_t h, uint32_t flags)
Mathias Agopian13127d82013-03-05 17:47:11 -080068 : contentDirty(false),
69 sequence(uint32_t(android_atomic_inc(&sSequence))),
70 mFlinger(flinger),
Mathias Agopiana67932f2011-04-20 14:20:59 -070071 mTextureName(-1U),
Mathias Agopian13127d82013-03-05 17:47:11 -080072 mPremultipliedAlpha(true),
73 mName("unnamed"),
Mathias Agopian13127d82013-03-05 17:47:11 -080074 mFormat(PIXEL_FORMAT_NONE),
Mathias Agopian13127d82013-03-05 17:47:11 -080075 mTransactionFlags(0),
Dan Stoza7dde5992015-05-22 09:51:44 -070076 mPendingStateMutex(),
77 mPendingStates(),
Mathias Agopiana67932f2011-04-20 14:20:59 -070078 mQueuedFrames(0),
Jesse Hall399184a2014-03-03 15:42:54 -080079 mSidebandStreamChanged(false),
Mathias Agopiana9347642017-02-13 16:42:28 -080080 mActiveBufferSlot(BufferQueue::INVALID_BUFFER_SLOT),
Mathias Agopiana67932f2011-04-20 14:20:59 -070081 mCurrentTransform(0),
Mathias Agopian933389f2011-07-18 16:15:08 -070082 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
Robert Carrc3574f72016-03-24 12:19:32 -070083 mOverrideScalingMode(-1),
Mathias Agopiana67932f2011-04-20 14:20:59 -070084 mCurrentOpacity(true),
Brian Andersond6927fb2016-07-23 23:37:30 -070085 mBufferLatched(false),
Dan Stozacac35382016-01-27 12:21:06 -080086 mCurrentFrameNumber(0),
Brian Anderson8cc8b102016-10-21 12:43:09 -070087 mPreviousFrameNumber(0),
Mathias Agopian4d143ee2012-02-23 20:05:39 -080088 mRefreshPending(false),
Mathias Agopian82d7ab62012-01-19 18:34:40 -080089 mFrameLatencyNeeded(false),
Mathias Agopian13127d82013-03-05 17:47:11 -080090 mFiltering(false),
91 mNeedsFiltering(false),
Mathias Agopian5cdc8992013-08-13 20:51:23 -070092 mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
Fabien Sanglard9d96de42016-10-11 00:15:18 +000093#ifndef USE_HWC2
94 mIsGlesComposition(false),
95#endif
Mathias Agopian13127d82013-03-05 17:47:11 -080096 mProtectedByApp(false),
97 mHasSurface(false),
Riley Andrews03414a12014-07-01 14:22:59 -070098 mClientRef(client),
Dan Stozaa4650a52015-05-12 12:56:16 -070099 mPotentialCursor(false),
100 mQueueItemLock(),
101 mQueueItemCondition(),
102 mQueueItems(),
Dan Stoza65476f32015-05-14 09:27:25 -0700103 mLastFrameNumberReceived(0),
Pablo Ceballos04839ab2015-11-13 13:39:23 -0800104 mUpdateTexImageFailed(false),
Robert Carr82364e32016-05-15 11:27:47 -0700105 mAutoRefresh(false),
Rob Carra3ed0322017-05-16 19:40:52 +0000106 mFreezePositionUpdates(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800107{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000108#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800109 ALOGV("Creating Layer %s", name.string());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000110#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -0800111
Mathias Agopiana67932f2011-04-20 14:20:59 -0700112 mCurrentCrop.makeInvalid();
Mathias Agopian3f844832013-08-07 21:24:32 -0700113 mFlinger->getRenderEngine().genTextures(1, &mTextureName);
Mathias Agopian49457ac2013-08-14 18:20:17 -0700114 mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700115
116 uint32_t layerFlags = 0;
117 if (flags & ISurfaceComposerClient::eHidden)
Andy McFadden4125a4f2014-01-29 17:17:11 -0800118 layerFlags |= layer_state_t::eLayerHidden;
119 if (flags & ISurfaceComposerClient::eOpaque)
120 layerFlags |= layer_state_t::eLayerOpaque;
Dan Stoza23116082015-06-18 14:58:39 -0700121 if (flags & ISurfaceComposerClient::eSecure)
122 layerFlags |= layer_state_t::eLayerSecure;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700123
124 if (flags & ISurfaceComposerClient::eNonPremultiplied)
125 mPremultipliedAlpha = false;
126
127 mName = name;
128
129 mCurrentState.active.w = w;
130 mCurrentState.active.h = h;
Robert Carr3dcabfa2016-03-01 18:36:58 -0800131 mCurrentState.active.transform.set(0, 0);
Robert Carrb5d3d262016-03-25 15:08:13 -0700132 mCurrentState.crop.makeInvalid();
133 mCurrentState.finalCrop.makeInvalid();
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700134 mCurrentState.z = 0;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000135#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800136 mCurrentState.alpha = 1.0f;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000137#else
138 mCurrentState.alpha = 0xFF;
139#endif
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700140 mCurrentState.layerStack = 0;
141 mCurrentState.flags = layerFlags;
142 mCurrentState.sequence = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700143 mCurrentState.requested = mCurrentState.active;
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700144 mCurrentState.dataSpace = HAL_DATASPACE_UNKNOWN;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500145 mCurrentState.appId = 0;
146 mCurrentState.type = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700147
148 // drawing state & current state are identical
149 mDrawingState = mCurrentState;
Jamie Gennis6547ff42013-07-16 20:12:42 -0700150
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000151#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800152 const auto& hwc = flinger->getHwComposer();
153 const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
154 nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000155#else
156 nsecs_t displayPeriod =
157 flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
158#endif
Jamie Gennis6547ff42013-07-16 20:12:42 -0700159 mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -0800160
161 CompositorTiming compositorTiming;
162 flinger->getCompositorTiming(&compositorTiming);
163 mFrameEventHistory.initializeCompositorTiming(compositorTiming);
Jamie Gennise8696a42012-01-15 18:54:57 -0800164}
165
Mathias Agopian3f844832013-08-07 21:24:32 -0700166void Layer::onFirstRef() {
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800167 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
Dan Stozab3d0bdf2014-04-07 16:33:59 -0700168 sp<IGraphicBufferProducer> producer;
169 sp<IGraphicBufferConsumer> consumer;
Mathias Agopian0556d792017-03-22 15:49:32 -0700170 BufferQueue::createBufferQueue(&producer, &consumer, true);
Robert Carr1db73f62016-12-21 12:58:51 -0800171 mProducer = new MonitoredProducer(producer, mFlinger, this);
Irvel468051e2016-06-13 16:44:44 -0700172 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800173 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Jesse Hall399184a2014-03-03 15:42:54 -0800174 mSurfaceFlingerConsumer->setContentsChangedListener(this);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700175 mSurfaceFlingerConsumer->setName(mName);
Daniel Lamb2675792012-02-23 14:35:13 -0800176
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800177 if (mFlinger->isLayerTripleBufferingDisabled()) {
178 mProducer->setMaxDequeuedBufferCount(2);
179 }
Andy McFadden69052052012-09-14 16:10:11 -0700180
Mathias Agopian84300952012-11-21 16:02:13 -0800181 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
182 updateTransformHint(hw);
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700183}
184
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700185Layer::~Layer() {
Pablo Ceballos8ea4e7b2016-03-03 15:20:02 -0800186 sp<Client> c(mClientRef.promote());
187 if (c != 0) {
188 c->detachLayer(this);
189 }
190
Dan Stozacac35382016-01-27 12:21:06 -0800191 for (auto& point : mRemoteSyncPoints) {
192 point->setTransactionApplied();
193 }
Dan Stozac8145172016-04-28 16:29:06 -0700194 for (auto& point : mLocalSyncPoints) {
195 point->setFrameAvailable();
196 }
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700197 mFlinger->deleteTextureAsync(mTextureName);
Jamie Gennis6547ff42013-07-16 20:12:42 -0700198 mFrameTracker.logAndResetStats(mName);
Mathias Agopian96f08192010-06-02 23:28:45 -0700199}
200
Mathias Agopian13127d82013-03-05 17:47:11 -0800201// ---------------------------------------------------------------------------
202// callbacks
203// ---------------------------------------------------------------------------
204
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000205#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800206void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
207 if (mHwcLayers.empty()) {
208 return;
209 }
210 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
211}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000212#else
213void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
214 HWComposer::HWCLayerInterface* layer) {
215 if (layer) {
216 layer->onDisplayed();
217 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
218 }
219}
220#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800221
Dan Stoza6b9454d2014-11-07 16:00:59 -0800222void Layer::onFrameAvailable(const BufferItem& item) {
223 // Add this buffer from our internal queue tracker
224 { // Autolock scope
225 Mutex::Autolock lock(mQueueItemLock);
Irvel468051e2016-06-13 16:44:44 -0700226 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
227 item.mGraphicBuffer->getHeight(), item.mFrameNumber);
Dan Stozaa4650a52015-05-12 12:56:16 -0700228 // Reset the frame number tracker when we receive the first buffer after
229 // a frame number reset
230 if (item.mFrameNumber == 1) {
231 mLastFrameNumberReceived = 0;
232 }
233
234 // Ensure that callbacks are handled in order
235 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
236 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
237 ms2ns(500));
238 if (result != NO_ERROR) {
239 ALOGE("[%s] Timed out waiting on callback", mName.string());
240 }
241 }
242
Dan Stoza6b9454d2014-11-07 16:00:59 -0800243 mQueueItems.push_back(item);
Dan Stozaecc50402015-04-28 14:42:06 -0700244 android_atomic_inc(&mQueuedFrames);
Dan Stozaa4650a52015-05-12 12:56:16 -0700245
246 // Wake up any pending callbacks
247 mLastFrameNumberReceived = item.mFrameNumber;
248 mQueueItemCondition.broadcast();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800249 }
250
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800251 mFlinger->signalLayerUpdate();
Mathias Agopian579b3f82010-06-08 19:54:15 -0700252}
253
Dan Stoza6b9454d2014-11-07 16:00:59 -0800254void Layer::onFrameReplaced(const BufferItem& item) {
Dan Stoza7dde5992015-05-22 09:51:44 -0700255 { // Autolock scope
256 Mutex::Autolock lock(mQueueItemLock);
Dan Stozaa4650a52015-05-12 12:56:16 -0700257
Dan Stoza7dde5992015-05-22 09:51:44 -0700258 // Ensure that callbacks are handled in order
259 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
260 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
261 ms2ns(500));
262 if (result != NO_ERROR) {
263 ALOGE("[%s] Timed out waiting on callback", mName.string());
264 }
Dan Stozaa4650a52015-05-12 12:56:16 -0700265 }
Dan Stoza7dde5992015-05-22 09:51:44 -0700266
267 if (mQueueItems.empty()) {
268 ALOGE("Can't replace a frame on an empty queue");
269 return;
270 }
Pablo Ceballos4d85da42016-04-19 20:11:56 -0700271 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
Dan Stoza7dde5992015-05-22 09:51:44 -0700272
273 // Wake up any pending callbacks
274 mLastFrameNumberReceived = item.mFrameNumber;
275 mQueueItemCondition.broadcast();
Dan Stozaa4650a52015-05-12 12:56:16 -0700276 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800277}
278
Jesse Hall399184a2014-03-03 15:42:54 -0800279void Layer::onSidebandStreamChanged() {
280 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
281 // mSidebandStreamChanged was false
282 mFlinger->signalLayerUpdate();
283 }
284}
285
Mathias Agopian67106042013-03-14 19:18:13 -0700286// called with SurfaceFlinger::mStateLock from the drawing thread after
287// the layer has been remove from the current state list (and just before
288// it's removed from the drawing state list)
Mathias Agopian13127d82013-03-05 17:47:11 -0800289void Layer::onRemoved() {
Robert Carr5edb1ad2017-04-25 10:54:24 -0700290 if (mCurrentState.zOrderRelativeOf != nullptr) {
291 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
292 if (strongRelative != nullptr) {
293 strongRelative->removeZOrderRelative(this);
294 }
295 mCurrentState.zOrderRelativeOf = nullptr;
296 }
297
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800298 mSurfaceFlingerConsumer->abandon();
Chia-I Wu38512252017-05-17 14:36:16 -0700299
300#ifdef USE_HWC2
301 clearHwcLayers();
302#endif
303
Robert Carr1f0a16a2016-10-24 16:27:39 -0700304 for (const auto& child : mCurrentChildren) {
305 child->onRemoved();
306 }
Mathias Agopian48d819a2009-09-10 19:41:18 -0700307}
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700308
Mathias Agopian13127d82013-03-05 17:47:11 -0800309// ---------------------------------------------------------------------------
310// set-up
311// ---------------------------------------------------------------------------
312
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700313const String8& Layer::getName() const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800314 return mName;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800315}
316
Mathias Agopianf9d93272009-06-19 17:00:27 -0700317status_t Layer::setBuffers( uint32_t w, uint32_t h,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800318 PixelFormat format, uint32_t flags)
319{
Mathias Agopianca99fb82010-04-14 16:43:44 -0700320 uint32_t const maxSurfaceDims = min(
Mathias Agopiana4912602012-07-12 14:25:33 -0700321 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
Mathias Agopianca99fb82010-04-14 16:43:44 -0700322
323 // never allow a surface larger than what our underlying GL implementation
324 // can handle.
325 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
Mathias Agopianff615cc2012-02-24 14:58:36 -0800326 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700327 return BAD_VALUE;
328 }
329
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700330 mFormat = format;
Mathias Agopianeff062c2010-08-25 14:59:15 -0700331
Riley Andrews03414a12014-07-01 14:22:59 -0700332 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
Mathias Agopian3165cc22012-08-08 19:42:09 -0700333 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700334 mCurrentOpacity = getOpacityForFormat(format);
335
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800336 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
337 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
338 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700339
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800340 return NO_ERROR;
341}
342
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700343sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800344 Mutex::Autolock _l(mLock);
345
346 LOG_ALWAYS_FATAL_IF(mHasSurface,
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700347 "Layer::getHandle() has already been called");
Mathias Agopian13127d82013-03-05 17:47:11 -0800348
349 mHasSurface = true;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700350
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700351 return new Handle(mFlinger, this);
Mathias Agopian13127d82013-03-05 17:47:11 -0800352}
353
Dan Stozab9b08832014-03-13 11:55:57 -0700354sp<IGraphicBufferProducer> Layer::getProducer() const {
355 return mProducer;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700356}
357
Mathias Agopian13127d82013-03-05 17:47:11 -0800358// ---------------------------------------------------------------------------
359// h/w composer set-up
360// ---------------------------------------------------------------------------
361
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800362Rect Layer::getContentCrop() const {
363 // this is the crop rectangle that applies to the buffer
364 // itself (as opposed to the window)
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700365 Rect crop;
366 if (!mCurrentCrop.isEmpty()) {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800367 // if the buffer crop is defined, we use that
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700368 crop = mCurrentCrop;
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800369 } else if (mActiveBuffer != NULL) {
370 // otherwise we use the whole buffer
371 crop = mActiveBuffer->getBounds();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700372 } else {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800373 // if we don't have a buffer yet, we use an empty/invalid crop
Mathias Agopian4fec8732012-06-29 14:12:52 -0700374 crop.makeInvalid();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700375 }
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700376 return crop;
377}
378
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700379static Rect reduce(const Rect& win, const Region& exclude) {
380 if (CC_LIKELY(exclude.isEmpty())) {
381 return win;
382 }
383 if (exclude.isRect()) {
384 return win.reduce(exclude.getBounds());
385 }
386 return Region(win).subtract(exclude).getBounds();
387}
388
Robert Carr1f0a16a2016-10-24 16:27:39 -0700389Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
390 const Layer::State& s(getDrawingState());
391 Rect win(s.active.w, s.active.h);
392
393 if (!s.crop.isEmpty()) {
394 win.intersect(s.crop, &win);
395 }
396
397 Transform t = getTransform();
398 win = t.transform(win);
399
400 const sp<Layer>& p = getParent();
401 // Now we need to calculate the parent bounds, so we can clip ourselves to those.
402 // When calculating the parent bounds for purposes of clipping,
403 // we don't need to constrain the parent to its transparent region.
404 // The transparent region is an optimization based on the
405 // buffer contents of the layer, but does not affect the space allocated to
406 // it by policy, and thus children should be allowed to extend into the
407 // parent's transparent region. In fact one of the main uses, is to reduce
408 // buffer allocation size in cases where a child window sits behind a main window
409 // (by marking the hole in the parent window as a transparent region)
410 if (p != nullptr) {
411 Rect bounds = p->computeScreenBounds(false);
412 bounds.intersect(win, &win);
413 }
414
415 if (reduceTransparentRegion) {
416 auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
417 win = reduce(win, screenTransparentRegion);
418 }
419
420 return win;
421}
422
Mathias Agopian13127d82013-03-05 17:47:11 -0800423Rect Layer::computeBounds() const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700424 const Layer::State& s(getDrawingState());
Michael Lentine6c925ed2014-09-26 17:55:01 -0700425 return computeBounds(s.activeTransparentRegion);
426}
427
428Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
429 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800430 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700431
432 if (!s.crop.isEmpty()) {
433 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -0800434 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700435
436 Rect bounds = win;
437 const auto& p = getParent();
438 if (p != nullptr) {
Robert Carrde9ec442017-02-08 17:43:36 -0800439 // Look in computeScreenBounds recursive call for explanation of
440 // why we pass false here.
441 bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700442 }
443
444 Transform t = getTransform();
445 if (p != nullptr) {
446 win = t.transform(win);
447 win.intersect(bounds, &win);
448 win = t.inverse().transform(win);
449 }
450
Mathias Agopian6c7f25a2013-05-09 20:37:10 -0700451 // subtract the transparent region and snap to the bounds
Michael Lentine6c925ed2014-09-26 17:55:01 -0700452 return reduce(win, activeTransparentRegion);
Mathias Agopian13127d82013-03-05 17:47:11 -0800453}
454
Robert Carr1f0a16a2016-10-24 16:27:39 -0700455Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
Robert Carrb5d3d262016-03-25 15:08:13 -0700456 // the crop is the area of the window that gets cropped, but not
Mathias Agopian13127d82013-03-05 17:47:11 -0800457 // scaled in any ways.
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700458 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800459
460 // apply the projection's clipping to the window crop in
461 // layerstack space, and convert-back to layer space.
Mathias Agopian6b442672013-07-09 21:24:52 -0700462 // if there are no window scaling involved, this operation will map to full
463 // pixels in the buffer.
464 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
465 // a viewport clipping and a window transform. we should use floating point to fix this.
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700466
467 Rect activeCrop(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700468 if (!s.crop.isEmpty()) {
469 activeCrop = s.crop;
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700470 }
471
Robert Carr1f0a16a2016-10-24 16:27:39 -0700472 Transform t = getTransform();
473 activeCrop = t.transform(activeCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000474 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
475 activeCrop.clear();
476 }
Robert Carrb5d3d262016-03-25 15:08:13 -0700477 if (!s.finalCrop.isEmpty()) {
478 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000479 activeCrop.clear();
480 }
481 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700482 return activeCrop;
483}
484
Dan Stoza5a423ea2017-02-16 14:10:39 -0800485FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
Robert Carr1f0a16a2016-10-24 16:27:39 -0700486 // the content crop is the area of the content that gets scaled to the
487 // layer's size. This is in buffer space.
Dan Stoza5a423ea2017-02-16 14:10:39 -0800488 FloatRect crop = getContentCrop().toFloatRect();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700489
490 // In addition there is a WM-specified crop we pull from our drawing state.
491 const State& s(getDrawingState());
492
493 // Screen space to make reduction to parent crop clearer.
494 Rect activeCrop = computeInitialCrop(hw);
495 const auto& p = getParent();
496 if (p != nullptr) {
497 auto parentCrop = p->computeInitialCrop(hw);
498 activeCrop.intersect(parentCrop, &activeCrop);
499 }
500 Transform t = getTransform();
501 // Back to layer space to work with the content crop.
502 activeCrop = t.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800503
Michael Lentine28ea2172014-11-19 18:32:37 -0800504 // This needs to be here as transform.transform(Rect) computes the
505 // transformed rect and then takes the bounding box of the result before
506 // returning. This means
507 // transform.inverse().transform(transform.transform(Rect)) != Rect
508 // in which case we need to make sure the final rect is clipped to the
509 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000510 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
511 activeCrop.clear();
512 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800513
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700514 // subtract the transparent region and snap to the bounds
515 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
516
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000517 // Transform the window crop to match the buffer coordinate system,
518 // which means using the inverse of the current transform set on the
519 // SurfaceFlingerConsumer.
520 uint32_t invTransform = mCurrentTransform;
Robert Carrcae605c2017-03-29 12:10:31 -0700521 if (getTransformToDisplayInverse()) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000522 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700523 * the code below applies the primary display's inverse transform to the
524 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000525 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700526 uint32_t invTransformOrient =
527 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000528 // calculate the inverse transform
529 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
530 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
531 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800532 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000533 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700534 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
535 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800536 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000537
538 int winWidth = s.active.w;
539 int winHeight = s.active.h;
540 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
541 // If the activeCrop has been rotate the ends are rotated but not
542 // the space itself so when transforming ends back we can't rely on
543 // a modification of the axes of rotation. To account for this we
544 // need to reorient the inverse rotation in terms of the current
545 // axes of rotation.
546 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
547 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
548 if (is_h_flipped == is_v_flipped) {
549 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
550 NATIVE_WINDOW_TRANSFORM_FLIP_H;
551 }
552 winWidth = s.active.h;
553 winHeight = s.active.w;
554 }
555 const Rect winCrop = activeCrop.transform(
556 invTransform, s.active.w, s.active.h);
557
558 // below, crop is intersected with winCrop expressed in crop's coordinate space
559 float xScale = crop.getWidth() / float(winWidth);
560 float yScale = crop.getHeight() / float(winHeight);
561
562 float insetL = winCrop.left * xScale;
563 float insetT = winCrop.top * yScale;
564 float insetR = (winWidth - winCrop.right ) * xScale;
565 float insetB = (winHeight - winCrop.bottom) * yScale;
566
567 crop.left += insetL;
568 crop.top += insetT;
569 crop.right -= insetR;
570 crop.bottom -= insetB;
571
Mathias Agopian13127d82013-03-05 17:47:11 -0800572 return crop;
573}
574
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000575#ifdef USE_HWC2
Robert Carrae060832016-11-28 10:51:00 -0800576void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000577#else
578void Layer::setGeometry(
579 const sp<const DisplayDevice>& hw,
580 HWComposer::HWCLayerInterface& layer)
581#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700582{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000583#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800584 const auto hwcId = displayDevice->getHwcDisplayId();
585 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000586#else
587 layer.setDefaultState();
588#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700589
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700590 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000591#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800592 hwcInfo.forceClientComposition = false;
593
594 if (isSecure() && !displayDevice->isSecure()) {
595 hwcInfo.forceClientComposition = true;
596 }
597
598 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000599#else
600 layer.setSkip(false);
601
602 if (isSecure() && !hw->isSecure()) {
603 layer.setSkip(true);
604 }
605#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700606
Mathias Agopian13127d82013-03-05 17:47:11 -0800607 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700608 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000609#ifdef USE_HWC2
David Revemanecf0fa52017-03-03 11:32:44 -0500610 auto blendMode = HWC2::BlendMode::None;
Robert Carr6452f122017-03-21 10:41:29 -0700611 if (!isOpaque(s) || getAlpha() != 1.0f) {
David Revemanecf0fa52017-03-03 11:32:44 -0500612 blendMode = mPremultipliedAlpha ?
Dan Stoza9e56aa02015-11-02 13:00:03 -0800613 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800614 }
David Revemanecf0fa52017-03-03 11:32:44 -0500615 auto error = hwcLayer->setBlendMode(blendMode);
616 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
617 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
618 to_string(error).c_str(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000619#else
Robert Carr6452f122017-03-21 10:41:29 -0700620 if (!isOpaque(s) || getAlpha() != 0xFF) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000621 layer.setBlending(mPremultipliedAlpha ?
622 HWC_BLENDING_PREMULT :
623 HWC_BLENDING_COVERAGE);
624 }
625#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800626
627 // apply the layer's transform, followed by the display's global transform
628 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700629 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700630 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -0700631 if (!s.crop.isEmpty()) {
632 Rect activeCrop(s.crop);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700633 activeCrop = t.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000634#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000635 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000636#else
637 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
638#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000639 activeCrop.clear();
640 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700641 activeCrop = t.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800642 // This needs to be here as transform.transform(Rect) computes the
643 // transformed rect and then takes the bounding box of the result before
644 // returning. This means
645 // transform.inverse().transform(transform.transform(Rect)) != Rect
646 // in which case we need to make sure the final rect is clipped to the
647 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000648 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
649 activeCrop.clear();
650 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700651 // mark regions outside the crop as transparent
652 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
653 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
654 s.active.w, s.active.h));
655 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
656 activeCrop.left, activeCrop.bottom));
657 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
658 s.active.w, activeCrop.bottom));
659 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700660
661 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700662 if (!s.finalCrop.isEmpty()) {
663 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000664 frame.clear();
665 }
666 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000667#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000668 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
669 frame.clear();
670 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800671 const Transform& tr(displayDevice->getTransform());
672 Rect transformedFrame = tr.transform(frame);
David Revemanecf0fa52017-03-03 11:32:44 -0500673 error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700674 if (error != HWC2::Error::None) {
675 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
676 mName.string(), transformedFrame.left, transformedFrame.top,
677 transformedFrame.right, transformedFrame.bottom,
678 to_string(error).c_str(), static_cast<int32_t>(error));
679 } else {
680 hwcInfo.displayFrame = transformedFrame;
681 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800682
Dan Stoza5a423ea2017-02-16 14:10:39 -0800683 FloatRect sourceCrop = computeCrop(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800684 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700685 if (error != HWC2::Error::None) {
686 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
687 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
688 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
689 static_cast<int32_t>(error));
690 } else {
691 hwcInfo.sourceCrop = sourceCrop;
692 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800693
Robert Carr6452f122017-03-21 10:41:29 -0700694 float alpha = getAlpha();
695 error = hwcLayer->setPlaneAlpha(alpha);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800696 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
Robert Carr6452f122017-03-21 10:41:29 -0700697 "%s (%d)", mName.string(), alpha, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800698 static_cast<int32_t>(error));
699
Robert Carrae060832016-11-28 10:51:00 -0800700 error = hwcLayer->setZOrder(z);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800701 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
Robert Carrae060832016-11-28 10:51:00 -0800702 mName.string(), z, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800703 static_cast<int32_t>(error));
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500704
Albert Chaulk2a589632017-05-04 16:59:44 -0400705 int type = s.type;
706 int appId = s.appId;
707 sp<Layer> parent = mParent.promote();
708 if (parent.get()) {
709 auto& parentState = parent->getDrawingState();
710 type = parentState.type;
711 appId = parentState.appId;
712 }
713
714 error = hwcLayer->setInfo(type, appId);
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500715 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
716 mName.string(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000717#else
718 if (!frame.intersect(hw->getViewport(), &frame)) {
719 frame.clear();
720 }
721 const Transform& tr(hw->getTransform());
722 layer.setFrame(tr.transform(frame));
723 layer.setCrop(computeCrop(hw));
Robert Carr6452f122017-03-21 10:41:29 -0700724 layer.setPlaneAlpha(getAlpha());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000725#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800726
Mathias Agopian29a367b2011-07-12 14:51:45 -0700727 /*
728 * Transformations are applied in this order:
729 * 1) buffer orientation/flip/mirror
730 * 2) state transformation (window manager)
731 * 3) layer orientation (screen orientation)
732 * (NOTE: the matrices are multiplied in reverse order)
733 */
734
735 const Transform bufferOrientation(mCurrentTransform);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700736 Transform transform(tr * t * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700737
Robert Carrcae605c2017-03-29 12:10:31 -0700738 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700739 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700740 * the code below applies the primary display's inverse transform to the
741 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700742 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700743 uint32_t invTransform =
744 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700745 // calculate the inverse transform
746 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
747 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
748 NATIVE_WINDOW_TRANSFORM_FLIP_H;
749 }
Robert Carrcae605c2017-03-29 12:10:31 -0700750
751 /*
752 * Here we cancel out the orientation component of the WM transform.
753 * The scaling and translate components are already included in our bounds
754 * computation so it's enough to just omit it in the composition.
755 * See comment in onDraw with ref to b/36727915 for why.
756 */
757 transform = Transform(invTransform) * tr * bufferOrientation;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700758 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700759
760 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800761 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000762#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800763 if (orientation & Transform::ROT_INVALID) {
764 // we can only handle simple transformation
765 hwcInfo.forceClientComposition = true;
766 } else {
767 auto transform = static_cast<HWC2::Transform>(orientation);
768 auto error = hwcLayer->setTransform(transform);
769 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
770 "%s (%d)", mName.string(), to_string(transform).c_str(),
771 to_string(error).c_str(), static_cast<int32_t>(error));
772 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000773#else
774 if (orientation & Transform::ROT_INVALID) {
775 // we can only handle simple transformation
776 layer.setSkip(true);
777 } else {
778 layer.setTransform(orientation);
779 }
780#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700781}
782
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000783#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800784void Layer::forceClientComposition(int32_t hwcId) {
785 if (mHwcLayers.count(hwcId) == 0) {
786 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
787 return;
788 }
789
790 mHwcLayers[hwcId].forceClientComposition = true;
791}
Dan Stoza9e56aa02015-11-02 13:00:03 -0800792
Dan Stoza9e56aa02015-11-02 13:00:03 -0800793void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
794 // Apply this display's projection's viewport to the visible region
795 // before giving it to the HWC HAL.
796 const Transform& tr = displayDevice->getTransform();
797 const auto& viewport = displayDevice->getViewport();
798 Region visible = tr.transform(visibleRegion.intersect(viewport));
799 auto hwcId = displayDevice->getHwcDisplayId();
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800800 auto& hwcInfo = mHwcLayers[hwcId];
801 auto& hwcLayer = hwcInfo.layer;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800802 auto error = hwcLayer->setVisibleRegion(visible);
803 if (error != HWC2::Error::None) {
804 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
805 to_string(error).c_str(), static_cast<int32_t>(error));
806 visible.dump(LOG_TAG);
807 }
808
809 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
810 if (error != HWC2::Error::None) {
811 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
812 to_string(error).c_str(), static_cast<int32_t>(error));
813 surfaceDamageRegion.dump(LOG_TAG);
814 }
815
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700816 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800817 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700818 setCompositionType(hwcId, HWC2::Composition::Sideband);
819 ALOGV("[%s] Requesting Sideband composition", mName.string());
820 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800821 if (error != HWC2::Error::None) {
822 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
823 mName.string(), mSidebandStream->handle(),
824 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800825 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700826 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800827 }
828
Dan Stoza0a21df72016-07-20 12:52:38 -0700829 // Client layers
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800830 if (hwcInfo.forceClientComposition ||
Dan Stoza0a21df72016-07-20 12:52:38 -0700831 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700832 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800833 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700834 return;
835 }
836
Dan Stoza0a21df72016-07-20 12:52:38 -0700837 // SolidColor layers
838 if (mActiveBuffer == nullptr) {
839 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700840
841 // For now, we only support black for DimLayer
Dan Stoza0a21df72016-07-20 12:52:38 -0700842 error = hwcLayer->setColor({0, 0, 0, 255});
843 if (error != HWC2::Error::None) {
844 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
845 to_string(error).c_str(), static_cast<int32_t>(error));
846 }
Dan Stozac6c89542016-07-27 10:16:52 -0700847
848 // Clear out the transform, because it doesn't make sense absent a
849 // source buffer
850 error = hwcLayer->setTransform(HWC2::Transform::None);
851 if (error != HWC2::Error::None) {
852 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
853 to_string(error).c_str(), static_cast<int32_t>(error));
854 }
855
Dan Stoza0a21df72016-07-20 12:52:38 -0700856 return;
857 }
858
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700859 // Device or Cursor layers
860 if (mPotentialCursor) {
861 ALOGV("[%s] Requesting Cursor composition", mName.string());
862 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800863 } else {
864 ALOGV("[%s] Requesting Device composition", mName.string());
865 setCompositionType(hwcId, HWC2::Composition::Device);
866 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700867
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700868 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
869 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
870 if (error != HWC2::Error::None) {
871 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
872 mCurrentState.dataSpace, to_string(error).c_str(),
873 static_cast<int32_t>(error));
874 }
875
Chia-I Wu06d63de2017-01-04 14:58:51 +0800876 uint32_t hwcSlot = 0;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400877 sp<GraphicBuffer> hwcBuffer;
878 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
879 &hwcSlot, &hwcBuffer);
Chia-I Wu06d63de2017-01-04 14:58:51 +0800880
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700881 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400882 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700883 if (error != HWC2::Error::None) {
884 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
885 mActiveBuffer->handle, to_string(error).c_str(),
886 static_cast<int32_t>(error));
887 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800888}
Courtney Goeltzenleuchter9551fd32016-10-20 17:18:15 -0600889
890android_dataspace Layer::getDataSpace() const {
891 return mCurrentState.dataSpace;
892}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000893#else
894void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
895 HWComposer::HWCLayerInterface& layer) {
896 // we have to set the visible region on every frame because
897 // we currently free it during onLayerDisplayed(), which is called
898 // after HWComposer::commit() -- every frame.
899 // Apply this display's projection's viewport to the visible region
900 // before giving it to the HWC HAL.
901 const Transform& tr = hw->getTransform();
902 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
903 layer.setVisibleRegionScreen(visible);
904 layer.setSurfaceDamage(surfaceDamageRegion);
905 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700906
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000907 if (mSidebandStream.get()) {
908 layer.setSidebandStream(mSidebandStream);
909 } else {
910 // NOTE: buffer can be NULL if the client never drew into this
911 // layer yet, or if we ran out of memory
912 layer.setBuffer(mActiveBuffer);
913 }
914}
915#endif
916
917#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800918void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
919 auto hwcId = displayDevice->getHwcDisplayId();
920 if (mHwcLayers.count(hwcId) == 0 ||
921 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
922 return;
923 }
924
925 // This gives us only the "orientation" component of the transform
926 const State& s(getCurrentState());
927
928 // Apply the layer's transform, followed by the display's global transform
929 // Here we're guaranteed that the layer's transform preserves rects
930 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700931 if (!s.crop.isEmpty()) {
932 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800933 }
934 // Subtract the transparent region and snap to the bounds
935 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700936 Rect frame(getTransform().transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800937 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -0700938 if (!s.finalCrop.isEmpty()) {
939 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000940 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800941 auto& displayTransform(displayDevice->getTransform());
942 auto position = displayTransform.transform(frame);
943
944 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
945 position.top);
946 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
947 "to (%d, %d): %s (%d)", mName.string(), position.left,
948 position.top, to_string(error).c_str(),
949 static_cast<int32_t>(error));
950}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000951#else
952void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
953 HWComposer::HWCLayerInterface& layer) {
954 int fenceFd = -1;
955
956 // TODO: there is a possible optimization here: we only need to set the
957 // acquire fence the first time a new buffer is acquired on EACH display.
958
959 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
960 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
961 if (fence->isValid()) {
962 fenceFd = fence->dup();
963 if (fenceFd == -1) {
964 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
965 }
966 }
967 }
968 layer.setAcquireFenceFd(fenceFd);
969}
970
971Rect Layer::getPosition(
972 const sp<const DisplayDevice>& hw)
973{
974 // this gives us only the "orientation" component of the transform
975 const State& s(getCurrentState());
976
977 // apply the layer's transform, followed by the display's global transform
978 // here we're guaranteed that the layer's transform preserves rects
979 Rect win(s.active.w, s.active.h);
980 if (!s.crop.isEmpty()) {
981 win.intersect(s.crop, &win);
982 }
983 // subtract the transparent region and snap to the bounds
984 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700985 Rect frame(getTransform().transform(bounds));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000986 frame.intersect(hw->getViewport(), &frame);
987 if (!s.finalCrop.isEmpty()) {
988 frame.intersect(s.finalCrop, &frame);
989 }
990 const Transform& tr(hw->getTransform());
991 return Rect(tr.transform(frame));
992}
993#endif
Riley Andrews03414a12014-07-01 14:22:59 -0700994
Mathias Agopian13127d82013-03-05 17:47:11 -0800995// ---------------------------------------------------------------------------
996// drawing...
997// ---------------------------------------------------------------------------
998
999void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -08001000 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -08001001}
1002
Dan Stozac7014012014-02-14 15:03:43 -08001003void Layer::draw(const sp<const DisplayDevice>& hw,
1004 bool useIdentityTransform) const {
1005 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001006}
1007
Dan Stozac7014012014-02-14 15:03:43 -08001008void Layer::draw(const sp<const DisplayDevice>& hw) const {
1009 onDraw(hw, Region(hw->bounds()), false);
1010}
1011
Robert Carrcae605c2017-03-29 12:10:31 -07001012static constexpr mat4 inverseOrientation(uint32_t transform) {
1013 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1014 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1015 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1016 mat4 tr;
1017
1018 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1019 tr = tr * rot90;
1020 }
1021 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1022 tr = tr * flipH;
1023 }
1024 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1025 tr = tr * flipV;
1026 }
1027 return inverse(tr);
1028}
1029
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001030/*
1031 * onDraw will draw the current layer onto the presentable buffer
1032 */
Dan Stozac7014012014-02-14 15:03:43 -08001033void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
1034 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001035{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001036 ATRACE_CALL();
1037
Mathias Agopiana67932f2011-04-20 14:20:59 -07001038 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001039 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -07001040 // in fact never been drawn into. This happens frequently with
1041 // SurfaceView because the WindowManager can't know when the client
1042 // has drawn the first time.
1043
1044 // If there is nothing under us, we paint the screen in black, otherwise
1045 // we just skip this update.
1046
1047 // figure out if there is something below us
1048 Region under;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001049 bool finished = false;
Dan Stoza412903f2017-04-27 13:42:17 -07001050 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001051 if (finished || layer == static_cast<Layer const*>(this)) {
1052 finished = true;
1053 return;
1054 }
Mathias Agopian42977342012-08-05 00:40:46 -07001055 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Robert Carr1f0a16a2016-10-24 16:27:39 -07001056 });
Mathias Agopian179169e2010-05-06 20:21:45 -07001057 // if not everything below us is covered, we plug the holes!
1058 Region holes(clip.subtract(under));
1059 if (!holes.isEmpty()) {
Fabien Sanglard17487192016-12-07 13:03:32 -08001060 clearWithOpenGL(hw, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -07001061 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001062 return;
1063 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001064
Andy McFadden97eba892012-12-11 15:21:45 -08001065 // Bind the current buffer to the GL texture, and wait for it to be
1066 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001067 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1068 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -08001069 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -07001070 // Go ahead and draw the buffer anyway; no matter what we do the screen
1071 // is probably going to have something visibly wrong.
1072 }
1073
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001074 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1075
Mathias Agopian875d8e12013-06-07 15:35:48 -07001076 RenderEngine& engine(mFlinger->getRenderEngine());
1077
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001078 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -07001079 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -07001080 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -07001081
1082 // Query the texture matrix given our current filtering mode.
1083 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001084 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1085 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -07001086
Robert Carrcae605c2017-03-29 12:10:31 -07001087 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001088
1089 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -07001090 * the code below applies the primary display's inverse transform to
1091 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001092 */
Pablo Ceballos021623b2016-04-15 17:31:51 -07001093 uint32_t transform =
1094 DisplayDevice::getPrimaryDisplayOrientationTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001095 mat4 tr = inverseOrientation(transform);
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001096
Robert Carrcae605c2017-03-29 12:10:31 -07001097 /**
1098 * TODO(b/36727915): This is basically a hack.
1099 *
1100 * Ensure that regardless of the parent transformation,
1101 * this buffer is always transformed from native display
1102 * orientation to display orientation. For example, in the case
1103 * of a camera where the buffer remains in native orientation,
1104 * we want the pixels to always be upright.
1105 */
1106 if (getParent() != nullptr) {
1107 const auto parentTransform = getParent()->getTransform();
1108 tr = tr * inverseOrientation(parentTransform.getOrientation());
1109 }
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001110
1111 // and finally apply it to the original texture matrix
1112 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1113 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1114 }
1115
Jamie Genniscbb1a952012-05-08 17:05:52 -07001116 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -07001117 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1118 mTexture.setFiltering(useFiltering);
1119 mTexture.setMatrix(textureMatrix);
1120
1121 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -07001122 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001123 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -07001124 }
Fabien Sanglard85789802016-12-07 13:08:24 -08001125 drawWithOpenGL(hw, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001126 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001127}
1128
Mathias Agopian13127d82013-03-05 17:47:11 -08001129
Dan Stozac7014012014-02-14 15:03:43 -08001130void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard17487192016-12-07 13:03:32 -08001131 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -08001132 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001133{
Mathias Agopian19733a32013-08-28 18:13:56 -07001134 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -08001135 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -07001136 engine.setupFillWithColor(red, green, blue, alpha);
1137 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -08001138}
1139
1140void Layer::clearWithOpenGL(
Fabien Sanglard17487192016-12-07 13:03:32 -08001141 const sp<const DisplayDevice>& hw) const {
1142 clearWithOpenGL(hw, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001143}
1144
Dan Stozac7014012014-02-14 15:03:43 -08001145void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard85789802016-12-07 13:08:24 -08001146 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001147 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001148
Dan Stozac7014012014-02-14 15:03:43 -08001149 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001150
Mathias Agopian13127d82013-03-05 17:47:11 -08001151 /*
1152 * NOTE: the way we compute the texture coordinates here produces
1153 * different results than when we take the HWC path -- in the later case
1154 * the "source crop" is rounded to texel boundaries.
1155 * This can produce significantly different results when the texture
1156 * is scaled by a large amount.
1157 *
1158 * The GL code below is more logical (imho), and the difference with
1159 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001160 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001161 * GL composition when a buffer scaling is applied (maybe with some
1162 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1163 * like more of a hack.
1164 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001165 Rect win(computeBounds());
1166
Robert Carr1f0a16a2016-10-24 16:27:39 -07001167 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -07001168 if (!s.finalCrop.isEmpty()) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001169 win = t.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001170 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001171 win.clear();
1172 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001173 win = t.inverse().transform(win);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001174 if (!win.intersect(computeBounds(), &win)) {
1175 win.clear();
1176 }
1177 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001178
Mathias Agopian3f844832013-08-07 21:24:32 -07001179 float left = float(win.left) / float(s.active.w);
1180 float top = float(win.top) / float(s.active.h);
1181 float right = float(win.right) / float(s.active.w);
1182 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001183
Mathias Agopian875d8e12013-06-07 15:35:48 -07001184 // TODO: we probably want to generate the texture coords with the mesh
1185 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001186 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1187 texCoords[0] = vec2(left, 1.0f - top);
1188 texCoords[1] = vec2(left, 1.0f - bottom);
1189 texCoords[2] = vec2(right, 1.0f - bottom);
1190 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001191
Mathias Agopian875d8e12013-06-07 15:35:48 -07001192 RenderEngine& engine(mFlinger->getRenderEngine());
Robert Carr6452f122017-03-21 10:41:29 -07001193 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), getAlpha());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001194#ifdef USE_HWC2
1195 engine.setSourceDataSpace(mCurrentState.dataSpace);
1196#endif
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001197 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001198 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001199}
1200
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001201#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001202void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1203 bool callIntoHwc) {
1204 if (mHwcLayers.count(hwcId) == 0) {
1205 ALOGE("setCompositionType called without a valid HWC layer");
1206 return;
1207 }
1208 auto& hwcInfo = mHwcLayers[hwcId];
1209 auto& hwcLayer = hwcInfo.layer;
1210 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1211 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1212 if (hwcInfo.compositionType != type) {
1213 ALOGV(" actually setting");
1214 hwcInfo.compositionType = type;
1215 if (callIntoHwc) {
1216 auto error = hwcLayer->setCompositionType(type);
1217 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1218 "composition type %s: %s (%d)", mName.string(),
1219 to_string(type).c_str(), to_string(error).c_str(),
1220 static_cast<int32_t>(error));
1221 }
1222 }
1223}
1224
1225HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001226 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1227 // If we're querying the composition type for a display that does not
1228 // have a HWC counterpart, then it will always be Client
1229 return HWC2::Composition::Client;
1230 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001231 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001232 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001233 return HWC2::Composition::Invalid;
1234 }
1235 return mHwcLayers.at(hwcId).compositionType;
1236}
1237
1238void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1239 if (mHwcLayers.count(hwcId) == 0) {
1240 ALOGE("setClearClientTarget called without a valid HWC layer");
1241 return;
1242 }
1243 mHwcLayers[hwcId].clearClientTarget = clear;
1244}
1245
1246bool Layer::getClearClientTarget(int32_t hwcId) const {
1247 if (mHwcLayers.count(hwcId) == 0) {
1248 ALOGE("getClearClientTarget called without a valid HWC layer");
1249 return false;
1250 }
1251 return mHwcLayers.at(hwcId).clearClientTarget;
1252}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001253#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001254
Ruben Brunk1681d952014-06-27 15:51:55 -07001255uint32_t Layer::getProducerStickyTransform() const {
1256 int producerStickyTransform = 0;
1257 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1258 if (ret != OK) {
1259 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1260 strerror(-ret), ret);
1261 return 0;
1262 }
1263 return static_cast<uint32_t>(producerStickyTransform);
1264}
1265
Dan Stozac5da2712016-07-20 15:38:12 -07001266bool Layer::latchUnsignaledBuffers() {
1267 static bool propertyLoaded = false;
1268 static bool latch = false;
1269 static std::mutex mutex;
1270 std::lock_guard<std::mutex> lock(mutex);
1271 if (!propertyLoaded) {
1272 char value[PROPERTY_VALUE_MAX] = {};
1273 property_get("debug.sf.latch_unsignaled", value, "0");
1274 latch = atoi(value);
1275 propertyLoaded = true;
1276 }
1277 return latch;
1278}
1279
Dan Stozacac35382016-01-27 12:21:06 -08001280uint64_t Layer::getHeadFrameNumber() const {
1281 Mutex::Autolock lock(mQueueItemLock);
1282 if (!mQueueItems.empty()) {
1283 return mQueueItems[0].mFrameNumber;
1284 } else {
1285 return mCurrentFrameNumber;
1286 }
1287}
1288
Dan Stoza1ce65812016-06-15 16:26:27 -07001289bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001290#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001291 if (latchUnsignaledBuffers()) {
1292 return true;
1293 }
1294
Dan Stoza1ce65812016-06-15 16:26:27 -07001295 Mutex::Autolock lock(mQueueItemLock);
1296 if (mQueueItems.empty()) {
1297 return true;
1298 }
1299 if (mQueueItems[0].mIsDroppable) {
1300 // Even though this buffer's fence may not have signaled yet, it could
1301 // be replaced by another buffer before it has a chance to, which means
1302 // that it's possible to get into a situation where a buffer is never
1303 // able to be latched. To avoid this, grab this buffer anyway.
1304 return true;
1305 }
1306 return mQueueItems[0].mFence->getSignalTime() != INT64_MAX;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001307#else
1308 return true;
1309#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001310}
1311
Dan Stozacac35382016-01-27 12:21:06 -08001312bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1313 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1314 // Don't bother with a SyncPoint, since we've already latched the
1315 // relevant frame
1316 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001317 }
1318
Dan Stozacac35382016-01-27 12:21:06 -08001319 Mutex::Autolock lock(mLocalSyncPointMutex);
1320 mLocalSyncPoints.push_back(point);
1321 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001322}
1323
Mathias Agopian13127d82013-03-05 17:47:11 -08001324void Layer::setFiltering(bool filtering) {
1325 mFiltering = filtering;
1326}
1327
1328bool Layer::getFiltering() const {
1329 return mFiltering;
1330}
1331
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001332// As documented in libhardware header, formats in the range
1333// 0x100 - 0x1FF are specific to the HAL implementation, and
1334// are known to have no alpha channel
1335// TODO: move definition for device-specific range into
1336// hardware.h, instead of using hard-coded values here.
1337#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1338
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001339bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001340 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1341 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001342 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001343 switch (format) {
1344 case HAL_PIXEL_FORMAT_RGBA_8888:
1345 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001346 case HAL_PIXEL_FORMAT_RGBA_FP16:
Romain Guy541f2262017-02-10 18:50:17 -08001347 case HAL_PIXEL_FORMAT_RGBA_1010102:
Mathias Agopiandd533712013-07-26 15:31:39 -07001348 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001349 }
1350 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001351 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001352}
1353
Mathias Agopian13127d82013-03-05 17:47:11 -08001354// ----------------------------------------------------------------------------
1355// local state
1356// ----------------------------------------------------------------------------
1357
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001358static void boundPoint(vec2* point, const Rect& crop) {
1359 if (point->x < crop.left) {
1360 point->x = crop.left;
1361 }
1362 if (point->x > crop.right) {
1363 point->x = crop.right;
1364 }
1365 if (point->y < crop.top) {
1366 point->y = crop.top;
1367 }
1368 if (point->y > crop.bottom) {
1369 point->y = crop.bottom;
1370 }
1371}
1372
Dan Stozac7014012014-02-14 15:03:43 -08001373void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1374 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001375{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001376 const Layer::State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001377 const Transform hwTransform(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001378 const uint32_t hw_h = hw->getHeight();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001379 Rect win = computeBounds();
Mathias Agopian3f844832013-08-07 21:24:32 -07001380
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001381 vec2 lt = vec2(win.left, win.top);
1382 vec2 lb = vec2(win.left, win.bottom);
1383 vec2 rb = vec2(win.right, win.bottom);
1384 vec2 rt = vec2(win.right, win.top);
1385
Robert Carr1f0a16a2016-10-24 16:27:39 -07001386 Transform layerTransform = getTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001387 if (!useIdentityTransform) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001388 lt = layerTransform.transform(lt);
1389 lb = layerTransform.transform(lb);
1390 rb = layerTransform.transform(rb);
1391 rt = layerTransform.transform(rt);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001392 }
1393
Robert Carrb5d3d262016-03-25 15:08:13 -07001394 if (!s.finalCrop.isEmpty()) {
1395 boundPoint(&lt, s.finalCrop);
1396 boundPoint(&lb, s.finalCrop);
1397 boundPoint(&rb, s.finalCrop);
1398 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001399 }
1400
Mathias Agopianff2ed702013-09-01 21:36:12 -07001401 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001402 position[0] = hwTransform.transform(lt);
1403 position[1] = hwTransform.transform(lb);
1404 position[2] = hwTransform.transform(rb);
1405 position[3] = hwTransform.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001406 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001407 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001408 }
1409}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001410
Andy McFadden4125a4f2014-01-29 17:17:11 -08001411bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001412{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001413 // if we don't have a buffer yet, we're translucent regardless of the
1414 // layer's opaque flag.
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001415 if (mActiveBuffer == 0) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001416 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001417 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001418
1419 // if the layer has the opaque flag, then we're always opaque,
1420 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001421 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001422}
1423
Dan Stoza23116082015-06-18 14:58:39 -07001424bool Layer::isSecure() const
1425{
1426 const Layer::State& s(mDrawingState);
1427 return (s.flags & layer_state_t::eLayerSecure);
1428}
1429
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001430bool Layer::isProtected() const
1431{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001432 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001433 return (activeBuffer != 0) &&
1434 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1435}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001436
Mathias Agopian13127d82013-03-05 17:47:11 -08001437bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001438 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001439}
1440
1441bool Layer::isCropped() const {
1442 return !mCurrentCrop.isEmpty();
1443}
1444
1445bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1446 return mNeedsFiltering || hw->needsFiltering();
1447}
1448
1449void Layer::setVisibleRegion(const Region& visibleRegion) {
1450 // always called from main thread
1451 this->visibleRegion = visibleRegion;
1452}
1453
1454void Layer::setCoveredRegion(const Region& coveredRegion) {
1455 // always called from main thread
1456 this->coveredRegion = coveredRegion;
1457}
1458
1459void Layer::setVisibleNonTransparentRegion(const Region&
1460 setVisibleNonTransparentRegion) {
1461 // always called from main thread
1462 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1463}
1464
1465// ----------------------------------------------------------------------------
1466// transaction
1467// ----------------------------------------------------------------------------
1468
Dan Stoza7dde5992015-05-22 09:51:44 -07001469void Layer::pushPendingState() {
1470 if (!mCurrentState.modified) {
1471 return;
1472 }
1473
Dan Stoza7dde5992015-05-22 09:51:44 -07001474 // If this transaction is waiting on the receipt of a frame, generate a sync
1475 // point and send it to the remote layer.
Robert Carr0d480722017-01-10 16:42:54 -08001476 if (mCurrentState.barrierLayer != nullptr) {
1477 sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1478 if (barrierLayer == nullptr) {
1479 ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
Dan Stoza7dde5992015-05-22 09:51:44 -07001480 // If we can't promote the layer we are intended to wait on,
1481 // then it is expired or otherwise invalid. Allow this transaction
1482 // to be applied as per normal (no synchronization).
Robert Carr0d480722017-01-10 16:42:54 -08001483 mCurrentState.barrierLayer = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001484 } else {
1485 auto syncPoint = std::make_shared<SyncPoint>(
1486 mCurrentState.frameNumber);
Robert Carr0d480722017-01-10 16:42:54 -08001487 if (barrierLayer->addSyncPoint(syncPoint)) {
Dan Stozacac35382016-01-27 12:21:06 -08001488 mRemoteSyncPoints.push_back(std::move(syncPoint));
1489 } else {
1490 // We already missed the frame we're supposed to synchronize
1491 // on, so go ahead and apply the state update
Robert Carr0d480722017-01-10 16:42:54 -08001492 mCurrentState.barrierLayer = nullptr;
Dan Stozacac35382016-01-27 12:21:06 -08001493 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001494 }
1495
Dan Stoza7dde5992015-05-22 09:51:44 -07001496 // Wake us up to check if the frame has been received
1497 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001498 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001499 }
1500 mPendingStates.push_back(mCurrentState);
1501}
1502
Pablo Ceballos05289c22016-04-14 15:49:55 -07001503void Layer::popPendingState(State* stateToCommit) {
1504 auto oldFlags = stateToCommit->flags;
1505 *stateToCommit = mPendingStates[0];
1506 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1507 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001508
1509 mPendingStates.removeAt(0);
1510}
1511
Pablo Ceballos05289c22016-04-14 15:49:55 -07001512bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001513 bool stateUpdateAvailable = false;
1514 while (!mPendingStates.empty()) {
Robert Carr0d480722017-01-10 16:42:54 -08001515 if (mPendingStates[0].barrierLayer != nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001516 if (mRemoteSyncPoints.empty()) {
1517 // If we don't have a sync point for this, apply it anyway. It
1518 // will be visually wrong, but it should keep us from getting
1519 // into too much trouble.
1520 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001521 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001522 stateUpdateAvailable = true;
1523 continue;
1524 }
1525
Dan Stozacac35382016-01-27 12:21:06 -08001526 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1527 mPendingStates[0].frameNumber) {
1528 ALOGE("[%s] Unexpected sync point frame number found",
1529 mName.string());
1530
1531 // Signal our end of the sync point and then dispose of it
1532 mRemoteSyncPoints.front()->setTransactionApplied();
1533 mRemoteSyncPoints.pop_front();
1534 continue;
1535 }
1536
Dan Stoza7dde5992015-05-22 09:51:44 -07001537 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1538 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001539 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001540 stateUpdateAvailable = true;
1541
1542 // Signal our end of the sync point and then dispose of it
1543 mRemoteSyncPoints.front()->setTransactionApplied();
1544 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001545 } else {
1546 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001547 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001548 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001549 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001550 stateUpdateAvailable = true;
1551 }
1552 }
1553
1554 // If we still have pending updates, wake SurfaceFlinger back up and point
1555 // it at this layer so we can process them
1556 if (!mPendingStates.empty()) {
1557 setTransactionFlags(eTransactionNeeded);
1558 mFlinger->setTransactionFlags(eTraversalNeeded);
1559 }
1560
1561 mCurrentState.modified = false;
1562 return stateUpdateAvailable;
1563}
1564
1565void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001566 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001567 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001568 Mutex::Autolock lock(mLocalSyncPointMutex);
1569 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001570 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001571 point->setFrameAvailable();
1572 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001573 }
1574}
1575
Mathias Agopian13127d82013-03-05 17:47:11 -08001576uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001577 ATRACE_CALL();
1578
Dan Stoza7dde5992015-05-22 09:51:44 -07001579 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001580 Layer::State c = getCurrentState();
1581 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001582 return 0;
1583 }
1584
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001585 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001586
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001587 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1588 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001589
1590 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001591 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001592 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001593 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001594 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001595 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001596 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001597 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001598 this, getName().string(), mCurrentTransform,
1599 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001600 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001601 c.crop.left,
1602 c.crop.top,
1603 c.crop.right,
1604 c.crop.bottom,
1605 c.crop.getWidth(),
1606 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001607 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001608 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001609 s.crop.left,
1610 s.crop.top,
1611 s.crop.right,
1612 s.crop.bottom,
1613 s.crop.getWidth(),
1614 s.crop.getHeight(),
1615 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001616
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001617 // record the new size, form this point on, when the client request
1618 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001619 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001620 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001621 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001622
Robert Carr82364e32016-05-15 11:27:47 -07001623 const bool resizePending = (c.requested.w != c.active.w) ||
1624 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001625 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001626 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001627 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001628 // if we have a pending resize, unless we are in fixed-size mode.
1629 // the drawing state will be updated only once we receive a buffer
1630 // with the correct size.
1631 //
1632 // in particular, we want to make sure the clip (which is part
1633 // of the geometry state) is latched together with the size but is
1634 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001635 //
1636 // If a sideband stream is attached, however, we want to skip this
1637 // optimization so that transactions aren't missed when a buffer
1638 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001639
1640 flags |= eDontUpdateGeometryState;
1641 }
1642 }
1643
Rob Carra3ed0322017-05-16 19:40:52 +00001644 // always set active to requested, unless we're asked not to
1645 // this is used by Layer, which special cases resizes.
1646 if (flags & eDontUpdateGeometryState) {
1647 } else {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001648 Layer::State& editCurrentState(getCurrentState());
Rob Carra3ed0322017-05-16 19:40:52 +00001649 if (mFreezePositionUpdates) {
Robert Carr82364e32016-05-15 11:27:47 -07001650 float tx = c.active.transform.tx();
1651 float ty = c.active.transform.ty();
1652 c.active = c.requested;
1653 c.active.transform.set(tx, ty);
1654 editCurrentState.active = c.active;
1655 } else {
1656 editCurrentState.active = editCurrentState.requested;
1657 c.active = c.requested;
1658 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001659 }
1660
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001661 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001662 // invalidate and recompute the visible regions if needed
1663 flags |= Layer::eVisibleRegion;
1664 }
1665
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001666 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001667 // invalidate and recompute the visible regions if needed
1668 flags |= eVisibleRegion;
1669 this->contentDirty = true;
1670
1671 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001672 const uint8_t type = c.active.transform.getType();
1673 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001674 (type >= Transform::SCALE));
1675 }
1676
Dan Stozac8145172016-04-28 16:29:06 -07001677 // If the layer is hidden, signal and clear out all local sync points so
1678 // that transactions for layers depending on this layer's frames becoming
1679 // visible are not blocked
1680 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001681 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001682 }
1683
Mathias Agopian13127d82013-03-05 17:47:11 -08001684 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001685 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001686 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001687}
1688
Pablo Ceballos05289c22016-04-14 15:49:55 -07001689void Layer::commitTransaction(const State& stateToCommit) {
1690 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001691}
1692
Mathias Agopian13127d82013-03-05 17:47:11 -08001693uint32_t Layer::getTransactionFlags(uint32_t flags) {
1694 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1695}
1696
1697uint32_t Layer::setTransactionFlags(uint32_t flags) {
1698 return android_atomic_or(flags, &mTransactionFlags);
1699}
1700
Robert Carr82364e32016-05-15 11:27:47 -07001701bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001702 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001703 return false;
1704 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001705
1706 // We update the requested and active position simultaneously because
1707 // we want to apply the position portion of the transform matrix immediately,
1708 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001709 mCurrentState.requested.transform.set(x, y);
Rob Carra3ed0322017-05-16 19:40:52 +00001710 if (immediate && !mFreezePositionUpdates) {
Robert Carr82364e32016-05-15 11:27:47 -07001711 mCurrentState.active.transform.set(x, y);
1712 }
Rob Carra3ed0322017-05-16 19:40:52 +00001713 mFreezePositionUpdates = mFreezePositionUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001714
Dan Stoza7dde5992015-05-22 09:51:44 -07001715 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001716 setTransactionFlags(eTransactionNeeded);
1717 return true;
1718}
Robert Carr82364e32016-05-15 11:27:47 -07001719
Robert Carr1f0a16a2016-10-24 16:27:39 -07001720bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1721 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1722 if (idx < 0) {
1723 return false;
1724 }
1725 if (childLayer->setLayer(z)) {
1726 mCurrentChildren.removeAt(idx);
1727 mCurrentChildren.add(childLayer);
1728 }
1729 return true;
1730}
1731
Robert Carrae060832016-11-28 10:51:00 -08001732bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001733 if (mCurrentState.z == z)
1734 return false;
1735 mCurrentState.sequence++;
1736 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001737 mCurrentState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001738
1739 // Discard all relative layering.
1740 if (mCurrentState.zOrderRelativeOf != nullptr) {
1741 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1742 if (strongRelative != nullptr) {
1743 strongRelative->removeZOrderRelative(this);
1744 }
1745 mCurrentState.zOrderRelativeOf = nullptr;
1746 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001747 setTransactionFlags(eTransactionNeeded);
1748 return true;
1749}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001750
Robert Carrdb66e622017-04-10 16:55:57 -07001751void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1752 mCurrentState.zOrderRelatives.remove(relative);
1753 mCurrentState.sequence++;
1754 mCurrentState.modified = true;
1755 setTransactionFlags(eTransactionNeeded);
1756}
1757
1758void Layer::addZOrderRelative(const wp<Layer>& relative) {
1759 mCurrentState.zOrderRelatives.add(relative);
1760 mCurrentState.modified = true;
1761 mCurrentState.sequence++;
1762 setTransactionFlags(eTransactionNeeded);
1763}
1764
1765bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1766 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1767 if (handle == nullptr) {
1768 return false;
1769 }
1770 sp<Layer> relative = handle->owner.promote();
1771 if (relative == nullptr) {
1772 return false;
1773 }
1774
1775 mCurrentState.sequence++;
1776 mCurrentState.modified = true;
1777 mCurrentState.z = z;
1778
1779 mCurrentState.zOrderRelativeOf = relative;
1780 relative->addZOrderRelative(this);
1781
1782 setTransactionFlags(eTransactionNeeded);
1783
1784 return true;
1785}
1786
Mathias Agopian13127d82013-03-05 17:47:11 -08001787bool Layer::setSize(uint32_t w, uint32_t h) {
1788 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1789 return false;
1790 mCurrentState.requested.w = w;
1791 mCurrentState.requested.h = h;
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}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001796#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001797bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001798#else
1799bool Layer::setAlpha(uint8_t alpha) {
1800#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001801 if (mCurrentState.alpha == alpha)
1802 return false;
1803 mCurrentState.sequence++;
1804 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001805 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001806 setTransactionFlags(eTransactionNeeded);
1807 return true;
1808}
1809bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1810 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001811 mCurrentState.requested.transform.set(
Robert Carrcb6e1e32017-02-21 19:48:26 -08001812 matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001813 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001814 setTransactionFlags(eTransactionNeeded);
1815 return true;
1816}
1817bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001818 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001819 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001820 setTransactionFlags(eTransactionNeeded);
1821 return true;
1822}
1823bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1824 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1825 if (mCurrentState.flags == newFlags)
1826 return false;
1827 mCurrentState.sequence++;
1828 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001829 mCurrentState.mask = mask;
1830 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001831 setTransactionFlags(eTransactionNeeded);
1832 return true;
1833}
Robert Carr99e27f02016-06-16 15:18:02 -07001834
1835bool Layer::setCrop(const Rect& crop, bool immediate) {
Rob Carra3ed0322017-05-16 19:40:52 +00001836 if (mCurrentState.crop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001837 return false;
1838 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001839 mCurrentState.requestedCrop = crop;
Rob Carra3ed0322017-05-16 19:40:52 +00001840 if (immediate) {
Robert Carr99e27f02016-06-16 15:18:02 -07001841 mCurrentState.crop = crop;
1842 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001843 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001844 setTransactionFlags(eTransactionNeeded);
1845 return true;
1846}
Robert Carr8d5227b2017-03-16 15:41:03 -07001847
1848bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
Rob Carra3ed0322017-05-16 19:40:52 +00001849 if (mCurrentState.finalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001850 return false;
1851 mCurrentState.sequence++;
Robert Carr8d5227b2017-03-16 15:41:03 -07001852 mCurrentState.requestedFinalCrop = crop;
Rob Carra3ed0322017-05-16 19:40:52 +00001853 if (immediate) {
Robert Carr8d5227b2017-03-16 15:41:03 -07001854 mCurrentState.finalCrop = crop;
1855 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001856 mCurrentState.modified = true;
1857 setTransactionFlags(eTransactionNeeded);
1858 return true;
1859}
Mathias Agopian13127d82013-03-05 17:47:11 -08001860
Robert Carrc3574f72016-03-24 12:19:32 -07001861bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1862 if (scalingMode == mOverrideScalingMode)
1863 return false;
1864 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001865 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001866 return true;
1867}
1868
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001869void Layer::setInfo(uint32_t type, uint32_t appId) {
1870 mCurrentState.appId = appId;
1871 mCurrentState.type = type;
1872 mCurrentState.modified = true;
1873 setTransactionFlags(eTransactionNeeded);
1874}
1875
Robert Carrc3574f72016-03-24 12:19:32 -07001876uint32_t Layer::getEffectiveScalingMode() const {
1877 if (mOverrideScalingMode >= 0) {
1878 return mOverrideScalingMode;
1879 }
1880 return mCurrentScalingMode;
1881}
1882
Mathias Agopian13127d82013-03-05 17:47:11 -08001883bool Layer::setLayerStack(uint32_t layerStack) {
1884 if (mCurrentState.layerStack == layerStack)
1885 return false;
1886 mCurrentState.sequence++;
1887 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001888 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001889 setTransactionFlags(eTransactionNeeded);
1890 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001891}
1892
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07001893bool Layer::setDataSpace(android_dataspace dataSpace) {
1894 if (mCurrentState.dataSpace == dataSpace)
1895 return false;
1896 mCurrentState.sequence++;
1897 mCurrentState.dataSpace = dataSpace;
1898 mCurrentState.modified = true;
1899 setTransactionFlags(eTransactionNeeded);
1900 return true;
1901}
1902
Robert Carr1f0a16a2016-10-24 16:27:39 -07001903uint32_t Layer::getLayerStack() const {
1904 auto p = getParent();
1905 if (p == nullptr) {
1906 return getDrawingState().layerStack;
1907 }
1908 return p->getLayerStack();
1909}
1910
Robert Carr0d480722017-01-10 16:42:54 -08001911void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
Dan Stoza7dde5992015-05-22 09:51:44 -07001912 uint64_t frameNumber) {
Robert Carr0d480722017-01-10 16:42:54 -08001913 mCurrentState.barrierLayer = barrierLayer;
Dan Stoza7dde5992015-05-22 09:51:44 -07001914 mCurrentState.frameNumber = frameNumber;
1915 // We don't set eTransactionNeeded, because just receiving a deferral
1916 // request without any other state updates shouldn't actually induce a delay
1917 mCurrentState.modified = true;
1918 pushPendingState();
Robert Carr0d480722017-01-10 16:42:54 -08001919 mCurrentState.barrierLayer = nullptr;
Dan Stoza792e5292016-02-11 11:43:58 -08001920 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07001921 mCurrentState.modified = false;
Robert Carr0d480722017-01-10 16:42:54 -08001922 ALOGE("Deferred transaction");
1923}
1924
1925void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
1926 uint64_t frameNumber) {
1927 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
1928 deferTransactionUntil(handle->owner.promote(), frameNumber);
Dan Stoza7dde5992015-05-22 09:51:44 -07001929}
1930
Dan Stozaee44edd2015-03-23 15:50:23 -07001931void Layer::useSurfaceDamage() {
1932 if (mFlinger->mForceFullDamage) {
1933 surfaceDamageRegion = Region::INVALID_REGION;
1934 } else {
1935 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1936 }
1937}
1938
1939void Layer::useEmptyDamage() {
1940 surfaceDamageRegion.clear();
1941}
1942
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001943// ----------------------------------------------------------------------------
1944// pageflip handling...
1945// ----------------------------------------------------------------------------
1946
Dan Stoza6b9454d2014-11-07 16:00:59 -08001947bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001948 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07001949 return true;
1950 }
1951
Dan Stoza6b9454d2014-11-07 16:00:59 -08001952 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001953 if (mQueueItems.empty()) {
1954 return false;
1955 }
1956 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001957 nsecs_t expectedPresent =
1958 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001959
1960 // Ignore timestamps more than a second in the future
1961 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1962 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1963 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1964 expectedPresent);
1965
1966 bool isDue = timestamp < expectedPresent;
1967 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001968}
1969
Brian Andersond6927fb2016-07-23 23:37:30 -07001970bool Layer::onPreComposition(nsecs_t refreshStartTime) {
1971 if (mBufferLatched) {
1972 Mutex::Autolock lock(mFrameEventHistoryMutex);
1973 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
1974 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08001975 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001976 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001977}
1978
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001979bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
Brian Anderson3d4039d2016-09-23 16:31:30 -07001980 const std::shared_ptr<FenceTime>& presentFence,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001981 const CompositorTiming& compositorTiming) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001982 mAcquireTimeline.updateSignalTimes();
1983 mReleaseTimeline.updateSignalTimes();
1984
Brian Andersond6927fb2016-07-23 23:37:30 -07001985 // mFrameLatencyNeeded is true when a new frame was latched for the
1986 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08001987 if (!mFrameLatencyNeeded)
1988 return false;
1989
Fabien Sanglard28e98082016-12-05 10:19:46 -08001990 // Update mFrameEventHistory.
1991 {
1992 Mutex::Autolock lock(mFrameEventHistoryMutex);
1993 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001994 glDoneFence, presentFence, compositorTiming);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001995 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08001996
1997 // Update mFrameTracker.
1998 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1999 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
2000
Brian Anderson3d4039d2016-09-23 16:31:30 -07002001 std::shared_ptr<FenceTime> frameReadyFence =
2002 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08002003 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002004 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002005 } else {
2006 // There was no fence for this frame, so assume that it was ready
2007 // to be presented at the desired present time.
2008 mFrameTracker.setFrameReadyTime(desiredPresentTime);
2009 }
2010
Brian Anderson3d4039d2016-09-23 16:31:30 -07002011 if (presentFence->isValid()) {
2012 mFrameTracker.setActualPresentFence(
2013 std::shared_ptr<FenceTime>(presentFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002014 } else {
2015 // The HWC doesn't support present fences, so use the refresh
2016 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002017 mFrameTracker.setActualPresentTime(
2018 mFlinger->getHwComposer().getRefreshTimestamp(
2019 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002020 }
2021
2022 mFrameTracker.advanceFrame();
2023 mFrameLatencyNeeded = false;
2024 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002025}
2026
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002027#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07002028void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Brian Anderson5ea5e592016-12-01 16:54:33 -08002029 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2030 return;
2031 }
2032
Brian Anderson3d4039d2016-09-23 16:31:30 -07002033 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002034 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002035 mReleaseTimeline.push(releaseFenceTime);
2036
2037 Mutex::Autolock lock(mFrameEventHistoryMutex);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002038 if (mPreviousFrameNumber != 0) {
2039 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2040 dequeueReadyTime, std::move(releaseFenceTime));
2041 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002042}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002043#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002044
Robert Carr1f0a16a2016-10-24 16:27:39 -07002045bool Layer::isHiddenByPolicy() const {
2046 const Layer::State& s(mDrawingState);
2047 const auto& parent = getParent();
2048 if (parent != nullptr && parent->isHiddenByPolicy()) {
2049 return true;
2050 }
2051 return s.flags & layer_state_t::eLayerHidden;
2052}
2053
Mathias Agopianda27af92012-09-13 18:17:13 -07002054bool Layer::isVisible() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002055#ifdef USE_HWC2
Robert Carr6452f122017-03-21 10:41:29 -07002056 return !(isHiddenByPolicy()) && getAlpha() > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08002057 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002058#else
Robert Carr6452f122017-03-21 10:41:29 -07002059 return !(isHiddenByPolicy()) && getAlpha()
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002060 && (mActiveBuffer != NULL || mSidebandStream != NULL);
2061#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07002062}
2063
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002064bool Layer::allTransactionsSignaled() {
2065 auto headFrameNumber = getHeadFrameNumber();
2066 bool matchingFramesFound = false;
2067 bool allTransactionsApplied = true;
2068 Mutex::Autolock lock(mLocalSyncPointMutex);
2069
2070 for (auto& point : mLocalSyncPoints) {
2071 if (point->getFrameNumber() > headFrameNumber) {
2072 break;
2073 }
2074 matchingFramesFound = true;
2075
2076 if (!point->frameIsAvailable()) {
2077 // We haven't notified the remote layer that the frame for
2078 // this point is available yet. Notify it now, and then
2079 // abort this attempt to latch.
2080 point->setFrameAvailable();
2081 allTransactionsApplied = false;
2082 break;
2083 }
2084
2085 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2086 }
2087 return !matchingFramesFound || allTransactionsApplied;
2088}
2089
Brian Andersond6927fb2016-07-23 23:37:30 -07002090Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002091{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08002092 ATRACE_CALL();
2093
Jesse Hall399184a2014-03-03 15:42:54 -08002094 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2095 // mSidebandStreamChanged was true
2096 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07002097 if (mSidebandStream != NULL) {
2098 setTransactionFlags(eTransactionNeeded);
2099 mFlinger->setTransactionFlags(eTraversalNeeded);
2100 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07002101 recomputeVisibleRegions = true;
2102
2103 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07002104 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08002105 }
2106
Mathias Agopian4fec8732012-06-29 14:12:52 -07002107 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07002108 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2109 return outDirtyRegion;
2110 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002111
Fabien Sanglard223eb912016-10-13 10:15:06 -07002112 // if we've already called updateTexImage() without going through
2113 // a composition step, we have to skip this layer at this point
2114 // because we cannot call updateTeximage() without a corresponding
2115 // compositionComplete() call.
2116 // we'll trigger an update in onPreComposition().
2117 if (mRefreshPending) {
2118 return outDirtyRegion;
2119 }
2120
2121 // If the head buffer's acquire fence hasn't signaled yet, return and
2122 // try again later
2123 if (!headFenceHasSignaled()) {
2124 mFlinger->signalLayerUpdate();
2125 return outDirtyRegion;
2126 }
2127
2128 // Capture the old state of the layer for comparisons later
2129 const State& s(getDrawingState());
2130 const bool oldOpacity = isOpaque(s);
2131 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2132
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002133 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002134 mFlinger->signalLayerUpdate();
2135 return outDirtyRegion;
2136 }
2137
2138 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2139 // of the buffer queue isn't modified when the buffer queue is returning
2140 // BufferItem's that weren't actually queued. This can happen in shared
2141 // buffer mode.
2142 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002143 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2144 getProducerStickyTransform() != 0, mName.string(),
Rob Carra3ed0322017-05-16 19:40:52 +00002145 mOverrideScalingMode, mFreezePositionUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002146 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2147 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2148 mLastFrameNumberReceived);
2149 if (updateResult == BufferQueue::PRESENT_LATER) {
2150 // Producer doesn't want buffer to be displayed yet. Signal a
2151 // layer update so we check again at the next opportunity.
2152 mFlinger->signalLayerUpdate();
2153 return outDirtyRegion;
2154 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2155 // If the buffer has been rejected, remove it from the shadow queue
2156 // and return early
2157 if (queuedBuffer) {
2158 Mutex::Autolock lock(mQueueItemLock);
2159 mQueueItems.removeAt(0);
2160 android_atomic_dec(&mQueuedFrames);
2161 }
2162 return outDirtyRegion;
2163 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2164 // This can occur if something goes wrong when trying to create the
2165 // EGLImage for this buffer. If this happens, the buffer has already
2166 // been released, so we need to clean up the queue and bug out
2167 // early.
2168 if (queuedBuffer) {
2169 Mutex::Autolock lock(mQueueItemLock);
2170 mQueueItems.clear();
2171 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002172 }
2173
Fabien Sanglard223eb912016-10-13 10:15:06 -07002174 // Once we have hit this state, the shadow queue may no longer
2175 // correctly reflect the incoming BufferQueue's contents, so even if
2176 // updateTexImage starts working, the only safe course of action is
2177 // to continue to ignore updates.
2178 mUpdateTexImageFailed = true;
2179
2180 return outDirtyRegion;
2181 }
2182
2183 if (queuedBuffer) {
2184 // Autolock scope
2185 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2186
2187 Mutex::Autolock lock(mQueueItemLock);
2188
2189 // Remove any stale buffers that have been dropped during
2190 // updateTexImage
2191 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2192 mQueueItems.removeAt(0);
2193 android_atomic_dec(&mQueuedFrames);
2194 }
2195
2196 mQueueItems.removeAt(0);
2197 }
2198
2199
2200 // Decrement the queued-frames count. Signal another event if we
2201 // have more frames pending.
2202 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2203 || mAutoRefresh) {
2204 mFlinger->signalLayerUpdate();
2205 }
2206
Fabien Sanglard223eb912016-10-13 10:15:06 -07002207 // update the active buffer
Chia-I Wu06d63de2017-01-04 14:58:51 +08002208 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2209 &mActiveBufferSlot);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002210 if (mActiveBuffer == NULL) {
2211 // this can only happen if the very first buffer was rejected.
2212 return outDirtyRegion;
2213 }
2214
Brian Andersond6927fb2016-07-23 23:37:30 -07002215 mBufferLatched = true;
2216 mPreviousFrameNumber = mCurrentFrameNumber;
2217 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2218
2219 {
2220 Mutex::Autolock lock(mFrameEventHistoryMutex);
2221 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2222#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002223 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002224 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002225 mReleaseTimeline.push(releaseFenceTime);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002226 if (mPreviousFrameNumber != 0) {
2227 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2228 latchTime, std::move(releaseFenceTime));
2229 }
Brian Andersond6927fb2016-07-23 23:37:30 -07002230#endif
2231 }
2232
Fabien Sanglard223eb912016-10-13 10:15:06 -07002233 mRefreshPending = true;
2234 mFrameLatencyNeeded = true;
2235 if (oldActiveBuffer == NULL) {
2236 // the first time we receive a buffer, we need to trigger a
2237 // geometry invalidation.
2238 recomputeVisibleRegions = true;
2239 }
2240
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002241 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2242
Fabien Sanglard223eb912016-10-13 10:15:06 -07002243 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2244 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2245 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2246 if ((crop != mCurrentCrop) ||
2247 (transform != mCurrentTransform) ||
2248 (scalingMode != mCurrentScalingMode))
2249 {
2250 mCurrentCrop = crop;
2251 mCurrentTransform = transform;
2252 mCurrentScalingMode = scalingMode;
2253 recomputeVisibleRegions = true;
2254 }
2255
2256 if (oldActiveBuffer != NULL) {
2257 uint32_t bufWidth = mActiveBuffer->getWidth();
2258 uint32_t bufHeight = mActiveBuffer->getHeight();
2259 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2260 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002261 recomputeVisibleRegions = true;
2262 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002263 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002264
Fabien Sanglard223eb912016-10-13 10:15:06 -07002265 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2266 if (oldOpacity != isOpaque(s)) {
2267 recomputeVisibleRegions = true;
2268 }
Dan Stozacac35382016-01-27 12:21:06 -08002269
Fabien Sanglard223eb912016-10-13 10:15:06 -07002270 // Remove any sync points corresponding to the buffer which was just
2271 // latched
2272 {
2273 Mutex::Autolock lock(mLocalSyncPointMutex);
2274 auto point = mLocalSyncPoints.begin();
2275 while (point != mLocalSyncPoints.end()) {
2276 if (!(*point)->frameIsAvailable() ||
2277 !(*point)->transactionIsApplied()) {
2278 // This sync point must have been added since we started
2279 // latching. Don't drop it yet.
2280 ++point;
2281 continue;
2282 }
2283
2284 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2285 point = mLocalSyncPoints.erase(point);
2286 } else {
2287 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002288 }
2289 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002290 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002291
2292 // FIXME: postedRegion should be dirty & bounds
2293 Region dirtyRegion(Rect(s.active.w, s.active.h));
2294
2295 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002296 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002297
Mathias Agopian4fec8732012-06-29 14:12:52 -07002298 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002299}
2300
Mathias Agopiana67932f2011-04-20 14:20:59 -07002301uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002302{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002303 // TODO: should we do something special if mSecure is set?
2304 if (mProtectedByApp) {
2305 // need a hardware-protected path to external video sink
2306 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002307 }
Riley Andrews03414a12014-07-01 14:22:59 -07002308 if (mPotentialCursor) {
2309 usage |= GraphicBuffer::USAGE_CURSOR;
2310 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002311 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002312 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002313}
2314
Mathias Agopian84300952012-11-21 16:02:13 -08002315void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002316 uint32_t orientation = 0;
2317 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002318 // The transform hint is used to improve performance, but we can
2319 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002320 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002321 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002322 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002323 if (orientation & Transform::ROT_INVALID) {
2324 orientation = 0;
2325 }
2326 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002327 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002328}
2329
Mathias Agopian13127d82013-03-05 17:47:11 -08002330// ----------------------------------------------------------------------------
2331// debugging
2332// ----------------------------------------------------------------------------
2333
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002334void Layer::dump(String8& result, Colorizer& colorizer) const
Mathias Agopian13127d82013-03-05 17:47:11 -08002335{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002336 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08002337
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002338 colorizer.colorize(result, Colorizer::GREEN);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002339 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002340 "+ %s %p (%s)\n",
2341 getTypeId(), this, getName().string());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002342 colorizer.reset(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002343
Mathias Agopian2ca79392013-04-02 18:30:32 -07002344 s.activeTransparentRegion.dump(result, "transparentRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002345 visibleRegion.dump(result, "visibleRegion");
Dan Stozaee44edd2015-03-23 15:50:23 -07002346 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002347 sp<Client> client(mClientRef.promote());
2348
Mathias Agopian74d211a2013-04-22 16:55:35 +02002349 result.appendFormat( " "
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002350 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2351 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
Mathias Agopian13127d82013-03-05 17:47:11 -08002352 "isOpaque=%1d, invalidate=%1d, "
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002353#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08002354 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002355#else
2356 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2357#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08002358 " client=%p\n",
Robert Carr1f0a16a2016-10-24 16:27:39 -07002359 getLayerStack(), s.z,
2360 s.active.transform.tx(), s.active.transform.ty(),
2361 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07002362 s.crop.left, s.crop.top,
2363 s.crop.right, s.crop.bottom,
2364 s.finalCrop.left, s.finalCrop.top,
2365 s.finalCrop.right, s.finalCrop.bottom,
Andy McFadden4125a4f2014-01-29 17:17:11 -08002366 isOpaque(s), contentDirty,
Mathias Agopian13127d82013-03-05 17:47:11 -08002367 s.alpha, s.flags,
Robert Carr3dcabfa2016-03-01 18:36:58 -08002368 s.active.transform[0][0], s.active.transform[0][1],
2369 s.active.transform[1][0], s.active.transform[1][1],
Mathias Agopian13127d82013-03-05 17:47:11 -08002370 client.get());
Mathias Agopian13127d82013-03-05 17:47:11 -08002371
2372 sp<const GraphicBuffer> buf0(mActiveBuffer);
2373 uint32_t w0=0, h0=0, s0=0, f0=0;
2374 if (buf0 != 0) {
2375 w0 = buf0->getWidth();
2376 h0 = buf0->getHeight();
2377 s0 = buf0->getStride();
2378 f0 = buf0->format;
2379 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02002380 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002381 " "
2382 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2383 " queued-frames=%d, mRefreshPending=%d\n",
2384 mFormat, w0, h0, s0,f0,
2385 mQueuedFrames, mRefreshPending);
2386
Mathias Agopian13127d82013-03-05 17:47:11 -08002387 if (mSurfaceFlingerConsumer != 0) {
Colin Cross3d1d2802016-09-26 18:10:16 -07002388 mSurfaceFlingerConsumer->dumpState(result, " ");
Mathias Agopian13127d82013-03-05 17:47:11 -08002389 }
2390}
2391
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002392#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002393void Layer::miniDumpHeader(String8& result) {
2394 result.append("----------------------------------------");
2395 result.append("---------------------------------------\n");
2396 result.append(" Layer name\n");
2397 result.append(" Z | ");
2398 result.append(" Comp Type | ");
2399 result.append(" Disp Frame (LTRB) | ");
2400 result.append(" Source Crop (LTRB)\n");
2401 result.append("----------------------------------------");
2402 result.append("---------------------------------------\n");
2403}
2404
2405void Layer::miniDump(String8& result, int32_t hwcId) const {
2406 if (mHwcLayers.count(hwcId) == 0) {
2407 return;
2408 }
2409
2410 String8 name;
2411 if (mName.length() > 77) {
2412 std::string shortened;
2413 shortened.append(mName.string(), 36);
2414 shortened.append("[...]");
2415 shortened.append(mName.string() + (mName.length() - 36), 36);
2416 name = shortened.c_str();
2417 } else {
2418 name = mName;
2419 }
2420
2421 result.appendFormat(" %s\n", name.string());
2422
2423 const Layer::State& layerState(getDrawingState());
2424 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2425 result.appendFormat(" %10u | ", layerState.z);
2426 result.appendFormat("%10s | ",
2427 to_string(getCompositionType(hwcId)).c_str());
2428 const Rect& frame = hwcInfo.displayFrame;
2429 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2430 frame.right, frame.bottom);
Dan Stoza5a423ea2017-02-16 14:10:39 -08002431 const FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002432 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2433 crop.right, crop.bottom);
2434
2435 result.append("- - - - - - - - - - - - - - - - - - - - ");
2436 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2437}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002438#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002439
Svetoslavd85084b2014-03-20 10:28:31 -07002440void Layer::dumpFrameStats(String8& result) const {
2441 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002442}
2443
Svetoslavd85084b2014-03-20 10:28:31 -07002444void Layer::clearFrameStats() {
2445 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002446}
2447
Jamie Gennis6547ff42013-07-16 20:12:42 -07002448void Layer::logFrameStats() {
2449 mFrameTracker.logAndResetStats(mName);
2450}
2451
Svetoslavd85084b2014-03-20 10:28:31 -07002452void Layer::getFrameStats(FrameStats* outStats) const {
2453 mFrameTracker.getStats(outStats);
2454}
2455
Brian Andersond6927fb2016-07-23 23:37:30 -07002456void Layer::dumpFrameEvents(String8& result) {
2457 result.appendFormat("- Layer %s (%s, %p)\n",
2458 getName().string(), getTypeId(), this);
2459 Mutex::Autolock lock(mFrameEventHistoryMutex);
2460 mFrameEventHistory.checkFencesForCompletion();
2461 mFrameEventHistory.dump(result);
2462}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002463
Brian Anderson5ea5e592016-12-01 16:54:33 -08002464void Layer::onDisconnect() {
2465 Mutex::Autolock lock(mFrameEventHistoryMutex);
2466 mFrameEventHistory.onDisconnect();
2467}
2468
Brian Anderson3890c392016-07-25 12:48:08 -07002469void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2470 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002471 Mutex::Autolock lock(mFrameEventHistoryMutex);
2472 if (newTimestamps) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002473 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002474 mFrameEventHistory.addQueue(*newTimestamps);
2475 }
2476
Brian Anderson3890c392016-07-25 12:48:08 -07002477 if (outDelta) {
2478 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002479 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002480}
Dan Stozae77c7662016-05-13 11:37:28 -07002481
2482std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2483 bool forceFlush) {
2484 std::vector<OccupancyTracker::Segment> history;
2485 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2486 &history);
2487 if (result != NO_ERROR) {
2488 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2489 result);
2490 return {};
2491 }
2492 return history;
2493}
2494
Robert Carr367c5682016-06-20 11:55:28 -07002495bool Layer::getTransformToDisplayInverse() const {
2496 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2497}
2498
Robert Carr1f0a16a2016-10-24 16:27:39 -07002499void Layer::addChild(const sp<Layer>& layer) {
2500 mCurrentChildren.add(layer);
2501 layer->setParent(this);
2502}
2503
2504ssize_t Layer::removeChild(const sp<Layer>& layer) {
2505 layer->setParent(nullptr);
2506 return mCurrentChildren.remove(layer);
2507}
2508
Robert Carr1db73f62016-12-21 12:58:51 -08002509bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2510 sp<Handle> handle = nullptr;
2511 sp<Layer> newParent = nullptr;
2512 if (newParentHandle == nullptr) {
2513 return false;
2514 }
2515 handle = static_cast<Handle*>(newParentHandle.get());
2516 newParent = handle->owner.promote();
2517 if (newParent == nullptr) {
2518 ALOGE("Unable to promote Layer handle");
2519 return false;
2520 }
2521
2522 for (const sp<Layer>& child : mCurrentChildren) {
2523 newParent->addChild(child);
2524
2525 sp<Client> client(child->mClientRef.promote());
2526 if (client != nullptr) {
2527 client->setParentLayer(newParent);
2528 }
2529 }
2530 mCurrentChildren.clear();
2531
2532 return true;
2533}
2534
Robert Carr9524cb32017-02-13 11:32:32 -08002535bool Layer::detachChildren() {
Dan Stoza412903f2017-04-27 13:42:17 -07002536 traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
Robert Carr9524cb32017-02-13 11:32:32 -08002537 if (child == this) {
2538 return;
2539 }
2540
2541 sp<Client> client(child->mClientRef.promote());
2542 if (client != nullptr) {
2543 client->detachLayer(child);
2544 }
2545 });
2546
2547 return true;
2548}
2549
Robert Carr1f0a16a2016-10-24 16:27:39 -07002550void Layer::setParent(const sp<Layer>& layer) {
2551 mParent = layer;
2552}
2553
2554void Layer::clearSyncPoints() {
2555 for (const auto& child : mCurrentChildren) {
2556 child->clearSyncPoints();
2557 }
2558
2559 Mutex::Autolock lock(mLocalSyncPointMutex);
2560 for (auto& point : mLocalSyncPoints) {
2561 point->setFrameAvailable();
2562 }
2563 mLocalSyncPoints.clear();
2564}
2565
2566int32_t Layer::getZ() const {
2567 return mDrawingState.z;
2568}
2569
Dan Stoza412903f2017-04-27 13:42:17 -07002570LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2571 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2572 "makeTraversalList received invalid stateSet");
2573 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2574 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2575 const State& state = useDrawing ? mDrawingState : mCurrentState;
2576
2577 if (state.zOrderRelatives.size() == 0) {
2578 return children;
Robert Carrdb66e622017-04-10 16:55:57 -07002579 }
2580 LayerVector traverse;
2581
Dan Stoza412903f2017-04-27 13:42:17 -07002582 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07002583 sp<Layer> strongRelative = weakRelative.promote();
2584 if (strongRelative != nullptr) {
2585 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07002586 }
2587 }
2588
Dan Stoza412903f2017-04-27 13:42:17 -07002589 for (const sp<Layer>& child : children) {
Robert Carrdb66e622017-04-10 16:55:57 -07002590 traverse.add(child);
2591 }
2592
2593 return traverse;
2594}
2595
Robert Carr1f0a16a2016-10-24 16:27:39 -07002596/**
Robert Carrdb66e622017-04-10 16:55:57 -07002597 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002598 */
Dan Stoza412903f2017-04-27 13:42:17 -07002599void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2600 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002601
Robert Carr1f0a16a2016-10-24 16:27:39 -07002602 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002603 for (; i < list.size(); i++) {
2604 const auto& relative = list[i];
2605 if (relative->getZ() >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002606 break;
Robert Carrdb66e622017-04-10 16:55:57 -07002607 }
Dan Stoza412903f2017-04-27 13:42:17 -07002608 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002609 }
Dan Stoza412903f2017-04-27 13:42:17 -07002610 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07002611 for (; i < list.size(); i++) {
2612 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002613 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002614 }
2615}
2616
2617/**
Robert Carrdb66e622017-04-10 16:55:57 -07002618 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002619 */
Dan Stoza412903f2017-04-27 13:42:17 -07002620void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2621 const LayerVector::Visitor& visitor) {
2622 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002623
Robert Carr1f0a16a2016-10-24 16:27:39 -07002624 int32_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002625 for (i = list.size()-1; i>=0; i--) {
2626 const auto& relative = list[i];
2627 if (relative->getZ() < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002628 break;
2629 }
Dan Stoza412903f2017-04-27 13:42:17 -07002630 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002631 }
Dan Stoza412903f2017-04-27 13:42:17 -07002632 visitor(this);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002633 for (; i>=0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002634 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002635 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002636 }
2637}
2638
2639Transform Layer::getTransform() const {
2640 Transform t;
2641 const auto& p = getParent();
2642 if (p != nullptr) {
2643 t = p->getTransform();
Robert Carr9b429f42017-04-17 14:56:57 -07002644
2645 // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2646 // it isFixedSize) then there may be additional scaling not accounted
2647 // for in the transform. We need to mirror this scaling in child surfaces
2648 // or we will break the contract where WM can treat child surfaces as
2649 // pixels in the parent surface.
2650 if (p->isFixedSize()) {
Robert Carr1725eee2017-04-26 18:32:15 -07002651 int bufferWidth;
2652 int bufferHeight;
2653 if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2654 bufferWidth = p->mActiveBuffer->getWidth();
2655 bufferHeight = p->mActiveBuffer->getHeight();
2656 } else {
2657 bufferHeight = p->mActiveBuffer->getWidth();
2658 bufferWidth = p->mActiveBuffer->getHeight();
2659 }
Robert Carr9b429f42017-04-17 14:56:57 -07002660 float sx = p->getDrawingState().active.w /
Robert Carr1725eee2017-04-26 18:32:15 -07002661 static_cast<float>(bufferWidth);
Robert Carr9b429f42017-04-17 14:56:57 -07002662 float sy = p->getDrawingState().active.h /
Robert Carr1725eee2017-04-26 18:32:15 -07002663 static_cast<float>(bufferHeight);
Robert Carr9b429f42017-04-17 14:56:57 -07002664 Transform extraParentScaling;
2665 extraParentScaling.set(sx, 0, 0, sy);
2666 t = t * extraParentScaling;
2667 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002668 }
2669 return t * getDrawingState().active.transform;
2670}
2671
Robert Carr6452f122017-03-21 10:41:29 -07002672#ifdef USE_HWC2
2673float Layer::getAlpha() const {
2674 const auto& p = getParent();
2675
2676 float parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0;
2677 return parentAlpha * getDrawingState().alpha;
2678}
2679#else
2680uint8_t Layer::getAlpha() const {
2681 const auto& p = getParent();
2682
2683 float parentAlpha = (p != nullptr) ? (p->getAlpha() / 255.0f) : 1.0;
2684 float drawingAlpha = getDrawingState().alpha / 255.0f;
2685 drawingAlpha = drawingAlpha * parentAlpha;
2686 return static_cast<uint8_t>(std::round(drawingAlpha * 255));
2687}
2688#endif
2689
Robert Carr1f0a16a2016-10-24 16:27:39 -07002690void Layer::commitChildList() {
2691 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2692 const auto& child = mCurrentChildren[i];
2693 child->commitChildList();
2694 }
2695 mDrawingChildren = mCurrentChildren;
2696}
2697
Mathias Agopian13127d82013-03-05 17:47:11 -08002698// ---------------------------------------------------------------------------
2699
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002700}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002701
2702#if defined(__gl_h_)
2703#error "don't include gl/gl.h in this file"
2704#endif
2705
2706#if defined(__gl2_h_)
2707#error "don't include gl2/gl2.h in this file"
2708#endif