blob: 06a0765719feb0af093642ee23c8d8f9f330ad38 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017//#define LOG_NDEBUG 0
18#undef LOG_TAG
19#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080020#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <stdlib.h>
23#include <stdint.h>
24#include <sys/types.h>
Mathias Agopian13127d82013-03-05 17:47:11 -080025#include <math.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080026
Mathias Agopiana67932f2011-04-20 14:20:59 -070027#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070028#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070029#include <cutils/properties.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
31#include <utils/Errors.h>
32#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080033#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080034#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080035#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080036
Mathias Agopian3330b202009-10-05 17:07:12 -070037#include <ui/GraphicBuffer.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080038#include <ui/PixelFormat.h>
Mathias Agopian9cce3252010-02-09 17:46:37 -080039
Dan Stoza6b9454d2014-11-07 16:00:59 -080040#include <gui/BufferItem.h>
Mathias Agopiana9347642017-02-13 16:42:28 -080041#include <gui/BufferQueue.h>
Mathias Agopian90ac7992012-02-25 18:48:35 -080042#include <gui/Surface.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080043
44#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020045#include "Colorizer.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070046#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080047#include "Layer.h"
Fabien Sanglard7b1563a2016-10-13 12:05:28 -070048#include "LayerRejecter.h"
Dan Stozab9b08832014-03-13 11:55:57 -070049#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080050#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080051
Mathias Agopian1b031492012-06-20 17:51:20 -070052#include "DisplayHardware/HWComposer.h"
53
Mathias Agopian875d8e12013-06-07 15:35:48 -070054#include "RenderEngine/RenderEngine.h"
55
Dan Stozac5da2712016-07-20 15:38:12 -070056#include <mutex>
57
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058#define DEBUG_RESIZE 0
59
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060namespace android {
61
62// ---------------------------------------------------------------------------
63
Mathias Agopian13127d82013-03-05 17:47:11 -080064int32_t Layer::sSequence = 1;
65
Mathias Agopian4d9b8222013-03-12 17:11:48 -070066Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
67 const String8& name, uint32_t w, uint32_t h, uint32_t flags)
Mathias Agopian13127d82013-03-05 17:47:11 -080068 : contentDirty(false),
69 sequence(uint32_t(android_atomic_inc(&sSequence))),
70 mFlinger(flinger),
Mathias Agopiana67932f2011-04-20 14:20:59 -070071 mTextureName(-1U),
Mathias Agopian13127d82013-03-05 17:47:11 -080072 mPremultipliedAlpha(true),
73 mName("unnamed"),
Mathias Agopian13127d82013-03-05 17:47:11 -080074 mFormat(PIXEL_FORMAT_NONE),
Mathias Agopian13127d82013-03-05 17:47:11 -080075 mTransactionFlags(0),
Dan Stoza7dde5992015-05-22 09:51:44 -070076 mPendingStateMutex(),
77 mPendingStates(),
Mathias Agopiana67932f2011-04-20 14:20:59 -070078 mQueuedFrames(0),
Jesse Hall399184a2014-03-03 15:42:54 -080079 mSidebandStreamChanged(false),
Mathias Agopiana9347642017-02-13 16:42:28 -080080 mActiveBufferSlot(BufferQueue::INVALID_BUFFER_SLOT),
Mathias Agopiana67932f2011-04-20 14:20:59 -070081 mCurrentTransform(0),
Mathias Agopian933389f2011-07-18 16:15:08 -070082 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
Robert Carrc3574f72016-03-24 12:19:32 -070083 mOverrideScalingMode(-1),
Mathias Agopiana67932f2011-04-20 14:20:59 -070084 mCurrentOpacity(true),
Brian Andersond6927fb2016-07-23 23:37:30 -070085 mBufferLatched(false),
Dan Stozacac35382016-01-27 12:21:06 -080086 mCurrentFrameNumber(0),
Brian Anderson8cc8b102016-10-21 12:43:09 -070087 mPreviousFrameNumber(0),
Mathias Agopian4d143ee2012-02-23 20:05:39 -080088 mRefreshPending(false),
Mathias Agopian82d7ab62012-01-19 18:34:40 -080089 mFrameLatencyNeeded(false),
Mathias Agopian13127d82013-03-05 17:47:11 -080090 mFiltering(false),
91 mNeedsFiltering(false),
Mathias Agopian5cdc8992013-08-13 20:51:23 -070092 mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
Fabien Sanglard9d96de42016-10-11 00:15:18 +000093#ifndef USE_HWC2
94 mIsGlesComposition(false),
95#endif
Mathias Agopian13127d82013-03-05 17:47:11 -080096 mProtectedByApp(false),
97 mHasSurface(false),
Riley Andrews03414a12014-07-01 14:22:59 -070098 mClientRef(client),
Dan Stozaa4650a52015-05-12 12:56:16 -070099 mPotentialCursor(false),
100 mQueueItemLock(),
101 mQueueItemCondition(),
102 mQueueItems(),
Dan Stoza65476f32015-05-14 09:27:25 -0700103 mLastFrameNumberReceived(0),
Pablo Ceballos04839ab2015-11-13 13:39:23 -0800104 mUpdateTexImageFailed(false),
Robert Carr82364e32016-05-15 11:27:47 -0700105 mAutoRefresh(false),
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;
Mathias Agopian0556d792017-03-22 15:49:32 -0700170 BufferQueue::createBufferQueue(&producer, &consumer, true);
Robert Carr1db73f62016-12-21 12:58:51 -0800171 mProducer = new MonitoredProducer(producer, mFlinger, this);
Irvel468051e2016-06-13 16:44:44 -0700172 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800173 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Jesse Hall399184a2014-03-03 15:42:54 -0800174 mSurfaceFlingerConsumer->setContentsChangedListener(this);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700175 mSurfaceFlingerConsumer->setName(mName);
Daniel Lamb2675792012-02-23 14:35:13 -0800176
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800177 if (mFlinger->isLayerTripleBufferingDisabled()) {
178 mProducer->setMaxDequeuedBufferCount(2);
179 }
Andy McFadden69052052012-09-14 16:10:11 -0700180
Mathias Agopian84300952012-11-21 16:02:13 -0800181 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
182 updateTransformHint(hw);
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700183}
184
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700185Layer::~Layer() {
Pablo Ceballos8ea4e7b2016-03-03 15:20:02 -0800186 sp<Client> c(mClientRef.promote());
187 if (c != 0) {
188 c->detachLayer(this);
189 }
190
Dan Stozacac35382016-01-27 12:21:06 -0800191 for (auto& point : mRemoteSyncPoints) {
192 point->setTransactionApplied();
193 }
Dan Stozac8145172016-04-28 16:29:06 -0700194 for (auto& point : mLocalSyncPoints) {
195 point->setFrameAvailable();
196 }
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700197 mFlinger->deleteTextureAsync(mTextureName);
Jamie Gennis6547ff42013-07-16 20:12:42 -0700198 mFrameTracker.logAndResetStats(mName);
Mathias Agopian96f08192010-06-02 23:28:45 -0700199}
200
Mathias Agopian13127d82013-03-05 17:47:11 -0800201// ---------------------------------------------------------------------------
202// callbacks
203// ---------------------------------------------------------------------------
204
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000205#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800206void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
207 if (mHwcLayers.empty()) {
208 return;
209 }
210 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
211}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000212#else
213void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
214 HWComposer::HWCLayerInterface* layer) {
215 if (layer) {
216 layer->onDisplayed();
217 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
218 }
219}
220#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800221
Dan Stoza6b9454d2014-11-07 16:00:59 -0800222void Layer::onFrameAvailable(const BufferItem& item) {
223 // Add this buffer from our internal queue tracker
224 { // Autolock scope
225 Mutex::Autolock lock(mQueueItemLock);
Irvel468051e2016-06-13 16:44:44 -0700226 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
227 item.mGraphicBuffer->getHeight(), item.mFrameNumber);
Dan Stozaa4650a52015-05-12 12:56:16 -0700228 // Reset the frame number tracker when we receive the first buffer after
229 // a frame number reset
230 if (item.mFrameNumber == 1) {
231 mLastFrameNumberReceived = 0;
232 }
233
234 // Ensure that callbacks are handled in order
235 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
236 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
237 ms2ns(500));
238 if (result != NO_ERROR) {
239 ALOGE("[%s] Timed out waiting on callback", mName.string());
240 }
241 }
242
Dan Stoza6b9454d2014-11-07 16:00:59 -0800243 mQueueItems.push_back(item);
Dan Stozaecc50402015-04-28 14:42:06 -0700244 android_atomic_inc(&mQueuedFrames);
Dan Stozaa4650a52015-05-12 12:56:16 -0700245
246 // Wake up any pending callbacks
247 mLastFrameNumberReceived = item.mFrameNumber;
248 mQueueItemCondition.broadcast();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800249 }
250
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800251 mFlinger->signalLayerUpdate();
Mathias Agopian579b3f82010-06-08 19:54:15 -0700252}
253
Dan Stoza6b9454d2014-11-07 16:00:59 -0800254void Layer::onFrameReplaced(const BufferItem& item) {
Dan Stoza7dde5992015-05-22 09:51:44 -0700255 { // Autolock scope
256 Mutex::Autolock lock(mQueueItemLock);
Dan Stozaa4650a52015-05-12 12:56:16 -0700257
Dan Stoza7dde5992015-05-22 09:51:44 -0700258 // Ensure that callbacks are handled in order
259 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
260 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
261 ms2ns(500));
262 if (result != NO_ERROR) {
263 ALOGE("[%s] Timed out waiting on callback", mName.string());
264 }
Dan Stozaa4650a52015-05-12 12:56:16 -0700265 }
Dan Stoza7dde5992015-05-22 09:51:44 -0700266
267 if (mQueueItems.empty()) {
268 ALOGE("Can't replace a frame on an empty queue");
269 return;
270 }
Pablo Ceballos4d85da42016-04-19 20:11:56 -0700271 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
Dan Stoza7dde5992015-05-22 09:51:44 -0700272
273 // Wake up any pending callbacks
274 mLastFrameNumberReceived = item.mFrameNumber;
275 mQueueItemCondition.broadcast();
Dan Stozaa4650a52015-05-12 12:56:16 -0700276 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800277}
278
Jesse Hall399184a2014-03-03 15:42:54 -0800279void Layer::onSidebandStreamChanged() {
280 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
281 // mSidebandStreamChanged was false
282 mFlinger->signalLayerUpdate();
283 }
284}
285
Mathias Agopian67106042013-03-14 19:18:13 -0700286// called with SurfaceFlinger::mStateLock from the drawing thread after
287// the layer has been remove from the current state list (and just before
288// it's removed from the drawing state list)
Mathias Agopian13127d82013-03-05 17:47:11 -0800289void Layer::onRemoved() {
Robert Carr5edb1ad2017-04-25 10:54:24 -0700290 if (mCurrentState.zOrderRelativeOf != nullptr) {
291 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
292 if (strongRelative != nullptr) {
293 strongRelative->removeZOrderRelative(this);
294 }
295 mCurrentState.zOrderRelativeOf = nullptr;
296 }
297
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800298 mSurfaceFlingerConsumer->abandon();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700299 for (const auto& child : mCurrentChildren) {
300 child->onRemoved();
301 }
Mathias Agopian48d819a2009-09-10 19:41:18 -0700302}
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700303
Mathias Agopian13127d82013-03-05 17:47:11 -0800304// ---------------------------------------------------------------------------
305// set-up
306// ---------------------------------------------------------------------------
307
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700308const String8& Layer::getName() const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800309 return mName;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800310}
311
Mathias Agopianf9d93272009-06-19 17:00:27 -0700312status_t Layer::setBuffers( uint32_t w, uint32_t h,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800313 PixelFormat format, uint32_t flags)
314{
Mathias Agopianca99fb82010-04-14 16:43:44 -0700315 uint32_t const maxSurfaceDims = min(
Mathias Agopiana4912602012-07-12 14:25:33 -0700316 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
Mathias Agopianca99fb82010-04-14 16:43:44 -0700317
318 // never allow a surface larger than what our underlying GL implementation
319 // can handle.
320 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
Mathias Agopianff615cc2012-02-24 14:58:36 -0800321 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700322 return BAD_VALUE;
323 }
324
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700325 mFormat = format;
Mathias Agopianeff062c2010-08-25 14:59:15 -0700326
Riley Andrews03414a12014-07-01 14:22:59 -0700327 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
Mathias Agopian3165cc22012-08-08 19:42:09 -0700328 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700329 mCurrentOpacity = getOpacityForFormat(format);
330
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800331 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
332 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
333 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700334
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800335 return NO_ERROR;
336}
337
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700338sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800339 Mutex::Autolock _l(mLock);
340
341 LOG_ALWAYS_FATAL_IF(mHasSurface,
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700342 "Layer::getHandle() has already been called");
Mathias Agopian13127d82013-03-05 17:47:11 -0800343
344 mHasSurface = true;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700345
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700346 return new Handle(mFlinger, this);
Mathias Agopian13127d82013-03-05 17:47:11 -0800347}
348
Dan Stozab9b08832014-03-13 11:55:57 -0700349sp<IGraphicBufferProducer> Layer::getProducer() const {
350 return mProducer;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700351}
352
Mathias Agopian13127d82013-03-05 17:47:11 -0800353// ---------------------------------------------------------------------------
354// h/w composer set-up
355// ---------------------------------------------------------------------------
356
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800357Rect Layer::getContentCrop() const {
358 // this is the crop rectangle that applies to the buffer
359 // itself (as opposed to the window)
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700360 Rect crop;
361 if (!mCurrentCrop.isEmpty()) {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800362 // if the buffer crop is defined, we use that
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700363 crop = mCurrentCrop;
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800364 } else if (mActiveBuffer != NULL) {
365 // otherwise we use the whole buffer
366 crop = mActiveBuffer->getBounds();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700367 } else {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800368 // if we don't have a buffer yet, we use an empty/invalid crop
Mathias Agopian4fec8732012-06-29 14:12:52 -0700369 crop.makeInvalid();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700370 }
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700371 return crop;
372}
373
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700374static Rect reduce(const Rect& win, const Region& exclude) {
375 if (CC_LIKELY(exclude.isEmpty())) {
376 return win;
377 }
378 if (exclude.isRect()) {
379 return win.reduce(exclude.getBounds());
380 }
381 return Region(win).subtract(exclude).getBounds();
382}
383
Robert Carr1f0a16a2016-10-24 16:27:39 -0700384Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
385 const Layer::State& s(getDrawingState());
386 Rect win(s.active.w, s.active.h);
387
388 if (!s.crop.isEmpty()) {
389 win.intersect(s.crop, &win);
390 }
391
392 Transform t = getTransform();
393 win = t.transform(win);
394
395 const sp<Layer>& p = getParent();
396 // Now we need to calculate the parent bounds, so we can clip ourselves to those.
397 // When calculating the parent bounds for purposes of clipping,
398 // we don't need to constrain the parent to its transparent region.
399 // The transparent region is an optimization based on the
400 // buffer contents of the layer, but does not affect the space allocated to
401 // it by policy, and thus children should be allowed to extend into the
402 // parent's transparent region. In fact one of the main uses, is to reduce
403 // buffer allocation size in cases where a child window sits behind a main window
404 // (by marking the hole in the parent window as a transparent region)
405 if (p != nullptr) {
406 Rect bounds = p->computeScreenBounds(false);
407 bounds.intersect(win, &win);
408 }
409
410 if (reduceTransparentRegion) {
411 auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
412 win = reduce(win, screenTransparentRegion);
413 }
414
415 return win;
416}
417
Mathias Agopian13127d82013-03-05 17:47:11 -0800418Rect Layer::computeBounds() const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700419 const Layer::State& s(getDrawingState());
Michael Lentine6c925ed2014-09-26 17:55:01 -0700420 return computeBounds(s.activeTransparentRegion);
421}
422
423Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
424 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800425 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700426
427 if (!s.crop.isEmpty()) {
428 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -0800429 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700430
431 Rect bounds = win;
432 const auto& p = getParent();
433 if (p != nullptr) {
Robert Carrde9ec442017-02-08 17:43:36 -0800434 // Look in computeScreenBounds recursive call for explanation of
435 // why we pass false here.
436 bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700437 }
438
439 Transform t = getTransform();
440 if (p != nullptr) {
441 win = t.transform(win);
442 win.intersect(bounds, &win);
443 win = t.inverse().transform(win);
444 }
445
Mathias Agopian6c7f25a2013-05-09 20:37:10 -0700446 // subtract the transparent region and snap to the bounds
Michael Lentine6c925ed2014-09-26 17:55:01 -0700447 return reduce(win, activeTransparentRegion);
Mathias Agopian13127d82013-03-05 17:47:11 -0800448}
449
Robert Carr1f0a16a2016-10-24 16:27:39 -0700450Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
Robert Carrb5d3d262016-03-25 15:08:13 -0700451 // the crop is the area of the window that gets cropped, but not
Mathias Agopian13127d82013-03-05 17:47:11 -0800452 // scaled in any ways.
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700453 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800454
455 // apply the projection's clipping to the window crop in
456 // layerstack space, and convert-back to layer space.
Mathias Agopian6b442672013-07-09 21:24:52 -0700457 // if there are no window scaling involved, this operation will map to full
458 // pixels in the buffer.
459 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
460 // a viewport clipping and a window transform. we should use floating point to fix this.
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700461
462 Rect activeCrop(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700463 if (!s.crop.isEmpty()) {
464 activeCrop = s.crop;
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700465 }
466
Robert Carr1f0a16a2016-10-24 16:27:39 -0700467 Transform t = getTransform();
468 activeCrop = t.transform(activeCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000469 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
470 activeCrop.clear();
471 }
Robert Carrb5d3d262016-03-25 15:08:13 -0700472 if (!s.finalCrop.isEmpty()) {
473 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000474 activeCrop.clear();
475 }
476 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700477 return activeCrop;
478}
479
Dan Stoza5a423ea2017-02-16 14:10:39 -0800480FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
Robert Carr1f0a16a2016-10-24 16:27:39 -0700481 // the content crop is the area of the content that gets scaled to the
482 // layer's size. This is in buffer space.
Dan Stoza5a423ea2017-02-16 14:10:39 -0800483 FloatRect crop = getContentCrop().toFloatRect();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700484
485 // In addition there is a WM-specified crop we pull from our drawing state.
486 const State& s(getDrawingState());
487
488 // Screen space to make reduction to parent crop clearer.
489 Rect activeCrop = computeInitialCrop(hw);
490 const auto& p = getParent();
491 if (p != nullptr) {
492 auto parentCrop = p->computeInitialCrop(hw);
493 activeCrop.intersect(parentCrop, &activeCrop);
494 }
495 Transform t = getTransform();
496 // Back to layer space to work with the content crop.
497 activeCrop = t.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800498
Michael Lentine28ea2172014-11-19 18:32:37 -0800499 // This needs to be here as transform.transform(Rect) computes the
500 // transformed rect and then takes the bounding box of the result before
501 // returning. This means
502 // transform.inverse().transform(transform.transform(Rect)) != Rect
503 // in which case we need to make sure the final rect is clipped to the
504 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000505 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
506 activeCrop.clear();
507 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800508
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700509 // subtract the transparent region and snap to the bounds
510 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
511
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000512 // Transform the window crop to match the buffer coordinate system,
513 // which means using the inverse of the current transform set on the
514 // SurfaceFlingerConsumer.
515 uint32_t invTransform = mCurrentTransform;
Robert Carrcae605c2017-03-29 12:10:31 -0700516 if (getTransformToDisplayInverse()) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000517 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700518 * the code below applies the primary display's inverse transform to the
519 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000520 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700521 uint32_t invTransformOrient =
522 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000523 // calculate the inverse transform
524 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
525 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
526 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800527 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000528 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700529 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
530 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800531 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000532
533 int winWidth = s.active.w;
534 int winHeight = s.active.h;
535 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
536 // If the activeCrop has been rotate the ends are rotated but not
537 // the space itself so when transforming ends back we can't rely on
538 // a modification of the axes of rotation. To account for this we
539 // need to reorient the inverse rotation in terms of the current
540 // axes of rotation.
541 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
542 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
543 if (is_h_flipped == is_v_flipped) {
544 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
545 NATIVE_WINDOW_TRANSFORM_FLIP_H;
546 }
547 winWidth = s.active.h;
548 winHeight = s.active.w;
549 }
550 const Rect winCrop = activeCrop.transform(
551 invTransform, s.active.w, s.active.h);
552
553 // below, crop is intersected with winCrop expressed in crop's coordinate space
554 float xScale = crop.getWidth() / float(winWidth);
555 float yScale = crop.getHeight() / float(winHeight);
556
557 float insetL = winCrop.left * xScale;
558 float insetT = winCrop.top * yScale;
559 float insetR = (winWidth - winCrop.right ) * xScale;
560 float insetB = (winHeight - winCrop.bottom) * yScale;
561
562 crop.left += insetL;
563 crop.top += insetT;
564 crop.right -= insetR;
565 crop.bottom -= insetB;
566
Mathias Agopian13127d82013-03-05 17:47:11 -0800567 return crop;
568}
569
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000570#ifdef USE_HWC2
Robert Carrae060832016-11-28 10:51:00 -0800571void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000572#else
573void Layer::setGeometry(
574 const sp<const DisplayDevice>& hw,
575 HWComposer::HWCLayerInterface& layer)
576#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700577{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000578#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800579 const auto hwcId = displayDevice->getHwcDisplayId();
580 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000581#else
582 layer.setDefaultState();
583#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700584
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700585 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000586#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800587 hwcInfo.forceClientComposition = false;
588
589 if (isSecure() && !displayDevice->isSecure()) {
590 hwcInfo.forceClientComposition = true;
591 }
592
593 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000594#else
595 layer.setSkip(false);
596
597 if (isSecure() && !hw->isSecure()) {
598 layer.setSkip(true);
599 }
600#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700601
Mathias Agopian13127d82013-03-05 17:47:11 -0800602 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700603 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000604#ifdef USE_HWC2
David Revemanecf0fa52017-03-03 11:32:44 -0500605 auto blendMode = HWC2::BlendMode::None;
Robert Carr6452f122017-03-21 10:41:29 -0700606 if (!isOpaque(s) || getAlpha() != 1.0f) {
David Revemanecf0fa52017-03-03 11:32:44 -0500607 blendMode = mPremultipliedAlpha ?
Dan Stoza9e56aa02015-11-02 13:00:03 -0800608 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800609 }
David Revemanecf0fa52017-03-03 11:32:44 -0500610 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));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000614#else
Robert Carr6452f122017-03-21 10:41:29 -0700615 if (!isOpaque(s) || getAlpha() != 0xFF) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000616 layer.setBlending(mPremultipliedAlpha ?
617 HWC_BLENDING_PREMULT :
618 HWC_BLENDING_COVERAGE);
619 }
620#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800621
622 // apply the layer's transform, followed by the display's global transform
623 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700624 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700625 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -0700626 if (!s.crop.isEmpty()) {
627 Rect activeCrop(s.crop);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700628 activeCrop = t.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000629#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000630 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000631#else
632 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
633#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000634 activeCrop.clear();
635 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700636 activeCrop = t.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800637 // This needs to be here as transform.transform(Rect) computes the
638 // transformed rect and then takes the bounding box of the result before
639 // returning. This means
640 // transform.inverse().transform(transform.transform(Rect)) != Rect
641 // in which case we need to make sure the final rect is clipped to the
642 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000643 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
644 activeCrop.clear();
645 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700646 // mark regions outside the crop as transparent
647 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
648 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
649 s.active.w, s.active.h));
650 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
651 activeCrop.left, activeCrop.bottom));
652 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
653 s.active.w, activeCrop.bottom));
654 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700655
656 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700657 if (!s.finalCrop.isEmpty()) {
658 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000659 frame.clear();
660 }
661 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000662#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000663 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
664 frame.clear();
665 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800666 const Transform& tr(displayDevice->getTransform());
667 Rect transformedFrame = tr.transform(frame);
David Revemanecf0fa52017-03-03 11:32:44 -0500668 error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700669 if (error != HWC2::Error::None) {
670 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
671 mName.string(), transformedFrame.left, transformedFrame.top,
672 transformedFrame.right, transformedFrame.bottom,
673 to_string(error).c_str(), static_cast<int32_t>(error));
674 } else {
675 hwcInfo.displayFrame = transformedFrame;
676 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800677
Dan Stoza5a423ea2017-02-16 14:10:39 -0800678 FloatRect sourceCrop = computeCrop(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800679 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700680 if (error != HWC2::Error::None) {
681 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
682 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
683 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
684 static_cast<int32_t>(error));
685 } else {
686 hwcInfo.sourceCrop = sourceCrop;
687 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800688
Robert Carr6452f122017-03-21 10:41:29 -0700689 float alpha = getAlpha();
690 error = hwcLayer->setPlaneAlpha(alpha);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800691 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
Robert Carr6452f122017-03-21 10:41:29 -0700692 "%s (%d)", mName.string(), alpha, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800693 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
Albert Chaulk2a589632017-05-04 16:59:44 -0400700 int type = s.type;
701 int appId = s.appId;
702 sp<Layer> parent = mParent.promote();
703 if (parent.get()) {
704 auto& parentState = parent->getDrawingState();
705 type = parentState.type;
706 appId = parentState.appId;
707 }
708
709 error = hwcLayer->setInfo(type, appId);
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500710 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
711 mName.string(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000712#else
713 if (!frame.intersect(hw->getViewport(), &frame)) {
714 frame.clear();
715 }
716 const Transform& tr(hw->getTransform());
717 layer.setFrame(tr.transform(frame));
718 layer.setCrop(computeCrop(hw));
Robert Carr6452f122017-03-21 10:41:29 -0700719 layer.setPlaneAlpha(getAlpha());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000720#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800721
Mathias Agopian29a367b2011-07-12 14:51:45 -0700722 /*
723 * Transformations are applied in this order:
724 * 1) buffer orientation/flip/mirror
725 * 2) state transformation (window manager)
726 * 3) layer orientation (screen orientation)
727 * (NOTE: the matrices are multiplied in reverse order)
728 */
729
730 const Transform bufferOrientation(mCurrentTransform);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700731 Transform transform(tr * t * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700732
Robert Carrcae605c2017-03-29 12:10:31 -0700733 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700734 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700735 * the code below applies the primary display's inverse transform to the
736 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700737 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700738 uint32_t invTransform =
739 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700740 // calculate the inverse transform
741 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
742 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
743 NATIVE_WINDOW_TRANSFORM_FLIP_H;
744 }
Robert Carrcae605c2017-03-29 12:10:31 -0700745
746 /*
747 * Here we cancel out the orientation component of the WM transform.
748 * The scaling and translate components are already included in our bounds
749 * computation so it's enough to just omit it in the composition.
750 * See comment in onDraw with ref to b/36727915 for why.
751 */
752 transform = Transform(invTransform) * tr * bufferOrientation;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700753 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700754
755 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800756 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000757#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800758 if (orientation & Transform::ROT_INVALID) {
759 // we can only handle simple transformation
760 hwcInfo.forceClientComposition = true;
761 } else {
762 auto transform = static_cast<HWC2::Transform>(orientation);
763 auto error = hwcLayer->setTransform(transform);
764 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
765 "%s (%d)", mName.string(), to_string(transform).c_str(),
766 to_string(error).c_str(), static_cast<int32_t>(error));
767 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000768#else
769 if (orientation & Transform::ROT_INVALID) {
770 // we can only handle simple transformation
771 layer.setSkip(true);
772 } else {
773 layer.setTransform(orientation);
774 }
775#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700776}
777
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000778#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800779void Layer::forceClientComposition(int32_t hwcId) {
780 if (mHwcLayers.count(hwcId) == 0) {
781 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
782 return;
783 }
784
785 mHwcLayers[hwcId].forceClientComposition = true;
786}
Dan Stoza9e56aa02015-11-02 13:00:03 -0800787
Dan Stoza9e56aa02015-11-02 13:00:03 -0800788void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
789 // Apply this display's projection's viewport to the visible region
790 // before giving it to the HWC HAL.
791 const Transform& tr = displayDevice->getTransform();
792 const auto& viewport = displayDevice->getViewport();
793 Region visible = tr.transform(visibleRegion.intersect(viewport));
794 auto hwcId = displayDevice->getHwcDisplayId();
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800795 auto& hwcInfo = mHwcLayers[hwcId];
796 auto& hwcLayer = hwcInfo.layer;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800797 auto error = hwcLayer->setVisibleRegion(visible);
798 if (error != HWC2::Error::None) {
799 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
800 to_string(error).c_str(), static_cast<int32_t>(error));
801 visible.dump(LOG_TAG);
802 }
803
804 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
805 if (error != HWC2::Error::None) {
806 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
807 to_string(error).c_str(), static_cast<int32_t>(error));
808 surfaceDamageRegion.dump(LOG_TAG);
809 }
810
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700811 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800812 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700813 setCompositionType(hwcId, HWC2::Composition::Sideband);
814 ALOGV("[%s] Requesting Sideband composition", mName.string());
815 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800816 if (error != HWC2::Error::None) {
817 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
818 mName.string(), mSidebandStream->handle(),
819 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800820 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700821 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800822 }
823
Dan Stoza0a21df72016-07-20 12:52:38 -0700824 // Client layers
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800825 if (hwcInfo.forceClientComposition ||
Dan Stoza0a21df72016-07-20 12:52:38 -0700826 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700827 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800828 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700829 return;
830 }
831
Dan Stoza0a21df72016-07-20 12:52:38 -0700832 // SolidColor layers
833 if (mActiveBuffer == nullptr) {
834 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700835
836 // For now, we only support black for DimLayer
Dan Stoza0a21df72016-07-20 12:52:38 -0700837 error = hwcLayer->setColor({0, 0, 0, 255});
838 if (error != HWC2::Error::None) {
839 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
840 to_string(error).c_str(), static_cast<int32_t>(error));
841 }
Dan Stozac6c89542016-07-27 10:16:52 -0700842
843 // Clear out the transform, because it doesn't make sense absent a
844 // source buffer
845 error = hwcLayer->setTransform(HWC2::Transform::None);
846 if (error != HWC2::Error::None) {
847 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
848 to_string(error).c_str(), static_cast<int32_t>(error));
849 }
850
Dan Stoza0a21df72016-07-20 12:52:38 -0700851 return;
852 }
853
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700854 // Device or Cursor layers
855 if (mPotentialCursor) {
856 ALOGV("[%s] Requesting Cursor composition", mName.string());
857 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800858 } else {
859 ALOGV("[%s] Requesting Device composition", mName.string());
860 setCompositionType(hwcId, HWC2::Composition::Device);
861 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700862
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700863 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
864 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
865 if (error != HWC2::Error::None) {
866 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
867 mCurrentState.dataSpace, to_string(error).c_str(),
868 static_cast<int32_t>(error));
869 }
870
Chia-I Wu06d63de2017-01-04 14:58:51 +0800871 uint32_t hwcSlot = 0;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400872 sp<GraphicBuffer> hwcBuffer;
873 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
874 &hwcSlot, &hwcBuffer);
Chia-I Wu06d63de2017-01-04 14:58:51 +0800875
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700876 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400877 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700878 if (error != HWC2::Error::None) {
879 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
880 mActiveBuffer->handle, to_string(error).c_str(),
881 static_cast<int32_t>(error));
882 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800883}
Courtney Goeltzenleuchter9551fd32016-10-20 17:18:15 -0600884
885android_dataspace Layer::getDataSpace() const {
886 return mCurrentState.dataSpace;
887}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000888#else
889void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
890 HWComposer::HWCLayerInterface& layer) {
891 // we have to set the visible region on every frame because
892 // we currently free it during onLayerDisplayed(), which is called
893 // after HWComposer::commit() -- every frame.
894 // Apply this display's projection's viewport to the visible region
895 // before giving it to the HWC HAL.
896 const Transform& tr = hw->getTransform();
897 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
898 layer.setVisibleRegionScreen(visible);
899 layer.setSurfaceDamage(surfaceDamageRegion);
900 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700901
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000902 if (mSidebandStream.get()) {
903 layer.setSidebandStream(mSidebandStream);
904 } else {
905 // NOTE: buffer can be NULL if the client never drew into this
906 // layer yet, or if we ran out of memory
907 layer.setBuffer(mActiveBuffer);
908 }
909}
910#endif
911
912#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800913void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
914 auto hwcId = displayDevice->getHwcDisplayId();
915 if (mHwcLayers.count(hwcId) == 0 ||
916 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
917 return;
918 }
919
920 // This gives us only the "orientation" component of the transform
921 const State& s(getCurrentState());
922
923 // Apply the layer's transform, followed by the display's global transform
924 // Here we're guaranteed that the layer's transform preserves rects
925 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700926 if (!s.crop.isEmpty()) {
927 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800928 }
929 // Subtract the transparent region and snap to the bounds
930 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700931 Rect frame(getTransform().transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800932 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -0700933 if (!s.finalCrop.isEmpty()) {
934 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000935 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800936 auto& displayTransform(displayDevice->getTransform());
937 auto position = displayTransform.transform(frame);
938
939 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
940 position.top);
941 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
942 "to (%d, %d): %s (%d)", mName.string(), position.left,
943 position.top, to_string(error).c_str(),
944 static_cast<int32_t>(error));
945}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000946#else
947void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
948 HWComposer::HWCLayerInterface& layer) {
949 int fenceFd = -1;
950
951 // TODO: there is a possible optimization here: we only need to set the
952 // acquire fence the first time a new buffer is acquired on EACH display.
953
954 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
955 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
956 if (fence->isValid()) {
957 fenceFd = fence->dup();
958 if (fenceFd == -1) {
959 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
960 }
961 }
962 }
963 layer.setAcquireFenceFd(fenceFd);
964}
965
966Rect Layer::getPosition(
967 const sp<const DisplayDevice>& hw)
968{
969 // this gives us only the "orientation" component of the transform
970 const State& s(getCurrentState());
971
972 // apply the layer's transform, followed by the display's global transform
973 // here we're guaranteed that the layer's transform preserves rects
974 Rect win(s.active.w, s.active.h);
975 if (!s.crop.isEmpty()) {
976 win.intersect(s.crop, &win);
977 }
978 // subtract the transparent region and snap to the bounds
979 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700980 Rect frame(getTransform().transform(bounds));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000981 frame.intersect(hw->getViewport(), &frame);
982 if (!s.finalCrop.isEmpty()) {
983 frame.intersect(s.finalCrop, &frame);
984 }
985 const Transform& tr(hw->getTransform());
986 return Rect(tr.transform(frame));
987}
988#endif
Riley Andrews03414a12014-07-01 14:22:59 -0700989
Mathias Agopian13127d82013-03-05 17:47:11 -0800990// ---------------------------------------------------------------------------
991// drawing...
992// ---------------------------------------------------------------------------
993
994void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -0800995 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -0800996}
997
Dan Stozac7014012014-02-14 15:03:43 -0800998void Layer::draw(const sp<const DisplayDevice>& hw,
999 bool useIdentityTransform) const {
1000 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001001}
1002
Dan Stozac7014012014-02-14 15:03:43 -08001003void Layer::draw(const sp<const DisplayDevice>& hw) const {
1004 onDraw(hw, Region(hw->bounds()), false);
1005}
1006
Robert Carrcae605c2017-03-29 12:10:31 -07001007static constexpr mat4 inverseOrientation(uint32_t transform) {
1008 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1009 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1010 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1011 mat4 tr;
1012
1013 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1014 tr = tr * rot90;
1015 }
1016 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1017 tr = tr * flipH;
1018 }
1019 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1020 tr = tr * flipV;
1021 }
1022 return inverse(tr);
1023}
1024
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001025/*
1026 * onDraw will draw the current layer onto the presentable buffer
1027 */
Dan Stozac7014012014-02-14 15:03:43 -08001028void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
1029 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001030{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001031 ATRACE_CALL();
1032
Mathias Agopiana67932f2011-04-20 14:20:59 -07001033 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001034 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -07001035 // in fact never been drawn into. This happens frequently with
1036 // SurfaceView because the WindowManager can't know when the client
1037 // has drawn the first time.
1038
1039 // If there is nothing under us, we paint the screen in black, otherwise
1040 // we just skip this update.
1041
1042 // figure out if there is something below us
1043 Region under;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001044 bool finished = false;
Dan Stoza412903f2017-04-27 13:42:17 -07001045 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001046 if (finished || layer == static_cast<Layer const*>(this)) {
1047 finished = true;
1048 return;
1049 }
Mathias Agopian42977342012-08-05 00:40:46 -07001050 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Robert Carr1f0a16a2016-10-24 16:27:39 -07001051 });
Mathias Agopian179169e2010-05-06 20:21:45 -07001052 // if not everything below us is covered, we plug the holes!
1053 Region holes(clip.subtract(under));
1054 if (!holes.isEmpty()) {
Fabien Sanglard17487192016-12-07 13:03:32 -08001055 clearWithOpenGL(hw, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -07001056 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001057 return;
1058 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001059
Andy McFadden97eba892012-12-11 15:21:45 -08001060 // Bind the current buffer to the GL texture, and wait for it to be
1061 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001062 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1063 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -08001064 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -07001065 // Go ahead and draw the buffer anyway; no matter what we do the screen
1066 // is probably going to have something visibly wrong.
1067 }
1068
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001069 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1070
Mathias Agopian875d8e12013-06-07 15:35:48 -07001071 RenderEngine& engine(mFlinger->getRenderEngine());
1072
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001073 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -07001074 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -07001075 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -07001076
1077 // Query the texture matrix given our current filtering mode.
1078 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001079 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1080 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -07001081
Robert Carrcae605c2017-03-29 12:10:31 -07001082 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001083
1084 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -07001085 * the code below applies the primary display's inverse transform to
1086 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001087 */
Pablo Ceballos021623b2016-04-15 17:31:51 -07001088 uint32_t transform =
1089 DisplayDevice::getPrimaryDisplayOrientationTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001090 mat4 tr = inverseOrientation(transform);
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001091
Robert Carrcae605c2017-03-29 12:10:31 -07001092 /**
1093 * TODO(b/36727915): This is basically a hack.
1094 *
1095 * Ensure that regardless of the parent transformation,
1096 * this buffer is always transformed from native display
1097 * orientation to display orientation. For example, in the case
1098 * of a camera where the buffer remains in native orientation,
1099 * we want the pixels to always be upright.
1100 */
1101 if (getParent() != nullptr) {
1102 const auto parentTransform = getParent()->getTransform();
1103 tr = tr * inverseOrientation(parentTransform.getOrientation());
1104 }
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001105
1106 // and finally apply it to the original texture matrix
1107 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1108 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1109 }
1110
Jamie Genniscbb1a952012-05-08 17:05:52 -07001111 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -07001112 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1113 mTexture.setFiltering(useFiltering);
1114 mTexture.setMatrix(textureMatrix);
1115
1116 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -07001117 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001118 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -07001119 }
Fabien Sanglard85789802016-12-07 13:08:24 -08001120 drawWithOpenGL(hw, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001121 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001122}
1123
Mathias Agopian13127d82013-03-05 17:47:11 -08001124
Dan Stozac7014012014-02-14 15:03:43 -08001125void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard17487192016-12-07 13:03:32 -08001126 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -08001127 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001128{
Mathias Agopian19733a32013-08-28 18:13:56 -07001129 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -08001130 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -07001131 engine.setupFillWithColor(red, green, blue, alpha);
1132 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -08001133}
1134
1135void Layer::clearWithOpenGL(
Fabien Sanglard17487192016-12-07 13:03:32 -08001136 const sp<const DisplayDevice>& hw) const {
1137 clearWithOpenGL(hw, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001138}
1139
Dan Stozac7014012014-02-14 15:03:43 -08001140void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard85789802016-12-07 13:08:24 -08001141 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001142 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001143
Dan Stozac7014012014-02-14 15:03:43 -08001144 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001145
Mathias Agopian13127d82013-03-05 17:47:11 -08001146 /*
1147 * NOTE: the way we compute the texture coordinates here produces
1148 * different results than when we take the HWC path -- in the later case
1149 * the "source crop" is rounded to texel boundaries.
1150 * This can produce significantly different results when the texture
1151 * is scaled by a large amount.
1152 *
1153 * The GL code below is more logical (imho), and the difference with
1154 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001155 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001156 * GL composition when a buffer scaling is applied (maybe with some
1157 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1158 * like more of a hack.
1159 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001160 Rect win(computeBounds());
1161
Robert Carr1f0a16a2016-10-24 16:27:39 -07001162 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -07001163 if (!s.finalCrop.isEmpty()) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001164 win = t.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001165 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001166 win.clear();
1167 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001168 win = t.inverse().transform(win);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001169 if (!win.intersect(computeBounds(), &win)) {
1170 win.clear();
1171 }
1172 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001173
Mathias Agopian3f844832013-08-07 21:24:32 -07001174 float left = float(win.left) / float(s.active.w);
1175 float top = float(win.top) / float(s.active.h);
1176 float right = float(win.right) / float(s.active.w);
1177 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001178
Mathias Agopian875d8e12013-06-07 15:35:48 -07001179 // TODO: we probably want to generate the texture coords with the mesh
1180 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001181 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1182 texCoords[0] = vec2(left, 1.0f - top);
1183 texCoords[1] = vec2(left, 1.0f - bottom);
1184 texCoords[2] = vec2(right, 1.0f - bottom);
1185 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001186
Mathias Agopian875d8e12013-06-07 15:35:48 -07001187 RenderEngine& engine(mFlinger->getRenderEngine());
Robert Carr6452f122017-03-21 10:41:29 -07001188 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), getAlpha());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001189#ifdef USE_HWC2
1190 engine.setSourceDataSpace(mCurrentState.dataSpace);
1191#endif
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001192 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001193 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001194}
1195
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001196#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001197void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1198 bool callIntoHwc) {
1199 if (mHwcLayers.count(hwcId) == 0) {
1200 ALOGE("setCompositionType called without a valid HWC layer");
1201 return;
1202 }
1203 auto& hwcInfo = mHwcLayers[hwcId];
1204 auto& hwcLayer = hwcInfo.layer;
1205 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1206 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1207 if (hwcInfo.compositionType != type) {
1208 ALOGV(" actually setting");
1209 hwcInfo.compositionType = type;
1210 if (callIntoHwc) {
1211 auto error = hwcLayer->setCompositionType(type);
1212 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1213 "composition type %s: %s (%d)", mName.string(),
1214 to_string(type).c_str(), to_string(error).c_str(),
1215 static_cast<int32_t>(error));
1216 }
1217 }
1218}
1219
1220HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001221 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1222 // If we're querying the composition type for a display that does not
1223 // have a HWC counterpart, then it will always be Client
1224 return HWC2::Composition::Client;
1225 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001226 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001227 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001228 return HWC2::Composition::Invalid;
1229 }
1230 return mHwcLayers.at(hwcId).compositionType;
1231}
1232
1233void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1234 if (mHwcLayers.count(hwcId) == 0) {
1235 ALOGE("setClearClientTarget called without a valid HWC layer");
1236 return;
1237 }
1238 mHwcLayers[hwcId].clearClientTarget = clear;
1239}
1240
1241bool Layer::getClearClientTarget(int32_t hwcId) const {
1242 if (mHwcLayers.count(hwcId) == 0) {
1243 ALOGE("getClearClientTarget called without a valid HWC layer");
1244 return false;
1245 }
1246 return mHwcLayers.at(hwcId).clearClientTarget;
1247}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001248#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001249
Ruben Brunk1681d952014-06-27 15:51:55 -07001250uint32_t Layer::getProducerStickyTransform() const {
1251 int producerStickyTransform = 0;
1252 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1253 if (ret != OK) {
1254 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1255 strerror(-ret), ret);
1256 return 0;
1257 }
1258 return static_cast<uint32_t>(producerStickyTransform);
1259}
1260
Dan Stozac5da2712016-07-20 15:38:12 -07001261bool Layer::latchUnsignaledBuffers() {
1262 static bool propertyLoaded = false;
1263 static bool latch = false;
1264 static std::mutex mutex;
1265 std::lock_guard<std::mutex> lock(mutex);
1266 if (!propertyLoaded) {
1267 char value[PROPERTY_VALUE_MAX] = {};
1268 property_get("debug.sf.latch_unsignaled", value, "0");
1269 latch = atoi(value);
1270 propertyLoaded = true;
1271 }
1272 return latch;
1273}
1274
Dan Stozacac35382016-01-27 12:21:06 -08001275uint64_t Layer::getHeadFrameNumber() const {
1276 Mutex::Autolock lock(mQueueItemLock);
1277 if (!mQueueItems.empty()) {
1278 return mQueueItems[0].mFrameNumber;
1279 } else {
1280 return mCurrentFrameNumber;
1281 }
1282}
1283
Dan Stoza1ce65812016-06-15 16:26:27 -07001284bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001285#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001286 if (latchUnsignaledBuffers()) {
1287 return true;
1288 }
1289
Dan Stoza1ce65812016-06-15 16:26:27 -07001290 Mutex::Autolock lock(mQueueItemLock);
1291 if (mQueueItems.empty()) {
1292 return true;
1293 }
1294 if (mQueueItems[0].mIsDroppable) {
1295 // Even though this buffer's fence may not have signaled yet, it could
1296 // be replaced by another buffer before it has a chance to, which means
1297 // that it's possible to get into a situation where a buffer is never
1298 // able to be latched. To avoid this, grab this buffer anyway.
1299 return true;
1300 }
1301 return mQueueItems[0].mFence->getSignalTime() != INT64_MAX;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001302#else
1303 return true;
1304#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001305}
1306
Dan Stozacac35382016-01-27 12:21:06 -08001307bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1308 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1309 // Don't bother with a SyncPoint, since we've already latched the
1310 // relevant frame
1311 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001312 }
1313
Dan Stozacac35382016-01-27 12:21:06 -08001314 Mutex::Autolock lock(mLocalSyncPointMutex);
1315 mLocalSyncPoints.push_back(point);
1316 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001317}
1318
Mathias Agopian13127d82013-03-05 17:47:11 -08001319void Layer::setFiltering(bool filtering) {
1320 mFiltering = filtering;
1321}
1322
1323bool Layer::getFiltering() const {
1324 return mFiltering;
1325}
1326
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001327// As documented in libhardware header, formats in the range
1328// 0x100 - 0x1FF are specific to the HAL implementation, and
1329// are known to have no alpha channel
1330// TODO: move definition for device-specific range into
1331// hardware.h, instead of using hard-coded values here.
1332#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1333
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001334bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001335 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1336 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001337 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001338 switch (format) {
1339 case HAL_PIXEL_FORMAT_RGBA_8888:
1340 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001341 case HAL_PIXEL_FORMAT_RGBA_FP16:
Romain Guy541f2262017-02-10 18:50:17 -08001342 case HAL_PIXEL_FORMAT_RGBA_1010102:
Mathias Agopiandd533712013-07-26 15:31:39 -07001343 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001344 }
1345 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001346 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001347}
1348
Mathias Agopian13127d82013-03-05 17:47:11 -08001349// ----------------------------------------------------------------------------
1350// local state
1351// ----------------------------------------------------------------------------
1352
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001353static void boundPoint(vec2* point, const Rect& crop) {
1354 if (point->x < crop.left) {
1355 point->x = crop.left;
1356 }
1357 if (point->x > crop.right) {
1358 point->x = crop.right;
1359 }
1360 if (point->y < crop.top) {
1361 point->y = crop.top;
1362 }
1363 if (point->y > crop.bottom) {
1364 point->y = crop.bottom;
1365 }
1366}
1367
Dan Stozac7014012014-02-14 15:03:43 -08001368void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1369 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001370{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001371 const Layer::State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001372 const Transform hwTransform(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001373 const uint32_t hw_h = hw->getHeight();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001374 Rect win = computeBounds();
Mathias Agopian3f844832013-08-07 21:24:32 -07001375
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001376 vec2 lt = vec2(win.left, win.top);
1377 vec2 lb = vec2(win.left, win.bottom);
1378 vec2 rb = vec2(win.right, win.bottom);
1379 vec2 rt = vec2(win.right, win.top);
1380
Robert Carr1f0a16a2016-10-24 16:27:39 -07001381 Transform layerTransform = getTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001382 if (!useIdentityTransform) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001383 lt = layerTransform.transform(lt);
1384 lb = layerTransform.transform(lb);
1385 rb = layerTransform.transform(rb);
1386 rt = layerTransform.transform(rt);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001387 }
1388
Robert Carrb5d3d262016-03-25 15:08:13 -07001389 if (!s.finalCrop.isEmpty()) {
1390 boundPoint(&lt, s.finalCrop);
1391 boundPoint(&lb, s.finalCrop);
1392 boundPoint(&rb, s.finalCrop);
1393 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001394 }
1395
Mathias Agopianff2ed702013-09-01 21:36:12 -07001396 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001397 position[0] = hwTransform.transform(lt);
1398 position[1] = hwTransform.transform(lb);
1399 position[2] = hwTransform.transform(rb);
1400 position[3] = hwTransform.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001401 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001402 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001403 }
1404}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001405
Andy McFadden4125a4f2014-01-29 17:17:11 -08001406bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001407{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001408 // if we don't have a buffer yet, we're translucent regardless of the
1409 // layer's opaque flag.
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001410 if (mActiveBuffer == 0) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001411 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001412 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001413
1414 // if the layer has the opaque flag, then we're always opaque,
1415 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001416 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001417}
1418
Dan Stoza23116082015-06-18 14:58:39 -07001419bool Layer::isSecure() const
1420{
1421 const Layer::State& s(mDrawingState);
1422 return (s.flags & layer_state_t::eLayerSecure);
1423}
1424
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001425bool Layer::isProtected() const
1426{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001427 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001428 return (activeBuffer != 0) &&
1429 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1430}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001431
Mathias Agopian13127d82013-03-05 17:47:11 -08001432bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001433 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001434}
1435
1436bool Layer::isCropped() const {
1437 return !mCurrentCrop.isEmpty();
1438}
1439
1440bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1441 return mNeedsFiltering || hw->needsFiltering();
1442}
1443
1444void Layer::setVisibleRegion(const Region& visibleRegion) {
1445 // always called from main thread
1446 this->visibleRegion = visibleRegion;
1447}
1448
1449void Layer::setCoveredRegion(const Region& coveredRegion) {
1450 // always called from main thread
1451 this->coveredRegion = coveredRegion;
1452}
1453
1454void Layer::setVisibleNonTransparentRegion(const Region&
1455 setVisibleNonTransparentRegion) {
1456 // always called from main thread
1457 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1458}
1459
1460// ----------------------------------------------------------------------------
1461// transaction
1462// ----------------------------------------------------------------------------
1463
Dan Stoza7dde5992015-05-22 09:51:44 -07001464void Layer::pushPendingState() {
1465 if (!mCurrentState.modified) {
1466 return;
1467 }
1468
Dan Stoza7dde5992015-05-22 09:51:44 -07001469 // If this transaction is waiting on the receipt of a frame, generate a sync
1470 // point and send it to the remote layer.
Robert Carr0d480722017-01-10 16:42:54 -08001471 if (mCurrentState.barrierLayer != nullptr) {
1472 sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1473 if (barrierLayer == nullptr) {
1474 ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
Dan Stoza7dde5992015-05-22 09:51:44 -07001475 // If we can't promote the layer we are intended to wait on,
1476 // then it is expired or otherwise invalid. Allow this transaction
1477 // to be applied as per normal (no synchronization).
Robert Carr0d480722017-01-10 16:42:54 -08001478 mCurrentState.barrierLayer = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001479 } else {
1480 auto syncPoint = std::make_shared<SyncPoint>(
1481 mCurrentState.frameNumber);
Robert Carr0d480722017-01-10 16:42:54 -08001482 if (barrierLayer->addSyncPoint(syncPoint)) {
Dan Stozacac35382016-01-27 12:21:06 -08001483 mRemoteSyncPoints.push_back(std::move(syncPoint));
1484 } else {
1485 // We already missed the frame we're supposed to synchronize
1486 // on, so go ahead and apply the state update
Robert Carr0d480722017-01-10 16:42:54 -08001487 mCurrentState.barrierLayer = nullptr;
Dan Stozacac35382016-01-27 12:21:06 -08001488 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001489 }
1490
Dan Stoza7dde5992015-05-22 09:51:44 -07001491 // Wake us up to check if the frame has been received
1492 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001493 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001494 }
1495 mPendingStates.push_back(mCurrentState);
1496}
1497
Pablo Ceballos05289c22016-04-14 15:49:55 -07001498void Layer::popPendingState(State* stateToCommit) {
1499 auto oldFlags = stateToCommit->flags;
1500 *stateToCommit = mPendingStates[0];
1501 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1502 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001503
1504 mPendingStates.removeAt(0);
1505}
1506
Pablo Ceballos05289c22016-04-14 15:49:55 -07001507bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001508 bool stateUpdateAvailable = false;
1509 while (!mPendingStates.empty()) {
Robert Carr0d480722017-01-10 16:42:54 -08001510 if (mPendingStates[0].barrierLayer != nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001511 if (mRemoteSyncPoints.empty()) {
1512 // If we don't have a sync point for this, apply it anyway. It
1513 // will be visually wrong, but it should keep us from getting
1514 // into too much trouble.
1515 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001516 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001517 stateUpdateAvailable = true;
1518 continue;
1519 }
1520
Dan Stozacac35382016-01-27 12:21:06 -08001521 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1522 mPendingStates[0].frameNumber) {
1523 ALOGE("[%s] Unexpected sync point frame number found",
1524 mName.string());
1525
1526 // Signal our end of the sync point and then dispose of it
1527 mRemoteSyncPoints.front()->setTransactionApplied();
1528 mRemoteSyncPoints.pop_front();
1529 continue;
1530 }
1531
Dan Stoza7dde5992015-05-22 09:51:44 -07001532 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1533 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001534 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001535 stateUpdateAvailable = true;
1536
1537 // Signal our end of the sync point and then dispose of it
1538 mRemoteSyncPoints.front()->setTransactionApplied();
1539 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001540 } else {
1541 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001542 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001543 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001544 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001545 stateUpdateAvailable = true;
1546 }
1547 }
1548
1549 // If we still have pending updates, wake SurfaceFlinger back up and point
1550 // it at this layer so we can process them
1551 if (!mPendingStates.empty()) {
1552 setTransactionFlags(eTransactionNeeded);
1553 mFlinger->setTransactionFlags(eTraversalNeeded);
1554 }
1555
1556 mCurrentState.modified = false;
1557 return stateUpdateAvailable;
1558}
1559
1560void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001561 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001562 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001563 Mutex::Autolock lock(mLocalSyncPointMutex);
1564 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001565 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001566 point->setFrameAvailable();
1567 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001568 }
1569}
1570
Mathias Agopian13127d82013-03-05 17:47:11 -08001571uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001572 ATRACE_CALL();
1573
Dan Stoza7dde5992015-05-22 09:51:44 -07001574 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001575 Layer::State c = getCurrentState();
1576 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001577 return 0;
1578 }
1579
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001580 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001581
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001582 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1583 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001584
1585 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001586 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001587 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001588 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001589 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001590 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001591 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001592 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001593 this, getName().string(), mCurrentTransform,
1594 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001595 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001596 c.crop.left,
1597 c.crop.top,
1598 c.crop.right,
1599 c.crop.bottom,
1600 c.crop.getWidth(),
1601 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001602 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001603 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001604 s.crop.left,
1605 s.crop.top,
1606 s.crop.right,
1607 s.crop.bottom,
1608 s.crop.getWidth(),
1609 s.crop.getHeight(),
1610 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001611
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001612 // record the new size, form this point on, when the client request
1613 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001614 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001615 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001616 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001617
Robert Carr82364e32016-05-15 11:27:47 -07001618 const bool resizePending = (c.requested.w != c.active.w) ||
1619 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001620 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001621 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001622 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001623 // if we have a pending resize, unless we are in fixed-size mode.
1624 // the drawing state will be updated only once we receive a buffer
1625 // with the correct size.
1626 //
1627 // in particular, we want to make sure the clip (which is part
1628 // of the geometry state) is latched together with the size but is
1629 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001630 //
1631 // If a sideband stream is attached, however, we want to skip this
1632 // optimization so that transactions aren't missed when a buffer
1633 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001634
1635 flags |= eDontUpdateGeometryState;
1636 }
1637 }
1638
Mathias Agopian13127d82013-03-05 17:47:11 -08001639 // always set active to requested, unless we're asked not to
1640 // this is used by Layer, which special cases resizes.
1641 if (flags & eDontUpdateGeometryState) {
1642 } else {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001643 Layer::State& editCurrentState(getCurrentState());
Robert Carr82364e32016-05-15 11:27:47 -07001644 if (mFreezePositionUpdates) {
1645 float tx = c.active.transform.tx();
1646 float ty = c.active.transform.ty();
1647 c.active = c.requested;
1648 c.active.transform.set(tx, ty);
1649 editCurrentState.active = c.active;
1650 } else {
1651 editCurrentState.active = editCurrentState.requested;
1652 c.active = c.requested;
1653 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001654 }
1655
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001656 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001657 // invalidate and recompute the visible regions if needed
1658 flags |= Layer::eVisibleRegion;
1659 }
1660
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001661 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001662 // invalidate and recompute the visible regions if needed
1663 flags |= eVisibleRegion;
1664 this->contentDirty = true;
1665
1666 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001667 const uint8_t type = c.active.transform.getType();
1668 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001669 (type >= Transform::SCALE));
1670 }
1671
Dan Stozac8145172016-04-28 16:29:06 -07001672 // If the layer is hidden, signal and clear out all local sync points so
1673 // that transactions for layers depending on this layer's frames becoming
1674 // visible are not blocked
1675 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001676 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001677 }
1678
Mathias Agopian13127d82013-03-05 17:47:11 -08001679 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001680 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001681 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001682}
1683
Pablo Ceballos05289c22016-04-14 15:49:55 -07001684void Layer::commitTransaction(const State& stateToCommit) {
1685 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001686}
1687
Mathias Agopian13127d82013-03-05 17:47:11 -08001688uint32_t Layer::getTransactionFlags(uint32_t flags) {
1689 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1690}
1691
1692uint32_t Layer::setTransactionFlags(uint32_t flags) {
1693 return android_atomic_or(flags, &mTransactionFlags);
1694}
1695
Robert Carr82364e32016-05-15 11:27:47 -07001696bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001697 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001698 return false;
1699 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001700
1701 // We update the requested and active position simultaneously because
1702 // we want to apply the position portion of the transform matrix immediately,
1703 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001704 mCurrentState.requested.transform.set(x, y);
Robert Carr82364e32016-05-15 11:27:47 -07001705 if (immediate && !mFreezePositionUpdates) {
1706 mCurrentState.active.transform.set(x, y);
1707 }
1708 mFreezePositionUpdates = mFreezePositionUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001709
Dan Stoza7dde5992015-05-22 09:51:44 -07001710 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001711 setTransactionFlags(eTransactionNeeded);
1712 return true;
1713}
Robert Carr82364e32016-05-15 11:27:47 -07001714
Robert Carr1f0a16a2016-10-24 16:27:39 -07001715bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1716 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1717 if (idx < 0) {
1718 return false;
1719 }
1720 if (childLayer->setLayer(z)) {
1721 mCurrentChildren.removeAt(idx);
1722 mCurrentChildren.add(childLayer);
1723 }
1724 return true;
1725}
1726
Robert Carrae060832016-11-28 10:51:00 -08001727bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001728 if (mCurrentState.z == z)
1729 return false;
1730 mCurrentState.sequence++;
1731 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001732 mCurrentState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001733
1734 // Discard all relative layering.
1735 if (mCurrentState.zOrderRelativeOf != nullptr) {
1736 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1737 if (strongRelative != nullptr) {
1738 strongRelative->removeZOrderRelative(this);
1739 }
1740 mCurrentState.zOrderRelativeOf = nullptr;
1741 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001742 setTransactionFlags(eTransactionNeeded);
1743 return true;
1744}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001745
Robert Carrdb66e622017-04-10 16:55:57 -07001746void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1747 mCurrentState.zOrderRelatives.remove(relative);
1748 mCurrentState.sequence++;
1749 mCurrentState.modified = true;
1750 setTransactionFlags(eTransactionNeeded);
1751}
1752
1753void Layer::addZOrderRelative(const wp<Layer>& relative) {
1754 mCurrentState.zOrderRelatives.add(relative);
1755 mCurrentState.modified = true;
1756 mCurrentState.sequence++;
1757 setTransactionFlags(eTransactionNeeded);
1758}
1759
1760bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1761 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1762 if (handle == nullptr) {
1763 return false;
1764 }
1765 sp<Layer> relative = handle->owner.promote();
1766 if (relative == nullptr) {
1767 return false;
1768 }
1769
1770 mCurrentState.sequence++;
1771 mCurrentState.modified = true;
1772 mCurrentState.z = z;
1773
1774 mCurrentState.zOrderRelativeOf = relative;
1775 relative->addZOrderRelative(this);
1776
1777 setTransactionFlags(eTransactionNeeded);
1778
1779 return true;
1780}
1781
Mathias Agopian13127d82013-03-05 17:47:11 -08001782bool Layer::setSize(uint32_t w, uint32_t h) {
1783 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1784 return false;
1785 mCurrentState.requested.w = w;
1786 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001787 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001788 setTransactionFlags(eTransactionNeeded);
1789 return true;
1790}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001791#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001792bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001793#else
1794bool Layer::setAlpha(uint8_t alpha) {
1795#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001796 if (mCurrentState.alpha == alpha)
1797 return false;
1798 mCurrentState.sequence++;
1799 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001800 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001801 setTransactionFlags(eTransactionNeeded);
1802 return true;
1803}
1804bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1805 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001806 mCurrentState.requested.transform.set(
Robert Carrcb6e1e32017-02-21 19:48:26 -08001807 matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001808 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001809 setTransactionFlags(eTransactionNeeded);
1810 return true;
1811}
1812bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001813 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001814 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001815 setTransactionFlags(eTransactionNeeded);
1816 return true;
1817}
1818bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1819 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1820 if (mCurrentState.flags == newFlags)
1821 return false;
1822 mCurrentState.sequence++;
1823 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001824 mCurrentState.mask = mask;
1825 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001826 setTransactionFlags(eTransactionNeeded);
1827 return true;
1828}
Robert Carr99e27f02016-06-16 15:18:02 -07001829
1830bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001831 if (mCurrentState.crop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001832 return false;
1833 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001834 mCurrentState.requestedCrop = crop;
1835 if (immediate) {
1836 mCurrentState.crop = crop;
1837 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001838 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001839 setTransactionFlags(eTransactionNeeded);
1840 return true;
1841}
Robert Carr8d5227b2017-03-16 15:41:03 -07001842
1843bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001844 if (mCurrentState.finalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001845 return false;
1846 mCurrentState.sequence++;
Robert Carr8d5227b2017-03-16 15:41:03 -07001847 mCurrentState.requestedFinalCrop = crop;
1848 if (immediate) {
1849 mCurrentState.finalCrop = crop;
1850 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001851 mCurrentState.modified = true;
1852 setTransactionFlags(eTransactionNeeded);
1853 return true;
1854}
Mathias Agopian13127d82013-03-05 17:47:11 -08001855
Robert Carrc3574f72016-03-24 12:19:32 -07001856bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1857 if (scalingMode == mOverrideScalingMode)
1858 return false;
1859 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001860 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001861 return true;
1862}
1863
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001864void Layer::setInfo(uint32_t type, uint32_t appId) {
1865 mCurrentState.appId = appId;
1866 mCurrentState.type = type;
1867 mCurrentState.modified = true;
1868 setTransactionFlags(eTransactionNeeded);
1869}
1870
Robert Carrc3574f72016-03-24 12:19:32 -07001871uint32_t Layer::getEffectiveScalingMode() const {
1872 if (mOverrideScalingMode >= 0) {
1873 return mOverrideScalingMode;
1874 }
1875 return mCurrentScalingMode;
1876}
1877
Mathias Agopian13127d82013-03-05 17:47:11 -08001878bool Layer::setLayerStack(uint32_t layerStack) {
1879 if (mCurrentState.layerStack == layerStack)
1880 return false;
1881 mCurrentState.sequence++;
1882 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001883 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001884 setTransactionFlags(eTransactionNeeded);
1885 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001886}
1887
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07001888bool Layer::setDataSpace(android_dataspace dataSpace) {
1889 if (mCurrentState.dataSpace == dataSpace)
1890 return false;
1891 mCurrentState.sequence++;
1892 mCurrentState.dataSpace = dataSpace;
1893 mCurrentState.modified = true;
1894 setTransactionFlags(eTransactionNeeded);
1895 return true;
1896}
1897
Robert Carr1f0a16a2016-10-24 16:27:39 -07001898uint32_t Layer::getLayerStack() const {
1899 auto p = getParent();
1900 if (p == nullptr) {
1901 return getDrawingState().layerStack;
1902 }
1903 return p->getLayerStack();
1904}
1905
Robert Carr0d480722017-01-10 16:42:54 -08001906void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
Dan Stoza7dde5992015-05-22 09:51:44 -07001907 uint64_t frameNumber) {
Robert Carr0d480722017-01-10 16:42:54 -08001908 mCurrentState.barrierLayer = barrierLayer;
Dan Stoza7dde5992015-05-22 09:51:44 -07001909 mCurrentState.frameNumber = frameNumber;
1910 // We don't set eTransactionNeeded, because just receiving a deferral
1911 // request without any other state updates shouldn't actually induce a delay
1912 mCurrentState.modified = true;
1913 pushPendingState();
Robert Carr0d480722017-01-10 16:42:54 -08001914 mCurrentState.barrierLayer = nullptr;
Dan Stoza792e5292016-02-11 11:43:58 -08001915 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07001916 mCurrentState.modified = false;
Robert Carr0d480722017-01-10 16:42:54 -08001917 ALOGE("Deferred transaction");
1918}
1919
1920void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
1921 uint64_t frameNumber) {
1922 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
1923 deferTransactionUntil(handle->owner.promote(), frameNumber);
Dan Stoza7dde5992015-05-22 09:51:44 -07001924}
1925
Dan Stozaee44edd2015-03-23 15:50:23 -07001926void Layer::useSurfaceDamage() {
1927 if (mFlinger->mForceFullDamage) {
1928 surfaceDamageRegion = Region::INVALID_REGION;
1929 } else {
1930 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1931 }
1932}
1933
1934void Layer::useEmptyDamage() {
1935 surfaceDamageRegion.clear();
1936}
1937
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001938// ----------------------------------------------------------------------------
1939// pageflip handling...
1940// ----------------------------------------------------------------------------
1941
Dan Stoza6b9454d2014-11-07 16:00:59 -08001942bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001943 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07001944 return true;
1945 }
1946
Dan Stoza6b9454d2014-11-07 16:00:59 -08001947 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001948 if (mQueueItems.empty()) {
1949 return false;
1950 }
1951 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001952 nsecs_t expectedPresent =
1953 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001954
1955 // Ignore timestamps more than a second in the future
1956 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1957 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1958 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1959 expectedPresent);
1960
1961 bool isDue = timestamp < expectedPresent;
1962 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001963}
1964
Brian Andersond6927fb2016-07-23 23:37:30 -07001965bool Layer::onPreComposition(nsecs_t refreshStartTime) {
1966 if (mBufferLatched) {
1967 Mutex::Autolock lock(mFrameEventHistoryMutex);
1968 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
1969 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08001970 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001971 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001972}
1973
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001974bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
Brian Anderson3d4039d2016-09-23 16:31:30 -07001975 const std::shared_ptr<FenceTime>& presentFence,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001976 const CompositorTiming& compositorTiming) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001977 mAcquireTimeline.updateSignalTimes();
1978 mReleaseTimeline.updateSignalTimes();
1979
Brian Andersond6927fb2016-07-23 23:37:30 -07001980 // mFrameLatencyNeeded is true when a new frame was latched for the
1981 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08001982 if (!mFrameLatencyNeeded)
1983 return false;
1984
Fabien Sanglard28e98082016-12-05 10:19:46 -08001985 // Update mFrameEventHistory.
1986 {
1987 Mutex::Autolock lock(mFrameEventHistoryMutex);
1988 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001989 glDoneFence, presentFence, compositorTiming);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001990 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08001991
1992 // Update mFrameTracker.
1993 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1994 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1995
Brian Anderson3d4039d2016-09-23 16:31:30 -07001996 std::shared_ptr<FenceTime> frameReadyFence =
1997 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08001998 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001999 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002000 } else {
2001 // There was no fence for this frame, so assume that it was ready
2002 // to be presented at the desired present time.
2003 mFrameTracker.setFrameReadyTime(desiredPresentTime);
2004 }
2005
Brian Anderson3d4039d2016-09-23 16:31:30 -07002006 if (presentFence->isValid()) {
2007 mFrameTracker.setActualPresentFence(
2008 std::shared_ptr<FenceTime>(presentFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002009 } else {
2010 // The HWC doesn't support present fences, so use the refresh
2011 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002012 mFrameTracker.setActualPresentTime(
2013 mFlinger->getHwComposer().getRefreshTimestamp(
2014 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002015 }
2016
2017 mFrameTracker.advanceFrame();
2018 mFrameLatencyNeeded = false;
2019 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002020}
2021
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002022#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07002023void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Brian Anderson5ea5e592016-12-01 16:54:33 -08002024 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2025 return;
2026 }
2027
Brian Anderson3d4039d2016-09-23 16:31:30 -07002028 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002029 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002030 mReleaseTimeline.push(releaseFenceTime);
2031
2032 Mutex::Autolock lock(mFrameEventHistoryMutex);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002033 if (mPreviousFrameNumber != 0) {
2034 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2035 dequeueReadyTime, std::move(releaseFenceTime));
2036 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002037}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002038#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002039
Robert Carr1f0a16a2016-10-24 16:27:39 -07002040bool Layer::isHiddenByPolicy() const {
2041 const Layer::State& s(mDrawingState);
2042 const auto& parent = getParent();
2043 if (parent != nullptr && parent->isHiddenByPolicy()) {
2044 return true;
2045 }
2046 return s.flags & layer_state_t::eLayerHidden;
2047}
2048
Mathias Agopianda27af92012-09-13 18:17:13 -07002049bool Layer::isVisible() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002050#ifdef USE_HWC2
Robert Carr6452f122017-03-21 10:41:29 -07002051 return !(isHiddenByPolicy()) && getAlpha() > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08002052 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002053#else
Robert Carr6452f122017-03-21 10:41:29 -07002054 return !(isHiddenByPolicy()) && getAlpha()
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002055 && (mActiveBuffer != NULL || mSidebandStream != NULL);
2056#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07002057}
2058
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002059bool Layer::allTransactionsSignaled() {
2060 auto headFrameNumber = getHeadFrameNumber();
2061 bool matchingFramesFound = false;
2062 bool allTransactionsApplied = true;
2063 Mutex::Autolock lock(mLocalSyncPointMutex);
2064
2065 for (auto& point : mLocalSyncPoints) {
2066 if (point->getFrameNumber() > headFrameNumber) {
2067 break;
2068 }
2069 matchingFramesFound = true;
2070
2071 if (!point->frameIsAvailable()) {
2072 // We haven't notified the remote layer that the frame for
2073 // this point is available yet. Notify it now, and then
2074 // abort this attempt to latch.
2075 point->setFrameAvailable();
2076 allTransactionsApplied = false;
2077 break;
2078 }
2079
2080 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2081 }
2082 return !matchingFramesFound || allTransactionsApplied;
2083}
2084
Brian Andersond6927fb2016-07-23 23:37:30 -07002085Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002086{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08002087 ATRACE_CALL();
2088
Jesse Hall399184a2014-03-03 15:42:54 -08002089 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2090 // mSidebandStreamChanged was true
2091 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07002092 if (mSidebandStream != NULL) {
2093 setTransactionFlags(eTransactionNeeded);
2094 mFlinger->setTransactionFlags(eTraversalNeeded);
2095 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07002096 recomputeVisibleRegions = true;
2097
2098 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07002099 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08002100 }
2101
Mathias Agopian4fec8732012-06-29 14:12:52 -07002102 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07002103 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2104 return outDirtyRegion;
2105 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002106
Fabien Sanglard223eb912016-10-13 10:15:06 -07002107 // if we've already called updateTexImage() without going through
2108 // a composition step, we have to skip this layer at this point
2109 // because we cannot call updateTeximage() without a corresponding
2110 // compositionComplete() call.
2111 // we'll trigger an update in onPreComposition().
2112 if (mRefreshPending) {
2113 return outDirtyRegion;
2114 }
2115
2116 // If the head buffer's acquire fence hasn't signaled yet, return and
2117 // try again later
2118 if (!headFenceHasSignaled()) {
2119 mFlinger->signalLayerUpdate();
2120 return outDirtyRegion;
2121 }
2122
2123 // Capture the old state of the layer for comparisons later
2124 const State& s(getDrawingState());
2125 const bool oldOpacity = isOpaque(s);
2126 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2127
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002128 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002129 mFlinger->signalLayerUpdate();
2130 return outDirtyRegion;
2131 }
2132
2133 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2134 // of the buffer queue isn't modified when the buffer queue is returning
2135 // BufferItem's that weren't actually queued. This can happen in shared
2136 // buffer mode.
2137 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002138 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2139 getProducerStickyTransform() != 0, mName.string(),
2140 mOverrideScalingMode, mFreezePositionUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002141 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2142 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2143 mLastFrameNumberReceived);
2144 if (updateResult == BufferQueue::PRESENT_LATER) {
2145 // Producer doesn't want buffer to be displayed yet. Signal a
2146 // layer update so we check again at the next opportunity.
2147 mFlinger->signalLayerUpdate();
2148 return outDirtyRegion;
2149 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2150 // If the buffer has been rejected, remove it from the shadow queue
2151 // and return early
2152 if (queuedBuffer) {
2153 Mutex::Autolock lock(mQueueItemLock);
2154 mQueueItems.removeAt(0);
2155 android_atomic_dec(&mQueuedFrames);
2156 }
2157 return outDirtyRegion;
2158 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2159 // This can occur if something goes wrong when trying to create the
2160 // EGLImage for this buffer. If this happens, the buffer has already
2161 // been released, so we need to clean up the queue and bug out
2162 // early.
2163 if (queuedBuffer) {
2164 Mutex::Autolock lock(mQueueItemLock);
2165 mQueueItems.clear();
2166 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002167 }
2168
Fabien Sanglard223eb912016-10-13 10:15:06 -07002169 // Once we have hit this state, the shadow queue may no longer
2170 // correctly reflect the incoming BufferQueue's contents, so even if
2171 // updateTexImage starts working, the only safe course of action is
2172 // to continue to ignore updates.
2173 mUpdateTexImageFailed = true;
2174
2175 return outDirtyRegion;
2176 }
2177
2178 if (queuedBuffer) {
2179 // Autolock scope
2180 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2181
2182 Mutex::Autolock lock(mQueueItemLock);
2183
2184 // Remove any stale buffers that have been dropped during
2185 // updateTexImage
2186 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2187 mQueueItems.removeAt(0);
2188 android_atomic_dec(&mQueuedFrames);
2189 }
2190
2191 mQueueItems.removeAt(0);
2192 }
2193
2194
2195 // Decrement the queued-frames count. Signal another event if we
2196 // have more frames pending.
2197 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2198 || mAutoRefresh) {
2199 mFlinger->signalLayerUpdate();
2200 }
2201
Fabien Sanglard223eb912016-10-13 10:15:06 -07002202 // update the active buffer
Chia-I Wu06d63de2017-01-04 14:58:51 +08002203 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2204 &mActiveBufferSlot);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002205 if (mActiveBuffer == NULL) {
2206 // this can only happen if the very first buffer was rejected.
2207 return outDirtyRegion;
2208 }
2209
Brian Andersond6927fb2016-07-23 23:37:30 -07002210 mBufferLatched = true;
2211 mPreviousFrameNumber = mCurrentFrameNumber;
2212 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2213
2214 {
2215 Mutex::Autolock lock(mFrameEventHistoryMutex);
2216 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2217#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002218 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002219 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002220 mReleaseTimeline.push(releaseFenceTime);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002221 if (mPreviousFrameNumber != 0) {
2222 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2223 latchTime, std::move(releaseFenceTime));
2224 }
Brian Andersond6927fb2016-07-23 23:37:30 -07002225#endif
2226 }
2227
Fabien Sanglard223eb912016-10-13 10:15:06 -07002228 mRefreshPending = true;
2229 mFrameLatencyNeeded = true;
2230 if (oldActiveBuffer == NULL) {
2231 // the first time we receive a buffer, we need to trigger a
2232 // geometry invalidation.
2233 recomputeVisibleRegions = true;
2234 }
2235
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002236 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2237
Fabien Sanglard223eb912016-10-13 10:15:06 -07002238 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2239 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2240 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2241 if ((crop != mCurrentCrop) ||
2242 (transform != mCurrentTransform) ||
2243 (scalingMode != mCurrentScalingMode))
2244 {
2245 mCurrentCrop = crop;
2246 mCurrentTransform = transform;
2247 mCurrentScalingMode = scalingMode;
2248 recomputeVisibleRegions = true;
2249 }
2250
2251 if (oldActiveBuffer != NULL) {
2252 uint32_t bufWidth = mActiveBuffer->getWidth();
2253 uint32_t bufHeight = mActiveBuffer->getHeight();
2254 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2255 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002256 recomputeVisibleRegions = true;
2257 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002258 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002259
Fabien Sanglard223eb912016-10-13 10:15:06 -07002260 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2261 if (oldOpacity != isOpaque(s)) {
2262 recomputeVisibleRegions = true;
2263 }
Dan Stozacac35382016-01-27 12:21:06 -08002264
Fabien Sanglard223eb912016-10-13 10:15:06 -07002265 // Remove any sync points corresponding to the buffer which was just
2266 // latched
2267 {
2268 Mutex::Autolock lock(mLocalSyncPointMutex);
2269 auto point = mLocalSyncPoints.begin();
2270 while (point != mLocalSyncPoints.end()) {
2271 if (!(*point)->frameIsAvailable() ||
2272 !(*point)->transactionIsApplied()) {
2273 // This sync point must have been added since we started
2274 // latching. Don't drop it yet.
2275 ++point;
2276 continue;
2277 }
2278
2279 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2280 point = mLocalSyncPoints.erase(point);
2281 } else {
2282 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002283 }
2284 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002285 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002286
2287 // FIXME: postedRegion should be dirty & bounds
2288 Region dirtyRegion(Rect(s.active.w, s.active.h));
2289
2290 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002291 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002292
Mathias Agopian4fec8732012-06-29 14:12:52 -07002293 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002294}
2295
Mathias Agopiana67932f2011-04-20 14:20:59 -07002296uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002297{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002298 // TODO: should we do something special if mSecure is set?
2299 if (mProtectedByApp) {
2300 // need a hardware-protected path to external video sink
2301 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002302 }
Riley Andrews03414a12014-07-01 14:22:59 -07002303 if (mPotentialCursor) {
2304 usage |= GraphicBuffer::USAGE_CURSOR;
2305 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002306 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002307 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002308}
2309
Mathias Agopian84300952012-11-21 16:02:13 -08002310void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002311 uint32_t orientation = 0;
2312 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002313 // The transform hint is used to improve performance, but we can
2314 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002315 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002316 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002317 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002318 if (orientation & Transform::ROT_INVALID) {
2319 orientation = 0;
2320 }
2321 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002322 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002323}
2324
Mathias Agopian13127d82013-03-05 17:47:11 -08002325// ----------------------------------------------------------------------------
2326// debugging
2327// ----------------------------------------------------------------------------
2328
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002329void Layer::dump(String8& result, Colorizer& colorizer) const
Mathias Agopian13127d82013-03-05 17:47:11 -08002330{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002331 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08002332
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002333 colorizer.colorize(result, Colorizer::GREEN);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002334 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002335 "+ %s %p (%s)\n",
2336 getTypeId(), this, getName().string());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002337 colorizer.reset(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002338
Mathias Agopian2ca79392013-04-02 18:30:32 -07002339 s.activeTransparentRegion.dump(result, "transparentRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002340 visibleRegion.dump(result, "visibleRegion");
Dan Stozaee44edd2015-03-23 15:50:23 -07002341 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002342 sp<Client> client(mClientRef.promote());
2343
Mathias Agopian74d211a2013-04-22 16:55:35 +02002344 result.appendFormat( " "
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002345 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2346 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
Mathias Agopian13127d82013-03-05 17:47:11 -08002347 "isOpaque=%1d, invalidate=%1d, "
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002348#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08002349 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002350#else
2351 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2352#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08002353 " client=%p\n",
Robert Carr1f0a16a2016-10-24 16:27:39 -07002354 getLayerStack(), s.z,
2355 s.active.transform.tx(), s.active.transform.ty(),
2356 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07002357 s.crop.left, s.crop.top,
2358 s.crop.right, s.crop.bottom,
2359 s.finalCrop.left, s.finalCrop.top,
2360 s.finalCrop.right, s.finalCrop.bottom,
Andy McFadden4125a4f2014-01-29 17:17:11 -08002361 isOpaque(s), contentDirty,
Mathias Agopian13127d82013-03-05 17:47:11 -08002362 s.alpha, s.flags,
Robert Carr3dcabfa2016-03-01 18:36:58 -08002363 s.active.transform[0][0], s.active.transform[0][1],
2364 s.active.transform[1][0], s.active.transform[1][1],
Mathias Agopian13127d82013-03-05 17:47:11 -08002365 client.get());
Mathias Agopian13127d82013-03-05 17:47:11 -08002366
2367 sp<const GraphicBuffer> buf0(mActiveBuffer);
2368 uint32_t w0=0, h0=0, s0=0, f0=0;
2369 if (buf0 != 0) {
2370 w0 = buf0->getWidth();
2371 h0 = buf0->getHeight();
2372 s0 = buf0->getStride();
2373 f0 = buf0->format;
2374 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02002375 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002376 " "
2377 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2378 " queued-frames=%d, mRefreshPending=%d\n",
2379 mFormat, w0, h0, s0,f0,
2380 mQueuedFrames, mRefreshPending);
2381
Mathias Agopian13127d82013-03-05 17:47:11 -08002382 if (mSurfaceFlingerConsumer != 0) {
Colin Cross3d1d2802016-09-26 18:10:16 -07002383 mSurfaceFlingerConsumer->dumpState(result, " ");
Mathias Agopian13127d82013-03-05 17:47:11 -08002384 }
2385}
2386
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002387#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002388void Layer::miniDumpHeader(String8& result) {
2389 result.append("----------------------------------------");
2390 result.append("---------------------------------------\n");
2391 result.append(" Layer name\n");
2392 result.append(" Z | ");
2393 result.append(" Comp Type | ");
2394 result.append(" Disp Frame (LTRB) | ");
2395 result.append(" Source Crop (LTRB)\n");
2396 result.append("----------------------------------------");
2397 result.append("---------------------------------------\n");
2398}
2399
2400void Layer::miniDump(String8& result, int32_t hwcId) const {
2401 if (mHwcLayers.count(hwcId) == 0) {
2402 return;
2403 }
2404
2405 String8 name;
2406 if (mName.length() > 77) {
2407 std::string shortened;
2408 shortened.append(mName.string(), 36);
2409 shortened.append("[...]");
2410 shortened.append(mName.string() + (mName.length() - 36), 36);
2411 name = shortened.c_str();
2412 } else {
2413 name = mName;
2414 }
2415
2416 result.appendFormat(" %s\n", name.string());
2417
2418 const Layer::State& layerState(getDrawingState());
2419 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2420 result.appendFormat(" %10u | ", layerState.z);
2421 result.appendFormat("%10s | ",
2422 to_string(getCompositionType(hwcId)).c_str());
2423 const Rect& frame = hwcInfo.displayFrame;
2424 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2425 frame.right, frame.bottom);
Dan Stoza5a423ea2017-02-16 14:10:39 -08002426 const FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002427 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2428 crop.right, crop.bottom);
2429
2430 result.append("- - - - - - - - - - - - - - - - - - - - ");
2431 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2432}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002433#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002434
Svetoslavd85084b2014-03-20 10:28:31 -07002435void Layer::dumpFrameStats(String8& result) const {
2436 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002437}
2438
Svetoslavd85084b2014-03-20 10:28:31 -07002439void Layer::clearFrameStats() {
2440 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002441}
2442
Jamie Gennis6547ff42013-07-16 20:12:42 -07002443void Layer::logFrameStats() {
2444 mFrameTracker.logAndResetStats(mName);
2445}
2446
Svetoslavd85084b2014-03-20 10:28:31 -07002447void Layer::getFrameStats(FrameStats* outStats) const {
2448 mFrameTracker.getStats(outStats);
2449}
2450
Brian Andersond6927fb2016-07-23 23:37:30 -07002451void Layer::dumpFrameEvents(String8& result) {
2452 result.appendFormat("- Layer %s (%s, %p)\n",
2453 getName().string(), getTypeId(), this);
2454 Mutex::Autolock lock(mFrameEventHistoryMutex);
2455 mFrameEventHistory.checkFencesForCompletion();
2456 mFrameEventHistory.dump(result);
2457}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002458
Brian Anderson5ea5e592016-12-01 16:54:33 -08002459void Layer::onDisconnect() {
2460 Mutex::Autolock lock(mFrameEventHistoryMutex);
2461 mFrameEventHistory.onDisconnect();
2462}
2463
Brian Anderson3890c392016-07-25 12:48:08 -07002464void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2465 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002466 Mutex::Autolock lock(mFrameEventHistoryMutex);
2467 if (newTimestamps) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002468 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002469 mFrameEventHistory.addQueue(*newTimestamps);
2470 }
2471
Brian Anderson3890c392016-07-25 12:48:08 -07002472 if (outDelta) {
2473 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002474 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002475}
Dan Stozae77c7662016-05-13 11:37:28 -07002476
2477std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2478 bool forceFlush) {
2479 std::vector<OccupancyTracker::Segment> history;
2480 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2481 &history);
2482 if (result != NO_ERROR) {
2483 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2484 result);
2485 return {};
2486 }
2487 return history;
2488}
2489
Robert Carr367c5682016-06-20 11:55:28 -07002490bool Layer::getTransformToDisplayInverse() const {
2491 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2492}
2493
Robert Carr1f0a16a2016-10-24 16:27:39 -07002494void Layer::addChild(const sp<Layer>& layer) {
2495 mCurrentChildren.add(layer);
2496 layer->setParent(this);
2497}
2498
2499ssize_t Layer::removeChild(const sp<Layer>& layer) {
2500 layer->setParent(nullptr);
2501 return mCurrentChildren.remove(layer);
2502}
2503
Robert Carr1db73f62016-12-21 12:58:51 -08002504bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2505 sp<Handle> handle = nullptr;
2506 sp<Layer> newParent = nullptr;
2507 if (newParentHandle == nullptr) {
2508 return false;
2509 }
2510 handle = static_cast<Handle*>(newParentHandle.get());
2511 newParent = handle->owner.promote();
2512 if (newParent == nullptr) {
2513 ALOGE("Unable to promote Layer handle");
2514 return false;
2515 }
2516
2517 for (const sp<Layer>& child : mCurrentChildren) {
2518 newParent->addChild(child);
2519
2520 sp<Client> client(child->mClientRef.promote());
2521 if (client != nullptr) {
2522 client->setParentLayer(newParent);
2523 }
2524 }
2525 mCurrentChildren.clear();
2526
2527 return true;
2528}
2529
Robert Carr9524cb32017-02-13 11:32:32 -08002530bool Layer::detachChildren() {
Dan Stoza412903f2017-04-27 13:42:17 -07002531 traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
Robert Carr9524cb32017-02-13 11:32:32 -08002532 if (child == this) {
2533 return;
2534 }
2535
2536 sp<Client> client(child->mClientRef.promote());
2537 if (client != nullptr) {
2538 client->detachLayer(child);
2539 }
2540 });
2541
2542 return true;
2543}
2544
Robert Carr1f0a16a2016-10-24 16:27:39 -07002545void Layer::setParent(const sp<Layer>& layer) {
2546 mParent = layer;
2547}
2548
2549void Layer::clearSyncPoints() {
2550 for (const auto& child : mCurrentChildren) {
2551 child->clearSyncPoints();
2552 }
2553
2554 Mutex::Autolock lock(mLocalSyncPointMutex);
2555 for (auto& point : mLocalSyncPoints) {
2556 point->setFrameAvailable();
2557 }
2558 mLocalSyncPoints.clear();
2559}
2560
2561int32_t Layer::getZ() const {
2562 return mDrawingState.z;
2563}
2564
Dan Stoza412903f2017-04-27 13:42:17 -07002565LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2566 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2567 "makeTraversalList received invalid stateSet");
2568 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2569 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2570 const State& state = useDrawing ? mDrawingState : mCurrentState;
2571
2572 if (state.zOrderRelatives.size() == 0) {
2573 return children;
Robert Carrdb66e622017-04-10 16:55:57 -07002574 }
2575 LayerVector traverse;
2576
Dan Stoza412903f2017-04-27 13:42:17 -07002577 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07002578 sp<Layer> strongRelative = weakRelative.promote();
2579 if (strongRelative != nullptr) {
2580 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07002581 }
2582 }
2583
Dan Stoza412903f2017-04-27 13:42:17 -07002584 for (const sp<Layer>& child : children) {
Robert Carrdb66e622017-04-10 16:55:57 -07002585 traverse.add(child);
2586 }
2587
2588 return traverse;
2589}
2590
Robert Carr1f0a16a2016-10-24 16:27:39 -07002591/**
Robert Carrdb66e622017-04-10 16:55:57 -07002592 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002593 */
Dan Stoza412903f2017-04-27 13:42:17 -07002594void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2595 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002596
Robert Carr1f0a16a2016-10-24 16:27:39 -07002597 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002598 for (; i < list.size(); i++) {
2599 const auto& relative = list[i];
2600 if (relative->getZ() >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002601 break;
Robert Carrdb66e622017-04-10 16:55:57 -07002602 }
Dan Stoza412903f2017-04-27 13:42:17 -07002603 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002604 }
Dan Stoza412903f2017-04-27 13:42:17 -07002605 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07002606 for (; i < list.size(); i++) {
2607 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002608 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002609 }
2610}
2611
2612/**
Robert Carrdb66e622017-04-10 16:55:57 -07002613 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002614 */
Dan Stoza412903f2017-04-27 13:42:17 -07002615void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2616 const LayerVector::Visitor& visitor) {
2617 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002618
Robert Carr1f0a16a2016-10-24 16:27:39 -07002619 int32_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002620 for (i = list.size()-1; i>=0; i--) {
2621 const auto& relative = list[i];
2622 if (relative->getZ() < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002623 break;
2624 }
Dan Stoza412903f2017-04-27 13:42:17 -07002625 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002626 }
Dan Stoza412903f2017-04-27 13:42:17 -07002627 visitor(this);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002628 for (; i>=0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002629 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002630 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002631 }
2632}
2633
2634Transform Layer::getTransform() const {
2635 Transform t;
2636 const auto& p = getParent();
2637 if (p != nullptr) {
2638 t = p->getTransform();
Robert Carr9b429f42017-04-17 14:56:57 -07002639
2640 // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2641 // it isFixedSize) then there may be additional scaling not accounted
2642 // for in the transform. We need to mirror this scaling in child surfaces
2643 // or we will break the contract where WM can treat child surfaces as
2644 // pixels in the parent surface.
2645 if (p->isFixedSize()) {
Robert Carr1725eee2017-04-26 18:32:15 -07002646 int bufferWidth;
2647 int bufferHeight;
2648 if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2649 bufferWidth = p->mActiveBuffer->getWidth();
2650 bufferHeight = p->mActiveBuffer->getHeight();
2651 } else {
2652 bufferHeight = p->mActiveBuffer->getWidth();
2653 bufferWidth = p->mActiveBuffer->getHeight();
2654 }
Robert Carr9b429f42017-04-17 14:56:57 -07002655 float sx = p->getDrawingState().active.w /
Robert Carr1725eee2017-04-26 18:32:15 -07002656 static_cast<float>(bufferWidth);
Robert Carr9b429f42017-04-17 14:56:57 -07002657 float sy = p->getDrawingState().active.h /
Robert Carr1725eee2017-04-26 18:32:15 -07002658 static_cast<float>(bufferHeight);
Robert Carr9b429f42017-04-17 14:56:57 -07002659 Transform extraParentScaling;
2660 extraParentScaling.set(sx, 0, 0, sy);
2661 t = t * extraParentScaling;
2662 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002663 }
2664 return t * getDrawingState().active.transform;
2665}
2666
Robert Carr6452f122017-03-21 10:41:29 -07002667#ifdef USE_HWC2
2668float Layer::getAlpha() const {
2669 const auto& p = getParent();
2670
2671 float parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0;
2672 return parentAlpha * getDrawingState().alpha;
2673}
2674#else
2675uint8_t Layer::getAlpha() const {
2676 const auto& p = getParent();
2677
2678 float parentAlpha = (p != nullptr) ? (p->getAlpha() / 255.0f) : 1.0;
2679 float drawingAlpha = getDrawingState().alpha / 255.0f;
2680 drawingAlpha = drawingAlpha * parentAlpha;
2681 return static_cast<uint8_t>(std::round(drawingAlpha * 255));
2682}
2683#endif
2684
Robert Carr1f0a16a2016-10-24 16:27:39 -07002685void Layer::commitChildList() {
2686 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2687 const auto& child = mCurrentChildren[i];
2688 child->commitChildList();
2689 }
2690 mDrawingChildren = mCurrentChildren;
2691}
2692
Mathias Agopian13127d82013-03-05 17:47:11 -08002693// ---------------------------------------------------------------------------
2694
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002695}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002696
2697#if defined(__gl_h_)
2698#error "don't include gl/gl.h in this file"
2699#endif
2700
2701#if defined(__gl2_h_)
2702#error "don't include gl2/gl2.h in this file"
2703#endif