blob: 3903a5546f334334886aaa1ab40b31972c2682b0 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017//#define LOG_NDEBUG 0
18#undef LOG_TAG
19#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080020#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <stdlib.h>
23#include <stdint.h>
24#include <sys/types.h>
Mathias Agopian13127d82013-03-05 17:47:11 -080025#include <math.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080026
Mathias Agopiana67932f2011-04-20 14:20:59 -070027#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070028#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070029#include <cutils/properties.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
31#include <utils/Errors.h>
32#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080033#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080034#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080035#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080036
Courtney Goeltzenleuchter36c44dc2017-04-14 09:33:16 -060037#include <ui/DebugUtils.h>
Mathias Agopian3330b202009-10-05 17:07:12 -070038#include <ui/GraphicBuffer.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080039#include <ui/PixelFormat.h>
Mathias Agopian9cce3252010-02-09 17:46:37 -080040
Dan Stoza6b9454d2014-11-07 16:00:59 -080041#include <gui/BufferItem.h>
Mathias Agopiana9347642017-02-13 16:42:28 -080042#include <gui/BufferQueue.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080043#include <gui/LayerDebugInfo.h>
Mathias Agopian90ac7992012-02-25 18:48:35 -080044#include <gui/Surface.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080045
46#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020047#include "Colorizer.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070048#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080049#include "Layer.h"
Fabien Sanglard7b1563a2016-10-13 12:05:28 -070050#include "LayerRejecter.h"
Dan Stozab9b08832014-03-13 11:55:57 -070051#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080052#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080053
Mathias Agopian1b031492012-06-20 17:51:20 -070054#include "DisplayHardware/HWComposer.h"
55
Mathias Agopian875d8e12013-06-07 15:35:48 -070056#include "RenderEngine/RenderEngine.h"
57
Dan Stozac5da2712016-07-20 15:38:12 -070058#include <mutex>
59
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060#define DEBUG_RESIZE 0
61
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062namespace android {
63
64// ---------------------------------------------------------------------------
65
Mathias Agopian13127d82013-03-05 17:47:11 -080066int32_t Layer::sSequence = 1;
67
Mathias Agopian4d9b8222013-03-12 17:11:48 -070068Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
69 const String8& name, uint32_t w, uint32_t h, uint32_t flags)
Mathias Agopian13127d82013-03-05 17:47:11 -080070 : contentDirty(false),
71 sequence(uint32_t(android_atomic_inc(&sSequence))),
72 mFlinger(flinger),
Mathias Agopiana67932f2011-04-20 14:20:59 -070073 mTextureName(-1U),
Mathias Agopian13127d82013-03-05 17:47:11 -080074 mPremultipliedAlpha(true),
75 mName("unnamed"),
Mathias Agopian13127d82013-03-05 17:47:11 -080076 mFormat(PIXEL_FORMAT_NONE),
Mathias Agopian13127d82013-03-05 17:47:11 -080077 mTransactionFlags(0),
Dan Stoza7dde5992015-05-22 09:51:44 -070078 mPendingStateMutex(),
79 mPendingStates(),
Mathias Agopiana67932f2011-04-20 14:20:59 -070080 mQueuedFrames(0),
Jesse Hall399184a2014-03-03 15:42:54 -080081 mSidebandStreamChanged(false),
Mathias Agopiana9347642017-02-13 16:42:28 -080082 mActiveBufferSlot(BufferQueue::INVALID_BUFFER_SLOT),
Mathias Agopiana67932f2011-04-20 14:20:59 -070083 mCurrentTransform(0),
Mathias Agopian933389f2011-07-18 16:15:08 -070084 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
Robert Carrc3574f72016-03-24 12:19:32 -070085 mOverrideScalingMode(-1),
Mathias Agopiana67932f2011-04-20 14:20:59 -070086 mCurrentOpacity(true),
Brian Andersond6927fb2016-07-23 23:37:30 -070087 mBufferLatched(false),
Dan Stozacac35382016-01-27 12:21:06 -080088 mCurrentFrameNumber(0),
Brian Anderson8cc8b102016-10-21 12:43:09 -070089 mPreviousFrameNumber(0),
Mathias Agopian4d143ee2012-02-23 20:05:39 -080090 mRefreshPending(false),
Mathias Agopian82d7ab62012-01-19 18:34:40 -080091 mFrameLatencyNeeded(false),
Mathias Agopian13127d82013-03-05 17:47:11 -080092 mFiltering(false),
93 mNeedsFiltering(false),
Mathias Agopian5cdc8992013-08-13 20:51:23 -070094 mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
Fabien Sanglard9d96de42016-10-11 00:15:18 +000095#ifndef USE_HWC2
96 mIsGlesComposition(false),
97#endif
Mathias Agopian13127d82013-03-05 17:47:11 -080098 mProtectedByApp(false),
99 mHasSurface(false),
Riley Andrews03414a12014-07-01 14:22:59 -0700100 mClientRef(client),
Dan Stozaa4650a52015-05-12 12:56:16 -0700101 mPotentialCursor(false),
102 mQueueItemLock(),
103 mQueueItemCondition(),
104 mQueueItems(),
Dan Stoza65476f32015-05-14 09:27:25 -0700105 mLastFrameNumberReceived(0),
Pablo Ceballos04839ab2015-11-13 13:39:23 -0800106 mUpdateTexImageFailed(false),
Robert Carr82364e32016-05-15 11:27:47 -0700107 mAutoRefresh(false),
Robert Carr7bf247e2017-05-18 14:02:49 -0700108 mFreezeGeometryUpdates(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800109{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000110#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800111 ALOGV("Creating Layer %s", name.string());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000112#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -0800113
Mathias Agopiana67932f2011-04-20 14:20:59 -0700114 mCurrentCrop.makeInvalid();
Mathias Agopian3f844832013-08-07 21:24:32 -0700115 mFlinger->getRenderEngine().genTextures(1, &mTextureName);
Mathias Agopian49457ac2013-08-14 18:20:17 -0700116 mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700117
118 uint32_t layerFlags = 0;
119 if (flags & ISurfaceComposerClient::eHidden)
Andy McFadden4125a4f2014-01-29 17:17:11 -0800120 layerFlags |= layer_state_t::eLayerHidden;
121 if (flags & ISurfaceComposerClient::eOpaque)
122 layerFlags |= layer_state_t::eLayerOpaque;
Dan Stoza23116082015-06-18 14:58:39 -0700123 if (flags & ISurfaceComposerClient::eSecure)
124 layerFlags |= layer_state_t::eLayerSecure;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700125
126 if (flags & ISurfaceComposerClient::eNonPremultiplied)
127 mPremultipliedAlpha = false;
128
129 mName = name;
Dan Stozaf7ba41a2017-05-10 15:11:11 -0700130 mTransactionName = String8("TX - ") + mName;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700131
132 mCurrentState.active.w = w;
133 mCurrentState.active.h = h;
Robert Carr3dcabfa2016-03-01 18:36:58 -0800134 mCurrentState.active.transform.set(0, 0);
Robert Carrb5d3d262016-03-25 15:08:13 -0700135 mCurrentState.crop.makeInvalid();
136 mCurrentState.finalCrop.makeInvalid();
Robert Carr7bf247e2017-05-18 14:02:49 -0700137 mCurrentState.requestedFinalCrop = mCurrentState.finalCrop;
138 mCurrentState.requestedCrop = mCurrentState.crop;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700139 mCurrentState.z = 0;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000140#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800141 mCurrentState.alpha = 1.0f;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000142#else
143 mCurrentState.alpha = 0xFF;
144#endif
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700145 mCurrentState.layerStack = 0;
146 mCurrentState.flags = layerFlags;
147 mCurrentState.sequence = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700148 mCurrentState.requested = mCurrentState.active;
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700149 mCurrentState.dataSpace = HAL_DATASPACE_UNKNOWN;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500150 mCurrentState.appId = 0;
151 mCurrentState.type = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700152
153 // drawing state & current state are identical
154 mDrawingState = mCurrentState;
Jamie Gennis6547ff42013-07-16 20:12:42 -0700155
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000156#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800157 const auto& hwc = flinger->getHwComposer();
158 const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
159 nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000160#else
161 nsecs_t displayPeriod =
162 flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
163#endif
Jamie Gennis6547ff42013-07-16 20:12:42 -0700164 mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -0800165
166 CompositorTiming compositorTiming;
167 flinger->getCompositorTiming(&compositorTiming);
168 mFrameEventHistory.initializeCompositorTiming(compositorTiming);
Jamie Gennise8696a42012-01-15 18:54:57 -0800169}
170
Mathias Agopian3f844832013-08-07 21:24:32 -0700171void Layer::onFirstRef() {
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800172 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
Dan Stozab3d0bdf2014-04-07 16:33:59 -0700173 sp<IGraphicBufferProducer> producer;
174 sp<IGraphicBufferConsumer> consumer;
Mathias Agopian0556d792017-03-22 15:49:32 -0700175 BufferQueue::createBufferQueue(&producer, &consumer, true);
Robert Carr1db73f62016-12-21 12:58:51 -0800176 mProducer = new MonitoredProducer(producer, mFlinger, this);
Irvel468051e2016-06-13 16:44:44 -0700177 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800178 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Jesse Hall399184a2014-03-03 15:42:54 -0800179 mSurfaceFlingerConsumer->setContentsChangedListener(this);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700180 mSurfaceFlingerConsumer->setName(mName);
Daniel Lamb2675792012-02-23 14:35:13 -0800181
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800182 if (mFlinger->isLayerTripleBufferingDisabled()) {
183 mProducer->setMaxDequeuedBufferCount(2);
184 }
Andy McFadden69052052012-09-14 16:10:11 -0700185
Mathias Agopian84300952012-11-21 16:02:13 -0800186 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
187 updateTransformHint(hw);
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700188}
189
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700190Layer::~Layer() {
Pablo Ceballos8ea4e7b2016-03-03 15:20:02 -0800191 sp<Client> c(mClientRef.promote());
192 if (c != 0) {
193 c->detachLayer(this);
194 }
195
Dan Stozacac35382016-01-27 12:21:06 -0800196 for (auto& point : mRemoteSyncPoints) {
197 point->setTransactionApplied();
198 }
Dan Stozac8145172016-04-28 16:29:06 -0700199 for (auto& point : mLocalSyncPoints) {
200 point->setFrameAvailable();
201 }
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700202 mFlinger->deleteTextureAsync(mTextureName);
Jamie Gennis6547ff42013-07-16 20:12:42 -0700203 mFrameTracker.logAndResetStats(mName);
Mathias Agopian96f08192010-06-02 23:28:45 -0700204}
205
Mathias Agopian13127d82013-03-05 17:47:11 -0800206// ---------------------------------------------------------------------------
207// callbacks
208// ---------------------------------------------------------------------------
209
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000210#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800211void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
212 if (mHwcLayers.empty()) {
213 return;
214 }
215 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
216}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000217#else
218void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
219 HWComposer::HWCLayerInterface* layer) {
220 if (layer) {
221 layer->onDisplayed();
222 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
223 }
224}
225#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800226
Dan Stoza6b9454d2014-11-07 16:00:59 -0800227void Layer::onFrameAvailable(const BufferItem& item) {
228 // Add this buffer from our internal queue tracker
229 { // Autolock scope
230 Mutex::Autolock lock(mQueueItemLock);
Irvel468051e2016-06-13 16:44:44 -0700231 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
232 item.mGraphicBuffer->getHeight(), item.mFrameNumber);
Dan Stozaa4650a52015-05-12 12:56:16 -0700233 // Reset the frame number tracker when we receive the first buffer after
234 // a frame number reset
235 if (item.mFrameNumber == 1) {
236 mLastFrameNumberReceived = 0;
237 }
238
239 // Ensure that callbacks are handled in order
240 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
241 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
242 ms2ns(500));
243 if (result != NO_ERROR) {
244 ALOGE("[%s] Timed out waiting on callback", mName.string());
245 }
246 }
247
Dan Stoza6b9454d2014-11-07 16:00:59 -0800248 mQueueItems.push_back(item);
Dan Stozaecc50402015-04-28 14:42:06 -0700249 android_atomic_inc(&mQueuedFrames);
Dan Stozaa4650a52015-05-12 12:56:16 -0700250
251 // Wake up any pending callbacks
252 mLastFrameNumberReceived = item.mFrameNumber;
253 mQueueItemCondition.broadcast();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800254 }
255
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800256 mFlinger->signalLayerUpdate();
Mathias Agopian579b3f82010-06-08 19:54:15 -0700257}
258
Dan Stoza6b9454d2014-11-07 16:00:59 -0800259void Layer::onFrameReplaced(const BufferItem& item) {
Dan Stoza7dde5992015-05-22 09:51:44 -0700260 { // Autolock scope
261 Mutex::Autolock lock(mQueueItemLock);
Dan Stozaa4650a52015-05-12 12:56:16 -0700262
Dan Stoza7dde5992015-05-22 09:51:44 -0700263 // Ensure that callbacks are handled in order
264 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
265 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
266 ms2ns(500));
267 if (result != NO_ERROR) {
268 ALOGE("[%s] Timed out waiting on callback", mName.string());
269 }
Dan Stozaa4650a52015-05-12 12:56:16 -0700270 }
Dan Stoza7dde5992015-05-22 09:51:44 -0700271
272 if (mQueueItems.empty()) {
273 ALOGE("Can't replace a frame on an empty queue");
274 return;
275 }
Pablo Ceballos4d85da42016-04-19 20:11:56 -0700276 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
Dan Stoza7dde5992015-05-22 09:51:44 -0700277
278 // Wake up any pending callbacks
279 mLastFrameNumberReceived = item.mFrameNumber;
280 mQueueItemCondition.broadcast();
Dan Stozaa4650a52015-05-12 12:56:16 -0700281 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800282}
283
Jesse Hall399184a2014-03-03 15:42:54 -0800284void Layer::onSidebandStreamChanged() {
285 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
286 // mSidebandStreamChanged was false
287 mFlinger->signalLayerUpdate();
288 }
289}
290
Mathias Agopian67106042013-03-14 19:18:13 -0700291// called with SurfaceFlinger::mStateLock from the drawing thread after
292// the layer has been remove from the current state list (and just before
293// it's removed from the drawing state list)
Mathias Agopian13127d82013-03-05 17:47:11 -0800294void Layer::onRemoved() {
Robert Carr5edb1ad2017-04-25 10:54:24 -0700295 if (mCurrentState.zOrderRelativeOf != nullptr) {
296 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
297 if (strongRelative != nullptr) {
298 strongRelative->removeZOrderRelative(this);
299 }
300 mCurrentState.zOrderRelativeOf = nullptr;
301 }
302
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800303 mSurfaceFlingerConsumer->abandon();
Chia-I Wu38512252017-05-17 14:36:16 -0700304
305#ifdef USE_HWC2
306 clearHwcLayers();
307#endif
308
Robert Carr1f0a16a2016-10-24 16:27:39 -0700309 for (const auto& child : mCurrentChildren) {
310 child->onRemoved();
311 }
Mathias Agopian48d819a2009-09-10 19:41:18 -0700312}
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700313
Mathias Agopian13127d82013-03-05 17:47:11 -0800314// ---------------------------------------------------------------------------
315// set-up
316// ---------------------------------------------------------------------------
317
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700318const String8& Layer::getName() const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800319 return mName;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800320}
321
Mathias Agopianf9d93272009-06-19 17:00:27 -0700322status_t Layer::setBuffers( uint32_t w, uint32_t h,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800323 PixelFormat format, uint32_t flags)
324{
Mathias Agopianca99fb82010-04-14 16:43:44 -0700325 uint32_t const maxSurfaceDims = min(
Mathias Agopiana4912602012-07-12 14:25:33 -0700326 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
Mathias Agopianca99fb82010-04-14 16:43:44 -0700327
328 // never allow a surface larger than what our underlying GL implementation
329 // can handle.
330 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
Mathias Agopianff615cc2012-02-24 14:58:36 -0800331 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700332 return BAD_VALUE;
333 }
334
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700335 mFormat = format;
Mathias Agopianeff062c2010-08-25 14:59:15 -0700336
Riley Andrews03414a12014-07-01 14:22:59 -0700337 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
Mathias Agopian3165cc22012-08-08 19:42:09 -0700338 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700339 mCurrentOpacity = getOpacityForFormat(format);
340
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800341 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
342 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
343 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700344
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800345 return NO_ERROR;
346}
347
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700348sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800349 Mutex::Autolock _l(mLock);
350
351 LOG_ALWAYS_FATAL_IF(mHasSurface,
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700352 "Layer::getHandle() has already been called");
Mathias Agopian13127d82013-03-05 17:47:11 -0800353
354 mHasSurface = true;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700355
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700356 return new Handle(mFlinger, this);
Mathias Agopian13127d82013-03-05 17:47:11 -0800357}
358
Dan Stozab9b08832014-03-13 11:55:57 -0700359sp<IGraphicBufferProducer> Layer::getProducer() const {
360 return mProducer;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700361}
362
Mathias Agopian13127d82013-03-05 17:47:11 -0800363// ---------------------------------------------------------------------------
364// h/w composer set-up
365// ---------------------------------------------------------------------------
366
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800367Rect Layer::getContentCrop() const {
368 // this is the crop rectangle that applies to the buffer
369 // itself (as opposed to the window)
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700370 Rect crop;
371 if (!mCurrentCrop.isEmpty()) {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800372 // if the buffer crop is defined, we use that
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700373 crop = mCurrentCrop;
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800374 } else if (mActiveBuffer != NULL) {
375 // otherwise we use the whole buffer
376 crop = mActiveBuffer->getBounds();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700377 } else {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800378 // if we don't have a buffer yet, we use an empty/invalid crop
Mathias Agopian4fec8732012-06-29 14:12:52 -0700379 crop.makeInvalid();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700380 }
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700381 return crop;
382}
383
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700384static Rect reduce(const Rect& win, const Region& exclude) {
385 if (CC_LIKELY(exclude.isEmpty())) {
386 return win;
387 }
388 if (exclude.isRect()) {
389 return win.reduce(exclude.getBounds());
390 }
391 return Region(win).subtract(exclude).getBounds();
392}
393
Robert Carr1f0a16a2016-10-24 16:27:39 -0700394Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
395 const Layer::State& s(getDrawingState());
396 Rect win(s.active.w, s.active.h);
397
398 if (!s.crop.isEmpty()) {
399 win.intersect(s.crop, &win);
400 }
401
402 Transform t = getTransform();
403 win = t.transform(win);
404
Robert Carr41b08b52017-06-01 16:11:34 -0700405 if (!s.finalCrop.isEmpty()) {
406 win.intersect(s.finalCrop, &win);
407 }
408
Chia-I Wue41dbe62017-06-13 14:10:56 -0700409 const sp<Layer>& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700410 // Now we need to calculate the parent bounds, so we can clip ourselves to those.
411 // When calculating the parent bounds for purposes of clipping,
412 // we don't need to constrain the parent to its transparent region.
413 // The transparent region is an optimization based on the
414 // buffer contents of the layer, but does not affect the space allocated to
415 // it by policy, and thus children should be allowed to extend into the
416 // parent's transparent region. In fact one of the main uses, is to reduce
417 // buffer allocation size in cases where a child window sits behind a main window
418 // (by marking the hole in the parent window as a transparent region)
419 if (p != nullptr) {
420 Rect bounds = p->computeScreenBounds(false);
421 bounds.intersect(win, &win);
422 }
423
424 if (reduceTransparentRegion) {
425 auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
426 win = reduce(win, screenTransparentRegion);
427 }
428
429 return win;
430}
431
Mathias Agopian13127d82013-03-05 17:47:11 -0800432Rect Layer::computeBounds() const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700433 const Layer::State& s(getDrawingState());
Michael Lentine6c925ed2014-09-26 17:55:01 -0700434 return computeBounds(s.activeTransparentRegion);
435}
436
437Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
438 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800439 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700440
441 if (!s.crop.isEmpty()) {
442 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -0800443 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700444
445 Rect bounds = win;
Chia-I Wue41dbe62017-06-13 14:10:56 -0700446 const auto& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700447 if (p != nullptr) {
Robert Carrde9ec442017-02-08 17:43:36 -0800448 // Look in computeScreenBounds recursive call for explanation of
449 // why we pass false here.
450 bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700451 }
452
453 Transform t = getTransform();
454 if (p != nullptr) {
455 win = t.transform(win);
456 win.intersect(bounds, &win);
457 win = t.inverse().transform(win);
458 }
459
Mathias Agopian6c7f25a2013-05-09 20:37:10 -0700460 // subtract the transparent region and snap to the bounds
Michael Lentine6c925ed2014-09-26 17:55:01 -0700461 return reduce(win, activeTransparentRegion);
Mathias Agopian13127d82013-03-05 17:47:11 -0800462}
463
Robert Carr1f0a16a2016-10-24 16:27:39 -0700464Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
Robert Carrb5d3d262016-03-25 15:08:13 -0700465 // the crop is the area of the window that gets cropped, but not
Mathias Agopian13127d82013-03-05 17:47:11 -0800466 // scaled in any ways.
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700467 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800468
469 // apply the projection's clipping to the window crop in
470 // layerstack space, and convert-back to layer space.
Mathias Agopian6b442672013-07-09 21:24:52 -0700471 // if there are no window scaling involved, this operation will map to full
472 // pixels in the buffer.
473 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
474 // a viewport clipping and a window transform. we should use floating point to fix this.
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700475
476 Rect activeCrop(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700477 if (!s.crop.isEmpty()) {
Chia-I Wudf7867f2017-07-20 14:24:37 -0700478 activeCrop.intersect(s.crop, &activeCrop);
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700479 }
480
Robert Carr1f0a16a2016-10-24 16:27:39 -0700481 Transform t = getTransform();
482 activeCrop = t.transform(activeCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000483 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
484 activeCrop.clear();
485 }
Robert Carrb5d3d262016-03-25 15:08:13 -0700486 if (!s.finalCrop.isEmpty()) {
487 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000488 activeCrop.clear();
489 }
490 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700491 return activeCrop;
492}
493
Dan Stoza5a423ea2017-02-16 14:10:39 -0800494FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
Robert Carr1f0a16a2016-10-24 16:27:39 -0700495 // the content crop is the area of the content that gets scaled to the
496 // layer's size. This is in buffer space.
Dan Stoza5a423ea2017-02-16 14:10:39 -0800497 FloatRect crop = getContentCrop().toFloatRect();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700498
499 // In addition there is a WM-specified crop we pull from our drawing state.
500 const State& s(getDrawingState());
501
502 // Screen space to make reduction to parent crop clearer.
503 Rect activeCrop = computeInitialCrop(hw);
Chia-I Wue41dbe62017-06-13 14:10:56 -0700504 const auto& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700505 if (p != nullptr) {
506 auto parentCrop = p->computeInitialCrop(hw);
507 activeCrop.intersect(parentCrop, &activeCrop);
508 }
509 Transform t = getTransform();
510 // Back to layer space to work with the content crop.
511 activeCrop = t.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800512
Michael Lentine28ea2172014-11-19 18:32:37 -0800513 // This needs to be here as transform.transform(Rect) computes the
514 // transformed rect and then takes the bounding box of the result before
515 // returning. This means
516 // transform.inverse().transform(transform.transform(Rect)) != Rect
517 // in which case we need to make sure the final rect is clipped to the
518 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000519 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
520 activeCrop.clear();
521 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800522
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700523 // subtract the transparent region and snap to the bounds
524 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
525
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000526 // Transform the window crop to match the buffer coordinate system,
527 // which means using the inverse of the current transform set on the
528 // SurfaceFlingerConsumer.
529 uint32_t invTransform = mCurrentTransform;
Robert Carrcae605c2017-03-29 12:10:31 -0700530 if (getTransformToDisplayInverse()) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000531 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700532 * the code below applies the primary display's inverse transform to the
533 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000534 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700535 uint32_t invTransformOrient =
536 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000537 // calculate the inverse transform
538 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
539 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
540 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800541 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000542 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700543 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
544 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800545 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000546
547 int winWidth = s.active.w;
548 int winHeight = s.active.h;
549 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
550 // If the activeCrop has been rotate the ends are rotated but not
551 // the space itself so when transforming ends back we can't rely on
552 // a modification of the axes of rotation. To account for this we
553 // need to reorient the inverse rotation in terms of the current
554 // axes of rotation.
555 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
556 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
557 if (is_h_flipped == is_v_flipped) {
558 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
559 NATIVE_WINDOW_TRANSFORM_FLIP_H;
560 }
561 winWidth = s.active.h;
562 winHeight = s.active.w;
563 }
564 const Rect winCrop = activeCrop.transform(
565 invTransform, s.active.w, s.active.h);
566
567 // below, crop is intersected with winCrop expressed in crop's coordinate space
568 float xScale = crop.getWidth() / float(winWidth);
569 float yScale = crop.getHeight() / float(winHeight);
570
571 float insetL = winCrop.left * xScale;
572 float insetT = winCrop.top * yScale;
573 float insetR = (winWidth - winCrop.right ) * xScale;
574 float insetB = (winHeight - winCrop.bottom) * yScale;
575
576 crop.left += insetL;
577 crop.top += insetT;
578 crop.right -= insetR;
579 crop.bottom -= insetB;
580
Mathias Agopian13127d82013-03-05 17:47:11 -0800581 return crop;
582}
583
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000584#ifdef USE_HWC2
Robert Carrae060832016-11-28 10:51:00 -0800585void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000586#else
587void Layer::setGeometry(
588 const sp<const DisplayDevice>& hw,
589 HWComposer::HWCLayerInterface& layer)
590#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700591{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000592#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800593 const auto hwcId = displayDevice->getHwcDisplayId();
594 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000595#else
596 layer.setDefaultState();
597#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700598
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700599 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000600#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800601 hwcInfo.forceClientComposition = false;
602
603 if (isSecure() && !displayDevice->isSecure()) {
604 hwcInfo.forceClientComposition = true;
605 }
606
607 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000608#else
609 layer.setSkip(false);
610
611 if (isSecure() && !hw->isSecure()) {
612 layer.setSkip(true);
613 }
614#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700615
Mathias Agopian13127d82013-03-05 17:47:11 -0800616 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700617 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000618#ifdef USE_HWC2
David Revemanecf0fa52017-03-03 11:32:44 -0500619 auto blendMode = HWC2::BlendMode::None;
Robert Carr6452f122017-03-21 10:41:29 -0700620 if (!isOpaque(s) || getAlpha() != 1.0f) {
David Revemanecf0fa52017-03-03 11:32:44 -0500621 blendMode = mPremultipliedAlpha ?
Dan Stoza9e56aa02015-11-02 13:00:03 -0800622 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800623 }
David Revemanecf0fa52017-03-03 11:32:44 -0500624 auto error = hwcLayer->setBlendMode(blendMode);
625 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
626 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
627 to_string(error).c_str(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000628#else
Robert Carr6452f122017-03-21 10:41:29 -0700629 if (!isOpaque(s) || getAlpha() != 0xFF) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000630 layer.setBlending(mPremultipliedAlpha ?
631 HWC_BLENDING_PREMULT :
632 HWC_BLENDING_COVERAGE);
633 }
634#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800635
636 // apply the layer's transform, followed by the display's global transform
637 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700638 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700639 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -0700640 if (!s.crop.isEmpty()) {
641 Rect activeCrop(s.crop);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700642 activeCrop = t.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000643#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000644 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000645#else
646 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
647#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000648 activeCrop.clear();
649 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700650 activeCrop = t.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800651 // This needs to be here as transform.transform(Rect) computes the
652 // transformed rect and then takes the bounding box of the result before
653 // returning. This means
654 // transform.inverse().transform(transform.transform(Rect)) != Rect
655 // in which case we need to make sure the final rect is clipped to the
656 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000657 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
658 activeCrop.clear();
659 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700660 // mark regions outside the crop as transparent
661 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
662 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
663 s.active.w, s.active.h));
664 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
665 activeCrop.left, activeCrop.bottom));
666 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
667 s.active.w, activeCrop.bottom));
668 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700669
670 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700671 if (!s.finalCrop.isEmpty()) {
672 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000673 frame.clear();
674 }
675 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000676#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000677 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
678 frame.clear();
679 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800680 const Transform& tr(displayDevice->getTransform());
681 Rect transformedFrame = tr.transform(frame);
David Revemanecf0fa52017-03-03 11:32:44 -0500682 error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700683 if (error != HWC2::Error::None) {
684 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
685 mName.string(), transformedFrame.left, transformedFrame.top,
686 transformedFrame.right, transformedFrame.bottom,
687 to_string(error).c_str(), static_cast<int32_t>(error));
688 } else {
689 hwcInfo.displayFrame = transformedFrame;
690 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800691
Dan Stoza5a423ea2017-02-16 14:10:39 -0800692 FloatRect sourceCrop = computeCrop(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800693 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700694 if (error != HWC2::Error::None) {
695 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
696 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
697 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
698 static_cast<int32_t>(error));
699 } else {
700 hwcInfo.sourceCrop = sourceCrop;
701 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800702
Robert Carr6452f122017-03-21 10:41:29 -0700703 float alpha = getAlpha();
704 error = hwcLayer->setPlaneAlpha(alpha);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800705 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
Robert Carr6452f122017-03-21 10:41:29 -0700706 "%s (%d)", mName.string(), alpha, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800707 static_cast<int32_t>(error));
708
Robert Carrae060832016-11-28 10:51:00 -0800709 error = hwcLayer->setZOrder(z);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800710 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
Robert Carrae060832016-11-28 10:51:00 -0800711 mName.string(), z, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800712 static_cast<int32_t>(error));
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500713
Albert Chaulk2a589632017-05-04 16:59:44 -0400714 int type = s.type;
715 int appId = s.appId;
Chia-I Wue41dbe62017-06-13 14:10:56 -0700716 sp<Layer> parent = mDrawingParent.promote();
Albert Chaulk2a589632017-05-04 16:59:44 -0400717 if (parent.get()) {
718 auto& parentState = parent->getDrawingState();
719 type = parentState.type;
720 appId = parentState.appId;
721 }
722
723 error = hwcLayer->setInfo(type, appId);
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500724 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
725 mName.string(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000726#else
727 if (!frame.intersect(hw->getViewport(), &frame)) {
728 frame.clear();
729 }
730 const Transform& tr(hw->getTransform());
731 layer.setFrame(tr.transform(frame));
732 layer.setCrop(computeCrop(hw));
Robert Carr6452f122017-03-21 10:41:29 -0700733 layer.setPlaneAlpha(getAlpha());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000734#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800735
Mathias Agopian29a367b2011-07-12 14:51:45 -0700736 /*
737 * Transformations are applied in this order:
738 * 1) buffer orientation/flip/mirror
739 * 2) state transformation (window manager)
740 * 3) layer orientation (screen orientation)
741 * (NOTE: the matrices are multiplied in reverse order)
742 */
743
744 const Transform bufferOrientation(mCurrentTransform);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700745 Transform transform(tr * t * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700746
Robert Carrcae605c2017-03-29 12:10:31 -0700747 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700748 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700749 * the code below applies the primary display's inverse transform to the
750 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700751 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700752 uint32_t invTransform =
753 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700754 // calculate the inverse transform
755 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
756 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
757 NATIVE_WINDOW_TRANSFORM_FLIP_H;
758 }
Robert Carrcae605c2017-03-29 12:10:31 -0700759
760 /*
761 * Here we cancel out the orientation component of the WM transform.
762 * The scaling and translate components are already included in our bounds
763 * computation so it's enough to just omit it in the composition.
764 * See comment in onDraw with ref to b/36727915 for why.
765 */
766 transform = Transform(invTransform) * tr * bufferOrientation;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700767 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700768
769 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800770 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000771#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800772 if (orientation & Transform::ROT_INVALID) {
773 // we can only handle simple transformation
774 hwcInfo.forceClientComposition = true;
775 } else {
776 auto transform = static_cast<HWC2::Transform>(orientation);
777 auto error = hwcLayer->setTransform(transform);
778 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
779 "%s (%d)", mName.string(), to_string(transform).c_str(),
780 to_string(error).c_str(), static_cast<int32_t>(error));
781 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000782#else
783 if (orientation & Transform::ROT_INVALID) {
784 // we can only handle simple transformation
785 layer.setSkip(true);
786 } else {
787 layer.setTransform(orientation);
788 }
789#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700790}
791
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000792#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800793void Layer::forceClientComposition(int32_t hwcId) {
794 if (mHwcLayers.count(hwcId) == 0) {
795 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
796 return;
797 }
798
799 mHwcLayers[hwcId].forceClientComposition = true;
800}
Dan Stoza9e56aa02015-11-02 13:00:03 -0800801
Dan Stoza9e56aa02015-11-02 13:00:03 -0800802void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
803 // Apply this display's projection's viewport to the visible region
804 // before giving it to the HWC HAL.
805 const Transform& tr = displayDevice->getTransform();
806 const auto& viewport = displayDevice->getViewport();
807 Region visible = tr.transform(visibleRegion.intersect(viewport));
808 auto hwcId = displayDevice->getHwcDisplayId();
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800809 auto& hwcInfo = mHwcLayers[hwcId];
810 auto& hwcLayer = hwcInfo.layer;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800811 auto error = hwcLayer->setVisibleRegion(visible);
812 if (error != HWC2::Error::None) {
813 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
814 to_string(error).c_str(), static_cast<int32_t>(error));
815 visible.dump(LOG_TAG);
816 }
817
818 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
819 if (error != HWC2::Error::None) {
820 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
821 to_string(error).c_str(), static_cast<int32_t>(error));
822 surfaceDamageRegion.dump(LOG_TAG);
823 }
824
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700825 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800826 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700827 setCompositionType(hwcId, HWC2::Composition::Sideband);
828 ALOGV("[%s] Requesting Sideband composition", mName.string());
829 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800830 if (error != HWC2::Error::None) {
831 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
832 mName.string(), mSidebandStream->handle(),
833 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800834 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700835 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800836 }
837
Dan Stoza0a21df72016-07-20 12:52:38 -0700838 // Client layers
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800839 if (hwcInfo.forceClientComposition ||
Dan Stoza0a21df72016-07-20 12:52:38 -0700840 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700841 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800842 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700843 return;
844 }
845
Dan Stoza0a21df72016-07-20 12:52:38 -0700846 // SolidColor layers
847 if (mActiveBuffer == nullptr) {
848 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700849
850 // For now, we only support black for DimLayer
Dan Stoza0a21df72016-07-20 12:52:38 -0700851 error = hwcLayer->setColor({0, 0, 0, 255});
852 if (error != HWC2::Error::None) {
853 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
854 to_string(error).c_str(), static_cast<int32_t>(error));
855 }
Dan Stozac6c89542016-07-27 10:16:52 -0700856
857 // Clear out the transform, because it doesn't make sense absent a
858 // source buffer
859 error = hwcLayer->setTransform(HWC2::Transform::None);
860 if (error != HWC2::Error::None) {
861 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
862 to_string(error).c_str(), static_cast<int32_t>(error));
863 }
864
Dan Stoza0a21df72016-07-20 12:52:38 -0700865 return;
866 }
867
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700868 // Device or Cursor layers
869 if (mPotentialCursor) {
870 ALOGV("[%s] Requesting Cursor composition", mName.string());
871 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800872 } else {
873 ALOGV("[%s] Requesting Device composition", mName.string());
874 setCompositionType(hwcId, HWC2::Composition::Device);
875 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700876
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700877 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
878 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
879 if (error != HWC2::Error::None) {
880 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
881 mCurrentState.dataSpace, to_string(error).c_str(),
882 static_cast<int32_t>(error));
883 }
884
Chia-I Wu06d63de2017-01-04 14:58:51 +0800885 uint32_t hwcSlot = 0;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400886 sp<GraphicBuffer> hwcBuffer;
887 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
888 &hwcSlot, &hwcBuffer);
Chia-I Wu06d63de2017-01-04 14:58:51 +0800889
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700890 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400891 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700892 if (error != HWC2::Error::None) {
893 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
894 mActiveBuffer->handle, to_string(error).c_str(),
895 static_cast<int32_t>(error));
896 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800897}
Courtney Goeltzenleuchter9551fd32016-10-20 17:18:15 -0600898
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000899#else
900void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
901 HWComposer::HWCLayerInterface& layer) {
902 // we have to set the visible region on every frame because
903 // we currently free it during onLayerDisplayed(), which is called
904 // after HWComposer::commit() -- every frame.
905 // Apply this display's projection's viewport to the visible region
906 // before giving it to the HWC HAL.
907 const Transform& tr = hw->getTransform();
908 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
909 layer.setVisibleRegionScreen(visible);
910 layer.setSurfaceDamage(surfaceDamageRegion);
911 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700912
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000913 if (mSidebandStream.get()) {
914 layer.setSidebandStream(mSidebandStream);
915 } else {
916 // NOTE: buffer can be NULL if the client never drew into this
917 // layer yet, or if we ran out of memory
918 layer.setBuffer(mActiveBuffer);
919 }
920}
921#endif
922
923#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800924void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
925 auto hwcId = displayDevice->getHwcDisplayId();
926 if (mHwcLayers.count(hwcId) == 0 ||
927 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
928 return;
929 }
930
931 // This gives us only the "orientation" component of the transform
932 const State& s(getCurrentState());
933
934 // Apply the layer's transform, followed by the display's global transform
935 // Here we're guaranteed that the layer's transform preserves rects
936 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700937 if (!s.crop.isEmpty()) {
938 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800939 }
940 // Subtract the transparent region and snap to the bounds
941 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700942 Rect frame(getTransform().transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800943 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -0700944 if (!s.finalCrop.isEmpty()) {
945 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000946 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800947 auto& displayTransform(displayDevice->getTransform());
948 auto position = displayTransform.transform(frame);
949
950 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
951 position.top);
952 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
953 "to (%d, %d): %s (%d)", mName.string(), position.left,
954 position.top, to_string(error).c_str(),
955 static_cast<int32_t>(error));
956}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000957#else
958void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
959 HWComposer::HWCLayerInterface& layer) {
960 int fenceFd = -1;
961
962 // TODO: there is a possible optimization here: we only need to set the
963 // acquire fence the first time a new buffer is acquired on EACH display.
964
965 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
966 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
967 if (fence->isValid()) {
968 fenceFd = fence->dup();
969 if (fenceFd == -1) {
970 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
971 }
972 }
973 }
974 layer.setAcquireFenceFd(fenceFd);
975}
976
977Rect Layer::getPosition(
978 const sp<const DisplayDevice>& hw)
979{
980 // this gives us only the "orientation" component of the transform
981 const State& s(getCurrentState());
982
983 // apply the layer's transform, followed by the display's global transform
984 // here we're guaranteed that the layer's transform preserves rects
985 Rect win(s.active.w, s.active.h);
986 if (!s.crop.isEmpty()) {
987 win.intersect(s.crop, &win);
988 }
989 // subtract the transparent region and snap to the bounds
990 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700991 Rect frame(getTransform().transform(bounds));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000992 frame.intersect(hw->getViewport(), &frame);
993 if (!s.finalCrop.isEmpty()) {
994 frame.intersect(s.finalCrop, &frame);
995 }
996 const Transform& tr(hw->getTransform());
997 return Rect(tr.transform(frame));
998}
999#endif
Riley Andrews03414a12014-07-01 14:22:59 -07001000
Mathias Agopian13127d82013-03-05 17:47:11 -08001001// ---------------------------------------------------------------------------
1002// drawing...
1003// ---------------------------------------------------------------------------
1004
1005void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -08001006 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -08001007}
1008
Dan Stozac7014012014-02-14 15:03:43 -08001009void Layer::draw(const sp<const DisplayDevice>& hw,
1010 bool useIdentityTransform) const {
1011 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001012}
1013
Dan Stozac7014012014-02-14 15:03:43 -08001014void Layer::draw(const sp<const DisplayDevice>& hw) const {
1015 onDraw(hw, Region(hw->bounds()), false);
1016}
1017
Robert Carrcae605c2017-03-29 12:10:31 -07001018static constexpr mat4 inverseOrientation(uint32_t transform) {
1019 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1020 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1021 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1022 mat4 tr;
1023
1024 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1025 tr = tr * rot90;
1026 }
1027 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1028 tr = tr * flipH;
1029 }
1030 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1031 tr = tr * flipV;
1032 }
1033 return inverse(tr);
1034}
1035
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001036/*
1037 * onDraw will draw the current layer onto the presentable buffer
1038 */
Dan Stozac7014012014-02-14 15:03:43 -08001039void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
1040 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001041{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001042 ATRACE_CALL();
1043
Mathias Agopiana67932f2011-04-20 14:20:59 -07001044 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001045 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -07001046 // in fact never been drawn into. This happens frequently with
1047 // SurfaceView because the WindowManager can't know when the client
1048 // has drawn the first time.
1049
1050 // If there is nothing under us, we paint the screen in black, otherwise
1051 // we just skip this update.
1052
1053 // figure out if there is something below us
1054 Region under;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001055 bool finished = false;
Dan Stoza412903f2017-04-27 13:42:17 -07001056 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001057 if (finished || layer == static_cast<Layer const*>(this)) {
1058 finished = true;
1059 return;
1060 }
Mathias Agopian42977342012-08-05 00:40:46 -07001061 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Robert Carr1f0a16a2016-10-24 16:27:39 -07001062 });
Mathias Agopian179169e2010-05-06 20:21:45 -07001063 // if not everything below us is covered, we plug the holes!
1064 Region holes(clip.subtract(under));
1065 if (!holes.isEmpty()) {
Fabien Sanglard17487192016-12-07 13:03:32 -08001066 clearWithOpenGL(hw, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -07001067 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001068 return;
1069 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001070
Andy McFadden97eba892012-12-11 15:21:45 -08001071 // Bind the current buffer to the GL texture, and wait for it to be
1072 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001073 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1074 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -08001075 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -07001076 // Go ahead and draw the buffer anyway; no matter what we do the screen
1077 // is probably going to have something visibly wrong.
1078 }
1079
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001080 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1081
Mathias Agopian875d8e12013-06-07 15:35:48 -07001082 RenderEngine& engine(mFlinger->getRenderEngine());
1083
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001084 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -07001085 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -07001086 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -07001087
1088 // Query the texture matrix given our current filtering mode.
1089 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001090 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1091 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -07001092
Robert Carrcae605c2017-03-29 12:10:31 -07001093 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001094
1095 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -07001096 * the code below applies the primary display's inverse transform to
1097 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001098 */
Pablo Ceballos021623b2016-04-15 17:31:51 -07001099 uint32_t transform =
1100 DisplayDevice::getPrimaryDisplayOrientationTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001101 mat4 tr = inverseOrientation(transform);
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001102
Robert Carrcae605c2017-03-29 12:10:31 -07001103 /**
1104 * TODO(b/36727915): This is basically a hack.
1105 *
1106 * Ensure that regardless of the parent transformation,
1107 * this buffer is always transformed from native display
1108 * orientation to display orientation. For example, in the case
1109 * of a camera where the buffer remains in native orientation,
1110 * we want the pixels to always be upright.
1111 */
Chia-I Wue41dbe62017-06-13 14:10:56 -07001112 sp<Layer> p = mDrawingParent.promote();
1113 if (p != nullptr) {
1114 const auto parentTransform = p->getTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001115 tr = tr * inverseOrientation(parentTransform.getOrientation());
1116 }
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001117
1118 // and finally apply it to the original texture matrix
1119 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1120 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1121 }
1122
Jamie Genniscbb1a952012-05-08 17:05:52 -07001123 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -07001124 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1125 mTexture.setFiltering(useFiltering);
1126 mTexture.setMatrix(textureMatrix);
1127
1128 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -07001129 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001130 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -07001131 }
Fabien Sanglard85789802016-12-07 13:08:24 -08001132 drawWithOpenGL(hw, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001133 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001134}
1135
Mathias Agopian13127d82013-03-05 17:47:11 -08001136
Dan Stozac7014012014-02-14 15:03:43 -08001137void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard17487192016-12-07 13:03:32 -08001138 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -08001139 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001140{
Mathias Agopian19733a32013-08-28 18:13:56 -07001141 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -08001142 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -07001143 engine.setupFillWithColor(red, green, blue, alpha);
1144 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -08001145}
1146
1147void Layer::clearWithOpenGL(
Fabien Sanglard17487192016-12-07 13:03:32 -08001148 const sp<const DisplayDevice>& hw) const {
1149 clearWithOpenGL(hw, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001150}
1151
Dan Stozac7014012014-02-14 15:03:43 -08001152void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard85789802016-12-07 13:08:24 -08001153 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001154 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001155
Dan Stozac7014012014-02-14 15:03:43 -08001156 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001157
Mathias Agopian13127d82013-03-05 17:47:11 -08001158 /*
1159 * NOTE: the way we compute the texture coordinates here produces
1160 * different results than when we take the HWC path -- in the later case
1161 * the "source crop" is rounded to texel boundaries.
1162 * This can produce significantly different results when the texture
1163 * is scaled by a large amount.
1164 *
1165 * The GL code below is more logical (imho), and the difference with
1166 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001167 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001168 * GL composition when a buffer scaling is applied (maybe with some
1169 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1170 * like more of a hack.
1171 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001172 Rect win(computeBounds());
1173
Robert Carr1f0a16a2016-10-24 16:27:39 -07001174 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -07001175 if (!s.finalCrop.isEmpty()) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001176 win = t.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001177 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001178 win.clear();
1179 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001180 win = t.inverse().transform(win);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001181 if (!win.intersect(computeBounds(), &win)) {
1182 win.clear();
1183 }
1184 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001185
Mathias Agopian3f844832013-08-07 21:24:32 -07001186 float left = float(win.left) / float(s.active.w);
1187 float top = float(win.top) / float(s.active.h);
1188 float right = float(win.right) / float(s.active.w);
1189 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001190
Mathias Agopian875d8e12013-06-07 15:35:48 -07001191 // TODO: we probably want to generate the texture coords with the mesh
1192 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001193 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1194 texCoords[0] = vec2(left, 1.0f - top);
1195 texCoords[1] = vec2(left, 1.0f - bottom);
1196 texCoords[2] = vec2(right, 1.0f - bottom);
1197 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001198
Mathias Agopian875d8e12013-06-07 15:35:48 -07001199 RenderEngine& engine(mFlinger->getRenderEngine());
Robert Carr6452f122017-03-21 10:41:29 -07001200 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), getAlpha());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001201#ifdef USE_HWC2
1202 engine.setSourceDataSpace(mCurrentState.dataSpace);
1203#endif
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001204 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001205 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001206}
1207
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001208#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001209void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1210 bool callIntoHwc) {
1211 if (mHwcLayers.count(hwcId) == 0) {
1212 ALOGE("setCompositionType called without a valid HWC layer");
1213 return;
1214 }
1215 auto& hwcInfo = mHwcLayers[hwcId];
1216 auto& hwcLayer = hwcInfo.layer;
1217 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1218 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1219 if (hwcInfo.compositionType != type) {
1220 ALOGV(" actually setting");
1221 hwcInfo.compositionType = type;
1222 if (callIntoHwc) {
1223 auto error = hwcLayer->setCompositionType(type);
1224 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1225 "composition type %s: %s (%d)", mName.string(),
1226 to_string(type).c_str(), to_string(error).c_str(),
1227 static_cast<int32_t>(error));
1228 }
1229 }
1230}
1231
1232HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001233 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1234 // If we're querying the composition type for a display that does not
1235 // have a HWC counterpart, then it will always be Client
1236 return HWC2::Composition::Client;
1237 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001238 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001239 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001240 return HWC2::Composition::Invalid;
1241 }
1242 return mHwcLayers.at(hwcId).compositionType;
1243}
1244
1245void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1246 if (mHwcLayers.count(hwcId) == 0) {
1247 ALOGE("setClearClientTarget called without a valid HWC layer");
1248 return;
1249 }
1250 mHwcLayers[hwcId].clearClientTarget = clear;
1251}
1252
1253bool Layer::getClearClientTarget(int32_t hwcId) const {
1254 if (mHwcLayers.count(hwcId) == 0) {
1255 ALOGE("getClearClientTarget called without a valid HWC layer");
1256 return false;
1257 }
1258 return mHwcLayers.at(hwcId).clearClientTarget;
1259}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001260#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001261
Ruben Brunk1681d952014-06-27 15:51:55 -07001262uint32_t Layer::getProducerStickyTransform() const {
1263 int producerStickyTransform = 0;
1264 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1265 if (ret != OK) {
1266 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1267 strerror(-ret), ret);
1268 return 0;
1269 }
1270 return static_cast<uint32_t>(producerStickyTransform);
1271}
1272
Dan Stozac5da2712016-07-20 15:38:12 -07001273bool Layer::latchUnsignaledBuffers() {
1274 static bool propertyLoaded = false;
1275 static bool latch = false;
1276 static std::mutex mutex;
1277 std::lock_guard<std::mutex> lock(mutex);
1278 if (!propertyLoaded) {
1279 char value[PROPERTY_VALUE_MAX] = {};
1280 property_get("debug.sf.latch_unsignaled", value, "0");
1281 latch = atoi(value);
1282 propertyLoaded = true;
1283 }
1284 return latch;
1285}
1286
Dan Stozacac35382016-01-27 12:21:06 -08001287uint64_t Layer::getHeadFrameNumber() const {
1288 Mutex::Autolock lock(mQueueItemLock);
1289 if (!mQueueItems.empty()) {
1290 return mQueueItems[0].mFrameNumber;
1291 } else {
1292 return mCurrentFrameNumber;
1293 }
1294}
1295
Dan Stoza1ce65812016-06-15 16:26:27 -07001296bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001297#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001298 if (latchUnsignaledBuffers()) {
1299 return true;
1300 }
1301
Dan Stoza1ce65812016-06-15 16:26:27 -07001302 Mutex::Autolock lock(mQueueItemLock);
1303 if (mQueueItems.empty()) {
1304 return true;
1305 }
1306 if (mQueueItems[0].mIsDroppable) {
1307 // Even though this buffer's fence may not have signaled yet, it could
1308 // be replaced by another buffer before it has a chance to, which means
1309 // that it's possible to get into a situation where a buffer is never
1310 // able to be latched. To avoid this, grab this buffer anyway.
1311 return true;
1312 }
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001313 return mQueueItems[0].mFenceTime->getSignalTime() !=
1314 Fence::SIGNAL_TIME_PENDING;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001315#else
1316 return true;
1317#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001318}
1319
Dan Stozacac35382016-01-27 12:21:06 -08001320bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1321 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1322 // Don't bother with a SyncPoint, since we've already latched the
1323 // relevant frame
1324 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001325 }
1326
Dan Stozacac35382016-01-27 12:21:06 -08001327 Mutex::Autolock lock(mLocalSyncPointMutex);
1328 mLocalSyncPoints.push_back(point);
1329 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001330}
1331
Mathias Agopian13127d82013-03-05 17:47:11 -08001332void Layer::setFiltering(bool filtering) {
1333 mFiltering = filtering;
1334}
1335
1336bool Layer::getFiltering() const {
1337 return mFiltering;
1338}
1339
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001340// As documented in libhardware header, formats in the range
1341// 0x100 - 0x1FF are specific to the HAL implementation, and
1342// are known to have no alpha channel
1343// TODO: move definition for device-specific range into
1344// hardware.h, instead of using hard-coded values here.
1345#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1346
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001347bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001348 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1349 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001350 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001351 switch (format) {
1352 case HAL_PIXEL_FORMAT_RGBA_8888:
1353 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001354 case HAL_PIXEL_FORMAT_RGBA_FP16:
Romain Guy541f2262017-02-10 18:50:17 -08001355 case HAL_PIXEL_FORMAT_RGBA_1010102:
Mathias Agopiandd533712013-07-26 15:31:39 -07001356 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001357 }
1358 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001359 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001360}
1361
Mathias Agopian13127d82013-03-05 17:47:11 -08001362// ----------------------------------------------------------------------------
1363// local state
1364// ----------------------------------------------------------------------------
1365
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001366static void boundPoint(vec2* point, const Rect& crop) {
1367 if (point->x < crop.left) {
1368 point->x = crop.left;
1369 }
1370 if (point->x > crop.right) {
1371 point->x = crop.right;
1372 }
1373 if (point->y < crop.top) {
1374 point->y = crop.top;
1375 }
1376 if (point->y > crop.bottom) {
1377 point->y = crop.bottom;
1378 }
1379}
1380
Dan Stozac7014012014-02-14 15:03:43 -08001381void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1382 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001383{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001384 const Layer::State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001385 const Transform hwTransform(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001386 const uint32_t hw_h = hw->getHeight();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001387 Rect win = computeBounds();
Mathias Agopian3f844832013-08-07 21:24:32 -07001388
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001389 vec2 lt = vec2(win.left, win.top);
1390 vec2 lb = vec2(win.left, win.bottom);
1391 vec2 rb = vec2(win.right, win.bottom);
1392 vec2 rt = vec2(win.right, win.top);
1393
Robert Carr1f0a16a2016-10-24 16:27:39 -07001394 Transform layerTransform = getTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001395 if (!useIdentityTransform) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001396 lt = layerTransform.transform(lt);
1397 lb = layerTransform.transform(lb);
1398 rb = layerTransform.transform(rb);
1399 rt = layerTransform.transform(rt);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001400 }
1401
Robert Carrb5d3d262016-03-25 15:08:13 -07001402 if (!s.finalCrop.isEmpty()) {
1403 boundPoint(&lt, s.finalCrop);
1404 boundPoint(&lb, s.finalCrop);
1405 boundPoint(&rb, s.finalCrop);
1406 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001407 }
1408
Mathias Agopianff2ed702013-09-01 21:36:12 -07001409 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001410 position[0] = hwTransform.transform(lt);
1411 position[1] = hwTransform.transform(lb);
1412 position[2] = hwTransform.transform(rb);
1413 position[3] = hwTransform.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001414 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001415 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001416 }
1417}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001418
Andy McFadden4125a4f2014-01-29 17:17:11 -08001419bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001420{
neo.hee6fd41d2017-02-17 14:35:33 +08001421 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
Mathias Agopiana67932f2011-04-20 14:20:59 -07001422 // layer's opaque flag.
neo.hee6fd41d2017-02-17 14:35:33 +08001423 if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001424 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001425 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001426
1427 // if the layer has the opaque flag, then we're always opaque,
1428 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001429 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001430}
1431
Dan Stoza23116082015-06-18 14:58:39 -07001432bool Layer::isSecure() const
1433{
1434 const Layer::State& s(mDrawingState);
1435 return (s.flags & layer_state_t::eLayerSecure);
1436}
1437
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001438bool Layer::isProtected() const
1439{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001440 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001441 return (activeBuffer != 0) &&
1442 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1443}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001444
Mathias Agopian13127d82013-03-05 17:47:11 -08001445bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001446 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001447}
1448
1449bool Layer::isCropped() const {
1450 return !mCurrentCrop.isEmpty();
1451}
1452
1453bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1454 return mNeedsFiltering || hw->needsFiltering();
1455}
1456
1457void Layer::setVisibleRegion(const Region& visibleRegion) {
1458 // always called from main thread
1459 this->visibleRegion = visibleRegion;
1460}
1461
1462void Layer::setCoveredRegion(const Region& coveredRegion) {
1463 // always called from main thread
1464 this->coveredRegion = coveredRegion;
1465}
1466
1467void Layer::setVisibleNonTransparentRegion(const Region&
1468 setVisibleNonTransparentRegion) {
1469 // always called from main thread
1470 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1471}
1472
1473// ----------------------------------------------------------------------------
1474// transaction
1475// ----------------------------------------------------------------------------
1476
Dan Stoza7dde5992015-05-22 09:51:44 -07001477void Layer::pushPendingState() {
1478 if (!mCurrentState.modified) {
1479 return;
1480 }
1481
Dan Stoza7dde5992015-05-22 09:51:44 -07001482 // If this transaction is waiting on the receipt of a frame, generate a sync
1483 // point and send it to the remote layer.
Robert Carr0d480722017-01-10 16:42:54 -08001484 if (mCurrentState.barrierLayer != nullptr) {
1485 sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1486 if (barrierLayer == nullptr) {
1487 ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
Dan Stoza7dde5992015-05-22 09:51:44 -07001488 // If we can't promote the layer we are intended to wait on,
1489 // then it is expired or otherwise invalid. Allow this transaction
1490 // to be applied as per normal (no synchronization).
Robert Carr0d480722017-01-10 16:42:54 -08001491 mCurrentState.barrierLayer = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001492 } else {
1493 auto syncPoint = std::make_shared<SyncPoint>(
1494 mCurrentState.frameNumber);
Robert Carr0d480722017-01-10 16:42:54 -08001495 if (barrierLayer->addSyncPoint(syncPoint)) {
Dan Stozacac35382016-01-27 12:21:06 -08001496 mRemoteSyncPoints.push_back(std::move(syncPoint));
1497 } else {
1498 // We already missed the frame we're supposed to synchronize
1499 // on, so go ahead and apply the state update
Robert Carr0d480722017-01-10 16:42:54 -08001500 mCurrentState.barrierLayer = nullptr;
Dan Stozacac35382016-01-27 12:21:06 -08001501 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001502 }
1503
Dan Stoza7dde5992015-05-22 09:51:44 -07001504 // Wake us up to check if the frame has been received
1505 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001506 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001507 }
1508 mPendingStates.push_back(mCurrentState);
Dan Stozaf7ba41a2017-05-10 15:11:11 -07001509 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
Dan Stoza7dde5992015-05-22 09:51:44 -07001510}
1511
Pablo Ceballos05289c22016-04-14 15:49:55 -07001512void Layer::popPendingState(State* stateToCommit) {
1513 auto oldFlags = stateToCommit->flags;
1514 *stateToCommit = mPendingStates[0];
1515 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1516 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001517
1518 mPendingStates.removeAt(0);
Dan Stozaf7ba41a2017-05-10 15:11:11 -07001519 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
Dan Stoza7dde5992015-05-22 09:51:44 -07001520}
1521
Pablo Ceballos05289c22016-04-14 15:49:55 -07001522bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001523 bool stateUpdateAvailable = false;
1524 while (!mPendingStates.empty()) {
Robert Carr0d480722017-01-10 16:42:54 -08001525 if (mPendingStates[0].barrierLayer != nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001526 if (mRemoteSyncPoints.empty()) {
1527 // If we don't have a sync point for this, apply it anyway. It
1528 // will be visually wrong, but it should keep us from getting
1529 // into too much trouble.
1530 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001531 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001532 stateUpdateAvailable = true;
1533 continue;
1534 }
1535
Dan Stozacac35382016-01-27 12:21:06 -08001536 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1537 mPendingStates[0].frameNumber) {
1538 ALOGE("[%s] Unexpected sync point frame number found",
1539 mName.string());
1540
1541 // Signal our end of the sync point and then dispose of it
1542 mRemoteSyncPoints.front()->setTransactionApplied();
1543 mRemoteSyncPoints.pop_front();
1544 continue;
1545 }
1546
Dan Stoza7dde5992015-05-22 09:51:44 -07001547 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1548 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001549 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001550 stateUpdateAvailable = true;
1551
1552 // Signal our end of the sync point and then dispose of it
1553 mRemoteSyncPoints.front()->setTransactionApplied();
1554 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001555 } else {
1556 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001557 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001558 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001559 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001560 stateUpdateAvailable = true;
1561 }
1562 }
1563
1564 // If we still have pending updates, wake SurfaceFlinger back up and point
1565 // it at this layer so we can process them
1566 if (!mPendingStates.empty()) {
1567 setTransactionFlags(eTransactionNeeded);
1568 mFlinger->setTransactionFlags(eTraversalNeeded);
1569 }
1570
1571 mCurrentState.modified = false;
1572 return stateUpdateAvailable;
1573}
1574
1575void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001576 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001577 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001578 Mutex::Autolock lock(mLocalSyncPointMutex);
1579 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001580 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001581 point->setFrameAvailable();
1582 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001583 }
1584}
1585
Mathias Agopian13127d82013-03-05 17:47:11 -08001586uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001587 ATRACE_CALL();
1588
Dan Stoza7dde5992015-05-22 09:51:44 -07001589 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001590 Layer::State c = getCurrentState();
1591 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001592 return 0;
1593 }
1594
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001595 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001596
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001597 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1598 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001599
1600 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001601 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001602 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001603 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001604 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001605 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001606 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001607 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001608 this, getName().string(), mCurrentTransform,
1609 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001610 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001611 c.crop.left,
1612 c.crop.top,
1613 c.crop.right,
1614 c.crop.bottom,
1615 c.crop.getWidth(),
1616 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001617 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001618 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001619 s.crop.left,
1620 s.crop.top,
1621 s.crop.right,
1622 s.crop.bottom,
1623 s.crop.getWidth(),
1624 s.crop.getHeight(),
1625 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001626
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001627 // record the new size, form this point on, when the client request
1628 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001629 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001630 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001631 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001632
Robert Carr82364e32016-05-15 11:27:47 -07001633 const bool resizePending = (c.requested.w != c.active.w) ||
1634 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001635 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001636 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001637 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001638 // if we have a pending resize, unless we are in fixed-size mode.
1639 // the drawing state will be updated only once we receive a buffer
1640 // with the correct size.
1641 //
1642 // in particular, we want to make sure the clip (which is part
1643 // of the geometry state) is latched together with the size but is
1644 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001645 //
1646 // If a sideband stream is attached, however, we want to skip this
1647 // optimization so that transactions aren't missed when a buffer
1648 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001649
1650 flags |= eDontUpdateGeometryState;
1651 }
1652 }
1653
Robert Carr7bf247e2017-05-18 14:02:49 -07001654 // Here we apply various requested geometry states, depending on our
1655 // latching configuration. See Layer.h for a detailed discussion of
1656 // how geometry latching is controlled.
1657 if (!(flags & eDontUpdateGeometryState)) {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001658 Layer::State& editCurrentState(getCurrentState());
Robert Carr7bf247e2017-05-18 14:02:49 -07001659
1660 // If mFreezeGeometryUpdates is true we are in the setGeometryAppliesWithResize
1661 // mode, which causes attributes which normally latch regardless of scaling mode,
1662 // to be delayed. We copy the requested state to the active state making sure
1663 // to respect these rules (again see Layer.h for a detailed discussion).
1664 //
1665 // There is an awkward asymmetry in the handling of the crop states in the position
1666 // states, as can be seen below. Largely this arises from position and transform
1667 // being stored in the same data structure while having different latching rules.
1668 // b/38182305
1669 //
1670 // Careful that "c" and editCurrentState may not begin as equivalent due to
1671 // applyPendingStates in the presence of deferred transactions.
1672 if (mFreezeGeometryUpdates) {
Robert Carr82364e32016-05-15 11:27:47 -07001673 float tx = c.active.transform.tx();
1674 float ty = c.active.transform.ty();
1675 c.active = c.requested;
1676 c.active.transform.set(tx, ty);
1677 editCurrentState.active = c.active;
1678 } else {
1679 editCurrentState.active = editCurrentState.requested;
1680 c.active = c.requested;
1681 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001682 }
1683
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001684 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001685 // invalidate and recompute the visible regions if needed
1686 flags |= Layer::eVisibleRegion;
1687 }
1688
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001689 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001690 // invalidate and recompute the visible regions if needed
1691 flags |= eVisibleRegion;
1692 this->contentDirty = true;
1693
1694 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001695 const uint8_t type = c.active.transform.getType();
1696 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001697 (type >= Transform::SCALE));
1698 }
1699
Dan Stozac8145172016-04-28 16:29:06 -07001700 // If the layer is hidden, signal and clear out all local sync points so
1701 // that transactions for layers depending on this layer's frames becoming
1702 // visible are not blocked
1703 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001704 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001705 }
1706
Mathias Agopian13127d82013-03-05 17:47:11 -08001707 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001708 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001709 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001710}
1711
Pablo Ceballos05289c22016-04-14 15:49:55 -07001712void Layer::commitTransaction(const State& stateToCommit) {
1713 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001714}
1715
Mathias Agopian13127d82013-03-05 17:47:11 -08001716uint32_t Layer::getTransactionFlags(uint32_t flags) {
1717 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1718}
1719
1720uint32_t Layer::setTransactionFlags(uint32_t flags) {
1721 return android_atomic_or(flags, &mTransactionFlags);
1722}
1723
Robert Carr82364e32016-05-15 11:27:47 -07001724bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001725 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001726 return false;
1727 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001728
1729 // We update the requested and active position simultaneously because
1730 // we want to apply the position portion of the transform matrix immediately,
1731 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001732 mCurrentState.requested.transform.set(x, y);
Robert Carr7bf247e2017-05-18 14:02:49 -07001733 if (immediate && !mFreezeGeometryUpdates) {
1734 // Here we directly update the active state
1735 // unlike other setters, because we store it within
1736 // the transform, but use different latching rules.
1737 // b/38182305
Robert Carr82364e32016-05-15 11:27:47 -07001738 mCurrentState.active.transform.set(x, y);
1739 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001740 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001741
Dan Stoza7dde5992015-05-22 09:51:44 -07001742 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001743 setTransactionFlags(eTransactionNeeded);
1744 return true;
1745}
Robert Carr82364e32016-05-15 11:27:47 -07001746
Robert Carr1f0a16a2016-10-24 16:27:39 -07001747bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1748 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1749 if (idx < 0) {
1750 return false;
1751 }
1752 if (childLayer->setLayer(z)) {
1753 mCurrentChildren.removeAt(idx);
1754 mCurrentChildren.add(childLayer);
1755 }
1756 return true;
1757}
1758
Robert Carrae060832016-11-28 10:51:00 -08001759bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001760 if (mCurrentState.z == z)
1761 return false;
1762 mCurrentState.sequence++;
1763 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001764 mCurrentState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001765
1766 // Discard all relative layering.
1767 if (mCurrentState.zOrderRelativeOf != nullptr) {
1768 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1769 if (strongRelative != nullptr) {
1770 strongRelative->removeZOrderRelative(this);
1771 }
1772 mCurrentState.zOrderRelativeOf = nullptr;
1773 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001774 setTransactionFlags(eTransactionNeeded);
1775 return true;
1776}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001777
Robert Carrdb66e622017-04-10 16:55:57 -07001778void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1779 mCurrentState.zOrderRelatives.remove(relative);
1780 mCurrentState.sequence++;
1781 mCurrentState.modified = true;
1782 setTransactionFlags(eTransactionNeeded);
1783}
1784
1785void Layer::addZOrderRelative(const wp<Layer>& relative) {
1786 mCurrentState.zOrderRelatives.add(relative);
1787 mCurrentState.modified = true;
1788 mCurrentState.sequence++;
1789 setTransactionFlags(eTransactionNeeded);
1790}
1791
1792bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1793 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1794 if (handle == nullptr) {
1795 return false;
1796 }
1797 sp<Layer> relative = handle->owner.promote();
1798 if (relative == nullptr) {
1799 return false;
1800 }
1801
1802 mCurrentState.sequence++;
1803 mCurrentState.modified = true;
1804 mCurrentState.z = z;
1805
1806 mCurrentState.zOrderRelativeOf = relative;
1807 relative->addZOrderRelative(this);
1808
1809 setTransactionFlags(eTransactionNeeded);
1810
1811 return true;
1812}
1813
Mathias Agopian13127d82013-03-05 17:47:11 -08001814bool Layer::setSize(uint32_t w, uint32_t h) {
1815 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1816 return false;
1817 mCurrentState.requested.w = w;
1818 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001819 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001820 setTransactionFlags(eTransactionNeeded);
1821 return true;
1822}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001823#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001824bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001825#else
1826bool Layer::setAlpha(uint8_t alpha) {
1827#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001828 if (mCurrentState.alpha == alpha)
1829 return false;
1830 mCurrentState.sequence++;
1831 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001832 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001833 setTransactionFlags(eTransactionNeeded);
1834 return true;
1835}
1836bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1837 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001838 mCurrentState.requested.transform.set(
Robert Carrcb6e1e32017-02-21 19:48:26 -08001839 matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001840 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001841 setTransactionFlags(eTransactionNeeded);
1842 return true;
1843}
1844bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001845 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001846 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001847 setTransactionFlags(eTransactionNeeded);
1848 return true;
1849}
1850bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1851 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1852 if (mCurrentState.flags == newFlags)
1853 return false;
1854 mCurrentState.sequence++;
1855 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001856 mCurrentState.mask = mask;
1857 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001858 setTransactionFlags(eTransactionNeeded);
1859 return true;
1860}
Robert Carr99e27f02016-06-16 15:18:02 -07001861
1862bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001863 if (mCurrentState.requestedCrop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001864 return false;
1865 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001866 mCurrentState.requestedCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001867 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr99e27f02016-06-16 15:18:02 -07001868 mCurrentState.crop = crop;
1869 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001870 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1871
Dan Stoza7dde5992015-05-22 09:51:44 -07001872 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001873 setTransactionFlags(eTransactionNeeded);
1874 return true;
1875}
Robert Carr8d5227b2017-03-16 15:41:03 -07001876
1877bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001878 if (mCurrentState.requestedFinalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001879 return false;
1880 mCurrentState.sequence++;
Robert Carr8d5227b2017-03-16 15:41:03 -07001881 mCurrentState.requestedFinalCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001882 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr8d5227b2017-03-16 15:41:03 -07001883 mCurrentState.finalCrop = crop;
1884 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001885 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1886
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001887 mCurrentState.modified = true;
1888 setTransactionFlags(eTransactionNeeded);
1889 return true;
1890}
Mathias Agopian13127d82013-03-05 17:47:11 -08001891
Robert Carrc3574f72016-03-24 12:19:32 -07001892bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1893 if (scalingMode == mOverrideScalingMode)
1894 return false;
1895 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001896 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001897 return true;
1898}
1899
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001900void Layer::setInfo(uint32_t type, uint32_t appId) {
1901 mCurrentState.appId = appId;
1902 mCurrentState.type = type;
1903 mCurrentState.modified = true;
1904 setTransactionFlags(eTransactionNeeded);
1905}
1906
Robert Carrc3574f72016-03-24 12:19:32 -07001907uint32_t Layer::getEffectiveScalingMode() const {
1908 if (mOverrideScalingMode >= 0) {
1909 return mOverrideScalingMode;
1910 }
1911 return mCurrentScalingMode;
1912}
1913
Mathias Agopian13127d82013-03-05 17:47:11 -08001914bool Layer::setLayerStack(uint32_t layerStack) {
1915 if (mCurrentState.layerStack == layerStack)
1916 return false;
1917 mCurrentState.sequence++;
1918 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001919 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001920 setTransactionFlags(eTransactionNeeded);
1921 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001922}
1923
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07001924bool Layer::setDataSpace(android_dataspace dataSpace) {
1925 if (mCurrentState.dataSpace == dataSpace)
1926 return false;
1927 mCurrentState.sequence++;
1928 mCurrentState.dataSpace = dataSpace;
1929 mCurrentState.modified = true;
1930 setTransactionFlags(eTransactionNeeded);
1931 return true;
1932}
1933
Courtney Goeltzenleuchter532b2632017-05-05 16:34:38 -06001934android_dataspace Layer::getDataSpace() const {
1935 return mCurrentState.dataSpace;
1936}
1937
Robert Carr1f0a16a2016-10-24 16:27:39 -07001938uint32_t Layer::getLayerStack() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07001939 auto p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001940 if (p == nullptr) {
1941 return getDrawingState().layerStack;
1942 }
1943 return p->getLayerStack();
1944}
1945
Robert Carr0d480722017-01-10 16:42:54 -08001946void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
Dan Stoza7dde5992015-05-22 09:51:44 -07001947 uint64_t frameNumber) {
Robert Carr0d480722017-01-10 16:42:54 -08001948 mCurrentState.barrierLayer = barrierLayer;
Dan Stoza7dde5992015-05-22 09:51:44 -07001949 mCurrentState.frameNumber = frameNumber;
1950 // We don't set eTransactionNeeded, because just receiving a deferral
1951 // request without any other state updates shouldn't actually induce a delay
1952 mCurrentState.modified = true;
1953 pushPendingState();
Robert Carr0d480722017-01-10 16:42:54 -08001954 mCurrentState.barrierLayer = nullptr;
Dan Stoza792e5292016-02-11 11:43:58 -08001955 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07001956 mCurrentState.modified = false;
Robert Carr0d480722017-01-10 16:42:54 -08001957}
1958
1959void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
1960 uint64_t frameNumber) {
1961 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
1962 deferTransactionUntil(handle->owner.promote(), frameNumber);
Dan Stoza7dde5992015-05-22 09:51:44 -07001963}
1964
Dan Stozaee44edd2015-03-23 15:50:23 -07001965void Layer::useSurfaceDamage() {
1966 if (mFlinger->mForceFullDamage) {
1967 surfaceDamageRegion = Region::INVALID_REGION;
1968 } else {
1969 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1970 }
1971}
1972
1973void Layer::useEmptyDamage() {
1974 surfaceDamageRegion.clear();
1975}
1976
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001977// ----------------------------------------------------------------------------
1978// pageflip handling...
1979// ----------------------------------------------------------------------------
1980
Dan Stoza6b9454d2014-11-07 16:00:59 -08001981bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001982 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07001983 return true;
1984 }
1985
Dan Stoza6b9454d2014-11-07 16:00:59 -08001986 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001987 if (mQueueItems.empty()) {
1988 return false;
1989 }
1990 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001991 nsecs_t expectedPresent =
1992 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001993
1994 // Ignore timestamps more than a second in the future
1995 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1996 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1997 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1998 expectedPresent);
1999
2000 bool isDue = timestamp < expectedPresent;
2001 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002002}
2003
Brian Andersond6927fb2016-07-23 23:37:30 -07002004bool Layer::onPreComposition(nsecs_t refreshStartTime) {
2005 if (mBufferLatched) {
2006 Mutex::Autolock lock(mFrameEventHistoryMutex);
2007 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
2008 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08002009 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08002010 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002011}
2012
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002013bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
Brian Anderson3d4039d2016-09-23 16:31:30 -07002014 const std::shared_ptr<FenceTime>& presentFence,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002015 const CompositorTiming& compositorTiming) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002016 // mFrameLatencyNeeded is true when a new frame was latched for the
2017 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08002018 if (!mFrameLatencyNeeded)
2019 return false;
2020
Fabien Sanglard28e98082016-12-05 10:19:46 -08002021 // Update mFrameEventHistory.
2022 {
2023 Mutex::Autolock lock(mFrameEventHistoryMutex);
2024 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002025 glDoneFence, presentFence, compositorTiming);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002026 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08002027
2028 // Update mFrameTracker.
2029 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
2030 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
2031
Brian Anderson3d4039d2016-09-23 16:31:30 -07002032 std::shared_ptr<FenceTime> frameReadyFence =
2033 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08002034 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002035 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002036 } else {
2037 // There was no fence for this frame, so assume that it was ready
2038 // to be presented at the desired present time.
2039 mFrameTracker.setFrameReadyTime(desiredPresentTime);
2040 }
2041
Brian Anderson3d4039d2016-09-23 16:31:30 -07002042 if (presentFence->isValid()) {
2043 mFrameTracker.setActualPresentFence(
2044 std::shared_ptr<FenceTime>(presentFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002045 } else {
2046 // The HWC doesn't support present fences, so use the refresh
2047 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002048 mFrameTracker.setActualPresentTime(
2049 mFlinger->getHwComposer().getRefreshTimestamp(
2050 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002051 }
2052
2053 mFrameTracker.advanceFrame();
2054 mFrameLatencyNeeded = false;
2055 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002056}
2057
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002058#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07002059void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Brian Anderson5ea5e592016-12-01 16:54:33 -08002060 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2061 return;
2062 }
2063
Brian Anderson3d4039d2016-09-23 16:31:30 -07002064 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002065 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002066 mReleaseTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002067 mReleaseTimeline.push(releaseFenceTime);
2068
2069 Mutex::Autolock lock(mFrameEventHistoryMutex);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002070 if (mPreviousFrameNumber != 0) {
2071 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2072 dequeueReadyTime, std::move(releaseFenceTime));
2073 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002074}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002075#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002076
Robert Carr1f0a16a2016-10-24 16:27:39 -07002077bool Layer::isHiddenByPolicy() const {
2078 const Layer::State& s(mDrawingState);
Chia-I Wue41dbe62017-06-13 14:10:56 -07002079 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002080 if (parent != nullptr && parent->isHiddenByPolicy()) {
2081 return true;
2082 }
2083 return s.flags & layer_state_t::eLayerHidden;
2084}
2085
Mathias Agopianda27af92012-09-13 18:17:13 -07002086bool Layer::isVisible() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002087#ifdef USE_HWC2
Robert Carr6452f122017-03-21 10:41:29 -07002088 return !(isHiddenByPolicy()) && getAlpha() > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08002089 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002090#else
Robert Carr6452f122017-03-21 10:41:29 -07002091 return !(isHiddenByPolicy()) && getAlpha()
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002092 && (mActiveBuffer != NULL || mSidebandStream != NULL);
2093#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07002094}
2095
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002096bool Layer::allTransactionsSignaled() {
2097 auto headFrameNumber = getHeadFrameNumber();
2098 bool matchingFramesFound = false;
2099 bool allTransactionsApplied = true;
2100 Mutex::Autolock lock(mLocalSyncPointMutex);
2101
2102 for (auto& point : mLocalSyncPoints) {
2103 if (point->getFrameNumber() > headFrameNumber) {
2104 break;
2105 }
2106 matchingFramesFound = true;
2107
2108 if (!point->frameIsAvailable()) {
2109 // We haven't notified the remote layer that the frame for
2110 // this point is available yet. Notify it now, and then
2111 // abort this attempt to latch.
2112 point->setFrameAvailable();
2113 allTransactionsApplied = false;
2114 break;
2115 }
2116
2117 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2118 }
2119 return !matchingFramesFound || allTransactionsApplied;
2120}
2121
Brian Andersond6927fb2016-07-23 23:37:30 -07002122Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002123{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08002124 ATRACE_CALL();
2125
Jesse Hall399184a2014-03-03 15:42:54 -08002126 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2127 // mSidebandStreamChanged was true
2128 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07002129 if (mSidebandStream != NULL) {
2130 setTransactionFlags(eTransactionNeeded);
2131 mFlinger->setTransactionFlags(eTraversalNeeded);
2132 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07002133 recomputeVisibleRegions = true;
2134
2135 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07002136 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08002137 }
2138
Mathias Agopian4fec8732012-06-29 14:12:52 -07002139 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07002140 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2141 return outDirtyRegion;
2142 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002143
Fabien Sanglard223eb912016-10-13 10:15:06 -07002144 // if we've already called updateTexImage() without going through
2145 // a composition step, we have to skip this layer at this point
2146 // because we cannot call updateTeximage() without a corresponding
2147 // compositionComplete() call.
2148 // we'll trigger an update in onPreComposition().
2149 if (mRefreshPending) {
2150 return outDirtyRegion;
2151 }
2152
2153 // If the head buffer's acquire fence hasn't signaled yet, return and
2154 // try again later
2155 if (!headFenceHasSignaled()) {
2156 mFlinger->signalLayerUpdate();
2157 return outDirtyRegion;
2158 }
2159
2160 // Capture the old state of the layer for comparisons later
2161 const State& s(getDrawingState());
2162 const bool oldOpacity = isOpaque(s);
2163 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2164
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002165 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002166 mFlinger->signalLayerUpdate();
2167 return outDirtyRegion;
2168 }
2169
2170 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2171 // of the buffer queue isn't modified when the buffer queue is returning
2172 // BufferItem's that weren't actually queued. This can happen in shared
2173 // buffer mode.
2174 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002175 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2176 getProducerStickyTransform() != 0, mName.string(),
Robert Carr7bf247e2017-05-18 14:02:49 -07002177 mOverrideScalingMode, mFreezeGeometryUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002178 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2179 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2180 mLastFrameNumberReceived);
2181 if (updateResult == BufferQueue::PRESENT_LATER) {
2182 // Producer doesn't want buffer to be displayed yet. Signal a
2183 // layer update so we check again at the next opportunity.
2184 mFlinger->signalLayerUpdate();
2185 return outDirtyRegion;
2186 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2187 // If the buffer has been rejected, remove it from the shadow queue
2188 // and return early
2189 if (queuedBuffer) {
2190 Mutex::Autolock lock(mQueueItemLock);
2191 mQueueItems.removeAt(0);
2192 android_atomic_dec(&mQueuedFrames);
2193 }
2194 return outDirtyRegion;
2195 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2196 // This can occur if something goes wrong when trying to create the
2197 // EGLImage for this buffer. If this happens, the buffer has already
2198 // been released, so we need to clean up the queue and bug out
2199 // early.
2200 if (queuedBuffer) {
2201 Mutex::Autolock lock(mQueueItemLock);
2202 mQueueItems.clear();
2203 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002204 }
2205
Fabien Sanglard223eb912016-10-13 10:15:06 -07002206 // Once we have hit this state, the shadow queue may no longer
2207 // correctly reflect the incoming BufferQueue's contents, so even if
2208 // updateTexImage starts working, the only safe course of action is
2209 // to continue to ignore updates.
2210 mUpdateTexImageFailed = true;
2211
2212 return outDirtyRegion;
2213 }
2214
2215 if (queuedBuffer) {
2216 // Autolock scope
2217 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2218
2219 Mutex::Autolock lock(mQueueItemLock);
2220
2221 // Remove any stale buffers that have been dropped during
2222 // updateTexImage
2223 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2224 mQueueItems.removeAt(0);
2225 android_atomic_dec(&mQueuedFrames);
2226 }
2227
2228 mQueueItems.removeAt(0);
2229 }
2230
2231
2232 // Decrement the queued-frames count. Signal another event if we
2233 // have more frames pending.
2234 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2235 || mAutoRefresh) {
2236 mFlinger->signalLayerUpdate();
2237 }
2238
Fabien Sanglard223eb912016-10-13 10:15:06 -07002239 // update the active buffer
Chia-I Wu06d63de2017-01-04 14:58:51 +08002240 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2241 &mActiveBufferSlot);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002242 if (mActiveBuffer == NULL) {
2243 // this can only happen if the very first buffer was rejected.
2244 return outDirtyRegion;
2245 }
2246
Brian Andersond6927fb2016-07-23 23:37:30 -07002247 mBufferLatched = true;
2248 mPreviousFrameNumber = mCurrentFrameNumber;
2249 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2250
2251 {
2252 Mutex::Autolock lock(mFrameEventHistoryMutex);
2253 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2254#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002255 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002256 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002257 mReleaseTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002258 mReleaseTimeline.push(releaseFenceTime);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002259 if (mPreviousFrameNumber != 0) {
2260 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2261 latchTime, std::move(releaseFenceTime));
2262 }
Brian Andersond6927fb2016-07-23 23:37:30 -07002263#endif
2264 }
2265
Fabien Sanglard223eb912016-10-13 10:15:06 -07002266 mRefreshPending = true;
2267 mFrameLatencyNeeded = true;
2268 if (oldActiveBuffer == NULL) {
2269 // the first time we receive a buffer, we need to trigger a
2270 // geometry invalidation.
2271 recomputeVisibleRegions = true;
2272 }
2273
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002274 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2275
Fabien Sanglard223eb912016-10-13 10:15:06 -07002276 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2277 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2278 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2279 if ((crop != mCurrentCrop) ||
2280 (transform != mCurrentTransform) ||
2281 (scalingMode != mCurrentScalingMode))
2282 {
2283 mCurrentCrop = crop;
2284 mCurrentTransform = transform;
2285 mCurrentScalingMode = scalingMode;
2286 recomputeVisibleRegions = true;
2287 }
2288
2289 if (oldActiveBuffer != NULL) {
2290 uint32_t bufWidth = mActiveBuffer->getWidth();
2291 uint32_t bufHeight = mActiveBuffer->getHeight();
2292 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2293 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002294 recomputeVisibleRegions = true;
2295 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002296 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002297
Fabien Sanglard223eb912016-10-13 10:15:06 -07002298 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2299 if (oldOpacity != isOpaque(s)) {
2300 recomputeVisibleRegions = true;
2301 }
Dan Stozacac35382016-01-27 12:21:06 -08002302
Fabien Sanglard223eb912016-10-13 10:15:06 -07002303 // Remove any sync points corresponding to the buffer which was just
2304 // latched
2305 {
2306 Mutex::Autolock lock(mLocalSyncPointMutex);
2307 auto point = mLocalSyncPoints.begin();
2308 while (point != mLocalSyncPoints.end()) {
2309 if (!(*point)->frameIsAvailable() ||
2310 !(*point)->transactionIsApplied()) {
2311 // This sync point must have been added since we started
2312 // latching. Don't drop it yet.
2313 ++point;
2314 continue;
2315 }
2316
2317 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2318 point = mLocalSyncPoints.erase(point);
2319 } else {
2320 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002321 }
2322 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002323 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002324
2325 // FIXME: postedRegion should be dirty & bounds
2326 Region dirtyRegion(Rect(s.active.w, s.active.h));
2327
2328 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002329 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002330
Mathias Agopian4fec8732012-06-29 14:12:52 -07002331 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002332}
2333
Mathias Agopiana67932f2011-04-20 14:20:59 -07002334uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002335{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002336 // TODO: should we do something special if mSecure is set?
2337 if (mProtectedByApp) {
2338 // need a hardware-protected path to external video sink
2339 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002340 }
Riley Andrews03414a12014-07-01 14:22:59 -07002341 if (mPotentialCursor) {
2342 usage |= GraphicBuffer::USAGE_CURSOR;
2343 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002344 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002345 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002346}
2347
Mathias Agopian84300952012-11-21 16:02:13 -08002348void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002349 uint32_t orientation = 0;
2350 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002351 // The transform hint is used to improve performance, but we can
2352 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002353 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002354 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002355 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002356 if (orientation & Transform::ROT_INVALID) {
2357 orientation = 0;
2358 }
2359 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002360 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002361}
2362
Mathias Agopian13127d82013-03-05 17:47:11 -08002363// ----------------------------------------------------------------------------
2364// debugging
2365// ----------------------------------------------------------------------------
2366
Kalle Raitaa099a242017-01-11 11:17:29 -08002367LayerDebugInfo Layer::getLayerDebugInfo() const {
2368 LayerDebugInfo info;
2369 const Layer::State& ds = getDrawingState();
2370 info.mName = getName();
chaviw1acbec72017-07-27 15:28:26 -07002371 sp<Layer> parent = getParent();
Kalle Raitaa099a242017-01-11 11:17:29 -08002372 info.mParentName = (parent == nullptr ? std::string("none") : parent->getName().string());
2373 info.mType = String8(getTypeId());
2374 info.mTransparentRegion = ds.activeTransparentRegion;
2375 info.mVisibleRegion = visibleRegion;
2376 info.mSurfaceDamageRegion = surfaceDamageRegion;
2377 info.mLayerStack = getLayerStack();
2378 info.mX = ds.active.transform.tx();
2379 info.mY = ds.active.transform.ty();
2380 info.mZ = ds.z;
2381 info.mWidth = ds.active.w;
2382 info.mHeight = ds.active.h;
2383 info.mCrop = ds.crop;
2384 info.mFinalCrop = ds.finalCrop;
2385 info.mAlpha = ds.alpha;
2386 info.mFlags = ds.flags;
2387 info.mPixelFormat = getPixelFormat();
2388 info.mDataSpace = getDataSpace();
2389 info.mMatrix[0][0] = ds.active.transform[0][0];
2390 info.mMatrix[0][1] = ds.active.transform[0][1];
2391 info.mMatrix[1][0] = ds.active.transform[1][0];
2392 info.mMatrix[1][1] = ds.active.transform[1][1];
2393 {
2394 sp<const GraphicBuffer> activeBuffer = getActiveBuffer();
2395 if (activeBuffer != 0) {
2396 info.mActiveBufferWidth = activeBuffer->getWidth();
2397 info.mActiveBufferHeight = activeBuffer->getHeight();
2398 info.mActiveBufferStride = activeBuffer->getStride();
2399 info.mActiveBufferFormat = activeBuffer->format;
2400 } else {
2401 info.mActiveBufferWidth = 0;
2402 info.mActiveBufferHeight = 0;
2403 info.mActiveBufferStride = 0;
2404 info.mActiveBufferFormat = 0;
2405 }
Mathias Agopian13127d82013-03-05 17:47:11 -08002406 }
Kalle Raitaa099a242017-01-11 11:17:29 -08002407 info.mNumQueuedFrames = getQueuedFrameCount();
2408 info.mRefreshPending = isBufferLatched();
2409 info.mIsOpaque = isOpaque(ds);
2410 info.mContentDirty = contentDirty;
2411 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08002412}
2413
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002414#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002415void Layer::miniDumpHeader(String8& result) {
2416 result.append("----------------------------------------");
2417 result.append("---------------------------------------\n");
2418 result.append(" Layer name\n");
2419 result.append(" Z | ");
2420 result.append(" Comp Type | ");
2421 result.append(" Disp Frame (LTRB) | ");
2422 result.append(" Source Crop (LTRB)\n");
2423 result.append("----------------------------------------");
2424 result.append("---------------------------------------\n");
2425}
2426
2427void Layer::miniDump(String8& result, int32_t hwcId) const {
2428 if (mHwcLayers.count(hwcId) == 0) {
2429 return;
2430 }
2431
2432 String8 name;
2433 if (mName.length() > 77) {
2434 std::string shortened;
2435 shortened.append(mName.string(), 36);
2436 shortened.append("[...]");
2437 shortened.append(mName.string() + (mName.length() - 36), 36);
2438 name = shortened.c_str();
2439 } else {
2440 name = mName;
2441 }
2442
2443 result.appendFormat(" %s\n", name.string());
2444
2445 const Layer::State& layerState(getDrawingState());
2446 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2447 result.appendFormat(" %10u | ", layerState.z);
2448 result.appendFormat("%10s | ",
2449 to_string(getCompositionType(hwcId)).c_str());
2450 const Rect& frame = hwcInfo.displayFrame;
2451 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2452 frame.right, frame.bottom);
Dan Stoza5a423ea2017-02-16 14:10:39 -08002453 const FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002454 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2455 crop.right, crop.bottom);
2456
2457 result.append("- - - - - - - - - - - - - - - - - - - - ");
2458 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2459}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002460#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002461
Svetoslavd85084b2014-03-20 10:28:31 -07002462void Layer::dumpFrameStats(String8& result) const {
2463 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002464}
2465
Svetoslavd85084b2014-03-20 10:28:31 -07002466void Layer::clearFrameStats() {
2467 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002468}
2469
Jamie Gennis6547ff42013-07-16 20:12:42 -07002470void Layer::logFrameStats() {
2471 mFrameTracker.logAndResetStats(mName);
2472}
2473
Svetoslavd85084b2014-03-20 10:28:31 -07002474void Layer::getFrameStats(FrameStats* outStats) const {
2475 mFrameTracker.getStats(outStats);
2476}
2477
Brian Andersond6927fb2016-07-23 23:37:30 -07002478void Layer::dumpFrameEvents(String8& result) {
2479 result.appendFormat("- Layer %s (%s, %p)\n",
2480 getName().string(), getTypeId(), this);
2481 Mutex::Autolock lock(mFrameEventHistoryMutex);
2482 mFrameEventHistory.checkFencesForCompletion();
2483 mFrameEventHistory.dump(result);
2484}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002485
Brian Anderson5ea5e592016-12-01 16:54:33 -08002486void Layer::onDisconnect() {
2487 Mutex::Autolock lock(mFrameEventHistoryMutex);
2488 mFrameEventHistory.onDisconnect();
2489}
2490
Brian Anderson3890c392016-07-25 12:48:08 -07002491void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2492 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002493 Mutex::Autolock lock(mFrameEventHistoryMutex);
2494 if (newTimestamps) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002495 // If there are any unsignaled fences in the aquire timeline at this
2496 // point, the previously queued frame hasn't been latched yet. Go ahead
2497 // and try to get the signal time here so the syscall is taken out of
2498 // the main thread's critical path.
2499 mAcquireTimeline.updateSignalTimes();
2500 // Push the new fence after updating since it's likely still pending.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002501 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002502 mFrameEventHistory.addQueue(*newTimestamps);
2503 }
2504
Brian Anderson3890c392016-07-25 12:48:08 -07002505 if (outDelta) {
2506 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002507 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002508}
Dan Stozae77c7662016-05-13 11:37:28 -07002509
2510std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2511 bool forceFlush) {
2512 std::vector<OccupancyTracker::Segment> history;
2513 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2514 &history);
2515 if (result != NO_ERROR) {
2516 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2517 result);
2518 return {};
2519 }
2520 return history;
2521}
2522
Robert Carr367c5682016-06-20 11:55:28 -07002523bool Layer::getTransformToDisplayInverse() const {
2524 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2525}
2526
Chia-I Wu98f1c102017-05-30 14:54:08 -07002527size_t Layer::getChildrenCount() const {
2528 size_t count = 0;
2529 for (const sp<Layer>& child : mCurrentChildren) {
2530 count += 1 + child->getChildrenCount();
2531 }
2532 return count;
2533}
2534
Robert Carr1f0a16a2016-10-24 16:27:39 -07002535void Layer::addChild(const sp<Layer>& layer) {
2536 mCurrentChildren.add(layer);
2537 layer->setParent(this);
2538}
2539
2540ssize_t Layer::removeChild(const sp<Layer>& layer) {
2541 layer->setParent(nullptr);
2542 return mCurrentChildren.remove(layer);
2543}
2544
Robert Carr1db73f62016-12-21 12:58:51 -08002545bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2546 sp<Handle> handle = nullptr;
2547 sp<Layer> newParent = nullptr;
2548 if (newParentHandle == nullptr) {
2549 return false;
2550 }
2551 handle = static_cast<Handle*>(newParentHandle.get());
2552 newParent = handle->owner.promote();
2553 if (newParent == nullptr) {
2554 ALOGE("Unable to promote Layer handle");
2555 return false;
2556 }
2557
2558 for (const sp<Layer>& child : mCurrentChildren) {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002559 newParent->addChild(child);
Robert Carr1db73f62016-12-21 12:58:51 -08002560
2561 sp<Client> client(child->mClientRef.promote());
2562 if (client != nullptr) {
2563 client->setParentLayer(newParent);
2564 }
2565 }
2566 mCurrentChildren.clear();
2567
2568 return true;
2569}
2570
Robert Carr9524cb32017-02-13 11:32:32 -08002571bool Layer::detachChildren() {
Dan Stoza412903f2017-04-27 13:42:17 -07002572 traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
Robert Carr9524cb32017-02-13 11:32:32 -08002573 if (child == this) {
2574 return;
2575 }
2576
2577 sp<Client> client(child->mClientRef.promote());
2578 if (client != nullptr) {
2579 client->detachLayer(child);
2580 }
2581 });
2582
2583 return true;
2584}
2585
Robert Carr1f0a16a2016-10-24 16:27:39 -07002586void Layer::setParent(const sp<Layer>& layer) {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002587 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002588}
2589
2590void Layer::clearSyncPoints() {
2591 for (const auto& child : mCurrentChildren) {
2592 child->clearSyncPoints();
2593 }
2594
2595 Mutex::Autolock lock(mLocalSyncPointMutex);
2596 for (auto& point : mLocalSyncPoints) {
2597 point->setFrameAvailable();
2598 }
2599 mLocalSyncPoints.clear();
2600}
2601
2602int32_t Layer::getZ() const {
2603 return mDrawingState.z;
2604}
2605
Dan Stoza412903f2017-04-27 13:42:17 -07002606LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2607 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2608 "makeTraversalList received invalid stateSet");
2609 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2610 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2611 const State& state = useDrawing ? mDrawingState : mCurrentState;
2612
2613 if (state.zOrderRelatives.size() == 0) {
2614 return children;
Robert Carrdb66e622017-04-10 16:55:57 -07002615 }
2616 LayerVector traverse;
2617
Dan Stoza412903f2017-04-27 13:42:17 -07002618 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07002619 sp<Layer> strongRelative = weakRelative.promote();
2620 if (strongRelative != nullptr) {
2621 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07002622 }
2623 }
2624
Dan Stoza412903f2017-04-27 13:42:17 -07002625 for (const sp<Layer>& child : children) {
Robert Carrdb66e622017-04-10 16:55:57 -07002626 traverse.add(child);
2627 }
2628
2629 return traverse;
2630}
2631
Robert Carr1f0a16a2016-10-24 16:27:39 -07002632/**
Robert Carrdb66e622017-04-10 16:55:57 -07002633 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002634 */
Dan Stoza412903f2017-04-27 13:42:17 -07002635void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2636 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002637
Robert Carr1f0a16a2016-10-24 16:27:39 -07002638 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002639 for (; i < list.size(); i++) {
2640 const auto& relative = list[i];
2641 if (relative->getZ() >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002642 break;
Robert Carrdb66e622017-04-10 16:55:57 -07002643 }
Dan Stoza412903f2017-04-27 13:42:17 -07002644 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002645 }
Dan Stoza412903f2017-04-27 13:42:17 -07002646 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07002647 for (; i < list.size(); i++) {
2648 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002649 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002650 }
2651}
2652
2653/**
Robert Carrdb66e622017-04-10 16:55:57 -07002654 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002655 */
Dan Stoza412903f2017-04-27 13:42:17 -07002656void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2657 const LayerVector::Visitor& visitor) {
2658 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002659
Robert Carr1f0a16a2016-10-24 16:27:39 -07002660 int32_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002661 for (i = list.size()-1; i>=0; i--) {
2662 const auto& relative = list[i];
2663 if (relative->getZ() < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002664 break;
2665 }
Dan Stoza412903f2017-04-27 13:42:17 -07002666 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002667 }
Dan Stoza412903f2017-04-27 13:42:17 -07002668 visitor(this);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002669 for (; i>=0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002670 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002671 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002672 }
2673}
2674
2675Transform Layer::getTransform() const {
2676 Transform t;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002677 const auto& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002678 if (p != nullptr) {
2679 t = p->getTransform();
Robert Carr9b429f42017-04-17 14:56:57 -07002680
2681 // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2682 // it isFixedSize) then there may be additional scaling not accounted
2683 // for in the transform. We need to mirror this scaling in child surfaces
2684 // or we will break the contract where WM can treat child surfaces as
2685 // pixels in the parent surface.
Chia-I Wu0a68b462017-07-18 11:30:05 -07002686 if (p->isFixedSize() && p->mActiveBuffer != nullptr) {
Robert Carr1725eee2017-04-26 18:32:15 -07002687 int bufferWidth;
2688 int bufferHeight;
2689 if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2690 bufferWidth = p->mActiveBuffer->getWidth();
2691 bufferHeight = p->mActiveBuffer->getHeight();
2692 } else {
2693 bufferHeight = p->mActiveBuffer->getWidth();
2694 bufferWidth = p->mActiveBuffer->getHeight();
2695 }
Robert Carr9b429f42017-04-17 14:56:57 -07002696 float sx = p->getDrawingState().active.w /
Robert Carr1725eee2017-04-26 18:32:15 -07002697 static_cast<float>(bufferWidth);
Robert Carr9b429f42017-04-17 14:56:57 -07002698 float sy = p->getDrawingState().active.h /
Robert Carr1725eee2017-04-26 18:32:15 -07002699 static_cast<float>(bufferHeight);
Robert Carr9b429f42017-04-17 14:56:57 -07002700 Transform extraParentScaling;
2701 extraParentScaling.set(sx, 0, 0, sy);
2702 t = t * extraParentScaling;
2703 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002704 }
2705 return t * getDrawingState().active.transform;
2706}
2707
Robert Carr6452f122017-03-21 10:41:29 -07002708#ifdef USE_HWC2
2709float Layer::getAlpha() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002710 const auto& p = mDrawingParent.promote();
Robert Carr6452f122017-03-21 10:41:29 -07002711
2712 float parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0;
2713 return parentAlpha * getDrawingState().alpha;
2714}
2715#else
2716uint8_t Layer::getAlpha() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002717 const auto& p = mDrawingParent.promote();
Robert Carr6452f122017-03-21 10:41:29 -07002718
2719 float parentAlpha = (p != nullptr) ? (p->getAlpha() / 255.0f) : 1.0;
2720 float drawingAlpha = getDrawingState().alpha / 255.0f;
2721 drawingAlpha = drawingAlpha * parentAlpha;
2722 return static_cast<uint8_t>(std::round(drawingAlpha * 255));
2723}
2724#endif
2725
Robert Carr1f0a16a2016-10-24 16:27:39 -07002726void Layer::commitChildList() {
2727 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2728 const auto& child = mCurrentChildren[i];
2729 child->commitChildList();
2730 }
2731 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002732 mDrawingParent = mCurrentParent;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002733}
2734
Mathias Agopian13127d82013-03-05 17:47:11 -08002735// ---------------------------------------------------------------------------
2736
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002737}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002738
2739#if defined(__gl_h_)
2740#error "don't include gl/gl.h in this file"
2741#endif
2742
2743#if defined(__gl2_h_)
2744#error "don't include gl2/gl2.h in this file"
2745#endif