blob: 6e0a489acf893b4d23accae035adf851ea37e774 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017//#define LOG_NDEBUG 0
18#undef LOG_TAG
19#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080020#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <stdlib.h>
23#include <stdint.h>
24#include <sys/types.h>
Mathias Agopian13127d82013-03-05 17:47:11 -080025#include <math.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080026
Mathias Agopiana67932f2011-04-20 14:20:59 -070027#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070028#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070029#include <cutils/properties.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
31#include <utils/Errors.h>
32#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080033#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080034#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080035#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080036
Mathias Agopian3330b202009-10-05 17:07:12 -070037#include <ui/GraphicBuffer.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080038#include <ui/PixelFormat.h>
Mathias Agopian9cce3252010-02-09 17:46:37 -080039
Dan Stoza6b9454d2014-11-07 16:00:59 -080040#include <gui/BufferItem.h>
Mathias Agopian90ac7992012-02-25 18:48:35 -080041#include <gui/Surface.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080042
43#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020044#include "Colorizer.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070045#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080046#include "Layer.h"
Fabien Sanglard7b1563a2016-10-13 12:05:28 -070047#include "LayerRejecter.h"
Dan Stozab9b08832014-03-13 11:55:57 -070048#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080049#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080050
Mathias Agopian1b031492012-06-20 17:51:20 -070051#include "DisplayHardware/HWComposer.h"
52
Mathias Agopian875d8e12013-06-07 15:35:48 -070053#include "RenderEngine/RenderEngine.h"
54
Dan Stozac5da2712016-07-20 15:38:12 -070055#include <mutex>
56
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#define DEBUG_RESIZE 0
58
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059namespace android {
60
61// ---------------------------------------------------------------------------
62
Mathias Agopian13127d82013-03-05 17:47:11 -080063int32_t Layer::sSequence = 1;
64
Mathias Agopian4d9b8222013-03-12 17:11:48 -070065Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
66 const String8& name, uint32_t w, uint32_t h, uint32_t flags)
Mathias Agopian13127d82013-03-05 17:47:11 -080067 : contentDirty(false),
68 sequence(uint32_t(android_atomic_inc(&sSequence))),
69 mFlinger(flinger),
Mathias Agopiana67932f2011-04-20 14:20:59 -070070 mTextureName(-1U),
Mathias Agopian13127d82013-03-05 17:47:11 -080071 mPremultipliedAlpha(true),
72 mName("unnamed"),
Mathias Agopian13127d82013-03-05 17:47:11 -080073 mFormat(PIXEL_FORMAT_NONE),
Mathias Agopian13127d82013-03-05 17:47:11 -080074 mTransactionFlags(0),
Dan Stoza7dde5992015-05-22 09:51:44 -070075 mPendingStateMutex(),
76 mPendingStates(),
Mathias Agopiana67932f2011-04-20 14:20:59 -070077 mQueuedFrames(0),
Jesse Hall399184a2014-03-03 15:42:54 -080078 mSidebandStreamChanged(false),
Mathias Agopiana67932f2011-04-20 14:20:59 -070079 mCurrentTransform(0),
Mathias Agopian933389f2011-07-18 16:15:08 -070080 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
Robert Carrc3574f72016-03-24 12:19:32 -070081 mOverrideScalingMode(-1),
Mathias Agopiana67932f2011-04-20 14:20:59 -070082 mCurrentOpacity(true),
Brian Andersond6927fb2016-07-23 23:37:30 -070083 mBufferLatched(false),
Dan Stozacac35382016-01-27 12:21:06 -080084 mCurrentFrameNumber(0),
Brian Andersond6927fb2016-07-23 23:37:30 -070085 mPreviousFrameNumber(-1U),
Mathias Agopian4d143ee2012-02-23 20:05:39 -080086 mRefreshPending(false),
Mathias Agopian82d7ab62012-01-19 18:34:40 -080087 mFrameLatencyNeeded(false),
Mathias Agopian13127d82013-03-05 17:47:11 -080088 mFiltering(false),
89 mNeedsFiltering(false),
Mathias Agopian5cdc8992013-08-13 20:51:23 -070090 mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
Fabien Sanglard9d96de42016-10-11 00:15:18 +000091#ifndef USE_HWC2
92 mIsGlesComposition(false),
93#endif
Mathias Agopian13127d82013-03-05 17:47:11 -080094 mProtectedByApp(false),
95 mHasSurface(false),
Riley Andrews03414a12014-07-01 14:22:59 -070096 mClientRef(client),
Dan Stozaa4650a52015-05-12 12:56:16 -070097 mPotentialCursor(false),
98 mQueueItemLock(),
99 mQueueItemCondition(),
100 mQueueItems(),
Dan Stoza65476f32015-05-14 09:27:25 -0700101 mLastFrameNumberReceived(0),
Pablo Ceballos04839ab2015-11-13 13:39:23 -0800102 mUpdateTexImageFailed(false),
Robert Carr82364e32016-05-15 11:27:47 -0700103 mAutoRefresh(false),
104 mFreezePositionUpdates(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000106#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800107 ALOGV("Creating Layer %s", name.string());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000108#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -0800109
Mathias Agopiana67932f2011-04-20 14:20:59 -0700110 mCurrentCrop.makeInvalid();
Mathias Agopian3f844832013-08-07 21:24:32 -0700111 mFlinger->getRenderEngine().genTextures(1, &mTextureName);
Mathias Agopian49457ac2013-08-14 18:20:17 -0700112 mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700113
114 uint32_t layerFlags = 0;
115 if (flags & ISurfaceComposerClient::eHidden)
Andy McFadden4125a4f2014-01-29 17:17:11 -0800116 layerFlags |= layer_state_t::eLayerHidden;
117 if (flags & ISurfaceComposerClient::eOpaque)
118 layerFlags |= layer_state_t::eLayerOpaque;
Dan Stoza23116082015-06-18 14:58:39 -0700119 if (flags & ISurfaceComposerClient::eSecure)
120 layerFlags |= layer_state_t::eLayerSecure;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700121
122 if (flags & ISurfaceComposerClient::eNonPremultiplied)
123 mPremultipliedAlpha = false;
124
125 mName = name;
126
127 mCurrentState.active.w = w;
128 mCurrentState.active.h = h;
Robert Carr3dcabfa2016-03-01 18:36:58 -0800129 mCurrentState.active.transform.set(0, 0);
Robert Carrb5d3d262016-03-25 15:08:13 -0700130 mCurrentState.crop.makeInvalid();
131 mCurrentState.finalCrop.makeInvalid();
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700132 mCurrentState.z = 0;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000133#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800134 mCurrentState.alpha = 1.0f;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000135#else
136 mCurrentState.alpha = 0xFF;
137#endif
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700138 mCurrentState.layerStack = 0;
139 mCurrentState.flags = layerFlags;
140 mCurrentState.sequence = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700141 mCurrentState.requested = mCurrentState.active;
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700142 mCurrentState.dataSpace = HAL_DATASPACE_UNKNOWN;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500143 mCurrentState.appId = 0;
144 mCurrentState.type = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700145
146 // drawing state & current state are identical
147 mDrawingState = mCurrentState;
Jamie Gennis6547ff42013-07-16 20:12:42 -0700148
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000149#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800150 const auto& hwc = flinger->getHwComposer();
151 const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
152 nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000153#else
154 nsecs_t displayPeriod =
155 flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
156#endif
Jamie Gennis6547ff42013-07-16 20:12:42 -0700157 mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
Jamie Gennise8696a42012-01-15 18:54:57 -0800158}
159
Mathias Agopian3f844832013-08-07 21:24:32 -0700160void Layer::onFirstRef() {
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800161 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
Dan Stozab3d0bdf2014-04-07 16:33:59 -0700162 sp<IGraphicBufferProducer> producer;
163 sp<IGraphicBufferConsumer> consumer;
Irvel468051e2016-06-13 16:44:44 -0700164 BufferQueue::createBufferQueue(&producer, &consumer, nullptr, true);
Robert Carr1db73f62016-12-21 12:58:51 -0800165 mProducer = new MonitoredProducer(producer, mFlinger, this);
Irvel468051e2016-06-13 16:44:44 -0700166 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800167 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Jesse Hall399184a2014-03-03 15:42:54 -0800168 mSurfaceFlingerConsumer->setContentsChangedListener(this);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700169 mSurfaceFlingerConsumer->setName(mName);
Daniel Lamb2675792012-02-23 14:35:13 -0800170
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800171 if (mFlinger->isLayerTripleBufferingDisabled()) {
172 mProducer->setMaxDequeuedBufferCount(2);
173 }
Andy McFadden69052052012-09-14 16:10:11 -0700174
Mathias Agopian84300952012-11-21 16:02:13 -0800175 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
176 updateTransformHint(hw);
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700177}
178
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700179Layer::~Layer() {
Pablo Ceballos8ea4e7b2016-03-03 15:20:02 -0800180 sp<Client> c(mClientRef.promote());
181 if (c != 0) {
182 c->detachLayer(this);
183 }
184
Dan Stozacac35382016-01-27 12:21:06 -0800185 for (auto& point : mRemoteSyncPoints) {
186 point->setTransactionApplied();
187 }
Dan Stozac8145172016-04-28 16:29:06 -0700188 for (auto& point : mLocalSyncPoints) {
189 point->setFrameAvailable();
190 }
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700191 mFlinger->deleteTextureAsync(mTextureName);
Jamie Gennis6547ff42013-07-16 20:12:42 -0700192 mFrameTracker.logAndResetStats(mName);
Mathias Agopian96f08192010-06-02 23:28:45 -0700193}
194
Mathias Agopian13127d82013-03-05 17:47:11 -0800195// ---------------------------------------------------------------------------
196// callbacks
197// ---------------------------------------------------------------------------
198
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000199#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800200void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
201 if (mHwcLayers.empty()) {
202 return;
203 }
204 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
205}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000206#else
207void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
208 HWComposer::HWCLayerInterface* layer) {
209 if (layer) {
210 layer->onDisplayed();
211 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
212 }
213}
214#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800215
Dan Stoza6b9454d2014-11-07 16:00:59 -0800216void Layer::onFrameAvailable(const BufferItem& item) {
217 // Add this buffer from our internal queue tracker
218 { // Autolock scope
219 Mutex::Autolock lock(mQueueItemLock);
Irvel468051e2016-06-13 16:44:44 -0700220 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
221 item.mGraphicBuffer->getHeight(), item.mFrameNumber);
Dan Stozaa4650a52015-05-12 12:56:16 -0700222 // Reset the frame number tracker when we receive the first buffer after
223 // a frame number reset
224 if (item.mFrameNumber == 1) {
225 mLastFrameNumberReceived = 0;
226 }
227
228 // Ensure that callbacks are handled in order
229 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
230 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
231 ms2ns(500));
232 if (result != NO_ERROR) {
233 ALOGE("[%s] Timed out waiting on callback", mName.string());
234 }
235 }
236
Dan Stoza6b9454d2014-11-07 16:00:59 -0800237 mQueueItems.push_back(item);
Dan Stozaecc50402015-04-28 14:42:06 -0700238 android_atomic_inc(&mQueuedFrames);
Dan Stozaa4650a52015-05-12 12:56:16 -0700239
240 // Wake up any pending callbacks
241 mLastFrameNumberReceived = item.mFrameNumber;
242 mQueueItemCondition.broadcast();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800243 }
244
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800245 mFlinger->signalLayerUpdate();
Mathias Agopian579b3f82010-06-08 19:54:15 -0700246}
247
Dan Stoza6b9454d2014-11-07 16:00:59 -0800248void Layer::onFrameReplaced(const BufferItem& item) {
Dan Stoza7dde5992015-05-22 09:51:44 -0700249 { // Autolock scope
250 Mutex::Autolock lock(mQueueItemLock);
Dan Stozaa4650a52015-05-12 12:56:16 -0700251
Dan Stoza7dde5992015-05-22 09:51:44 -0700252 // Ensure that callbacks are handled in order
253 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
254 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
255 ms2ns(500));
256 if (result != NO_ERROR) {
257 ALOGE("[%s] Timed out waiting on callback", mName.string());
258 }
Dan Stozaa4650a52015-05-12 12:56:16 -0700259 }
Dan Stoza7dde5992015-05-22 09:51:44 -0700260
261 if (mQueueItems.empty()) {
262 ALOGE("Can't replace a frame on an empty queue");
263 return;
264 }
Pablo Ceballos4d85da42016-04-19 20:11:56 -0700265 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
Dan Stoza7dde5992015-05-22 09:51:44 -0700266
267 // Wake up any pending callbacks
268 mLastFrameNumberReceived = item.mFrameNumber;
269 mQueueItemCondition.broadcast();
Dan Stozaa4650a52015-05-12 12:56:16 -0700270 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800271}
272
Chia-I Wu06d63de2017-01-04 14:58:51 +0800273void Layer::onBuffersReleased() {
274#ifdef USE_HWC2
275 Mutex::Autolock lock(mHwcBufferCacheMutex);
276
277 for (auto info : mHwcBufferCaches) {
278 info.second.clear();
279 }
280#endif
281}
282
Jesse Hall399184a2014-03-03 15:42:54 -0800283void Layer::onSidebandStreamChanged() {
284 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
285 // mSidebandStreamChanged was false
286 mFlinger->signalLayerUpdate();
287 }
288}
289
Mathias Agopian67106042013-03-14 19:18:13 -0700290// called with SurfaceFlinger::mStateLock from the drawing thread after
291// the layer has been remove from the current state list (and just before
292// it's removed from the drawing state list)
Mathias Agopian13127d82013-03-05 17:47:11 -0800293void Layer::onRemoved() {
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800294 mSurfaceFlingerConsumer->abandon();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700295 for (const auto& child : mCurrentChildren) {
296 child->onRemoved();
297 }
Mathias Agopian48d819a2009-09-10 19:41:18 -0700298}
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700299
Mathias Agopian13127d82013-03-05 17:47:11 -0800300// ---------------------------------------------------------------------------
301// set-up
302// ---------------------------------------------------------------------------
303
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700304const String8& Layer::getName() const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800305 return mName;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800306}
307
Mathias Agopianf9d93272009-06-19 17:00:27 -0700308status_t Layer::setBuffers( uint32_t w, uint32_t h,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800309 PixelFormat format, uint32_t flags)
310{
Mathias Agopianca99fb82010-04-14 16:43:44 -0700311 uint32_t const maxSurfaceDims = min(
Mathias Agopiana4912602012-07-12 14:25:33 -0700312 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
Mathias Agopianca99fb82010-04-14 16:43:44 -0700313
314 // never allow a surface larger than what our underlying GL implementation
315 // can handle.
316 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
Mathias Agopianff615cc2012-02-24 14:58:36 -0800317 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700318 return BAD_VALUE;
319 }
320
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700321 mFormat = format;
Mathias Agopianeff062c2010-08-25 14:59:15 -0700322
Riley Andrews03414a12014-07-01 14:22:59 -0700323 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
Mathias Agopian3165cc22012-08-08 19:42:09 -0700324 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700325 mCurrentOpacity = getOpacityForFormat(format);
326
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800327 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
328 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
329 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700330
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800331 return NO_ERROR;
332}
333
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700334sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800335 Mutex::Autolock _l(mLock);
336
337 LOG_ALWAYS_FATAL_IF(mHasSurface,
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700338 "Layer::getHandle() has already been called");
Mathias Agopian13127d82013-03-05 17:47:11 -0800339
340 mHasSurface = true;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700341
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700342 return new Handle(mFlinger, this);
Mathias Agopian13127d82013-03-05 17:47:11 -0800343}
344
Dan Stozab9b08832014-03-13 11:55:57 -0700345sp<IGraphicBufferProducer> Layer::getProducer() const {
346 return mProducer;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700347}
348
Mathias Agopian13127d82013-03-05 17:47:11 -0800349// ---------------------------------------------------------------------------
350// h/w composer set-up
351// ---------------------------------------------------------------------------
352
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800353Rect Layer::getContentCrop() const {
354 // this is the crop rectangle that applies to the buffer
355 // itself (as opposed to the window)
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700356 Rect crop;
357 if (!mCurrentCrop.isEmpty()) {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800358 // if the buffer crop is defined, we use that
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700359 crop = mCurrentCrop;
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800360 } else if (mActiveBuffer != NULL) {
361 // otherwise we use the whole buffer
362 crop = mActiveBuffer->getBounds();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700363 } else {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800364 // if we don't have a buffer yet, we use an empty/invalid crop
Mathias Agopian4fec8732012-06-29 14:12:52 -0700365 crop.makeInvalid();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700366 }
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700367 return crop;
368}
369
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700370static Rect reduce(const Rect& win, const Region& exclude) {
371 if (CC_LIKELY(exclude.isEmpty())) {
372 return win;
373 }
374 if (exclude.isRect()) {
375 return win.reduce(exclude.getBounds());
376 }
377 return Region(win).subtract(exclude).getBounds();
378}
379
Robert Carr1f0a16a2016-10-24 16:27:39 -0700380Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
381 const Layer::State& s(getDrawingState());
382 Rect win(s.active.w, s.active.h);
383
384 if (!s.crop.isEmpty()) {
385 win.intersect(s.crop, &win);
386 }
387
388 Transform t = getTransform();
389 win = t.transform(win);
390
391 const sp<Layer>& p = getParent();
392 // Now we need to calculate the parent bounds, so we can clip ourselves to those.
393 // When calculating the parent bounds for purposes of clipping,
394 // we don't need to constrain the parent to its transparent region.
395 // The transparent region is an optimization based on the
396 // buffer contents of the layer, but does not affect the space allocated to
397 // it by policy, and thus children should be allowed to extend into the
398 // parent's transparent region. In fact one of the main uses, is to reduce
399 // buffer allocation size in cases where a child window sits behind a main window
400 // (by marking the hole in the parent window as a transparent region)
401 if (p != nullptr) {
402 Rect bounds = p->computeScreenBounds(false);
403 bounds.intersect(win, &win);
404 }
405
406 if (reduceTransparentRegion) {
407 auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
408 win = reduce(win, screenTransparentRegion);
409 }
410
411 return win;
412}
413
Mathias Agopian13127d82013-03-05 17:47:11 -0800414Rect Layer::computeBounds() const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700415 const Layer::State& s(getDrawingState());
Michael Lentine6c925ed2014-09-26 17:55:01 -0700416 return computeBounds(s.activeTransparentRegion);
417}
418
419Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
420 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800421 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700422
423 if (!s.crop.isEmpty()) {
424 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -0800425 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700426
427 Rect bounds = win;
428 const auto& p = getParent();
429 if (p != nullptr) {
Robert Carrde9ec442017-02-08 17:43:36 -0800430 // Look in computeScreenBounds recursive call for explanation of
431 // why we pass false here.
432 bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700433 }
434
435 Transform t = getTransform();
436 if (p != nullptr) {
437 win = t.transform(win);
438 win.intersect(bounds, &win);
439 win = t.inverse().transform(win);
440 }
441
Mathias Agopian6c7f25a2013-05-09 20:37:10 -0700442 // subtract the transparent region and snap to the bounds
Michael Lentine6c925ed2014-09-26 17:55:01 -0700443 return reduce(win, activeTransparentRegion);
Mathias Agopian13127d82013-03-05 17:47:11 -0800444}
445
Robert Carr1f0a16a2016-10-24 16:27:39 -0700446Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
Robert Carrb5d3d262016-03-25 15:08:13 -0700447 // the crop is the area of the window that gets cropped, but not
Mathias Agopian13127d82013-03-05 17:47:11 -0800448 // scaled in any ways.
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700449 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800450
451 // apply the projection's clipping to the window crop in
452 // layerstack space, and convert-back to layer space.
Mathias Agopian6b442672013-07-09 21:24:52 -0700453 // if there are no window scaling involved, this operation will map to full
454 // pixels in the buffer.
455 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
456 // a viewport clipping and a window transform. we should use floating point to fix this.
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700457
458 Rect activeCrop(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700459 if (!s.crop.isEmpty()) {
460 activeCrop = s.crop;
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700461 }
462
Robert Carr1f0a16a2016-10-24 16:27:39 -0700463 Transform t = getTransform();
464 activeCrop = t.transform(activeCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000465 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
466 activeCrop.clear();
467 }
Robert Carrb5d3d262016-03-25 15:08:13 -0700468 if (!s.finalCrop.isEmpty()) {
469 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000470 activeCrop.clear();
471 }
472 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700473 return activeCrop;
474}
475
476gfx::FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
477 // the content crop is the area of the content that gets scaled to the
478 // layer's size. This is in buffer space.
479 gfx::FloatRect crop = getContentCrop().toFloatRect();
480
481 // In addition there is a WM-specified crop we pull from our drawing state.
482 const State& s(getDrawingState());
483
484 // Screen space to make reduction to parent crop clearer.
485 Rect activeCrop = computeInitialCrop(hw);
486 const auto& p = getParent();
487 if (p != nullptr) {
488 auto parentCrop = p->computeInitialCrop(hw);
489 activeCrop.intersect(parentCrop, &activeCrop);
490 }
491 Transform t = getTransform();
492 // Back to layer space to work with the content crop.
493 activeCrop = t.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800494
Michael Lentine28ea2172014-11-19 18:32:37 -0800495 // This needs to be here as transform.transform(Rect) computes the
496 // transformed rect and then takes the bounding box of the result before
497 // returning. This means
498 // transform.inverse().transform(transform.transform(Rect)) != Rect
499 // in which case we need to make sure the final rect is clipped to the
500 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000501 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
502 activeCrop.clear();
503 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800504
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700505 // subtract the transparent region and snap to the bounds
506 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
507
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000508 // Transform the window crop to match the buffer coordinate system,
509 // which means using the inverse of the current transform set on the
510 // SurfaceFlingerConsumer.
511 uint32_t invTransform = mCurrentTransform;
512 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
513 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700514 * the code below applies the primary display's inverse transform to the
515 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000516 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700517 uint32_t invTransformOrient =
518 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000519 // calculate the inverse transform
520 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
521 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
522 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800523 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000524 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700525 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
526 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800527 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000528
529 int winWidth = s.active.w;
530 int winHeight = s.active.h;
531 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
532 // If the activeCrop has been rotate the ends are rotated but not
533 // the space itself so when transforming ends back we can't rely on
534 // a modification of the axes of rotation. To account for this we
535 // need to reorient the inverse rotation in terms of the current
536 // axes of rotation.
537 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
538 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
539 if (is_h_flipped == is_v_flipped) {
540 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
541 NATIVE_WINDOW_TRANSFORM_FLIP_H;
542 }
543 winWidth = s.active.h;
544 winHeight = s.active.w;
545 }
546 const Rect winCrop = activeCrop.transform(
547 invTransform, s.active.w, s.active.h);
548
549 // below, crop is intersected with winCrop expressed in crop's coordinate space
550 float xScale = crop.getWidth() / float(winWidth);
551 float yScale = crop.getHeight() / float(winHeight);
552
553 float insetL = winCrop.left * xScale;
554 float insetT = winCrop.top * yScale;
555 float insetR = (winWidth - winCrop.right ) * xScale;
556 float insetB = (winHeight - winCrop.bottom) * yScale;
557
558 crop.left += insetL;
559 crop.top += insetT;
560 crop.right -= insetR;
561 crop.bottom -= insetB;
562
Mathias Agopian13127d82013-03-05 17:47:11 -0800563 return crop;
564}
565
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000566#ifdef USE_HWC2
Robert Carrae060832016-11-28 10:51:00 -0800567void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000568#else
569void Layer::setGeometry(
570 const sp<const DisplayDevice>& hw,
571 HWComposer::HWCLayerInterface& layer)
572#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700573{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000574#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800575 const auto hwcId = displayDevice->getHwcDisplayId();
576 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000577#else
578 layer.setDefaultState();
579#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700580
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700581 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000582#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800583 hwcInfo.forceClientComposition = false;
584
585 if (isSecure() && !displayDevice->isSecure()) {
586 hwcInfo.forceClientComposition = true;
587 }
588
589 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000590#else
591 layer.setSkip(false);
592
593 if (isSecure() && !hw->isSecure()) {
594 layer.setSkip(true);
595 }
596#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700597
Mathias Agopian13127d82013-03-05 17:47:11 -0800598 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700599 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000600#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800601 if (!isOpaque(s) || s.alpha != 1.0f) {
602 auto blendMode = mPremultipliedAlpha ?
603 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
604 auto error = hwcLayer->setBlendMode(blendMode);
605 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
606 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
607 to_string(error).c_str(), static_cast<int32_t>(error));
608 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000609#else
610 if (!isOpaque(s) || s.alpha != 0xFF) {
611 layer.setBlending(mPremultipliedAlpha ?
612 HWC_BLENDING_PREMULT :
613 HWC_BLENDING_COVERAGE);
614 }
615#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800616
617 // apply the layer's transform, followed by the display's global transform
618 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700619 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700620 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -0700621 if (!s.crop.isEmpty()) {
622 Rect activeCrop(s.crop);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700623 activeCrop = t.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000624#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000625 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000626#else
627 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
628#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000629 activeCrop.clear();
630 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700631 activeCrop = t.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800632 // This needs to be here as transform.transform(Rect) computes the
633 // transformed rect and then takes the bounding box of the result before
634 // returning. This means
635 // transform.inverse().transform(transform.transform(Rect)) != Rect
636 // in which case we need to make sure the final rect is clipped to the
637 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000638 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
639 activeCrop.clear();
640 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700641 // mark regions outside the crop as transparent
642 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
643 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
644 s.active.w, s.active.h));
645 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
646 activeCrop.left, activeCrop.bottom));
647 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
648 s.active.w, activeCrop.bottom));
649 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700650
651 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700652 if (!s.finalCrop.isEmpty()) {
653 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000654 frame.clear();
655 }
656 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000657#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000658 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
659 frame.clear();
660 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800661 const Transform& tr(displayDevice->getTransform());
662 Rect transformedFrame = tr.transform(frame);
663 auto error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700664 if (error != HWC2::Error::None) {
665 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
666 mName.string(), transformedFrame.left, transformedFrame.top,
667 transformedFrame.right, transformedFrame.bottom,
668 to_string(error).c_str(), static_cast<int32_t>(error));
669 } else {
670 hwcInfo.displayFrame = transformedFrame;
671 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800672
Dan Stoza71bded52016-10-19 11:10:33 -0700673 gfx::FloatRect sourceCrop = computeCrop(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800674 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700675 if (error != HWC2::Error::None) {
676 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
677 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
678 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
679 static_cast<int32_t>(error));
680 } else {
681 hwcInfo.sourceCrop = sourceCrop;
682 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800683
684 error = hwcLayer->setPlaneAlpha(s.alpha);
685 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
686 "%s (%d)", mName.string(), s.alpha, to_string(error).c_str(),
687 static_cast<int32_t>(error));
688
Robert Carrae060832016-11-28 10:51:00 -0800689 error = hwcLayer->setZOrder(z);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800690 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
Robert Carrae060832016-11-28 10:51:00 -0800691 mName.string(), z, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800692 static_cast<int32_t>(error));
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500693
694 error = hwcLayer->setInfo(s.type, s.appId);
695 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
696 mName.string(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000697#else
698 if (!frame.intersect(hw->getViewport(), &frame)) {
699 frame.clear();
700 }
701 const Transform& tr(hw->getTransform());
702 layer.setFrame(tr.transform(frame));
703 layer.setCrop(computeCrop(hw));
704 layer.setPlaneAlpha(s.alpha);
705#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800706
Mathias Agopian29a367b2011-07-12 14:51:45 -0700707 /*
708 * Transformations are applied in this order:
709 * 1) buffer orientation/flip/mirror
710 * 2) state transformation (window manager)
711 * 3) layer orientation (screen orientation)
712 * (NOTE: the matrices are multiplied in reverse order)
713 */
714
715 const Transform bufferOrientation(mCurrentTransform);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700716 Transform transform(tr * t * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700717
718 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
719 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700720 * the code below applies the primary display's inverse transform to the
721 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700722 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700723 uint32_t invTransform =
724 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700725 // calculate the inverse transform
726 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
727 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
728 NATIVE_WINDOW_TRANSFORM_FLIP_H;
729 }
730 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700731 transform = Transform(invTransform) * transform;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700732 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700733
734 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800735 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000736#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800737 if (orientation & Transform::ROT_INVALID) {
738 // we can only handle simple transformation
739 hwcInfo.forceClientComposition = true;
740 } else {
741 auto transform = static_cast<HWC2::Transform>(orientation);
742 auto error = hwcLayer->setTransform(transform);
743 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
744 "%s (%d)", mName.string(), to_string(transform).c_str(),
745 to_string(error).c_str(), static_cast<int32_t>(error));
746 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000747#else
748 if (orientation & Transform::ROT_INVALID) {
749 // we can only handle simple transformation
750 layer.setSkip(true);
751 } else {
752 layer.setTransform(orientation);
753 }
754#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700755}
756
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000757#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800758void Layer::forceClientComposition(int32_t hwcId) {
759 if (mHwcLayers.count(hwcId) == 0) {
760 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
761 return;
762 }
763
764 mHwcLayers[hwcId].forceClientComposition = true;
765}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000766#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -0800767
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000768#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800769void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
770 // Apply this display's projection's viewport to the visible region
771 // before giving it to the HWC HAL.
772 const Transform& tr = displayDevice->getTransform();
773 const auto& viewport = displayDevice->getViewport();
774 Region visible = tr.transform(visibleRegion.intersect(viewport));
775 auto hwcId = displayDevice->getHwcDisplayId();
776 auto& hwcLayer = mHwcLayers[hwcId].layer;
777 auto error = hwcLayer->setVisibleRegion(visible);
778 if (error != HWC2::Error::None) {
779 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
780 to_string(error).c_str(), static_cast<int32_t>(error));
781 visible.dump(LOG_TAG);
782 }
783
784 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
785 if (error != HWC2::Error::None) {
786 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
787 to_string(error).c_str(), static_cast<int32_t>(error));
788 surfaceDamageRegion.dump(LOG_TAG);
789 }
790
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700791 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800792 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700793 setCompositionType(hwcId, HWC2::Composition::Sideband);
794 ALOGV("[%s] Requesting Sideband composition", mName.string());
795 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800796 if (error != HWC2::Error::None) {
797 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
798 mName.string(), mSidebandStream->handle(),
799 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800800 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700801 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800802 }
803
Dan Stoza0a21df72016-07-20 12:52:38 -0700804 // Client layers
805 if (mHwcLayers[hwcId].forceClientComposition ||
806 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700807 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800808 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700809 return;
810 }
811
Dan Stoza0a21df72016-07-20 12:52:38 -0700812 // SolidColor layers
813 if (mActiveBuffer == nullptr) {
814 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700815
816 // For now, we only support black for DimLayer
Dan Stoza0a21df72016-07-20 12:52:38 -0700817 error = hwcLayer->setColor({0, 0, 0, 255});
818 if (error != HWC2::Error::None) {
819 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
820 to_string(error).c_str(), static_cast<int32_t>(error));
821 }
Dan Stozac6c89542016-07-27 10:16:52 -0700822
823 // Clear out the transform, because it doesn't make sense absent a
824 // source buffer
825 error = hwcLayer->setTransform(HWC2::Transform::None);
826 if (error != HWC2::Error::None) {
827 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
828 to_string(error).c_str(), static_cast<int32_t>(error));
829 }
830
Dan Stoza0a21df72016-07-20 12:52:38 -0700831 return;
832 }
833
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700834 // Device or Cursor layers
835 if (mPotentialCursor) {
836 ALOGV("[%s] Requesting Cursor composition", mName.string());
837 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800838 } else {
839 ALOGV("[%s] Requesting Device composition", mName.string());
840 setCompositionType(hwcId, HWC2::Composition::Device);
841 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700842
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700843 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
844 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
845 if (error != HWC2::Error::None) {
846 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
847 mCurrentState.dataSpace, to_string(error).c_str(),
848 static_cast<int32_t>(error));
849 }
850
Chia-I Wu06d63de2017-01-04 14:58:51 +0800851 uint32_t hwcSlot = 0;
852 buffer_handle_t hwcHandle = nullptr;
853 {
854 Mutex::Autolock lock(mHwcBufferCacheMutex);
855
856 auto& hwcBufferCache = mHwcBufferCaches[hwcId];
857 sp<GraphicBuffer> hwcBuffer;
858 hwcBufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
859 &hwcSlot, &hwcBuffer);
860 if (hwcBuffer != nullptr) {
861 hwcHandle = hwcBuffer->handle;
862 }
863 }
864
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700865 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
Chia-I Wu06d63de2017-01-04 14:58:51 +0800866 error = hwcLayer->setBuffer(hwcSlot, hwcHandle, acquireFence);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700867 if (error != HWC2::Error::None) {
868 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
869 mActiveBuffer->handle, to_string(error).c_str(),
870 static_cast<int32_t>(error));
871 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800872}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000873#else
874void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
875 HWComposer::HWCLayerInterface& layer) {
876 // we have to set the visible region on every frame because
877 // we currently free it during onLayerDisplayed(), which is called
878 // after HWComposer::commit() -- every frame.
879 // Apply this display's projection's viewport to the visible region
880 // before giving it to the HWC HAL.
881 const Transform& tr = hw->getTransform();
882 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
883 layer.setVisibleRegionScreen(visible);
884 layer.setSurfaceDamage(surfaceDamageRegion);
885 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700886
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000887 if (mSidebandStream.get()) {
888 layer.setSidebandStream(mSidebandStream);
889 } else {
890 // NOTE: buffer can be NULL if the client never drew into this
891 // layer yet, or if we ran out of memory
892 layer.setBuffer(mActiveBuffer);
893 }
894}
895#endif
896
897#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800898void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
899 auto hwcId = displayDevice->getHwcDisplayId();
900 if (mHwcLayers.count(hwcId) == 0 ||
901 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
902 return;
903 }
904
905 // This gives us only the "orientation" component of the transform
906 const State& s(getCurrentState());
907
908 // Apply the layer's transform, followed by the display's global transform
909 // Here we're guaranteed that the layer's transform preserves rects
910 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700911 if (!s.crop.isEmpty()) {
912 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800913 }
914 // Subtract the transparent region and snap to the bounds
915 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700916 Rect frame(getTransform().transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800917 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -0700918 if (!s.finalCrop.isEmpty()) {
919 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000920 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800921 auto& displayTransform(displayDevice->getTransform());
922 auto position = displayTransform.transform(frame);
923
924 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
925 position.top);
926 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
927 "to (%d, %d): %s (%d)", mName.string(), position.left,
928 position.top, to_string(error).c_str(),
929 static_cast<int32_t>(error));
930}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000931#else
932void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
933 HWComposer::HWCLayerInterface& layer) {
934 int fenceFd = -1;
935
936 // TODO: there is a possible optimization here: we only need to set the
937 // acquire fence the first time a new buffer is acquired on EACH display.
938
939 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
940 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
941 if (fence->isValid()) {
942 fenceFd = fence->dup();
943 if (fenceFd == -1) {
944 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
945 }
946 }
947 }
948 layer.setAcquireFenceFd(fenceFd);
949}
950
951Rect Layer::getPosition(
952 const sp<const DisplayDevice>& hw)
953{
954 // this gives us only the "orientation" component of the transform
955 const State& s(getCurrentState());
956
957 // apply the layer's transform, followed by the display's global transform
958 // here we're guaranteed that the layer's transform preserves rects
959 Rect win(s.active.w, s.active.h);
960 if (!s.crop.isEmpty()) {
961 win.intersect(s.crop, &win);
962 }
963 // subtract the transparent region and snap to the bounds
964 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700965 Rect frame(getTransform().transform(bounds));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000966 frame.intersect(hw->getViewport(), &frame);
967 if (!s.finalCrop.isEmpty()) {
968 frame.intersect(s.finalCrop, &frame);
969 }
970 const Transform& tr(hw->getTransform());
971 return Rect(tr.transform(frame));
972}
973#endif
Riley Andrews03414a12014-07-01 14:22:59 -0700974
Mathias Agopian13127d82013-03-05 17:47:11 -0800975// ---------------------------------------------------------------------------
976// drawing...
977// ---------------------------------------------------------------------------
978
979void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -0800980 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -0800981}
982
Dan Stozac7014012014-02-14 15:03:43 -0800983void Layer::draw(const sp<const DisplayDevice>& hw,
984 bool useIdentityTransform) const {
985 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -0800986}
987
Dan Stozac7014012014-02-14 15:03:43 -0800988void Layer::draw(const sp<const DisplayDevice>& hw) const {
989 onDraw(hw, Region(hw->bounds()), false);
990}
991
992void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
993 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800994{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -0800995 ATRACE_CALL();
996
Mathias Agopiana67932f2011-04-20 14:20:59 -0700997 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800998 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -0700999 // in fact never been drawn into. This happens frequently with
1000 // SurfaceView because the WindowManager can't know when the client
1001 // has drawn the first time.
1002
1003 // If there is nothing under us, we paint the screen in black, otherwise
1004 // we just skip this update.
1005
1006 // figure out if there is something below us
1007 Region under;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001008 bool finished = false;
1009 mFlinger->mDrawingState.layersSortedByZ.traverseInZOrder([&](Layer* layer) {
1010 if (finished || layer == static_cast<Layer const*>(this)) {
1011 finished = true;
1012 return;
1013 }
Mathias Agopian42977342012-08-05 00:40:46 -07001014 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Robert Carr1f0a16a2016-10-24 16:27:39 -07001015 });
Mathias Agopian179169e2010-05-06 20:21:45 -07001016 // if not everything below us is covered, we plug the holes!
1017 Region holes(clip.subtract(under));
1018 if (!holes.isEmpty()) {
Fabien Sanglard17487192016-12-07 13:03:32 -08001019 clearWithOpenGL(hw, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -07001020 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001021 return;
1022 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001023
Andy McFadden97eba892012-12-11 15:21:45 -08001024 // Bind the current buffer to the GL texture, and wait for it to be
1025 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001026 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1027 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -08001028 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -07001029 // Go ahead and draw the buffer anyway; no matter what we do the screen
1030 // is probably going to have something visibly wrong.
1031 }
1032
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001033 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1034
Mathias Agopian875d8e12013-06-07 15:35:48 -07001035 RenderEngine& engine(mFlinger->getRenderEngine());
1036
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001037 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -07001038 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -07001039 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -07001040
1041 // Query the texture matrix given our current filtering mode.
1042 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001043 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1044 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -07001045
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001046 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
1047
1048 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -07001049 * the code below applies the primary display's inverse transform to
1050 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001051 */
1052
1053 // create a 4x4 transform matrix from the display transform flags
1054 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1055 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1056 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1057
1058 mat4 tr;
Pablo Ceballos021623b2016-04-15 17:31:51 -07001059 uint32_t transform =
1060 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001061 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90)
1062 tr = tr * rot90;
1063 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H)
1064 tr = tr * flipH;
1065 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V)
1066 tr = tr * flipV;
1067
1068 // calculate the inverse
1069 tr = inverse(tr);
1070
1071 // and finally apply it to the original texture matrix
1072 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1073 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1074 }
1075
Jamie Genniscbb1a952012-05-08 17:05:52 -07001076 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -07001077 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1078 mTexture.setFiltering(useFiltering);
1079 mTexture.setMatrix(textureMatrix);
1080
1081 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -07001082 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001083 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -07001084 }
Fabien Sanglard85789802016-12-07 13:08:24 -08001085 drawWithOpenGL(hw, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001086 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001087}
1088
Mathias Agopian13127d82013-03-05 17:47:11 -08001089
Dan Stozac7014012014-02-14 15:03:43 -08001090void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard17487192016-12-07 13:03:32 -08001091 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -08001092 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001093{
Mathias Agopian19733a32013-08-28 18:13:56 -07001094 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -08001095 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -07001096 engine.setupFillWithColor(red, green, blue, alpha);
1097 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -08001098}
1099
1100void Layer::clearWithOpenGL(
Fabien Sanglard17487192016-12-07 13:03:32 -08001101 const sp<const DisplayDevice>& hw) const {
1102 clearWithOpenGL(hw, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001103}
1104
Dan Stozac7014012014-02-14 15:03:43 -08001105void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard85789802016-12-07 13:08:24 -08001106 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001107 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001108
Dan Stozac7014012014-02-14 15:03:43 -08001109 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001110
Mathias Agopian13127d82013-03-05 17:47:11 -08001111 /*
1112 * NOTE: the way we compute the texture coordinates here produces
1113 * different results than when we take the HWC path -- in the later case
1114 * the "source crop" is rounded to texel boundaries.
1115 * This can produce significantly different results when the texture
1116 * is scaled by a large amount.
1117 *
1118 * The GL code below is more logical (imho), and the difference with
1119 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001120 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001121 * GL composition when a buffer scaling is applied (maybe with some
1122 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1123 * like more of a hack.
1124 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001125 Rect win(computeBounds());
1126
Robert Carr1f0a16a2016-10-24 16:27:39 -07001127 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -07001128 if (!s.finalCrop.isEmpty()) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001129 win = t.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001130 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001131 win.clear();
1132 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001133 win = t.inverse().transform(win);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001134 if (!win.intersect(computeBounds(), &win)) {
1135 win.clear();
1136 }
1137 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001138
Mathias Agopian3f844832013-08-07 21:24:32 -07001139 float left = float(win.left) / float(s.active.w);
1140 float top = float(win.top) / float(s.active.h);
1141 float right = float(win.right) / float(s.active.w);
1142 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001143
Mathias Agopian875d8e12013-06-07 15:35:48 -07001144 // TODO: we probably want to generate the texture coords with the mesh
1145 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001146 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1147 texCoords[0] = vec2(left, 1.0f - top);
1148 texCoords[1] = vec2(left, 1.0f - bottom);
1149 texCoords[2] = vec2(right, 1.0f - bottom);
1150 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001151
Mathias Agopian875d8e12013-06-07 15:35:48 -07001152 RenderEngine& engine(mFlinger->getRenderEngine());
Andy McFadden4125a4f2014-01-29 17:17:11 -08001153 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), s.alpha);
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001154 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001155 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001156}
1157
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001158#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001159void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1160 bool callIntoHwc) {
1161 if (mHwcLayers.count(hwcId) == 0) {
1162 ALOGE("setCompositionType called without a valid HWC layer");
1163 return;
1164 }
1165 auto& hwcInfo = mHwcLayers[hwcId];
1166 auto& hwcLayer = hwcInfo.layer;
1167 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1168 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1169 if (hwcInfo.compositionType != type) {
1170 ALOGV(" actually setting");
1171 hwcInfo.compositionType = type;
1172 if (callIntoHwc) {
1173 auto error = hwcLayer->setCompositionType(type);
1174 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1175 "composition type %s: %s (%d)", mName.string(),
1176 to_string(type).c_str(), to_string(error).c_str(),
1177 static_cast<int32_t>(error));
1178 }
1179 }
1180}
1181
1182HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001183 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1184 // If we're querying the composition type for a display that does not
1185 // have a HWC counterpart, then it will always be Client
1186 return HWC2::Composition::Client;
1187 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001188 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001189 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001190 return HWC2::Composition::Invalid;
1191 }
1192 return mHwcLayers.at(hwcId).compositionType;
1193}
1194
1195void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1196 if (mHwcLayers.count(hwcId) == 0) {
1197 ALOGE("setClearClientTarget called without a valid HWC layer");
1198 return;
1199 }
1200 mHwcLayers[hwcId].clearClientTarget = clear;
1201}
1202
1203bool Layer::getClearClientTarget(int32_t hwcId) const {
1204 if (mHwcLayers.count(hwcId) == 0) {
1205 ALOGE("getClearClientTarget called without a valid HWC layer");
1206 return false;
1207 }
1208 return mHwcLayers.at(hwcId).clearClientTarget;
1209}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001210#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001211
Ruben Brunk1681d952014-06-27 15:51:55 -07001212uint32_t Layer::getProducerStickyTransform() const {
1213 int producerStickyTransform = 0;
1214 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1215 if (ret != OK) {
1216 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1217 strerror(-ret), ret);
1218 return 0;
1219 }
1220 return static_cast<uint32_t>(producerStickyTransform);
1221}
1222
Dan Stozac5da2712016-07-20 15:38:12 -07001223bool Layer::latchUnsignaledBuffers() {
1224 static bool propertyLoaded = false;
1225 static bool latch = false;
1226 static std::mutex mutex;
1227 std::lock_guard<std::mutex> lock(mutex);
1228 if (!propertyLoaded) {
1229 char value[PROPERTY_VALUE_MAX] = {};
1230 property_get("debug.sf.latch_unsignaled", value, "0");
1231 latch = atoi(value);
1232 propertyLoaded = true;
1233 }
1234 return latch;
1235}
1236
Dan Stozacac35382016-01-27 12:21:06 -08001237uint64_t Layer::getHeadFrameNumber() const {
1238 Mutex::Autolock lock(mQueueItemLock);
1239 if (!mQueueItems.empty()) {
1240 return mQueueItems[0].mFrameNumber;
1241 } else {
1242 return mCurrentFrameNumber;
1243 }
1244}
1245
Dan Stoza1ce65812016-06-15 16:26:27 -07001246bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001247#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001248 if (latchUnsignaledBuffers()) {
1249 return true;
1250 }
1251
Dan Stoza1ce65812016-06-15 16:26:27 -07001252 Mutex::Autolock lock(mQueueItemLock);
1253 if (mQueueItems.empty()) {
1254 return true;
1255 }
1256 if (mQueueItems[0].mIsDroppable) {
1257 // Even though this buffer's fence may not have signaled yet, it could
1258 // be replaced by another buffer before it has a chance to, which means
1259 // that it's possible to get into a situation where a buffer is never
1260 // able to be latched. To avoid this, grab this buffer anyway.
1261 return true;
1262 }
1263 return mQueueItems[0].mFence->getSignalTime() != INT64_MAX;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001264#else
1265 return true;
1266#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001267}
1268
Dan Stozacac35382016-01-27 12:21:06 -08001269bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1270 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1271 // Don't bother with a SyncPoint, since we've already latched the
1272 // relevant frame
1273 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001274 }
1275
Dan Stozacac35382016-01-27 12:21:06 -08001276 Mutex::Autolock lock(mLocalSyncPointMutex);
1277 mLocalSyncPoints.push_back(point);
1278 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001279}
1280
Mathias Agopian13127d82013-03-05 17:47:11 -08001281void Layer::setFiltering(bool filtering) {
1282 mFiltering = filtering;
1283}
1284
1285bool Layer::getFiltering() const {
1286 return mFiltering;
1287}
1288
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001289// As documented in libhardware header, formats in the range
1290// 0x100 - 0x1FF are specific to the HAL implementation, and
1291// are known to have no alpha channel
1292// TODO: move definition for device-specific range into
1293// hardware.h, instead of using hard-coded values here.
1294#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1295
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001296bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001297 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1298 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001299 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001300 switch (format) {
1301 case HAL_PIXEL_FORMAT_RGBA_8888:
1302 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001303 case HAL_PIXEL_FORMAT_RGBA_FP16:
Mathias Agopiandd533712013-07-26 15:31:39 -07001304 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001305 }
1306 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001307 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001308}
1309
Mathias Agopian13127d82013-03-05 17:47:11 -08001310// ----------------------------------------------------------------------------
1311// local state
1312// ----------------------------------------------------------------------------
1313
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001314static void boundPoint(vec2* point, const Rect& crop) {
1315 if (point->x < crop.left) {
1316 point->x = crop.left;
1317 }
1318 if (point->x > crop.right) {
1319 point->x = crop.right;
1320 }
1321 if (point->y < crop.top) {
1322 point->y = crop.top;
1323 }
1324 if (point->y > crop.bottom) {
1325 point->y = crop.bottom;
1326 }
1327}
1328
Dan Stozac7014012014-02-14 15:03:43 -08001329void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1330 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001331{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001332 const Layer::State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001333 const Transform hwTransform(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001334 const uint32_t hw_h = hw->getHeight();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001335 Rect win = computeBounds();
Mathias Agopian3f844832013-08-07 21:24:32 -07001336
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001337 vec2 lt = vec2(win.left, win.top);
1338 vec2 lb = vec2(win.left, win.bottom);
1339 vec2 rb = vec2(win.right, win.bottom);
1340 vec2 rt = vec2(win.right, win.top);
1341
Robert Carr1f0a16a2016-10-24 16:27:39 -07001342 Transform layerTransform = getTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001343 if (!useIdentityTransform) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001344 lt = layerTransform.transform(lt);
1345 lb = layerTransform.transform(lb);
1346 rb = layerTransform.transform(rb);
1347 rt = layerTransform.transform(rt);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001348 }
1349
Robert Carrb5d3d262016-03-25 15:08:13 -07001350 if (!s.finalCrop.isEmpty()) {
1351 boundPoint(&lt, s.finalCrop);
1352 boundPoint(&lb, s.finalCrop);
1353 boundPoint(&rb, s.finalCrop);
1354 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001355 }
1356
Mathias Agopianff2ed702013-09-01 21:36:12 -07001357 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001358 position[0] = hwTransform.transform(lt);
1359 position[1] = hwTransform.transform(lb);
1360 position[2] = hwTransform.transform(rb);
1361 position[3] = hwTransform.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001362 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001363 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001364 }
1365}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001366
Andy McFadden4125a4f2014-01-29 17:17:11 -08001367bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001368{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001369 // if we don't have a buffer yet, we're translucent regardless of the
1370 // layer's opaque flag.
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001371 if (mActiveBuffer == 0) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001372 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001373 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001374
1375 // if the layer has the opaque flag, then we're always opaque,
1376 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001377 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001378}
1379
Dan Stoza23116082015-06-18 14:58:39 -07001380bool Layer::isSecure() const
1381{
1382 const Layer::State& s(mDrawingState);
1383 return (s.flags & layer_state_t::eLayerSecure);
1384}
1385
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001386bool Layer::isProtected() const
1387{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001388 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001389 return (activeBuffer != 0) &&
1390 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1391}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001392
Mathias Agopian13127d82013-03-05 17:47:11 -08001393bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001394 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001395}
1396
1397bool Layer::isCropped() const {
1398 return !mCurrentCrop.isEmpty();
1399}
1400
1401bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1402 return mNeedsFiltering || hw->needsFiltering();
1403}
1404
1405void Layer::setVisibleRegion(const Region& visibleRegion) {
1406 // always called from main thread
1407 this->visibleRegion = visibleRegion;
1408}
1409
1410void Layer::setCoveredRegion(const Region& coveredRegion) {
1411 // always called from main thread
1412 this->coveredRegion = coveredRegion;
1413}
1414
1415void Layer::setVisibleNonTransparentRegion(const Region&
1416 setVisibleNonTransparentRegion) {
1417 // always called from main thread
1418 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1419}
1420
1421// ----------------------------------------------------------------------------
1422// transaction
1423// ----------------------------------------------------------------------------
1424
Dan Stoza7dde5992015-05-22 09:51:44 -07001425void Layer::pushPendingState() {
1426 if (!mCurrentState.modified) {
1427 return;
1428 }
1429
Dan Stoza7dde5992015-05-22 09:51:44 -07001430 // If this transaction is waiting on the receipt of a frame, generate a sync
1431 // point and send it to the remote layer.
1432 if (mCurrentState.handle != nullptr) {
Dan Stoza22851c32016-08-09 13:21:03 -07001433 sp<IBinder> strongBinder = mCurrentState.handle.promote();
1434 sp<Handle> handle = nullptr;
1435 sp<Layer> handleLayer = nullptr;
1436 if (strongBinder != nullptr) {
1437 handle = static_cast<Handle*>(strongBinder.get());
1438 handleLayer = handle->owner.promote();
1439 }
1440 if (strongBinder == nullptr || handleLayer == nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001441 ALOGE("[%s] Unable to promote Layer handle", mName.string());
1442 // If we can't promote the layer we are intended to wait on,
1443 // then it is expired or otherwise invalid. Allow this transaction
1444 // to be applied as per normal (no synchronization).
1445 mCurrentState.handle = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001446 } else {
1447 auto syncPoint = std::make_shared<SyncPoint>(
1448 mCurrentState.frameNumber);
Dan Stozacac35382016-01-27 12:21:06 -08001449 if (handleLayer->addSyncPoint(syncPoint)) {
1450 mRemoteSyncPoints.push_back(std::move(syncPoint));
1451 } else {
1452 // We already missed the frame we're supposed to synchronize
1453 // on, so go ahead and apply the state update
1454 mCurrentState.handle = nullptr;
1455 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001456 }
1457
Dan Stoza7dde5992015-05-22 09:51:44 -07001458 // Wake us up to check if the frame has been received
1459 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001460 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001461 }
1462 mPendingStates.push_back(mCurrentState);
1463}
1464
Pablo Ceballos05289c22016-04-14 15:49:55 -07001465void Layer::popPendingState(State* stateToCommit) {
1466 auto oldFlags = stateToCommit->flags;
1467 *stateToCommit = mPendingStates[0];
1468 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1469 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001470
1471 mPendingStates.removeAt(0);
1472}
1473
Pablo Ceballos05289c22016-04-14 15:49:55 -07001474bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001475 bool stateUpdateAvailable = false;
1476 while (!mPendingStates.empty()) {
1477 if (mPendingStates[0].handle != nullptr) {
1478 if (mRemoteSyncPoints.empty()) {
1479 // If we don't have a sync point for this, apply it anyway. It
1480 // will be visually wrong, but it should keep us from getting
1481 // into too much trouble.
1482 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001483 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001484 stateUpdateAvailable = true;
1485 continue;
1486 }
1487
Dan Stozacac35382016-01-27 12:21:06 -08001488 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1489 mPendingStates[0].frameNumber) {
1490 ALOGE("[%s] Unexpected sync point frame number found",
1491 mName.string());
1492
1493 // Signal our end of the sync point and then dispose of it
1494 mRemoteSyncPoints.front()->setTransactionApplied();
1495 mRemoteSyncPoints.pop_front();
1496 continue;
1497 }
1498
Dan Stoza7dde5992015-05-22 09:51:44 -07001499 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1500 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001501 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001502 stateUpdateAvailable = true;
1503
1504 // Signal our end of the sync point and then dispose of it
1505 mRemoteSyncPoints.front()->setTransactionApplied();
1506 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001507 } else {
1508 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001509 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001510 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001511 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001512 stateUpdateAvailable = true;
1513 }
1514 }
1515
1516 // If we still have pending updates, wake SurfaceFlinger back up and point
1517 // it at this layer so we can process them
1518 if (!mPendingStates.empty()) {
1519 setTransactionFlags(eTransactionNeeded);
1520 mFlinger->setTransactionFlags(eTraversalNeeded);
1521 }
1522
1523 mCurrentState.modified = false;
1524 return stateUpdateAvailable;
1525}
1526
1527void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001528 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001529 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001530 Mutex::Autolock lock(mLocalSyncPointMutex);
1531 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001532 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001533 point->setFrameAvailable();
1534 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001535 }
1536}
1537
Mathias Agopian13127d82013-03-05 17:47:11 -08001538uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001539 ATRACE_CALL();
1540
Dan Stoza7dde5992015-05-22 09:51:44 -07001541 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001542 Layer::State c = getCurrentState();
1543 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001544 return 0;
1545 }
1546
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001547 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001548
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001549 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1550 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001551
1552 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001553 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001554 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001555 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001556 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001557 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001558 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001559 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001560 this, getName().string(), mCurrentTransform,
1561 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001562 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001563 c.crop.left,
1564 c.crop.top,
1565 c.crop.right,
1566 c.crop.bottom,
1567 c.crop.getWidth(),
1568 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001569 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001570 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001571 s.crop.left,
1572 s.crop.top,
1573 s.crop.right,
1574 s.crop.bottom,
1575 s.crop.getWidth(),
1576 s.crop.getHeight(),
1577 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001578
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001579 // record the new size, form this point on, when the client request
1580 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001581 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001582 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001583 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001584
Robert Carr82364e32016-05-15 11:27:47 -07001585 const bool resizePending = (c.requested.w != c.active.w) ||
1586 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001587 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001588 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001589 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001590 // if we have a pending resize, unless we are in fixed-size mode.
1591 // the drawing state will be updated only once we receive a buffer
1592 // with the correct size.
1593 //
1594 // in particular, we want to make sure the clip (which is part
1595 // of the geometry state) is latched together with the size but is
1596 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001597 //
1598 // If a sideband stream is attached, however, we want to skip this
1599 // optimization so that transactions aren't missed when a buffer
1600 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001601
1602 flags |= eDontUpdateGeometryState;
1603 }
1604 }
1605
Mathias Agopian13127d82013-03-05 17:47:11 -08001606 // always set active to requested, unless we're asked not to
1607 // this is used by Layer, which special cases resizes.
1608 if (flags & eDontUpdateGeometryState) {
1609 } else {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001610 Layer::State& editCurrentState(getCurrentState());
Robert Carr82364e32016-05-15 11:27:47 -07001611 if (mFreezePositionUpdates) {
1612 float tx = c.active.transform.tx();
1613 float ty = c.active.transform.ty();
1614 c.active = c.requested;
1615 c.active.transform.set(tx, ty);
1616 editCurrentState.active = c.active;
1617 } else {
1618 editCurrentState.active = editCurrentState.requested;
1619 c.active = c.requested;
1620 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001621 }
1622
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001623 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001624 // invalidate and recompute the visible regions if needed
1625 flags |= Layer::eVisibleRegion;
1626 }
1627
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001628 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001629 // invalidate and recompute the visible regions if needed
1630 flags |= eVisibleRegion;
1631 this->contentDirty = true;
1632
1633 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001634 const uint8_t type = c.active.transform.getType();
1635 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001636 (type >= Transform::SCALE));
1637 }
1638
Dan Stozac8145172016-04-28 16:29:06 -07001639 // If the layer is hidden, signal and clear out all local sync points so
1640 // that transactions for layers depending on this layer's frames becoming
1641 // visible are not blocked
1642 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001643 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001644 }
1645
Mathias Agopian13127d82013-03-05 17:47:11 -08001646 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001647 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001648 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001649}
1650
Pablo Ceballos05289c22016-04-14 15:49:55 -07001651void Layer::commitTransaction(const State& stateToCommit) {
1652 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001653}
1654
Mathias Agopian13127d82013-03-05 17:47:11 -08001655uint32_t Layer::getTransactionFlags(uint32_t flags) {
1656 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1657}
1658
1659uint32_t Layer::setTransactionFlags(uint32_t flags) {
1660 return android_atomic_or(flags, &mTransactionFlags);
1661}
1662
Robert Carr82364e32016-05-15 11:27:47 -07001663bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001664 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001665 return false;
1666 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001667
1668 // We update the requested and active position simultaneously because
1669 // we want to apply the position portion of the transform matrix immediately,
1670 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001671 mCurrentState.requested.transform.set(x, y);
Robert Carr82364e32016-05-15 11:27:47 -07001672 if (immediate && !mFreezePositionUpdates) {
1673 mCurrentState.active.transform.set(x, y);
1674 }
1675 mFreezePositionUpdates = mFreezePositionUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001676
Dan Stoza7dde5992015-05-22 09:51:44 -07001677 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001678 setTransactionFlags(eTransactionNeeded);
1679 return true;
1680}
Robert Carr82364e32016-05-15 11:27:47 -07001681
Robert Carr1f0a16a2016-10-24 16:27:39 -07001682bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1683 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1684 if (idx < 0) {
1685 return false;
1686 }
1687 if (childLayer->setLayer(z)) {
1688 mCurrentChildren.removeAt(idx);
1689 mCurrentChildren.add(childLayer);
1690 }
1691 return true;
1692}
1693
Robert Carrae060832016-11-28 10:51:00 -08001694bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001695 if (mCurrentState.z == z)
1696 return false;
1697 mCurrentState.sequence++;
1698 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001699 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001700 setTransactionFlags(eTransactionNeeded);
1701 return true;
1702}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001703
Mathias Agopian13127d82013-03-05 17:47:11 -08001704bool Layer::setSize(uint32_t w, uint32_t h) {
1705 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1706 return false;
1707 mCurrentState.requested.w = w;
1708 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001709 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001710 setTransactionFlags(eTransactionNeeded);
1711 return true;
1712}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001713#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001714bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001715#else
1716bool Layer::setAlpha(uint8_t alpha) {
1717#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001718 if (mCurrentState.alpha == alpha)
1719 return false;
1720 mCurrentState.sequence++;
1721 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001722 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001723 setTransactionFlags(eTransactionNeeded);
1724 return true;
1725}
1726bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1727 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001728 mCurrentState.requested.transform.set(
Mathias Agopian13127d82013-03-05 17:47:11 -08001729 matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001730 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001731 setTransactionFlags(eTransactionNeeded);
1732 return true;
1733}
1734bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001735 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001736 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001737 setTransactionFlags(eTransactionNeeded);
1738 return true;
1739}
1740bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1741 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1742 if (mCurrentState.flags == newFlags)
1743 return false;
1744 mCurrentState.sequence++;
1745 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001746 mCurrentState.mask = mask;
1747 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001748 setTransactionFlags(eTransactionNeeded);
1749 return true;
1750}
Robert Carr99e27f02016-06-16 15:18:02 -07001751
1752bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001753 if (mCurrentState.crop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001754 return false;
1755 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001756 mCurrentState.requestedCrop = crop;
1757 if (immediate) {
1758 mCurrentState.crop = crop;
1759 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001760 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001761 setTransactionFlags(eTransactionNeeded);
1762 return true;
1763}
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001764bool Layer::setFinalCrop(const Rect& crop) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001765 if (mCurrentState.finalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001766 return false;
1767 mCurrentState.sequence++;
Robert Carrb5d3d262016-03-25 15:08:13 -07001768 mCurrentState.finalCrop = crop;
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001769 mCurrentState.modified = true;
1770 setTransactionFlags(eTransactionNeeded);
1771 return true;
1772}
Mathias Agopian13127d82013-03-05 17:47:11 -08001773
Robert Carrc3574f72016-03-24 12:19:32 -07001774bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1775 if (scalingMode == mOverrideScalingMode)
1776 return false;
1777 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001778 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001779 return true;
1780}
1781
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001782void Layer::setInfo(uint32_t type, uint32_t appId) {
1783 mCurrentState.appId = appId;
1784 mCurrentState.type = type;
1785 mCurrentState.modified = true;
1786 setTransactionFlags(eTransactionNeeded);
1787}
1788
Robert Carrc3574f72016-03-24 12:19:32 -07001789uint32_t Layer::getEffectiveScalingMode() const {
1790 if (mOverrideScalingMode >= 0) {
1791 return mOverrideScalingMode;
1792 }
1793 return mCurrentScalingMode;
1794}
1795
Mathias Agopian13127d82013-03-05 17:47:11 -08001796bool Layer::setLayerStack(uint32_t layerStack) {
1797 if (mCurrentState.layerStack == layerStack)
1798 return false;
1799 mCurrentState.sequence++;
1800 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001801 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001802 setTransactionFlags(eTransactionNeeded);
1803 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001804}
1805
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07001806bool Layer::setDataSpace(android_dataspace dataSpace) {
1807 if (mCurrentState.dataSpace == dataSpace)
1808 return false;
1809 mCurrentState.sequence++;
1810 mCurrentState.dataSpace = dataSpace;
1811 mCurrentState.modified = true;
1812 setTransactionFlags(eTransactionNeeded);
1813 return true;
1814}
1815
Robert Carr1f0a16a2016-10-24 16:27:39 -07001816uint32_t Layer::getLayerStack() const {
1817 auto p = getParent();
1818 if (p == nullptr) {
1819 return getDrawingState().layerStack;
1820 }
1821 return p->getLayerStack();
1822}
1823
Dan Stoza7dde5992015-05-22 09:51:44 -07001824void Layer::deferTransactionUntil(const sp<IBinder>& handle,
1825 uint64_t frameNumber) {
1826 mCurrentState.handle = handle;
1827 mCurrentState.frameNumber = frameNumber;
1828 // We don't set eTransactionNeeded, because just receiving a deferral
1829 // request without any other state updates shouldn't actually induce a delay
1830 mCurrentState.modified = true;
1831 pushPendingState();
Dan Stoza792e5292016-02-11 11:43:58 -08001832 mCurrentState.handle = nullptr;
1833 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07001834 mCurrentState.modified = false;
1835}
1836
Dan Stozaee44edd2015-03-23 15:50:23 -07001837void Layer::useSurfaceDamage() {
1838 if (mFlinger->mForceFullDamage) {
1839 surfaceDamageRegion = Region::INVALID_REGION;
1840 } else {
1841 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1842 }
1843}
1844
1845void Layer::useEmptyDamage() {
1846 surfaceDamageRegion.clear();
1847}
1848
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001849// ----------------------------------------------------------------------------
1850// pageflip handling...
1851// ----------------------------------------------------------------------------
1852
Dan Stoza6b9454d2014-11-07 16:00:59 -08001853bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001854 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07001855 return true;
1856 }
1857
Dan Stoza6b9454d2014-11-07 16:00:59 -08001858 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001859 if (mQueueItems.empty()) {
1860 return false;
1861 }
1862 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001863 nsecs_t expectedPresent =
1864 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001865
1866 // Ignore timestamps more than a second in the future
1867 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1868 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1869 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1870 expectedPresent);
1871
1872 bool isDue = timestamp < expectedPresent;
1873 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001874}
1875
Brian Andersond6927fb2016-07-23 23:37:30 -07001876bool Layer::onPreComposition(nsecs_t refreshStartTime) {
1877 if (mBufferLatched) {
1878 Mutex::Autolock lock(mFrameEventHistoryMutex);
1879 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
1880 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08001881 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001882 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001883}
1884
Brian Anderson3d4039d2016-09-23 16:31:30 -07001885bool Layer::onPostComposition(
1886 const std::shared_ptr<FenceTime>& glDoneFence,
1887 const std::shared_ptr<FenceTime>& presentFence,
1888 const std::shared_ptr<FenceTime>& retireFence) {
1889 mAcquireTimeline.updateSignalTimes();
1890 mReleaseTimeline.updateSignalTimes();
1891
Brian Andersond6927fb2016-07-23 23:37:30 -07001892 // mFrameLatencyNeeded is true when a new frame was latched for the
1893 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08001894 if (!mFrameLatencyNeeded)
1895 return false;
1896
Fabien Sanglard28e98082016-12-05 10:19:46 -08001897 // Update mFrameEventHistory.
1898 {
1899 Mutex::Autolock lock(mFrameEventHistoryMutex);
1900 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson3d4039d2016-09-23 16:31:30 -07001901 glDoneFence, presentFence);
Fabien Sanglard28e98082016-12-05 10:19:46 -08001902 mFrameEventHistory.addRetire(mPreviousFrameNumber,
1903 retireFence);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001904 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08001905
1906 // Update mFrameTracker.
1907 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1908 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1909
Brian Anderson3d4039d2016-09-23 16:31:30 -07001910 std::shared_ptr<FenceTime> frameReadyFence =
1911 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08001912 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001913 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001914 } else {
1915 // There was no fence for this frame, so assume that it was ready
1916 // to be presented at the desired present time.
1917 mFrameTracker.setFrameReadyTime(desiredPresentTime);
1918 }
1919
Brian Anderson3d4039d2016-09-23 16:31:30 -07001920 if (presentFence->isValid()) {
1921 mFrameTracker.setActualPresentFence(
1922 std::shared_ptr<FenceTime>(presentFence));
1923 } else if (retireFence->isValid()) {
1924 mFrameTracker.setActualPresentFence(
1925 std::shared_ptr<FenceTime>(retireFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001926 } else {
1927 // The HWC doesn't support present fences, so use the refresh
1928 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07001929 mFrameTracker.setActualPresentTime(
1930 mFlinger->getHwComposer().getRefreshTimestamp(
1931 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001932 }
1933
1934 mFrameTracker.advanceFrame();
1935 mFrameLatencyNeeded = false;
1936 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001937}
1938
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001939#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07001940void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001941 mSurfaceFlingerConsumer->releasePendingBuffer();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001942 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07001943 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001944 mReleaseTimeline.push(releaseFenceTime);
1945
1946 Mutex::Autolock lock(mFrameEventHistoryMutex);
1947 mFrameEventHistory.addRelease(
Brian Andersonf6386862016-10-31 16:34:13 -07001948 mPreviousFrameNumber, dequeueReadyTime, std::move(releaseFenceTime));
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001950#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001951
Robert Carr1f0a16a2016-10-24 16:27:39 -07001952bool Layer::isHiddenByPolicy() const {
1953 const Layer::State& s(mDrawingState);
1954 const auto& parent = getParent();
1955 if (parent != nullptr && parent->isHiddenByPolicy()) {
1956 return true;
1957 }
1958 return s.flags & layer_state_t::eLayerHidden;
1959}
1960
Mathias Agopianda27af92012-09-13 18:17:13 -07001961bool Layer::isVisible() const {
Mathias Agopian13127d82013-03-05 17:47:11 -08001962 const Layer::State& s(mDrawingState);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001963#ifdef USE_HWC2
Robert Carr1f0a16a2016-10-24 16:27:39 -07001964 return !(isHiddenByPolicy()) && s.alpha > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08001965 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001966#else
Robert Carr1f0a16a2016-10-24 16:27:39 -07001967 return !(isHiddenByPolicy()) && s.alpha
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001968 && (mActiveBuffer != NULL || mSidebandStream != NULL);
1969#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07001970}
1971
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07001972bool Layer::allTransactionsSignaled() {
1973 auto headFrameNumber = getHeadFrameNumber();
1974 bool matchingFramesFound = false;
1975 bool allTransactionsApplied = true;
1976 Mutex::Autolock lock(mLocalSyncPointMutex);
1977
1978 for (auto& point : mLocalSyncPoints) {
1979 if (point->getFrameNumber() > headFrameNumber) {
1980 break;
1981 }
1982 matchingFramesFound = true;
1983
1984 if (!point->frameIsAvailable()) {
1985 // We haven't notified the remote layer that the frame for
1986 // this point is available yet. Notify it now, and then
1987 // abort this attempt to latch.
1988 point->setFrameAvailable();
1989 allTransactionsApplied = false;
1990 break;
1991 }
1992
1993 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
1994 }
1995 return !matchingFramesFound || allTransactionsApplied;
1996}
1997
Brian Andersond6927fb2016-07-23 23:37:30 -07001998Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001999{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08002000 ATRACE_CALL();
2001
Jesse Hall399184a2014-03-03 15:42:54 -08002002 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2003 // mSidebandStreamChanged was true
2004 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07002005 if (mSidebandStream != NULL) {
2006 setTransactionFlags(eTransactionNeeded);
2007 mFlinger->setTransactionFlags(eTraversalNeeded);
2008 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07002009 recomputeVisibleRegions = true;
2010
2011 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07002012 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08002013 }
2014
Mathias Agopian4fec8732012-06-29 14:12:52 -07002015 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07002016 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2017 return outDirtyRegion;
2018 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002019
Fabien Sanglard223eb912016-10-13 10:15:06 -07002020 // if we've already called updateTexImage() without going through
2021 // a composition step, we have to skip this layer at this point
2022 // because we cannot call updateTeximage() without a corresponding
2023 // compositionComplete() call.
2024 // we'll trigger an update in onPreComposition().
2025 if (mRefreshPending) {
2026 return outDirtyRegion;
2027 }
2028
2029 // If the head buffer's acquire fence hasn't signaled yet, return and
2030 // try again later
2031 if (!headFenceHasSignaled()) {
2032 mFlinger->signalLayerUpdate();
2033 return outDirtyRegion;
2034 }
2035
2036 // Capture the old state of the layer for comparisons later
2037 const State& s(getDrawingState());
2038 const bool oldOpacity = isOpaque(s);
2039 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2040
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002041 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002042 mFlinger->signalLayerUpdate();
2043 return outDirtyRegion;
2044 }
2045
2046 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2047 // of the buffer queue isn't modified when the buffer queue is returning
2048 // BufferItem's that weren't actually queued. This can happen in shared
2049 // buffer mode.
2050 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002051 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2052 getProducerStickyTransform() != 0, mName.string(),
2053 mOverrideScalingMode, mFreezePositionUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002054 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2055 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2056 mLastFrameNumberReceived);
2057 if (updateResult == BufferQueue::PRESENT_LATER) {
2058 // Producer doesn't want buffer to be displayed yet. Signal a
2059 // layer update so we check again at the next opportunity.
2060 mFlinger->signalLayerUpdate();
2061 return outDirtyRegion;
2062 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2063 // If the buffer has been rejected, remove it from the shadow queue
2064 // and return early
2065 if (queuedBuffer) {
2066 Mutex::Autolock lock(mQueueItemLock);
2067 mQueueItems.removeAt(0);
2068 android_atomic_dec(&mQueuedFrames);
2069 }
2070 return outDirtyRegion;
2071 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2072 // This can occur if something goes wrong when trying to create the
2073 // EGLImage for this buffer. If this happens, the buffer has already
2074 // been released, so we need to clean up the queue and bug out
2075 // early.
2076 if (queuedBuffer) {
2077 Mutex::Autolock lock(mQueueItemLock);
2078 mQueueItems.clear();
2079 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002080 }
2081
Fabien Sanglard223eb912016-10-13 10:15:06 -07002082 // Once we have hit this state, the shadow queue may no longer
2083 // correctly reflect the incoming BufferQueue's contents, so even if
2084 // updateTexImage starts working, the only safe course of action is
2085 // to continue to ignore updates.
2086 mUpdateTexImageFailed = true;
2087
2088 return outDirtyRegion;
2089 }
2090
2091 if (queuedBuffer) {
2092 // Autolock scope
2093 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2094
2095 Mutex::Autolock lock(mQueueItemLock);
2096
2097 // Remove any stale buffers that have been dropped during
2098 // updateTexImage
2099 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2100 mQueueItems.removeAt(0);
2101 android_atomic_dec(&mQueuedFrames);
2102 }
2103
2104 mQueueItems.removeAt(0);
2105 }
2106
2107
2108 // Decrement the queued-frames count. Signal another event if we
2109 // have more frames pending.
2110 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2111 || mAutoRefresh) {
2112 mFlinger->signalLayerUpdate();
2113 }
2114
Fabien Sanglard223eb912016-10-13 10:15:06 -07002115 // update the active buffer
Chia-I Wu06d63de2017-01-04 14:58:51 +08002116 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2117 &mActiveBufferSlot);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002118 if (mActiveBuffer == NULL) {
2119 // this can only happen if the very first buffer was rejected.
2120 return outDirtyRegion;
2121 }
2122
Brian Andersond6927fb2016-07-23 23:37:30 -07002123 mBufferLatched = true;
2124 mPreviousFrameNumber = mCurrentFrameNumber;
2125 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2126
2127 {
2128 Mutex::Autolock lock(mFrameEventHistoryMutex);
2129 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2130#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002131 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002132 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002133 mReleaseTimeline.push(releaseFenceTime);
2134 mFrameEventHistory.addRelease(
Brian Andersonf6386862016-10-31 16:34:13 -07002135 mPreviousFrameNumber, latchTime, std::move(releaseFenceTime));
Brian Andersond6927fb2016-07-23 23:37:30 -07002136#endif
2137 }
2138
Fabien Sanglard223eb912016-10-13 10:15:06 -07002139 mRefreshPending = true;
2140 mFrameLatencyNeeded = true;
2141 if (oldActiveBuffer == NULL) {
2142 // the first time we receive a buffer, we need to trigger a
2143 // geometry invalidation.
2144 recomputeVisibleRegions = true;
2145 }
2146
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002147 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2148
Fabien Sanglard223eb912016-10-13 10:15:06 -07002149 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2150 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2151 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2152 if ((crop != mCurrentCrop) ||
2153 (transform != mCurrentTransform) ||
2154 (scalingMode != mCurrentScalingMode))
2155 {
2156 mCurrentCrop = crop;
2157 mCurrentTransform = transform;
2158 mCurrentScalingMode = scalingMode;
2159 recomputeVisibleRegions = true;
2160 }
2161
2162 if (oldActiveBuffer != NULL) {
2163 uint32_t bufWidth = mActiveBuffer->getWidth();
2164 uint32_t bufHeight = mActiveBuffer->getHeight();
2165 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2166 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002167 recomputeVisibleRegions = true;
2168 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002169 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002170
Fabien Sanglard223eb912016-10-13 10:15:06 -07002171 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2172 if (oldOpacity != isOpaque(s)) {
2173 recomputeVisibleRegions = true;
2174 }
Dan Stozacac35382016-01-27 12:21:06 -08002175
Fabien Sanglard223eb912016-10-13 10:15:06 -07002176 // Remove any sync points corresponding to the buffer which was just
2177 // latched
2178 {
2179 Mutex::Autolock lock(mLocalSyncPointMutex);
2180 auto point = mLocalSyncPoints.begin();
2181 while (point != mLocalSyncPoints.end()) {
2182 if (!(*point)->frameIsAvailable() ||
2183 !(*point)->transactionIsApplied()) {
2184 // This sync point must have been added since we started
2185 // latching. Don't drop it yet.
2186 ++point;
2187 continue;
2188 }
2189
2190 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2191 point = mLocalSyncPoints.erase(point);
2192 } else {
2193 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002194 }
2195 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002196 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002197
2198 // FIXME: postedRegion should be dirty & bounds
2199 Region dirtyRegion(Rect(s.active.w, s.active.h));
2200
2201 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002202 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002203
Mathias Agopian4fec8732012-06-29 14:12:52 -07002204 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002205}
2206
Mathias Agopiana67932f2011-04-20 14:20:59 -07002207uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002208{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002209 // TODO: should we do something special if mSecure is set?
2210 if (mProtectedByApp) {
2211 // need a hardware-protected path to external video sink
2212 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002213 }
Riley Andrews03414a12014-07-01 14:22:59 -07002214 if (mPotentialCursor) {
2215 usage |= GraphicBuffer::USAGE_CURSOR;
2216 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002217 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002218 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002219}
2220
Mathias Agopian84300952012-11-21 16:02:13 -08002221void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002222 uint32_t orientation = 0;
2223 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002224 // The transform hint is used to improve performance, but we can
2225 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002226 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002227 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002228 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002229 if (orientation & Transform::ROT_INVALID) {
2230 orientation = 0;
2231 }
2232 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002233 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002234}
2235
Mathias Agopian13127d82013-03-05 17:47:11 -08002236// ----------------------------------------------------------------------------
2237// debugging
2238// ----------------------------------------------------------------------------
2239
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002240void Layer::dump(String8& result, Colorizer& colorizer) const
Mathias Agopian13127d82013-03-05 17:47:11 -08002241{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002242 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08002243
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002244 colorizer.colorize(result, Colorizer::GREEN);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002245 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002246 "+ %s %p (%s)\n",
2247 getTypeId(), this, getName().string());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002248 colorizer.reset(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002249
Mathias Agopian2ca79392013-04-02 18:30:32 -07002250 s.activeTransparentRegion.dump(result, "transparentRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002251 visibleRegion.dump(result, "visibleRegion");
Dan Stozaee44edd2015-03-23 15:50:23 -07002252 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002253 sp<Client> client(mClientRef.promote());
2254
Mathias Agopian74d211a2013-04-22 16:55:35 +02002255 result.appendFormat( " "
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002256 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2257 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
Mathias Agopian13127d82013-03-05 17:47:11 -08002258 "isOpaque=%1d, invalidate=%1d, "
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002259#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08002260 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002261#else
2262 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2263#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08002264 " client=%p\n",
Robert Carr1f0a16a2016-10-24 16:27:39 -07002265 getLayerStack(), s.z,
2266 s.active.transform.tx(), s.active.transform.ty(),
2267 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07002268 s.crop.left, s.crop.top,
2269 s.crop.right, s.crop.bottom,
2270 s.finalCrop.left, s.finalCrop.top,
2271 s.finalCrop.right, s.finalCrop.bottom,
Andy McFadden4125a4f2014-01-29 17:17:11 -08002272 isOpaque(s), contentDirty,
Mathias Agopian13127d82013-03-05 17:47:11 -08002273 s.alpha, s.flags,
Robert Carr3dcabfa2016-03-01 18:36:58 -08002274 s.active.transform[0][0], s.active.transform[0][1],
2275 s.active.transform[1][0], s.active.transform[1][1],
Mathias Agopian13127d82013-03-05 17:47:11 -08002276 client.get());
Mathias Agopian13127d82013-03-05 17:47:11 -08002277
2278 sp<const GraphicBuffer> buf0(mActiveBuffer);
2279 uint32_t w0=0, h0=0, s0=0, f0=0;
2280 if (buf0 != 0) {
2281 w0 = buf0->getWidth();
2282 h0 = buf0->getHeight();
2283 s0 = buf0->getStride();
2284 f0 = buf0->format;
2285 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02002286 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002287 " "
2288 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2289 " queued-frames=%d, mRefreshPending=%d\n",
2290 mFormat, w0, h0, s0,f0,
2291 mQueuedFrames, mRefreshPending);
2292
Mathias Agopian13127d82013-03-05 17:47:11 -08002293 if (mSurfaceFlingerConsumer != 0) {
Colin Cross3d1d2802016-09-26 18:10:16 -07002294 mSurfaceFlingerConsumer->dumpState(result, " ");
Mathias Agopian13127d82013-03-05 17:47:11 -08002295 }
2296}
2297
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002298#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002299void Layer::miniDumpHeader(String8& result) {
2300 result.append("----------------------------------------");
2301 result.append("---------------------------------------\n");
2302 result.append(" Layer name\n");
2303 result.append(" Z | ");
2304 result.append(" Comp Type | ");
2305 result.append(" Disp Frame (LTRB) | ");
2306 result.append(" Source Crop (LTRB)\n");
2307 result.append("----------------------------------------");
2308 result.append("---------------------------------------\n");
2309}
2310
2311void Layer::miniDump(String8& result, int32_t hwcId) const {
2312 if (mHwcLayers.count(hwcId) == 0) {
2313 return;
2314 }
2315
2316 String8 name;
2317 if (mName.length() > 77) {
2318 std::string shortened;
2319 shortened.append(mName.string(), 36);
2320 shortened.append("[...]");
2321 shortened.append(mName.string() + (mName.length() - 36), 36);
2322 name = shortened.c_str();
2323 } else {
2324 name = mName;
2325 }
2326
2327 result.appendFormat(" %s\n", name.string());
2328
2329 const Layer::State& layerState(getDrawingState());
2330 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2331 result.appendFormat(" %10u | ", layerState.z);
2332 result.appendFormat("%10s | ",
2333 to_string(getCompositionType(hwcId)).c_str());
2334 const Rect& frame = hwcInfo.displayFrame;
2335 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2336 frame.right, frame.bottom);
Dan Stoza71bded52016-10-19 11:10:33 -07002337 const gfx::FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002338 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2339 crop.right, crop.bottom);
2340
2341 result.append("- - - - - - - - - - - - - - - - - - - - ");
2342 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2343}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002344#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002345
Svetoslavd85084b2014-03-20 10:28:31 -07002346void Layer::dumpFrameStats(String8& result) const {
2347 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002348}
2349
Svetoslavd85084b2014-03-20 10:28:31 -07002350void Layer::clearFrameStats() {
2351 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002352}
2353
Jamie Gennis6547ff42013-07-16 20:12:42 -07002354void Layer::logFrameStats() {
2355 mFrameTracker.logAndResetStats(mName);
2356}
2357
Svetoslavd85084b2014-03-20 10:28:31 -07002358void Layer::getFrameStats(FrameStats* outStats) const {
2359 mFrameTracker.getStats(outStats);
2360}
2361
Brian Andersond6927fb2016-07-23 23:37:30 -07002362void Layer::dumpFrameEvents(String8& result) {
2363 result.appendFormat("- Layer %s (%s, %p)\n",
2364 getName().string(), getTypeId(), this);
2365 Mutex::Autolock lock(mFrameEventHistoryMutex);
2366 mFrameEventHistory.checkFencesForCompletion();
2367 mFrameEventHistory.dump(result);
2368}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002369
Brian Anderson3890c392016-07-25 12:48:08 -07002370void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2371 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002372 Mutex::Autolock lock(mFrameEventHistoryMutex);
2373 if (newTimestamps) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002374 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002375 mFrameEventHistory.addQueue(*newTimestamps);
2376 }
2377
Brian Anderson3890c392016-07-25 12:48:08 -07002378 if (outDelta) {
2379 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002380 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002381}
Dan Stozae77c7662016-05-13 11:37:28 -07002382
2383std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2384 bool forceFlush) {
2385 std::vector<OccupancyTracker::Segment> history;
2386 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2387 &history);
2388 if (result != NO_ERROR) {
2389 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2390 result);
2391 return {};
2392 }
2393 return history;
2394}
2395
Robert Carr367c5682016-06-20 11:55:28 -07002396bool Layer::getTransformToDisplayInverse() const {
2397 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2398}
2399
Robert Carr1f0a16a2016-10-24 16:27:39 -07002400void Layer::addChild(const sp<Layer>& layer) {
2401 mCurrentChildren.add(layer);
2402 layer->setParent(this);
2403}
2404
2405ssize_t Layer::removeChild(const sp<Layer>& layer) {
2406 layer->setParent(nullptr);
2407 return mCurrentChildren.remove(layer);
2408}
2409
Robert Carr1db73f62016-12-21 12:58:51 -08002410bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2411 sp<Handle> handle = nullptr;
2412 sp<Layer> newParent = nullptr;
2413 if (newParentHandle == nullptr) {
2414 return false;
2415 }
2416 handle = static_cast<Handle*>(newParentHandle.get());
2417 newParent = handle->owner.promote();
2418 if (newParent == nullptr) {
2419 ALOGE("Unable to promote Layer handle");
2420 return false;
2421 }
2422
2423 for (const sp<Layer>& child : mCurrentChildren) {
2424 newParent->addChild(child);
2425
2426 sp<Client> client(child->mClientRef.promote());
2427 if (client != nullptr) {
2428 client->setParentLayer(newParent);
2429 }
2430 }
2431 mCurrentChildren.clear();
2432
2433 return true;
2434}
2435
Robert Carr1f0a16a2016-10-24 16:27:39 -07002436void Layer::setParent(const sp<Layer>& layer) {
2437 mParent = layer;
2438}
2439
2440void Layer::clearSyncPoints() {
2441 for (const auto& child : mCurrentChildren) {
2442 child->clearSyncPoints();
2443 }
2444
2445 Mutex::Autolock lock(mLocalSyncPointMutex);
2446 for (auto& point : mLocalSyncPoints) {
2447 point->setFrameAvailable();
2448 }
2449 mLocalSyncPoints.clear();
2450}
2451
2452int32_t Layer::getZ() const {
2453 return mDrawingState.z;
2454}
2455
2456/**
2457 * Negatively signed children are before 'this' in Z-order.
2458 */
2459void Layer::traverseInZOrder(const std::function<void(Layer*)>& exec) {
2460 size_t i = 0;
2461 for (; i < mDrawingChildren.size(); i++) {
2462 const auto& child = mDrawingChildren[i];
2463 if (child->getZ() >= 0)
2464 break;
2465 child->traverseInZOrder(exec);
2466 }
2467 exec(this);
2468 for (; i < mDrawingChildren.size(); i++) {
2469 const auto& child = mDrawingChildren[i];
2470 child->traverseInZOrder(exec);
2471 }
2472}
2473
2474/**
2475 * Positively signed children are before 'this' in reverse Z-order.
2476 */
2477void Layer::traverseInReverseZOrder(const std::function<void(Layer*)>& exec) {
2478 int32_t i = 0;
2479 for (i = mDrawingChildren.size()-1; i>=0; i--) {
2480 const auto& child = mDrawingChildren[i];
2481 if (child->getZ() < 0) {
2482 break;
2483 }
2484 child->traverseInReverseZOrder(exec);
2485 }
2486 exec(this);
2487 for (; i>=0; i--) {
2488 const auto& child = mDrawingChildren[i];
2489 child->traverseInReverseZOrder(exec);
2490 }
2491}
2492
2493Transform Layer::getTransform() const {
2494 Transform t;
2495 const auto& p = getParent();
2496 if (p != nullptr) {
2497 t = p->getTransform();
2498 }
2499 return t * getDrawingState().active.transform;
2500}
2501
2502void Layer::commitChildList() {
2503 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2504 const auto& child = mCurrentChildren[i];
2505 child->commitChildList();
2506 }
2507 mDrawingChildren = mCurrentChildren;
2508}
2509
Mathias Agopian13127d82013-03-05 17:47:11 -08002510// ---------------------------------------------------------------------------
2511
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002513
2514#if defined(__gl_h_)
2515#error "don't include gl/gl.h in this file"
2516#endif
2517
2518#if defined(__gl2_h_)
2519#error "don't include gl2/gl2.h in this file"
2520#endif