blob: 9afc608f86e3dd5e994bc90fbd4aa82997396e54 [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 Andersond6927fb2016-07-23 23:37:30 -070087 mPreviousFrameNumber(-1U),
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),
106 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;
Irvel468051e2016-06-13 16:44:44 -0700170 BufferQueue::createBufferQueue(&producer, &consumer, nullptr, 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
Chia-I Wu06d63de2017-01-04 14:58:51 +0800279void Layer::onBuffersReleased() {
280#ifdef USE_HWC2
281 Mutex::Autolock lock(mHwcBufferCacheMutex);
282
283 for (auto info : mHwcBufferCaches) {
284 info.second.clear();
285 }
286#endif
287}
288
Jesse Hall399184a2014-03-03 15:42:54 -0800289void Layer::onSidebandStreamChanged() {
290 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
291 // mSidebandStreamChanged was false
292 mFlinger->signalLayerUpdate();
293 }
294}
295
Mathias Agopian67106042013-03-14 19:18:13 -0700296// called with SurfaceFlinger::mStateLock from the drawing thread after
297// the layer has been remove from the current state list (and just before
298// it's removed from the drawing state list)
Mathias Agopian13127d82013-03-05 17:47:11 -0800299void Layer::onRemoved() {
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800300 mSurfaceFlingerConsumer->abandon();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700301 for (const auto& child : mCurrentChildren) {
302 child->onRemoved();
303 }
Mathias Agopian48d819a2009-09-10 19:41:18 -0700304}
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700305
Mathias Agopian13127d82013-03-05 17:47:11 -0800306// ---------------------------------------------------------------------------
307// set-up
308// ---------------------------------------------------------------------------
309
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700310const String8& Layer::getName() const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800311 return mName;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800312}
313
Mathias Agopianf9d93272009-06-19 17:00:27 -0700314status_t Layer::setBuffers( uint32_t w, uint32_t h,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800315 PixelFormat format, uint32_t flags)
316{
Mathias Agopianca99fb82010-04-14 16:43:44 -0700317 uint32_t const maxSurfaceDims = min(
Mathias Agopiana4912602012-07-12 14:25:33 -0700318 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
Mathias Agopianca99fb82010-04-14 16:43:44 -0700319
320 // never allow a surface larger than what our underlying GL implementation
321 // can handle.
322 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
Mathias Agopianff615cc2012-02-24 14:58:36 -0800323 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700324 return BAD_VALUE;
325 }
326
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700327 mFormat = format;
Mathias Agopianeff062c2010-08-25 14:59:15 -0700328
Riley Andrews03414a12014-07-01 14:22:59 -0700329 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
Mathias Agopian3165cc22012-08-08 19:42:09 -0700330 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700331 mCurrentOpacity = getOpacityForFormat(format);
332
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800333 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
334 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
335 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700336
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800337 return NO_ERROR;
338}
339
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700340sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800341 Mutex::Autolock _l(mLock);
342
343 LOG_ALWAYS_FATAL_IF(mHasSurface,
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700344 "Layer::getHandle() has already been called");
Mathias Agopian13127d82013-03-05 17:47:11 -0800345
346 mHasSurface = true;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700347
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700348 return new Handle(mFlinger, this);
Mathias Agopian13127d82013-03-05 17:47:11 -0800349}
350
Dan Stozab9b08832014-03-13 11:55:57 -0700351sp<IGraphicBufferProducer> Layer::getProducer() const {
352 return mProducer;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700353}
354
Mathias Agopian13127d82013-03-05 17:47:11 -0800355// ---------------------------------------------------------------------------
356// h/w composer set-up
357// ---------------------------------------------------------------------------
358
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800359Rect Layer::getContentCrop() const {
360 // this is the crop rectangle that applies to the buffer
361 // itself (as opposed to the window)
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700362 Rect crop;
363 if (!mCurrentCrop.isEmpty()) {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800364 // if the buffer crop is defined, we use that
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700365 crop = mCurrentCrop;
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800366 } else if (mActiveBuffer != NULL) {
367 // otherwise we use the whole buffer
368 crop = mActiveBuffer->getBounds();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700369 } else {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800370 // if we don't have a buffer yet, we use an empty/invalid crop
Mathias Agopian4fec8732012-06-29 14:12:52 -0700371 crop.makeInvalid();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700372 }
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700373 return crop;
374}
375
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700376static Rect reduce(const Rect& win, const Region& exclude) {
377 if (CC_LIKELY(exclude.isEmpty())) {
378 return win;
379 }
380 if (exclude.isRect()) {
381 return win.reduce(exclude.getBounds());
382 }
383 return Region(win).subtract(exclude).getBounds();
384}
385
Robert Carr1f0a16a2016-10-24 16:27:39 -0700386Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
387 const Layer::State& s(getDrawingState());
388 Rect win(s.active.w, s.active.h);
389
390 if (!s.crop.isEmpty()) {
391 win.intersect(s.crop, &win);
392 }
393
394 Transform t = getTransform();
395 win = t.transform(win);
396
397 const sp<Layer>& p = getParent();
398 // Now we need to calculate the parent bounds, so we can clip ourselves to those.
399 // When calculating the parent bounds for purposes of clipping,
400 // we don't need to constrain the parent to its transparent region.
401 // The transparent region is an optimization based on the
402 // buffer contents of the layer, but does not affect the space allocated to
403 // it by policy, and thus children should be allowed to extend into the
404 // parent's transparent region. In fact one of the main uses, is to reduce
405 // buffer allocation size in cases where a child window sits behind a main window
406 // (by marking the hole in the parent window as a transparent region)
407 if (p != nullptr) {
408 Rect bounds = p->computeScreenBounds(false);
409 bounds.intersect(win, &win);
410 }
411
412 if (reduceTransparentRegion) {
413 auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
414 win = reduce(win, screenTransparentRegion);
415 }
416
417 return win;
418}
419
Mathias Agopian13127d82013-03-05 17:47:11 -0800420Rect Layer::computeBounds() const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700421 const Layer::State& s(getDrawingState());
Michael Lentine6c925ed2014-09-26 17:55:01 -0700422 return computeBounds(s.activeTransparentRegion);
423}
424
425Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
426 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800427 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700428
429 if (!s.crop.isEmpty()) {
430 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -0800431 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700432
433 Rect bounds = win;
434 const auto& p = getParent();
435 if (p != nullptr) {
Robert Carrde9ec442017-02-08 17:43:36 -0800436 // Look in computeScreenBounds recursive call for explanation of
437 // why we pass false here.
438 bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700439 }
440
441 Transform t = getTransform();
442 if (p != nullptr) {
443 win = t.transform(win);
444 win.intersect(bounds, &win);
445 win = t.inverse().transform(win);
446 }
447
Mathias Agopian6c7f25a2013-05-09 20:37:10 -0700448 // subtract the transparent region and snap to the bounds
Michael Lentine6c925ed2014-09-26 17:55:01 -0700449 return reduce(win, activeTransparentRegion);
Mathias Agopian13127d82013-03-05 17:47:11 -0800450}
451
Robert Carr1f0a16a2016-10-24 16:27:39 -0700452Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
Robert Carrb5d3d262016-03-25 15:08:13 -0700453 // the crop is the area of the window that gets cropped, but not
Mathias Agopian13127d82013-03-05 17:47:11 -0800454 // scaled in any ways.
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700455 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800456
457 // apply the projection's clipping to the window crop in
458 // layerstack space, and convert-back to layer space.
Mathias Agopian6b442672013-07-09 21:24:52 -0700459 // if there are no window scaling involved, this operation will map to full
460 // pixels in the buffer.
461 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
462 // a viewport clipping and a window transform. we should use floating point to fix this.
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700463
464 Rect activeCrop(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700465 if (!s.crop.isEmpty()) {
466 activeCrop = s.crop;
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700467 }
468
Robert Carr1f0a16a2016-10-24 16:27:39 -0700469 Transform t = getTransform();
470 activeCrop = t.transform(activeCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000471 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
472 activeCrop.clear();
473 }
Robert Carrb5d3d262016-03-25 15:08:13 -0700474 if (!s.finalCrop.isEmpty()) {
475 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000476 activeCrop.clear();
477 }
478 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700479 return activeCrop;
480}
481
482gfx::FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
483 // the content crop is the area of the content that gets scaled to the
484 // layer's size. This is in buffer space.
485 gfx::FloatRect crop = getContentCrop().toFloatRect();
486
487 // In addition there is a WM-specified crop we pull from our drawing state.
488 const State& s(getDrawingState());
489
490 // Screen space to make reduction to parent crop clearer.
491 Rect activeCrop = computeInitialCrop(hw);
492 const auto& p = getParent();
493 if (p != nullptr) {
494 auto parentCrop = p->computeInitialCrop(hw);
495 activeCrop.intersect(parentCrop, &activeCrop);
496 }
497 Transform t = getTransform();
498 // Back to layer space to work with the content crop.
499 activeCrop = t.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800500
Michael Lentine28ea2172014-11-19 18:32:37 -0800501 // This needs to be here as transform.transform(Rect) computes the
502 // transformed rect and then takes the bounding box of the result before
503 // returning. This means
504 // transform.inverse().transform(transform.transform(Rect)) != Rect
505 // in which case we need to make sure the final rect is clipped to the
506 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000507 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
508 activeCrop.clear();
509 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800510
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700511 // subtract the transparent region and snap to the bounds
512 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
513
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000514 // Transform the window crop to match the buffer coordinate system,
515 // which means using the inverse of the current transform set on the
516 // SurfaceFlingerConsumer.
517 uint32_t invTransform = mCurrentTransform;
518 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
519 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700520 * the code below applies the primary display's inverse transform to the
521 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000522 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700523 uint32_t invTransformOrient =
524 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000525 // calculate the inverse transform
526 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
527 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
528 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800529 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000530 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700531 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
532 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800533 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000534
535 int winWidth = s.active.w;
536 int winHeight = s.active.h;
537 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
538 // If the activeCrop has been rotate the ends are rotated but not
539 // the space itself so when transforming ends back we can't rely on
540 // a modification of the axes of rotation. To account for this we
541 // need to reorient the inverse rotation in terms of the current
542 // axes of rotation.
543 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
544 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
545 if (is_h_flipped == is_v_flipped) {
546 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
547 NATIVE_WINDOW_TRANSFORM_FLIP_H;
548 }
549 winWidth = s.active.h;
550 winHeight = s.active.w;
551 }
552 const Rect winCrop = activeCrop.transform(
553 invTransform, s.active.w, s.active.h);
554
555 // below, crop is intersected with winCrop expressed in crop's coordinate space
556 float xScale = crop.getWidth() / float(winWidth);
557 float yScale = crop.getHeight() / float(winHeight);
558
559 float insetL = winCrop.left * xScale;
560 float insetT = winCrop.top * yScale;
561 float insetR = (winWidth - winCrop.right ) * xScale;
562 float insetB = (winHeight - winCrop.bottom) * yScale;
563
564 crop.left += insetL;
565 crop.top += insetT;
566 crop.right -= insetR;
567 crop.bottom -= insetB;
568
Mathias Agopian13127d82013-03-05 17:47:11 -0800569 return crop;
570}
571
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000572#ifdef USE_HWC2
Robert Carrae060832016-11-28 10:51:00 -0800573void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000574#else
575void Layer::setGeometry(
576 const sp<const DisplayDevice>& hw,
577 HWComposer::HWCLayerInterface& layer)
578#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700579{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000580#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800581 const auto hwcId = displayDevice->getHwcDisplayId();
582 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000583#else
584 layer.setDefaultState();
585#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700586
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700587 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000588#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800589 hwcInfo.forceClientComposition = false;
590
591 if (isSecure() && !displayDevice->isSecure()) {
592 hwcInfo.forceClientComposition = true;
593 }
594
595 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000596#else
597 layer.setSkip(false);
598
599 if (isSecure() && !hw->isSecure()) {
600 layer.setSkip(true);
601 }
602#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700603
Mathias Agopian13127d82013-03-05 17:47:11 -0800604 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700605 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000606#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800607 if (!isOpaque(s) || s.alpha != 1.0f) {
608 auto blendMode = mPremultipliedAlpha ?
609 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
610 auto error = hwcLayer->setBlendMode(blendMode);
611 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
612 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
613 to_string(error).c_str(), static_cast<int32_t>(error));
614 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000615#else
616 if (!isOpaque(s) || s.alpha != 0xFF) {
617 layer.setBlending(mPremultipliedAlpha ?
618 HWC_BLENDING_PREMULT :
619 HWC_BLENDING_COVERAGE);
620 }
621#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800622
623 // apply the layer's transform, followed by the display's global transform
624 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700625 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700626 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -0700627 if (!s.crop.isEmpty()) {
628 Rect activeCrop(s.crop);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700629 activeCrop = t.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000630#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000631 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000632#else
633 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
634#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000635 activeCrop.clear();
636 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700637 activeCrop = t.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800638 // This needs to be here as transform.transform(Rect) computes the
639 // transformed rect and then takes the bounding box of the result before
640 // returning. This means
641 // transform.inverse().transform(transform.transform(Rect)) != Rect
642 // in which case we need to make sure the final rect is clipped to the
643 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000644 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
645 activeCrop.clear();
646 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700647 // mark regions outside the crop as transparent
648 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
649 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
650 s.active.w, s.active.h));
651 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
652 activeCrop.left, activeCrop.bottom));
653 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
654 s.active.w, activeCrop.bottom));
655 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700656
657 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700658 if (!s.finalCrop.isEmpty()) {
659 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000660 frame.clear();
661 }
662 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000663#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000664 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
665 frame.clear();
666 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800667 const Transform& tr(displayDevice->getTransform());
668 Rect transformedFrame = tr.transform(frame);
669 auto error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700670 if (error != HWC2::Error::None) {
671 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
672 mName.string(), transformedFrame.left, transformedFrame.top,
673 transformedFrame.right, transformedFrame.bottom,
674 to_string(error).c_str(), static_cast<int32_t>(error));
675 } else {
676 hwcInfo.displayFrame = transformedFrame;
677 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800678
Dan Stoza71bded52016-10-19 11:10:33 -0700679 gfx::FloatRect sourceCrop = computeCrop(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800680 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700681 if (error != HWC2::Error::None) {
682 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
683 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
684 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
685 static_cast<int32_t>(error));
686 } else {
687 hwcInfo.sourceCrop = sourceCrop;
688 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800689
690 error = hwcLayer->setPlaneAlpha(s.alpha);
691 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
692 "%s (%d)", mName.string(), s.alpha, to_string(error).c_str(),
693 static_cast<int32_t>(error));
694
Robert Carrae060832016-11-28 10:51:00 -0800695 error = hwcLayer->setZOrder(z);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800696 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
Robert Carrae060832016-11-28 10:51:00 -0800697 mName.string(), z, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800698 static_cast<int32_t>(error));
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500699
700 error = hwcLayer->setInfo(s.type, s.appId);
701 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
702 mName.string(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000703#else
704 if (!frame.intersect(hw->getViewport(), &frame)) {
705 frame.clear();
706 }
707 const Transform& tr(hw->getTransform());
708 layer.setFrame(tr.transform(frame));
709 layer.setCrop(computeCrop(hw));
710 layer.setPlaneAlpha(s.alpha);
711#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800712
Mathias Agopian29a367b2011-07-12 14:51:45 -0700713 /*
714 * Transformations are applied in this order:
715 * 1) buffer orientation/flip/mirror
716 * 2) state transformation (window manager)
717 * 3) layer orientation (screen orientation)
718 * (NOTE: the matrices are multiplied in reverse order)
719 */
720
721 const Transform bufferOrientation(mCurrentTransform);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700722 Transform transform(tr * t * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700723
724 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
725 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700726 * the code below applies the primary display's inverse transform to the
727 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700728 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700729 uint32_t invTransform =
730 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700731 // calculate the inverse transform
732 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
733 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
734 NATIVE_WINDOW_TRANSFORM_FLIP_H;
735 }
736 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700737 transform = Transform(invTransform) * transform;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700738 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700739
740 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800741 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000742#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800743 if (orientation & Transform::ROT_INVALID) {
744 // we can only handle simple transformation
745 hwcInfo.forceClientComposition = true;
746 } else {
747 auto transform = static_cast<HWC2::Transform>(orientation);
748 auto error = hwcLayer->setTransform(transform);
749 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
750 "%s (%d)", mName.string(), to_string(transform).c_str(),
751 to_string(error).c_str(), static_cast<int32_t>(error));
752 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000753#else
754 if (orientation & Transform::ROT_INVALID) {
755 // we can only handle simple transformation
756 layer.setSkip(true);
757 } else {
758 layer.setTransform(orientation);
759 }
760#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700761}
762
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000763#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800764void Layer::forceClientComposition(int32_t hwcId) {
765 if (mHwcLayers.count(hwcId) == 0) {
766 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
767 return;
768 }
769
770 mHwcLayers[hwcId].forceClientComposition = true;
771}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000772#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -0800773
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000774#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800775void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
776 // Apply this display's projection's viewport to the visible region
777 // before giving it to the HWC HAL.
778 const Transform& tr = displayDevice->getTransform();
779 const auto& viewport = displayDevice->getViewport();
780 Region visible = tr.transform(visibleRegion.intersect(viewport));
781 auto hwcId = displayDevice->getHwcDisplayId();
782 auto& hwcLayer = mHwcLayers[hwcId].layer;
783 auto error = hwcLayer->setVisibleRegion(visible);
784 if (error != HWC2::Error::None) {
785 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
786 to_string(error).c_str(), static_cast<int32_t>(error));
787 visible.dump(LOG_TAG);
788 }
789
790 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
791 if (error != HWC2::Error::None) {
792 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
793 to_string(error).c_str(), static_cast<int32_t>(error));
794 surfaceDamageRegion.dump(LOG_TAG);
795 }
796
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700797 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800798 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700799 setCompositionType(hwcId, HWC2::Composition::Sideband);
800 ALOGV("[%s] Requesting Sideband composition", mName.string());
801 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800802 if (error != HWC2::Error::None) {
803 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
804 mName.string(), mSidebandStream->handle(),
805 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800806 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700807 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800808 }
809
Dan Stoza0a21df72016-07-20 12:52:38 -0700810 // Client layers
811 if (mHwcLayers[hwcId].forceClientComposition ||
812 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700813 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800814 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700815 return;
816 }
817
Dan Stoza0a21df72016-07-20 12:52:38 -0700818 // SolidColor layers
819 if (mActiveBuffer == nullptr) {
820 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700821
822 // For now, we only support black for DimLayer
Dan Stoza0a21df72016-07-20 12:52:38 -0700823 error = hwcLayer->setColor({0, 0, 0, 255});
824 if (error != HWC2::Error::None) {
825 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
826 to_string(error).c_str(), static_cast<int32_t>(error));
827 }
Dan Stozac6c89542016-07-27 10:16:52 -0700828
829 // Clear out the transform, because it doesn't make sense absent a
830 // source buffer
831 error = hwcLayer->setTransform(HWC2::Transform::None);
832 if (error != HWC2::Error::None) {
833 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
834 to_string(error).c_str(), static_cast<int32_t>(error));
835 }
836
Dan Stoza0a21df72016-07-20 12:52:38 -0700837 return;
838 }
839
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700840 // Device or Cursor layers
841 if (mPotentialCursor) {
842 ALOGV("[%s] Requesting Cursor composition", mName.string());
843 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800844 } else {
845 ALOGV("[%s] Requesting Device composition", mName.string());
846 setCompositionType(hwcId, HWC2::Composition::Device);
847 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700848
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700849 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
850 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
851 if (error != HWC2::Error::None) {
852 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
853 mCurrentState.dataSpace, to_string(error).c_str(),
854 static_cast<int32_t>(error));
855 }
856
Chia-I Wu06d63de2017-01-04 14:58:51 +0800857 uint32_t hwcSlot = 0;
858 buffer_handle_t hwcHandle = nullptr;
859 {
860 Mutex::Autolock lock(mHwcBufferCacheMutex);
861
862 auto& hwcBufferCache = mHwcBufferCaches[hwcId];
863 sp<GraphicBuffer> hwcBuffer;
864 hwcBufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
865 &hwcSlot, &hwcBuffer);
866 if (hwcBuffer != nullptr) {
867 hwcHandle = hwcBuffer->handle;
868 }
869 }
870
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700871 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
Chia-I Wu06d63de2017-01-04 14:58:51 +0800872 error = hwcLayer->setBuffer(hwcSlot, hwcHandle, acquireFence);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700873 if (error != HWC2::Error::None) {
874 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
875 mActiveBuffer->handle, to_string(error).c_str(),
876 static_cast<int32_t>(error));
877 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800878}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000879#else
880void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
881 HWComposer::HWCLayerInterface& layer) {
882 // we have to set the visible region on every frame because
883 // we currently free it during onLayerDisplayed(), which is called
884 // after HWComposer::commit() -- every frame.
885 // Apply this display's projection's viewport to the visible region
886 // before giving it to the HWC HAL.
887 const Transform& tr = hw->getTransform();
888 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
889 layer.setVisibleRegionScreen(visible);
890 layer.setSurfaceDamage(surfaceDamageRegion);
891 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700892
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000893 if (mSidebandStream.get()) {
894 layer.setSidebandStream(mSidebandStream);
895 } else {
896 // NOTE: buffer can be NULL if the client never drew into this
897 // layer yet, or if we ran out of memory
898 layer.setBuffer(mActiveBuffer);
899 }
900}
901#endif
902
903#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800904void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
905 auto hwcId = displayDevice->getHwcDisplayId();
906 if (mHwcLayers.count(hwcId) == 0 ||
907 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
908 return;
909 }
910
911 // This gives us only the "orientation" component of the transform
912 const State& s(getCurrentState());
913
914 // Apply the layer's transform, followed by the display's global transform
915 // Here we're guaranteed that the layer's transform preserves rects
916 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700917 if (!s.crop.isEmpty()) {
918 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800919 }
920 // Subtract the transparent region and snap to the bounds
921 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700922 Rect frame(getTransform().transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800923 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -0700924 if (!s.finalCrop.isEmpty()) {
925 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000926 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800927 auto& displayTransform(displayDevice->getTransform());
928 auto position = displayTransform.transform(frame);
929
930 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
931 position.top);
932 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
933 "to (%d, %d): %s (%d)", mName.string(), position.left,
934 position.top, to_string(error).c_str(),
935 static_cast<int32_t>(error));
936}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000937#else
938void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
939 HWComposer::HWCLayerInterface& layer) {
940 int fenceFd = -1;
941
942 // TODO: there is a possible optimization here: we only need to set the
943 // acquire fence the first time a new buffer is acquired on EACH display.
944
945 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
946 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
947 if (fence->isValid()) {
948 fenceFd = fence->dup();
949 if (fenceFd == -1) {
950 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
951 }
952 }
953 }
954 layer.setAcquireFenceFd(fenceFd);
955}
956
957Rect Layer::getPosition(
958 const sp<const DisplayDevice>& hw)
959{
960 // this gives us only the "orientation" component of the transform
961 const State& s(getCurrentState());
962
963 // apply the layer's transform, followed by the display's global transform
964 // here we're guaranteed that the layer's transform preserves rects
965 Rect win(s.active.w, s.active.h);
966 if (!s.crop.isEmpty()) {
967 win.intersect(s.crop, &win);
968 }
969 // subtract the transparent region and snap to the bounds
970 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700971 Rect frame(getTransform().transform(bounds));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000972 frame.intersect(hw->getViewport(), &frame);
973 if (!s.finalCrop.isEmpty()) {
974 frame.intersect(s.finalCrop, &frame);
975 }
976 const Transform& tr(hw->getTransform());
977 return Rect(tr.transform(frame));
978}
979#endif
Riley Andrews03414a12014-07-01 14:22:59 -0700980
Mathias Agopian13127d82013-03-05 17:47:11 -0800981// ---------------------------------------------------------------------------
982// drawing...
983// ---------------------------------------------------------------------------
984
985void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -0800986 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -0800987}
988
Dan Stozac7014012014-02-14 15:03:43 -0800989void Layer::draw(const sp<const DisplayDevice>& hw,
990 bool useIdentityTransform) const {
991 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -0800992}
993
Dan Stozac7014012014-02-14 15:03:43 -0800994void Layer::draw(const sp<const DisplayDevice>& hw) const {
995 onDraw(hw, Region(hw->bounds()), false);
996}
997
998void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
999 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001000{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001001 ATRACE_CALL();
1002
Mathias Agopiana67932f2011-04-20 14:20:59 -07001003 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001004 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -07001005 // in fact never been drawn into. This happens frequently with
1006 // SurfaceView because the WindowManager can't know when the client
1007 // has drawn the first time.
1008
1009 // If there is nothing under us, we paint the screen in black, otherwise
1010 // we just skip this update.
1011
1012 // figure out if there is something below us
1013 Region under;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001014 bool finished = false;
1015 mFlinger->mDrawingState.layersSortedByZ.traverseInZOrder([&](Layer* layer) {
1016 if (finished || layer == static_cast<Layer const*>(this)) {
1017 finished = true;
1018 return;
1019 }
Mathias Agopian42977342012-08-05 00:40:46 -07001020 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Robert Carr1f0a16a2016-10-24 16:27:39 -07001021 });
Mathias Agopian179169e2010-05-06 20:21:45 -07001022 // if not everything below us is covered, we plug the holes!
1023 Region holes(clip.subtract(under));
1024 if (!holes.isEmpty()) {
Fabien Sanglard17487192016-12-07 13:03:32 -08001025 clearWithOpenGL(hw, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -07001026 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001027 return;
1028 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001029
Andy McFadden97eba892012-12-11 15:21:45 -08001030 // Bind the current buffer to the GL texture, and wait for it to be
1031 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001032 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1033 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -08001034 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -07001035 // Go ahead and draw the buffer anyway; no matter what we do the screen
1036 // is probably going to have something visibly wrong.
1037 }
1038
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001039 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1040
Mathias Agopian875d8e12013-06-07 15:35:48 -07001041 RenderEngine& engine(mFlinger->getRenderEngine());
1042
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001043 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -07001044 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -07001045 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -07001046
1047 // Query the texture matrix given our current filtering mode.
1048 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001049 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1050 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -07001051
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001052 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
1053
1054 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -07001055 * the code below applies the primary display's inverse transform to
1056 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001057 */
1058
1059 // create a 4x4 transform matrix from the display transform flags
1060 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1061 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1062 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1063
1064 mat4 tr;
Pablo Ceballos021623b2016-04-15 17:31:51 -07001065 uint32_t transform =
1066 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001067 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90)
1068 tr = tr * rot90;
1069 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H)
1070 tr = tr * flipH;
1071 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V)
1072 tr = tr * flipV;
1073
1074 // calculate the inverse
1075 tr = inverse(tr);
1076
1077 // and finally apply it to the original texture matrix
1078 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1079 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1080 }
1081
Jamie Genniscbb1a952012-05-08 17:05:52 -07001082 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -07001083 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1084 mTexture.setFiltering(useFiltering);
1085 mTexture.setMatrix(textureMatrix);
1086
1087 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -07001088 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001089 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -07001090 }
Fabien Sanglard85789802016-12-07 13:08:24 -08001091 drawWithOpenGL(hw, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001092 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001093}
1094
Mathias Agopian13127d82013-03-05 17:47:11 -08001095
Dan Stozac7014012014-02-14 15:03:43 -08001096void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard17487192016-12-07 13:03:32 -08001097 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -08001098 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001099{
Mathias Agopian19733a32013-08-28 18:13:56 -07001100 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -08001101 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -07001102 engine.setupFillWithColor(red, green, blue, alpha);
1103 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -08001104}
1105
1106void Layer::clearWithOpenGL(
Fabien Sanglard17487192016-12-07 13:03:32 -08001107 const sp<const DisplayDevice>& hw) const {
1108 clearWithOpenGL(hw, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001109}
1110
Dan Stozac7014012014-02-14 15:03:43 -08001111void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard85789802016-12-07 13:08:24 -08001112 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001113 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001114
Dan Stozac7014012014-02-14 15:03:43 -08001115 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001116
Mathias Agopian13127d82013-03-05 17:47:11 -08001117 /*
1118 * NOTE: the way we compute the texture coordinates here produces
1119 * different results than when we take the HWC path -- in the later case
1120 * the "source crop" is rounded to texel boundaries.
1121 * This can produce significantly different results when the texture
1122 * is scaled by a large amount.
1123 *
1124 * The GL code below is more logical (imho), and the difference with
1125 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001126 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001127 * GL composition when a buffer scaling is applied (maybe with some
1128 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1129 * like more of a hack.
1130 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001131 Rect win(computeBounds());
1132
Robert Carr1f0a16a2016-10-24 16:27:39 -07001133 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -07001134 if (!s.finalCrop.isEmpty()) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001135 win = t.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001136 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001137 win.clear();
1138 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001139 win = t.inverse().transform(win);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001140 if (!win.intersect(computeBounds(), &win)) {
1141 win.clear();
1142 }
1143 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001144
Mathias Agopian3f844832013-08-07 21:24:32 -07001145 float left = float(win.left) / float(s.active.w);
1146 float top = float(win.top) / float(s.active.h);
1147 float right = float(win.right) / float(s.active.w);
1148 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001149
Mathias Agopian875d8e12013-06-07 15:35:48 -07001150 // TODO: we probably want to generate the texture coords with the mesh
1151 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001152 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1153 texCoords[0] = vec2(left, 1.0f - top);
1154 texCoords[1] = vec2(left, 1.0f - bottom);
1155 texCoords[2] = vec2(right, 1.0f - bottom);
1156 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001157
Mathias Agopian875d8e12013-06-07 15:35:48 -07001158 RenderEngine& engine(mFlinger->getRenderEngine());
Andy McFadden4125a4f2014-01-29 17:17:11 -08001159 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), s.alpha);
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001160 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001161 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001162}
1163
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001164#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001165void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1166 bool callIntoHwc) {
1167 if (mHwcLayers.count(hwcId) == 0) {
1168 ALOGE("setCompositionType called without a valid HWC layer");
1169 return;
1170 }
1171 auto& hwcInfo = mHwcLayers[hwcId];
1172 auto& hwcLayer = hwcInfo.layer;
1173 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1174 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1175 if (hwcInfo.compositionType != type) {
1176 ALOGV(" actually setting");
1177 hwcInfo.compositionType = type;
1178 if (callIntoHwc) {
1179 auto error = hwcLayer->setCompositionType(type);
1180 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1181 "composition type %s: %s (%d)", mName.string(),
1182 to_string(type).c_str(), to_string(error).c_str(),
1183 static_cast<int32_t>(error));
1184 }
1185 }
1186}
1187
1188HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001189 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1190 // If we're querying the composition type for a display that does not
1191 // have a HWC counterpart, then it will always be Client
1192 return HWC2::Composition::Client;
1193 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001194 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001195 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001196 return HWC2::Composition::Invalid;
1197 }
1198 return mHwcLayers.at(hwcId).compositionType;
1199}
1200
1201void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1202 if (mHwcLayers.count(hwcId) == 0) {
1203 ALOGE("setClearClientTarget called without a valid HWC layer");
1204 return;
1205 }
1206 mHwcLayers[hwcId].clearClientTarget = clear;
1207}
1208
1209bool Layer::getClearClientTarget(int32_t hwcId) const {
1210 if (mHwcLayers.count(hwcId) == 0) {
1211 ALOGE("getClearClientTarget called without a valid HWC layer");
1212 return false;
1213 }
1214 return mHwcLayers.at(hwcId).clearClientTarget;
1215}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001216#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001217
Ruben Brunk1681d952014-06-27 15:51:55 -07001218uint32_t Layer::getProducerStickyTransform() const {
1219 int producerStickyTransform = 0;
1220 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1221 if (ret != OK) {
1222 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1223 strerror(-ret), ret);
1224 return 0;
1225 }
1226 return static_cast<uint32_t>(producerStickyTransform);
1227}
1228
Dan Stozac5da2712016-07-20 15:38:12 -07001229bool Layer::latchUnsignaledBuffers() {
1230 static bool propertyLoaded = false;
1231 static bool latch = false;
1232 static std::mutex mutex;
1233 std::lock_guard<std::mutex> lock(mutex);
1234 if (!propertyLoaded) {
1235 char value[PROPERTY_VALUE_MAX] = {};
1236 property_get("debug.sf.latch_unsignaled", value, "0");
1237 latch = atoi(value);
1238 propertyLoaded = true;
1239 }
1240 return latch;
1241}
1242
Dan Stozacac35382016-01-27 12:21:06 -08001243uint64_t Layer::getHeadFrameNumber() const {
1244 Mutex::Autolock lock(mQueueItemLock);
1245 if (!mQueueItems.empty()) {
1246 return mQueueItems[0].mFrameNumber;
1247 } else {
1248 return mCurrentFrameNumber;
1249 }
1250}
1251
Dan Stoza1ce65812016-06-15 16:26:27 -07001252bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001253#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001254 if (latchUnsignaledBuffers()) {
1255 return true;
1256 }
1257
Dan Stoza1ce65812016-06-15 16:26:27 -07001258 Mutex::Autolock lock(mQueueItemLock);
1259 if (mQueueItems.empty()) {
1260 return true;
1261 }
1262 if (mQueueItems[0].mIsDroppable) {
1263 // Even though this buffer's fence may not have signaled yet, it could
1264 // be replaced by another buffer before it has a chance to, which means
1265 // that it's possible to get into a situation where a buffer is never
1266 // able to be latched. To avoid this, grab this buffer anyway.
1267 return true;
1268 }
1269 return mQueueItems[0].mFence->getSignalTime() != INT64_MAX;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001270#else
1271 return true;
1272#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001273}
1274
Dan Stozacac35382016-01-27 12:21:06 -08001275bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1276 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1277 // Don't bother with a SyncPoint, since we've already latched the
1278 // relevant frame
1279 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001280 }
1281
Dan Stozacac35382016-01-27 12:21:06 -08001282 Mutex::Autolock lock(mLocalSyncPointMutex);
1283 mLocalSyncPoints.push_back(point);
1284 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001285}
1286
Mathias Agopian13127d82013-03-05 17:47:11 -08001287void Layer::setFiltering(bool filtering) {
1288 mFiltering = filtering;
1289}
1290
1291bool Layer::getFiltering() const {
1292 return mFiltering;
1293}
1294
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001295// As documented in libhardware header, formats in the range
1296// 0x100 - 0x1FF are specific to the HAL implementation, and
1297// are known to have no alpha channel
1298// TODO: move definition for device-specific range into
1299// hardware.h, instead of using hard-coded values here.
1300#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1301
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001302bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001303 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1304 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001305 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001306 switch (format) {
1307 case HAL_PIXEL_FORMAT_RGBA_8888:
1308 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001309 case HAL_PIXEL_FORMAT_RGBA_FP16:
Romain Guy541f2262017-02-10 18:50:17 -08001310 case HAL_PIXEL_FORMAT_RGBA_1010102:
Mathias Agopiandd533712013-07-26 15:31:39 -07001311 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001312 }
1313 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001314 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001315}
1316
Mathias Agopian13127d82013-03-05 17:47:11 -08001317// ----------------------------------------------------------------------------
1318// local state
1319// ----------------------------------------------------------------------------
1320
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001321static void boundPoint(vec2* point, const Rect& crop) {
1322 if (point->x < crop.left) {
1323 point->x = crop.left;
1324 }
1325 if (point->x > crop.right) {
1326 point->x = crop.right;
1327 }
1328 if (point->y < crop.top) {
1329 point->y = crop.top;
1330 }
1331 if (point->y > crop.bottom) {
1332 point->y = crop.bottom;
1333 }
1334}
1335
Dan Stozac7014012014-02-14 15:03:43 -08001336void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1337 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001338{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001339 const Layer::State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001340 const Transform hwTransform(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001341 const uint32_t hw_h = hw->getHeight();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001342 Rect win = computeBounds();
Mathias Agopian3f844832013-08-07 21:24:32 -07001343
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001344 vec2 lt = vec2(win.left, win.top);
1345 vec2 lb = vec2(win.left, win.bottom);
1346 vec2 rb = vec2(win.right, win.bottom);
1347 vec2 rt = vec2(win.right, win.top);
1348
Robert Carr1f0a16a2016-10-24 16:27:39 -07001349 Transform layerTransform = getTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001350 if (!useIdentityTransform) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001351 lt = layerTransform.transform(lt);
1352 lb = layerTransform.transform(lb);
1353 rb = layerTransform.transform(rb);
1354 rt = layerTransform.transform(rt);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001355 }
1356
Robert Carrb5d3d262016-03-25 15:08:13 -07001357 if (!s.finalCrop.isEmpty()) {
1358 boundPoint(&lt, s.finalCrop);
1359 boundPoint(&lb, s.finalCrop);
1360 boundPoint(&rb, s.finalCrop);
1361 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001362 }
1363
Mathias Agopianff2ed702013-09-01 21:36:12 -07001364 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001365 position[0] = hwTransform.transform(lt);
1366 position[1] = hwTransform.transform(lb);
1367 position[2] = hwTransform.transform(rb);
1368 position[3] = hwTransform.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001369 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001370 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001371 }
1372}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001373
Andy McFadden4125a4f2014-01-29 17:17:11 -08001374bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001375{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001376 // if we don't have a buffer yet, we're translucent regardless of the
1377 // layer's opaque flag.
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001378 if (mActiveBuffer == 0) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001379 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001380 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001381
1382 // if the layer has the opaque flag, then we're always opaque,
1383 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001384 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001385}
1386
Dan Stoza23116082015-06-18 14:58:39 -07001387bool Layer::isSecure() const
1388{
1389 const Layer::State& s(mDrawingState);
1390 return (s.flags & layer_state_t::eLayerSecure);
1391}
1392
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001393bool Layer::isProtected() const
1394{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001395 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001396 return (activeBuffer != 0) &&
1397 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1398}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001399
Mathias Agopian13127d82013-03-05 17:47:11 -08001400bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001401 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001402}
1403
1404bool Layer::isCropped() const {
1405 return !mCurrentCrop.isEmpty();
1406}
1407
1408bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1409 return mNeedsFiltering || hw->needsFiltering();
1410}
1411
1412void Layer::setVisibleRegion(const Region& visibleRegion) {
1413 // always called from main thread
1414 this->visibleRegion = visibleRegion;
1415}
1416
1417void Layer::setCoveredRegion(const Region& coveredRegion) {
1418 // always called from main thread
1419 this->coveredRegion = coveredRegion;
1420}
1421
1422void Layer::setVisibleNonTransparentRegion(const Region&
1423 setVisibleNonTransparentRegion) {
1424 // always called from main thread
1425 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1426}
1427
1428// ----------------------------------------------------------------------------
1429// transaction
1430// ----------------------------------------------------------------------------
1431
Dan Stoza7dde5992015-05-22 09:51:44 -07001432void Layer::pushPendingState() {
1433 if (!mCurrentState.modified) {
1434 return;
1435 }
1436
Dan Stoza7dde5992015-05-22 09:51:44 -07001437 // If this transaction is waiting on the receipt of a frame, generate a sync
1438 // point and send it to the remote layer.
1439 if (mCurrentState.handle != nullptr) {
Dan Stoza22851c32016-08-09 13:21:03 -07001440 sp<IBinder> strongBinder = mCurrentState.handle.promote();
1441 sp<Handle> handle = nullptr;
1442 sp<Layer> handleLayer = nullptr;
1443 if (strongBinder != nullptr) {
1444 handle = static_cast<Handle*>(strongBinder.get());
1445 handleLayer = handle->owner.promote();
1446 }
1447 if (strongBinder == nullptr || handleLayer == nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001448 ALOGE("[%s] Unable to promote Layer handle", mName.string());
1449 // If we can't promote the layer we are intended to wait on,
1450 // then it is expired or otherwise invalid. Allow this transaction
1451 // to be applied as per normal (no synchronization).
1452 mCurrentState.handle = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001453 } else {
1454 auto syncPoint = std::make_shared<SyncPoint>(
1455 mCurrentState.frameNumber);
Dan Stozacac35382016-01-27 12:21:06 -08001456 if (handleLayer->addSyncPoint(syncPoint)) {
1457 mRemoteSyncPoints.push_back(std::move(syncPoint));
1458 } else {
1459 // We already missed the frame we're supposed to synchronize
1460 // on, so go ahead and apply the state update
1461 mCurrentState.handle = nullptr;
1462 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001463 }
1464
Dan Stoza7dde5992015-05-22 09:51:44 -07001465 // Wake us up to check if the frame has been received
1466 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001467 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001468 }
1469 mPendingStates.push_back(mCurrentState);
1470}
1471
Pablo Ceballos05289c22016-04-14 15:49:55 -07001472void Layer::popPendingState(State* stateToCommit) {
1473 auto oldFlags = stateToCommit->flags;
1474 *stateToCommit = mPendingStates[0];
1475 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1476 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001477
1478 mPendingStates.removeAt(0);
1479}
1480
Pablo Ceballos05289c22016-04-14 15:49:55 -07001481bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001482 bool stateUpdateAvailable = false;
1483 while (!mPendingStates.empty()) {
1484 if (mPendingStates[0].handle != nullptr) {
1485 if (mRemoteSyncPoints.empty()) {
1486 // If we don't have a sync point for this, apply it anyway. It
1487 // will be visually wrong, but it should keep us from getting
1488 // into too much trouble.
1489 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001490 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001491 stateUpdateAvailable = true;
1492 continue;
1493 }
1494
Dan Stozacac35382016-01-27 12:21:06 -08001495 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1496 mPendingStates[0].frameNumber) {
1497 ALOGE("[%s] Unexpected sync point frame number found",
1498 mName.string());
1499
1500 // Signal our end of the sync point and then dispose of it
1501 mRemoteSyncPoints.front()->setTransactionApplied();
1502 mRemoteSyncPoints.pop_front();
1503 continue;
1504 }
1505
Dan Stoza7dde5992015-05-22 09:51:44 -07001506 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1507 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001508 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001509 stateUpdateAvailable = true;
1510
1511 // Signal our end of the sync point and then dispose of it
1512 mRemoteSyncPoints.front()->setTransactionApplied();
1513 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001514 } else {
1515 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001516 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001517 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001518 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001519 stateUpdateAvailable = true;
1520 }
1521 }
1522
1523 // If we still have pending updates, wake SurfaceFlinger back up and point
1524 // it at this layer so we can process them
1525 if (!mPendingStates.empty()) {
1526 setTransactionFlags(eTransactionNeeded);
1527 mFlinger->setTransactionFlags(eTraversalNeeded);
1528 }
1529
1530 mCurrentState.modified = false;
1531 return stateUpdateAvailable;
1532}
1533
1534void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001535 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001536 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001537 Mutex::Autolock lock(mLocalSyncPointMutex);
1538 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001539 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001540 point->setFrameAvailable();
1541 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001542 }
1543}
1544
Mathias Agopian13127d82013-03-05 17:47:11 -08001545uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001546 ATRACE_CALL();
1547
Dan Stoza7dde5992015-05-22 09:51:44 -07001548 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001549 Layer::State c = getCurrentState();
1550 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001551 return 0;
1552 }
1553
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001554 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001555
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001556 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1557 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001558
1559 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001560 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001561 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001562 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001563 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001564 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001565 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001566 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001567 this, getName().string(), mCurrentTransform,
1568 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001569 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001570 c.crop.left,
1571 c.crop.top,
1572 c.crop.right,
1573 c.crop.bottom,
1574 c.crop.getWidth(),
1575 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001576 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001577 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001578 s.crop.left,
1579 s.crop.top,
1580 s.crop.right,
1581 s.crop.bottom,
1582 s.crop.getWidth(),
1583 s.crop.getHeight(),
1584 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001585
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001586 // record the new size, form this point on, when the client request
1587 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001588 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001589 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001590 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001591
Robert Carr82364e32016-05-15 11:27:47 -07001592 const bool resizePending = (c.requested.w != c.active.w) ||
1593 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001594 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001595 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001596 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001597 // if we have a pending resize, unless we are in fixed-size mode.
1598 // the drawing state will be updated only once we receive a buffer
1599 // with the correct size.
1600 //
1601 // in particular, we want to make sure the clip (which is part
1602 // of the geometry state) is latched together with the size but is
1603 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001604 //
1605 // If a sideband stream is attached, however, we want to skip this
1606 // optimization so that transactions aren't missed when a buffer
1607 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001608
1609 flags |= eDontUpdateGeometryState;
1610 }
1611 }
1612
Mathias Agopian13127d82013-03-05 17:47:11 -08001613 // always set active to requested, unless we're asked not to
1614 // this is used by Layer, which special cases resizes.
1615 if (flags & eDontUpdateGeometryState) {
1616 } else {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001617 Layer::State& editCurrentState(getCurrentState());
Robert Carr82364e32016-05-15 11:27:47 -07001618 if (mFreezePositionUpdates) {
1619 float tx = c.active.transform.tx();
1620 float ty = c.active.transform.ty();
1621 c.active = c.requested;
1622 c.active.transform.set(tx, ty);
1623 editCurrentState.active = c.active;
1624 } else {
1625 editCurrentState.active = editCurrentState.requested;
1626 c.active = c.requested;
1627 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001628 }
1629
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001630 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001631 // invalidate and recompute the visible regions if needed
1632 flags |= Layer::eVisibleRegion;
1633 }
1634
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001635 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001636 // invalidate and recompute the visible regions if needed
1637 flags |= eVisibleRegion;
1638 this->contentDirty = true;
1639
1640 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001641 const uint8_t type = c.active.transform.getType();
1642 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001643 (type >= Transform::SCALE));
1644 }
1645
Dan Stozac8145172016-04-28 16:29:06 -07001646 // If the layer is hidden, signal and clear out all local sync points so
1647 // that transactions for layers depending on this layer's frames becoming
1648 // visible are not blocked
1649 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001650 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001651 }
1652
Mathias Agopian13127d82013-03-05 17:47:11 -08001653 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001654 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001655 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001656}
1657
Pablo Ceballos05289c22016-04-14 15:49:55 -07001658void Layer::commitTransaction(const State& stateToCommit) {
1659 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001660}
1661
Mathias Agopian13127d82013-03-05 17:47:11 -08001662uint32_t Layer::getTransactionFlags(uint32_t flags) {
1663 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1664}
1665
1666uint32_t Layer::setTransactionFlags(uint32_t flags) {
1667 return android_atomic_or(flags, &mTransactionFlags);
1668}
1669
Robert Carr82364e32016-05-15 11:27:47 -07001670bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001671 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001672 return false;
1673 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001674
1675 // We update the requested and active position simultaneously because
1676 // we want to apply the position portion of the transform matrix immediately,
1677 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001678 mCurrentState.requested.transform.set(x, y);
Robert Carr82364e32016-05-15 11:27:47 -07001679 if (immediate && !mFreezePositionUpdates) {
1680 mCurrentState.active.transform.set(x, y);
1681 }
1682 mFreezePositionUpdates = mFreezePositionUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001683
Dan Stoza7dde5992015-05-22 09:51:44 -07001684 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001685 setTransactionFlags(eTransactionNeeded);
1686 return true;
1687}
Robert Carr82364e32016-05-15 11:27:47 -07001688
Robert Carr1f0a16a2016-10-24 16:27:39 -07001689bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1690 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1691 if (idx < 0) {
1692 return false;
1693 }
1694 if (childLayer->setLayer(z)) {
1695 mCurrentChildren.removeAt(idx);
1696 mCurrentChildren.add(childLayer);
1697 }
1698 return true;
1699}
1700
Robert Carrae060832016-11-28 10:51:00 -08001701bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001702 if (mCurrentState.z == z)
1703 return false;
1704 mCurrentState.sequence++;
1705 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001706 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001707 setTransactionFlags(eTransactionNeeded);
1708 return true;
1709}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001710
Mathias Agopian13127d82013-03-05 17:47:11 -08001711bool Layer::setSize(uint32_t w, uint32_t h) {
1712 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1713 return false;
1714 mCurrentState.requested.w = w;
1715 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001716 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001717 setTransactionFlags(eTransactionNeeded);
1718 return true;
1719}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001720#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001721bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001722#else
1723bool Layer::setAlpha(uint8_t alpha) {
1724#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001725 if (mCurrentState.alpha == alpha)
1726 return false;
1727 mCurrentState.sequence++;
1728 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001729 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001730 setTransactionFlags(eTransactionNeeded);
1731 return true;
1732}
1733bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1734 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001735 mCurrentState.requested.transform.set(
Mathias Agopian13127d82013-03-05 17:47:11 -08001736 matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001737 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001738 setTransactionFlags(eTransactionNeeded);
1739 return true;
1740}
1741bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001742 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001743 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001744 setTransactionFlags(eTransactionNeeded);
1745 return true;
1746}
1747bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1748 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1749 if (mCurrentState.flags == newFlags)
1750 return false;
1751 mCurrentState.sequence++;
1752 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001753 mCurrentState.mask = mask;
1754 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001755 setTransactionFlags(eTransactionNeeded);
1756 return true;
1757}
Robert Carr99e27f02016-06-16 15:18:02 -07001758
1759bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001760 if (mCurrentState.crop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001761 return false;
1762 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001763 mCurrentState.requestedCrop = crop;
1764 if (immediate) {
1765 mCurrentState.crop = crop;
1766 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001767 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001768 setTransactionFlags(eTransactionNeeded);
1769 return true;
1770}
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001771bool Layer::setFinalCrop(const Rect& crop) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001772 if (mCurrentState.finalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001773 return false;
1774 mCurrentState.sequence++;
Robert Carrb5d3d262016-03-25 15:08:13 -07001775 mCurrentState.finalCrop = crop;
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001776 mCurrentState.modified = true;
1777 setTransactionFlags(eTransactionNeeded);
1778 return true;
1779}
Mathias Agopian13127d82013-03-05 17:47:11 -08001780
Robert Carrc3574f72016-03-24 12:19:32 -07001781bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1782 if (scalingMode == mOverrideScalingMode)
1783 return false;
1784 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001785 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001786 return true;
1787}
1788
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001789void Layer::setInfo(uint32_t type, uint32_t appId) {
1790 mCurrentState.appId = appId;
1791 mCurrentState.type = type;
1792 mCurrentState.modified = true;
1793 setTransactionFlags(eTransactionNeeded);
1794}
1795
Robert Carrc3574f72016-03-24 12:19:32 -07001796uint32_t Layer::getEffectiveScalingMode() const {
1797 if (mOverrideScalingMode >= 0) {
1798 return mOverrideScalingMode;
1799 }
1800 return mCurrentScalingMode;
1801}
1802
Mathias Agopian13127d82013-03-05 17:47:11 -08001803bool Layer::setLayerStack(uint32_t layerStack) {
1804 if (mCurrentState.layerStack == layerStack)
1805 return false;
1806 mCurrentState.sequence++;
1807 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001808 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001809 setTransactionFlags(eTransactionNeeded);
1810 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001811}
1812
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07001813bool Layer::setDataSpace(android_dataspace dataSpace) {
1814 if (mCurrentState.dataSpace == dataSpace)
1815 return false;
1816 mCurrentState.sequence++;
1817 mCurrentState.dataSpace = dataSpace;
1818 mCurrentState.modified = true;
1819 setTransactionFlags(eTransactionNeeded);
1820 return true;
1821}
1822
Robert Carr1f0a16a2016-10-24 16:27:39 -07001823uint32_t Layer::getLayerStack() const {
1824 auto p = getParent();
1825 if (p == nullptr) {
1826 return getDrawingState().layerStack;
1827 }
1828 return p->getLayerStack();
1829}
1830
Dan Stoza7dde5992015-05-22 09:51:44 -07001831void Layer::deferTransactionUntil(const sp<IBinder>& handle,
1832 uint64_t frameNumber) {
1833 mCurrentState.handle = handle;
1834 mCurrentState.frameNumber = frameNumber;
1835 // We don't set eTransactionNeeded, because just receiving a deferral
1836 // request without any other state updates shouldn't actually induce a delay
1837 mCurrentState.modified = true;
1838 pushPendingState();
Dan Stoza792e5292016-02-11 11:43:58 -08001839 mCurrentState.handle = nullptr;
1840 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07001841 mCurrentState.modified = false;
1842}
1843
Dan Stozaee44edd2015-03-23 15:50:23 -07001844void Layer::useSurfaceDamage() {
1845 if (mFlinger->mForceFullDamage) {
1846 surfaceDamageRegion = Region::INVALID_REGION;
1847 } else {
1848 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1849 }
1850}
1851
1852void Layer::useEmptyDamage() {
1853 surfaceDamageRegion.clear();
1854}
1855
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001856// ----------------------------------------------------------------------------
1857// pageflip handling...
1858// ----------------------------------------------------------------------------
1859
Dan Stoza6b9454d2014-11-07 16:00:59 -08001860bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001861 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07001862 return true;
1863 }
1864
Dan Stoza6b9454d2014-11-07 16:00:59 -08001865 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001866 if (mQueueItems.empty()) {
1867 return false;
1868 }
1869 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001870 nsecs_t expectedPresent =
1871 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001872
1873 // Ignore timestamps more than a second in the future
1874 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1875 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1876 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1877 expectedPresent);
1878
1879 bool isDue = timestamp < expectedPresent;
1880 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001881}
1882
Brian Andersond6927fb2016-07-23 23:37:30 -07001883bool Layer::onPreComposition(nsecs_t refreshStartTime) {
1884 if (mBufferLatched) {
1885 Mutex::Autolock lock(mFrameEventHistoryMutex);
1886 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
1887 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08001888 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001889 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001890}
1891
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001892bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
Brian Anderson3d4039d2016-09-23 16:31:30 -07001893 const std::shared_ptr<FenceTime>& presentFence,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001894 const std::shared_ptr<FenceTime>& retireFence,
1895 const CompositorTiming& compositorTiming) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001896 mAcquireTimeline.updateSignalTimes();
1897 mReleaseTimeline.updateSignalTimes();
1898
Brian Andersond6927fb2016-07-23 23:37:30 -07001899 // mFrameLatencyNeeded is true when a new frame was latched for the
1900 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08001901 if (!mFrameLatencyNeeded)
1902 return false;
1903
Fabien Sanglard28e98082016-12-05 10:19:46 -08001904 // Update mFrameEventHistory.
1905 {
1906 Mutex::Autolock lock(mFrameEventHistoryMutex);
1907 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001908 glDoneFence, presentFence, compositorTiming);
Fabien Sanglard28e98082016-12-05 10:19:46 -08001909 mFrameEventHistory.addRetire(mPreviousFrameNumber,
1910 retireFence);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001911 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08001912
1913 // Update mFrameTracker.
1914 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1915 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1916
Brian Anderson3d4039d2016-09-23 16:31:30 -07001917 std::shared_ptr<FenceTime> frameReadyFence =
1918 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08001919 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001920 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001921 } else {
1922 // There was no fence for this frame, so assume that it was ready
1923 // to be presented at the desired present time.
1924 mFrameTracker.setFrameReadyTime(desiredPresentTime);
1925 }
1926
Brian Anderson3d4039d2016-09-23 16:31:30 -07001927 if (presentFence->isValid()) {
1928 mFrameTracker.setActualPresentFence(
1929 std::shared_ptr<FenceTime>(presentFence));
1930 } else if (retireFence->isValid()) {
1931 mFrameTracker.setActualPresentFence(
1932 std::shared_ptr<FenceTime>(retireFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001933 } else {
1934 // The HWC doesn't support present fences, so use the refresh
1935 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07001936 mFrameTracker.setActualPresentTime(
1937 mFlinger->getHwComposer().getRefreshTimestamp(
1938 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001939 }
1940
1941 mFrameTracker.advanceFrame();
1942 mFrameLatencyNeeded = false;
1943 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001944}
1945
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001946#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07001947void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001948 mSurfaceFlingerConsumer->releasePendingBuffer();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001949 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07001950 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001951 mReleaseTimeline.push(releaseFenceTime);
1952
1953 Mutex::Autolock lock(mFrameEventHistoryMutex);
1954 mFrameEventHistory.addRelease(
Brian Andersonf6386862016-10-31 16:34:13 -07001955 mPreviousFrameNumber, dequeueReadyTime, std::move(releaseFenceTime));
Dan Stoza9e56aa02015-11-02 13:00:03 -08001956}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001957#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001958
Robert Carr1f0a16a2016-10-24 16:27:39 -07001959bool Layer::isHiddenByPolicy() const {
1960 const Layer::State& s(mDrawingState);
1961 const auto& parent = getParent();
1962 if (parent != nullptr && parent->isHiddenByPolicy()) {
1963 return true;
1964 }
1965 return s.flags & layer_state_t::eLayerHidden;
1966}
1967
Mathias Agopianda27af92012-09-13 18:17:13 -07001968bool Layer::isVisible() const {
Mathias Agopian13127d82013-03-05 17:47:11 -08001969 const Layer::State& s(mDrawingState);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001970#ifdef USE_HWC2
Robert Carr1f0a16a2016-10-24 16:27:39 -07001971 return !(isHiddenByPolicy()) && s.alpha > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08001972 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001973#else
Robert Carr1f0a16a2016-10-24 16:27:39 -07001974 return !(isHiddenByPolicy()) && s.alpha
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001975 && (mActiveBuffer != NULL || mSidebandStream != NULL);
1976#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07001977}
1978
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07001979bool Layer::allTransactionsSignaled() {
1980 auto headFrameNumber = getHeadFrameNumber();
1981 bool matchingFramesFound = false;
1982 bool allTransactionsApplied = true;
1983 Mutex::Autolock lock(mLocalSyncPointMutex);
1984
1985 for (auto& point : mLocalSyncPoints) {
1986 if (point->getFrameNumber() > headFrameNumber) {
1987 break;
1988 }
1989 matchingFramesFound = true;
1990
1991 if (!point->frameIsAvailable()) {
1992 // We haven't notified the remote layer that the frame for
1993 // this point is available yet. Notify it now, and then
1994 // abort this attempt to latch.
1995 point->setFrameAvailable();
1996 allTransactionsApplied = false;
1997 break;
1998 }
1999
2000 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2001 }
2002 return !matchingFramesFound || allTransactionsApplied;
2003}
2004
Brian Andersond6927fb2016-07-23 23:37:30 -07002005Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002006{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08002007 ATRACE_CALL();
2008
Jesse Hall399184a2014-03-03 15:42:54 -08002009 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2010 // mSidebandStreamChanged was true
2011 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07002012 if (mSidebandStream != NULL) {
2013 setTransactionFlags(eTransactionNeeded);
2014 mFlinger->setTransactionFlags(eTraversalNeeded);
2015 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07002016 recomputeVisibleRegions = true;
2017
2018 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07002019 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08002020 }
2021
Mathias Agopian4fec8732012-06-29 14:12:52 -07002022 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07002023 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2024 return outDirtyRegion;
2025 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002026
Fabien Sanglard223eb912016-10-13 10:15:06 -07002027 // if we've already called updateTexImage() without going through
2028 // a composition step, we have to skip this layer at this point
2029 // because we cannot call updateTeximage() without a corresponding
2030 // compositionComplete() call.
2031 // we'll trigger an update in onPreComposition().
2032 if (mRefreshPending) {
2033 return outDirtyRegion;
2034 }
2035
2036 // If the head buffer's acquire fence hasn't signaled yet, return and
2037 // try again later
2038 if (!headFenceHasSignaled()) {
2039 mFlinger->signalLayerUpdate();
2040 return outDirtyRegion;
2041 }
2042
2043 // Capture the old state of the layer for comparisons later
2044 const State& s(getDrawingState());
2045 const bool oldOpacity = isOpaque(s);
2046 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2047
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002048 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002049 mFlinger->signalLayerUpdate();
2050 return outDirtyRegion;
2051 }
2052
2053 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2054 // of the buffer queue isn't modified when the buffer queue is returning
2055 // BufferItem's that weren't actually queued. This can happen in shared
2056 // buffer mode.
2057 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002058 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2059 getProducerStickyTransform() != 0, mName.string(),
2060 mOverrideScalingMode, mFreezePositionUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002061 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2062 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2063 mLastFrameNumberReceived);
2064 if (updateResult == BufferQueue::PRESENT_LATER) {
2065 // Producer doesn't want buffer to be displayed yet. Signal a
2066 // layer update so we check again at the next opportunity.
2067 mFlinger->signalLayerUpdate();
2068 return outDirtyRegion;
2069 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2070 // If the buffer has been rejected, remove it from the shadow queue
2071 // and return early
2072 if (queuedBuffer) {
2073 Mutex::Autolock lock(mQueueItemLock);
2074 mQueueItems.removeAt(0);
2075 android_atomic_dec(&mQueuedFrames);
2076 }
2077 return outDirtyRegion;
2078 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2079 // This can occur if something goes wrong when trying to create the
2080 // EGLImage for this buffer. If this happens, the buffer has already
2081 // been released, so we need to clean up the queue and bug out
2082 // early.
2083 if (queuedBuffer) {
2084 Mutex::Autolock lock(mQueueItemLock);
2085 mQueueItems.clear();
2086 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002087 }
2088
Fabien Sanglard223eb912016-10-13 10:15:06 -07002089 // Once we have hit this state, the shadow queue may no longer
2090 // correctly reflect the incoming BufferQueue's contents, so even if
2091 // updateTexImage starts working, the only safe course of action is
2092 // to continue to ignore updates.
2093 mUpdateTexImageFailed = true;
2094
2095 return outDirtyRegion;
2096 }
2097
2098 if (queuedBuffer) {
2099 // Autolock scope
2100 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2101
2102 Mutex::Autolock lock(mQueueItemLock);
2103
2104 // Remove any stale buffers that have been dropped during
2105 // updateTexImage
2106 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2107 mQueueItems.removeAt(0);
2108 android_atomic_dec(&mQueuedFrames);
2109 }
2110
2111 mQueueItems.removeAt(0);
2112 }
2113
2114
2115 // Decrement the queued-frames count. Signal another event if we
2116 // have more frames pending.
2117 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2118 || mAutoRefresh) {
2119 mFlinger->signalLayerUpdate();
2120 }
2121
Fabien Sanglard223eb912016-10-13 10:15:06 -07002122 // update the active buffer
Chia-I Wu06d63de2017-01-04 14:58:51 +08002123 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2124 &mActiveBufferSlot);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002125 if (mActiveBuffer == NULL) {
2126 // this can only happen if the very first buffer was rejected.
2127 return outDirtyRegion;
2128 }
2129
Brian Andersond6927fb2016-07-23 23:37:30 -07002130 mBufferLatched = true;
2131 mPreviousFrameNumber = mCurrentFrameNumber;
2132 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2133
2134 {
2135 Mutex::Autolock lock(mFrameEventHistoryMutex);
2136 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2137#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002138 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002139 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002140 mReleaseTimeline.push(releaseFenceTime);
2141 mFrameEventHistory.addRelease(
Brian Andersonf6386862016-10-31 16:34:13 -07002142 mPreviousFrameNumber, latchTime, std::move(releaseFenceTime));
Brian Andersond6927fb2016-07-23 23:37:30 -07002143#endif
2144 }
2145
Fabien Sanglard223eb912016-10-13 10:15:06 -07002146 mRefreshPending = true;
2147 mFrameLatencyNeeded = true;
2148 if (oldActiveBuffer == NULL) {
2149 // the first time we receive a buffer, we need to trigger a
2150 // geometry invalidation.
2151 recomputeVisibleRegions = true;
2152 }
2153
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002154 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2155
Fabien Sanglard223eb912016-10-13 10:15:06 -07002156 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2157 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2158 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2159 if ((crop != mCurrentCrop) ||
2160 (transform != mCurrentTransform) ||
2161 (scalingMode != mCurrentScalingMode))
2162 {
2163 mCurrentCrop = crop;
2164 mCurrentTransform = transform;
2165 mCurrentScalingMode = scalingMode;
2166 recomputeVisibleRegions = true;
2167 }
2168
2169 if (oldActiveBuffer != NULL) {
2170 uint32_t bufWidth = mActiveBuffer->getWidth();
2171 uint32_t bufHeight = mActiveBuffer->getHeight();
2172 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2173 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002174 recomputeVisibleRegions = true;
2175 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002176 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002177
Fabien Sanglard223eb912016-10-13 10:15:06 -07002178 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2179 if (oldOpacity != isOpaque(s)) {
2180 recomputeVisibleRegions = true;
2181 }
Dan Stozacac35382016-01-27 12:21:06 -08002182
Fabien Sanglard223eb912016-10-13 10:15:06 -07002183 // Remove any sync points corresponding to the buffer which was just
2184 // latched
2185 {
2186 Mutex::Autolock lock(mLocalSyncPointMutex);
2187 auto point = mLocalSyncPoints.begin();
2188 while (point != mLocalSyncPoints.end()) {
2189 if (!(*point)->frameIsAvailable() ||
2190 !(*point)->transactionIsApplied()) {
2191 // This sync point must have been added since we started
2192 // latching. Don't drop it yet.
2193 ++point;
2194 continue;
2195 }
2196
2197 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2198 point = mLocalSyncPoints.erase(point);
2199 } else {
2200 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002201 }
2202 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002203 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002204
2205 // FIXME: postedRegion should be dirty & bounds
2206 Region dirtyRegion(Rect(s.active.w, s.active.h));
2207
2208 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002209 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002210
Mathias Agopian4fec8732012-06-29 14:12:52 -07002211 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002212}
2213
Mathias Agopiana67932f2011-04-20 14:20:59 -07002214uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002215{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002216 // TODO: should we do something special if mSecure is set?
2217 if (mProtectedByApp) {
2218 // need a hardware-protected path to external video sink
2219 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002220 }
Riley Andrews03414a12014-07-01 14:22:59 -07002221 if (mPotentialCursor) {
2222 usage |= GraphicBuffer::USAGE_CURSOR;
2223 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002224 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002225 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002226}
2227
Mathias Agopian84300952012-11-21 16:02:13 -08002228void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002229 uint32_t orientation = 0;
2230 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002231 // The transform hint is used to improve performance, but we can
2232 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002233 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002234 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002235 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002236 if (orientation & Transform::ROT_INVALID) {
2237 orientation = 0;
2238 }
2239 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002240 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002241}
2242
Mathias Agopian13127d82013-03-05 17:47:11 -08002243// ----------------------------------------------------------------------------
2244// debugging
2245// ----------------------------------------------------------------------------
2246
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002247void Layer::dump(String8& result, Colorizer& colorizer) const
Mathias Agopian13127d82013-03-05 17:47:11 -08002248{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002249 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08002250
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002251 colorizer.colorize(result, Colorizer::GREEN);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002252 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002253 "+ %s %p (%s)\n",
2254 getTypeId(), this, getName().string());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002255 colorizer.reset(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002256
Mathias Agopian2ca79392013-04-02 18:30:32 -07002257 s.activeTransparentRegion.dump(result, "transparentRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002258 visibleRegion.dump(result, "visibleRegion");
Dan Stozaee44edd2015-03-23 15:50:23 -07002259 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002260 sp<Client> client(mClientRef.promote());
2261
Mathias Agopian74d211a2013-04-22 16:55:35 +02002262 result.appendFormat( " "
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002263 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2264 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
Mathias Agopian13127d82013-03-05 17:47:11 -08002265 "isOpaque=%1d, invalidate=%1d, "
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002266#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08002267 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002268#else
2269 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2270#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08002271 " client=%p\n",
Robert Carr1f0a16a2016-10-24 16:27:39 -07002272 getLayerStack(), s.z,
2273 s.active.transform.tx(), s.active.transform.ty(),
2274 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07002275 s.crop.left, s.crop.top,
2276 s.crop.right, s.crop.bottom,
2277 s.finalCrop.left, s.finalCrop.top,
2278 s.finalCrop.right, s.finalCrop.bottom,
Andy McFadden4125a4f2014-01-29 17:17:11 -08002279 isOpaque(s), contentDirty,
Mathias Agopian13127d82013-03-05 17:47:11 -08002280 s.alpha, s.flags,
Robert Carr3dcabfa2016-03-01 18:36:58 -08002281 s.active.transform[0][0], s.active.transform[0][1],
2282 s.active.transform[1][0], s.active.transform[1][1],
Mathias Agopian13127d82013-03-05 17:47:11 -08002283 client.get());
Mathias Agopian13127d82013-03-05 17:47:11 -08002284
2285 sp<const GraphicBuffer> buf0(mActiveBuffer);
2286 uint32_t w0=0, h0=0, s0=0, f0=0;
2287 if (buf0 != 0) {
2288 w0 = buf0->getWidth();
2289 h0 = buf0->getHeight();
2290 s0 = buf0->getStride();
2291 f0 = buf0->format;
2292 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02002293 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002294 " "
2295 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2296 " queued-frames=%d, mRefreshPending=%d\n",
2297 mFormat, w0, h0, s0,f0,
2298 mQueuedFrames, mRefreshPending);
2299
Mathias Agopian13127d82013-03-05 17:47:11 -08002300 if (mSurfaceFlingerConsumer != 0) {
Colin Cross3d1d2802016-09-26 18:10:16 -07002301 mSurfaceFlingerConsumer->dumpState(result, " ");
Mathias Agopian13127d82013-03-05 17:47:11 -08002302 }
2303}
2304
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002305#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002306void Layer::miniDumpHeader(String8& result) {
2307 result.append("----------------------------------------");
2308 result.append("---------------------------------------\n");
2309 result.append(" Layer name\n");
2310 result.append(" Z | ");
2311 result.append(" Comp Type | ");
2312 result.append(" Disp Frame (LTRB) | ");
2313 result.append(" Source Crop (LTRB)\n");
2314 result.append("----------------------------------------");
2315 result.append("---------------------------------------\n");
2316}
2317
2318void Layer::miniDump(String8& result, int32_t hwcId) const {
2319 if (mHwcLayers.count(hwcId) == 0) {
2320 return;
2321 }
2322
2323 String8 name;
2324 if (mName.length() > 77) {
2325 std::string shortened;
2326 shortened.append(mName.string(), 36);
2327 shortened.append("[...]");
2328 shortened.append(mName.string() + (mName.length() - 36), 36);
2329 name = shortened.c_str();
2330 } else {
2331 name = mName;
2332 }
2333
2334 result.appendFormat(" %s\n", name.string());
2335
2336 const Layer::State& layerState(getDrawingState());
2337 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2338 result.appendFormat(" %10u | ", layerState.z);
2339 result.appendFormat("%10s | ",
2340 to_string(getCompositionType(hwcId)).c_str());
2341 const Rect& frame = hwcInfo.displayFrame;
2342 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2343 frame.right, frame.bottom);
Dan Stoza71bded52016-10-19 11:10:33 -07002344 const gfx::FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002345 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2346 crop.right, crop.bottom);
2347
2348 result.append("- - - - - - - - - - - - - - - - - - - - ");
2349 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2350}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002351#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002352
Svetoslavd85084b2014-03-20 10:28:31 -07002353void Layer::dumpFrameStats(String8& result) const {
2354 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002355}
2356
Svetoslavd85084b2014-03-20 10:28:31 -07002357void Layer::clearFrameStats() {
2358 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002359}
2360
Jamie Gennis6547ff42013-07-16 20:12:42 -07002361void Layer::logFrameStats() {
2362 mFrameTracker.logAndResetStats(mName);
2363}
2364
Svetoslavd85084b2014-03-20 10:28:31 -07002365void Layer::getFrameStats(FrameStats* outStats) const {
2366 mFrameTracker.getStats(outStats);
2367}
2368
Brian Andersond6927fb2016-07-23 23:37:30 -07002369void Layer::dumpFrameEvents(String8& result) {
2370 result.appendFormat("- Layer %s (%s, %p)\n",
2371 getName().string(), getTypeId(), this);
2372 Mutex::Autolock lock(mFrameEventHistoryMutex);
2373 mFrameEventHistory.checkFencesForCompletion();
2374 mFrameEventHistory.dump(result);
2375}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002376
Brian Anderson3890c392016-07-25 12:48:08 -07002377void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2378 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002379 Mutex::Autolock lock(mFrameEventHistoryMutex);
2380 if (newTimestamps) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002381 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002382 mFrameEventHistory.addQueue(*newTimestamps);
2383 }
2384
Brian Anderson3890c392016-07-25 12:48:08 -07002385 if (outDelta) {
2386 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002387 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002388}
Dan Stozae77c7662016-05-13 11:37:28 -07002389
2390std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2391 bool forceFlush) {
2392 std::vector<OccupancyTracker::Segment> history;
2393 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2394 &history);
2395 if (result != NO_ERROR) {
2396 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2397 result);
2398 return {};
2399 }
2400 return history;
2401}
2402
Robert Carr367c5682016-06-20 11:55:28 -07002403bool Layer::getTransformToDisplayInverse() const {
2404 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2405}
2406
Robert Carr1f0a16a2016-10-24 16:27:39 -07002407void Layer::addChild(const sp<Layer>& layer) {
2408 mCurrentChildren.add(layer);
2409 layer->setParent(this);
2410}
2411
2412ssize_t Layer::removeChild(const sp<Layer>& layer) {
2413 layer->setParent(nullptr);
2414 return mCurrentChildren.remove(layer);
2415}
2416
Robert Carr1db73f62016-12-21 12:58:51 -08002417bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2418 sp<Handle> handle = nullptr;
2419 sp<Layer> newParent = nullptr;
2420 if (newParentHandle == nullptr) {
2421 return false;
2422 }
2423 handle = static_cast<Handle*>(newParentHandle.get());
2424 newParent = handle->owner.promote();
2425 if (newParent == nullptr) {
2426 ALOGE("Unable to promote Layer handle");
2427 return false;
2428 }
2429
2430 for (const sp<Layer>& child : mCurrentChildren) {
2431 newParent->addChild(child);
2432
2433 sp<Client> client(child->mClientRef.promote());
2434 if (client != nullptr) {
2435 client->setParentLayer(newParent);
2436 }
2437 }
2438 mCurrentChildren.clear();
2439
2440 return true;
2441}
2442
Robert Carr1f0a16a2016-10-24 16:27:39 -07002443void Layer::setParent(const sp<Layer>& layer) {
2444 mParent = layer;
2445}
2446
2447void Layer::clearSyncPoints() {
2448 for (const auto& child : mCurrentChildren) {
2449 child->clearSyncPoints();
2450 }
2451
2452 Mutex::Autolock lock(mLocalSyncPointMutex);
2453 for (auto& point : mLocalSyncPoints) {
2454 point->setFrameAvailable();
2455 }
2456 mLocalSyncPoints.clear();
2457}
2458
2459int32_t Layer::getZ() const {
2460 return mDrawingState.z;
2461}
2462
2463/**
2464 * Negatively signed children are before 'this' in Z-order.
2465 */
2466void Layer::traverseInZOrder(const std::function<void(Layer*)>& exec) {
2467 size_t i = 0;
2468 for (; i < mDrawingChildren.size(); i++) {
2469 const auto& child = mDrawingChildren[i];
2470 if (child->getZ() >= 0)
2471 break;
2472 child->traverseInZOrder(exec);
2473 }
2474 exec(this);
2475 for (; i < mDrawingChildren.size(); i++) {
2476 const auto& child = mDrawingChildren[i];
2477 child->traverseInZOrder(exec);
2478 }
2479}
2480
2481/**
2482 * Positively signed children are before 'this' in reverse Z-order.
2483 */
2484void Layer::traverseInReverseZOrder(const std::function<void(Layer*)>& exec) {
2485 int32_t i = 0;
2486 for (i = mDrawingChildren.size()-1; i>=0; i--) {
2487 const auto& child = mDrawingChildren[i];
2488 if (child->getZ() < 0) {
2489 break;
2490 }
2491 child->traverseInReverseZOrder(exec);
2492 }
2493 exec(this);
2494 for (; i>=0; i--) {
2495 const auto& child = mDrawingChildren[i];
2496 child->traverseInReverseZOrder(exec);
2497 }
2498}
2499
2500Transform Layer::getTransform() const {
2501 Transform t;
2502 const auto& p = getParent();
2503 if (p != nullptr) {
2504 t = p->getTransform();
2505 }
2506 return t * getDrawingState().active.transform;
2507}
2508
2509void Layer::commitChildList() {
2510 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2511 const auto& child = mCurrentChildren[i];
2512 child->commitChildList();
2513 }
2514 mDrawingChildren = mCurrentChildren;
2515}
2516
Mathias Agopian13127d82013-03-05 17:47:11 -08002517// ---------------------------------------------------------------------------
2518
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002519}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002520
2521#if defined(__gl_h_)
2522#error "don't include gl/gl.h in this file"
2523#endif
2524
2525#if defined(__gl2_h_)
2526#error "don't include gl2/gl2.h in this file"
2527#endif