blob: 54d4cbd6137afcb5fa488f5ca8445fb66b9caad2 [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);
Steven Thomasb02664d2017-07-26 18:48:28 -0700204
205#ifdef USE_HWC2
206 ALOGE_IF(!mHwcLayers.empty(),
207 "Found stale hardware composer layers when destroying "
208 "surface flinger layer");
209#endif
Mathias Agopian96f08192010-06-02 23:28:45 -0700210}
211
Mathias Agopian13127d82013-03-05 17:47:11 -0800212// ---------------------------------------------------------------------------
213// callbacks
214// ---------------------------------------------------------------------------
215
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000216#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800217void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
218 if (mHwcLayers.empty()) {
219 return;
220 }
221 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
222}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000223#else
224void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
225 HWComposer::HWCLayerInterface* layer) {
226 if (layer) {
227 layer->onDisplayed();
228 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
229 }
230}
231#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800232
Dan Stoza6b9454d2014-11-07 16:00:59 -0800233void Layer::onFrameAvailable(const BufferItem& item) {
234 // Add this buffer from our internal queue tracker
235 { // Autolock scope
236 Mutex::Autolock lock(mQueueItemLock);
Irvel468051e2016-06-13 16:44:44 -0700237 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
238 item.mGraphicBuffer->getHeight(), item.mFrameNumber);
Dan Stozaa4650a52015-05-12 12:56:16 -0700239 // Reset the frame number tracker when we receive the first buffer after
240 // a frame number reset
241 if (item.mFrameNumber == 1) {
242 mLastFrameNumberReceived = 0;
243 }
244
245 // Ensure that callbacks are handled in order
246 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
247 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
248 ms2ns(500));
249 if (result != NO_ERROR) {
250 ALOGE("[%s] Timed out waiting on callback", mName.string());
251 }
252 }
253
Dan Stoza6b9454d2014-11-07 16:00:59 -0800254 mQueueItems.push_back(item);
Dan Stozaecc50402015-04-28 14:42:06 -0700255 android_atomic_inc(&mQueuedFrames);
Dan Stozaa4650a52015-05-12 12:56:16 -0700256
257 // Wake up any pending callbacks
258 mLastFrameNumberReceived = item.mFrameNumber;
259 mQueueItemCondition.broadcast();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800260 }
261
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800262 mFlinger->signalLayerUpdate();
Mathias Agopian579b3f82010-06-08 19:54:15 -0700263}
264
Dan Stoza6b9454d2014-11-07 16:00:59 -0800265void Layer::onFrameReplaced(const BufferItem& item) {
Dan Stoza7dde5992015-05-22 09:51:44 -0700266 { // Autolock scope
267 Mutex::Autolock lock(mQueueItemLock);
Dan Stozaa4650a52015-05-12 12:56:16 -0700268
Dan Stoza7dde5992015-05-22 09:51:44 -0700269 // Ensure that callbacks are handled in order
270 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
271 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
272 ms2ns(500));
273 if (result != NO_ERROR) {
274 ALOGE("[%s] Timed out waiting on callback", mName.string());
275 }
Dan Stozaa4650a52015-05-12 12:56:16 -0700276 }
Dan Stoza7dde5992015-05-22 09:51:44 -0700277
278 if (mQueueItems.empty()) {
279 ALOGE("Can't replace a frame on an empty queue");
280 return;
281 }
Pablo Ceballos4d85da42016-04-19 20:11:56 -0700282 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
Dan Stoza7dde5992015-05-22 09:51:44 -0700283
284 // Wake up any pending callbacks
285 mLastFrameNumberReceived = item.mFrameNumber;
286 mQueueItemCondition.broadcast();
Dan Stozaa4650a52015-05-12 12:56:16 -0700287 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800288}
289
Jesse Hall399184a2014-03-03 15:42:54 -0800290void Layer::onSidebandStreamChanged() {
291 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
292 // mSidebandStreamChanged was false
293 mFlinger->signalLayerUpdate();
294 }
295}
296
Mathias Agopian67106042013-03-14 19:18:13 -0700297// called with SurfaceFlinger::mStateLock from the drawing thread after
298// the layer has been remove from the current state list (and just before
299// it's removed from the drawing state list)
Mathias Agopian13127d82013-03-05 17:47:11 -0800300void Layer::onRemoved() {
Robert Carr5edb1ad2017-04-25 10:54:24 -0700301 if (mCurrentState.zOrderRelativeOf != nullptr) {
302 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
303 if (strongRelative != nullptr) {
304 strongRelative->removeZOrderRelative(this);
305 }
306 mCurrentState.zOrderRelativeOf = nullptr;
307 }
308
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800309 mSurfaceFlingerConsumer->abandon();
Chia-I Wu38512252017-05-17 14:36:16 -0700310
311#ifdef USE_HWC2
Steven Thomasb02664d2017-07-26 18:48:28 -0700312 destroyAllHwcLayers();
Chia-I Wu38512252017-05-17 14:36:16 -0700313#endif
314
Robert Carr1f0a16a2016-10-24 16:27:39 -0700315 for (const auto& child : mCurrentChildren) {
316 child->onRemoved();
317 }
Mathias Agopian48d819a2009-09-10 19:41:18 -0700318}
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700319
Mathias Agopian13127d82013-03-05 17:47:11 -0800320// ---------------------------------------------------------------------------
321// set-up
322// ---------------------------------------------------------------------------
323
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700324const String8& Layer::getName() const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800325 return mName;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800326}
327
Mathias Agopianf9d93272009-06-19 17:00:27 -0700328status_t Layer::setBuffers( uint32_t w, uint32_t h,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800329 PixelFormat format, uint32_t flags)
330{
Mathias Agopianca99fb82010-04-14 16:43:44 -0700331 uint32_t const maxSurfaceDims = min(
Mathias Agopiana4912602012-07-12 14:25:33 -0700332 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
Mathias Agopianca99fb82010-04-14 16:43:44 -0700333
334 // never allow a surface larger than what our underlying GL implementation
335 // can handle.
336 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
Mathias Agopianff615cc2012-02-24 14:58:36 -0800337 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700338 return BAD_VALUE;
339 }
340
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700341 mFormat = format;
Mathias Agopianeff062c2010-08-25 14:59:15 -0700342
Riley Andrews03414a12014-07-01 14:22:59 -0700343 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
Mathias Agopian3165cc22012-08-08 19:42:09 -0700344 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700345 mCurrentOpacity = getOpacityForFormat(format);
346
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800347 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
348 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
349 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700350
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351 return NO_ERROR;
352}
353
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700354sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800355 Mutex::Autolock _l(mLock);
356
357 LOG_ALWAYS_FATAL_IF(mHasSurface,
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700358 "Layer::getHandle() has already been called");
Mathias Agopian13127d82013-03-05 17:47:11 -0800359
360 mHasSurface = true;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700361
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700362 return new Handle(mFlinger, this);
Mathias Agopian13127d82013-03-05 17:47:11 -0800363}
364
Dan Stozab9b08832014-03-13 11:55:57 -0700365sp<IGraphicBufferProducer> Layer::getProducer() const {
366 return mProducer;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700367}
368
Mathias Agopian13127d82013-03-05 17:47:11 -0800369// ---------------------------------------------------------------------------
370// h/w composer set-up
371// ---------------------------------------------------------------------------
372
Steven Thomasb02664d2017-07-26 18:48:28 -0700373#ifdef USE_HWC2
374bool Layer::createHwcLayer(HWComposer* hwc, int32_t hwcId) {
375 LOG_ALWAYS_FATAL_IF(mHwcLayers.count(hwcId) != 0,
376 "Already have a layer for hwcId %d", hwcId);
377 HWC2::Layer* layer = hwc->createLayer(hwcId);
378 if (!layer) {
379 return false;
380 }
381 HWCInfo& hwcInfo = mHwcLayers[hwcId];
382 hwcInfo.hwc = hwc;
383 hwcInfo.layer = layer;
384 layer->setLayerDestroyedListener(
385 [this, hwcId] (HWC2::Layer* /*layer*/){mHwcLayers.erase(hwcId);});
386 return true;
387}
388
389void Layer::destroyHwcLayer(int32_t hwcId) {
390 if (mHwcLayers.count(hwcId) == 0) {
391 return;
392 }
393 auto& hwcInfo = mHwcLayers[hwcId];
394 LOG_ALWAYS_FATAL_IF(hwcInfo.layer == nullptr,
395 "Attempt to destroy null layer");
396 LOG_ALWAYS_FATAL_IF(hwcInfo.hwc == nullptr, "Missing HWComposer");
397 hwcInfo.hwc->destroyLayer(hwcId, hwcInfo.layer);
398 // The layer destroyed listener should have cleared the entry from
399 // mHwcLayers. Verify that.
400 LOG_ALWAYS_FATAL_IF(mHwcLayers.count(hwcId) != 0,
401 "Stale layer entry in mHwcLayers");
402}
403
404void Layer::destroyAllHwcLayers() {
405 size_t numLayers = mHwcLayers.size();
406 for (size_t i = 0; i < numLayers; ++i) {
407 LOG_ALWAYS_FATAL_IF(mHwcLayers.empty(), "destroyAllHwcLayers failed");
408 destroyHwcLayer(mHwcLayers.begin()->first);
409 }
410 LOG_ALWAYS_FATAL_IF(!mHwcLayers.empty(),
411 "All hardware composer layers should have been destroyed");
412}
413#endif
414
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800415Rect Layer::getContentCrop() const {
416 // this is the crop rectangle that applies to the buffer
417 // itself (as opposed to the window)
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700418 Rect crop;
419 if (!mCurrentCrop.isEmpty()) {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800420 // if the buffer crop is defined, we use that
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700421 crop = mCurrentCrop;
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800422 } else if (mActiveBuffer != NULL) {
423 // otherwise we use the whole buffer
424 crop = mActiveBuffer->getBounds();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700425 } else {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800426 // if we don't have a buffer yet, we use an empty/invalid crop
Mathias Agopian4fec8732012-06-29 14:12:52 -0700427 crop.makeInvalid();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700428 }
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700429 return crop;
430}
431
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700432static Rect reduce(const Rect& win, const Region& exclude) {
433 if (CC_LIKELY(exclude.isEmpty())) {
434 return win;
435 }
436 if (exclude.isRect()) {
437 return win.reduce(exclude.getBounds());
438 }
439 return Region(win).subtract(exclude).getBounds();
440}
441
Robert Carr1f0a16a2016-10-24 16:27:39 -0700442Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
443 const Layer::State& s(getDrawingState());
444 Rect win(s.active.w, s.active.h);
445
446 if (!s.crop.isEmpty()) {
447 win.intersect(s.crop, &win);
448 }
449
450 Transform t = getTransform();
451 win = t.transform(win);
452
Robert Carr41b08b52017-06-01 16:11:34 -0700453 if (!s.finalCrop.isEmpty()) {
454 win.intersect(s.finalCrop, &win);
455 }
456
Chia-I Wue41dbe62017-06-13 14:10:56 -0700457 const sp<Layer>& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700458 // Now we need to calculate the parent bounds, so we can clip ourselves to those.
459 // When calculating the parent bounds for purposes of clipping,
460 // we don't need to constrain the parent to its transparent region.
461 // The transparent region is an optimization based on the
462 // buffer contents of the layer, but does not affect the space allocated to
463 // it by policy, and thus children should be allowed to extend into the
464 // parent's transparent region. In fact one of the main uses, is to reduce
465 // buffer allocation size in cases where a child window sits behind a main window
466 // (by marking the hole in the parent window as a transparent region)
467 if (p != nullptr) {
468 Rect bounds = p->computeScreenBounds(false);
469 bounds.intersect(win, &win);
470 }
471
472 if (reduceTransparentRegion) {
473 auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
474 win = reduce(win, screenTransparentRegion);
475 }
476
477 return win;
478}
479
Mathias Agopian13127d82013-03-05 17:47:11 -0800480Rect Layer::computeBounds() const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700481 const Layer::State& s(getDrawingState());
Michael Lentine6c925ed2014-09-26 17:55:01 -0700482 return computeBounds(s.activeTransparentRegion);
483}
484
485Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
486 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800487 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700488
489 if (!s.crop.isEmpty()) {
490 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -0800491 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700492
493 Rect bounds = win;
Chia-I Wue41dbe62017-06-13 14:10:56 -0700494 const auto& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700495 if (p != nullptr) {
Robert Carrde9ec442017-02-08 17:43:36 -0800496 // Look in computeScreenBounds recursive call for explanation of
497 // why we pass false here.
498 bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700499 }
500
501 Transform t = getTransform();
502 if (p != nullptr) {
503 win = t.transform(win);
504 win.intersect(bounds, &win);
505 win = t.inverse().transform(win);
506 }
507
Mathias Agopian6c7f25a2013-05-09 20:37:10 -0700508 // subtract the transparent region and snap to the bounds
Michael Lentine6c925ed2014-09-26 17:55:01 -0700509 return reduce(win, activeTransparentRegion);
Mathias Agopian13127d82013-03-05 17:47:11 -0800510}
511
Robert Carr1f0a16a2016-10-24 16:27:39 -0700512Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
Robert Carrb5d3d262016-03-25 15:08:13 -0700513 // the crop is the area of the window that gets cropped, but not
Mathias Agopian13127d82013-03-05 17:47:11 -0800514 // scaled in any ways.
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700515 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800516
517 // apply the projection's clipping to the window crop in
518 // layerstack space, and convert-back to layer space.
Mathias Agopian6b442672013-07-09 21:24:52 -0700519 // if there are no window scaling involved, this operation will map to full
520 // pixels in the buffer.
521 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
522 // a viewport clipping and a window transform. we should use floating point to fix this.
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700523
524 Rect activeCrop(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700525 if (!s.crop.isEmpty()) {
Chia-I Wudf7867f2017-07-20 14:24:37 -0700526 activeCrop.intersect(s.crop, &activeCrop);
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700527 }
528
Robert Carr1f0a16a2016-10-24 16:27:39 -0700529 Transform t = getTransform();
530 activeCrop = t.transform(activeCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000531 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
532 activeCrop.clear();
533 }
Robert Carrb5d3d262016-03-25 15:08:13 -0700534 if (!s.finalCrop.isEmpty()) {
535 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000536 activeCrop.clear();
537 }
538 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700539 return activeCrop;
540}
541
Dan Stoza5a423ea2017-02-16 14:10:39 -0800542FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
Robert Carr1f0a16a2016-10-24 16:27:39 -0700543 // the content crop is the area of the content that gets scaled to the
544 // layer's size. This is in buffer space.
Dan Stoza5a423ea2017-02-16 14:10:39 -0800545 FloatRect crop = getContentCrop().toFloatRect();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700546
547 // In addition there is a WM-specified crop we pull from our drawing state.
548 const State& s(getDrawingState());
549
550 // Screen space to make reduction to parent crop clearer.
551 Rect activeCrop = computeInitialCrop(hw);
Chia-I Wue41dbe62017-06-13 14:10:56 -0700552 const auto& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700553 if (p != nullptr) {
554 auto parentCrop = p->computeInitialCrop(hw);
555 activeCrop.intersect(parentCrop, &activeCrop);
556 }
557 Transform t = getTransform();
558 // Back to layer space to work with the content crop.
559 activeCrop = t.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800560
Michael Lentine28ea2172014-11-19 18:32:37 -0800561 // This needs to be here as transform.transform(Rect) computes the
562 // transformed rect and then takes the bounding box of the result before
563 // returning. This means
564 // transform.inverse().transform(transform.transform(Rect)) != Rect
565 // in which case we need to make sure the final rect is clipped to the
566 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000567 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
568 activeCrop.clear();
569 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800570
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700571 // subtract the transparent region and snap to the bounds
572 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
573
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000574 // Transform the window crop to match the buffer coordinate system,
575 // which means using the inverse of the current transform set on the
576 // SurfaceFlingerConsumer.
577 uint32_t invTransform = mCurrentTransform;
Robert Carrcae605c2017-03-29 12:10:31 -0700578 if (getTransformToDisplayInverse()) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000579 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700580 * the code below applies the primary display's inverse transform to the
581 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000582 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700583 uint32_t invTransformOrient =
584 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000585 // calculate the inverse transform
586 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
587 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
588 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800589 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000590 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700591 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
592 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800593 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000594
595 int winWidth = s.active.w;
596 int winHeight = s.active.h;
597 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
598 // If the activeCrop has been rotate the ends are rotated but not
599 // the space itself so when transforming ends back we can't rely on
600 // a modification of the axes of rotation. To account for this we
601 // need to reorient the inverse rotation in terms of the current
602 // axes of rotation.
603 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
604 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
605 if (is_h_flipped == is_v_flipped) {
606 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
607 NATIVE_WINDOW_TRANSFORM_FLIP_H;
608 }
609 winWidth = s.active.h;
610 winHeight = s.active.w;
611 }
612 const Rect winCrop = activeCrop.transform(
613 invTransform, s.active.w, s.active.h);
614
615 // below, crop is intersected with winCrop expressed in crop's coordinate space
616 float xScale = crop.getWidth() / float(winWidth);
617 float yScale = crop.getHeight() / float(winHeight);
618
619 float insetL = winCrop.left * xScale;
620 float insetT = winCrop.top * yScale;
621 float insetR = (winWidth - winCrop.right ) * xScale;
622 float insetB = (winHeight - winCrop.bottom) * yScale;
623
624 crop.left += insetL;
625 crop.top += insetT;
626 crop.right -= insetR;
627 crop.bottom -= insetB;
628
Mathias Agopian13127d82013-03-05 17:47:11 -0800629 return crop;
630}
631
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000632#ifdef USE_HWC2
Robert Carrae060832016-11-28 10:51:00 -0800633void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000634#else
635void Layer::setGeometry(
636 const sp<const DisplayDevice>& hw,
637 HWComposer::HWCLayerInterface& layer)
638#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700639{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000640#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800641 const auto hwcId = displayDevice->getHwcDisplayId();
642 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000643#else
644 layer.setDefaultState();
645#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700646
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700647 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000648#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800649 hwcInfo.forceClientComposition = false;
650
651 if (isSecure() && !displayDevice->isSecure()) {
652 hwcInfo.forceClientComposition = true;
653 }
654
655 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000656#else
657 layer.setSkip(false);
658
659 if (isSecure() && !hw->isSecure()) {
660 layer.setSkip(true);
661 }
662#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700663
Mathias Agopian13127d82013-03-05 17:47:11 -0800664 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700665 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000666#ifdef USE_HWC2
David Revemanecf0fa52017-03-03 11:32:44 -0500667 auto blendMode = HWC2::BlendMode::None;
Robert Carr6452f122017-03-21 10:41:29 -0700668 if (!isOpaque(s) || getAlpha() != 1.0f) {
David Revemanecf0fa52017-03-03 11:32:44 -0500669 blendMode = mPremultipliedAlpha ?
Dan Stoza9e56aa02015-11-02 13:00:03 -0800670 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800671 }
David Revemanecf0fa52017-03-03 11:32:44 -0500672 auto error = hwcLayer->setBlendMode(blendMode);
673 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
674 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
675 to_string(error).c_str(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000676#else
Robert Carr6452f122017-03-21 10:41:29 -0700677 if (!isOpaque(s) || getAlpha() != 0xFF) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000678 layer.setBlending(mPremultipliedAlpha ?
679 HWC_BLENDING_PREMULT :
680 HWC_BLENDING_COVERAGE);
681 }
682#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800683
684 // apply the layer's transform, followed by the display's global transform
685 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700686 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700687 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -0700688 if (!s.crop.isEmpty()) {
689 Rect activeCrop(s.crop);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700690 activeCrop = t.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000691#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000692 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000693#else
694 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
695#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000696 activeCrop.clear();
697 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700698 activeCrop = t.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800699 // This needs to be here as transform.transform(Rect) computes the
700 // transformed rect and then takes the bounding box of the result before
701 // returning. This means
702 // transform.inverse().transform(transform.transform(Rect)) != Rect
703 // in which case we need to make sure the final rect is clipped to the
704 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000705 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
706 activeCrop.clear();
707 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700708 // mark regions outside the crop as transparent
709 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
710 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
711 s.active.w, s.active.h));
712 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
713 activeCrop.left, activeCrop.bottom));
714 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
715 s.active.w, activeCrop.bottom));
716 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700717
718 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700719 if (!s.finalCrop.isEmpty()) {
720 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000721 frame.clear();
722 }
723 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000724#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000725 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
726 frame.clear();
727 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800728 const Transform& tr(displayDevice->getTransform());
729 Rect transformedFrame = tr.transform(frame);
David Revemanecf0fa52017-03-03 11:32:44 -0500730 error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700731 if (error != HWC2::Error::None) {
732 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
733 mName.string(), transformedFrame.left, transformedFrame.top,
734 transformedFrame.right, transformedFrame.bottom,
735 to_string(error).c_str(), static_cast<int32_t>(error));
736 } else {
737 hwcInfo.displayFrame = transformedFrame;
738 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800739
Dan Stoza5a423ea2017-02-16 14:10:39 -0800740 FloatRect sourceCrop = computeCrop(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800741 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700742 if (error != HWC2::Error::None) {
743 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
744 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
745 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
746 static_cast<int32_t>(error));
747 } else {
748 hwcInfo.sourceCrop = sourceCrop;
749 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800750
Robert Carr6452f122017-03-21 10:41:29 -0700751 float alpha = getAlpha();
752 error = hwcLayer->setPlaneAlpha(alpha);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800753 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
Robert Carr6452f122017-03-21 10:41:29 -0700754 "%s (%d)", mName.string(), alpha, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800755 static_cast<int32_t>(error));
756
Robert Carrae060832016-11-28 10:51:00 -0800757 error = hwcLayer->setZOrder(z);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800758 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
Robert Carrae060832016-11-28 10:51:00 -0800759 mName.string(), z, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800760 static_cast<int32_t>(error));
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500761
Albert Chaulk2a589632017-05-04 16:59:44 -0400762 int type = s.type;
763 int appId = s.appId;
Chia-I Wue41dbe62017-06-13 14:10:56 -0700764 sp<Layer> parent = mDrawingParent.promote();
Albert Chaulk2a589632017-05-04 16:59:44 -0400765 if (parent.get()) {
766 auto& parentState = parent->getDrawingState();
767 type = parentState.type;
768 appId = parentState.appId;
769 }
770
771 error = hwcLayer->setInfo(type, appId);
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500772 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
773 mName.string(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000774#else
775 if (!frame.intersect(hw->getViewport(), &frame)) {
776 frame.clear();
777 }
778 const Transform& tr(hw->getTransform());
779 layer.setFrame(tr.transform(frame));
780 layer.setCrop(computeCrop(hw));
Robert Carr6452f122017-03-21 10:41:29 -0700781 layer.setPlaneAlpha(getAlpha());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000782#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800783
Mathias Agopian29a367b2011-07-12 14:51:45 -0700784 /*
785 * Transformations are applied in this order:
786 * 1) buffer orientation/flip/mirror
787 * 2) state transformation (window manager)
788 * 3) layer orientation (screen orientation)
789 * (NOTE: the matrices are multiplied in reverse order)
790 */
791
792 const Transform bufferOrientation(mCurrentTransform);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700793 Transform transform(tr * t * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700794
Robert Carrcae605c2017-03-29 12:10:31 -0700795 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700796 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700797 * the code below applies the primary display's inverse transform to the
798 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700799 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700800 uint32_t invTransform =
801 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700802 // calculate the inverse transform
803 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
804 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
805 NATIVE_WINDOW_TRANSFORM_FLIP_H;
806 }
Robert Carrcae605c2017-03-29 12:10:31 -0700807
808 /*
809 * Here we cancel out the orientation component of the WM transform.
810 * The scaling and translate components are already included in our bounds
811 * computation so it's enough to just omit it in the composition.
812 * See comment in onDraw with ref to b/36727915 for why.
813 */
814 transform = Transform(invTransform) * tr * bufferOrientation;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700815 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700816
817 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800818 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000819#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800820 if (orientation & Transform::ROT_INVALID) {
821 // we can only handle simple transformation
822 hwcInfo.forceClientComposition = true;
823 } else {
824 auto transform = static_cast<HWC2::Transform>(orientation);
825 auto error = hwcLayer->setTransform(transform);
826 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
827 "%s (%d)", mName.string(), to_string(transform).c_str(),
828 to_string(error).c_str(), static_cast<int32_t>(error));
829 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000830#else
831 if (orientation & Transform::ROT_INVALID) {
832 // we can only handle simple transformation
833 layer.setSkip(true);
834 } else {
835 layer.setTransform(orientation);
836 }
837#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700838}
839
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000840#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800841void Layer::forceClientComposition(int32_t hwcId) {
842 if (mHwcLayers.count(hwcId) == 0) {
843 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
844 return;
845 }
846
847 mHwcLayers[hwcId].forceClientComposition = true;
848}
Dan Stoza9e56aa02015-11-02 13:00:03 -0800849
Dan Stoza9e56aa02015-11-02 13:00:03 -0800850void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
851 // Apply this display's projection's viewport to the visible region
852 // before giving it to the HWC HAL.
853 const Transform& tr = displayDevice->getTransform();
854 const auto& viewport = displayDevice->getViewport();
855 Region visible = tr.transform(visibleRegion.intersect(viewport));
856 auto hwcId = displayDevice->getHwcDisplayId();
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800857 auto& hwcInfo = mHwcLayers[hwcId];
858 auto& hwcLayer = hwcInfo.layer;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800859 auto error = hwcLayer->setVisibleRegion(visible);
860 if (error != HWC2::Error::None) {
861 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
862 to_string(error).c_str(), static_cast<int32_t>(error));
863 visible.dump(LOG_TAG);
864 }
865
866 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
867 if (error != HWC2::Error::None) {
868 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
869 to_string(error).c_str(), static_cast<int32_t>(error));
870 surfaceDamageRegion.dump(LOG_TAG);
871 }
872
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700873 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800874 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700875 setCompositionType(hwcId, HWC2::Composition::Sideband);
876 ALOGV("[%s] Requesting Sideband composition", mName.string());
877 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800878 if (error != HWC2::Error::None) {
879 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
880 mName.string(), mSidebandStream->handle(),
881 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800882 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700883 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800884 }
885
Dan Stoza0a21df72016-07-20 12:52:38 -0700886 // Client layers
Chia-I Wuaaff73f2017-02-13 12:28:24 -0800887 if (hwcInfo.forceClientComposition ||
Dan Stoza0a21df72016-07-20 12:52:38 -0700888 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700889 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800890 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700891 return;
892 }
893
Dan Stoza0a21df72016-07-20 12:52:38 -0700894 // SolidColor layers
895 if (mActiveBuffer == nullptr) {
896 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700897
898 // For now, we only support black for DimLayer
Dan Stoza0a21df72016-07-20 12:52:38 -0700899 error = hwcLayer->setColor({0, 0, 0, 255});
900 if (error != HWC2::Error::None) {
901 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
902 to_string(error).c_str(), static_cast<int32_t>(error));
903 }
Dan Stozac6c89542016-07-27 10:16:52 -0700904
905 // Clear out the transform, because it doesn't make sense absent a
906 // source buffer
907 error = hwcLayer->setTransform(HWC2::Transform::None);
908 if (error != HWC2::Error::None) {
909 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
910 to_string(error).c_str(), static_cast<int32_t>(error));
911 }
912
Dan Stoza0a21df72016-07-20 12:52:38 -0700913 return;
914 }
915
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700916 // Device or Cursor layers
917 if (mPotentialCursor) {
918 ALOGV("[%s] Requesting Cursor composition", mName.string());
919 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800920 } else {
921 ALOGV("[%s] Requesting Device composition", mName.string());
922 setCompositionType(hwcId, HWC2::Composition::Device);
923 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700924
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700925 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
926 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
927 if (error != HWC2::Error::None) {
928 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
929 mCurrentState.dataSpace, to_string(error).c_str(),
930 static_cast<int32_t>(error));
931 }
932
Chia-I Wu06d63de2017-01-04 14:58:51 +0800933 uint32_t hwcSlot = 0;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400934 sp<GraphicBuffer> hwcBuffer;
935 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
936 &hwcSlot, &hwcBuffer);
Chia-I Wu06d63de2017-01-04 14:58:51 +0800937
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700938 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -0400939 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700940 if (error != HWC2::Error::None) {
941 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
942 mActiveBuffer->handle, to_string(error).c_str(),
943 static_cast<int32_t>(error));
944 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800945}
Courtney Goeltzenleuchter9551fd32016-10-20 17:18:15 -0600946
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000947#else
948void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
949 HWComposer::HWCLayerInterface& layer) {
950 // we have to set the visible region on every frame because
951 // we currently free it during onLayerDisplayed(), which is called
952 // after HWComposer::commit() -- every frame.
953 // Apply this display's projection's viewport to the visible region
954 // before giving it to the HWC HAL.
955 const Transform& tr = hw->getTransform();
956 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
957 layer.setVisibleRegionScreen(visible);
958 layer.setSurfaceDamage(surfaceDamageRegion);
959 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700960
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000961 if (mSidebandStream.get()) {
962 layer.setSidebandStream(mSidebandStream);
963 } else {
964 // NOTE: buffer can be NULL if the client never drew into this
965 // layer yet, or if we ran out of memory
966 layer.setBuffer(mActiveBuffer);
967 }
968}
969#endif
970
971#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800972void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
973 auto hwcId = displayDevice->getHwcDisplayId();
974 if (mHwcLayers.count(hwcId) == 0 ||
975 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
976 return;
977 }
978
979 // This gives us only the "orientation" component of the transform
980 const State& s(getCurrentState());
981
982 // Apply the layer's transform, followed by the display's global transform
983 // Here we're guaranteed that the layer's transform preserves rects
984 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700985 if (!s.crop.isEmpty()) {
986 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800987 }
988 // Subtract the transparent region and snap to the bounds
989 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700990 Rect frame(getTransform().transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800991 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -0700992 if (!s.finalCrop.isEmpty()) {
993 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000994 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800995 auto& displayTransform(displayDevice->getTransform());
996 auto position = displayTransform.transform(frame);
997
998 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
999 position.top);
1000 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
1001 "to (%d, %d): %s (%d)", mName.string(), position.left,
1002 position.top, to_string(error).c_str(),
1003 static_cast<int32_t>(error));
1004}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001005#else
1006void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
1007 HWComposer::HWCLayerInterface& layer) {
1008 int fenceFd = -1;
1009
1010 // TODO: there is a possible optimization here: we only need to set the
1011 // acquire fence the first time a new buffer is acquired on EACH display.
1012
1013 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
1014 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
1015 if (fence->isValid()) {
1016 fenceFd = fence->dup();
1017 if (fenceFd == -1) {
1018 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
1019 }
1020 }
1021 }
1022 layer.setAcquireFenceFd(fenceFd);
1023}
1024
1025Rect Layer::getPosition(
1026 const sp<const DisplayDevice>& hw)
1027{
1028 // this gives us only the "orientation" component of the transform
1029 const State& s(getCurrentState());
1030
1031 // apply the layer's transform, followed by the display's global transform
1032 // here we're guaranteed that the layer's transform preserves rects
1033 Rect win(s.active.w, s.active.h);
1034 if (!s.crop.isEmpty()) {
1035 win.intersect(s.crop, &win);
1036 }
1037 // subtract the transparent region and snap to the bounds
1038 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001039 Rect frame(getTransform().transform(bounds));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001040 frame.intersect(hw->getViewport(), &frame);
1041 if (!s.finalCrop.isEmpty()) {
1042 frame.intersect(s.finalCrop, &frame);
1043 }
1044 const Transform& tr(hw->getTransform());
1045 return Rect(tr.transform(frame));
1046}
1047#endif
Riley Andrews03414a12014-07-01 14:22:59 -07001048
Mathias Agopian13127d82013-03-05 17:47:11 -08001049// ---------------------------------------------------------------------------
1050// drawing...
1051// ---------------------------------------------------------------------------
1052
1053void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -08001054 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -08001055}
1056
Dan Stozac7014012014-02-14 15:03:43 -08001057void Layer::draw(const sp<const DisplayDevice>& hw,
1058 bool useIdentityTransform) const {
1059 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001060}
1061
Dan Stozac7014012014-02-14 15:03:43 -08001062void Layer::draw(const sp<const DisplayDevice>& hw) const {
1063 onDraw(hw, Region(hw->bounds()), false);
1064}
1065
Robert Carrcae605c2017-03-29 12:10:31 -07001066static constexpr mat4 inverseOrientation(uint32_t transform) {
1067 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1068 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1069 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1070 mat4 tr;
1071
1072 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1073 tr = tr * rot90;
1074 }
1075 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1076 tr = tr * flipH;
1077 }
1078 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1079 tr = tr * flipV;
1080 }
1081 return inverse(tr);
1082}
1083
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001084/*
1085 * onDraw will draw the current layer onto the presentable buffer
1086 */
Dan Stozac7014012014-02-14 15:03:43 -08001087void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
1088 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001089{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001090 ATRACE_CALL();
1091
Mathias Agopiana67932f2011-04-20 14:20:59 -07001092 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001093 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -07001094 // in fact never been drawn into. This happens frequently with
1095 // SurfaceView because the WindowManager can't know when the client
1096 // has drawn the first time.
1097
1098 // If there is nothing under us, we paint the screen in black, otherwise
1099 // we just skip this update.
1100
1101 // figure out if there is something below us
1102 Region under;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001103 bool finished = false;
Dan Stoza412903f2017-04-27 13:42:17 -07001104 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001105 if (finished || layer == static_cast<Layer const*>(this)) {
1106 finished = true;
1107 return;
1108 }
Mathias Agopian42977342012-08-05 00:40:46 -07001109 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Robert Carr1f0a16a2016-10-24 16:27:39 -07001110 });
Mathias Agopian179169e2010-05-06 20:21:45 -07001111 // if not everything below us is covered, we plug the holes!
1112 Region holes(clip.subtract(under));
1113 if (!holes.isEmpty()) {
Fabien Sanglard17487192016-12-07 13:03:32 -08001114 clearWithOpenGL(hw, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -07001115 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001116 return;
1117 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001118
Andy McFadden97eba892012-12-11 15:21:45 -08001119 // Bind the current buffer to the GL texture, and wait for it to be
1120 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001121 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1122 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -08001123 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -07001124 // Go ahead and draw the buffer anyway; no matter what we do the screen
1125 // is probably going to have something visibly wrong.
1126 }
1127
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001128 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1129
Mathias Agopian875d8e12013-06-07 15:35:48 -07001130 RenderEngine& engine(mFlinger->getRenderEngine());
1131
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001132 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -07001133 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -07001134 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -07001135
1136 // Query the texture matrix given our current filtering mode.
1137 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001138 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1139 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -07001140
Robert Carrcae605c2017-03-29 12:10:31 -07001141 if (getTransformToDisplayInverse()) {
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001142
1143 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -07001144 * the code below applies the primary display's inverse transform to
1145 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001146 */
Pablo Ceballos021623b2016-04-15 17:31:51 -07001147 uint32_t transform =
1148 DisplayDevice::getPrimaryDisplayOrientationTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001149 mat4 tr = inverseOrientation(transform);
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001150
Robert Carrcae605c2017-03-29 12:10:31 -07001151 /**
1152 * TODO(b/36727915): This is basically a hack.
1153 *
1154 * Ensure that regardless of the parent transformation,
1155 * this buffer is always transformed from native display
1156 * orientation to display orientation. For example, in the case
1157 * of a camera where the buffer remains in native orientation,
1158 * we want the pixels to always be upright.
1159 */
Chia-I Wue41dbe62017-06-13 14:10:56 -07001160 sp<Layer> p = mDrawingParent.promote();
1161 if (p != nullptr) {
1162 const auto parentTransform = p->getTransform();
Robert Carrcae605c2017-03-29 12:10:31 -07001163 tr = tr * inverseOrientation(parentTransform.getOrientation());
1164 }
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001165
1166 // and finally apply it to the original texture matrix
1167 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1168 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1169 }
1170
Jamie Genniscbb1a952012-05-08 17:05:52 -07001171 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -07001172 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1173 mTexture.setFiltering(useFiltering);
1174 mTexture.setMatrix(textureMatrix);
1175
1176 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -07001177 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001178 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -07001179 }
Fabien Sanglard85789802016-12-07 13:08:24 -08001180 drawWithOpenGL(hw, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001181 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001182}
1183
Mathias Agopian13127d82013-03-05 17:47:11 -08001184
Dan Stozac7014012014-02-14 15:03:43 -08001185void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard17487192016-12-07 13:03:32 -08001186 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -08001187 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001188{
Mathias Agopian19733a32013-08-28 18:13:56 -07001189 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -08001190 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -07001191 engine.setupFillWithColor(red, green, blue, alpha);
1192 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -08001193}
1194
1195void Layer::clearWithOpenGL(
Fabien Sanglard17487192016-12-07 13:03:32 -08001196 const sp<const DisplayDevice>& hw) const {
1197 clearWithOpenGL(hw, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001198}
1199
Dan Stozac7014012014-02-14 15:03:43 -08001200void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard85789802016-12-07 13:08:24 -08001201 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001202 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001203
Dan Stozac7014012014-02-14 15:03:43 -08001204 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001205
Mathias Agopian13127d82013-03-05 17:47:11 -08001206 /*
1207 * NOTE: the way we compute the texture coordinates here produces
1208 * different results than when we take the HWC path -- in the later case
1209 * the "source crop" is rounded to texel boundaries.
1210 * This can produce significantly different results when the texture
1211 * is scaled by a large amount.
1212 *
1213 * The GL code below is more logical (imho), and the difference with
1214 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001215 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001216 * GL composition when a buffer scaling is applied (maybe with some
1217 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1218 * like more of a hack.
1219 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001220 Rect win(computeBounds());
1221
Robert Carr1f0a16a2016-10-24 16:27:39 -07001222 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -07001223 if (!s.finalCrop.isEmpty()) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001224 win = t.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001225 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001226 win.clear();
1227 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001228 win = t.inverse().transform(win);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001229 if (!win.intersect(computeBounds(), &win)) {
1230 win.clear();
1231 }
1232 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001233
Mathias Agopian3f844832013-08-07 21:24:32 -07001234 float left = float(win.left) / float(s.active.w);
1235 float top = float(win.top) / float(s.active.h);
1236 float right = float(win.right) / float(s.active.w);
1237 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001238
Mathias Agopian875d8e12013-06-07 15:35:48 -07001239 // TODO: we probably want to generate the texture coords with the mesh
1240 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001241 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1242 texCoords[0] = vec2(left, 1.0f - top);
1243 texCoords[1] = vec2(left, 1.0f - bottom);
1244 texCoords[2] = vec2(right, 1.0f - bottom);
1245 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001246
Mathias Agopian875d8e12013-06-07 15:35:48 -07001247 RenderEngine& engine(mFlinger->getRenderEngine());
Robert Carr6452f122017-03-21 10:41:29 -07001248 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), getAlpha());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001249#ifdef USE_HWC2
1250 engine.setSourceDataSpace(mCurrentState.dataSpace);
1251#endif
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001252 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001253 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001254}
1255
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001256#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001257void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1258 bool callIntoHwc) {
1259 if (mHwcLayers.count(hwcId) == 0) {
1260 ALOGE("setCompositionType called without a valid HWC layer");
1261 return;
1262 }
1263 auto& hwcInfo = mHwcLayers[hwcId];
1264 auto& hwcLayer = hwcInfo.layer;
1265 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1266 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1267 if (hwcInfo.compositionType != type) {
1268 ALOGV(" actually setting");
1269 hwcInfo.compositionType = type;
1270 if (callIntoHwc) {
1271 auto error = hwcLayer->setCompositionType(type);
1272 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1273 "composition type %s: %s (%d)", mName.string(),
1274 to_string(type).c_str(), to_string(error).c_str(),
1275 static_cast<int32_t>(error));
1276 }
1277 }
1278}
1279
1280HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001281 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1282 // If we're querying the composition type for a display that does not
1283 // have a HWC counterpart, then it will always be Client
1284 return HWC2::Composition::Client;
1285 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001286 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001287 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001288 return HWC2::Composition::Invalid;
1289 }
1290 return mHwcLayers.at(hwcId).compositionType;
1291}
1292
1293void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1294 if (mHwcLayers.count(hwcId) == 0) {
1295 ALOGE("setClearClientTarget called without a valid HWC layer");
1296 return;
1297 }
1298 mHwcLayers[hwcId].clearClientTarget = clear;
1299}
1300
1301bool Layer::getClearClientTarget(int32_t hwcId) const {
1302 if (mHwcLayers.count(hwcId) == 0) {
1303 ALOGE("getClearClientTarget called without a valid HWC layer");
1304 return false;
1305 }
1306 return mHwcLayers.at(hwcId).clearClientTarget;
1307}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001308#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001309
Ruben Brunk1681d952014-06-27 15:51:55 -07001310uint32_t Layer::getProducerStickyTransform() const {
1311 int producerStickyTransform = 0;
1312 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1313 if (ret != OK) {
1314 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1315 strerror(-ret), ret);
1316 return 0;
1317 }
1318 return static_cast<uint32_t>(producerStickyTransform);
1319}
1320
Dan Stozac5da2712016-07-20 15:38:12 -07001321bool Layer::latchUnsignaledBuffers() {
1322 static bool propertyLoaded = false;
1323 static bool latch = false;
1324 static std::mutex mutex;
1325 std::lock_guard<std::mutex> lock(mutex);
1326 if (!propertyLoaded) {
1327 char value[PROPERTY_VALUE_MAX] = {};
1328 property_get("debug.sf.latch_unsignaled", value, "0");
1329 latch = atoi(value);
1330 propertyLoaded = true;
1331 }
1332 return latch;
1333}
1334
Dan Stozacac35382016-01-27 12:21:06 -08001335uint64_t Layer::getHeadFrameNumber() const {
1336 Mutex::Autolock lock(mQueueItemLock);
1337 if (!mQueueItems.empty()) {
1338 return mQueueItems[0].mFrameNumber;
1339 } else {
1340 return mCurrentFrameNumber;
1341 }
1342}
1343
Dan Stoza1ce65812016-06-15 16:26:27 -07001344bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001345#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001346 if (latchUnsignaledBuffers()) {
1347 return true;
1348 }
1349
Dan Stoza1ce65812016-06-15 16:26:27 -07001350 Mutex::Autolock lock(mQueueItemLock);
1351 if (mQueueItems.empty()) {
1352 return true;
1353 }
1354 if (mQueueItems[0].mIsDroppable) {
1355 // Even though this buffer's fence may not have signaled yet, it could
1356 // be replaced by another buffer before it has a chance to, which means
1357 // that it's possible to get into a situation where a buffer is never
1358 // able to be latched. To avoid this, grab this buffer anyway.
1359 return true;
1360 }
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001361 return mQueueItems[0].mFenceTime->getSignalTime() !=
1362 Fence::SIGNAL_TIME_PENDING;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001363#else
1364 return true;
1365#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001366}
1367
Dan Stozacac35382016-01-27 12:21:06 -08001368bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1369 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1370 // Don't bother with a SyncPoint, since we've already latched the
1371 // relevant frame
1372 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001373 }
1374
Dan Stozacac35382016-01-27 12:21:06 -08001375 Mutex::Autolock lock(mLocalSyncPointMutex);
1376 mLocalSyncPoints.push_back(point);
1377 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001378}
1379
Mathias Agopian13127d82013-03-05 17:47:11 -08001380void Layer::setFiltering(bool filtering) {
1381 mFiltering = filtering;
1382}
1383
1384bool Layer::getFiltering() const {
1385 return mFiltering;
1386}
1387
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001388// As documented in libhardware header, formats in the range
1389// 0x100 - 0x1FF are specific to the HAL implementation, and
1390// are known to have no alpha channel
1391// TODO: move definition for device-specific range into
1392// hardware.h, instead of using hard-coded values here.
1393#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1394
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001395bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001396 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1397 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001398 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001399 switch (format) {
1400 case HAL_PIXEL_FORMAT_RGBA_8888:
1401 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001402 case HAL_PIXEL_FORMAT_RGBA_FP16:
Romain Guy541f2262017-02-10 18:50:17 -08001403 case HAL_PIXEL_FORMAT_RGBA_1010102:
Mathias Agopiandd533712013-07-26 15:31:39 -07001404 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001405 }
1406 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001407 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001408}
1409
Mathias Agopian13127d82013-03-05 17:47:11 -08001410// ----------------------------------------------------------------------------
1411// local state
1412// ----------------------------------------------------------------------------
1413
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001414static void boundPoint(vec2* point, const Rect& crop) {
1415 if (point->x < crop.left) {
1416 point->x = crop.left;
1417 }
1418 if (point->x > crop.right) {
1419 point->x = crop.right;
1420 }
1421 if (point->y < crop.top) {
1422 point->y = crop.top;
1423 }
1424 if (point->y > crop.bottom) {
1425 point->y = crop.bottom;
1426 }
1427}
1428
Dan Stozac7014012014-02-14 15:03:43 -08001429void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1430 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001431{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001432 const Layer::State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001433 const Transform hwTransform(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001434 const uint32_t hw_h = hw->getHeight();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001435 Rect win = computeBounds();
Mathias Agopian3f844832013-08-07 21:24:32 -07001436
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001437 vec2 lt = vec2(win.left, win.top);
1438 vec2 lb = vec2(win.left, win.bottom);
1439 vec2 rb = vec2(win.right, win.bottom);
1440 vec2 rt = vec2(win.right, win.top);
1441
Robert Carr1f0a16a2016-10-24 16:27:39 -07001442 Transform layerTransform = getTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001443 if (!useIdentityTransform) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001444 lt = layerTransform.transform(lt);
1445 lb = layerTransform.transform(lb);
1446 rb = layerTransform.transform(rb);
1447 rt = layerTransform.transform(rt);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001448 }
1449
Robert Carrb5d3d262016-03-25 15:08:13 -07001450 if (!s.finalCrop.isEmpty()) {
1451 boundPoint(&lt, s.finalCrop);
1452 boundPoint(&lb, s.finalCrop);
1453 boundPoint(&rb, s.finalCrop);
1454 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001455 }
1456
Mathias Agopianff2ed702013-09-01 21:36:12 -07001457 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001458 position[0] = hwTransform.transform(lt);
1459 position[1] = hwTransform.transform(lb);
1460 position[2] = hwTransform.transform(rb);
1461 position[3] = hwTransform.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001462 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001463 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001464 }
1465}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001466
Andy McFadden4125a4f2014-01-29 17:17:11 -08001467bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001468{
neo.hee6fd41d2017-02-17 14:35:33 +08001469 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
Mathias Agopiana67932f2011-04-20 14:20:59 -07001470 // layer's opaque flag.
neo.hee6fd41d2017-02-17 14:35:33 +08001471 if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001472 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001473 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001474
1475 // if the layer has the opaque flag, then we're always opaque,
1476 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001477 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001478}
1479
Dan Stoza23116082015-06-18 14:58:39 -07001480bool Layer::isSecure() const
1481{
1482 const Layer::State& s(mDrawingState);
1483 return (s.flags & layer_state_t::eLayerSecure);
1484}
1485
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001486bool Layer::isProtected() const
1487{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001488 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001489 return (activeBuffer != 0) &&
1490 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1491}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001492
Mathias Agopian13127d82013-03-05 17:47:11 -08001493bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001494 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001495}
1496
1497bool Layer::isCropped() const {
1498 return !mCurrentCrop.isEmpty();
1499}
1500
1501bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1502 return mNeedsFiltering || hw->needsFiltering();
1503}
1504
1505void Layer::setVisibleRegion(const Region& visibleRegion) {
1506 // always called from main thread
1507 this->visibleRegion = visibleRegion;
1508}
1509
1510void Layer::setCoveredRegion(const Region& coveredRegion) {
1511 // always called from main thread
1512 this->coveredRegion = coveredRegion;
1513}
1514
1515void Layer::setVisibleNonTransparentRegion(const Region&
1516 setVisibleNonTransparentRegion) {
1517 // always called from main thread
1518 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1519}
1520
1521// ----------------------------------------------------------------------------
1522// transaction
1523// ----------------------------------------------------------------------------
1524
Dan Stoza7dde5992015-05-22 09:51:44 -07001525void Layer::pushPendingState() {
1526 if (!mCurrentState.modified) {
1527 return;
1528 }
1529
Dan Stoza7dde5992015-05-22 09:51:44 -07001530 // If this transaction is waiting on the receipt of a frame, generate a sync
1531 // point and send it to the remote layer.
Robert Carr0d480722017-01-10 16:42:54 -08001532 if (mCurrentState.barrierLayer != nullptr) {
1533 sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1534 if (barrierLayer == nullptr) {
1535 ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
Dan Stoza7dde5992015-05-22 09:51:44 -07001536 // If we can't promote the layer we are intended to wait on,
1537 // then it is expired or otherwise invalid. Allow this transaction
1538 // to be applied as per normal (no synchronization).
Robert Carr0d480722017-01-10 16:42:54 -08001539 mCurrentState.barrierLayer = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001540 } else {
1541 auto syncPoint = std::make_shared<SyncPoint>(
1542 mCurrentState.frameNumber);
Robert Carr0d480722017-01-10 16:42:54 -08001543 if (barrierLayer->addSyncPoint(syncPoint)) {
Dan Stozacac35382016-01-27 12:21:06 -08001544 mRemoteSyncPoints.push_back(std::move(syncPoint));
1545 } else {
1546 // We already missed the frame we're supposed to synchronize
1547 // on, so go ahead and apply the state update
Robert Carr0d480722017-01-10 16:42:54 -08001548 mCurrentState.barrierLayer = nullptr;
Dan Stozacac35382016-01-27 12:21:06 -08001549 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001550 }
1551
Dan Stoza7dde5992015-05-22 09:51:44 -07001552 // Wake us up to check if the frame has been received
1553 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001554 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001555 }
1556 mPendingStates.push_back(mCurrentState);
Dan Stozaf7ba41a2017-05-10 15:11:11 -07001557 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
Dan Stoza7dde5992015-05-22 09:51:44 -07001558}
1559
Pablo Ceballos05289c22016-04-14 15:49:55 -07001560void Layer::popPendingState(State* stateToCommit) {
1561 auto oldFlags = stateToCommit->flags;
1562 *stateToCommit = mPendingStates[0];
1563 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1564 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001565
1566 mPendingStates.removeAt(0);
Dan Stozaf7ba41a2017-05-10 15:11:11 -07001567 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
Dan Stoza7dde5992015-05-22 09:51:44 -07001568}
1569
Pablo Ceballos05289c22016-04-14 15:49:55 -07001570bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001571 bool stateUpdateAvailable = false;
1572 while (!mPendingStates.empty()) {
Robert Carr0d480722017-01-10 16:42:54 -08001573 if (mPendingStates[0].barrierLayer != nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001574 if (mRemoteSyncPoints.empty()) {
1575 // If we don't have a sync point for this, apply it anyway. It
1576 // will be visually wrong, but it should keep us from getting
1577 // into too much trouble.
1578 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001579 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001580 stateUpdateAvailable = true;
1581 continue;
1582 }
1583
Dan Stozacac35382016-01-27 12:21:06 -08001584 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1585 mPendingStates[0].frameNumber) {
1586 ALOGE("[%s] Unexpected sync point frame number found",
1587 mName.string());
1588
1589 // Signal our end of the sync point and then dispose of it
1590 mRemoteSyncPoints.front()->setTransactionApplied();
1591 mRemoteSyncPoints.pop_front();
1592 continue;
1593 }
1594
Dan Stoza7dde5992015-05-22 09:51:44 -07001595 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1596 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001597 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001598 stateUpdateAvailable = true;
1599
1600 // Signal our end of the sync point and then dispose of it
1601 mRemoteSyncPoints.front()->setTransactionApplied();
1602 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001603 } else {
1604 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001605 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001606 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001607 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001608 stateUpdateAvailable = true;
1609 }
1610 }
1611
1612 // If we still have pending updates, wake SurfaceFlinger back up and point
1613 // it at this layer so we can process them
1614 if (!mPendingStates.empty()) {
1615 setTransactionFlags(eTransactionNeeded);
1616 mFlinger->setTransactionFlags(eTraversalNeeded);
1617 }
1618
1619 mCurrentState.modified = false;
1620 return stateUpdateAvailable;
1621}
1622
1623void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001624 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001625 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001626 Mutex::Autolock lock(mLocalSyncPointMutex);
1627 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001628 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001629 point->setFrameAvailable();
1630 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001631 }
1632}
1633
Mathias Agopian13127d82013-03-05 17:47:11 -08001634uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001635 ATRACE_CALL();
1636
Dan Stoza7dde5992015-05-22 09:51:44 -07001637 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001638 Layer::State c = getCurrentState();
1639 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001640 return 0;
1641 }
1642
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001643 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001644
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001645 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1646 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001647
1648 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001649 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001650 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001651 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001652 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001653 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001654 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001655 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001656 this, getName().string(), mCurrentTransform,
1657 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001658 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001659 c.crop.left,
1660 c.crop.top,
1661 c.crop.right,
1662 c.crop.bottom,
1663 c.crop.getWidth(),
1664 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001665 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001666 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001667 s.crop.left,
1668 s.crop.top,
1669 s.crop.right,
1670 s.crop.bottom,
1671 s.crop.getWidth(),
1672 s.crop.getHeight(),
1673 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001674
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001675 // record the new size, form this point on, when the client request
1676 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001677 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001678 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001679 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001680
Robert Carr82364e32016-05-15 11:27:47 -07001681 const bool resizePending = (c.requested.w != c.active.w) ||
1682 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001683 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001684 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001685 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001686 // if we have a pending resize, unless we are in fixed-size mode.
1687 // the drawing state will be updated only once we receive a buffer
1688 // with the correct size.
1689 //
1690 // in particular, we want to make sure the clip (which is part
1691 // of the geometry state) is latched together with the size but is
1692 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001693 //
1694 // If a sideband stream is attached, however, we want to skip this
1695 // optimization so that transactions aren't missed when a buffer
1696 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001697
1698 flags |= eDontUpdateGeometryState;
1699 }
1700 }
1701
Robert Carr7bf247e2017-05-18 14:02:49 -07001702 // Here we apply various requested geometry states, depending on our
1703 // latching configuration. See Layer.h for a detailed discussion of
1704 // how geometry latching is controlled.
1705 if (!(flags & eDontUpdateGeometryState)) {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001706 Layer::State& editCurrentState(getCurrentState());
Robert Carr7bf247e2017-05-18 14:02:49 -07001707
1708 // If mFreezeGeometryUpdates is true we are in the setGeometryAppliesWithResize
1709 // mode, which causes attributes which normally latch regardless of scaling mode,
1710 // to be delayed. We copy the requested state to the active state making sure
1711 // to respect these rules (again see Layer.h for a detailed discussion).
1712 //
1713 // There is an awkward asymmetry in the handling of the crop states in the position
1714 // states, as can be seen below. Largely this arises from position and transform
1715 // being stored in the same data structure while having different latching rules.
1716 // b/38182305
1717 //
1718 // Careful that "c" and editCurrentState may not begin as equivalent due to
1719 // applyPendingStates in the presence of deferred transactions.
1720 if (mFreezeGeometryUpdates) {
Robert Carr82364e32016-05-15 11:27:47 -07001721 float tx = c.active.transform.tx();
1722 float ty = c.active.transform.ty();
1723 c.active = c.requested;
1724 c.active.transform.set(tx, ty);
1725 editCurrentState.active = c.active;
1726 } else {
1727 editCurrentState.active = editCurrentState.requested;
1728 c.active = c.requested;
1729 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001730 }
1731
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001732 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001733 // invalidate and recompute the visible regions if needed
1734 flags |= Layer::eVisibleRegion;
1735 }
1736
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001737 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001738 // invalidate and recompute the visible regions if needed
1739 flags |= eVisibleRegion;
1740 this->contentDirty = true;
1741
1742 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001743 const uint8_t type = c.active.transform.getType();
1744 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001745 (type >= Transform::SCALE));
1746 }
1747
Dan Stozac8145172016-04-28 16:29:06 -07001748 // If the layer is hidden, signal and clear out all local sync points so
1749 // that transactions for layers depending on this layer's frames becoming
1750 // visible are not blocked
1751 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001752 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001753 }
1754
Mathias Agopian13127d82013-03-05 17:47:11 -08001755 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001756 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001757 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001758}
1759
Pablo Ceballos05289c22016-04-14 15:49:55 -07001760void Layer::commitTransaction(const State& stateToCommit) {
1761 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001762}
1763
Mathias Agopian13127d82013-03-05 17:47:11 -08001764uint32_t Layer::getTransactionFlags(uint32_t flags) {
1765 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1766}
1767
1768uint32_t Layer::setTransactionFlags(uint32_t flags) {
1769 return android_atomic_or(flags, &mTransactionFlags);
1770}
1771
Robert Carr82364e32016-05-15 11:27:47 -07001772bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001773 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001774 return false;
1775 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001776
1777 // We update the requested and active position simultaneously because
1778 // we want to apply the position portion of the transform matrix immediately,
1779 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001780 mCurrentState.requested.transform.set(x, y);
Robert Carr7bf247e2017-05-18 14:02:49 -07001781 if (immediate && !mFreezeGeometryUpdates) {
1782 // Here we directly update the active state
1783 // unlike other setters, because we store it within
1784 // the transform, but use different latching rules.
1785 // b/38182305
Robert Carr82364e32016-05-15 11:27:47 -07001786 mCurrentState.active.transform.set(x, y);
1787 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001788 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001789
Dan Stoza7dde5992015-05-22 09:51:44 -07001790 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001791 setTransactionFlags(eTransactionNeeded);
1792 return true;
1793}
Robert Carr82364e32016-05-15 11:27:47 -07001794
Robert Carr1f0a16a2016-10-24 16:27:39 -07001795bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1796 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1797 if (idx < 0) {
1798 return false;
1799 }
1800 if (childLayer->setLayer(z)) {
1801 mCurrentChildren.removeAt(idx);
1802 mCurrentChildren.add(childLayer);
1803 }
1804 return true;
1805}
1806
Robert Carrae060832016-11-28 10:51:00 -08001807bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001808 if (mCurrentState.z == z)
1809 return false;
1810 mCurrentState.sequence++;
1811 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001812 mCurrentState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001813
1814 // Discard all relative layering.
1815 if (mCurrentState.zOrderRelativeOf != nullptr) {
1816 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1817 if (strongRelative != nullptr) {
1818 strongRelative->removeZOrderRelative(this);
1819 }
1820 mCurrentState.zOrderRelativeOf = nullptr;
1821 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001822 setTransactionFlags(eTransactionNeeded);
1823 return true;
1824}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001825
Robert Carrdb66e622017-04-10 16:55:57 -07001826void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1827 mCurrentState.zOrderRelatives.remove(relative);
1828 mCurrentState.sequence++;
1829 mCurrentState.modified = true;
1830 setTransactionFlags(eTransactionNeeded);
1831}
1832
1833void Layer::addZOrderRelative(const wp<Layer>& relative) {
1834 mCurrentState.zOrderRelatives.add(relative);
1835 mCurrentState.modified = true;
1836 mCurrentState.sequence++;
1837 setTransactionFlags(eTransactionNeeded);
1838}
1839
1840bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1841 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1842 if (handle == nullptr) {
1843 return false;
1844 }
1845 sp<Layer> relative = handle->owner.promote();
1846 if (relative == nullptr) {
1847 return false;
1848 }
1849
1850 mCurrentState.sequence++;
1851 mCurrentState.modified = true;
1852 mCurrentState.z = z;
1853
1854 mCurrentState.zOrderRelativeOf = relative;
1855 relative->addZOrderRelative(this);
1856
1857 setTransactionFlags(eTransactionNeeded);
1858
1859 return true;
1860}
1861
Mathias Agopian13127d82013-03-05 17:47:11 -08001862bool Layer::setSize(uint32_t w, uint32_t h) {
1863 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1864 return false;
1865 mCurrentState.requested.w = w;
1866 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001867 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001868 setTransactionFlags(eTransactionNeeded);
1869 return true;
1870}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001871#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001872bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001873#else
1874bool Layer::setAlpha(uint8_t alpha) {
1875#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001876 if (mCurrentState.alpha == alpha)
1877 return false;
1878 mCurrentState.sequence++;
1879 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001880 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001881 setTransactionFlags(eTransactionNeeded);
1882 return true;
1883}
1884bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1885 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001886 mCurrentState.requested.transform.set(
Robert Carrcb6e1e32017-02-21 19:48:26 -08001887 matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001888 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001889 setTransactionFlags(eTransactionNeeded);
1890 return true;
1891}
1892bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001893 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001894 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001895 setTransactionFlags(eTransactionNeeded);
1896 return true;
1897}
1898bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1899 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1900 if (mCurrentState.flags == newFlags)
1901 return false;
1902 mCurrentState.sequence++;
1903 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001904 mCurrentState.mask = mask;
1905 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001906 setTransactionFlags(eTransactionNeeded);
1907 return true;
1908}
Robert Carr99e27f02016-06-16 15:18:02 -07001909
1910bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001911 if (mCurrentState.requestedCrop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001912 return false;
1913 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001914 mCurrentState.requestedCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001915 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr99e27f02016-06-16 15:18:02 -07001916 mCurrentState.crop = crop;
1917 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001918 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1919
Dan Stoza7dde5992015-05-22 09:51:44 -07001920 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001921 setTransactionFlags(eTransactionNeeded);
1922 return true;
1923}
Robert Carr8d5227b2017-03-16 15:41:03 -07001924
1925bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
Robert Carr7bf247e2017-05-18 14:02:49 -07001926 if (mCurrentState.requestedFinalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001927 return false;
1928 mCurrentState.sequence++;
Robert Carr8d5227b2017-03-16 15:41:03 -07001929 mCurrentState.requestedFinalCrop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001930 if (immediate && !mFreezeGeometryUpdates) {
Robert Carr8d5227b2017-03-16 15:41:03 -07001931 mCurrentState.finalCrop = crop;
1932 }
Robert Carr7bf247e2017-05-18 14:02:49 -07001933 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1934
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001935 mCurrentState.modified = true;
1936 setTransactionFlags(eTransactionNeeded);
1937 return true;
1938}
Mathias Agopian13127d82013-03-05 17:47:11 -08001939
Robert Carrc3574f72016-03-24 12:19:32 -07001940bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1941 if (scalingMode == mOverrideScalingMode)
1942 return false;
1943 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001944 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001945 return true;
1946}
1947
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001948void Layer::setInfo(uint32_t type, uint32_t appId) {
1949 mCurrentState.appId = appId;
1950 mCurrentState.type = type;
1951 mCurrentState.modified = true;
1952 setTransactionFlags(eTransactionNeeded);
1953}
1954
Robert Carrc3574f72016-03-24 12:19:32 -07001955uint32_t Layer::getEffectiveScalingMode() const {
1956 if (mOverrideScalingMode >= 0) {
1957 return mOverrideScalingMode;
1958 }
1959 return mCurrentScalingMode;
1960}
1961
Mathias Agopian13127d82013-03-05 17:47:11 -08001962bool Layer::setLayerStack(uint32_t layerStack) {
1963 if (mCurrentState.layerStack == layerStack)
1964 return false;
1965 mCurrentState.sequence++;
1966 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001967 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001968 setTransactionFlags(eTransactionNeeded);
1969 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001970}
1971
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07001972bool Layer::setDataSpace(android_dataspace dataSpace) {
1973 if (mCurrentState.dataSpace == dataSpace)
1974 return false;
1975 mCurrentState.sequence++;
1976 mCurrentState.dataSpace = dataSpace;
1977 mCurrentState.modified = true;
1978 setTransactionFlags(eTransactionNeeded);
1979 return true;
1980}
1981
Courtney Goeltzenleuchter532b2632017-05-05 16:34:38 -06001982android_dataspace Layer::getDataSpace() const {
1983 return mCurrentState.dataSpace;
1984}
1985
Robert Carr1f0a16a2016-10-24 16:27:39 -07001986uint32_t Layer::getLayerStack() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07001987 auto p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001988 if (p == nullptr) {
1989 return getDrawingState().layerStack;
1990 }
1991 return p->getLayerStack();
1992}
1993
Robert Carr0d480722017-01-10 16:42:54 -08001994void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
Dan Stoza7dde5992015-05-22 09:51:44 -07001995 uint64_t frameNumber) {
Robert Carr0d480722017-01-10 16:42:54 -08001996 mCurrentState.barrierLayer = barrierLayer;
Dan Stoza7dde5992015-05-22 09:51:44 -07001997 mCurrentState.frameNumber = frameNumber;
1998 // We don't set eTransactionNeeded, because just receiving a deferral
1999 // request without any other state updates shouldn't actually induce a delay
2000 mCurrentState.modified = true;
2001 pushPendingState();
Robert Carr0d480722017-01-10 16:42:54 -08002002 mCurrentState.barrierLayer = nullptr;
Dan Stoza792e5292016-02-11 11:43:58 -08002003 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07002004 mCurrentState.modified = false;
Robert Carr0d480722017-01-10 16:42:54 -08002005}
2006
2007void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
2008 uint64_t frameNumber) {
2009 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
2010 deferTransactionUntil(handle->owner.promote(), frameNumber);
Dan Stoza7dde5992015-05-22 09:51:44 -07002011}
2012
Dan Stozaee44edd2015-03-23 15:50:23 -07002013void Layer::useSurfaceDamage() {
2014 if (mFlinger->mForceFullDamage) {
2015 surfaceDamageRegion = Region::INVALID_REGION;
2016 } else {
2017 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
2018 }
2019}
2020
2021void Layer::useEmptyDamage() {
2022 surfaceDamageRegion.clear();
2023}
2024
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002025// ----------------------------------------------------------------------------
2026// pageflip handling...
2027// ----------------------------------------------------------------------------
2028
Dan Stoza6b9454d2014-11-07 16:00:59 -08002029bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08002030 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07002031 return true;
2032 }
2033
Dan Stoza6b9454d2014-11-07 16:00:59 -08002034 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07002035 if (mQueueItems.empty()) {
2036 return false;
2037 }
2038 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002039 nsecs_t expectedPresent =
2040 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07002041
2042 // Ignore timestamps more than a second in the future
2043 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
2044 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
2045 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
2046 expectedPresent);
2047
2048 bool isDue = timestamp < expectedPresent;
2049 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002050}
2051
Brian Andersond6927fb2016-07-23 23:37:30 -07002052bool Layer::onPreComposition(nsecs_t refreshStartTime) {
2053 if (mBufferLatched) {
2054 Mutex::Autolock lock(mFrameEventHistoryMutex);
2055 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
2056 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08002057 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08002058 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002059}
2060
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002061bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
Brian Anderson3d4039d2016-09-23 16:31:30 -07002062 const std::shared_ptr<FenceTime>& presentFence,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002063 const CompositorTiming& compositorTiming) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002064 // mFrameLatencyNeeded is true when a new frame was latched for the
2065 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08002066 if (!mFrameLatencyNeeded)
2067 return false;
2068
Fabien Sanglard28e98082016-12-05 10:19:46 -08002069 // Update mFrameEventHistory.
2070 {
2071 Mutex::Autolock lock(mFrameEventHistoryMutex);
2072 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002073 glDoneFence, presentFence, compositorTiming);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002074 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08002075
2076 // Update mFrameTracker.
2077 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
2078 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
2079
Brian Anderson3d4039d2016-09-23 16:31:30 -07002080 std::shared_ptr<FenceTime> frameReadyFence =
2081 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08002082 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002083 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002084 } else {
2085 // There was no fence for this frame, so assume that it was ready
2086 // to be presented at the desired present time.
2087 mFrameTracker.setFrameReadyTime(desiredPresentTime);
2088 }
2089
Brian Anderson3d4039d2016-09-23 16:31:30 -07002090 if (presentFence->isValid()) {
2091 mFrameTracker.setActualPresentFence(
2092 std::shared_ptr<FenceTime>(presentFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002093 } else {
2094 // The HWC doesn't support present fences, so use the refresh
2095 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002096 mFrameTracker.setActualPresentTime(
2097 mFlinger->getHwComposer().getRefreshTimestamp(
2098 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08002099 }
2100
2101 mFrameTracker.advanceFrame();
2102 mFrameLatencyNeeded = false;
2103 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07002104}
2105
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002106#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07002107void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Brian Anderson5ea5e592016-12-01 16:54:33 -08002108 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2109 return;
2110 }
2111
Brian Anderson3d4039d2016-09-23 16:31:30 -07002112 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002113 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002114 mReleaseTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002115 mReleaseTimeline.push(releaseFenceTime);
2116
2117 Mutex::Autolock lock(mFrameEventHistoryMutex);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002118 if (mPreviousFrameNumber != 0) {
2119 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2120 dequeueReadyTime, std::move(releaseFenceTime));
2121 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002122}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002123#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002124
Robert Carr1f0a16a2016-10-24 16:27:39 -07002125bool Layer::isHiddenByPolicy() const {
2126 const Layer::State& s(mDrawingState);
Chia-I Wue41dbe62017-06-13 14:10:56 -07002127 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002128 if (parent != nullptr && parent->isHiddenByPolicy()) {
2129 return true;
2130 }
2131 return s.flags & layer_state_t::eLayerHidden;
2132}
2133
Mathias Agopianda27af92012-09-13 18:17:13 -07002134bool Layer::isVisible() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002135#ifdef USE_HWC2
Robert Carr6452f122017-03-21 10:41:29 -07002136 return !(isHiddenByPolicy()) && getAlpha() > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08002137 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002138#else
Robert Carr6452f122017-03-21 10:41:29 -07002139 return !(isHiddenByPolicy()) && getAlpha()
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002140 && (mActiveBuffer != NULL || mSidebandStream != NULL);
2141#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07002142}
2143
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002144bool Layer::allTransactionsSignaled() {
2145 auto headFrameNumber = getHeadFrameNumber();
2146 bool matchingFramesFound = false;
2147 bool allTransactionsApplied = true;
2148 Mutex::Autolock lock(mLocalSyncPointMutex);
2149
2150 for (auto& point : mLocalSyncPoints) {
2151 if (point->getFrameNumber() > headFrameNumber) {
2152 break;
2153 }
2154 matchingFramesFound = true;
2155
2156 if (!point->frameIsAvailable()) {
2157 // We haven't notified the remote layer that the frame for
2158 // this point is available yet. Notify it now, and then
2159 // abort this attempt to latch.
2160 point->setFrameAvailable();
2161 allTransactionsApplied = false;
2162 break;
2163 }
2164
2165 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2166 }
2167 return !matchingFramesFound || allTransactionsApplied;
2168}
2169
Brian Andersond6927fb2016-07-23 23:37:30 -07002170Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002171{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08002172 ATRACE_CALL();
2173
Jesse Hall399184a2014-03-03 15:42:54 -08002174 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2175 // mSidebandStreamChanged was true
2176 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07002177 if (mSidebandStream != NULL) {
2178 setTransactionFlags(eTransactionNeeded);
2179 mFlinger->setTransactionFlags(eTraversalNeeded);
2180 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07002181 recomputeVisibleRegions = true;
2182
2183 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07002184 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08002185 }
2186
Mathias Agopian4fec8732012-06-29 14:12:52 -07002187 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07002188 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2189 return outDirtyRegion;
2190 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002191
Fabien Sanglard223eb912016-10-13 10:15:06 -07002192 // if we've already called updateTexImage() without going through
2193 // a composition step, we have to skip this layer at this point
2194 // because we cannot call updateTeximage() without a corresponding
2195 // compositionComplete() call.
2196 // we'll trigger an update in onPreComposition().
2197 if (mRefreshPending) {
2198 return outDirtyRegion;
2199 }
2200
2201 // If the head buffer's acquire fence hasn't signaled yet, return and
2202 // try again later
2203 if (!headFenceHasSignaled()) {
2204 mFlinger->signalLayerUpdate();
2205 return outDirtyRegion;
2206 }
2207
2208 // Capture the old state of the layer for comparisons later
2209 const State& s(getDrawingState());
2210 const bool oldOpacity = isOpaque(s);
2211 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2212
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002213 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002214 mFlinger->signalLayerUpdate();
2215 return outDirtyRegion;
2216 }
2217
2218 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2219 // of the buffer queue isn't modified when the buffer queue is returning
2220 // BufferItem's that weren't actually queued. This can happen in shared
2221 // buffer mode.
2222 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002223 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2224 getProducerStickyTransform() != 0, mName.string(),
Robert Carr7bf247e2017-05-18 14:02:49 -07002225 mOverrideScalingMode, mFreezeGeometryUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002226 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2227 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2228 mLastFrameNumberReceived);
2229 if (updateResult == BufferQueue::PRESENT_LATER) {
2230 // Producer doesn't want buffer to be displayed yet. Signal a
2231 // layer update so we check again at the next opportunity.
2232 mFlinger->signalLayerUpdate();
2233 return outDirtyRegion;
2234 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2235 // If the buffer has been rejected, remove it from the shadow queue
2236 // and return early
2237 if (queuedBuffer) {
2238 Mutex::Autolock lock(mQueueItemLock);
2239 mQueueItems.removeAt(0);
2240 android_atomic_dec(&mQueuedFrames);
2241 }
2242 return outDirtyRegion;
2243 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2244 // This can occur if something goes wrong when trying to create the
2245 // EGLImage for this buffer. If this happens, the buffer has already
2246 // been released, so we need to clean up the queue and bug out
2247 // early.
2248 if (queuedBuffer) {
2249 Mutex::Autolock lock(mQueueItemLock);
2250 mQueueItems.clear();
2251 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002252 }
2253
Fabien Sanglard223eb912016-10-13 10:15:06 -07002254 // Once we have hit this state, the shadow queue may no longer
2255 // correctly reflect the incoming BufferQueue's contents, so even if
2256 // updateTexImage starts working, the only safe course of action is
2257 // to continue to ignore updates.
2258 mUpdateTexImageFailed = true;
2259
2260 return outDirtyRegion;
2261 }
2262
2263 if (queuedBuffer) {
2264 // Autolock scope
2265 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2266
2267 Mutex::Autolock lock(mQueueItemLock);
2268
2269 // Remove any stale buffers that have been dropped during
2270 // updateTexImage
2271 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2272 mQueueItems.removeAt(0);
2273 android_atomic_dec(&mQueuedFrames);
2274 }
2275
2276 mQueueItems.removeAt(0);
2277 }
2278
2279
2280 // Decrement the queued-frames count. Signal another event if we
2281 // have more frames pending.
2282 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2283 || mAutoRefresh) {
2284 mFlinger->signalLayerUpdate();
2285 }
2286
Fabien Sanglard223eb912016-10-13 10:15:06 -07002287 // update the active buffer
Chia-I Wu06d63de2017-01-04 14:58:51 +08002288 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2289 &mActiveBufferSlot);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002290 if (mActiveBuffer == NULL) {
2291 // this can only happen if the very first buffer was rejected.
2292 return outDirtyRegion;
2293 }
2294
Brian Andersond6927fb2016-07-23 23:37:30 -07002295 mBufferLatched = true;
2296 mPreviousFrameNumber = mCurrentFrameNumber;
2297 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2298
2299 {
2300 Mutex::Autolock lock(mFrameEventHistoryMutex);
2301 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2302#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002303 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002304 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002305 mReleaseTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002306 mReleaseTimeline.push(releaseFenceTime);
Brian Anderson8cc8b102016-10-21 12:43:09 -07002307 if (mPreviousFrameNumber != 0) {
2308 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2309 latchTime, std::move(releaseFenceTime));
2310 }
Brian Andersond6927fb2016-07-23 23:37:30 -07002311#endif
2312 }
2313
Fabien Sanglard223eb912016-10-13 10:15:06 -07002314 mRefreshPending = true;
2315 mFrameLatencyNeeded = true;
2316 if (oldActiveBuffer == NULL) {
2317 // the first time we receive a buffer, we need to trigger a
2318 // geometry invalidation.
2319 recomputeVisibleRegions = true;
2320 }
2321
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002322 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2323
Fabien Sanglard223eb912016-10-13 10:15:06 -07002324 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2325 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2326 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2327 if ((crop != mCurrentCrop) ||
2328 (transform != mCurrentTransform) ||
2329 (scalingMode != mCurrentScalingMode))
2330 {
2331 mCurrentCrop = crop;
2332 mCurrentTransform = transform;
2333 mCurrentScalingMode = scalingMode;
2334 recomputeVisibleRegions = true;
2335 }
2336
2337 if (oldActiveBuffer != NULL) {
2338 uint32_t bufWidth = mActiveBuffer->getWidth();
2339 uint32_t bufHeight = mActiveBuffer->getHeight();
2340 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2341 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002342 recomputeVisibleRegions = true;
2343 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002344 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002345
Fabien Sanglard223eb912016-10-13 10:15:06 -07002346 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2347 if (oldOpacity != isOpaque(s)) {
2348 recomputeVisibleRegions = true;
2349 }
Dan Stozacac35382016-01-27 12:21:06 -08002350
Fabien Sanglard223eb912016-10-13 10:15:06 -07002351 // Remove any sync points corresponding to the buffer which was just
2352 // latched
2353 {
2354 Mutex::Autolock lock(mLocalSyncPointMutex);
2355 auto point = mLocalSyncPoints.begin();
2356 while (point != mLocalSyncPoints.end()) {
2357 if (!(*point)->frameIsAvailable() ||
2358 !(*point)->transactionIsApplied()) {
2359 // This sync point must have been added since we started
2360 // latching. Don't drop it yet.
2361 ++point;
2362 continue;
2363 }
2364
2365 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2366 point = mLocalSyncPoints.erase(point);
2367 } else {
2368 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002369 }
2370 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002371 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002372
2373 // FIXME: postedRegion should be dirty & bounds
2374 Region dirtyRegion(Rect(s.active.w, s.active.h));
2375
2376 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002377 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002378
Mathias Agopian4fec8732012-06-29 14:12:52 -07002379 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002380}
2381
Mathias Agopiana67932f2011-04-20 14:20:59 -07002382uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002383{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002384 // TODO: should we do something special if mSecure is set?
2385 if (mProtectedByApp) {
2386 // need a hardware-protected path to external video sink
2387 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002388 }
Riley Andrews03414a12014-07-01 14:22:59 -07002389 if (mPotentialCursor) {
2390 usage |= GraphicBuffer::USAGE_CURSOR;
2391 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002392 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002393 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002394}
2395
Mathias Agopian84300952012-11-21 16:02:13 -08002396void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002397 uint32_t orientation = 0;
2398 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002399 // The transform hint is used to improve performance, but we can
2400 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002401 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002402 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002403 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002404 if (orientation & Transform::ROT_INVALID) {
2405 orientation = 0;
2406 }
2407 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002408 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002409}
2410
Mathias Agopian13127d82013-03-05 17:47:11 -08002411// ----------------------------------------------------------------------------
2412// debugging
2413// ----------------------------------------------------------------------------
2414
Kalle Raitaa099a242017-01-11 11:17:29 -08002415LayerDebugInfo Layer::getLayerDebugInfo() const {
2416 LayerDebugInfo info;
2417 const Layer::State& ds = getDrawingState();
2418 info.mName = getName();
chaviw1acbec72017-07-27 15:28:26 -07002419 sp<Layer> parent = getParent();
Kalle Raitaa099a242017-01-11 11:17:29 -08002420 info.mParentName = (parent == nullptr ? std::string("none") : parent->getName().string());
2421 info.mType = String8(getTypeId());
2422 info.mTransparentRegion = ds.activeTransparentRegion;
2423 info.mVisibleRegion = visibleRegion;
2424 info.mSurfaceDamageRegion = surfaceDamageRegion;
2425 info.mLayerStack = getLayerStack();
2426 info.mX = ds.active.transform.tx();
2427 info.mY = ds.active.transform.ty();
2428 info.mZ = ds.z;
2429 info.mWidth = ds.active.w;
2430 info.mHeight = ds.active.h;
2431 info.mCrop = ds.crop;
2432 info.mFinalCrop = ds.finalCrop;
2433 info.mAlpha = ds.alpha;
2434 info.mFlags = ds.flags;
2435 info.mPixelFormat = getPixelFormat();
2436 info.mDataSpace = getDataSpace();
2437 info.mMatrix[0][0] = ds.active.transform[0][0];
2438 info.mMatrix[0][1] = ds.active.transform[0][1];
2439 info.mMatrix[1][0] = ds.active.transform[1][0];
2440 info.mMatrix[1][1] = ds.active.transform[1][1];
2441 {
2442 sp<const GraphicBuffer> activeBuffer = getActiveBuffer();
2443 if (activeBuffer != 0) {
2444 info.mActiveBufferWidth = activeBuffer->getWidth();
2445 info.mActiveBufferHeight = activeBuffer->getHeight();
2446 info.mActiveBufferStride = activeBuffer->getStride();
2447 info.mActiveBufferFormat = activeBuffer->format;
2448 } else {
2449 info.mActiveBufferWidth = 0;
2450 info.mActiveBufferHeight = 0;
2451 info.mActiveBufferStride = 0;
2452 info.mActiveBufferFormat = 0;
2453 }
Mathias Agopian13127d82013-03-05 17:47:11 -08002454 }
Kalle Raitaa099a242017-01-11 11:17:29 -08002455 info.mNumQueuedFrames = getQueuedFrameCount();
2456 info.mRefreshPending = isBufferLatched();
2457 info.mIsOpaque = isOpaque(ds);
2458 info.mContentDirty = contentDirty;
2459 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08002460}
2461
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002462#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002463void Layer::miniDumpHeader(String8& result) {
2464 result.append("----------------------------------------");
2465 result.append("---------------------------------------\n");
2466 result.append(" Layer name\n");
2467 result.append(" Z | ");
2468 result.append(" Comp Type | ");
2469 result.append(" Disp Frame (LTRB) | ");
2470 result.append(" Source Crop (LTRB)\n");
2471 result.append("----------------------------------------");
2472 result.append("---------------------------------------\n");
2473}
2474
2475void Layer::miniDump(String8& result, int32_t hwcId) const {
2476 if (mHwcLayers.count(hwcId) == 0) {
2477 return;
2478 }
2479
2480 String8 name;
2481 if (mName.length() > 77) {
2482 std::string shortened;
2483 shortened.append(mName.string(), 36);
2484 shortened.append("[...]");
2485 shortened.append(mName.string() + (mName.length() - 36), 36);
2486 name = shortened.c_str();
2487 } else {
2488 name = mName;
2489 }
2490
2491 result.appendFormat(" %s\n", name.string());
2492
2493 const Layer::State& layerState(getDrawingState());
2494 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2495 result.appendFormat(" %10u | ", layerState.z);
2496 result.appendFormat("%10s | ",
2497 to_string(getCompositionType(hwcId)).c_str());
2498 const Rect& frame = hwcInfo.displayFrame;
2499 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2500 frame.right, frame.bottom);
Dan Stoza5a423ea2017-02-16 14:10:39 -08002501 const FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002502 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2503 crop.right, crop.bottom);
2504
2505 result.append("- - - - - - - - - - - - - - - - - - - - ");
2506 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2507}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002508#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002509
Svetoslavd85084b2014-03-20 10:28:31 -07002510void Layer::dumpFrameStats(String8& result) const {
2511 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002512}
2513
Svetoslavd85084b2014-03-20 10:28:31 -07002514void Layer::clearFrameStats() {
2515 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002516}
2517
Jamie Gennis6547ff42013-07-16 20:12:42 -07002518void Layer::logFrameStats() {
2519 mFrameTracker.logAndResetStats(mName);
2520}
2521
Svetoslavd85084b2014-03-20 10:28:31 -07002522void Layer::getFrameStats(FrameStats* outStats) const {
2523 mFrameTracker.getStats(outStats);
2524}
2525
Brian Andersond6927fb2016-07-23 23:37:30 -07002526void Layer::dumpFrameEvents(String8& result) {
2527 result.appendFormat("- Layer %s (%s, %p)\n",
2528 getName().string(), getTypeId(), this);
2529 Mutex::Autolock lock(mFrameEventHistoryMutex);
2530 mFrameEventHistory.checkFencesForCompletion();
2531 mFrameEventHistory.dump(result);
2532}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002533
Brian Anderson5ea5e592016-12-01 16:54:33 -08002534void Layer::onDisconnect() {
2535 Mutex::Autolock lock(mFrameEventHistoryMutex);
2536 mFrameEventHistory.onDisconnect();
2537}
2538
Brian Anderson3890c392016-07-25 12:48:08 -07002539void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2540 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002541 Mutex::Autolock lock(mFrameEventHistoryMutex);
2542 if (newTimestamps) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002543 // If there are any unsignaled fences in the aquire timeline at this
2544 // point, the previously queued frame hasn't been latched yet. Go ahead
2545 // and try to get the signal time here so the syscall is taken out of
2546 // the main thread's critical path.
2547 mAcquireTimeline.updateSignalTimes();
2548 // Push the new fence after updating since it's likely still pending.
Brian Anderson3d4039d2016-09-23 16:31:30 -07002549 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002550 mFrameEventHistory.addQueue(*newTimestamps);
2551 }
2552
Brian Anderson3890c392016-07-25 12:48:08 -07002553 if (outDelta) {
2554 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002555 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002556}
Dan Stozae77c7662016-05-13 11:37:28 -07002557
2558std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2559 bool forceFlush) {
2560 std::vector<OccupancyTracker::Segment> history;
2561 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2562 &history);
2563 if (result != NO_ERROR) {
2564 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2565 result);
2566 return {};
2567 }
2568 return history;
2569}
2570
Robert Carr367c5682016-06-20 11:55:28 -07002571bool Layer::getTransformToDisplayInverse() const {
2572 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2573}
2574
Chia-I Wu98f1c102017-05-30 14:54:08 -07002575size_t Layer::getChildrenCount() const {
2576 size_t count = 0;
2577 for (const sp<Layer>& child : mCurrentChildren) {
2578 count += 1 + child->getChildrenCount();
2579 }
2580 return count;
2581}
2582
Robert Carr1f0a16a2016-10-24 16:27:39 -07002583void Layer::addChild(const sp<Layer>& layer) {
2584 mCurrentChildren.add(layer);
2585 layer->setParent(this);
2586}
2587
2588ssize_t Layer::removeChild(const sp<Layer>& layer) {
2589 layer->setParent(nullptr);
2590 return mCurrentChildren.remove(layer);
2591}
2592
Robert Carr1db73f62016-12-21 12:58:51 -08002593bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2594 sp<Handle> handle = nullptr;
2595 sp<Layer> newParent = nullptr;
2596 if (newParentHandle == nullptr) {
2597 return false;
2598 }
2599 handle = static_cast<Handle*>(newParentHandle.get());
2600 newParent = handle->owner.promote();
2601 if (newParent == nullptr) {
2602 ALOGE("Unable to promote Layer handle");
2603 return false;
2604 }
2605
2606 for (const sp<Layer>& child : mCurrentChildren) {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002607 newParent->addChild(child);
Robert Carr1db73f62016-12-21 12:58:51 -08002608
2609 sp<Client> client(child->mClientRef.promote());
2610 if (client != nullptr) {
2611 client->setParentLayer(newParent);
2612 }
2613 }
2614 mCurrentChildren.clear();
2615
2616 return true;
2617}
2618
Robert Carr9524cb32017-02-13 11:32:32 -08002619bool Layer::detachChildren() {
Dan Stoza412903f2017-04-27 13:42:17 -07002620 traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
Robert Carr9524cb32017-02-13 11:32:32 -08002621 if (child == this) {
2622 return;
2623 }
2624
2625 sp<Client> client(child->mClientRef.promote());
2626 if (client != nullptr) {
2627 client->detachLayer(child);
2628 }
2629 });
2630
2631 return true;
2632}
2633
Robert Carr1f0a16a2016-10-24 16:27:39 -07002634void Layer::setParent(const sp<Layer>& layer) {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002635 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002636}
2637
2638void Layer::clearSyncPoints() {
2639 for (const auto& child : mCurrentChildren) {
2640 child->clearSyncPoints();
2641 }
2642
2643 Mutex::Autolock lock(mLocalSyncPointMutex);
2644 for (auto& point : mLocalSyncPoints) {
2645 point->setFrameAvailable();
2646 }
2647 mLocalSyncPoints.clear();
2648}
2649
2650int32_t Layer::getZ() const {
2651 return mDrawingState.z;
2652}
2653
Dan Stoza412903f2017-04-27 13:42:17 -07002654LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2655 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2656 "makeTraversalList received invalid stateSet");
2657 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2658 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2659 const State& state = useDrawing ? mDrawingState : mCurrentState;
2660
2661 if (state.zOrderRelatives.size() == 0) {
2662 return children;
Robert Carrdb66e622017-04-10 16:55:57 -07002663 }
2664 LayerVector traverse;
2665
Dan Stoza412903f2017-04-27 13:42:17 -07002666 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07002667 sp<Layer> strongRelative = weakRelative.promote();
2668 if (strongRelative != nullptr) {
2669 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07002670 }
2671 }
2672
Dan Stoza412903f2017-04-27 13:42:17 -07002673 for (const sp<Layer>& child : children) {
Robert Carrdb66e622017-04-10 16:55:57 -07002674 traverse.add(child);
2675 }
2676
2677 return traverse;
2678}
2679
Robert Carr1f0a16a2016-10-24 16:27:39 -07002680/**
Robert Carrdb66e622017-04-10 16:55:57 -07002681 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002682 */
Dan Stoza412903f2017-04-27 13:42:17 -07002683void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2684 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002685
Robert Carr1f0a16a2016-10-24 16:27:39 -07002686 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002687 for (; i < list.size(); i++) {
2688 const auto& relative = list[i];
2689 if (relative->getZ() >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002690 break;
Robert Carrdb66e622017-04-10 16:55:57 -07002691 }
Dan Stoza412903f2017-04-27 13:42:17 -07002692 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002693 }
Dan Stoza412903f2017-04-27 13:42:17 -07002694 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07002695 for (; i < list.size(); i++) {
2696 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002697 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002698 }
2699}
2700
2701/**
Robert Carrdb66e622017-04-10 16:55:57 -07002702 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07002703 */
Dan Stoza412903f2017-04-27 13:42:17 -07002704void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2705 const LayerVector::Visitor& visitor) {
2706 LayerVector list = makeTraversalList(stateSet);
Robert Carrdb66e622017-04-10 16:55:57 -07002707
Robert Carr1f0a16a2016-10-24 16:27:39 -07002708 int32_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07002709 for (i = list.size()-1; i>=0; i--) {
2710 const auto& relative = list[i];
2711 if (relative->getZ() < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002712 break;
2713 }
Dan Stoza412903f2017-04-27 13:42:17 -07002714 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002715 }
Dan Stoza412903f2017-04-27 13:42:17 -07002716 visitor(this);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002717 for (; i>=0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002718 const auto& relative = list[i];
Dan Stoza412903f2017-04-27 13:42:17 -07002719 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002720 }
2721}
2722
2723Transform Layer::getTransform() const {
2724 Transform t;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002725 const auto& p = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002726 if (p != nullptr) {
2727 t = p->getTransform();
Robert Carr9b429f42017-04-17 14:56:57 -07002728
2729 // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2730 // it isFixedSize) then there may be additional scaling not accounted
2731 // for in the transform. We need to mirror this scaling in child surfaces
2732 // or we will break the contract where WM can treat child surfaces as
2733 // pixels in the parent surface.
Chia-I Wu0a68b462017-07-18 11:30:05 -07002734 if (p->isFixedSize() && p->mActiveBuffer != nullptr) {
Robert Carr1725eee2017-04-26 18:32:15 -07002735 int bufferWidth;
2736 int bufferHeight;
2737 if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2738 bufferWidth = p->mActiveBuffer->getWidth();
2739 bufferHeight = p->mActiveBuffer->getHeight();
2740 } else {
2741 bufferHeight = p->mActiveBuffer->getWidth();
2742 bufferWidth = p->mActiveBuffer->getHeight();
2743 }
Robert Carr9b429f42017-04-17 14:56:57 -07002744 float sx = p->getDrawingState().active.w /
Robert Carr1725eee2017-04-26 18:32:15 -07002745 static_cast<float>(bufferWidth);
Robert Carr9b429f42017-04-17 14:56:57 -07002746 float sy = p->getDrawingState().active.h /
Robert Carr1725eee2017-04-26 18:32:15 -07002747 static_cast<float>(bufferHeight);
Robert Carr9b429f42017-04-17 14:56:57 -07002748 Transform extraParentScaling;
2749 extraParentScaling.set(sx, 0, 0, sy);
2750 t = t * extraParentScaling;
2751 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002752 }
2753 return t * getDrawingState().active.transform;
2754}
2755
Robert Carr6452f122017-03-21 10:41:29 -07002756#ifdef USE_HWC2
2757float Layer::getAlpha() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002758 const auto& p = mDrawingParent.promote();
Robert Carr6452f122017-03-21 10:41:29 -07002759
2760 float parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0;
2761 return parentAlpha * getDrawingState().alpha;
2762}
2763#else
2764uint8_t Layer::getAlpha() const {
Chia-I Wue41dbe62017-06-13 14:10:56 -07002765 const auto& p = mDrawingParent.promote();
Robert Carr6452f122017-03-21 10:41:29 -07002766
2767 float parentAlpha = (p != nullptr) ? (p->getAlpha() / 255.0f) : 1.0;
2768 float drawingAlpha = getDrawingState().alpha / 255.0f;
2769 drawingAlpha = drawingAlpha * parentAlpha;
2770 return static_cast<uint8_t>(std::round(drawingAlpha * 255));
2771}
2772#endif
2773
Robert Carr1f0a16a2016-10-24 16:27:39 -07002774void Layer::commitChildList() {
2775 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2776 const auto& child = mCurrentChildren[i];
2777 child->commitChildList();
2778 }
2779 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002780 mDrawingParent = mCurrentParent;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002781}
2782
Mathias Agopian13127d82013-03-05 17:47:11 -08002783// ---------------------------------------------------------------------------
2784
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002785}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002786
2787#if defined(__gl_h_)
2788#error "don't include gl/gl.h in this file"
2789#endif
2790
2791#if defined(__gl2_h_)
2792#error "don't include gl2/gl2.h in this file"
2793#endif